how to robustly identify a floor trendline ignoring outliers?

Question: I've got the following sets of data (x and y scales on each chart are identical):

The eye picks out an upward-sloping floor trendline on each chart that runs upward from left to right, hugging the bottom of the bulk of blue dots, with a few outliers below it. And that trendline is different for each chart.
That's easy enough for the eye to pick out.  But is there a robust way to do it algorithmically?
I've considered writing an objective function that calculates the residuals from a trend line, discards (say) 1% of points that are further below the trend line, and then weights residuals so that points above the line all contribute very little to the objective function, and points below the line contribute a lot, to get the line to hug the bottom of the bulk. And then find the trendline that minimises that objective function.
Are there more robust methods?
Answer: I think linear quantile regression would be close to what you want. This fits a line so that the predicted value for each x value is close to the chosen quantile of the response conditional on x.
Here's an R package:
http://cran.r-project.org/web/packages/quantreg/index.html
For example, you could try a 1% quantile, and see if that avoids the outliers. You can adjust the quantile you choose until it looks about right.
If you want to be more principled about deciding where the outliers start, I think you'll need to make some more assumptions about your data distribution.
Comment: In principle and in practice linear quantile regression could mean predictors other than straight x, e.g. cubic splines or fractional polynomials in x.
Comment: +1 This was my first thought as well. It seems to me that this is fairly principled.
Comment: Well said from amother DavidR
Comment: Thanks, linear quantile regression does a pretty decent job. I found the MatLab quantreg package, and that's given me something pretty plausible.
Comment: Yes, I agree @NickCox... you can just feed transformed x's into your quantile regression.  If you have enough data, you can also pretty easily do a "poor man's" non-parametric quantile regression: bin up the x's into groups, as though you were making a histogram, and find the quantile you're looking for in each bin.  Then you get a piecewise constant nonparametric quantile regression line.
Answer: Is there only 1 trend line ? Probably not . You have outlying points below the "visual trend line at the bottom" . How will these be "ignored" so as to capture the dominant floor trend line that the eye sees and not be influenced by them. To detect tehm and reduce their influence one would want to simultaneously detect BOTH trend line(s) and pulses that are inconsistent with the trend(s). If you can reduce your xy observations as you said and then post the reduced set , I might take a shot at this using the only piece of commercially avaialable software that I know that deals with trend detection while considering ARIMA structure and pulses. As far as I know nothing free is available and of course the heuristics to duplicate the human eye are not disclosable.
Answer: perhaps try running this custom-built code in the R language..if you've never used R, check http://twotorials.com/ to get started ;)
<code># create eight sets of a thousand random x values
x1 <- rnorm( 1000 , mean = 1 )
x2 <- rnorm( 1000 , mean = 2 )
x3 <- rnorm( 1000 , mean = 3 )
x4 <- rnorm( 1000 , mean = 4 )
x5 <- rnorm( 1000 , mean = 5 )
x6 <- rnorm( 1000 , mean = 1 )
x7 <- rnorm( 1000 , mean = 1 )
x8 <- rnorm( 1000 , mean = 3 )

# create eight sets of a thousand random y values
y1 <- rnorm( 1000 , mean = 1 )
y2 <- rnorm( 1000 , mean = 2 )
y3 <- rnorm( 1000 , mean = 3 )
y4 <- rnorm( 1000 , mean = 4 )
y5 <- rnorm( 1000 , mean = 5 )
y6 <- rnorm( 1000 , mean = 5 )
y7 <- rnorm( 1000 , mean = 3 )
y8 <- rnorm( 1000 , mean = 5 )

# combine all of these values into two vectors
x <- c( x1 , x2 , x3 , x4 , x5 , x6 , x7 , x8 )
y <- c( y1 , y2 , y3, y4 , y5 , y6 , y7 , y8 )

# this distribution looks like your example distribution
plot( x , y )

# along the x axis, figure out some reasonable intervals to "bin" the data

# let's say you want one bin per 100 points..
num.bins <- length( x ) / 100

# figure out what quantiles to cut your bins at
quantile.probs <- seq( 0 , 1 , length.out = num.bins )

# slice up your `x` data into that many equal bins
bin.cutpoints <- quantile( x , quantile.probs )

# now let's look at just the first bin #

# positions within the first bin
first.bin <- which( bin.cutpoints [ 1 ] <= x & x < bin.cutpoints [ 2 ] )

# x midpoint between first two cutpoints
first.midpoint <- as.numeric( bin.cutpoints [ 1 ] + ( bin.cutpoints [ 2 ] - bin.cutpoints [ 1 ] ) / 2 )

first.midpoint

# since you wanted to discard 1% of all points, choose the 1% quantile cutoff point
one.percent.cutoff <- round( quantile( 1:length( y[ first.bin ] ) , 0.01 ) )

# find the point at the edge of the first percentile within this bin
first.percentile <- sort( y[ first.bin ] )[ one.percent.cutoff ]

# and there's your `y` value
first.percentile

# create two empty vectors to start storing values
low.x <- NULL
low.y <- NULL

# repeat this process for all bins:
for ( i in 2:length( bin.cutpoints ) ){

    this.bin <- which( bin.cutpoints [ i - 1 ] <= x & x < bin.cutpoints [ i ] )

    this.midpoint <- as.numeric( bin.cutpoints [ i ] + ( bin.cutpoints [ i ] - bin.cutpoints [ i ] ) / 2 )

    low.x <- c( low.x , this.midpoint )

    # since you wanted to discard 1% of all points, choose the 1% quantile cutoff point
    one.percent.cutoff <- round( quantile( 1:length( y[ this.bin ] ) , 0.01 ) )

    # find the point at the edge of the first percentile within this bin
    first.percentile <- sort( y[ this.bin ] )[ one.percent.cutoff ]

    # and there's your `y` value
    first.percentile

    low.y <- c( low.y , first.percentile )
}

# plot your original points
plot( x , y , main = 'one bin per hundred points' )

# RE-plot the points that had the second-lowest y value within each "bin"
# so you can see exactly what line you're best-fitting
points( low.x , low.y , col = "red" , pch = 19 )

# draw your line of best fit
abline( lm( low.y ~ low.x ) )
</code>
here's the result..

notice it is sensitive to the size of each bin..
Comment: Interesting ! Does this distinguish multiple trend lines or does it assume 1 trend. How does it deal with the third row third column example from the OP. Do you have to manually ignore the anomalies after the visually obvious floor trend line ?
Comment: Thanks for this. Please add a disclosure about your relationship with the site you've linked to - otherwise, your answer risks being deleted as spam.
Comment: i anthony damico hereby disclose my relationship with twotorials.com.  also, linear quantile regression is the right answer ;)


Issue with syntax for javascript promise

Question: I am using pdfjs to read a pdf file and get its pages as images. After all the images are loaded, I need to call an ajax to send and get details from the server. The code for iterating pages in the pdf has been taken from here: https://ourcodeworld.com/articles/read/405/how-to-convert-pdf-to-text-extract-text-from-pdf-with-javascript
I am having problem writing the syntax for the promise that will call the ajax function after all the required details mentioned above has been fetched.
Here is my code:
getDataUrlsAndSizesFromPdf(file).then(proceedAndCheckOnServer(file));

const getDataUrlsAndSizesFromPdf = function(file) {
    PDFJS.disableWorker = true;
    fileReader = new FileReader();
    fileReader.readAsArrayBuffer(file);

    return new Promise(function(resolve, reject) {
        fileReader.onload = function(ev) {
            PDFJS.getDocument(fileReader.result).then(function (pdf) {
                var pdfDocument = pdf;
                var pagesPromises = [];

                for (var i = 0; i < pdf.pdfInfo.numPages; i++) {
                    var pageNum = i + 1;

                    pagesPromises.push(getImageUrl(pageNum, pdfDocument));
                }

                Promise.all(pagesPromises).then(function () {
                    console.log(pdfPagesInfo);

                    resolve();
                }, function () {
                    console.log('failed');

                    reject();
                });
            }, function (reason) {
                console.error(reason);
            });
        }
    });
}

function getImageUrl() {
    return new Promise(function (resolve, reject) {
        PDFDocumentInstance.getPage(pageNum).then(function (pdfPage) {
            var scale = 1;
            var viewport = pdfPage.getViewport(scale);

            var canvas = document.getElementById('dummy-canvas');
            var context = canvas.getContext('2d');
            canvas.height = viewport.height;
            canvas.width = viewport.width;

            var task = pdfPage.render({canvasContext: context, viewport: viewport})
            task.promise.then(function(){
                var sizesArr = {
                    height : viewport.height,
                    width : viewport.width
                }
                pdfPagesInfo.sizes[pageNum.toString()] = sizesArr
                pdfPagesInfo.images[pageNum.toString()] = canvas.toDataURL('image/jpeg');

                resolve();
            });
        });
    });
}

function proceedAndCheckOnServer() {
    ....
}

What I want is "proceedAndCheckOnServer()" to be executed when all the details have been fetched from "getImageUrl()". But presently the execution directly goes to "proceedAndCheckOnServer()" without waiting for the promise from "getDataUrlsAndSizesFromPdf" to be resolved. I am new to javascript promises. Please help me with the syntax.
Comment: Avoid the [`Promise` constructor antipattern](https://stackoverflow.com/q/23803743/1048572?What-is-the-promise-construction-antipattern-and-how-to-avoid-it)! (You only need a `new Promise` around the `fileReader.onload =`, like [here](https://stackoverflow.com/a/54575211/1048572) or [there](https://stackoverflow.com/a/33931307/1048572))
Answer: You are calling your function instead of using a callback function.
proceedAndCheckOnServer is invoked, and the result of that function is used as the parameter to then.
getDataUrlsAndSizesFromPdf(file).then(proceedAndCheckOnServer(file));

Try one of these:
getDataUrlsAndSizesFromPdf(file).then(()=>proceedAndCheckOnServer(file));

getDataUrlsAndSizesFromPdf(file).then(function(){ proceedAndCheckOnServer(file) });

Or resolve your getDataUrlsAndSizesFromPdf promise with file and use the function without () to pipeline the result.
getDataUrlsAndSizesFromPdf(file).then(proceedAndCheckOnServer);

Comment: My bad. I didn't notice it before.


Find all values for cos(i)

Question: In my Differential Equations class recently we have learned about Euler's Formula and Fourier Series. I am given the problem Find all values for cos(i) where i = sqrt(-1). There is a long list of similar problems, but I figure if I can get some help on one of them I can learn to do the rest.
If possible, could an answer show me not all the work, but maybe just show me where to start? I want to learn how to get the answers myself, not just be given answers.
TIA!
Comment: There is only one value for $\cos(i)$.  Indeed, $\cos$ is an entire function.  On the other hand, it is a good problem to find all values of $\arccos i$.
Comment: $$2\cos(x)=e^{ix}+e^{-ix}$$
Comment: @labbhattacharjee that is perfect, definitely all I needed! I appreciate it very much!
Answer: $$\cos(i)=\frac{e^{i^2}+e^{-i^2}}{2}=\frac{e^{-1}+e}{2}=\frac{1+e^2}{2e}$$
Comment: Would this be considered the most simplified? Becuase I know that `1/2e + e/2` would technically be the same thing.
Comment: It's the same. Then you choose :-)
Answer: Let $k \in \mathbb{Z}$. We have the relation$$\cos(\theta+2k\pi)=\frac{1}{2}\left[e^{i(\theta+2k\pi)}+e^{-i(\theta+2k\pi)} \right]$$ for all $k$. Now let $\theta=i$. Our expression becomes $$\frac{1}{2}\left[e^{i(i+2k\pi)}+e^{-i(i+2k\pi)} \right]$$ $$=\frac{1}{2}\left[e^{2k\pi i-1}+e^{-2k\pi i+1} \right]$$ $$=\frac{1}{2}\left[\frac{e^{2k\pi i}}{e}+e\cdot e^{-2k\pi i} \right]$$ Now use Euler's formula on each complex exponent inside the brackets. We will get $$\frac{1}{2}\left[\frac{e^{2k\pi i}}{e}+e\cdot e^{-2k\pi i} \right]=\frac{1}{2}\left[\frac{\cos(2k\pi)+i\sin(2k\pi)}{e}+e\cdot (\cos(-2k\pi)+i\sin(-2k\pi) )\right]$$ We know $\sin(\pm2k\pi)=0$ for all $k$ so this expression disappears from inside the large brackets. Similarly, we know $\cos(\pm2k\pi)=1$ for all $k$. Plugging this back in should leave us with a final result of $$\cos(i)=\frac{1}{2}\left[\frac{1+0}{e}+e\cdot (1+0 )\right] = \frac{1}{2} \left[\frac{1}{e}+e \right]=\frac{1+e^2}{2e}$$ Note: It is important that we let $k$ be arbitrary. This establishes there is precisely one value for $\cos(i)$ which was part of your question.
Comment: It isn't called complex analysis for nothing ;)
Comment: very complicate for a such an easy thing !
Comment: But complex analysis makes things easier, not harder ;-)
Comment: Fo' sho'. In my experience with complex, things can get pretty gnarly with the algebra (as I demonstrated above) but always reduces to an impossibly simple result. I see your answer was far more concise. Nicely done!
Answer: Too simple, has only one real value.
$\cos(i)= \cosh(i.i) = \cosh(-1)  = \cosh(1) =( e + 1/e)/2$

Find all values for cos(i)


Ajuda com um PIVOT ( Sql Server )

Question: Galera procurei muitos exemplos de Pivot mas não consegui entender... e simplesmente não estou conseguindo utilizar no meu select... o que acontece, estou tendo esse resultado :
+---------------------------------------------------------------------------------------------------+-------------------------------------------+
|  Controle     | Colonia     |    Nome    |  Matricula| QtaPessoa | Tipo Hospedagem                | NumeroVoucher | valorvoucher| Tipovoucher |
+---------------|-------------|------------|-----------|-----------|--------------------------------+---------------|-------------|-------------|
|  114539       | Campos      |   Cassio   |  1234567  | 2         | Associado a partir 12 anos     | 987654321     | 158,90      | Evento      |
|  114539       | Campos      |   Cassio   |  1234567  | 2         | Associado de 12 anos           | 123456789     | 100,00      | Promoçao    |
|  114539       | Campos      |   Cassio   |  1234567  | 3         | Associado de 7 a 11 anos       | 123456789     | 100,00      | Promoçao    |
+---------------------------------------------------------------------------------------------------+-------------------------------------------+

E gostaria de ter Esse resultado
+--------------------------------------------------------------------------------------------------------------------++-------------------------------------------+
|  Controle| Colonia| Nome |  Matricula|| Associado a partir 12 anos| Associado de 12 anos| Associado de 7 a 11 anos || NumeroVoucher | valorvoucher| Tipovoucher |
+----------|--------|------|-----------||----------------------------------------------------------------------------++---------------|-------------|-------------|
|  114539  | Campos |Cassio|  1234567  ||             2             |       NULL          |         NULL           | 987654321      | 158,90      | Evento      |
|  114539  | Campos |Cassio|  1234567  ||             NULL          |       2             |         3                  | 123456789      | 100,00      | Promoçao    |
+-----------------------------------------------------------------------------------------------------------------------------------------------------------------+

Meu select seria
SELECT distinct
    a.idEmpregadoReserva as Controle
    ,(select EmpresaAplicativo from tbEmpresaAplicativo where tbEmpresaAplicativo.idEmpresaAplicativo = c.idEmpresaAplicativo) Colonia
    ,d.Nome
    ,d.Matricula
    ,a.NumeroDocumento as [Numero Voucher]
    ,e.ValorVoucher
    ,f.TipoVoucher
    ,(select tipoformapagto from tbHPG_TipoFormaPagto where tbHPG_TipoFormaPagto.idTipoFormaPagto = a.idTipoFormaPagto) [Forma Pagamento]
  FROM [APCEF].[dbo].[tbHPG_EmpregadoReserva_Financeiro] a join tbHPG_EmpregadoReserva_Reserva b on a.idEmpregadoReserva = b.idEmpregadoReserva
   join tbHPG_Reserva c on b.idReserva = c.idReserva join tbEmpregado d on c.idEmpregado = d.idEmpregado join tbEmpregadoVoucher e
    on a.NumeroDocumento = e.idEmpregadoVoucher
    join tbTipoVoucher f on e.idTipoVoucher = f.idTipoVoucher
  where c.DataEntrada between '2019-01-23' and '2019-01-27' and (c.idEmpresaAplicativo = 4 or c.idEmpresaAplicativo = 5)
  and a.idTipoFormaPagto = 1

Tentei de varias maneiras mas como tem muito join de inumeras tabelas estou me perdendo.
Comment: É `MySQL` ou `SQL Server`? Os valores são fixos ou variáveis? Você não adicionou a estrutura das tabelas e deu poucas informações que possibilitem a resposta. Tente simplificar sua pergunta de forma que seja fácil encontrar a raiz do seu problema e propor uma solução. Da forma como sua pergunta foi feita é difícil fazer a resposta útil para outros usuários
Comment: Utilizo 'SQL SERVER', os valores são fixos,  o meu maior problema seria transformar essas linhas "tipo hospedagem" em colunas evitando que crie varias linhas por conta da Quantidade de pessoas e o tipo de hospedagem,

Basicamente seria,   1 quarto  pode ter varios tipos de hospedes e eu gostaria de deixar tudo junto a mesma hospedagem e voucher.

obs: Sorack você é o cara curto muito seu trampo em sql aqui no stack aprendi muito do 0 com vc ajudando a galera xD,
Answer: Você não informou corretamente qual o SGBD utilizado, não informou a estrutura das tabelas e não disse se os tipos variam ou se são fixos. Utilizei a estrutura a seguir para MySQL porém irá funcionar também para SQL Server considerando que os tipos sejam fixos:
CREATE TABLE reserva (
  controle   INTEGER,
  quantidade INTEGER,
  tipo       VARCHAR(100),
  valor      NUMERIC(15, 2),
  voucher    VARCHAR(100)
);

INSERT INTO reserva(controle, quantidade, tipo, valor, voucher) VALUES
(114539, 2, 'Associado a partir 12 anos', 158.90, 'Evento'),
(114539, 2, 'Associado de 12 anos', 100.00, 'Promoção'),
(114539, 3, 'Associado de 7 a 11 anos', 100.00, 'Promoção');

A query ficaria similar à seguinte:
SELECT r.controle,
       SUM(CASE r.tipo WHEN 'Associado a partir 12 anos' THEN r.quantidade ELSE 0 END) AS 'Associado a partir 12 anos',
       SUM(CASE r.tipo WHEN 'Associado de 12 anos' THEN r.quantidade ELSE 0 END) AS 'Associado de 12 anos',
       SUM(CASE r.tipo WHEN 'Associado de 7 a 11 anos' THEN r.quantidade ELSE 0 END) AS 'Associado de 7 a 11 anos',
       r.valor,
       r.voucher
  FROM reserva r
 GROUP BY r.controle,
          r.valor,
          r.voucher

Resultando em:
| controle | valor | voucher  | Associado a partir 12 anos | Associado de 12 anos | Associado de 7 a 11 anos |
| -------- | ----- | -------- | -------------------------- | -------------------- | ------------------------ |
| 114539   | 158.9 | Evento   | 2                          | 0                    | 0                        |
| 114539   | 100   | Promoção | 0                          | 2                    | 3                        |

Você deve utilizar na cláusula GROUP BY as colunas as quais irão agrupar o registro, no caso do resultado que você apresentou, aparentemente você só não quer agrupar o tipo (que irá se tornar uma coluna utilizando o CASE na query) e a quantidade (que irá ser somada com o SUM).
Você pode ver o resultado da query em execução no DB Fiddle.
Caso queira utilizar o PIVOT a query ficaria como a seguinte:
SELECT y.controle,
       ISNULL(y.[Associado a partir 12 anos], 0) AS [Associado a partir 12 anos],
       ISNULL(y.[Associado de 12 anos], 0) AS [Associado de 12 anos],
       ISNULL(y.[Associado de 7 a 11 anos], 0) AS [Associado de 7 a 11 anos],
       y.valor,
       y.voucher
  FROM reserva r
 PIVOT (SUM(r.quantidade) FOR r.tipo IN ([Associado a partir 12 anos], [Associado de 12 anos], [Associado de 7 a 11 anos])) y

Usando PIVOT e UNPIVOT
Você pode usar os operadores relacionais PIVOT e UNPIVOT para alterar uma expressão com valor de tabela em outra tabela. PIVOT gira uma expressão com valor de tabela ao transformar os valores exclusivos de uma coluna na expressão em colunas múltiplas na saída, além de executar agregações onde forem necessárias em quaisquer valores de coluna remanescentes que sejam desejados na saída final. UNPIVOT executa a operação oposta a PIVOT, girando colunas de uma expressão com valor de tabela em valores de coluna.
Comment: A solução que você aplicou com a ausência das informações citadas acima, na mesma logica eu consegui solucionar utilizando CASE em vez de utilizar o PIVOT !
Muito obrigado

Ajuda com um PIVOT ( Sql Server )


How can I prevent a page with PHP content getting flagged in Security Review "Dangerous tags in content" check?

Question: I am using Drupal 7. I have a page that has a PHP body that I know does not have any dangerous tags. According to the README.txt file in Security Review I need to add this to the "security_review_known_risky_fields" system variable ? Can somebody provide an example on how to do this? I am not sure exactly what the entry in the variable table should look like.
Answer: In settings.php add the following:
$conf['security_review_known_risky_fields'] = implode(
  ',',
  array(
    'xxx',
    'yyy',
    'zzz'
  ),
);

...where 'xxx', 'yyy', and 'zzz' are the content hash strings shown for each problematic file in the Security Review report.
Comment: Does some of my answer need to be combined with this one?
Comment: Would be good if an example of this gets added to the module's README.
Answer: The README says to create "a SHA-256 hash of the entity_id, entity_type, and field contents". It looks like you have to call hash('sha256', $entity_id.$entity_type.$field_contents) and save that in the security_review_known_risky_fields string variable, which can be done in settings.php. If there are multiple fields you want to allow, separate their respective hashes with commas.


Porting MPICH-1 source codes to MPICH-2

Question: I have a source code of an application written in 2005 in C++ for a 32-bit architecture and used MPICH-1 library. I know the logic and I want to upgrade the source code for 64-bit machines and with MPICH-2.
How different the syntax/semantics of MPICH-1 is from MPICH-2? Should I consider re-designing the software or changing the MPI functions to newer version is enough?
Answer: TL;DR - Just update your MPICH library to the newest version and you're all set
First, MPICH has actually progressed beyond MPICH-2 now. The latest version (3.1) was just released recently. Also, the project is no longer renaming itself with every major release. It's just MPICH now.
Semantics aside, the API that MPICH exposes isn't determined by the MPICH developers, but by the MPI Standard. Since MPICH-1, the standard has gone through two major versions and is now on version 3.0. There were some major changes between the 1.x series and the 3.x series, however everything is backwards compatible so you should be able to just recompile with the most recent version and you're all set.
However, if you want to take a look at the latest and greatest, there were new additions in both MPI 2.x and MPI 3.0 related to one-sided communication that you might take a look at. There are also new collective operations, topologies, dynamic processes, I/O, non-blocking operations, etc. In the past 9 years, there's been a lot of progress (certainly lots more than can be posted in this answer).

Porting MPICH-1 source codes to MPICH-2


Floor datetime with custom start time (lubridate)

Question: Is there a way to floor dates using a custom start time instead of the earliest possible time?
For example, flooring hours in a day into 2 12-hour intervals starting at 8am and 8pm rather than 12am and 12pm.
Example:
x <- ymd_hms("2009-08-03 21:00:00")
y <- ymd_hms("2009-08-03 09:00:00")
floor_date(x, '12 hours')
floor_date(y, '12 hours')

# default lubridate output:
[1] "2009-08-03 12:00:00 UTC"
[1] "2009-08-03 UTC"

# what i would like to have:
[1] "2009-08-03 20:00:00 UTC"
[1] "2009-08-03 08:00:00 UTC"

Answer: You could program a small switch (without lubridate, though).
FUN <- function(x) {
  s <- switch(which.min(abs(mapply(`-`, c(8, 20), as.numeric(substr(x, 12, 13))))),
              "08:00:00", "20:00:00")
  as.POSIXct(paste(as.Date(x), s))
}
FUN("2009-08-03 21:00:00")
# [1] "2009-08-03 20:00:00 CEST"

FUN("2009-08-03 09:00:00")
# [1] "2009-08-03 08:00:00 CEST"

Comment: thanks! i will up-vote, and wait a while to see if any lubridate option is posible/available.


If $R$ is open equivalence then $Rx$ is closed?

Question: Let $R$ be an equivalence relation on topological space $X$. "Suppose $R$ is open.(i.e. $\forall x\in X, Rx$ is open.) Then $Rx$ is closed."
$\textbf{Q:}$ Why is $Rx$ closed and open?
Ref: Profinite Groups Chpt 1, pg 10. by Luis Ribes, Pavel Zalesski.
Answer: Hint: Show:
$$Rx=\left(\bigcup\limits_{y\,\mid\,(y,x)\notin R} Ry\right)^{c}.$$
Comment: Well, you need to show this, but yes.
Comment: Ah in this case, it is obvious by definition.
Comment: That is basically giving out the full answer. Thanks a lot. I was wondering why the author mentioned this in 1 line.


Truth functional completness for quantifiers

Question: There is a definition for truth-functional completness for a set of propositional connectives. Is there a definition for truth-functional completness of a set of quantifiers and propositional connectives ?
Answer: There cannot be a direct analogue, because a formula with quantifiers in it can depend on the truth values of infinitely many atomic propositions. There are $2^{2^{\kappa}}$ different possible truth functions of $\kappa$ inputs, and when $\kappa$ is infinite this much larger than the number of possible formulas one can build from any finite set of connectives. So in this sense there is no complete finite set of quantifiers and connectives.
I suppose one could consider complete sets containing (uncountably) infinitely many different quantifiers, but that's not very practical.


Why my QToolButton which I try to make collapsible doesn't collapse properly?

Question: guys.
Asking for your help to troubleshoot my test script.
I am practicing to make collapsible button with widgets inside.
Script was mainly taken from another question in stackoverflow about collapsible buttons.
So I am trying to put under QTabWidget my class CollpsibleBox(QWidget). Problem is that my CollapsibleBox is acting very weird - buttons are jumping , sometimes it doesn't open/close properly.
I was wondering if it's some mistake in placing correctly my widget under QTabWidget or is there some problem with animation?
import random
from PySide2.QtGui import QPixmap, QBrush, QColor, QIcon, QPainterPath, QPolygonF, QPen, QTransform
from PySide2.QtCore import QSize, Qt, Signal, QPointF, QRect, QPoint, QParallelAnimationGroup, QPropertyAnimation, QAbstractAnimation
from PySide2.QtWidgets import QMainWindow, QDialog, QVBoxLayout, QHBoxLayout, QGraphicsView, QGraphicsScene, QFrame, \
    QSizePolicy, QGraphicsPixmapItem, QApplication, QRubberBand, QMenu, QMenuBar, QTabWidget, QWidget, QPushButton, \
    QSlider, QGraphicsPolygonItem, QToolButton, QScrollArea, QLabel

extraDict = {'buttonSetA': ['test'], 'buttonSetB': ['test']}
tabList = ['Main', 'Extra']
_ui = dict()

class MainWindow(QDialog):
    def __init__(self, parent=None):
        QDialog.__init__(self, parent=parent)
        self.create()

    def create(self, **kwargs):
        _ui['mainLayout'] = QVBoxLayout()
        _ui['tabWidget'] = QTabWidget()
        _ui['mainLayout'].addWidget(_ui['tabWidget'])
        for tab in tabList:
            _ui['tab' + tab] = QWidget()
            _ui['tabWidget'].addTab(_ui['tab' + tab], tab)

        _ui['tabExtra'].layout = QVBoxLayout()
        _ui['tabExtra'].setLayout(_ui['tabExtra'].layout)

        _ui['content'] = QWidget()
        _ui['tabExtra'].layout.addWidget(_ui['content'])

        vlay = QVBoxLayout(_ui['content'])
        for name in extraDict.keys():
            box = CollapsibleBox(name)
            vlay.addWidget(box)
            lay = QVBoxLayout()
            for j in range(8):
                label = QLabel("{}".format(j))
                color = QColor(*[random.randint(0, 255) for _ in range(3)])
                label.setStyleSheet(
                    "background-color: {}; color : white;".format(color.name())
                )
                label.setAlignment(Qt.AlignCenter)
                lay.addWidget(label)

            box.setContentLayout(lay)
        self.setLayout(_ui['mainLayout'])

class CollapsibleBox(QWidget):
    def __init__(self, name):
        super(CollapsibleBox, self).__init__()
        self.toggle_button = QToolButton(text=name, checkable=True, checked=False)
        self.toggle_button.setToolButtonStyle(Qt.ToolButtonTextBesideIcon)
        self.toggle_button.setArrowType(Qt.RightArrow)
        self.toggle_button.pressed.connect(self.on_pressed)
        self.toggle_animation = QParallelAnimationGroup(self)
        self.content_area = QScrollArea(maximumHeight=0, minimumHeight=0)
        self.content_area.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
        self.content_area.setFrameShape(QFrame.NoFrame)

        lay = QVBoxLayout(self)
        lay.setSpacing(0)
        lay.setContentsMargins(0, 0, 0, 0)
        lay.addWidget(self.toggle_button)
        lay.addWidget(self.content_area)

        self.toggle_animation.addAnimation(QPropertyAnimation(self, b"minimumHeight"))
        self.toggle_animation.addAnimation(QPropertyAnimation(self, b"maximumHeight"))
        self.toggle_animation.addAnimation(QPropertyAnimation(self.content_area, b"maximumHeight"))

    def on_pressed(self):
        checked = self.toggle_button.isChecked()
        self.toggle_button.setArrowType(Qt.DownArrow if not checked else Qt.RightArrow)
        self.toggle_animation.setDirection(QAbstractAnimation.Forward
            if not checked
            else QAbstractAnimation.Backward
                                           )
        self.toggle_animation.start()

    def setContentLayout(self, layout):
        lay = self.content_area.layout()
        del lay
        self.content_area.setLayout(layout)
        collapsed_height = (self.sizeHint().height() - self.content_area.maximumHeight())
        content_height = layout.sizeHint().height()
        for i in range(self.toggle_animation.animationCount()):
            animation = self.toggle_animation.animationAt(i)
            animation.setDuration(500)
            animation.setStartValue(collapsed_height)
            animation.setEndValue(collapsed_height + content_height)
        content_animation = self.toggle_animation.animationAt(self.toggle_animation.animationCount() - 1)
        content_animation.setDuration(500)
        content_animation.setStartValue(0)
        content_animation.setEndValue(content_height)

if __name__ == '__main__':
    import sys
    app = QApplication(sys.argv)
    window = MainWindow()
    window.setGeometry(500, 100, 500, 500)
    window.show()
    sys.exit(app.exec_())

Answer: The problem is that you are only adding two widgets to the full layout, and the layout will try to place them as better as possible (tipically at the center of the area that is available for each widget, based on its size hints).
You could either set the alignment of the widget for the layout (placing the buttons on top of their available space):
        vlay = QVBoxLayout(_ui['content'])
        for name in extraDict.keys():
            box = CollapsibleBox(name)
            vlay.addWidget(box, alignment=Qt.AlignTop)

Or add a stretch to the bottom of the layout:
        vlay = QVBoxLayout(_ui['content'])
        for name in extraDict.keys():
            # ...
        vlay.addStretch(1)

which will position all buttons on top of the layout.
As a side note, I'd suggest you to avoid the dictionary logic for the ui, as it might become very confusing and prone to errors. If you really need to do that for some (I hope, very good) reason that's ok, but please avoid it when asking questions: it makes really hard to read your code, and people might end up just ignoring your question at all.
Comment: You're welcome! You don't need to use a dict for this, just create class instance attributes (eg. `self.tabWidget = QTabWidget()`), which is exactly what Qt does when using `setupUi` or `uic.loadUi` with .ui files created from Designer. You only have to ensure that attribute names are unique (but that would be the same for dictionaries) and don't overwrite the basic QWidget/QObject methods. Since you're creating the ui from code, you can avoid creating persistent instance attributes for objects you don't need tracking for (usually widget layouts, as you can access them with `widget.layout()`)
Comment: Usually one would use a list to group those buttons (remember that there is QButtonGroup), or eventually by means of setattr (eg. `setattr(self, 'button_{:02}'.format(b), QPushButton(str(b)))`). Look around S.O. for answers about creating dynamic attribute names for classes.
Comment: Thank you for your help, it really helped. Also thanks for note about dictionary, I am  an amateur in coding and still don't know how to make proper codes. Can you please suggest me then how to avoid dictionary? I am making dictionaries , because sometimes in my scripts I find that I need to use some information from mainWindow class in other classes without making global variables.
Comment: Ohh... I see, true that. Then can I ask one last question about this topic. How do you handle 'for loop' then ? If you need to make a lot of same buttons, but with unique naming , is there any other option then dictionary ?


vue-good-table has no styles

Question: I've been trying vue-good-tabel module which i installed directly with npm
but whatever I do, i can't get it to load it's default styles or any styles at all for that reason.
Note: if I add styles manually to my styles.css file they will be displayed but i have to make the styles myself.

   <vue-good-table
      :columns="columns"
      :rows="rows"
      theme="nocturnal"
      :pagination-options="{
        enabled: true,
        mode: 'records',
        perPage: 10,
        position: 'top',
        perPageDropdown: [10, 20, 50],
      }">

        No data to display

    </vue-good-table>

Edit 1: I also have Bootstrap in my vue project and jquery if it makes any difference
Edit 2 This is the error I get if i do import 'vue-good-table/dist/vue-good-table.css' which should import it from node_modules folder
Module build failed: Error: EISDIR: illegal operation on a directory, read

 @ ./node_modules/vue-good-table/dist/vue-good-table.css 4:14-127 13:3-17:5 14:22-135
 @ ./node_modules/babel-loader/lib!./node_modules/vue-loader/lib??vue-loader-options!./src/components/Admin.vue?vue&type=script&lang=js&
 @ ./src/components/Admin.vue?vue&type=script&lang=js&
 @ ./src/components/Admin.vue
 @ ./src/router/index.js
 @ ./src/main.js
 @ multi (webpack)-dev-server/client?http://0.0.0.0:8080 webpack/hot/dev-server ./src/main.js

Edit 3 If i try to add the import at the global level i still get the error but it's like this:
 ERROR  Failed to compile with 1 errors

 error  in ./node_modules/vue-good-table/dist/vue-good-table.css

Module build failed: Error: EISDIR: illegal operation on a directory, read

 @ ./node_modules/vue-good-table/dist/vue-good-table.css 4:14-127 13:3-17:5 14:22-135
 @ ./src/main.js
 @ multi (webpack)-dev-server/client?http://0.0.0.0:8080 webpack/hot/dev-server ./src/main.js

Comment: Are you importing the style sheet from the package as the example indicates? https://www.npmjs.com/package/vue-good-table
Comment: It was installed using npm directly, if i do `import 'vue-good-table/dist/vue-good-table.css'` in the component, i get an error
Comment: If i try to import the css styles like the vue-good-table docs show, i get that error
Comment: The error indicates that the file you're trying to use is actually a directory. Check the structure and find the actual CSS file.
Comment: Already did, and there's no directory with that name
Comment: add  `:row-style-class="yourFunctionName"` after `:rows="rows"`. And write the function inside methods. `yourFunctionName(){ return 'text-warning'}`
Answer: I was having the same problem, then got further confused by the scss files.
I went back to  look at the documentation under Installation
[https://xaksis.github.io/vue-good-table/guide/#installation]
and saw
// import the styles
import 'vue-good-table/dist/vue-good-table.css'

which prompted me to add a link to the stylesheet and it worked for me.
 <link href="../../../node_modules/vue-good-table/dist/vue-good-table.css" rel="stylesheet" />

Hope that helps.
Answer: This worked for me:
@import '~vue-good-table/dist/vue-good-table.css';

vue-good-table has no styles


Solve the integral equation $\int_0^{-x}f(t)dt= f(x) + x$.

Question:
Solve the integral equation $\displaystyle\int_0^{-x}f(t)dt= f(x) + x$.

Like it says, I'm playing around with even and odd functions and require a function such that $$\int_0^{-x}f(t)dt= f(x) + x\,.$$ I can't think how to go about it, any help appreciated.
If $F(x)=\int_0^{x}f(t)dt$, then $$F(-x)=F'(x)+x$$ with $F(0)=0$.  Then by differentiating both sides, we get
$$-F'(-x)=F''(x)+1.$$
How to solve this differential equation?
Comment: First I would use another dummy variable in the integral as $x$ is busy.  Second I would take a derivative with respect to $x$.
Comment: So overall you mean ${F(-x) = f(x) + x}$? where ${F(x)=\int f(x)dx}$? What have you tried?
Comment: The title is different, I answered to the title!
Comment: @RossMillikan In order for the left side to be differentiable for sure we must know if $f$ is continuous. Otherwise we have no clue!
Comment: The problem is that the OP does not give any further clues.
Comment: The left side is continuous.  Therefore the right side is continuous.  Therefore the left side is differentiable.  Therefore the right side is differentiable...
Comment: The differential equation to be solved: $$\frac{d}{dx} \left(f(x) + x\right) = -f(x)$$
Comment: have been trying of the form e^ax so that when the a comes down it can factor out to same function with a one. Was hoping for a solution that wasn't exponential but obviously I didn't specific that so it's not compulsory
Comment: @RossMillikan; why is $f$ differentiable?
Comment: fair enough, pretty likely I made a mistake before admins changed it, removed the downvote,
Comment: Is that a problem found in a textbook or just a problem that you alone posed just for personal interest?
Comment: If found on textbook provide the whole problem statement
Comment: @Arnaldo:  because it always is in these problems.  More seriously, the left side is differentiable because of the fundamental theorem of calculus.  That means the right side is, too.
Comment: Indeed @GEdgar, my bad - silly mistake on my part :)
Answer: From $$\displaystyle\int_0^{-x}\,f(t)\,\text{d}t=f(x)+x\,,\tag{#}$$ we see that $f$ is differentiable, and by taking the derivative of this integral equation with respect to $x$, we have $$-f(-x)=f'(x)+1\,.\tag{*}$$
That is, $f'$ is also differentiable, and by taking derivative of (*) with respect to $x$, we get
$$f'(-x)=f''(x)\,.$$
From (*), we get $f'(-x)=-f(x)-1$.  Therefore,
$$f''(x)=f'(-x)=-f(x)-1\,.$$
This means
$$f(x)=a\cos(x)+b\sin(x)-1$$
for some constants $a$ and $b$.  Now,
$$x+a\cos(x)+b\sin(x)-1=f(x)+x=\int_0^{-x}\,f(t)\,\text{d}t=x-a\sin(x)-b\cos(x)+b\,.$$
This shows that $b=-1$ and $a=-b=1$.  That is,
$$f(x)=\cos(x)-\sin(x)-1\,.$$

Alternatively, we can continue from the results
$$F(-x)=F'(x)+x\text{ and }-F''(-x)=F'(x)+1\,,$$
by noting that
$$F(x)=F'(-x)+(-x)\text{ and }-F''(x)=F'(-x)+1\,.$$
Therefore,
$$F'(-x)=F(x)+x\text{ so }-F''(x)=\big(F(x)+x\big)+1\,.$$
Hence,
$$F''(x)+F(x)=-x-1\,.$$
This shows that
$$F(x)=A\cos(x)+B\sin(x)-x-1\,.$$
Because $F(0)=0$, we get $A=1$, so $$F(x)=\cos(x)+B\sin(x)-x-1\,.$$
That is,
$$F'(x)+x=-\sin(x)+B\cos(x)+x-1$$
and
$$F(-x)=\cos(x)-B\sin(x)+x-1\,.$$
This means $B=1$, and so $F(x)=\cos(x)+\sin(x)-x-1$, and we get
$$f(x)=F'(x)=F(-x)-x=\cos(x)-\sin(x)-1\,.$$

P.S.  Since there have been many questions regarding differentiability of $f$, I shall explain.  First, we at least need the assumption that $f$ is integrable.  Therefore, $\int_0^{-x}\,f(t)\,\text{d}t$ is a continuous function in $x$.  Then, (#) implies that $f$ is continuous.  Now, as $f$ is continuous, $\int_0^{-x}\,f(t)\,\text{d}t$ is a differentiable function in $x$, whence (#) tells us again that $f$ is differentiable.  By doing this cyclically infinitely (but countably) many times, we can conclude that $f$ is in fact a smooth function.
Comment: @Riemann'sPointyNose  The integral equation already says that $f$ is continuous.  If $f$ is integrable, then $\int_0^{-x}\,f(t)\,\text{d}t$ is continuous in $x$.
Comment: @Rieman'sPointyNode Continuity of $f$ is a sufficient condition to say that the integral of it is differentiable. It's a theorem.
Comment: @Riemann'sPointyNose Yes, it does.  You now know that $f$ is continuous, and $f(x)=\int_0^{-x}\,f(t)\,\text{d}t-x$.  Since $f$ is continuous, $\int_0^{-x}\,f(t)\,\text{d}t$ is differentiable.
Comment: @Batominovski Not all integrabe functions are continuous.
Comment: @AnastassisKapetanakis The integral equation tells you that.  First, if $f$ is integrable, $\int_0^{-x}\,f(t)\,\text{d}t$ is continuous in $x$.  Therefore, $\int_0^{-x}\,f(t)\,\text{d}t-x$ is continuous in $x$.  Thus, $f$ is continuous.
Comment: @Batominovski Yes indeed the integral is continuous. But we do not know if it is differentiable. So we do not know if you can apply the common theorem about differentiation of integrals
Comment: @AnastassisKapetanakis ${f(x) = \int_{0}^{-x}f(x)dx - x}$. Since the integral is continuous (because it's implied the ${f(x)}$ is integrable) then that implies ${f(x)}$ is continuous (since it's the sum of two continuous functions) and so ${f}$ is continous and we can differentiate both sides
Comment: @Batominovski There are functions that are not continous but they are differentiable! But I hope in the OP's problem $f$ is continuous.
Comment: Thanks for clarifying that!
Comment: you are correct, although the question I asked wasn't able to get me to the criteria I wanted to, I'm looking for a algebraic function that doesn't require if statements like absolute value, that has the property
y=1 if x>0
y=0 if x<0


How to add inline Models in admin Interface [Django]

Question: I am trying to add an inline model to a Post model. As the docs says, i am trying to do something like:
models.py
from django.db import models

class images(models.Model):
    image = models.ImageField(upload_to='images/')

class Post(models.Model):
    Title = models.CharField(max_length=60)
    Images = models.ForeignKey(images)

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

class ModelInlinePost(admin.TabularInline):
    model = models.images

class ModelPost(admin.ModelAdmin):
    view_on_site = False
    inlines = [PythonInlineAdmin,]

When i try execute any command with manage.py. It throws back this error:
python manage.py makemigrations
SystemCheckError: System check identified some issues:

ERRORS:
 <class 'home.admin.ModelInlinePost'>: (admin.E202) 'home.Post' has no ForeignKey to 'home.images'.

Answer: Try deleting all posts with no images. The code below works for me:-
Models
class Image(models.Model):
  image = models.ImageField(upload_to='images/')

class Post(models.Model):
  image = models.ForeignKey(Image, on_delete=models.CASCADE)
  title = models.CharField(max_length=50)

Admin
class ImageInline(admin.TabularInline):
    model = Image

class PostAdmin(admin.ModelAdmin):
    inlines = [
        ImageInline,
    ]


How to update fsspec in Pandas

Question: I am trying to use the Pandas read_csv method. Everything was working fine. I saved everything and started to work on it the next day but then I kept getting this error:
ImportError: Pandas requires version '0.7.4' or newer of 'fsspec' (version '0.6.2' currently installed)

I have updated pandas to the latest version twice to make sure that it is up to date. I am unsure what to do to troubleshoot going forward, any suggestions are appreciated!
Answer: Just do on command prompt
pip install  fsspec=0.7.4

It will work fine.
Comment: == instead of =
Answer: You would need to install fsspec==0.8.2 (or a newer version than 0.6.2) in your project to continue working with pandas

How to update fsspec in Pandas


"calinvite" url scheme in ios?

Question: How can i use this url-scheme in practise?
calinvite   calinvite:eventid=id
(source: http://iphonedevwiki.net/index.php/NSURL)
is it possible to add a calendar entry with this URL scheme?
thanks for your thoughts!
Answer: You can't use it. Because it is private.
You can only use the URL schemes that are public, if you use these private url schemes in your app, the app will be rejected from AppStore.
Comment: Ok, thanks for your answer. i've found another way with calling a extern php script, maybe for some of you this will be of use:
https://gist.github.com/jakebellacera/635416

"calinvite" url scheme in ios?


Dynamic Field Adition / Subtraction using FAPI

Question: Goal Provide a user with a drop down menu defaulted to a value of none. Other options are the number 1 through 27. Based on the value select have drupal FAPI generate a fieldset that has anywhere from 1 to 27 required text fields. And should they then change their mind it would re-render accordingly.
What I have
So far I am able to get the FAPI to hide the field on initial form render however I can't seem to figure out how I'd take the selected array value and use that to generate out a new field set dynamically.
function single_add_ucm_form($form, &$form_state) {
$form['number_subscribers'] = array(
'#type' => 'select',
'#title' => t('How many subscribers are in the CUCM cluster?'),
'#required' => TRUE,
'#default_value' =>  0,
'#ajax' => array(
  'callback' => 'ajax_select_callback',
  'wrapper' => 'replace_subscribers_div',
  'effect' => 'slide',
 ),
'#options' => array(
  0 => t('none'),
  1 => t('1'),
  2 => t('2'),
  3 => t('3'),
  4 => t('4'),
  5 => t('5'),
  6 => t('6'),
  7 => t('7'),
  8 => t('8'),
  9 => t('9'),
  10 => t('10'),
  11 => t('11'),
  12 => t('12'),
  13 => t('13'),
  14 => t('14'),
  15 => t('15'),
  16 => t('16'),
  17 => t('17'),
  18 => t('18'),
  19 => t('19'),
  20 => t('20'),
  21 => t('21'),
  22 => t('22'),
  23 => t('23'),
  24 => t('24'),
  25 => t('25'),
  27 => t('26'),
  27 => t('27'),
),
);
$form ['subscribers_wrapper_container'] = array(
'#type' => 'container',
'#prefix' => '
',
'#suffix' => '
',
);

if (isset($form_state['values']['number_subscribers'])) {
$form_state >= 1;
$form['subscribers_wrapper_container']['UCM_SUB'] = array(
    '#type' => 'textfield',
    '#size' => 30,
    '#title' => t('Subscriber IP Address'),
    '#required' => TRUE,
  );
}
}

function ajax_select_callback($form, $form_state) {
return $form['subscribers_wrapper_container'];
  }

Answer: if (!isset($form_state['values']['number_subscribers'])) {
   $form_state['values']['number_subscribers'] = 0;
}

for($i = 0; $i < $form_state['values']['number_subscribers']; $i++){
$form['subscribers_wrapper_container'][]['UCM_SUB'] = array(
    '#type' => 'textfield',
    '#size' => 30,
    '#title' => t('Subscriber IP Address'),
    '#required' => TRUE,
  );
}

You should add '#tree' => TRUE on your form, it will be easier to extract the form values afterwards


Warning: Cannot modify header information - headers already sent

Question: My log is cluttered with this message:
Warning: Cannot modify header information - headers already sent by (output started at /home/path/to/drupal/7/includes/common.inc:2681) in drupal_send_headers() (line 1216 of /home/path/to/drupal/7/includes/bootstrap.inc).

It occurrs only when someone types address to a non-existing comment like this:
http://example.com/comment/874

If the comment exists, or for any other address, there is no error. (I was deleting lots of spam comments recently and the bots keep coming back to read their own comments, that's why there is a lot of not found comments.)
Is there any means to get rid of this error? The only comment module I have is Comment Goodness and there isn't complaint on such error in the issue queue, so maybe it's something else. I checked all my custom module files and each of them starts with <?php and there is no space or anything before this tag, and there is no closing tag. I have no idea what else to check.
Comment: This is an old PHP gotcha. If in your preprocessing you place a closing tag and then a space, you have created page output and headers are sent. The best practice used to be to omit the closing tags from php files so an accidental space would not trigger the problem.
Comment: @Triskelion Not on my watch ;)
Comment: I've seen a lot of these warnings recently too, on a few different sites. Only on 404 pages though (not just comment pages). I haven't got round to debugging it yet, would be interested to see if it's a wider problem
Comment: I would also check all the custom modules and theme files that if the php ending `?>` at the end of the file is omitted. This is a best practice recommended on Drupal Coding Standarts. [https://drupal.org/coding-standards#phptags](https://drupal.org/coding-standards#phptags)
Comment: @Triskelion In my case I have no closing PHP tags in any file. They're probably unrelated to be honest, I'm seeing it for all 404 pages on a couple of sites (with very little in common)
Comment: @Clive - It would also happen if the opening tag were preceded by a space. But to be truthful I have never encountered it with Drupal (touch wood!). Could it be creeping in through eval()?
Comment: @Clive Did you ever get to the bottom of this?
Comment: @MPD 'Fraid not. I put a temp solution in to cover most cases, but it still pops up fairly often
Answer: In my own case, I've found that this was due to modules that attempt to return a 404 by mistakenly calling drupal_not_found() instead of returning the MENU_NOT_FOUND constant. This causes drupal_deliver_page() to be called twice in a single page request.
Views is the biggest culprit right now; see https://drupal.org/node/1414068 (comment #16) for a patch that resolves it. You should grep through your modules directory for "drupal_not_found" to find other modules with this problem.
Answer: I have seen a few things cause this.
A closing ?> on a file with space after it.  The Drupal convention is to not use the closing PHp tag on any file.
A UTF-8 encoded file with a BOM.  The BOM would be before the the opening <?php, and is output.
Following the advice of Yahoo! YSlow and adding a flush() between the  and  in html.tpl.php
Debug directly using print or print_r instead of dsm() in code.
I also recall a weird problem I had where I had some framebusting code in a template file, and if a linked resource 404ed, then I think I had this problem b/c the Drupal 404 page would load for the linked resource.
Answer: Building on Les Lim's answer, combined with your finding that you are seeing this with comment URLs, you are probably seeing issue #2218501 from the Comment Goodness module (are you using that on your site?). It is inserting its own callback for comment URLs and is indeed calling drupal_not_found() when it can not find the comment (where it should be retuning MENU_NOT_FOUND).
There is a patch in the issue, and it has been committed to the development branch of the module, in october of 2014. Looking from the project status and the issue queue, it doesn't look like we can expect an updated official release any time soon, though.


Any way to speed up this Magento code?

Question: Is there any way to speed up this Magento code?  Currently it is looking through about 2k products and takes approximately 20 minutes to run.
I'm guessing the issue is around the product->load() call, but I'm not familiar enough Magento to know the overhead it takes.
Thank you.
from controller
Mage::dispatchEvent(
    'category_rule_save',
    array(
        'rule_id'        => $id,
        'attribute_code' => $data['attribute_code'],
        'operator'       => $data['operator'],
        'value'          => $data['value'],
        'category_id'    => $data['category'],
        'store_id'       => $data['store_id']
    )
);

from Observer.php
public function onCategoryRuleSave($observe)
{
    $collection =
        Mage::getModel('catalog/product')->getCollection()
            ->addAttributeToSelect($observe['attribute_code']);
    $write = Mage::getSingleton('core/resource')->getConnection('core_write');

    foreach ($collection as $product) {
        $productId = $product->getId();
        $product = $product->load($productId);
        $productAttributeValue = '';
        $productAttributeValue =
            Mage::getModel('catalog/product')->load($productId)
                ->getAttributeText( $observe['attribute_code'] );
        $r = 0;

        if ( is_numeric($observe['value']) ) {
            switch($observe['operator']) {
                case "<":
                    $r = ($productAttributeValue < $observe['value']) ? 1 : 0;
                    break;
                case ">":
                    $r = ($productAttributeValue > $observe['value']) ? 1 : 0;
                    break;
                case "<=":
                    $r = ($productAttributeValue <= $observe['value']) ? 1 : 0;
                    break;
                case ">=":
                    $r = ($productAttributeValue >= $observe['value']) ? 1 : 0;
                    break;
                case "==":
                    $r = ($productAttributeValue == $observe['value']) ? 1 : 0;
                    break;
                case "!=":
                    $r = ($productAttributeValue != $observe['value']) ? 1 : 0;
                    break;
            }
        }
        else {
            switch($observe['operator']) {
                case "==":
                    $r = (
                        strcmp(strtolower($productAttributeValue) , strtolower($observe['value'])) == 0
                    ) ? 1 : 0;
                    break;
                case "!=":
                    $r = (
                        strtolower($productAttributeValue) != strtolower($observe['value'])
                    ) ? 1 : 0;
                    break;
            }
        }

        if ($r==1) {
            $write->query(
                "REPLACE INTO `catalog_category_product` (`category_id`, `product_id`)
                VALUES (" . $observe['category_id'] . "," . $product->getId() . ")"
            );
        }
    }
}

Answer: Try replacing the product loading with:
...
foreach ($collection as $product) {
 $productAttributeValue = $product->getAttributeText( $observe['attribute_code'] );
 $r = 0;
...

You're loading a product object 2 extra times.  The $product variable in the foreach already is the loaded product with the attribute that you need to work with.  Loading a $product object with all of its attributes is expensive given Magento's EAV database structure.
Comment: You'll also notice a big speed difference depending on the hardware that you're running the code on and the optimization of the MySQL install (which is a little outside of the scope of the question).  Feel free to click the checkmark next to the answer to accept it if it solved your problem ;)
Comment: Thank you.  This brought the time from ~20min down to ~5min.
Comment: Update.  Removed the extra product->load. This brought the time down to ~5seconds.  Again, thanks a ton!
Comment: For more speed, test setting up an Amazon EC2 server with nginx, redis, and php-fpm. It is proving pretty snappy for us (1500 products, 5k+ sales).
Answer:
1.$collection =
        Mage::getModel('catalog/product')->getCollection()
        ->addAttributeToSelect($observe['attribute_code']);
2.Mage::getModel('catalog/product')->load($productId)
                ->getAttributeText( $observe['attribute_code'] );
3.$product = $product->load($productId);

That is really awful :)

$collection =
        Mage::getModel('catalog/product')->getCollection()
        ->addAttributeToSelect('*');//this string should load all of the product attributes

There also were some methods to add product websites, product store and some others.

Any way to speed up this Magento code?


How can I replace this condition by a probability?

Question: I want to see if a datapoint x should (or not) be assigned to a nearest component y using the following condition:
if ($d > T$) then {do not assign x to y}. With $d = distance(x,y)$ and $T = \bar{d}+\sigma$ where $\bar{d}$ is the mean distance of y to datapoints that were already assigned to it in the past, and $\sigma$ the associated stdev.
I want to replace this condition (i.e. ($d > T$)) by an equivalent expression which is expressed as a probability $p$. How can I do that ? I've tried for exemple $p = exp(\frac{-d^2}{2\sigma`^2}) / (\sigma`\sqrt{2\pi})$ but it does not behave like the first condition unless we manually find a good value for $\sigma`$
Note: it does not really matter if it is not a true probability (that sum to one).
Comment: If you have any parameters at all in your probability calculation, they are going to have to be tuned somehow if you want good results, and if you don't have any parameters, you're not likely to get good results, except by great luck.  Also, any probability calculation will have to take into account all the distances, otherwise you can't ensure the probabilities sum to one (note that even "set p=1 for the minimum distance component" takes all the distances into account when calculating the minimum.)
Comment: @jbowman please be more clear, are you saying that I should keep $\sigma`$ and vary it manually (by increasing it) until I get a satisfying results ?! Note that the first condition works well, I just want to replace it with an equivalent probabilistic expression.
Comment: Note that exp(−d$^2$/2σ`$^2$) is not a probability.  You need to normalize by dividing it by (√2π)σ`.
Comment: @MichaelChernick this does not matter since we manually change $\sigma`$ until it behaves like the first condition. I don't know however if there is any way to "learn" the good value for $\sigma`$
Comment: What you have is only proportional to a probability density.  It is not the normal probability density without the normalization. In any case the terminology is wrong.  You were attempting to express the requirement in terms of the height of the probability density and not in terms of a probability.
Comment: @MichaelChernick Well ok let's normalize on $(\sigma`\sqrt{2\pi})$, this does not change the fact that we still need to find the value of $\sigma`$ that makes this probability behaves like the first condition ($d < T$). I heard about maximum likelihood, but I don't know what is it exactly and if it is convenient for this problem ?
Comment: Maximizing the likelihood would look for parameter values for the parameters that define the probability density for the distance between x and y to be highest.  But what you want hear is to find a d so the the density is relatively low beyond that d.  So you would want to choose T so that the tail probability P(d>T)T for various values of T until that integral gets smaller than a.
Comment: @MichaelChernick is this equivalent to computing the integral of P which is defined as ($P = exp(\frac{-d^2}{2\sigma`^2}) / (\sigma`\sqrt{2\pi})$) for d > T, and repeat this for various values of $sigma`$ until that integral gets smaller than a=0.05 ? Then I can say this is the good value for $sigma`$ ?
Comment: @user995434 I suppose you could do that if somehow you already know the right value of T and want to see what sigma makes that probability sufficiently small.  But originally T was defined in terms of sigma.  If you want to maintain the definition of T as average d + sigma  you could change sigma and be changing T at the same time until you got the sigma that satisfied your conditions.
Comment: @MichaelChernick note that here $\sigma$ is totally different from $\sigma`$. And what do you mean by "until you got the value that **satisfied your conditions**" ? Do you mean that for each new d higher than T, I compute the probability P, and see if it is higher than 0.05 then I increase T and do P = P + Previous_P (discrete integration for values of d > T) ?
Comment: @user995434 Why are the sigmas different.  Id T= avg. d + sigma and you increase sigma leaving avg d fixed P(d>T) gets smaller and at the same time the density you are integrating is getting smaller.
Comment: @MichaelChernick but $\bar{d}$ and $\sigma$ will change each time a new datapoint x is assigned to y, does this matter ? And how do we increase $\sigma$ since it changes when a new x is assigned to y ?
Comment: @user995434 p is a probability density function. You take its integral for a d greater than T after you pick sigma.  If the integral is too large increase sigma and thus increase T repat the integration.  Once the integral gets small enough you have the sigma you want.
Comment: The threshold T is fixed.  You determine it through the integration and apply the same T to every new data point unless for some reason you think there is some change to your model that requires a reevaluation of sigma.
Comment: @MichaelChernick The threshold T is local to each component y (normally I should write $T_y$ instead), and it is not fixed since it depends on "the mean distance ($\bar{d}$)" of y to data points that were already assigned to it (this mean that each time a new datapoint x is assigned to y, its associated $\bar{d}$ will be updated) ! I understand that we can compute a "good" sigma (or say $\sigma_y$) for a given component y through the integration P(d > $T_y$), but is it possible when the $\bar{d}$ associated to this y is not fix ?
Comment: In the integral you have removed mu from the equation.  So the only effect on the integral will come from sigma.  A small change in sigma may not make the change in the integral very noticeable.
Answer: If y is too far from x you should be able to define T independent of y. I wouldn't do it this way.  But if you want to update sigma and T and then calculate P(d>T) you can and decide whether or not to keep y based on that probability.


Help getting the following create table function to work with mysql and C#

Question: <code>string createTable = "CREATE TABLE IF NOT EXISTS " + m_strDatabase + "_TimeLogs (logName VARCHAR(16), logTime INTEGER, logCountry TEXT, UNIQUE(logName)) TYPE=MyISAM;";
</code>
When this runs, no table is created.
No errors either.
Im using an ODBC connector.
the variable passes in the db name, so that the table created would be   users_TimeLogs if the database was called users for example.
Am I doing something wrong?
Comment: Where's the rest of the code that actually executes this string?
Comment: I didn't include it because I know that bit works, i've used it before..  Its the first time i've tried to create a table though.  I'm using the OdbcCommand, and then OdbcCom.ExecuteNonQuery().
Comment: Creating table and inserting records are different things.
Do you have enough rights to create table?
Comment: yeah I do, it executes perfectly through phpMyAdmin.. Just not when running in the C# code.
Answer: I'd forgotten that way way above in my code I had a constraint to only run if a list.count > 0, and since I'm only testing at this stage the list was empty..
Comment: "I didn't include [the rest of the code] because I know that bit works"... :D


How to load the link stored in a cell from sql table PHP

Question:
Possible Duplicate:
mysql_fetch_array() expects parameter 1 to be resource, boolean given in select

I am trying to load/generate the link stored inside a cell from my sql table via php.
But I am getting an error:
Warning: simplexml_load_file() expects parameter 1 to be string, resource given in ... on line 78
Could you guys please tell me where I did wrong?
Here is my code:
$sql = "SELECT link FROM previousbroadcast WHERE id=21";
$result=mysql_query($sql);

$xml = simplexml_load_file($result);

Answer: $result variable is a SQL Result set, not a string. You have to use a function like mysql_fetch_array to get the value of the individual columns from your SQL results.
Perhaps something like:
$sql = "SELECT link FROM previousbroadcast WHERE id=21";
$result=mysql_query($sql);

while($row = mysql_fetch_array($result)){
    $xml = simplexml_load_file($row[0]);
    break;
}

Answer: mysql_query returns a statement handle. You have to fetch a row from that handle and extract the value:
$sql = "SELECT ..."
$result = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_assoc($result);
$xml = simplexml_load_file($row['link']);

Answer: $result is not the value of the link field in your table, but the ressource id. You want something like
$sql = "SELECT link FROM previousbroadcast WHERE id=21";
$ressource=mysql_query($sql);  // remember, it's just the ressource
$result = mysql_fetch_array($ressource); // let's get this into an associative array

$xml = simplexml_load_file($result['link']); // and use the respective field in the array to fetch the XML

Be aware that this is very simple code, and you should make sure that the file exists before you try to load it...
Comment: thank you so much for helping. i tried this, but instead of loading the link in only row 21, it loads all the links present in the table. why is that?
Comment: Without seeing more of your code, there is no way to tell.
Answer: You need to get the result first. In your $result variable you only have a SQL resource stored. To get the actual content of the query, use $result_array = mysql_fetch_array($result) which will return an array with your data. You can then call the simplexml_load_file($result_array[0]) function.
Answer: mysql_query returns a resource. use mysql_fetch_array to get to the content. They have examples in the documentation.
Answer: $sql = "SELECT link FROM previousbroadcast WHERE id = '21'";

$result = mysql_query($sql);
if(mysql_num_rows($result) >= 1) {
$row = mysql_fetch_array($result);
$xml = simplexml_load_file($row['previousbroadcast']);
}

Firstly, you should encapsulate your SQL parameters with single quotes ('). Secondly using mysql_query only returns a handle, you need to actually generate an array of that result using mysql_fetch_array(). You should also add in some error-catching as shown above too.


How to decelerate an AddForce slowly FIXED

Question: I have a 2d rigidbody that needs to glide to a stop. To move, I add a force to the rigidbody at the speed that I like, called speedUp, and I do not know how to make it glide to a stop. I tried adding an opposite force when I let go of the W key, but it stopped immediately. I need to find a way to make the "ship" decelerate to a stop after .5 seconds. I have found others asking this question, but none of the answers have worked for me and my specific code. Adding Drag does not work either, as I want to be able to move in other directions as well.
GameObject ship;
public Vector2 speedUp;
public Rigidbody2D shipRig;

// Use this for initialization
void Start () {
    ship = GameObject.FindGameObjectWithTag ("ship");
    shipRig = ship.GetComponent<Rigidbody2D> ();
}

// Update is called once per frame
void Update () {
    if (Input.GetKeyDown (KeyCode.W)) {
        shipRig.drag = 0;
        shipRig.AddForce(speedUp);
    }
    if (Input.GetKeyUp (KeyCode.W)) {
    }

Thanks to all of you!
EDIT!
I fixed it!!! Thanks all of you guys for your suggestions, all I did was change it from 'GetKeyDown' to 'GetKey' and it worked! I put the drag to 2 and the speed is 40px.
GameObject ship;
public Vector2 speedUp;
public Vector2 speedDown;
public Vector2 speedLeft;
public Vector2 speedRight;
public Rigidbody2D shipRig;

public Vector2 speed1;

// Use this for initialization
void Start () {
    ship = GameObject.FindGameObjectWithTag ("ship");
    shipRig = ship.GetComponent<Rigidbody2D> ();
}

// Update is called once per frame
void FixedUpdate () {
    if (Input.GetKey (KeyCode.W)) {
        shipRig.AddForce(speedUp);
    }

    if (Input.GetKey (KeyCode.S)) {
        shipRig.AddForce(speedDown);
    }
    if (Input.GetKey (KeyCode.A)) {
        shipRig.AddForce(speedLeft);
    }
    if (Input.GetKey (KeyCode.D)) {
        shipRig.AddForce(speedRight);
    }

}

Comment: Using an opposite force is the simplest course of action here. This is a typical mechanics problem, determining how much deceleration is required to stop an object over a set period of time (and hence how much force should be applied over that time). Have you taken a physics course before in school?
Comment: Does setting the drag to a value other than 0 not work?
Comment: @ḞḹáḿíṅḡⱫỏḿƀíé I tried setting drag to 1 after i let go of the key, but I also want the ship to go in other directions. The drag interferes if I want to move the ship in the other directions.
Comment: Have you tried giving the ship a vector3 for travel/movement? if you did you alway apply the travel/movement vector to the ship in your update loop but when you want to move forward  instead of adding your speedUp to the ship you add it to the vector3 for travel/.movement..
Comment: @Serlite I tried adding an opposite force but it stops it immediately and I want it to glide to a stop. And no I have not take a physics course yet.
Comment: @racorse if you wanted to have it slow down at the same rate it sped up at you would want to add the inverse of your speedUp (shipRig.AddForce(-speedUp)) after all, there is no such thing as decelerating, only accelerating in a negative direction.
Comment: @racorse It is a good practice to put the answer outside of the question so that when people are searching for similar problems to yours they are able to see that the question was answered even if it way by the OP.
Answer: As you are using physics, you just need to apply enough force according to player input to make the ship move as you want. You could set the drag to begin with and keep it that way but make the input force bigger so that you can override the drag.
If you do this, the drag will always be there and will naturally slow something down if there is no force acting on it. If the player presses W, we apply a force big enough that will overcome the drag and propel the ship forwards; when they release W, the only "force" acting will be the drag, which will slow it down.
This is an alternative approach to Serlite's comment of using an opposing force.
Newton's First Law of Motion:

In an inertial reference frame, an object either remains at rest or
  continues to move at a constant velocity, unless acted upon by a
  force.

In your case, the only force you have is being applied by the input. You either need an active opposing force in the form of AddForce or resistance in the form of friction or drag.
If you want the ship to slow to a halt in exactly 0.5 seconds, you will need to calculate how much drag vs how much velocity the ship has when the player releases the button but if you will accept something "close" to 0.5 seconds you can just get there will some trial and error.
Comment: Just as a side thought, op could also in the update loop do a check to see if a key is being pressed and if it is op can not add the drag to the ship.
Comment: That seems like an unnecessary step to me. Why not just set it as default and leave it?
Comment: @AnselFaillace I did that but it interferes with the other directions when I add them in the future.
Comment: @ḞḹáḿíṅḡⱫỏḿƀíé You are right, it is in large part is unnecessary. The reason I stated this as a possible option is because some people like to see only what they are currently affecting it with instead of everything that is affecting it.
Comment: @racorse How did it interfere with your other directions?
Answer: First of all, all the physics calculations MUST be inside the FixedUpdate () and not the Update () function, as by its own nature the Update function happens after a variable time and can happen from 30 to over 200 times every second. This makes it extremely unreliable when it comes to balancing speeds, forces and other physics calculations.
To have it decelerating you can add some drag or apply an opposite force, as already mentioned by Flaming Zombie.
Comment: Thanks for the tip on that!
Comment: No worries, just keep it in mind for the future. It saves you a lot of headaches. ;)


GeoLiteCityv6.dat seems to return different data from a day ago

Question: I regularly check the values being returned from the GeoLityCityv6.dat data file in unit tests.
Today it is returning completely different values from yesterday
For example
220.127.116.11
Used to return
CountryCode [US], CountryName [United States], ContinentCode [NA], ContinentName [North America],
today it returns
CountryCode [CN], CountryName [China], ContinentCode [AS], ContinentName [Asia], City [V±!S%Õ¨áNY], regionCode [3]
184.108.40.206
user to return,
CountryCode [CO], CountryName [Columbia], ContinentCode [SA], ContinentName [South America], City [Medell], regionCode [02]
today returnes
CountryCode [DE], CountryName [Germany], ContinentCode [EU], ContinentName [Europe], City []?ïù102], regionCode [3420]
184.108.40.206
used to return
CountryCode [CN], CountryName [China], ContinentCode [AS], ContinentName [Asia], City [Guangzhou], regionCode [30]
today returns
CountryCode [JO], CountryName [Jordan], ContinentCode [AS], ContinentName [Asia],  City [null], regionCode [gbao]
188.8.131.52
used to return
CountryCode [AT], CountryName [Austria], ContinentCode [EU], ContinentName [Europe]
today returns
CountryCode [CO], CountryName [Colombia], ContinentCode [SA], ContinentName [South America], City [Ì}$é307], regionCode [751]
When I look up these IP Addresses on maxmind.org home page I get the old data not the new data
Comment: What API are you using to read the database?
Answer: This was a corrupt database file. The issue has been corrected. Please download a new version.


Solving $\arcsin(1-x)-2\arcsin(x)=\pi/2$

Question: \begin{eqnarray*}
\arcsin(1-x)-2\arcsin(x) & = & \frac{\pi}{2}\\
1-x & = & \sin\left(\frac{\pi}{2}+2\arcsin(x)\right)\\
 & = & \cos\left(2\arcsin(x)\right)\\
 & = & 1-2\left(\sin\left(\arcsin(x)\right)\right)^{2}\\
 & = & 1-2x^{2}\\
x & = & 2x^{2}\\
x\left(x-\frac{1}{2}\right) & = & 0
\end{eqnarray*}
So $x=0$ or $x=\frac{1}{2}$
But puttig $x=\frac{1}{2}$ in the original expression gives $-\frac {\pi} 4 \ne \frac \pi 2$
So, why do we get $x=-1/2$ as an answer?
Answer: In your first step you added an extra solution.
Since $\arcsin x$ must be smaller than $\pi/2$, the first line reads:
$$\arcsin(1-x)= \frac{\pi}{2}+2\arcsin(x) \le \frac{\pi}{2}$$
Thus, $x\le 0$ as well.
Now, by taking the $\sin$ of both sides, you took a function that was only defined up to $x=1$ (e.g. $\arcsin(x-1)$ ) and extended it to all reals (e.g $x-1$). Here is where you added the extra solution.
Comment: So $1-x\le \sin(\pi/2) \quad \quad \quad 1-x\le 1 \quad \quad \quad -x\le 0 \quad \quad \quad x\ge 0$
Comment: @user80551 - yes, that too.
Answer: Beside the good answers you already received, you can also consider the problem from an algebraic point of view. Let $$f(x)=\arcsin(1-x)-2\arcsin(x)-\frac{\pi }{2}$$ Its derivative $$f'(x)=-\frac{2}{\sqrt{1-x^2}}-\frac{1}{\sqrt{(2-x) x}}$$ is always negative (with infinite branches at $x=0$ and $x=1$). For $x=0$, $f(0)=0$ and since the function decreases, you cannot have any root beside $x=0$ (remember that $f(x)$ is only defined for [$0<x<1$]).
Answer: As  $\displaystyle \sin\left(\frac\pi2\pm A\right)=\cos A,$
$\displaystyle\sin\left(\frac\pi2\pm2\arcsin x\right)=\cos(2\arcsin x)=1-2\left[\sin(\arcsin x)\right]^2=1-2x^2$
So, $\displaystyle x=\frac12$ corresponds to $\displaystyle\arcsin(1-x)+2\arcsin x=\frac\pi2$ as $\displaystyle\arcsin\frac12=\frac\pi6$
Comment: Er, that's exactly what I did. What are you getting at?
Comment: @user80551, my point is if we start with $$\displaystyle\arcsin(1-x)+2\arcsin x=\frac\pi2$$ we shall reach at $$x=2x^2$$ as well
Comment: I did reach $x=2x^2$, see the question. That quadratic has two roots, one of which is not the answer. My question is where did that root come from?
Comment: @user80551, that is coming from the fact pointed out in the first line of my answer
Comment: Oh, you mean $\sin(\pi /2 +A)=\cos A$ ***and*** $\sin(\pi /2 -A)=\cos A$ ?
Comment: @user80551, yes.


C# WPF pages information

Question: I have a bunch of WPF userContol in my project with a bunch of textboxes and datepickers the idea is to get all the data from all the pages, when the user click the submit button on the last page, and fill a pdf form.
<code>    <UserControl x:Class="FormFiller.Pages.UserInfo"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             mc:Ignorable="d"
             d:DesignHeight="300" d:DesignWidth="600">
    <Grid>
        <Label x:Name="lblName" Content="EMPLOYEE'S NAME (Last, First, Middle Initial)" HorizontalAlignment="Left" Margin="1,55,0,0" VerticalAlignment="Top" Width="263" Foreground="#FF151212" FontSize="12" FontFamily="Times New Roman" FontWeight="Bold"/>
        <TextBox x:Name="txtBoxEmpName" HorizontalAlignment="Left" Height="23" Margin="23,90,0,0" TextWrapping="Wrap" Text="" VerticalAlignment="Top" Width="201">
            <TextBox.BorderBrush>
                <LinearGradientBrush EndPoint="0,20" MappingMode="Absolute" StartPoint="0,0">
                    <GradientStop Color="#FFABADB3" Offset="0.05"/>
                    <GradientStop Color="#FFE2E3EA" Offset="0.07"/>
                    <GradientStop Color="#FF8DC1F5" Offset="1"/>
                </LinearGradientBrush>
            </TextBox.BorderBrush>
        </TextBox>
        <Label x:Name="lblDateAssigned" Content="DATE ASSIGNED PRESENT POSITION" HorizontalAlignment="Left" Margin="338,55,0,0" VerticalAlignment="Top" Foreground="#FF151212" FontFamily="Times New Roman" FontWeight="Bold"/>
        <DatePicker x:Name="DpAssigned" HorizontalAlignment="Left" Margin="357,90,0,0" VerticalAlignment="Top" Width="178"/>
        <Label x:Name="lblduedate" Content="DUE DATE OF WITHIN-GRADE INCREASE" HorizontalAlignment="Left" Margin="1,158,0,0" VerticalAlignment="Top" Width="241" FontFamily="Times New Roman" FontWeight="Bold"/>
        <DatePicker x:Name="DpDue" HorizontalAlignment="Left" Margin="23,196,0,0" VerticalAlignment="Top" Width="179"/>
        <Label x:Name="lblPeriod" Content="PERIOD COVERED BY THIS PERFORMANCE PLAN" HorizontalAlignment="Left" Margin="298,158,0,0" VerticalAlignment="Top" Width="298" FontFamily="Times New Roman" FontWeight="Bold"/>
        <DatePicker x:Name="DpFrom" HorizontalAlignment="Left" Margin="323,201,0,0" VerticalAlignment="Top"/>
        <Label x:Name="lblFrom" Content="From" HorizontalAlignment="Left" Margin="346,184,0,0" VerticalAlignment="Top" FontFamily="Times New Roman" FontWeight="Bold"/>
        <Label x:Name="lblTo" Content="To" HorizontalAlignment="Left" Margin="509,184,0,0" VerticalAlignment="Top" FontFamily="Times New Roman" FontWeight="Bold"/>
        <DatePicker x:Name="DpTo" HorizontalAlignment="Left" Margin="471,201,0,0" VerticalAlignment="Top"/>
    </Grid>
</UserControl>
</code>
any idea on how to accomplish that?
Answer: Create a ViewModel with fields for each of your FrameworkElements and set up bindings so that they update those fields as the user interacts with them. Then add an RelayCommand to your ViewModel and bind the "Submit" button's command handler to it. When the RelayCommand's handler is called all the data will be ready to save using whatever PDF 3rd-party library you prefer.
Comment: Just to paraphrase/elaborate on this answer: there is no reason why you cannot bind several different views to one concrete instance of one viewmodel. If you want to restrict what each view can "see" in the VM just implement an interface on the VM for each view, the view should access it by that interface only (although the interface is totally transparent/nonexistent as far as the binding subsystem is concerned).

C# WPF pages information


Jquery remove element after append

Question: So i was just wondering. Why does this work:
$("input[name='edit-meta']").keyup(function(e){
    if(e.keyCode=='32'||e.keyCode=='13'){
        var clicked=$(this);
        var tag=$(this).val();
        clicked.siblings("#edit-meta").append('<span style="background:<?php echo $ad_details_arr[9]?>;color:<?php echo $ad_details_arr[8]?>" class="tag">'+tag.slice(0,-1)+'<a href="#" class="remove" style="background:<?php echo $ad_details_arr[10]?>;color:<?php echo $ad_details_arr[8]?>;margin:5px">x');
        clicked.val("");
    }
    $("a.remove").on("click",function(e){
        e.preventDefault();
        var clicked=$(this);
        clicked.closest("span.tag").fadeOut(function(){
            $(this).remove();
        });
    });
});

And not this:
$("input[name='edit-meta']").keyup(function(e){
    if(e.keyCode=='32'||e.keyCode=='13'){
        var clicked=$(this);
        var tag=$(this).val();
        clicked.siblings("#edit-meta").append('<span style="background:<?php echo $ad_details_arr[9]?>;color:<?php echo $ad_details_arr[8]?>" class="tag">'+tag.slice(0,-1)+'<a href="#" class="remove" style="background:<?php echo $ad_details_arr[10]?>;color:<?php echo $ad_details_arr[8]?>;margin:5px">x');
        clicked.val("");
    }
});
$("a.remove").on("click",function(e){
    e.preventDefault();
    var clicked=$(this);
    clicked.closest("span.tag").fadeOut(function(){
        $(this).remove();
    });
});

I thought the .on would be sufficient to allow me to perform handlers yet created just like .live does.
Also stated in the jquery .on page.
"
... ability to handle events on descendant elements not yet created
"
Comment: What is it supposed to do and what goes wrong?
Answer: You can use this:-
$(document).on("click" , "a.remove" ,function(e){
    e.preventDefault();
    var clicked=$(this);
    clicked.closest("span.tag").fadeOut(function(){
        $(this).remove();
    });
});

The above thing will not work because a.remove is not available in the DOM.
The first example work because you are attaching event to a.remove after it is added to the DOM.

Jquery remove element after append


Finding the unknown variable

Question: What is the value of $x$ in $x^{x}=25$? How can this be solved in the easiest way of all? I just couldn't deduce any idea regarding where to start.
Comment: The product-log function (it's called that in Mathematica), is more commonly called the [Lambert W function](http://en.wikipedia.org/wiki/Lambert_W_function).
Comment: Do you know about the Product-log-Function?
Answer: $$
\begin{align}
x^x&=25\tag{1}\\
x\log(x)&=\log(25)\tag{2}\\
\log(x)e^{\log(x)}&=\log(25)\tag{3}\\
\log(x)&=\mathrm{W}(\log(25))\tag{4}\\
x&=e^{\mathrm{W}(\log(25))}\tag{5}\\
&=\frac{\log(25)}{\mathrm{W}(\log(25))}\tag{6}
\end{align}
$$
Explanation:
$(2)$: take log of both sides
$(3)$: $x=e^{\log(x)}$
$(4)$: if $we^w=x$, then $w=\mathrm{W}(x)$, $\mathrm{W}$ is Lambert W
$(5)$: exponentiate $(4)$
$(6)$: divide $(2)$ by $(4)$
Answer: The solution of
$
x^x=a
$
is
$$
x = \frac{\log a}{W(\log a)}
$$
where $W$ is the Lambert W function, not an elementary function.
Answer: \begin{align}
x^x &= 25 \\
x^2 &= 25
\end{align}
possibilities, $x=5$ or $x=-5$ because $5^2 = 25$ and $-5^2 =25$
description:
\begin{align}
-5\times-5
&=(-1)\times5\times(-1)\times5 \\
&=(-1)\times(-1)\times5\times5 \\
&=1\times5\times5 \\
&=25
\end{align}
Comment: Usually $x^x\ne x^2$.

Finding the unknown variable


how to create XElement from a string?

Question: Say I have a string like
string var = "This is a test";

Then I want to use this string to create an instance of XElement like:
XElement element =  XElement.Load(var);

Comment: Use vb.net -> Dim myX = This is a test… Done.
Answer: Use the XDocument.Parse method to parse the string into an XML Document.
var document = XDocument.Parse("<element>This is a test</element>");

var element = document.Root;

Comment: Thank you so much Michael. I love your answer! It saved my time. I think it is also good to use `stringBuilder` and `string.Format()` to work with the string part. +1 for your answer! : )
Answer: XElement myX = new XElement("elementName", "This is a test");

This will be equivalent to the XML:
<elementName>This is a test</elementName>

Answer: Isn't it just:
var el = new XElement("name", value);

? Elements need names, note.
Comment: I was gonna vote you up, but then I noticed that you have enough rep to bail out the mortgage vendors. Still... +1
Answer: XDocument.Parse(str).Root returns XElement. str must be well-formed xml document.
If you want to construct xml you can: XElement el = new XElement("Root"); (this means as if it was <Root />)
BTW your string var = "This is a test"; is neither XML not valid XML tag name.

how to create XElement from a string?


Why v²/2 comes equal to (-k/m)*(x²/2) while doing indefinite integration to express v as a function of x in case of spring-mass system.

Question: We know that, using indefinite integration over f'(x) we can get f(x) whose derivative is f'(x). That's why integration is also called antiderivative. But when we do definite Integration, we get ∆f(x) for ∆x.
But in the above mentioned case, indefinite integration gives an absurd result.
The case is as follows,
 A body of mass m connected to a spring displaces from its equilibrium position..
On applying force on the body for a while  the body displaces  to x=x(i.e. position w.r.t. equilibrium position is a certain value x) and at that position it has velocity equals to V. But due to its inertia it moves to further to x=a. Durin this displacement from x to a, the body experiences varying spring force and this causes the body to retardate and at x=a, velocity becomes 'zero'.
According to *Hook's law', F(spring force)= -kx, where k is the spring constant.
Now using this formula and doing a bit of indefinite integration to express V in terms of x, we get the following equation,
Expressing V as a function of x in case of spring-mass system.
Since Velocity can't be imaginary,hence this equation is quite absurd. However applying the upper and lower limits 0 and V & a and x respectively for both sides, we get **V = √{(k/m)*(a²-x²)}, which seems quite correct. But the question is why the equation from where we have derived this one seems to be so 'incorrect' or 'invalid' ?
Comment: You dropped the constant of integration.
Comment: First, it's Hooke. Second, you omitted the all-important constant of integration (which is necessarily positive). Tge method is  not incorrect; you screwed up!
Answer: $v \frac {dv}{dx} = -\frac {k}{m} x\\
\int v\ dv = \int -\frac {k}{m} x\\
\frac 12 v^2 = -\frac 12 \frac {k}{m} x^2 + C\\
v^2 = -\frac {k}{m} x^2 + C\\
v = \sqrt {C - \frac {k}{m} x^2}$
Now, what you would normally do...
Since $C$ is an arbitrary constant we can replace $C$ with $\frac {k}{m}C.$ And since C is necessarily positive we can replace $C$ with $\frac {k}{m} C^2$
$\frac {dx}{dt} = \sqrt {\frac {k}{m}C^2 - \frac {k}{m} x^2}\\
\int \frac {dx}{\sqrt {C^2 - x^2}} = \int \sqrt {\frac km}dt\\
\arcsin \frac {x}{C}  = \sqrt {\frac {k}{m}}t + \phi\\
x = C\sin (\sqrt{\frac km} t + \phi)$
$C$ is the maximum amplitude of the oscillation.
Comment: That's great , but I am a bit confused about how you replaced C by C² . Can you elaborate that part ?
Comment: C is an arbitrary constant.  You can to a lot of things to an arbitrary constant and have it still be an arbitrary constant.  It would have been even cleaner to replace $C$ with $\frac {k}{m} C^2.$  Which I think I am going to do!
Comment: @Doug_M Oh! That means you are considering the arbitrary constant to be the square of another arbitrary  constant . But I think it would be more clear if we write C= K² , where K is also an arbitrary constant.
Comment: It is pretty standard stuff in differential equation to just keep carrying the same variable name of the constant as you manipulate it... It is a little bit confusing at first and then it becomes old-hat.


How to query Marklogic with punctuation-sensitve terms using JAVA?

Question: I have the following info stored in Marklogic for the json files as follows.
1.json>> "dateSubmitted" : "2017/10/11 09:15:14"
2.json>> "dateSubmitted" : "2017/10/11 10:13:14"
3.json>> "dateSubmitted" : "2017/10/14 11:12:13"

My query term is:
String dateQuery = "2017/10/11";

I tried 2 methods and none seems to be working.
Method 1:
StructuredQueryBuilder qb = new StructuredQueryBuilder();
QueryDefinition queryDef = qb.and(qb.word((qb.jsonProperty("dateSubmitted"),dateQuery)));
queryDef.setDirectory(DIRECTORY);
SearchHandle resultsHandle = new SearchHandle();
queryManager.search(queryDef, resultsHandle, start);

Method 2:
StructuredQueryBuilder qb = new StructuredQueryBuilder();
String[] wordQueryOptions = {"punctuation-sensitive", "space-sensitive"};
QueryDefinition queryDef = qb.and(qb.word((qb.jsonProperty("dateSubmitted"),
                                      FragmentScope.DOCUMENTS,
                                      wordQueryOptions,100.0,dateQuery)));
queryDef.setDirectory(DIRECTORY);
SearchHandle resultsHandle = new SearchHandle();
queryManager.search(queryDef, resultsHandle, start);

The expected result is to return only 1.json and 2.json.
However 3.json was also returned.
Is there some settings I'm missing in my Marklogic admin to activate options or punctuation-sensitive?
Answer: Working with dates is often easier and more powerful if you index the property as a date. That way, you can do before and after matches on the date as well as sort on the date.
To index a property as a date, you can create a range index on the date. You can then use a range query on the date.
In MarkLogic 9, you can also use TDE to project rows from the documents with a column for the dates.
Hoping that helps,


How do I remove the "Save draft" button from every page of a multi-step form?

Question: I have a multi-step webform and I want to add a save draft button however it needs to be added only to the last preview page and not all step pages.
I have used settings within submission to activate saving draft however the button appears on each page. Any way to hide, without changing code but just through configuration/settings?
Answer: Create a new module and then you can check the <code>$form_state</code> page to conditionally enable to disable buttons.

function submission_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'webform_submission_xyz') {
    $form['actions']['button or field']['#access'] = $form_state->get('current_page' )== 'abcd';
}
Comment: Wasn't there a simple setting/permission you can uncheck?
Comment: There is no setting/permission; this is a good solution. Another approach would be using CSS to hide the 'Save draft' button, which is not as good a solution.


Disable Webform Componotent (field) after certain number of submissions

Question: I'm working on a registration form that collects student information and the class session they're signing up to. Class sessions are of select type and has four options (sessions). Each sessions has a cap of 38 students. Is there any way to automatically disable options once submission count reaches the cap..? Please note that this is a field level condition, not the entire form level.
Would that be rules? Any pointers... thanks!
Comment: https://www.drupal.org/node/342896
Answer: I would approach this by using
hook_webform_submission_insert (which is triggered after the submission is inserted into the database)
http://www.drupalcontrib.org/api/drupal/contributions%21webform%21webform.api.php/function/hook_webform_submission_insert/7
Once in that hook i would use webform_get_submission_count to get the number of submissions , if this was the last allowed submission i would then unpublish the node and create a redirect to a "this class is now closed page".
http://www.drupalcontrib.org/api/drupal/contributions%21webform%21includes%21webform.submissions.inc/function/webform_get_submission_count/7
You could also approach it by using hook_webform_submission_presave or a custom form validator to generate a form error.


Application of Poincaré-Bendixon Theorem

Question:

Consider the planar system in polar corrdinates:
    $$
\frac{dr}{dt}=r-r^3+r^2\sin\phi,\qquad\frac{d\phi}{dt}=1+\frac{1}{2}r\cos\phi.
$$
    Show that it has at least one periodic orbit.

As far as I know, the theorem of Poincaré-Bendixon says that if the $\omega$-limit set $\Omega(r_0,\phi_0)$ of some point $(r_0,\phi_0)$ is finite and does not contain a critical point, then $\Omega(r_0,\phi_0)$ is a periodic orbit.
The solution says that the $\omega$-limit set of any non-zero point must be finite and must lie at non-zero $r$ since for small $r>0$, we have $\dot{r}>0$ and for all large $r>0$, we have $\dot{r}<0$. I do not understand this. Why does this follow?
Moreover, it says that there can't be an equilibrium at $r\neq 0$: If $\dot{\phi}=0$, then, it is said, we have $r\geq 2$ and hence $\dot{r}\leq -2$. I cannot see this, since if $\dot{\phi}=0$ we have $r=-\frac{2}{\cos\phi}$. Why is this $\geq 2$?
Comment: Seems like a straightforward application of Poincaré-Bendixson theorem. http://www.scholarpedia.org/article/Poincare-Bendixson_theorem#Poincare-Bendixson_Theorem
Comment: It is easy to see that in the circle $r=\frac12$, $\dot{r}>0$ and in the circle $r=3$, $\dot{r}<0$. So by the Poincaré-Bendixon theorem, there is a periodic orbit in $\frac12 ...$.
Comment: @Mattos I can follow this. But what does this tell me about finitness of the $\omega$-limit set
Comment: @Did The version you've linked is connected with the version of the theorem I wrote down?
Comment: Did you *read* the link?
Comment: Yes, I read it. In your version the trajectory has to enter (and not leave) a closed and bounded region. In my version, the omega-limit set has to be finite.
Comment: In other words: (1.) I cannot see how from $\dot{r}>0$ for $r>0$ small and $\dot{r}<0$ for $r$ large it follows that the $\omega$-limit set is finite and lies at non-zero $r$ and, moreover, I do not see (2.) how the finitness of the $\omega$-limit set is connected with the linked version of the theorem.
Answer: It follows from the fact that ${dr\over{dt}}= r-r^3+r^2sin(\phi)$, you can write ${dr\over{dt}} =r(1-r^2+rsin(\phi))$, so there exists an interval $[0,u]$ on which $dr/dt>0$ since $lim_{r\rightarrow 0}1-r^2+rsin(\phi)=1$. This implies that if the norm $r(t)$ of an orbit is contained in $(0,u]$ it increases, so the $\omega$-limit of a non zero point can't be zero.
on the other hand, you can also write
  ${dr\over{dt}} =r^3(1/r^2-1+(sin(\phi))/r)$ this shows that if the length of $r(t)$ is bigger than a given constant $M$, it decreases since $lim_{r\rightarrow +\infty}1/r^2-1+(sin(\phi))/r=-1$, so the $\omega$-limit can't  go to the infinity.
The $\omega$-limit has finitely fixed points since they are finitely many fixed points. A fixed point is characterised by $dr/dt=0$, and $d\phi/dt=0$. If you write $dr/dt=0$, you can express $sin(\phi)$ has a rational function of $r$, you obtain $cos(\phi)$ has a rational function of $r$ if you write $d\phi/dt=0$. By writing $cos^2\phi+sin^2\phi=1$, you obtain a polynomial equation $P(r)$ which has only finitely many solutions this implies also that $sin\phi$ and $cos\phi$ are elements of a finite set (they are obtain from the solutions of $P(r)=0$ with $dr/dt=0, d\phi/dt=0$). this implies that the point such that $dr/dt=0$ and $d\phi/dt=0$ are finite.
Comment: Sorry, I do not understand: That the $\omega$-limit set of a point is finite means that it has finite many elements. And I cannot see how this follows from $r'>0$ for small $r>0$ and $r'<0$ for large $r$.


Selenium ide (Firefox) is giving error in feature of deleting a record from list

Question: I am using selenium ide (Firefox addon) to make Test Cases of Web Application.
When I click on Delete icon in a list of records, a javascript conformation message appear. selenium Display error in running a click on Delete icon.
Comment: What is the error message?
Comment: Element //a[@onclick='javascript:DeleteCategoryMaster(480,this);'] not Found
Answer: Selenium does not support popup window handling. For this u have to add extra lines in the generated script.


Java Future verify if success or failure?

Question: When calling the Kafka Producer, is there a way to verify if the result is success or failure? I get back a Future<RecordMetaData> but I do not know how to verify if it is successful or not successful. Or is it the fact that if this is returned, then the call is successful, if it failed then there would be an error thrown?
Comment: Unfortunately, there's a zoo of futures in Java. Which one are you referring to? Post a link to the class Javadoc.
Comment: *Or is it the fact that if this is returned, then the call is successful,* The operation may not even have happened yet.  The Future is a handle on the future success or failure of the operation.
Answer: The Future is a handle on the future successful or failed completion of the operation.
If for example you call `get()' on the Future object, then if it returns, you'll have a RecordMetaData.  Otherwise, it'll throw an ExecutionException, whose cause will tell you the actual failure.
See the documentation.
Comment: So the get() on the Future object either returns something if successful or throws an ExecutionException if the process was unsuccessful?
Comment: Yes.  (After suspending the calling thread to wait for completion, if necessary).
Comment: This is for publishing kafka logs in a springboot app, so it'll be live and users would hit the endpoint to publish. Assuming this, the logic you stated is still valid correct?
Comment: I don't really understand your use-case, but clearly the Kafka Producer is async to caller, since it returns a Future. If you in turn have an endpoint to your users, such that the operation needs to be complete before you respond to a user request, then yes, you have to wait for the Future to be completed.