Home loan affordability Calculator

Question: I am asked to create a function: maximum_home_loan(PMT, i, n) that calculates the maximum home loan that my customer can afford, if they:

Can afford to pay an amount, PMT at the end of every YEAR (with the 1st payment made at exactly one year from now)
at an interest of i% per year compounded annually, and
pay off the home over a term of n year.

This is how I did it but I think the amount don't add up.
def maximum_home_loan(PMT, i, n):
       For i in range(n):
           PMT = PMT*(1 + i)**n
           PV = PMT + i
           PV = PV + PMT
           PV = round(PV, 2)
           return float(PV)
print(maximum_home_loan(15000*12, 0.1045/100, 25))

Output: 369523.89
And the output should actually be: 1578934.73
What is it that am doing wrong?
Comment: Where do you want to put the return statement? Inside or outside the loop?
Comment: Can you please check the statement "PV=PMT+i". It is not right to add interest rate to an amount.
Comment: @RegiMathew, it's even more "not right", because here `i` is not the interest rate, but the `i` from `for i in range(n)`, an integer.
Comment: Somehow your course doesn't seem to prepare you guys very well to solve this problem, you're [the second one with this question](https://stackoverflow.com/q/52576448/476) today… [:watching_you_emoji:](https://media.giphy.com/media/Ef0TRTKRVGGQw/giphy.gif)
Comment: Inside the loop
Comment: Then you have an algorithm design problem and not a typo. Why do you want it to be inside the loop, provided that a return statement terminates the execution of a function?
Comment: Well am still new to Python. And I thought maybe if I put it inside the loop then it would return as it should. What would you suggest I change
Comment: What would you suggest I do to get an output of 1578934.73?
Comment: I agree with you deceze
Comment: ForceBru if I was to change the i in range to j in range, would that be ok
Comment: @Creeto is the interest rate `.1045` _percent_?
Comment: Yes the interest rate is 0.1045
Comment: @Creeto, if that value is in _percents_, the answer'll be around 4.4 million. Clearly, it's meant to be 10.45%, so you shouldn't divide the value by 100 in your code.
Answer: I'm not really sure what you're trying to do in your code, so here's another solution.
Let's say at the end of the first year your debt is the following:
Debt1 = Loan * (1 + i) - PMT
At the end of the second year it'll be:
D2 = D1 * (1 + i) - PMT = Loan * (1 + i)2 - PMT * (1 + (1 + i))
For the Nth year, we get:
Dn = Loan * (1 + i)n - PMT * sumj=0n-1 (1+i)j
Because Dn must be zero, you have a formula for Loan (I'm pretty sure you can simplify the sum dramatically, but I can't remember how see below):
def calculate(PMT, i, n):
    return PMT * sum((1+i)**j for j in range(n)) / (1+i)**n

You don't really need to calculate the sum with sum(...) as there's a formula for this kind of sums:
sumj=0n-1 rj = (rn - 1) / (r - 1)
So, here's this formula in action:
def calculate(PMT, i, n: int) -> float:
    return PMT * ((1+i)**n - 1) / i / (1+i)**n

calculate(15_000 * 12, .1045, 25)  # 1578934.728701355

Comment: Thank you so much @ForceBru it works fine. Thank you.  So at point on the code would I input. If I'd like to round it off to two decimal places?
Comment: @Creeto, what would you like to round?
Comment: The output #157893.728701355.
Comment: Just like you do in your code: `round(whatever_you_want_to_round, 2)`.
Comment: OK cool and I would have to add it on the code before I return it l? Am I right.
Comment: Thanks a lot ForceBru. You the best :)

Home loan affordability Calculator


Kuratowski's theorem on Planar graphs

Question: I've got an exercise that I've been battling for 5 hours to solve. There is a picture of the graph below. I am sure that I can't find a K5 as a minor since every vertex has 3 edges leaving. I tried so long to find a K3,3 minor and failed. What is the correct approach? I also strongly believe that it is not planar graph.
Comment: Duplicate of https://math.stackexchange.com/q/2625442/120540 (but no upvoted/accepted answers)
Comment: It's a duplicate. You can close/delete the question
Answer: Delete the edges $\{EG\}$ and $\{FH\}$. Then you can do the following:
Comment: I forgot to add lettering to my original graph. Could you please edit your answer so I can understand where is the K3,3 minor that I still don't see?
Comment: I edited the graph in the question, now it is appropriate.

Kuratowski's theorem on Planar graphs


Prove that g=e for a finite group G

Question: Suppose G is a finite group of order n and m is relatively prime to n. If $g \in G$ and $g^{m}=e$, prove that $g=e$.
Let $\left | G \right |=n$ and $gcd\left ( n,m \right )=1$

Recall:
  $\left | g \right | \mid \left | G \right |$ for an element $g \in G$

This implies $\left | G \right |=k\left | g \right | \exists k \in \mathbb{Z}\setminus \left \{ 0 \right \}$
How do I use the fact that gcd(n,m)=1 to aid me?
Looking only for hints.
Thanks in advance.
Comment: Since $\text{gcd}(m,n) = 1$, there exist integers $a,b$ such that $1 = am + bn$.
Comment: As suspected. I tried this and it worked!
Answer: HINT: Let $k=|g|$. Recall that $g^m=e$ if and only if $k\mid m$; if you've seen this before, it's the key fact that you need, and you should try to prove it. You also know that $k\mid n$.
Comment: Bezout's identity works. But I will attempt the question using your hint.

Prove that g=e for a finite group G


monoids of injections and surjections

Question: Let $X$ be an infinite set, and let $I(X)$ and $S(X)$ denote the monoids of injective and surjective maps from $X$ to itself, respectively.  How do $I(X)$ and $S(X)$ relate algebraically?  Is there any reason to suspect that they may be isomorphic aside from optimism?
Comment: Well, assuming the axiom of choice every surjection has an injective inverse. Doesn't this define some sort of embedding from $I(X)$ into $S(X)$ and vice versa; and this embedding preserves the intersection of the two (where it is just the map $f\mapsto f^{-1}$ where $f$ is a bijection)
Comment: @AsafKaragila doesn't it feel a bit like the monoid of maps should be isomorphic to its opposite? That would restrict to an isomorphism between these two sets, I think. I wouldn't be surprised if there were a set theoretic surprise hiding in there...
Comment: @rschwieb: No idea, sorry. As for a bijection between the sets, sure, as long as we assume the axiom of choice holds such a bijection exists.
Answer: $
\newcommand{\tuple}[1]{\left\langle#1\right\rangle}
\newcommand{idX}{\operatorname{id}_X}
%
$The monoids $$\tuple{I(X),\circ,\idX} \text{ and }\tuple{S(X),\circ,\idX}$$ are not isomorphic and neither are $$\tuple{I(X),\circ,\idX} \text{ and }\tuple{S(X),\bullet,\idX},$$ where $f\bullet g = x \mapsto g(f(x))$ is the inverted composition (sometimes denoted by a semicolon like $f{;}g$).
To simplify notation, fix some set $X$, so that $I = I(X)$ and $S = S(X)$, and let assume that there exists isomorphism $\Phi : I \to S$ between them.
Let $B = B(X)$ be the set of all the bijections $X \to X$. Moreover, let
\begin{align}
B_I &= \{f \in I \mid \exists g \in I.\ g\circ f = \idX \land f\circ g = \idX\} \\
B_S &= \{f \in S \mid \exists g \in S.\ g\circ f = \idX \land f\circ g = \idX\}
\end{align}
Surely elements of $B$ have inverses, so $B \subset B_S \subset S$ and $B \subset B_I \subset I$, but we also have that each element of $B_S$ and $B_I$ is a bijection, so $B_I = B = B_S$. Please note that $B$ is a group, so we have four $G$-sets:

left action for $I$, that is, $\lambda_I : B \times I \to I$,
right action for $I$, that is, $\rho_I : I \times B \to I$,
left action for $S$, that is, $\lambda_S : B \times S \to S$,
right action for $S$, that is, $\rho_S : S \times B \to S$.

Observe that, $$\Phi(\idX) = \idX,$$
so $f\circ g = \idX$ implies that $\Phi(f)\circ\Phi(g) = \idX$, hence $\Phi(B) = B$, which means that $\Phi|_B$ is an automorphism of $B$. That also means that $\Phi(I \setminus B) = S \setminus B$. Now $\Phi$ doesn't have to be an isomorphism between the above $G$-sets, but it does preserve stabilizers, that is, set (there are only two symbols, because we know from context whether $f \in I$ or $f \in S$).
\begin{align}
B_{\lambda}(f) &= \{g \in B \mid g \circ f = f\} \\
B_{\rho}(f) &= \{g \in B \mid f \circ g = f\}
\end{align}
then
\begin{align}
\Phi(B_\lambda(f)) &= \{\Phi(g) \in B \mid g \circ f = f\} \\
 &= \{g \in B \mid \Phi^{-1}(g) \circ f = f\} \\
 &= \{g \in B \mid g \circ \Phi(f) = \Phi(f)\} \\
 &= B_\lambda(\Phi(f))
\end{align}
and for any $g \in B_\lambda(f)$ we have $\Phi(g) \in B_\lambda(\Phi(f))$. Similarly for $B_\rho$.
Now, observe that stabilizers for the above defined $G$-sets have specific properties:

for any $f \in I$ we have $B_\lambda(f) = \{\idX\}$,
there exist $f \in I\setminus B$ such that $B_\rho(f) = \{\idX\}$, let's call them lonely,
there exist $f \in I\setminus B$ such that $|B_\rho(f)| \geq 2$.
for any $f \in S\setminus B$ we have $|B_\lambda(f)| \geq 2$,
for any $f \in S$ we have $B_\rho(f) = \{\idX\}$.

This implies that there is no isomorphism between $\tuple{I,\circ,\idX}$ and $\tuple{S,\circ,\idX}$, because for any $f \in I \setminus B$ we would have $\Phi(f) \in S \setminus B$ and $\Phi(B_\lambda(f)) = B_\lambda(\Phi(f))$ which is a contradiction with
$$|\Phi(B_\lambda(f))| = |B_\lambda(f)| = 1 < 2 \leq |B_\lambda(\Phi(f))|.$$
Similarly for $\tuple{I,\circ,\idX}$ and $\tuple{S,\bullet,\idX}$, if you would take any lonely $f \in I \setminus B$, then
$\Phi(f) \in S \setminus B$, but $$|\Phi(B_\rho(f))| = |B_\rho(f)| = 1 < 2 \leq |B_\rho(\Phi(f))|$$ (the composition order is changed for $\tuple{S,\bullet,\idX}$, hence the interpretatino of $\lambda$ and $\rho$ switches too), so there cannot be any isomorphism between them.
I hope this helps $\ddot\smile$

monoids of injections and surjections


Remove row if it is same as previous row, with exception of one column

Question: I have the following dataframe
x <- data.frame(id = c(1:6),
                a = c('a', 'b', 'b', 'a', 'a', 'c'),
                b = rep(2, 6),
                c = c(5, 4, 4, 5, 5, 2))

> x
  id a b c
1  1 a 2 5
2  2 b 2 4
3  3 b 2 4
4  4 a 2 5
5  5 a 2 5
6  6 c 2 2

I want to end up with
  id a b c
1  1 a 2 5
2  2 b 2 4
4  4 a 2 5
6  6 c 2 2

Requirement is that I want to remove the row if it is the same as the previous row, with the exception of the column id. If it is the same as a column further up the column but not immediately previous I do not want to get rid of it. For example id4 is the same as id1 but not removed, as it is not immediately above it.
Any help would be appreciated
Answer: We can use  base R
x[!c(FALSE, !rowSums(x[-1, -1] != x[-nrow(x), -1])),]
#  id a b c
#1  1 a 2 5
#2  2 b 2 4
#4  4 a 2 5
#6  6 c 2 2

Comment: @user1165199  If you need to use the names `nm1 <- setdiff(names(x), "id");  x[!c(FALSE, !rowSums(x[-1, nm1] != x[-nrow(x), nm1])),]`
Comment: This would work, but I have it in a generic function and I cannot guarantee the id column will be the first column so would be dangerous to use this methid
Answer: Here is a way using lag function in dplyr. The idea is creating a key column and check whether it's the same as previous one.
library(dplyr)
x %>%
  mutate(key=paste(a, b, c, sep="|")) %>%
  filter(key != lag(key, default="0")) %>%
  select(-key)

Comment: I think we need the non-standard evaluation in this case. However, I didn't come up with a way to create key using `mutate_`. What I end up with is: `x$key <- apply(x[names(x[-1])], 1, function(x) paste(x, collapse="|"))`.
Comment: Thanks Jason, however in my actual case I have a lot more columns than just a, b and c. Is there a way to do it without naming them all?


Como alterar o idioma da IDE Netbeans No Mac?

Question: Boa noite,
Podem me ajudar a altera o idioma no IDE netbeans 8.2 ? o meu sistema Operacional esta em Português mas como a primeira versão do netbeans instalado estava em inglês acho que deve ter influenciado a versão portuguesa instalado actualmente, tem como alterar manualmente? pelos menus não encontro
Comment: A resposta de alguma forma te atendeu? Precisa de mais alguma informação para aceitá-la?
Answer: Navegue até o diretório de instalação do Netbeans:
C:\Program Files\NetBeans 8\etc

Abre o arquivo netbeans.conf e procure pela linha com a chave netbeans_default_options:
netbeans_default_options="-J-client -J-Xss2m -J-Xms32m -J-XX:PermSize=32m -J-XX:MaxPermSize=200m -J-Xverify:none -J-Dapple.laf.useScreenMenuBar=true"

Adicione o seguinte no final da linha:
"-J-Duser.language=en -J-Duser.region=US"

Reinicie o Netbeans!
Comment: ai meu caro, Murillo Goulart diz quiser no Mac desculpa.
Comment: @Anselmo só o caminho que deve mudar, a princípio, mas a configuração é a mesma!
Comment: Acabei de pensar nisso, estou a procura do arquivo
Comment: Não achei o arquivo, estou a reinstalar o OS.
Answer: Alterar o idioma para inglês no mac:

abra o terminal e acesse o diretório /Applications/NetBeans/NetBeans 8.2.app/Contents/Resources/NetBeans/etc
digite sudo vim netbeans.conf (isso abre o arquivo netbeans.conf em modo admin)
encontre a linha iniciada com netbeans_default_options
ao final desta linha, antes do " adicione -J-Duser.language=en -J-Duser.region=US
salve o arquivo e reexecute o netbeans.

No meu caso, esta linha ficou assim:
netbeans_default_options="-J-client -J-Xss2m -J-Xms32m -J-Dapple.laf.useScreenMenuBar=true -J-Dapple.awt.graphics.UseQuartz=true -J-Dsun.java2d.noddraw=true -J-Dsun.java2d.dpiaware=true -J-Dsun.zip.disableMemoryMapping=true -J-Duser.language=en -J-Duser.region=US"

OBS: meu netbeans é a versão 8.2. Caso você tenha outra instalada, basta ajustar o caminho até a pasta /etc.


partial correlation to control for a continuous variable when examining the relationship between continuous and categorical DV and IVs

Question: I have two similar issues. I have two separate questions, one has a binary DV (is there a brain response yes/no) and the other a continuous DV (how widespread the response is). Each question is looking at the effect of a few IVs on each of the DVs. The IVs are age (continuous), head circumference (continuous) and sex (binary). I am working with infant data and as expected the age and HC are highly correlated.
What I want to do is look at the the effect of age and sex on the two DVs (separately) while controlling for HC. First, is the needed since I know HC and age are correlated (r=.74) so wouldn't controlling for HC of course remove any relationship that may have been there with age and the DV? Would it be best to look at the effect of HC and if there is none, leave it out as a covariate and instead interpret any age effects with HC in mind?
Also, which test is appropriate for this. Before controlling for HC I was using a logistic regression for the binary DV which allows for both continuous and binary IVs. For the continuous DV, I was using a linear regression. Is this even correct? I don't know which test allows me to input a continuous DV and both continuous and binary IVs, let alone a test that allows for that while also inputting a continuous covariate. I use SPSS but if anyone has a specific test in mind I should be able to find a way to do it if SPSS can't.
Thanks in advance!
Answer: If you include both head circumference (HC) and age in your model you will be able to see if HC has an effect independent of age. This would be important if it was thought that having a big head made you more or less likely to respond even allowing for the fact that older infants have bigger heads. It would not be important if you thought HC was only important as another marker of age.
You can include any sort of variable as a predictor in your model (what you call an IV): binary, continuous, and categorical assuming your software will handle categorical appropriately. It does not matter what is on the left hand side of your model (what you call a DV) so it works for linear, logistic, and many others.
Answer:
wouldn't controlling for HC remove any relationship that may have been there with age and the DV?

No. You can imagine multiple regression as trying to test the effect of age on the DV within same age groups: if age truly has an effect on the DV (that is not mediated through HC) it will not disappear after controlling. However, if HC and DV are highly correlated, it will be difficult to separate the age effect from the HC effect. See threads on multicollinearity, e.g. Is there an intuitive explanation why multicollinearity is a problem in linear regression?

Would it be best to look at the effect of HC and if there is none,
  leave it out as a covariate and instead interpret any age effects with
  HC in mind?

No. Univariate models can give different results from the full model (see any intro text on epidemiology, or e.g. Regression coefficients that flip sign after including other predictors). Such unreported testing also leads to model overfitting and inflated p-values (see any thread here on stepwise regression).
To comment more specifically on your situation: in early growth epidemiology it is customary to use age-adjusted measurements, so instead of using raw HC you could look up population-based growth curves and convert your measurements to Z-scores of HC for the corresponding age group. Just keep in mind that it slightly changes your model and interpretation.


How to identify the web element of a select item using Selenium, for the dynamically changing name and id

Question:

<select name="ni.VE402765a6db1fef4043fb7d668c961997" id="ni.VE402765a6db1fef4043fb7d668c961997" class="form-control cat_item_option" onchange="if (typeof(variableOnChange) == 'function') variableOnChange('ni.VE402765a6db1fef4043fb7d668c961997')" aria-readonly="false" aria-required="true"><option value="" selected="SELECTED">-- None --</option><option value="Yes">Yes</option></select>
<input type="HIDDEN" class="cat_item_option" name="sys_original.ni.VE402765a6db1fef4043fb7d668c961997" id="sys_original.ni.VE402765a6db1fef4043fb7d668c961997" value="">

The above is the DIV class of the "SelectBox". The numbers are changing for each and every "SelectBox". I dont want to hard code the id or name, i need a way to identify each and every SelectBox individually.
All the "SelectBox" have the same name and id except for the numbers.
Comment: Can you post the html structure of the selectbox you are referring to ?
Comment: Please check now
Comment: Is `` also same for every selectbox ?
Comment: @SameerArora yes
Comment: @Ijaazops The text in the HTML which you are trying to publish as **bold** isn't really getting **bold**. I would suggest to provide the text based raw HTML. Contributors will be at ease identifying the _dynamic_ part.
Comment: @Ijaazops _The numbers are changing for each and every "SelectBox"_ Can you update the question with the pattern how they are changing and a bit of the _outerHTML_ (parent node)?
Comment: Post more of the surrounding HTML. I'm assuming this `SELECT` has a label like, `State: `. If you provide that, we can write a locator to find that specific `SELECT`.
Answer: Please use the class of the select tag.It should work.I have tried using python code.If you are using java Xpath remain same.
select=Select(driver.find_element_by_xpath("(//select[@class='form-control cat_item_option'])[n]"))
select.select_by_value('Yes')

where n=1.2..n
if you want to search 1st element put 1 instaed of n
Let me Know if this work for you.
Comment: The problem here is that there are several Select Box with the same name and i am unable to identify each Select Box uniquely.
Comment: Try with index.I have updated my code.where 1 is the first element.that way you can identify other object.
Comment: Using indexes on a collection is really not a good idea. Imagine one day another `SELECT` is added to the top of the form. Now your code is finding the wrong `SELECT` and it's going to take you a while to figure out what happened.
Answer: If you don't have a unique identifier for the select you'll have to try to nail it down with the surrounding elements and possibly relying on the fixed ordinal of child elements for the containing element or so.
See Get Nth child of a node using xpath for more details on that.
Comment: I am trying to identify the Select Box not the elements within it. As u suggested in that case the Select Box below this also have the same value
Comment: @ijaazops Surely there is some kind of structure outside of the div you included in the code sample? You should be able to find the correct element with a combination of class selectors, index selectors and element hierarchy. If not then you can get it. Depending on how dynamic the content is this might also be the case but I doubt it.


Create multiple surface plots in GUI

Question: so I just started a new project in which I need to present data I collected on a GUI. For that purpose I created a test script, that reads the data from a .mat file and then calculates the surface plots. So far everything is working. Now I need to start with the GUI. I already managed to create an other test program that can open the OpenFileName-Dialog and reads the data from the file.
from PyQt5 import QtCore, QtGui, QtWidgets
import matplotlib
import matplotlib.pyplot as plt
matplotlib.use('Qt5Agg')
from PyQt5 import QtCore, QtWidgets
from PyQt5.QtWidgets import QFileDialog
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg, NavigationToolbar2QT as Navi
from matplotlib.figure import Figure
import seaborn as sns
import pandas as pd
import sip
import h5py
import mat73
import numpy as np

class MatplotlibCanvas(FigureCanvasQTAgg):
    def __init__(self, parent=None, width = 5, height = 4, dpi = 120):
        fig = Figure(figsize = (width,height))
        self.axes = fig.add_subplot(111)
        super(MatplotlibCanvas,self).__init__(fig)
        fig.tight_layout()

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(1466, 910)
        font = QtGui.QFont()
        font.setFamily("Tahoma")
        MainWindow.setFont(font)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.graphicsView = QtWidgets.QGraphicsView(self.centralwidget)
        self.graphicsView.setGeometry(QtCore.QRect(280, 0, 561, 441))
        self.graphicsView.setObjectName("graphicsView")
        self.graphicsView_2 = QtWidgets.QGraphicsView(self.centralwidget)
        self.graphicsView_2.setGeometry(QtCore.QRect(860, 0, 561, 441))
        self.graphicsView_2.setObjectName("graphicsView_2")
        self.graphicsView_3 = QtWidgets.QGraphicsView(self.centralwidget)
        self.graphicsView_3.setGeometry(QtCore.QRect(280, 440, 561, 441))
        self.graphicsView_3.setObjectName("graphicsView_3")
        self.graphicsView_4 = QtWidgets.QGraphicsView(self.centralwidget)
        self.graphicsView_4.setGeometry(QtCore.QRect(860, 440, 561, 441))
        self.graphicsView_4.setObjectName("graphicsView_4")
        self.pushButton = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton.setGeometry(QtCore.QRect(40, 90, 75, 23))
        self.pushButton.setObjectName("pushButton")
        MainWindow.setCentralWidget(self.centralwidget)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)
        self.action_Open = QtWidgets.QAction(MainWindow)
        self.action_Open.setObjectName("action_Open")
        self.action_Save = QtWidgets.QAction(MainWindow)
        self.action_Save.setObjectName("action_Save")
        self.action_Export = QtWidgets.QAction(MainWindow)
        self.action_Export.setObjectName("action_Export")
        self.action_Exit = QtWidgets.QAction(MainWindow)
        self.action_Exit.setObjectName("action_Exit")

        self.filename = ''
        self.canv = MatplotlibCanvas(self)
        self.df = []

        self.toolbar = Navi(self.canv, self.centralwidget)

        self.pushButton.clicked.connect(self.getFile)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def getFile(self):
        """ this function will get the adress of the mat file location
            also calls a readData function
        """
        self.filename = QFileDialog.getOpenFileName(filter="mat (*.mat)")[0]
        print("File: ", self.filename)
        self.readData()

    def readData(self):
        self.df = mat73.loadmat(self.filename, use_attrdict=True)
        struct = self.df['DemoData']
        print(struct.Nr.data)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.pushButton.setText(_translate("MainWindow", "Open "))
        self.action_Open.setText(_translate("MainWindow", "&Open"))
        self.action_Save.setText(_translate("MainWindow", "&Save"))
        self.action_Export.setText(_translate("MainWindow", "&Export"))
        self.action_Exit.setText(_translate("MainWindow", "&Quit"))

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())

Since I can read the data, next step would be to create the surface plots and display the data. My idea was to use the graphicsView elements to display the four needed plots, but I just can't find how to link the figures, I used in the first test program (without GUI) to the graphicsView element. For the figure I used the following code line:
fig, ax = plt.subplots(subplot_kw={"projection": "3d"})
surf = ax.plot_surface(pArray, rArray, trArray, alpha = 0.5)
surf = ax.plot_surface(pArray, rArray, tArray, cmap=cm.jet, alpha = 1)

Can someone give me a tip, how I could achieve that?
Edit: I uploaded a .mat File .mat File
Comment: please share some .mat
Comment: @eyllanesc I added the link to a .mat file, I would be using for the surface plot
Comment: How to read this file to get the X, Y and Z?
Comment: I could read the data: TempRef, Nr and TempAct but they are 1162334x1 arrays but those do not form a surface since for this they need to be two-dimensional arrays
Answer: I have to note that:

mat73 has trouble reading the provided .mat so I use scipy.
The data contained in the .mat are one-dimensional arrays so they could not form a surface since for this two-dimensional arrays are required so I will only show how to draw the points.
Due to the large number of dots, painting takes time and may freeze

The logic is to work with the FigureCanvas and create 3d plots:
from functools import cached_property

from PyQt5.QtWidgets import QApplication, QFileDialog, QMainWindow

from matplotlib.backends.backend_qt5agg import (
    FigureCanvas,
    NavigationToolbar2QT as NavigationToolbar,
)
from matplotlib.figure import Figure
from matplotlib import cm

import scipy.io as sio

class MainWindow(QMainWindow):
    def __init__(self, parent=None):
        super().__init__(parent)

        self.ax = self.canvas.figure.add_subplot(projection="3d")
        self.setCentralWidget(self.canvas)
        self.addToolBar(self.toolbar)

        file_menu = self.menuBar().addMenu("&File")
        open_action = file_menu.addAction("&Open")

        open_action.triggered.connect(self.handle_open_action_triggered)

    @cached_property
    def canvas(self):
        return FigureCanvas()

    @cached_property
    def toolbar(self):
        return NavigationToolbar(self.canvas, self)

    def handle_open_action_triggered(self):
        filename, _ = QFileDialog.getOpenFileName(self, filter="mat (*.mat)")
        if filename:
            self.load_mat(filename)

    def load_mat(self, filename):

        res = sio.loadmat(filename)
        record = res["record"]
        data = record["Data"]
        temp_ref = data[0, 0]["TempRef"][0, 0][0, 0]["data"]
        nr = data[0][0]["Nr"][0, 0][0, 0]["data"]
        temp_act = data[0, 0]["TempAct"][0, 0][0, 0]["data"]
        self.update_plot(temp_ref, nr, temp_act)

    def update_plot(self, x, y, z):
        print(x.shape, y.shape, z.shape)
        self.ax.scatter(x, y, z)
        self.canvas.draw()

if __name__ == "__main__":
    import sys

    app = QApplication(sys.argv)
    w = MainWindow()
    w.show()
    sys.exit(app.exec_())

Comment: Thank you for your code. It seems that the .mat file got changed by Matlab, when I deleted some datapoint, which I'm not allowed to share. That must be the reason why mat73 is not working. The .mat files I receive from the recording software can be read just by using mat73. The data I shared with you, is actually the same data I'm using for the calculation, I just create the needed arrays with the three arrays.
Comment: I just tried to update my code with the code you provided, but I do not get a plot. What I don't get are the following points: I'm using 'class Ui_MainWindow(object)', but you are using 'MainWindow(QMainWindow)', what is the differenc? I'm creating the code using the QT Desinger. Also how can I set the position of the plot. In my GUI I need to show four surface plots at the same time. That's why I created such a big main window
Comment: @user3794592  read https://stackoverflow.com/questions/46544780/qtdesigner-changes-will-be-lost-after-redesign-user-interface
Comment: Thank you for the link. I will update my code, for using a logic.py and Design.py
Comment: now updated my code, so that the figure is shown on the main window. So that works fine. But how can I set the geometry (the size of the figure and the position) of the plot? I also want to show four plots on one screen. For that, can I create multiple instances of the subplot and call multiple times the update_plot() method?
Comment: I already figured it out, thanks for your help. For documentation, I'm using four instances of the subplot command and use the grid location of the subplot

Create multiple surface plots in GUI


How to run a command at boot up automatically?

Question: I need to mount a shared folder at a boot up automatically so I don't have to manually write this line to the xterm every time:
sudo mount -t vboxsf share ~/host

I have done this:
sudo crontab -e

And added at the end of the file:
@reboot /home/richard/mounthost

The file /home/richard/mounthost contains:
sudo mount -t vboxsf share ~/host

But it is not working. Any help?
I am using Ubuntu 10.10
Answer: For mounting on boot, you should add it to /etc/fstab. Take a look here:

https://help.ubuntu.com/community/Fstab
Answer: The proper place to add filesystems to be mounted on boot is /etc/fstab. See the fstab(5) man page for details.
Answer: Add a line to /etc/fstab.  This will mount the file system at startup,  The header will show you which column to place the various option.  Use man mount and man fstab for additional information.
Answer: The other answers here have already pointed out the proper way of specifying boot-time mounts.
So why does your script not work? Have you set execute permissions on it? e.g.
chmod +x /home/richard/mounthost

Perhaps the device is not yet ready to be mounted at the point in time when cron runs its @reboot jobs? Check the system logs for messages.
Finally, a note about system security: It is very bad policy to run scripts from the root crontab that are not owned by root! If the richard account is ever compromised, an intruder can gain root access by modifying /home/richard/mounthost. If you decide not to put your device into /etc/fstab, I would strongly recommend changing your crontab entry so that it runs the mount command directly, and does not run a non-root-owned script.
Comment: Very nice point on not running scripts from root, which are not owned by root. :)


How can i find a solution of this optimization problem?

Question: I need to give a solution for this variational problem
$$\min_{x\in C^2[0,1]}\int_0^1\left(1+|x''(t)|^2\right)dt$$
$$x(0)=0\hspace{0.2cm},\hspace{0.2cm} x(1)=1\hspace{0.2cm},\hspace{0.2cm}x'(0)=1\hspace{0.2cm},\hspace{0.2cm} x'(1)=1$$
I know I have to use Euler-Lagrange equation but I'm having a problem with the second order derivative of $x$. Can someone enlighten me plis?
Answer: The integral yields a minimum value of $1$ precisely when $x''(t)=0$ uniformly on $[0,1]$. Otherwise, there would exist non-zero continuous $y'':t\mapsto y''(t)$ such that $$\int_0^1\big(1+0^2\big)dt\geq\int_0^1\big(1+|y''(t)|^2\big)dt$$ implying $\int_0^1|y''(t)|^2dt\leq0$. However, since $y''$ is non-zero and continuous we may fix $\epsilon>0$ and a non-empty open sub-interval $(a,b)$ of $[0,1]$ on which $y''(t)^2>\epsilon$ yielding the contradiction
$$\int_0^1|y''(t)|^2dt=\int_a^b|y''(t)|^2dt+\int_{[0,1]-(a,b)}|y''(t)|^2dt>(b-a)\epsilon+0>0$$ because every Riemann sum approximation of $\int_{[0,1]-(a,b)}|y''(t)|^2dt$ is a non-negative real number.
Therefore, because $x'(1)=1$ then $x'$ is the constant function defined by $x'(t)=1$. Since $x(0)=0$ then $x(t)=t$ which also satisfies $x(1)=1$.


How to solve $\int_0^{\infty}\frac{\log^n(x)}{1+x^2}dx$?

Question: As an exercise for myself I constructed the Integral
$$
\int_0^{\infty}\frac{\log^n(x)}{1+x^2}dx
$$
with $n\in \mathbb{N}$. With the help of Mathematica I found the analytical result
$$
\int_0^{\infty}\frac{\log^n(x)}{1+x^2}dx=\frac{1+(-1)^n}{4^{n+1}}\Gamma(n+1)\left[\zeta\left(n+1,\frac{1}{4}\right)-\zeta\left(n+1,\frac{3}{4}\right)\right].
$$
For $n=1$ (and probably $n\in \mathbb{N}$) one can employ the methods of complex analysis and find a result. For $n\in \mathbb{N}$ I encountered a nasty recursion relation. I can provide details if needed. Is there another way how to solve the integral at hand?
Comment: $\displaystyle \beta(n+1)=\frac{1}{4^{n+1}}\left[\zeta\left(n+1,\frac{1}{4}\right)-\zeta\left(n+1,\frac{3}{4}\right)\right]\enspace$ where $\beta(s)$ is the *Dirichlet beta function* .
Answer: Referring to this answer,
$$I_n=\frac{\pi}2\frac{d^n}{dx^n}\sec\left(\frac{\pi x}2\right)\bigg\vert_{x=0}$$
or equivalently,
$$\int^\infty_0\frac{\log^n(x)}{x^2+1}dx=\left(\frac{\pi}2\right)^{n+1}\sec^{(n)}(0)$$
$$\int^\infty_0\frac{\log^{2n}(x)}{x^2+1}dx=(-1)^nE_{2n}\left( \frac{\pi}2\right)^{2n+1} $$
The integral is zero for odd $n$.
Comment: @Schnarco : $E_n$ are called *Euler numbers* .
Comment: Thank you both!
Answer: Let, for $n$, a natural integer,
\begin{align}J_n=\int_0^\infty \frac{\ln^n x}{1+x^2}\,dx\end{align}
First, observe that if $n$ is odd then $J_n=0$ (perform the change of variable $y=\dfrac{1}{x}$ )
Consider, for $n$, a natural integer,
\begin{align}K_n=\int_0^\infty \int_0^\infty\frac{\ln^n(xy)}{(1+x^2)(1+y^2)}\,dx\,dy\end{align}
Observe that,
\begin{align}K_{2n}&=\sum_{k=0}^{2n}\binom{2n}{k} J_kJ_{2n-k}\\
&=\sum_{k=0}^{n}\binom{2n}{2k} J_{2k}J_{2(n-k)}
\end{align}
On the other hand,
Perform the change of variable $u=xy$ ($x$ variable, $y$, a "parameter"),
\begin{align}K_n&=\int_0^\infty \int_0^\infty\frac{y\ln^n u}{(1+y^2)(u^2+y^2)}\,du\,dy\\
&=\frac{1}{2}\int_0^\infty \left[\ln\left(\frac{1+y^2}{u^2+y^2}\right)\right]_{y=0}^{y=\infty}\frac{\ln^{n} u}{u^2-1}\,du\\
&=\int_0^\infty \frac{\ln^{n+1} u}{u^2-1}\,du\\
&=\int_0^1 \frac{\ln^{n+1} u}{u^2-1}\,du+\int_1^\infty \frac{\ln^{n+1} u}{u^2-1}\,du\\
\end{align}
In the second integral perform the change of variable $v=\dfrac{1}{u}$,
\begin{align}K_n&=\int_0^1 \frac{\ln^{n+1} u}{u^2-1}\,du+\int_0^1 \frac{\ln^{n+1} u}{u^2-1}\,du\\
&=\int_0^1 \frac{\left(1+(-1)^n\right)\ln^{n+1} u}{u^2-1}\,du\\
&=\left(1+(-1)^n\right)\int_0^1 \frac{\ln^{n+1} u}{u-1}\,du-\left(1+(-1)^n\right)\int_0^1\frac{u\ln^{n+1} u}{u^2-1}\,du\\
\end{align}
In the latter integral perform the change of variable $y=u^2$,
\begin{align}K_n&=\left(1+(-1)^n\right)\int_0^1 \frac{\ln^{n+1} u}{u-1}\,du-\frac{1+(-1)^n}{2^{n+2}}\int_0^1 \frac{\ln^{n+1} u}{u-1}\,du\\
&=\left(1+(-1)^n\right)\left(1-\frac{1}{2^{n+2}}\right)\int_0^1 \frac{\ln^{n+1} u}{u-1}\,du\\
&=\left(1+(-1)^n\right)\left(1-\frac{1}{2^{n+2}}\right)(-1)^{n+2}(n+1)!\zeta(n+2)
\end{align}
Therefore, one obtains a recursion relation,
\begin{align}
\boxed{\sum_{k=0}^{n}\binom{2n}{2k} J_{2k}J_{2(n-k)}=2\left(1-\frac{1}{2^{2n+2}}\right)(2n+1)!\zeta(2n+2)}
\end{align}
Observe that,
\begin{align}J_0=\frac{\pi}{2}\end{align}


HTML5 localStorage adding to value with script

Question: I'm trying to use localStorage to register the right answers to an offline game. I've got the key and value stored, and can alter it using the code below. I'd like each right answer to add to the localStorage (localStorage.right plus 1), then move to the new page. Any ideas? Thank you in advance.
Code for HTML:

<input name="rightbtn" type="button" id="rightbtn" onclick="localStorage.right = '7'" value="Right" />

Answer: Should work
localStorage.right = localStorage.right++;

Or a bit nicer:
// 'right' is a bit conflict prone.
localStorage.correctAwnsers = localStorage.correctAwnsers + 1;

Note: localStorage is only supported in the latest browsers.
Note: When testing from file:// protocol, localStorage goes wonky in some browsers.


Sum of 6 cards being multiple of 6

Question: I pick 6 cards from a set of 13 (ace-king). If ace = 1 and jack,queen,king = 10 what is the probability of the sum of the cards being a multiple of 6?
Tried so far:
I split the numbers into sets with values:
6n, 6n+1, 6n+2, 6n+3
like so:
{6}{1,7}{2,8}{3,9}{4,10,j,q,k}{5}
and then grouped the combinations that added to a multiple of 6:
(5c4)(1c1)(2c1) + (2c2)(2c2)(2c2) + (5c4)(2c2) + (5c2)(1c1)(1c1)(2c1)(2c1)
/ (13c6)
= 10/1716
I am almost certain I am missing combinations but am having trouble finding out which.
Comment: Sure, i've edited my question with what i've done so far.
Comment: The valid numbers are {24,30,36,42,48,54}, You could find all the combinations that add to 24,30, etc. but that seems tedious.
Comment: Looks like a good start. It would probably help to list the numbers (modulo $6$) from each combination, for example it looks like you have found $4+4+4+4+5+3=6\cdot4,$ or maybe it's $4+4+4+4+2+0=6\cdot3.$ Each such combination fits different possible sets of cards.
Comment: For example, we can easily see we can't use all five of the "$6n+4$" cards in the six-card set, but we can use exactly three of them. Or two. Or even exactly one.
Comment: Ok, I think i see what i'm missing. I'll update what I have now. @Oliver yes, i am hoping to do it in a less tedious way.
Comment: @DavidK Why not all 5 from '6n + 4'? 44 and then add both from the {2,8} set to = 54.
Comment: @JayF Because then you would have seven cards, and we're looking for sets of six cards.
Comment: Ahh, sorry my bad.
Comment: Nobody has asked if these six cards are picked with or without replacement.
Comment: @satishramanathan Good point. I think because it is "cards" with standard playing-card ranks, we tend to assume "without replacement," similar to dealing a hand in poker or bridge.
Answer: You can "cast out" any $6$s from the values of the cards, since it will not affect whether the sum is a multiple of $6$. So you have 13 cards valued 1,2,3,4,5,0,1,2,3,4,4,4, and 4. How many ways can you make a multiple of 6 from the sum of 6 of these numbers? Consider the number of 4s used. If none, you can make a sum of 12 (1,2,3,1,2,3) or (0,1,1,2,3,5). With one 4, you can enumerate the possibilities, and so on.
Answer: Here is a partial answer to your question.  You want the sum of two cards to be 6, 12 or 18.
For the sum of 6, the possibilities are 1+5, 2+4, and 3+3
The probability of an ace and a 5 is 1/13 times 1/12.
Same with 2+4, to wit, 1/(13*12) = 1/156.
For two threes, we have 1/13 times 3/51.
The sum of these is 2/156 + 3/(13*51)
You still need to do 12 and 18
Comment: He is drawing six cards, not two.
Comment: Sum of *6* cards. So the multiples are in the range of 24 -54.
Answer: Your combinations are $4\cdot 4+1\cdot 0+1\cdot 2, 2\cdot 1+2\cdot2+2\cdot3, 4 \cdot 4+2\cdot 1,+$ something that doesn't make sense because there are three places you choose from $1$ and only $0,5$ qualify.  The left number is the number of cards of that value $\pmod 6$ .  You could also have $3\cdot 4+1 \cdot 5+1 \cdot 1+1 \cdot 0, 3 \cdot 4+ 2 \cdot 2 + 1 \cdot 0$ and others
Comment: It looks like the question is still a work in progress. I asked OP to show his work, and now he's doing that as well as he can (given that he's still working on the problem!).
Comment: I'm not quite sure I understand. You're saying (5c2)(1c1)(1c1)(2c1)(1c1) doesn't make sense? Haha, yes @DavidK definitely a work in progress.
Comment: @JayF:  I couldn't figure out what sum of cards it represented.  You have three $1c1$s, but there are only two values (0 and 5) that have only one card that can represent them.  If it is $2\cdot 4 + 1 \cdot 5 + 1 \cdot 0 + $ something that adds to $3$, it would have to be $2\cdot 4 + 1 \cdot 5 + 1 \cdot 0 + 1 \cdot 1 + 1 \cdot 2 $ and one of the $1c1$s should be a $2c1$
Comment: Ah you're right. It should be (5c2)(1c1)(1c1)(2c1)(2c1) like you say.
Comment: I think my problem is not knowing how to systematically find all the combinations. Any ones you can see that i'm missing?
Comment: I listed some in the last sentence of my answer.  You are right, it is hard to make sure you have them all.  Intuitively, the probability should not be too far from $1/6$ so you must be missing a lot.
Answer: Answer:
Repetition of 10 is not the same as they represent different cards.  I have done it through brute force.  Hopefully I have captured everything.
Good luck
Satish
Answer: It will help to explicitly list the values of cards in each combination, as other answers have done, then count the number of ways you can make each combination.
If doing this by hand rather than by computer, you were wise to group the cards by
their remainders after division by $6$; you can use just the remainders as the terms
of your sum (as already shown in two answers).
For example, you can make a multiple of $6$ by taking $4+4+4+4+5+3=24.$
There are exactly $\binom54\binom11\binom21$ ways to draw cards without replacement
whose remainders would add up in exactly this way.
(You could also write this expression $(5C4)(1C1)(2C1)$ as you did in the question.)
But you can also make a multiple of $6$ by taking $4+4+4+4+2+0=24.$
There are also exactly $\binom54\binom11\binom21$ ways to draw such a set of cards
(or you could write $\binom54\binom21\binom11$ so that the terms you are multiplying
are in the same order as the corresponding terms of the sum, for clarity),
and these sets are all different from the ones that are counted in the previous paragraph.
You might make a table of sums and the number of ways to draw each sum:
$$\begin{array}{lcrcr}
4+4+4+4+5+3=24 && \binom54\binom11\binom21&=&10 \\
4+4+4+4+2+0=24 && \binom54\binom21\binom11&=&10 \\
4+4+4+4+1+1=24 && \binom54\binom22&=&5 \\
4+4+4+5+1+0=18 && \binom53\binom11\binom21\binom11&=&20
\end{array}$$
Continue this column for several more rows until you have listed all the sums that
are possible to draw that are divisible by $6.$
Then you can add up the values in the right-hand column.

Sum of 6 cards being multiple of 6


How to include geoscript as a dependency in Scala intelliJ project?

Question: New to Scala and sbt; coming from a python world, and rather confused by library dependencies, versioning, and what sbt can and cannot automatically download (i.e. when a .jar needs to be manually placed in /lib).
I want to use classes from the Scala geoscript project (http://geoscript.org/scala/quickstart.html) in my Scala app.
I'm using IntelliJ with Scala 2.11.8.
Can I ultimately do something like:
libraryDependencies += "org.geoscript" % "some-artifact" % some=version
Or is this going to be an "unmanaged dependency"? And if so, what's the cleanest way to do that?
Answer: If a dependency jar is published to Maven Central and some other repositories, sbt will automatically be able to resolve and download it when declaring it as libraryDependency. This is a "managed dependency". Usually a library's documentation will tell you the "coordinates" (group id, artifact id, version) you need to install it.
From the page you linked and the Maven search, it looks like Geoscript is not published, so you will have to add it to your /lib folder in the project. That should be enough to put it in the classpath. You may need to refresh the project for IntelliJ to pick it up and offer completions.
Comment: Thanks for the response Justin. I tried to build and then package the project into a .jar, and added that to my project's external libraries. While the import statements worked (intelliJ was able to locate the classes), actually using the library threw a lot of "unresolved symbol" despite the successful imports - some further underlying dependencies issues. In any case, I'm going to KISS, and find an alternative geospatial project included in Maven Central. Thanks!
Comment: If you package up your own jar based on the other library and use it in yet another project, you will need to put both your and the other jar on the classpath. sbt does this for you with managed dependencies, but with unmanged you have to do it yourself


Funcão Javascript não funciona

Question: Tenho uma função que funciona no meu teste feito no bloco de notas, mas no projeto não funciona.

                                                Para Sistema Integrado de Gestão, clique aqui

                                                (abrirá um formulário nesta mesma página para você preencher)

                                                6 - Apenas para Sistema Integrado de Gestão

                                                Responda a esta seção apenas se você estiver interessado em uma certificação integrada (opcional).

                                                A Política e o Manual do Sistema de Gestão são integrados?

                                                <asp:RadioButtonList ID="rblPoliticaManualSistemaIntegrados" runat="server" RepeatDirection="Horizontal">
                                                    <asp:ListItem Value="Sim" Text="Sim"></asp:ListItem>
                                                    <asp:ListItem Value="Não" Text="Não"></asp:ListItem>
                                                </asp:RadioButtonList>

                                                Os procedimentos de gestão (ex: Controle Documentos, Auditorias) são integrados?

                                                <asp:RadioButtonList ID="rblProcGestaoIntegrados" runat="server" RepeatDirection="Horizontal">
                                                    <asp:ListItem Value="Sim" Text="Sim, pelo menos 80% dos procedimentos de gestão são integrados"></asp:ListItem>
                                                    <asp:ListItem Value="Não" Text="Não"></asp:ListItem>
                                                </asp:RadioButtonList>

                                                Os procedimentos operacionais (ex: Controle de produção) são integrados?

                                                <asp:RadioButtonList ID="rblProcOperacionaisIntegrados" runat="server" RepeatDirection="Horizontal">
                                                    <asp:ListItem Value="Sim" Text="Sim, pelo menos 80% dos procedimentos operacionais são integrados"></asp:ListItem>
                                                    <asp:ListItem Value="Não" Text="Não"></asp:ListItem>
                                                </asp:RadioButtonList>

Comment: Você já viu no console qual é a mensagem de erro que dá?
Comment: @JoelRodrigues da "Object Required"
Comment: Funciona bem para mim... ---> http://jsfiddle.net/6nj8djdo/ Podes explicar o que fica errado nesse exemplo?
Comment: @Sergio Então, fora da aplicação funciona, mas dentro não funciona.
Comment: @AndreeH tens essa aplicação online para podermos ver? senão fica dificil reproduzir o problema e poder ajudar.
Comment: @Sergio, cara depois de um tempo tentando muitas coisas, fui perceber que era asp.net pelo runat="server" e então coloquei o  ClientIDMode="Static" e funcionou.
Answer: Assim como disse na outra resposta, o seu erro acontece, porque no seu elemento não existe nenhum atributo display definido.
getElementById(div).style.display == "none"

O que essa linha de código significa:
"Compare o atributo display do elemento com tal ID e compare com none"
Como o atributo display não existe na definição de seu elemento, o erro é gerado.
Correção
Edite o elemento HTML chamado pela função e adicione style="display:none"
Por exemplo:
Se o seu elemento era:

ele deve ficar:

Comment: Consegui. Adicionei um ClientIDMode="Static" na div que eu queria pegar o id e foi. Obrigado a todos.
Answer: Percebi que você está usando ASP.NET Web Forms, certo? O ID de alguns elementos é alterado em tempo de execução, isso pode estar causando o problema. Coloque, por exemplo, um alert(div) dentro da função para ver se o ID está sendo passado como esperado e inspecione o elemento no browser para ver se ele está com o mesmo ID.
Comment: Puts @Joel Rodrigues, to ligado nisso, mexo com asp.net, mas nesse caso to mexendo com asp clássico que não manjo muito, e sei um pouco de javascript também mas esse erro me tirou do sério rs.
Answer: Tente trocar:
Para Sistema Integrado de Gestão, clique aqui

Por
Para Sistema Integrado de Gestão, clique aqui

Algumas aplicações costumam dar bug quando usamos a tag de link...
Editado: A div está rorando no servidor e a o script rodando do lado do cliente, acompanhar comentários
Comment: Não adianta @jefissu .. :S
Comment: Acho que é por que seu div está carregado no servidor e vc está tentando escondê-lo pelo cliente então. tente colocar um runat="server" na div que executa a função. tente deixar também a função js no lado do server
Comment: então, eu creio que pode ser isso. Como mudo isso, sabe ?
Comment: Experimente excluir este runar server desta div div e mode-o para a tabela, acho q deve resolver
Comment: No Asp classico vc não precisa definir nenhum controle com runat server, pelo menos eu não uso nada rodando no servidor relacionado a controles...
Comment: Então @jefissu, tá tudo misturado essa zica aqui. Eu percebi isso também agora e fiz o teste, joguei um ClientIDMode="Static" e consegui.
Comment: Ok, só não esqueça de marcar a questão como resolvida então
Comment: @AndreeH Isso é do ASP.Net, sinal que você não está usando asp clássico...
Comment: @bfavaretto é cara, eu percebi quando eu vi o runat="server", ai coloquei o  ClientIDMode="Static" e funcionou.
Answer: Consegui colocando ClientIDMode="Static" no elemento em que eu precisava pegar o ID e passar como parâmetro para a function.

Funcão Javascript não funciona


Store output from a php function

Question: I think im a bit over my head on this, but I have a wordpress function that i cant control and it outputs HTML.
It specifically outputs a  tag. When i try to store that output into a variable it just echos out the anchor tag even though i thought i stored the output.
I talked to someone that knows more about this and they said the function probably is using its own output system.
Im wondering if there is a way to store the functions output before it echos it out. Like this(but this doesn't work):
$link = wp_function();

This echos out the  tag and doesn't store the data.
Comment: What's the exact name of function you are trying with?
Answer: <?php
ob_start();
wp_function();
$link = ob_get_contents();
ob_end_clean();
?>

Same issue here, How do I capture PHP output into a variable?
Answer: Wordpress have to two types of functions:-

Functions which does not return anything but echoes out output.
Functions which does not echoes out anything but returns output for further uses.

All most all functions have prefixed with get_ to return the value.
for an example the_title just output title whereas get_the_title returns the title.
Search if the function have their get_ version available and use them.
Comment: +1 because while it doesn't solve the question as stated, that doesn't mean that it isn't the right way of solving the problem. Hopefully this will help others in the future as well.
Comment: this is the function that i am working with: http://codex.wordpress.org/Template_Tags/wp_list_categories
Answer: You should be able to call ob_start prior to your wp_function() call and then use ob_get_flush():
ob_start();
wp_function();
$link = ob_get_flush();

Comment: i see that ob_get_flush() is a combination of returning the string and turning off the output buffering but is it any different from ob_get_contents();
ob_end_clean();
Comment: @Nils: No. It just combines the two.
Comment: this actually doesn't seem to "catch" the output the same way the other two functions do. When i use the other two functions, it catches whatever the output is and then i do some manipulating and regex stuff to it and echo out the final result. When i use the single ending function, it still echos out the original function AND the regex stuff that i did to it as well. So there seems to be a difference
Answer: https://www.php.net/manual/en/ref.outcontrol.php this may help with more functions
Answer: What function are you using exactly?
Have you tried to pass the 'echo' => false argument?
I have had this problem when using the wp_nav_menu() function and fixed it with this argument:
$menu = wp_nav_menu( 'echo' => false );

Store output from a php function


Race condition when running functional tests in Sails.js using Mocha and Grunt

Question: I am using Sails v0.10.x and have an issue when running my functional tests.
test/bootstrap.test.js
// force the test environment to 'test'
process.env.NODE_ENV = 'test';

var Sails = require('sails');

// use zombie.js as headless browser
var Browser = require('zombie');

// Global before hook
before(function(done) {
  var self = this;
  // Lift Sails and start the server
  Sails.lift({
    log: {
        level: 'error'
    },
  }, function(err, sails) {
    // initialize the browser using the same port as the test application
    self.browser = new Browser({ site: 'http://localhost:1337', debug: false });

    done(err, sails);
  });
});

// Global after hook
after(function(done) {
  Sails.lower(done);
  this.browser.close();
});

The problem is Sails.lift triggers the default Grunt task to run. One of the things this task does is clean out the public folder and then copy assets across.
The issue I have is my functional tests are running whilst this copying is still happening. This means I get lots of 404 errors (and failing tests) when my headless browser is requesting static assets.
I'm guessing there could be several solutions

add a news "sails lift" command that doesn't clean down the public folder (this could cause issues when running tests after deployments though?)
adding a timeout after sails lifts before firing up my headless browser (this seems hacky though)
some kind of callback/event (not sure this is possible?)

What solutions have others come up with for this problem?
Answer: You can try lifting the app in production mode:
Sails.lift({
  log: {
      level: 'error'
  },
  environment: 'production'
}, function(err, sails) {...}

In production mode, Sails doesn't finish lifting until all Grunt tasks are complete.
If this isn't an option for you (because you require your tests to run in a different environment with specific settings), you can instead listen for the hook:grunt:done event and not start your test until you receive it.  You'll need to turn off the "watch" task for the environment you're running the tests in (otherwise Grunt will never be done!).  That means if you want to keep "watch" for your development environment, you'll need to run the tests in a different environment (which is a good idea anyway).  So first, in tasks/register/default.js:
module.exports = function (grunt) {
  var tasks = ['compileAssets', 'linkAssets'];
  if (process.env.NODE_ENV !== 'test') {tasks.push('watch');}
    grunt.registerTask('default', tasks);
};

Then in your test:
var async = require('async');
async.parallel({
  // Set up a listener for grunt finish
  listenForGrunt: function(cb) {sails.on('hook:grunt:done', cb);},
  // Lift sails
  liftSails: function(cb) {
    Sails.lift({
      log: {
        level: 'error'
      },
    }, function(err, sails) {
      self.browser = new Browser({ site: 'http://localhost:1337', debug: false });
      cb(err, sails);
    });
  }
}, done);

Run your tests with NODE_ENV=test mocha, or better yet in your package.json under scripts, put:
"test": "NODE_ENV=test mocha"

So that you can just run npm test.
This will ensure that done is not called until Sails has lifted and Grunt is finished.
Comment: Thanks for the reply, but unfortunately this doesn't work. The done is being triggered whilst the copy is still happening.
Comment: Interesting--when I tested this I couldn't get it to call "done" at all, as I realized the "watch" task was preventing it.  Updated my answer with info about disabling "watch" for tests.  After I did that, this worked like a charm.


How to use module template to override a specific Views field and send the right variable?

Question: I hope the title is ok. I've seen many discussion here about using custom templates in a module when using views, but i lack a piece of answer : how to use specific variables from an entity in that template ?
Backgound information about my problem :
I'm making a module 'youtube2drupal', using a custom table 'youtube_video', having some fields (one of them is 'vhash', the video hash in youtube). With this table i create an entity 'ytv'. I added this key to mymodule_entity_info() to use with Views : 'views controller class' => 'EntityDefaultViewsController',
Then to test it i create a view displaying one video with all its informations => everything is ok.
Everything BUT, to display the video, i need a iframe and i cant't use the rewrite of the output for the 'vhash' field i added in the view field.
The code needs to be :
<iframe width="560" height="315" src="//www.youtube.com/embed/<?php print $vhash; ?>" frameborder="0" allowfullscreen>

In the suggested template for the view, there is one i can use : views-view-field--vhash.tpl.php
I don't want to override any theme : i'd like to have all the code in my module.
So I created this file 'views-view-field--vhash.tpl.php' in my /templates dir in my module.
I looked for solutions to tell Drupal to use it:
First, I've checked this lead, with hook_theme_registry_alter()
https://swsblog.stanford.edu/blog/using-templates-custom-drupal-module
and i tried
function youtube2drupal_theme_registry_alter(&$theme_registry) {
  dpm($theme_registry);
  $module_path = drupal_get_path('module', 'youtube2drupal');
  $theme_registry['views_view_field__vhash']['theme path'] = $module_path . '/templates';
  $theme_registry['views_view_field__vhash']['template'] = 'views-view-field--vhash';
}

but the 'views_view_field__vhash' key doesn't exists, so it seems this is not the right solution to register this template.
Then i saw this discussion
https://stackoverflow.com/questions/5305114/drupal-7-how-to-load-a-template-file-from-a-module#answer-5307126
so i tried
function youtube2drupal_theme($existing, $type, $theme, $path){
  return array(
    'views_view_field__vhash' => array(
      'variables' => array('vhash' => NULL),
      'template' => 'views-view-field--vhash',
      'path' => drupal_get_path('module', 'youtube2drupal') . '/templates'
    )
  );
}
function youtube2drupal_page(){
  // some code to generate $vhash variable : this is where i'm stuck !
  return theme('views_view_field__vhash', array('vhash' => $vhash));
}

=> This seems the right way to register correctly the template but i don't know how to set vhash variable in this context :
i want to use something like $myentity->vhash.
but i can't use $myentity = entity_load('ytv', array($entity_id)); because $entity_id is not defined in youtube2drupal_page() context.
Am i on the right track using youtube2drupal_theme() / youtube2drupal_page() to register the
template for the module ? If so how can i tell Drupal to use the right value of vhash for this entity i created ?
----- Edit -------
I tried the preprocess function :
I changed :
function youtube2drupal_theme($existing, $type, $theme, $path){
  return array(
    'views_view_field__vhash' => array(
      'template' => 'templates/views-view-field--vhash',
      'file' => 'includes/youtube2drupal.theme.inc',
      'base hook' => 'views-view-field',
    )
  );
}

and added in the includes/youtube2drupal.theme.inc :
function youtube2drupal_preprocess_views_view_field__vhash(&$variables, $hook) {
  dpm($variables);
  $variables['vhash'] = $variables['view']->result[0]->youtube_video_vhash;
  //sets the right value into $vhash, but only for the first element
}

This doesn't "break" the site, but obviously the $variables['view']->result[0]->youtube_video_vhash; is valid only for the first element in the list. If i want to display 2 or more videos, the keys for $variables['view']->result should be 1, 2, ...
So, how can i dynamically set this vhash variable with the correct value ? Is it possible that way ?
Thanks in advance.
Answer: Try to get the value from row object instead of view object like $variables['row']
Comment: I can't vote up for you since i'm new on this Drupal board, but i thumb up ! Using row IS the solution. I should have tried it . But when dpm($variables), the row bloc showed infinite recursion. I just had to dpm($variables['row']); and all is bright now. Thank you
Comment: In any case, i can display what i need thanks to your answer, but just for my education : the way i get it, is it correct ? using mymodule_theme() to register the template hook and then use the hook preprocess function to change the variable ? Thanks anyway
Comment: Yes, It is correct.


Clear cairo text in gtk_window

Question: I'm have a trouble with a cairo text.
I write some lines in a gtk_window:
cr = gdk_cairo_create(window->window);
        cairo_set_source_rgb(cr, 255, 255, 255);
        cairo_select_font_face(cr, "Sans", CAIRO_FONT_SLANT_NORMAL, CAIRO_FONT_WEIGHT_NORMAL);
        cairo_set_font_size(cr, 14.0);

        cairo_move_to(cr, 90.0, 85.0);
        cairo_show_text(cr, "Terror");
        cairo_set_font_size(cr, 12.0);
        cairo_set_source_rgb(cr, 30, 254, 145);
        cairo_move_to(cr, 90.0, 105.0);
        cairo_show_text(cr, "Underdogs");
        cairo_move_to(cr, 90.0, 120.0);
        cairo_show_text(cr, "Disziplin");
        cairo_destroy(cr);

The problem is that this text should be dynamic, but if I call more than one time the function that writes the text, lines is overlapped.
Is there any method that flushes the previous text?
Thanks!
Answer: From the Cairo FAQ:

If you want to clear your surface to a uniform, opaque color then it
is quite straightforward:
/* Set surface to opaque color (r, g, b) */
cairo_set_source_rgb (cr, r, g, b);
cairo_paint (cr);

However, what if you want to clear the surface to something other than
an opaque color. Simply modifying the above code to use
cairo_set_source_rgba (cr, 0, 0, 0, 0); will not work since Cairo
uses the OVER compositing operator by default, and blending something
entirely transparent OVER something else has no effect at all.
Instead, you can use the SOURCE operator which copies both color and
alpha values directly from the source to the destination instead of
blending:
/* Set surface to translucent color (r, g, b, a) */
cairo_set_source_rgba (cr, r, g, b, a);
cairo_set_operator (cr, CAIRO_OPERATOR_SOURCE);
cairo_paint (cr);

Of course, you won't want to forget to set the default
CAIRO_OPERATOR_OVER again when you're finished. And the most
convenient habit for doing that is to just use
cairo_save/cairo_restore around the whole block:
/* Set surface to translucent color (r, g, b, a) without disturbing graphics state. */
cairo_save (cr);
cairo_set_source_rgba (cr, r, g, b, a);
cairo_set_operator (cr, CAIRO_OPERATOR_SOURCE);
cairo_paint (cr);
cairo_restore (cr);

Finally, to clear a surface to all transparent, one could simply use
CAIRO_OPERATOR_CLEAR instead of CAIRO_OPERATOR_SOURCE, in which case
the call to cairo_set_source_rgba would not be needed at all, (the
CLEAR operator always sets the destination to 0 in every channel
regardless of what the source pattern contains). But the above
approach with CAIRO_OPERATOR_SOURCE is a more general way to clear the
surface since it allows for "clearing" to a translucent color such as
50% red rather than just clearing to entirely transparent.
Answer: You have to overwrite the text with the background color :)
Comment: But this is ugly. I thought in clearing the "surface". Overwrite the text with the background color implies reload my theme every time that i want to write another text.

Clear cairo text in gtk_window


When to use a normal approximation of a Bernoulli distribution

Question: What is a practical example where one would want to use a normal approximation of a binomial distribution over using properties of the binomial distribution itself?
I.e if I already know that the process can be modelled as a Bernoulli distribution, then in what circumstance would I want to use a normal approximation ? I already know the formula to find the probability of x successes in n trials, so why do I need a normal approximation ?
Comment: I use this approximation all the time when I'm not at a computer: I might be having a conversation with someone, for instance, and need a fast way to mentally estimate some binomial probabilities. When $n$ is much larger than $6$ or so, I'm just not that good at performing the sums--or, equivalently, evaluating the corresponding incomplete Beta integrals--needed to compute Binomial probabilities in my head. I don't know whether having this facility with mental approximations would constitute a "practical example" for you, though.
Comment: There have been occasions when I've needed to compute binomial probabilities for extremely large $n$ (tens of thousands, at least). In this situation, even with reasonably small $p$, the normal approximation can often be used with very little error. I also sometimes need to get an approximate calculation of binomial probabilities 'on the fly' for one reason or another.
Answer: If you had $X$ with a binomial distribution with parameters $n_x$ and $p_x$ and independently $Y$ with a binomial distribution with parameters $n_y$ and $p_y$, then you know that the distribution of $X+Y$ has mean $n_xp_x+n_yp_y$ and variance $n_xp_x(1-p_x)+n_yp_y(1-p_y)$, but you do not know the distribution in most cases.
The Normal distribution with continuity correction may provide a reasonable approximation for $X+Y$, at least away from the tails.  Take the sum of several binomially distributed random variables, and it may be the only alternative to simulation.
Comment: Well, perhaps not the *only* alternative, since 'exact' numerical convolution is doable, but in some cases the normal approximation is a substantially more convenient approach and often quite sufficient.
Comment: @Victor - I used the MathJax version of TeX.  See http://meta.math.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference for some tips
Comment: @Henry: Can you tell me how you got those beautifully formatted formulas. Quite a work of art!


Good form to remove outliers?

Question: I'm working on statistics for software builds. I have data for each build on pass/fail and elapsed time and we generate ~200 of these/week.
The success rate is easy to aggregate, I can say that 45% passed any given week. But I'd like to aggregate elapsed time as well, and I want to make sure I don't misrepresent the data too badly. Figured I'd better ask the pros :-)
Say I have 10 durations. They represent both pass and fail cases. Some builds fail immediately, which makes duration unusually short. Some hang during testing and eventually time out, causing very long durations. We build different products, so even successful builds vary between 90 seconds and 4 hours.
I might get a set like this:
[50, 7812, 3014, 13400, 21011, 155, 60, 8993, 8378, 9100]

My first approach was to get the median time by sorting the set and picking the mid-value, in this case 7812 (I didn't bother with the arithmetic mean for even-numbered sets.)
Unfortunately, this seems to generate a lot of variation, since I only pick out one given value. So if I were to trend this value it would bounce around between 5000-10000 seconds depending on which build was at the median.
So to smooth this out, I tried another approach -- remove outliers and then calculate a mean over the remaining values. I decided to split it into tertiles and work only on the middle one:
[50, 60, 155, 3014, 7812, 8378, 8993, 9100, 13400, 21011] ->
[50, 60, 155], [3014, 7812, 8378, 8993], [9100, 13400, 21011] ->
[3014, 7812, 8378, 8993]

The reason this seems better to me is two-fold:

We don't want any action on the faster builds, they're already fine
The longest builds are likely timeout-induced, and will always be there. We have other mechanisms to detect those

So it seems to me that this is the data I'm looking for, but I'm worried that I've achieved smoothness by removing, well, truth.
Is this controversial? Is the method sane?
Thanks!
Comment: Well it looks to me that you have three groups in your data: (i) builds that build; (ii) builds that fail (and you say they tend to fail rather quickly), and (iii) builds that hang up (or nearly so) -- and that's probably the main if not the only group you want to take action upon. The aggregate measure of time may not be of great use; but something like the 10th longest build, or the 10th highest percentile of the distribution of build times, might be a better measure of what's at the extreme of the distribution that you care about. That's roughly what EPA uses in their pollution monitoring.
Comment: Thank you! Actually, no. The group we want to act on is the normal case; the builds that build. Collectively we do that ~500 times/day, and if we can optimize that case we save massive amounts of time. The others are truly outliers -- the fast ones are either the lucky few who maintain small products or immediate failures. The slow ones are typically hanging or running on unusually loaded machines. Both ends are exceptional.
Comment: is there any way for you to classify the builds upfront? Or at least do you have any information you can use to classify them? Lumping non-homogenous things together is rarely a good idea, especially if you have a way to tease them apart.
Comment: Not currently, no. But it might be something to look out for in the future. I see what you're saying about lumping things together.
Comment: You still have not said *why* you want to have your measure of elapsed time. Do you need to estimate the total machine time you are paying for? Do you need to estimate how many trips to the coffee machine you'd be able to make? What is the action that you will likely take if you knew the times?
Comment: Also, if you have heterogeneous products that you build, then bouncing around is natural, and you should not try to get rid of it. If you have a measure of complexity of a given project (# of files, # of lines of code, # of routines, etc.), then you may be interested in elapsed time normalized by complexity, which may be more stable. If you want to make it really stable and flat over time, then you won't be able to learn when you need to take your actions.
Comment: @StasK: thanks for your comments, this is valuable input. The action is already known: many of these builds take waaaay too long, and we should work on making them faster. I want to use the aggregate measure to see if things are getting better or worse.
Comment: And yes, ideally I would probably do this by product, but the source data doesn't maintain that information so I cheat based on what I know about the distribution. This might change over time, of course, and I may have to re-think.
Answer: What you're doing is known as a trimmed mean.
As you have done, it's common to trim the same proportion from each side (the trimming proportion).
You can trim anything between 0% (an ordinary mean) up to (almost) 50% (which gives the median). Your example has 30% trimmed from each end.
See this answer and the relevant
Wikipedia article.
[Edit: See Nick Cox's excellent discussion on this topic.]
It's quite a reasonable, somewhat robust location estimator. It's generally considered more suitable for near-symmetric distributions than highly skewed ones, but if it suits your purpose* there's no reason not to use it. How much is best to trim depends on the kinds of distribution you have and the properties you seek.
* It's not completely clear what you want to estimate here.
There are a large number of other robust approaches to summarizing the 'center' of distributions, some of which you might also find useful. (e.g. M-estimators might have some use for you, perhaps)
[If you need a corresponding measure of variability to go with your trimmed mean, a Winsorized standard deviation might be of some use to you (essentially, when calculating the s.d., replace the values you would cut off when trimming with the most extreme values you didn't cut off).]
Comment: I haven't actually checked the typical shape of my distribution, I think it varies week-by-week depending on where people make changes. It might in fact be highly skewed.
Comment: Thanks for putting a name on my hack-job, btw. It inspires some confidence :-)
Answer: Your approach makes sense to me, taking your goal into account. It's simple, it's straightforward, it gets the job done, and you likely don't want to write a scientific paper about it.
One thing that one should always do in dealing with outliers is to understand them, and you already do a great job about this. So possible ways of improving your approach would be: can you use info on which builds are hanging? You mention that you have "other mechanisms to detect those" - can you detect them and then remove only those from the sample?
Otherwise, if you have more data, you could think about removing not tertiles, but quintiles... but at some point, this will likely not make much of a difference.
Comment: When I say "other" mechanisms, I mean _completely different_ outside of this data set, so I can't make decisions based on it here.

We're aggregating data daily, and we only get ~50 builds per day, so I think quintiles might yield too little data, but thanks for the suggestion, I can experiment with it!
Answer: Yet another method is to compute the median of all pairwise averages or do bootstrapping.
Update:
The median of all pairwise avarages is called the Hodges–Lehmann estimator.  This estimator has usually a high efficiency. This encyclopedia entry by Scott L. Hershberger says:

While both the median and Hodges-Lehmann estimator are both preferable to the sample mean for nonsymmetric distributions, the Hodges-Lehmann estimator has larger asymptotic relative efficiency with respect to the mean than the median

Bootstrapping may be less relevant and more computational intensive, but you could take a small random sample of the data with replacement and compute the mean of that subsample, do it many times and compute the median of all the means.
In both cases you do no longer have to pick a value among the values of your data (when you compute the ordinary median), but instead you pick among many averages from subsets of the data.
Comment: Can you describe advantages and disadvantages of these methods? A one-line answer is an insufficient one.
Comment: I have tried to make an update with more explanation
Comment: Both pairwise averages and bootstrapping seem to involve a number of recalculations over the whole dataset. The sample is generally pretty small (<500 values), so it's probably not a problem, but it does seem more complicated. Good to know there are more approaches to experiment with if the trimmed mean turns out to be too blunt. Thanks!
Answer: Seems reasonable what you are doing : just for information I use the following process quite often for a similar purpose: but I'm only ever really interested in the Upper Outliers.
Calculate five number summary: Min, Q1, Median, Q3, Max.
Calculate Interquartile Range : Q3-Q1.
Set your outlier 'fences' at Q1-IQR*X, and Q3+IQR*X: where a reasonable value of 'X' is 1.5.
Using Excel and your figures the above (using 1.5 for 'X' **) yields one upper outlier :21011
MIN 50
Q1  3014
MEDIAN  8095
Q3  9073.25
MAX 21011
IQR 6059.25
UPPER FENCE 18162.125
LOWER FENCE -6074.875

So the lower fence here isn't useful or realistic for your example in fact: which backs up the point made by the other post regarding the importance of understanding the meaning of your specific data.
(**Found one citation for the '1.5' rule: I'm not saying it is authoritative, but is seems a reasonable starting point to me : http://statistics.about.com/od/Descriptive-Statistics/a/What-Is-The-Interquartile-Range-Rule.htm)
You could also decide (perhaps) just to use the data points that fall within the IQR itself  : this seems to yield sensible results (in that the membership to your method is very similar).
using the same data, this would place the following data points in the 'area of interest':
7812
3014
13400
21011
8993
8378
9100

On a Boxplot : these points would all fall within the box-part (rather than the whiskers-part) of the diagram.
At can be seen that this list includes some items not in your original list (the longer running builds); I can't say whether one list is more accurate in any way. (again, comes down to understanding your dataset).
Comment: I can't really say whether either method is better or not: I suggested this based on what I have read in stats books /sites. One thing (I think) the method adds is that allows you to adjust the 'fences' to whatever you feel is suitable (adjusting the 1.5 factor) ; where just taking the middle third might be more susceptible to including a potentially high outlier (which arguably could be better classified outside of the fence).....but I cant' say that for sure. One other things about using Quartiles, is that the 5-number summary is quite well understood and commonly used.
Comment: Thanks for the added detail! I do this in Python, so I already have a function where I partition the dataset into N parts and then pull out the middle part. It's a one-character change to make it 5 or 7 partitions instead. But your point is well taken, and it's good to see another common way of approaching this problem. Thanks again.
Comment: sounds fine to me : I will add one more thing to emphasize about using quartiles and fences (rather than having variable partitions) - is that they map straight onto boxplots: http://en.wikipedia.org/wiki/Box_plot which allow (amongst other things) a standard way of comparing different distributions graphically.
Comment: Thanks, this seems very close in principle to what I'm already doing. In what ways might this method be better than just partitioning the data set?

Good form to remove outliers?


Imprimira na tela uma mensagem ativada após uma validação

Question: Eu fiz uma validação de email e cpf para ver se já estão cadastrados, existe uma forma melhor para escrever a mensagem na variável $menssage? Do que fazer a validação um por um?
if($emailRetornado !== null || $cpfRetornado !== null){
    if($emailRetornado !== null && $cpfRetornado !== null){
        $menssage = "EMAIL e CPF já cadastrados!";
    }
    else{
     //Ou o email foi retornado como não valido ou o cpf
         if($emailRetornado !== null){
             $menssage = "EMAIL já cadastrado!";
         }
         if($cpfRetornado !== null){
             $menssage = "CPF já cadastrado!";
         }
     }
}
echo $menssage;

Answer: Partindo de que $emailRetornado e $cpfRetornado venha do banco de dados ou seja já existe um cadastro anterior dessa pessoa.
Mude a lógica para identificar qual dos campos já tem algum valor, com um if simples para cada, utilize empty() para verificar se valor nas variáveis. $erros é um array que possui as mensagens dos erros que ocorreram, então se ela for vazia o cadastro da pessoa ainda não existe, do contrário cancele o processo e exiba a mensagem de erro com um implode() por exemplo.
$emailRetornado = 'firstname.lastname@example.com';
$cpfRetornado =  '';

$erros = [];
if(!empty($emailRetornado)) $erros[] = 'EMAIL já cadastrado!';
if(!empty($cpfRetornado)) $erros[] = 'CPF já cadastrado!';

if(!empty($erros)){
    echo 'Problemas no cadastros
'. implode('
', $erros);
} else {
    //faça o tratamento do fluxo de sucesso aqui<<
}

Exemplo - ideone


issues with calculating Median

Question: Here is my data

10 A
12 A
14 B
15 B
15 C
11 D
12 D
10 B
11 A

I want to select A and C from Column B and then calculate the median based on column A.
I have used this function
=MEDIAN(IF(B1:B9="A",B1:B9="C",A1:A9))
But I got a wrong Number. Can we solve this issues? Many thanks for your help.
Comment: you have three answers below.  If you used one of them then please mark that one as correct.  It is something only you can do.  It will close this question as answered.  Click on the green check mark by the one answer to mark it as correct.
Answer: Try this, entered as an array formula by holding down ctrl+shift while you hit Enter
=MEDIAN(IF($B$1:$B$10={"A","C"},$A$1:$A$10))

The IF function returns an array of either the appropriate value in A1:A10, or FALSE.  And the MEDIAN function will ignore the logical values, since they are produced by a function, and not manually entered.
Here is a screen shot showing the data and the result.  You can see the formula in the formula bar: (Note that the braces {...} around the formula are NOT added manually.  They will be added by Excel when you confirm the formula with ctrl+shift+enter.  With regard to the array constant, however, those braces you do type in manually.
Comment: Nice.  Moments after I express my doubt that it's possible.  This is elegant, and seems to work when I try it
Comment: @Baronz `MEDIAN` is a bit odd.  It will ignore logical values if they are produced by a function, as does the `IF` function in my solution.  However, if you manually enter a logical value, it will use it.
Comment: No, that doesn't work.  When I change row A6 to 500, your median changes, but mine stays the same.  Yours is still counting the rows he is trying to exclude.
Comment: @Baronz When I change A6 to 500, my median remains 11.5
Comment: Ron, It seems it work, But I got the median in C1:C9, Can we see it in a cell only
Comment: I don't understand what you have done.  If I enter the formula in, for example, C1, that is where I see the result.  Did you enter the formula in multiple cells?  If so, why?
Comment: @Baronz  Did you array-enter the formula?  I don't see the braces `{...}` around the formula in the formula bar.
Comment: @USER2313456 You may not have been flagged with my last response.  I will add a screenshot showing the data and my formula, so you can see it showing up in only a single cell.
Comment: @Baronz  I don't understand how you are getting a result of `12` in that screenshot.  Can you upload the workbook so I can look at it more closely?
Comment: @RonRosenfeld - in that screenshot, F5 **could** have a custom number format of `0` but I don't get the lack of array formula **{** and **}** either unless F2 had been tapped and the cursor is in the formula bar (with allow edit directly in cells turned off) but that *should* show the precedents with colored borders.
Comment: @Jeeped  My thoughts also.  That's why I would like to examine the workbook, to see what's going on.  Although, my recollection is that with older versions of Excel (e.g 2007-), the precedents did not get highlighted with colored borders.
Answer: Try this aggregate Function:
=AGGREGATE(17,6,$A$1:$A$500/(($B$1:$B$500 = "A")+($B$1:$B$500 = "C")),2)

This is entered as normal formula. It is a non CSE array formula.
Comment: Thanks, Scott.  Did not see that in the documentation.  Recently upgraded from 2007 to 2016 and `AGGREGATE` is new to me.
Comment: I understand that the 2nd quartile is the Median, but when I try to use the Median function directly (argument #12), I get a #VALUE! error.  Can you explain that? `=AGGREGATE(12,6,$A$1:$A$500/(($B$1:$B$500 = "A")+($B$1:$B$500 = "C")))`
Comment: @RonRosenfeld that is because in the first criteria, anything under 14 cannot use arrays as the third criteria, but has to use direct references.  That is why it was needed to use 17.
Answer: I don't think you can do it all in one equation.  I think you need a new column to create an intermediate value, then solve it.

I put this equation in column C (and dragged it down the column):
=IF(OR(B1="A",B1="B"),A1,"")

And then I tested the values by calculating the Mean (average), Median (middle number), and Mode (most common value).  Because there are 6 values, Excel takes the middle of the two.
Here are my equations for column F:
=AVERAGE(C1:C9)
=MEDIAN(C1:C9)
=MODE(C1:C19)

Here is the Microsoft link talking about why the "Median" may be a value between two on the list:
https://support.office.com/en-us/article/MEDIAN-function-D0916313-4753-414C-8537-CE85BDD967D2
Comment: I knew this method, but I am interested to run it on function. Is it possible to run it in a function
Comment: I doubt there is a method without some serious excel trickery, because you need the "tally" of values too.  Your original set has 9 values, but you want to do a median only only 6 of them.

issues with calculating Median


Is financial market commentary off topic?

Question: See this question.
When a stock price shifts suddenly there is probably some underlying reason, and frequently the price shift is the result of some new information - a technological breakthrough, a government deal, etc.
One might argue that in the answer "The company can expect higher profits from now on because of XY" the economic reasoning is all in the part before XY, therefore revealing XY is not really economics. (Unless XY itself is a complicated economic phenomenon, e.g., a change in market structure.)
One might also argue that economics based explanations are always/usually on-topic.
Are questions that ask for financial market commentary off-topic?
Comment: Will accept the most upvoted answer on Aug 21. (Hopefully I will not forget.)
Answer: Not sure if this is an answer, or another question. To the extent it is an answer, I argue that they are very rarely on topic.
What's the value-added of answering a question as to why a particular share changed in price on a particular day? Will that answer ever be useful for anyone else in the future? Maybe a big financial market crash might be of future interest (or negative oil prices), but run-of-the-mill share volatility?
One can debate market efficiency, but it seems pretty safe to argue that there are no simple rules to predict market changes - otherwise, people would be using them to make big bucks. Given that backdrop, how can price changes be "explained"?
A related issue: there are dozens of questions being posted that are all of the same format "what did some random financial commentator mean by X?" Why would those questions ever be useful to future readers?
Update:
Based on a comment by Giskard, I think the key criterion would be "of potential interest to future readers". Vague, but it at least offers a guideline to people asking questions. Otherwise, questions are just being downvoted or closed on other grounds that are also being mis-applied.
Comment: I like your argument about future uselessness of an explanation of a specific share movement. I am not sure if the same applies to "what did some random financial commentator mean by X?" because it could be a regular (but perhaps less well-known) use of X, and then the answer is useful to people googling X.
Answer: I think there is also another issue which was not addressed by Brian's +1 answer and that is that save for some special circumstances any contemporary stock market commentary is highly opinion based.
For example, if tomorrow government announces some new Covid19 stimulus and stock market raises by $3\%$ how can anyone say what is the the reason why that happened without doing some empirical study about the event?
For all we know the $3\%$ increase might be just due to random variation. After all this is why in financial economics people always do event studies when they look whether the there really was significant change in abnormal returns.
Moreover, events often dont happen individually. Lets say that government again announces covid stimulus but this time stock market falls. Is it because the stimulus was signal the crisis is worse than people expected? Is it because the stimulus itself is not perceived credible because lets say there is an election coming up and some anti-stimulus candidate has high chances of winning and undoing it?
The problem is not that the questions would be inherently opinion based as there will be eventually some non-opinion based answer once someone actually puts an effort to research empirically the issue.  Hence, for events that are not contemporary there actually might be some solid studies out there about their impact on stock market and hence the question might be answered in objective fashion. Therefore, we should probably not lump all of these questions into same category either and rather consider off topic commentary that is about unfolding events.
Comment: @AdamBailey yes sorry for that - I corrected it - my grammar is so terrible that the proofreading company on our university campus must be experiencing the biggest economic boom in their history since I entered graduate school :p
Comment: "consider of topic" in the last line.  Presumably you meant "consider off topic"?
Answer: I believe that at some point the community decided that this site was to be primarily geared towards "academic economics" like that found in academic journals coming out of a research university (e.g. QJE or JPE), the federal reserve banks, or similar. Market commentary like the kind in the referenced question would never be published in these kinds of outlets. I would say the question is off-topic. I believe a good criterion would be to ask if the question is one that resembles this kind of research.
I'd argue that we want to encourage users that do this kind of work to join our community. One way to do that is to strictly disallow market commentary and other punditry like the one on the referenced question.


How do I query a Domain Controlers NTP service from a linux box?

Question: I need to confirm that a Domain Controller is acting as a NTP time server for non windows devices and servers. I figure there must be a command in linux that will query an NTP server and see if it is accessible and serving the right time.
Answer: As mentioned ntpdate is a standard tool for requesting the time, and using it to set your local system.
If you have the full NTP daemon installed, you could update your ntp.conf restart the daemon, and then query the status of your local daemon with ntpq -p.
If you want to continuously monitor NTP, then https://www.monitoring-plugins.org/ includes check commands for monitoring various aspects of NTP check_ntp, check_ntp_peer, and check_ntp_time.  This plugin package is available on most linux distros.  Though it may go by the older name nagios-plugins.
Answer: Make sure you have the ntp package installed. You can then run the following as root
ntpdate -q ip.of.server

Comment: This would set the time on the querying machine - probably not an intended outcome.
Comment: this did what I wanted.  I just wanted to prove that a non windows client could query time.  I just did it on a test linux box


UISegmentedControl With AutoLayout Misaligns Title

Question: I have a custom UITableViewCell that has a label on the left side a UISegmentedControl on the right. I'm just getting used to using Auto Layout in code, and this is what I have in my custom cell (using UIView+AutoLayout):
-(void)updateConstraints
{
    self.titleLabel.translatesAutoresizingMaskIntoConstraints = NO;
    self.segmentedControl.translatesAutoresizingMaskIntoConstraints = NO;

    [self.titleLabel pinToSuperviewEdges:JRTViewPinLeftEdge inset:DB_AUTOLAYOUT_DEFAULT_INSET];
    [self.titleLabel centerInContainerOnAxis:NSLayoutAttributeCenterY];
    [self.segmentedControl pinToSuperviewEdges:JRTViewPinRightEdge inset:DB_AUTOLAYOUT_DEFAULT_INSET];
    [self.segmentedControl pinAttribute:NSLayoutAttributeBaseline
                            toAttribute:NSLayoutAttributeBaseline
                                 ofItem:self.titleLabel];

    [super updateConstraints];
}

My problem is that the segmented control's first title is always misaligned:
This is what it looks like on iOS 6:
And on iOS 7:
So first question is: How do I fix this?
Other, tangential question: Am I doing the right thing by putting auto layout code in updateConstraints or should I just apply the constraints once?
Comment: To answer your second question, you shouldn't be putting the constraints in `updateConstraints` unless you put a `BOOL` check around if they've been added already, `viewDidLoad`, or the `init` method would be a better place. You should also add `[self.segmentedControl pinAttribute:NSLayoutAttributeLeft toAttribute:NSLayoutAttributeRight ofItem:self.titleLabel];` too, so the title is to the left of the control (in case they can become larger)
Comment: Hmm... seems like the tangential question was more important. Just taking the constraints out of `updateConstraints` fixed it. When would you use `updateConstraints`? I've read the doc on it but it's not very clear.
Answer: In short from UIView.h
If you do all of your constraint set up in -updateConstraints, you might never even receive updateConstraints if no one makes a constraint.  To fix this chicken and egg problem, override this method to return YES.
+ (BOOL)requiresConstraintBasedLayout {
        return YES;
}


Difference Between Discrete Time Proportional Hazards and Logistic Regression

Question: My data consists of one row per person, per month that person was "exposed" to an event. So the month is the discrete time and the row corresponds to one "person-month".
There are a few independent variables, most of which are time-independent: Age at enrolment, Region, Type of individual. The time period (month) is obviously also a variable. The dependent variable is whether or not the event occurred in that month. If the event doesn't occur in a 48-month window from enrolment, every row has a zero.
Clarification based on a comment below: there are only as many rows as # of months until the event. There are only 48 rows for the individuals who reach month 48 without the event occurring. Also, the event could technically happen after month 48, but the probability of that happening is really, really small, so the data is censored for those folks, but not in a meaningful way. I can essentially treat the 48th month as a hard limit.
The event can only occur once. (i.e. the individual couldn't experience the event then start over, so there can't be two clusters of the same individual.)
I am modeling this with logistic regression and getting good results. But, do I need to be worried about the fact that the rows are not completely indpendent? And is this what the difference is between straight-up logistic regression and discrete time proportional hazards modeling using the logit?
I read about using a generalized linear mixed model instead of a standard GLM, but can't find a clear description of why that would make a difference. (or exactly what time as a random effect really means.) I also found descriptions where a standard logistic regression model was used.
Also, in my specific case, I'm not sure there is any real theoretical dependence row-to-row, because none of the factors are affected by the individual.
So, any insight would be appreciated.
Answer: [I'm rebooting my answer based on our previous discussion and new insights]

I am modeling this with logistic regression and getting good results. But, do I need to be worried about the fact that the rows are not completely indpendent? And is this what the difference is between straight-up logistic regression and discrete time proportional hazards modeling using the logit?

You don't have to worry about the independence of the rows here, because this analysis has an alternate statistical interpretation which doesn't have this issue. Instead of standard logistic regression, you can think of what you're doing as using a logistic regression solver to fit a discrete time logit PH model.
This is possible because the likelihood function for logistic regression is identical to that for the PH model if the data is input the way you specified (where each subject has rows until the event occurs or we hit 48 months). So you can use the logistic solver to fit the PH model and get perfectly valid fit coefficients and standard errors. The only difference between the two approaches arises when you need to interpret the results or predict something.
A similar phenomenon occurs in continuous time, where a Poisson GLM solver can be used to fit a continuous time proportional hazards model. See here for more info.

I read about using a generalized linear mixed model instead of a standard GLM, but can't find a clear description of why that would make a difference. (or exactly what time as a random effect really means.) I also found descriptions where a standard logistic regression model was used.

Mixed models would not be useful for your situation - you might use that if you had a more complex longitudinal dataset and wanted to account for the correlation of multiple events for one individual. In this case the individual's identity (or membership in some group) would be the random effect. Time would not be the random effect here. In any case, you only have one event so you don't need mixed models.
Comment: That's interesting. So if I understand, the mixed model (something I know very little about) is accounting for the fact that an individual's propensity to have the target event occur is not independent across time. (e.g. If you have a stroke, you're more likely to have another.) Because I only have an event once, that's not an issue. This might explain why insurance people use this kind of thing to model deaths...

Thanks for the Poisson link - I will check it out.