Mostrar dados de uma javascript dentro da parte de renderização do ElectronJS

Question: Quero executar um arquivo JS junto com o Electron e retornar seu resultado dentro da parte de renderização do Electron
Codigo que quero mostrar dentro do Electron na parte de HTML:
const si = require('systeminformation');
si.cpu().then(data => console.log(data));

Como eu penso que pode ser:
const { app, BrowserWindow } = require('electron')

function createWindow () {
  // Cria uma janela de navegação.
  let win = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: true
    }
  })

  // e carregar o index.html do aplicativo.
  win.loadFile('index.html')
}

function informationSystem(){
    const si = require('systeminformation');
    si.cpu().then(data => console.log(data));

}

informationSystem()
app.whenReady().then(createWindow)

Answer: É isso o que você quer fazer?
Arquivo dentro de main.js
const { app, BrowserWindow } = require('electron')

function createWindow () {
  // Cria uma janela de navegação.
  let win = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: true
    }
  })
  win.webContents.openDevTools()
  win.loadFile('index.html')
}

app.whenReady().then(createWindow)

Arquivo dentro de index.html
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

Hello


>Javascript Comparing 2 dates

Question: I have this code in comparing dates
var startDate = jQuery("#startDate_field_id").val();
var endDate = jQuery("#endDate_field_id").val();
var startDateSplit = startDate.split("-");
var endDateSplit = endDate.split("-");
var start = new Date();
var end = new Date();
start.setFullYear( startDateSplit[0], startDateSplit[1], startDateSplit[2] );
end.setFullYear( endDateSplit[0], endDateSplit[1], endDateSplit[2] );

if( end < start ) {
 alert("End Date should be less than Start Date of the Event");
}

The value of #startDate_field_id is 2011-10-05

white the value of $endDate_field_id is 2011-10-04
What do you think is the reason why this isn't working.
Any help would be greatly appreciated and rewarded.
Thanks! :)
Answer: I'd use UNIX epoch timestamps for the comparison:
if (end.getTime() > start.getTime()) {
    alert('...');
}

Comment: Have you tried dumping the values for start and end through alert() or into the DOM to make sure they're correct?
Answer: Because setFullYear method month parameter accept 0..11, means 9 is October.
why not use
var start = new Date(startDate);
var end = new Date(endDate);

Comment: This a right way. But IE8 dont support date string in "yyyy-mm-dd" format.
Answer: var start = new Date(Number(startDateSplit[0]), Number(startDateSplit[1])-1, Number(startDateSplit[2]));
var end = new Date(Number(endDateSplit[0]), Number(endDateSplit[1])-1, Number(endDateSplit[2]));

or simply:
Answer: I am not sure I correctly understand your question .
I guess you want make sure that the end date must be greater than start date.
your code will work fine if you cahnge the if condition .And i just changed the alert message too to get proper meaning
Check this DEMO  .
Answer: I think your first problem is that you are using the Date object incorrectly. You are passing three arguments to the setFullYear() method, which only takes a single argument, a 4 digit year.
var start = new Date();
var end = new Date();
start.setFullYear( startDateSplit[0], startDateSplit[1], startDateSplit[2] );
end.setFullYear( endDateSplit[0], endDateSplit[1], endDateSplit[2] );

You might want to try something like this:
var start = new Date(startDateSplit[0], startDateSplit[1] - 1, startDateSplit[2])
var end = new Date(endDateSplit[0], endDateSplit[1] - 1, endDateSplit[2]);

>Javascript Comparing 2 dates


iOS app breakpoints on running

Question: I'm an experienced developer, but new to iOS/Objective C.
The app below builds OK (modulo any typo/cut'n'paste errors).
When I run it, it breaks in the print method, in a way that makes it look like there is some error.   I cannot see what or where the error is.   Probably a real newby error though!
Can anyone help me out by explaining what I am doing wrong and how to fix it?
This is a command line MacOS app, with Foundation, being built & run in XCode.
@interface DayOfYear : NSObject
- (void) print;
- (id) init : (int) day;
@end // DayOfYear

@implementation DayOfYear

int dayInYr =0;

- (id) init : (int) day {
    self = [super init];
    dayInYr = day;
    return self;
}

- (void) print {
     // NSLog(@"In print with %d", dayInYr);

}    // WHEN RUN THIS IS WHERE IT BREAKPOINTS SAYING "Thread 1, breakpoint 1.1, 2.1

@end

int main(int argc, const char * argv[])
{

    @autoreleasepool {

        // insert code here...
        NSLog(@"Hello, World!");

        DayOfYear *d =[[DayOfYear alloc] init : 2 ];
        [d print];

        NSLog(@"Finished!");

    }
    return 0;
}

Comment: Did you accidentally set a breakpoint there? To the left of your code where the breakpoint occurs, check to see if there's a horizontal blue arrow that points to that line of code.
Comment: make day in year a member of the class. eg DayOfYear : NSObject { int dayInYr; }
Answer: You have two breakpoints set on the print method.  Breakpoints are shown in the left margin as blue flags.  You can get rid of them by dragging them out of the margin, like this:
Comment: Just getting started with XCode, this saved me after hours of messing around. Heroic.
Comment: Yep, that was totally it!   Thank you, thank you, thank you!   It turns out that if you happen to click (not even double click) the mouse while the cursor is in that margin, it sets a breakpoint.   I was setting them through ignorance of that feature, and lazy mousing.  Much appreciated!   Now I can get on with the homework assignment.

iOS app breakpoints on running


generalized additive model with proportion independent variable

Question: I'm using GAM to model a potentially non-linear relationship between two variables (with some controls variables included) in mgcv. My main independent variable is a proportion (without 0's or 1's) that is highly skewed (see image 1 histogram).

Is there justification/reasoning to make an IV normal in GAM?
Should I transform this variable? I tried to sqrt(IV) (see image 2) and log10((IV)/(1-IV)) (see image 3). Functional form of results are different but not drastically depending on which (or none) transformation is used.

r code:
gam(DV ~ s(IV) + CV1 + CV2 +
                   s(CASEID, bs="re"), data = df, method = "REML")

Histograms of IV:
untransformed IV

sqrt(IV)

log10(IV)/(1-IV)
Comment: Thank you! That makes sense. If I were to want to transform the variable, is there justification for that position? As stated, the results are generally the same, but cleaner (less chaotic wiggliness) in the transformed IV analyses.
Answer: GAMs make no assumptions at all about the independent (predictor) variables (except, for some types of inference, that they are measured without error); certainly there are no assumptions about the distribution of the predictors, which are taken as observed values rather than as random variables.
Although the flexibility of GAMs can in principle handle most of the the issues that transforming the data would alleviate in a 'vanilla' linear model (i.e. nonlinearity in the response), I can imagine that using a transformation to stretch out part of the predictor space could improve the performance of the model under some circumstances.

you should have a clear idea what your metric is for model improvement (you say the result is 'cleaner'; do you have an objective way of quantifying that, or are you OK with using subjective assessments to guide your modeling?).
if you are worried about overfitting, be aware that trying a bunch of different transformations could be a form of 'data snooping'
Comment: Transforming does improve fit, as Robert has suggested. Constraining the basis function to be the same across the models produces the same functional form but with varying confidence intervals (much wider for untransformed). Thank you Bolker and Robert for your helpful responses.
Comment: If one or both of these questions solved your problem, you should pick one (whichever you thought was most useful) and click the check-mark to accept it ...
Answer: The third plot should be
log10(IV/(1-IV)),
not log10(IV) /(1-IV).
Often transforming an IV to a more "normal" distribution
gives a better fit to the response variable.
You could see which of the 3 transforms gives the best fit
according to a criterion, e.g the generalised Akaike information criterion (GAIC), which includes AIC and BIC as special cases.


Why isn't the Endroid\QrCode\QrCode found?

Question: I created a custom module and installed the endroid/qrcode library in my module using Composer. When I try to use that library, I get  the following error.

Error: Class 'Endroid\QrCode\QrCode' not found in Drupal\shopexp\Plugin\Block\ShopExp->build() (line 25 of modules\custom\shopexp\src\Plugin\Block\ShopExp.php).

The code using the library is the following one.
namespace Drupal\shopexp\Plugin\Block;
use Drupal\Core\Block\BlockBase;
use Endroid\QrCode\QrCode;

class ShopExp extends BlockBase {
  public function createpr() {
      $qr = QrCode::create("https://site.com");
  }
  public function build() {
    $qr = new QrCode();
    return [
      '#markup' => 'test msg',
    ];
  }
}

The composer.json file used by the module is the following one.
{
    "require": {
        "endroid/qr-code": "^2.5"
    }
}

The folder structure is the following one.
Comment: Why not use the existing module for that rather than write your own code? And if it doesn't do exactly what you want then maybe help out with that module. https://www.drupal.org/project/endroid_qr_code
Comment: @anonymous Actually i tried to reduce the module count and tried to include other functionalities in one module
Comment: That's faulty logic. What's wrong with many modules? It's still the same number of lines of code, no matter where you put them. Regardless, IMO you have the wrong approach. Collaborate and make the existing code better for everyone, don't just solve your own problem.
Comment: @anonymous i understand your point. But problem is where i did wrong using a php library to use inside a block after its included via composer
Comment: Composer dependencies shouldn't be installed into the module root. It should be in the project root.
Answer: You have to composer require endroid/qrcode from the Drupal root directory, not from your custom module directory. The package needs to be installed in the main vendor directory along with all the other packages used by Drupal, otherwise the class loader can't find it.
Comment: if include in root composer json means what happens if i use same module to other system. Will installing this module in a other drupal instance will include the dependencies ?
Comment: No - if you want Composer to install the dependencies for your module automatically, your module itself needs to be installed by Composer. Unless you use something like the composer merge plugin which might be an option, but that will also require changes to each site's composer.json


Relation between Uniform distribution, Metropolis Algorithm, and Symmetric Proposal Distribution

Question: I am having some confusion over the Metropolis algorithm. Let $g(x|y)$ be our proposal distribution for the algorithm. For the Metropolis, $g$ must be symmetric (from Wikipedia). In the discrete case, we can think of this as a stochastic matrix. I have also read, that

Transition matrices that are symmetric $P(i,j)=P(j,i)$ always have detailed balance. In these cases, a uniform distribution over the states is an equilibrium distribution.

I assume this is because symmetric matrices are doubly stochastic.
Could someone please clarify the ties between the Metropolis algorithm, Metropolis-Hastings, detailed balance, symmetry and the uniform distribution? More specifically, when does the Metropolis algorithm yield a uniform distribution (or why is it not always uniform since our $g$ is symmetric)?
Comment: $g$ does not have to be symmetric.  The Wikipedia heading refers to the special case where it is, but it is not a requirement.  To see why we might not want to use a symmetric proposal, consider a parameter that is bounded, say $\theta > 0$, but with a largeish plausible range, say $0 - 10$, and assume that on the very first draw we proposed and accepted $\theta_1 = 0.000001$.  With a symmetric proposal, we'd be probably be spending a very, very long time trapped at the extreme edge of the plausible range.
Comment: Doesn't $g$ have to be symmetric for Metropolis and then can be asymmetric for Metropolis-Hastings? I'm hoping to focus on the case when $g$ is symmetric under Metropolis.
Answer:
The case when the Metropolis-Hastings proposal $g$ is symmetric as in $g(x\mid y)=g(y\mid x)$ (and the above excerpt from Metropolis et al. 1953) does not imply that the stationary distribution $\pi$ associated with this proposal and the Metropolis-Hastings algorithm is uniform, but only that the Metropolis-Hastings acceptance ratio
$$1\wedge\frac{\pi(x')g(x\mid x')}{\pi(x)g(x\mid x)}=1\wedge\frac{\pi(x')}{\pi(x)}$$
does not depend on $g$. Even though $g$ itself as a Markov kernel is associated with a uniform measure, due to the acceptance step in the Metropolis-Hastings algorithm, the stationary distribution of the algorithm is not the stationary distribution of the proposal. This is the whole idea and appeal of the algorithm that the acceptance probability modifies the stationary distribution of the Markov chain thus generated.
Comment: Suppose our $g$ for the Metropolis is the normal distribution. That distribution is symmetric (or is this a different definition of symmetric), but obviously the normal distribution is not uniform. How can that be since the normal distribution is symmetric and not uniform?
Comment: Additionally, suppose our desired distribution $\pi$ is uniform. Wouldn't $\pi(x')=\pi(x)$ in that case and just cancel out to 1?
Comment: I am afraid you are missing the point: The symmetry in $g(x|y)$ means that $g(x|y)=g(y|x)$. In the special case when $\pi$ is constant and $g$ is symmetric, the acceptance probability is equal to one, which is correct.


Não fechar Bootstrap dropdown automaticamente

Question: Tenho um Bootstrap dropdown onde uma lista dinâmica é carregada quando o usuário abre o mesmo. O problema é que cada vez que existe uma iteração, por exemplo quando o usuário apaga um item da lista, o dropdown é fechado. Quero que o dropdown seja fechado somente quando o usuário clica no botão para fechar o mesmo.
Como evitar que em cada iteração o dropdown seja fechado automaticamente?
Código para remover um item da lista.
$('#containerNotice').on('click', 'button[data-process="removeNotice"]', function(event) {
    event.preventDefault();
    var noticeId = $(this).attr('data-notice-id');
    $.ajax({
        crossDomain: true,
        crossOrigin:true,
        type:"post",
        url: 'src/inc/notice/',
        data: { noticeId: noticeId, DataProcess: 'remove' },
        dataType: "json",
        success: function(data) {
            switch(data.status) {
                case 'success':
                    $('button[data-notice-id="'+noticeId+'"]').prop("disabled", true).css('opacity', '0.2');
                    break;
            }
        }
    });
});

Comment: Tenta isso meu jovem: `$(document).on('click', '.dropdown-item', function(event){
   event.stopPropagation();
});`
Comment: Coloca uma amostra do código para ver como é feita a remoção do item.
Comment: Sam.. editei o post original para inserir o código
Comment: vai que é tuuuuuua @tiosam
Comment: O ideal é postar código que possamos usar para reproduzir o problema.
Comment: Valeu sam.. funcionou
Answer: Ao clicar em um item da lista, ele irá disparar um evento que faz com que o dropdown seja fechado. Para evitar isso, use event.stopPropagation() no document apontando para a classe dos itens, que no caso é a .dropdown-item:
$(document).on('click', '.dropdown-item', function(event){
   event.stopPropagation();
});

Isso fará com que não seja disparado outro evento atribuído ao dropdown (bubbling) que faz com que ele se feche.
Comment: estou com esse erro, inseri o código acima porém não funcionou... No meu caso eu tenho vários checkbox e queria ter a liberdade de escolher eles sem ter que ficar clicando toda hora no icone do dropdown.
Answer: Sei que o tópico é antigo mas talvez ainda ajude quem estiver pesquisando esse erro hoje em dia assim como aconteceu comigo.
Mesmo na versão 5.0 do Bootstrap eu também me deparei com este erro.
A dica que eu dou é observar os links das dependências dos arquivos bootstrap.min.js.
No meu caso esse era o problema, muitas vezes além da ordem dos links você pode estar duplicando a dependência e entrando em conflito. Faça testes comentando de 1 por 1 os links e veja qual é o problema.
No meu caso era o link para o arquivo bootstrap.bundle.min.js que estava conflitando com o arquivo bootstrap.min.js, certifíque-se de deixar o arquivo correto da versão que está utilizando.
Espero ter ajudado. Abraço.
Answer: Me deparei com esse mesmo problema e a solução que encontrei foi colocar uma condicional no style do dropdown-menu, em que o estado é controlado pelo onclick do button "dropdown-toggle".
style={{ display: `${this.state.openMenu ? 'block' : 'none'}` }}

Comment: Outra alternativa que encontrei na documentação e a mais correta, é usar o ``


Partial fraction expansion - handling multiple roots

Question: I am trying to solve the partial fraction expansion of the following:
$X(z) = \dfrac{3-15z}{9z^2-6z+1}$.
So I calculated the roots of $9z^2 - 6z + 1$.
This gives $n_1 = n_2 = \frac{1}{3}$
and $9z^2-6z+1 = 9(z-\frac{1}{3})(z-\frac{1}{3})$.
Now I don't know how to deal with it.
If there were no factor $9$, I would take the approach $X(z) = \frac{A}{z-\frac{1}{3}} + \frac{B}{(z-\frac{1}{3})^2}$.
And if there were two different roots, $z_1$ and $z_2$, I'd take the approach $X(z) = \frac{A}{z-z_1} + \frac{B}{z-z_2}$.
But since neither of these two cases is what we have here, I don't know what to do.
Comment: or just use $\dfrac A {3z-1} + \dfrac B {(3z-1)^2}$
Comment: Forget about the 9, then divide everything by it at the end?
Comment: Factor out the $9$! We write $\frac{3-15z}{9(z-1/3)(z-1/3)} = \frac{3-15z}{9}\cdot \frac{1}{(z-1/3)(z-1/3)}$. And you know how to write that last factor (it's exactly as you have written). Thus you would end up with $\frac{3-15z}{9} \left(\frac{A}{z-1/3} + \frac{B}{(z-1/3)^2}\right) = \frac{3-15z}{9z^2-6z+1}$
Comment: Thanks to all of you! All your suggestions are helpful! :)
Answer: You could just use  $$\dfrac A {3z-1} + \dfrac B {(3z-1)^2}=\dfrac{3-15z}{(3z-1)^2}$$
whence   $$A(3z-1)+B=3-15z$$
so $B-A=3$ and $3A=-15$.  Can you take it from here?
Comment: Hi J. W. Tanner, thanks for your help! I didn't realize I could factor the 9. Now it's obvious. :)
Answer: You could absolutely do it your way:  \begin{align}
X(z)=\frac{3-15z}{9z^2-6z+1}&=\frac{3-15z}{9(z-\frac13)^2}\\
&=\frac19\bigg(\frac{3-15z}{(z-\frac13)^2}\bigg)\\
&=\frac19\bigg(\frac{A}{z-\frac13}+\frac{B}{(z-\frac13)^2}\bigg)
\end{align}
Not impossible, but not very nice.
Alternatively:
\begin{align}
X(z)=\frac{3-15z}{9z^2-6z+1}&=\frac{3-15z}{(3z-1)^2}\\
&=\frac{A}{3z-1}+\frac{B}{(3z-1)^2}\\
&=\frac{A(3z-1)+B}{(3z-1)^2}\\
&=\frac{3Az-A+B}{(3z-1)^2}\Rightarrow \left\{\begin{array}
& 3A &=-15\\
-A+B&=3\end{array} \right. \Rightarrow (A,B)=(-5,-2)\\
&=-\frac{5}{3z-1}-\frac{2}{(3z-1)^2}
\end{align}
Comment: Thank you for listing both options! So now I also know how to deal with the factor if it hasn't a square root in the natural numbers. This was very helpful. :)


Uri(Uri, String) constructor does not works properly?

Question: Here is a part of my code:
Uri branches = new Uri(@"https://127.0.0.1:8443/svn/CXB1/Validation/branches");
Uri testBranch = new Uri(branches, "test");

I expect testBranches will be https://127.0.0.1:8443/svn/CXB1/Validation/branches/test, but it is https://127.0.0.1:8443/svn/CXB1/Validation/test. I can not understand why Uri(Uri, string) constructor eats the last part of the path.
Comment: try `Uri branches = new Uri(@"https://127.0.0.1:8443/svn/CXB1/Validation/branches/");`
Comment: `Uri` is not a path, it does not work the same way as `Path.Combine`. http://stackoverflow.com/a/1527643/284240 (see comments)
Answer: Add a slash after branches
  Uri branches = new Uri(@"https://127.0.0.1:8443/svn/CXB1/Validation/branches/");
  Uri testBranch = new Uri(branches, "test");

Comment: Adding a slash at the end of the first url also have no effect because  Uri(string) constructor removes it. And `branches` will be `https://127.0.0.1:8443/svn/CXB1/Validation/branches`
Comment: Sorry, I've found a probem in other part of the code. Adding a slash works fine. Thank you.
Comment: Is there any official documentation for this (i.e., the trailing slash)? I couldn't find any.
Answer: The Behaviour you see is correct, because replacing the last part is a good idea if you want to change the filename.
I would add the backslash at the end of the first part. Then it is clear that this is a directory, otherwise it may be interpretated as a file.
Uri branches = new Uri(@"https://127.0.0.1:8443/svn/CXB1/Validation/branches/");
Uri testBranch = new Uri(branches, "test");
Console.WriteLine(testBranch);

Will get this output:
 https://127.0.0.1:8443/svn/CXB1/Validation/branches/test

Answer: That's the expected behaviour.
If, in a browser, you were on a page with its full URI as https://127.0.0.1:8443/svn/CXB1/Validation/branches, and if, on that page, you clicked on a link that just had an href of test, you would be taken to https://127.0.0.1:8443/svn/CXB1/Validation/test. This is how a relative URI is composed with a base URI.
On the other hand, if the first URI ended with a / then it would work as you seem to have expected.
Comment: Is there any official documentation for this (i.e., that the URI should behave in this way)? I couldn't find any.
Comment: @RovinBhandari - yes, that second bullet seems to have it covered - you remove all characters to the right of the last `/` before appending the new text.


How to change the teaser for the front page articles

Question: In my site : http://www.indiacustomercare.com  front page(which is not displaying correctly) I want to show 200 words in teaser for each article.
I've changed it in Post Settings but does not work.
What could be the reason?
Answer: You need to Edit and Save again the articles to take effect.
I know can be painful if you have hundreds of nodes. If you google about it you will find scripts to do it like this
http://befused.com/drupal/script-update-drupal-teasers
Or use the module retease http://drupal.org/project/retease
I advice you to take a database dump before testing these solutions, just in case.
Comment: I've done it but it does not change the teaser of my front page: http://www.indiacustomercare.com/blogs/admin . Previously this was (/node) was the front page but now I've assigned an article to be the front page. Pl. see the link, I've changed the articles and saved them, cleared the caches. But still it does not work!
Comment: Are you using the tag   inside the node content? This will override that setting.
Comment: no nothing. This issue surfaced within a month only. Previously it was working fine.
Answer: With views module you can customize look of front page how ever you wish. You can style predefined "front-page" view or make your custom view and make front page of it.
In view, include field teaser (and title, post date etc.).
Trim output of teaser to any number of characters you like and thats it.
I like to exclude HTML tags from output as well so images, flash and such don't brake my layout
Hope this helps.
Comment: Well first I should find the problem than look for alternative solution.


Finding Number of Zeros in the First Quadrant of a Complex Polymomial

Question: I am trying to determine the number of roots of $p(z) = z^6 + 4z^4 + z^3 + 2z^2 + z + 5$ in the first quadrant. I I understand that one does this by finding the change in argument of $p(z)$ over the boundary of the quarter disc of radius $R$ (for large $R$) centered at the origin. I found the change over the real axis and the circular arc, but I don't understand how to find the change over the imaginary axis from $iR$ to $0$.I consulted my book but found the discussion very confusing and not very rigorous. I cou use some help.
Note that $p(it) = -t^6 + 4t^4 - 2t^2 + 5 + i(-t^3 + t)$, where $0 \le t \le R$. Because $-t^6$ dominates the real part, and $-t^3$ dominates the imaginary part, we see that $p(iR)$ lies in the third quadrant.
Not exactly sure where in the 3rd quadrant it is, so I can't say exactly what $\arg p(iR)$ is, but whatever I guess. Then from my understanding I am suppose to find the nonnegative zeros of the real and imaginary part and track where it crosses the real and imaginary axis, and then look at it's final position. But this how can I calculate the argument change if I don't know exactly where these points are?
$p(0) = 5$, so it ends up in the first quadrant. According to a solution I found, the change in argument over the imaginary axis is $\cong \pi$, but I don't see it for some reason. I don't like these estimates.
Answer: There is not too much more to say, and what little it takes is basically Calculus I curve-sketching analysis. Observe that when $t>1$, $p(it)$ is in the lower half-plane and, as $t\to\infty$, $\arg(p(it))\to -\pi$, since the slope for large $t$ is approaching $0$. On the interval $[0,1]$, $p(it)$ starts and ends on the positive real axis, staying in the first quadrant between. Thus, $\Delta\arg_{[0,i]} p(z)=0$. Since $p(z)$ is in the second and third quadrants for $t>1$, we conclude that $|\arg(p(it)) - \arg(p(i))|<\pi$ for all $t>1$. Thus $\Delta_{[0,R]}\arg f(it)$ approaches $-\pi$ as $R\to\infty$. Now just turn everything upside-down.


Qt e Android - Pegar caminho de uma imagem da galeria

Question: Estou desenvolvendo um código para pegar uma imagem da Galeria do Android. Estou usando QtAndroid para escrever em Qt um código equivalente ao java.
Eu já abri a galeria, selecionei a imagem and e recebi o caminho, mas o retorno é o MediaColumn do arquivo e eu preciso do caminho absoluto.
Como eu posso pegar o caminho absoluto do arquivo usando QAndroid para escrever no Qt um código equivalente ao Java?
Aqui está o código:
imagepickerandroid.h
#ifndef IMAGEPICKERANDROID_H
#define IMAGEPICKERANDROID_H

#include <QObject>
#include <QtAndroidExtras>

#include <QDebug>

class imagePickerAndroid : public QObject, public QAndroidActivityResultReceiver
{
    Q_OBJECT

public:
    imagePickerAndroid();

    void buscaImagem();

    virtual void handleActivityResult(int receiverRequestCode, int resultCode, const QAndroidJniObject & data);

signals:
    void imagemCaminhoSignal(QString);
};

#endif // IMAGEPICKERANDROID_H

imagepickerandroid.cpp
#include "imagepickerandroid.h"

imagePickerAndroid::imagePickerAndroid()
{

}

void imagePickerAndroid::buscaImagem()
{
    QAndroidJniObject ACTION_PICK = QAndroidJniObject::fromString("android.intent.action.GET_CONTENT");
    QAndroidJniObject intent("android/content/Intent");
    if (ACTION_PICK.isValid() && intent.isValid())
    {
        intent.callObjectMethod("setAction", "(Ljava/lang/String;)Landroid/content/Intent;", ACTION_PICK.object<jstring>());
        intent.callObjectMethod("setType", "(Ljava/lang/String;)Landroid/content/Intent;", QAndroidJniObject::fromString("image/*").object<jstring>());
        QtAndroid::startActivity(intent.object<jobject>(), 101, this);
        qDebug() << "OK";
    }
    else
    {
        qDebug() << "ERRO";
    }
}

void imagePickerAndroid::handleActivityResult(int receiverRequestCode, int resultCode, const QAndroidJniObject &data)
{
    qDebug() << "Trabalha com os dados";

    jint RESULT_OK = QAndroidJniObject::getStaticField<jint>("android/app/Activity", "RESULT_OK");
    if (receiverRequestCode == 101 && resultCode == RESULT_OK) {
        QString imagemCaminho = data.callObjectMethod("getData", "()Landroid/net/Uri;").callObjectMethod("getPath", "()Ljava/lang/String;").toString();
        emit imagemCaminhoSignal(imagemCaminho);

        qDebug() << imagemCaminho;
    }
    else
    {
        qDebug() << "Caminho errado";
    }
}

Comment: Em geral você recebe uma URL com `content://` do android, não um caminho absoluto. A unica forma de realmente ler isso é usando a API em java, que envolveria criar um `java.io.File` para ler a URL. Não muito prático, mas acredito ser a unica forma que sempre funcionaria.
Comment: Pois é. O problema é que não consigo exibir a imagem no `QML` usando somente esta referência. Como eu posso fazer isto?
Comment: Uma opção é usar a api do java para ler a url e escrever em um arquivo no seu diretório de cache, e então ler de lá. Ou ainda: ler o arquivo para um `byte[]` na memória e passar isso para o construtor de `QPixmap`  para carregar a imagem e repassar ao QML. Não tenho nenhuma solução realmente boa.
Comment: E soluções como esta desta link https://github.com/eswarm/AutoSortD/blob/master/androidfiledialog.cpp ?
Answer: Respondendo minha própria pergunta
Aqui está o código para pegar o caminho completo de uma imagem da galeria do Android usando código em Qt equivalente ao Java:
#include "imagepickerandroid.h"

imagePickerAndroid::imagePickerAndroid()
{

}

void imagePickerAndroid::buscaImagem()
{
    QAndroidJniObject ACTION_PICK = QAndroidJniObject::getStaticObjectField("android/content/Intent", "ACTION_PICK", "Ljava/lang/String;");
    QAndroidJniObject EXTERNAL_CONTENT_URI = QAndroidJniObject::getStaticObjectField("android/provider/MediaStore$Images$Media", "EXTERNAL_CONTENT_URI", "Landroid/net/Uri;");

    QAndroidJniObject intent=QAndroidJniObject("android/content/Intent", "(Ljava/lang/String;Landroid/net/Uri;)V", ACTION_PICK.object<jstring>(), EXTERNAL_CONTENT_URI.object<jobject>());

    if (ACTION_PICK.isValid() && intent.isValid())
    {
        intent.callObjectMethod("setType", "(Ljava/lang/String;)Landroid/content/Intent;", QAndroidJniObject::fromString("image/*").object<jstring>());
        QtAndroid::startActivity(intent.object<jobject>(), 101, this);
        qDebug() << "OK";
    }
    else
    {
        qDebug() << "ERRO";
    }
}

void imagePickerAndroid::handleActivityResult(int receiverRequestCode, int resultCode, const QAndroidJniObject &data)
{
    jint RESULT_OK = QAndroidJniObject::getStaticField<jint>("android/app/Activity", "RESULT_OK");
    if (receiverRequestCode == 101 && resultCode == RESULT_OK)
    {
        QAndroidJniObject uri = data.callObjectMethod("getData", "()Landroid/net/Uri;");
        QAndroidJniObject dadosAndroid = QAndroidJniObject::getStaticObjectField("android/provider/MediaStore$MediaColumns", "DATA", "Ljava/lang/String;");
        QAndroidJniEnvironment env;
        jobjectArray projecao = (jobjectArray)env->NewObjectArray(1, env->FindClass("java/lang/String"), NULL);
        jobject projacaoDadosAndroid = env->NewStringUTF(dadosAndroid.toString().toStdString().c_str());
        env->SetObjectArrayElement(projecao, 0, projacaoDadosAndroid);
        QAndroidJniObject contentResolver = QtAndroid::androidActivity().callObjectMethod("getContentResolver", "()Landroid/content/ContentResolver;");
        QAndroidJniObject cursor = contentResolver.callObjectMethod("query", "(Landroid/net/Uri;[Ljava/lang/String;Ljava/lang/String;[Ljava/lang/String;Ljava/lang/String;)Landroid/database/Cursor;", uri.object<jobject>(), projecao, NULL, NULL, NULL);
        jint columnIndex = cursor.callMethod<jint>("getColumnIndex", "(Ljava/lang/String;)I", dadosAndroid.object<jstring>());
        cursor.callMethod<jboolean>("moveToFirst", "()Z");
        QAndroidJniObject resultado = cursor.callObjectMethod("getString", "(I)Ljava/lang/String;", columnIndex);
        QString imagemCaminho = "file://" + resultado.toString();
        emit imagemCaminhoSignal(imagemCaminho);
    }
    else
    {
        qDebug() << "Caminho errado";
    }
}


Como remover os dias do DatePickerDialog?

Question: Como eu posso remover os dias do DatePickerDialog eu queria um calendário só com ano e mês, se alguém souber uma forma de fazer isso e poder me ajudar?
Answer: É possível, encontrei um método personalizado uma vez que remove o dia, porém não sei como ele se comporta com as versões mais atuais do DatePicker das novas versões do android.
private DatePickerDialog createDialogWithoutDateField() {

 Calendar calendar = Calendar.getInstance();
        DatePickerDialog dpd = new DatePickerDialog(this, null, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));

    try {
        java.lang.reflect.Field[] datePickerDialogFields = dpd.getClass().getDeclaredFields();

        for (java.lang.reflect.Field datePickerDialogField : datePickerDialogFields) {

            if (datePickerDialogField.getName().equals("mDatePicker")) {
                datePickerDialogField.setAccessible(true);
                DatePicker datePicker = (DatePicker) datePickerDialogField.get(dpd);
                java.lang.reflect.Field[] datePickerFields = datePickerDialogField.getType().getDeclaredFields();

                for (java.lang.reflect.Field datePickerField : datePickerFields) {
                    Log.i("test", datePickerField.getName());

                    if ("mDaySpinner".equals(datePickerField.getName())) {
                        datePickerField.setAccessible(true);
                        Object dayPicker = datePickerField.get(datePicker);
                        ((View) dayPicker).setVisibility(View.GONE);
                    }
                }
            }
        }
    }
    catch (Exception ex) {
    }
    return dpd;
}

como esse método retorna um objeto DatePickerDialog, você pode passar para o seu próprio date picker ou simplesmente chamar o show():
createDialogWithoutDateField().show();


Odds ratio from logistic regression isn't negative when it should be

Question: I just recently started working with logistic regression, and I'm struggling with the interpretation of the results.
Say I have brain disease (BD) as an outcome and gestational age (GE) as an explanatory variable. The OR is 0.99. I have used R to calculate this:
<code>gl1 <- glm(BD~GE, data, family = "binomial")
</code>
How do I know what my reference group is in this case? Does the model pick a reference for me? Individuals with disease is explained by 1, and individuals with no disease are 0. The clinical theory is that individuals with a low GE is more likely to get BD.
But this doesn't make sense to me in this case.  Every time I Google this issue, I get: "every increase of GE is associated with 0.99 times the odds of BD". But shouldn't it be opposite? That is, every decrease of GE, is associated with 0.99 time the odds of BD?
Comment: Welcome to CV.  Have you [searched our site for similar questions?](https://stats.stackexchange.com/search?q=logistic+regression+odds+ratio+reference+group)  You can find many posts about this topic here.
Comment: Show the results of `summary(gl1)` and provide the codebook's definition of GE: what units or thresholds are used? Also verify if the OR is on the natural scale or log scale.
Answer: It may help to read more about how odds work.  A place to start might be: Interpretation of simple predictions to odds ratios in logistic regression.
To answer your specific question, $0.99$ is a negative relationship.  Every time you increase gestational age by $1$ unit (week?) the odds of having a brain disease is multiplied by $0.99$.  That's less than $1.0$, so the odds are decreasing.  To illustrate, let's imagine the odds of brain disease for babies born at $30$ weeks is $1.0$.  Now, let's see what happens to the odds of brain disease as babies are born later (less early):
<code>      week  odds(BD)
 [1,]   30 1.0000000
 [2,]   31 0.9900000
 [3,]   32 0.9801000
 [4,]   33 0.9702990
 [5,]   34 0.9605960
 [6,]   35 0.9509900
 [7,]   36 0.9414801
 [8,]   37 0.9320653
 [9,]   38 0.9227447
[10,]   39 0.9135172
[11,]   40 0.9043821
</code>
The odds are in fact decreasing.
Comment: I have a second question that I have posted here https://stats.stackexchange.com/questions/608755/decreasing-odds-ratio-when-adding-more-cases if you have time to answer (ofc if you know the answer), I would really appreciate it! Thanks!


Copiar determinado número de arquivos em Python

Question: Olá, tudo bem?
Estou iniciando na programação, estou tentando automatizar algumas tarefas no meu ambiente de trabalho e tenho a seguinte necessidade:
Efetuar a cópia de x arquivos (x será fornecido pelo user) para outro diretório... fiz algumas pesquisas e desenvolvi algo próximo a isso:
import shutil
import os
origem = r"C:/Copiador/de/"
destino = r"C:/Copiador/para/"
lista = os.listdir(origem)
x = 0
num_files = 20 #aqui seria o valor que o user iria fornecer
while x < num_files:
    origemtotal = origem + lista[x]
    destinototal = destino + lista[x]
    shutil.move(origemtotal, destinototal)
    print(x, '-', lista[x])
    x +=1;

A questão é que, quando o num_files é maior que o número de arquivos na origem, o programa retorna erro :
IndexError: list index out of range
Eu acredito que é até esperado, pois ele não achou o índice que procurava pra efetuar a cópia...
Porém não consegui pensar em um modo de caso o num_files seja maior que a quantidade de arquivos na origem, ele efetuar a cópia da quantidade de arquivos na origem e finalizar a execução.
Talvez eu esteja errando em algo básico que não esteja vendo... Podem me ajudar?
Comment: Guto,
Obrigado pela ajuda, funcionou tranquilamente...

        if lista_len < num_files:
            num_files = lista_len
        else:
            pass

Eu só adicionei isso antes do While e agora funcionou sem problemas.
Comment: Seria interessante você validar se esse `num_files` é maior que a quantidade de arquivos. Caso sim, o `num_files` recebe o número real de arquivos na origem.
Comment: Coloquei como resposta. Se puder aceitar eu agradeço.
Answer: Seria interessante você validar se esse num_files é maior que a quantidade de arquivos. Caso sim, o num_files recebe a quantidade real de arquivos na origem.
Segue exemplo abaixo:
import shutil
import os
origem = r"C:/Copiador/de"
destino = r"C:/Copiador/para/"
lista = os.listdir(origem)
num_files = 5 #aqui seria o valor que o user iria fornecer
if len(lista) < num_files:
    num_files = len(lista)

print(num_files)

# loop de cópia


$\forall\epsilon>0, \exists N\in\Bbb N$ such that $\forall n>m\ge N, a_n-a_m<\epsilon$. Prove that $a_n$ converges to a real limit or to $-\infty$

Question: Assume $(a_n)_{n=1}^\infty$ has the following property: For all $\epsilon>0$ exists some $N\in\Bbb N$ such that for every $n>m\ge N$, $a_n-a_m<\epsilon$. We want to prove that $a_n$ converges to a real limit or to $-\infty$.
This condition implies that $a_n$ is bounded above.
So, I tried to show what happens if it's bounded below or unbounded below.
When bounded below, by Bolzano-Weierstrass $a_n$ has some convergent subsequence, $a_{n_k} \rightarrow L$, so for all $k\ge K$ for some $K\in \Bbb N$, $|a_{n_k}-L|<\epsilon \iff -\epsilon<a_{n_k}-L<\epsilon$ .
I tried to use this to prove the convergence of the entire sequence but it didn't work -  I tried to take some $n>n_k>max(N, n_K)$, $a_n-L=a_n-a_{n_k}+a_{n_k}-L <2\epsilon$, but now I can't get the left inequality right. This makes me question my entire process. Maybe I should've gone about this a different way?
Answer: Your approach is fine.
If $(a_n)_{n\in\mathbb N}$ is undounded below, Take $M<0$. The inequality $a_n<M-1$ holds infinitely often and there is a $N\in\mathbb N$ such that $$n>m\geqslant N\implies a_n-a_m<1.$$Therefore, if $n\gg1$, $a_n<(M-1)+1=M$. This proves that $\lim_{n\to\infty}a_n=-\infty$.
Otherwise, let $L=\liminf_na_n$. Take $\varepsilon>0$. Then the inequality $|a_n-L|<\frac\varepsilon2$ hold infinitely often and $a_n>L-\frac\varepsilon2$ if $n\gg1$. Now, take $N\in\mathbb N$ such that$$n>m\geqslant N\implies a_n-a_m<\frac\varepsilon2.$$Then, if $n\gg1$, $|L-a_n|<\varepsilon$.
Comment: I don't understand the sentence beginning with "Therefore".
Comment: @DanielWainfleet I suppose that that's due to a typo in the previous sentence: I wrote "$a_nm\geqslant M\implies a_n-a_m<1$. Take $m\geqslant N$ such that $a_m<M-1$. Then,$$n\geqslant m\implies a_n=a_n-a_m+a_m<1+M-1=M.$$
Comment: Ah! I think I get it now. I should think of this particular $a_m$ as a sort of an axis, as for all the following $n$'s the condition holds. Thank you so much for the clarification and for your time!
Comment: @Noa I'm glad that I could help.


Changing the order of integration of these two double integrals.

Question:
$\int^2_1dx\int^{\sqrt{2x-x^2}}_{2-x}f(x,y)dy$
$\int^e_1dx\int^{ln(x)}_{0}f(x,y)dy$

My attempts:
For the first Integral:
I can see that $y=\sqrt{2x-x^2}$ defines half of a circle with radius $1$.
And $2-x$ is basically a line, I drew them, and I can see that if I wanted to change the order of integration, $y$ will be between $0$ and $1$, and now my problem is $x$, I need to get what is the upper $x$ from this equation $y=\sqrt{2x-x^2} \Longrightarrow y^2=2x-x^2$, but how do I keep going? I'm not succeeding to get $x$ from that equation.

For the second integral:
I can see the area between $y=ln(x)$, $x=e$, $x=1$.
In order to change the order of integration, I must see the borders of $y$, and that's the intersection between $y=ln(x)$ and $x=e$, which is $y=1$.
So the integral will be:
$\int^1_0dy\int^{e}_{e^y}f(x,y)dx$
Any help and feedback is really appreciated, thanks in advance!
Answer: The second one is correct.
For the first one, yes you are right on bound of $y$.
For $x$, it is bound below by line $x+y = 2$ so $x \geq 2 - y$.
For upper bound,
$y=\sqrt{2x-x^2} \implies x^2 - 2x + y^2 = 0$
Rewriting, $(x-1)^2 = 1 - y^2 \implies x = 1 \pm \sqrt{1-y^2}$
Please note that for any given $y \ne \pm1$, there are two values of $x$ on the circle, one to the left of $x = 1$ and one to the right of $x = 1$ as the circle is centered at $(1, 0)$. Here we are interested in,
$x = 1 + \sqrt{1-y^2}$
So bounds are $ 2 - y \leq x \leq 1 + \sqrt{1-y^2}, 0 \leq y \leq 1$


Symfony / Sonata Admin: List form on Edit form

Question: I have a one (category) to many (product) relationship set up, and I'd like to have a list of products show up at the bottom of the edit category page.
It seems like this would be a common thing to do, but I haven't found any way to do it (or any examples of it).  I have managed to get the product to display using sonata_type_collection but that gives me a whole edit form for the Product, when I really just want a list of products associated with the category.
Two questions here, really:
Is this possible?
Is it discouraged (which would explain the lack of examples)?  If so, why?
Comment: What do you exactly mean with "have a list of products" ? Is this general information irrelevant to the form you are submitting or input for the category you are editing?
Comment: The info isn't relevant to the submission of the form, but I want to provide direct links to the relevant products at the bottom of a category detail page.  E.g. if the category is iPhone, then I'd like to have a list of iPhone products at the bottom of the page.
Answer: The fastest way to do what you are looking for is overriding the edit template. At your admin serivce declaration you can do so:
services:
    sonata.admin.mail:
        class: %sonata.admin.category.class%
        tags:
            - { name: sonata.admin, manager_type: orm, group: "Categories", label: "Category" }
        arguments:
            - ~
            - %skooli.category.class%
            - ~
        calls:
            - [ setTemplate, ["edit", "AcmeAdminBundle:CategoryAdmin:edit.html.twig"] ]

Then, under AcmeBundle/Resources/views/CategoryAdmin/edit.html.twig you can have something like this:
{% extends 'SonataAdminBundle:CRUD:base_edit.html.twig' %}
{# Override any block from the parent view if necessary #}
{% block products %}

    {% for product in object.products%}

{{ product.name }}

    {% endfor %}

{% endblock products %}

Comment: Thanks. This looks like it's very close to what I'm trying to do.  The only problem I'm having is that I currently have

`->add('product','sonata_type_collection', array(
                    'type_options' => array(
                        'delete' => false,
                        'read_only' => true,
                        'btn_add' => false,
                    )
            ))`
in my CategoryAdmin.php configureFormFields function, and despite trying a few different variations, I can't find anything that'll cause it to pull in that new custom template.
Comment: The template is related to your Category Admin not your Product Admin
Comment: The template is at Resources/views/CategoryAdmin/edit.html.twig, and in my services.yml I have sonata.admin.category:....

But in CategoryAdmin.php in configureFormFields I have the chained calls to add() that determine what shows up in the edit form.  If I don't put anything related to 'product' in there, the form renders without the list I was hoping for, and all of the attempts I've made to include an add() for products hasn't panned out.

This is my first attempt at a custom template, so I might be missing something fundamental here.
Comment: Are you trying to create a Category or Edit an existing Category which you know for sure that has been related to some Products?
Comment: I'm trying to edit an existing Category, which has Products associated with it.  I'd like to have all of those products show up in a list at the bottom of the page.

See this example I cobbled together: http://i.imgur.com/wZv2qpu.jpg
Comment: I never did get this working, and have given up for now, but I'm accepting this answer because I'm convinced that this is what I'd have to do to get it working.
Answer: In your original question you were talking about the edit template of the category. In your comment you want the list to appear in the show action.
The latter is easy. As soon as you add your relation to your showFields action they will be shown:
use Sonata\AdminBundle\Show\ShowMapper;

class CategoryAdmin extends Admin
{
    protected function configureShowFields(ShowMapper $showMapper)
    {
        $showMapper
            ->add('products')
        ;
    }
}

If you don't like the look you can create a custom template. This will work for show and edit:
https://sonata-project.org/bundles/admin/master/doc/reference/action_show.html#setting-up-a-custom-show-template-very-useful
Comment: Thanks for the reply, and apologies for the imprecise wording.  What I'm looking for is a list of relevant Products when I view the edit screen for a given category (e.g. foobar.com/bundle/category/1234/edit).
Comment: That sounds like strange request since most of the time you want to inline edit child entities instead of only showing them. But you can use a custom edit template then.
Comment: Inline editing of child entities is a possibility down the road, but for now I'd just like to have a coherent representation of them.  The default display is the entire editform for all Products associated with the Category, and this is definitely not what I'm looking for.

I think overriding the template is what I need to do, but so far I haven't been able to get that to work. This seems to be close: http://php-jotter.blogspot.com.es/2013/01/override-display-of-sonatacollectiontyp.html but it's not working as-is, and I don't have the knowledge to tweak it.
Comment: I now have a similar task. I need to show the list view of existing items in the edit form for a new item. I just realized that you can use blocks that were meant for the dashboard page on every template - even the edit template. I will post a gist example soon!
Comment: Thanks @webDEVILopers - I'd love to see that gist when it's done.
Comment: This is my "Recent Contracts" custom list view example so far: https://gist.github.com/webdevilopers/11520ffd82d762c4ca72 - Still have to find out how to pass parameters to the execute method in order to pass a categoryId for instance. @MattBoutet
Comment: And this is a nice example for using a ProductId resp. CategoryId: https://gist.githubusercontent.com/ronanguilloux/0676257355c3e6bf3005/raw/837f76cdc112c7c46c1a4eb7ff2b79276a6bf41c/ProductBlockService.php


Random effects in GAM

Question: I'm modelling some biological function, outcome, in patients over 8 hours.  Over time, I measure two additional covariates x and w.  Shown below is a sample of the data.  Only show the first three measurements per patient.
I'm interested in estimating the effects of x and w and their interaction on outcome.  I plan to use a gam to take care of the time effect.
My question is: do I need to model the effects of x and w as a random effect this they change in time and I have multiple observations of these covariates per patient?  If so, what is the appropriate way to specify this model with a gam?
Currently, I do something like
gam(outcome ~ s(time, by=patient, bs = 'gp') + x*w, data= data)

I can provide more details as necessary, including more data.

Data
tibble::tribble(
     ~patient,     ~time,      ~x,         ~w,          ~outcome,
            1,     3.245,     87.738,    38.571,         19.006,
            1,     8.245,     80.104,    39.958,         19.441,
            1,    13.245,     76.206,    40.912,         19.046,
            2,     5.335,     80.731,    56.822,         32.689,
            2,    10.335,     83.174,     52.52,         32.654,
            2,    15.335,     81.507,    52.374,         32.589,
            3,     4.965,     68.584,    111.69,         37.621,
            3,     9.965,     68.544,   111.751,         37.762,
            3,    14.965,     68.979,   112.118,         37.451,
            4,     20.38,     108.19,    78.406,         44.792,
            4,     25.38,    111.694,    81.583,         49.085,
            4,     30.38,    111.312,    80.914,         44.741,
            5,     6.295,     72.692,    52.059,         42.737,
            5,    11.295,     75.155,     49.55,         42.788,
            5,    23.533,     78.084,    49.131,         41.934,
            6,     7.075,     79.788,    69.537,         25.219,
            6,    12.075,     79.652,    68.692,         25.427,
            6,    17.075,     78.746,    69.277,         25.635,
            7,     3.335,      80.44,    34.839,         61.974,
            7,     8.335,     79.318,    34.325,         56.651,
            7,    13.335,     79.624,    34.346,          53.32,
            8,      9.92,     96.634,    64.871,         44.481,
            8,     14.92,    100.979,    67.194,         43.645,
            8,     19.92,     97.952,    67.456,         43.934,
            9,    74.635,      98.08,    83.723,         39.156,
            9,    79.635,     97.779,    85.049,         38.958,
            9,    84.635,     96.881,    88.736,         38.911,
           10,    70.155,     73.583,    53.296,         28.519,
           10,    75.155,     73.332,    52.935,         28.705,
           10,    80.155,     73.174,    51.781,         29.405,
           11,      3.17,     80.425,    45.579,         27.271,
           11,      8.17,     86.442,    39.839,         27.095,
           11,     13.17,     80.377,    42.182,         28.844,
           12,      3.23,     53.399,    75.199,         26.986,
           12,      8.23,     64.986,    63.395,         17.803,
           12,     13.23,     65.306,    68.421,         15.915
     )

Answer: I'm reasonably sure you don't want to use the gp basis for this; when used with the defaults, mgcv fits a smooth with a Gaussian Process basis comprising correlation functions as the basis functions where the effective range parameter is set to essentially be the largest observable time difference between any two observations. If you must use the gp basis then you probably want to profile over the effective range parameter, fitting a new GAM for a grid of values over the set of values for the effective range parameter you want to optimise for.
Anyway, you really don't need to do this.
You are fitting one option for group-level splines (the by variable smoother) but you could take an approach that is slightly more a "random effect" than this by using the fs basis. The main difference is that in the fs basis, all the splines (one per patient) have the same smoothness parameter (so the same wiggliness) though the don not need to have the same shape. The by variant estimates a separate smoothness parameter per patient, which essentially means you are fitting an entirely separate smoother for each patient. Both are acceptable, there's just a lot more parameters (length(levels(patient)) - 1 more) to estimate for the by variant.
If you think the effect of x (or w) changes over time then you should include terms in the model for that. There are a number of ways in which this can be done, including

a varying coefficient model-like approach, wherein the effect of x is linear but varying smoothly with some other covariate, in your case time. Think of this as a linear regression of y ~ x where the slope of the linear regression line changes smoothly over time.
For this kind of term, use s(time, by = x) and so on in place of the x and w parametric terms.
If you also want the interaction to change smoothly, then I think you need to create a new variable xw which is the product of x and w, and then use xw as the variables passed to by.
A full smooth effect of x on outcome that smoothly interacts with time. These are produced via tensor products and the te() function. A bivariate interaction would be
+ te(x, time)

and the full blown three-way would be
+ te(x, w, time)

but to smooth in high dimensions like this you really need a lot of data.

To give more specifics you'll need to explain more about how you view the effect of x, w and x:w changing over time.

Random effects in GAM


Find $\|A\|$ for the operator $A$

Question: Let $C[0, 1]$ be the linear space of all continuous functions on the interval $[0, 1]$ equipped with the
norm $\|f\| = \max_{0≤x≤1} |f(x)|$. Let $K(x, y)$ be a fixed function of two variables, continuous on the
square $[0, 1] \times [0, 1]$, and let $A$ be the operator defined by $$Af(x) = \int^{ 1}_0 K(x, y)f(y) dy.$$  For $K(x, y) = x$, find $\|A\|$.
Proof idea:
$A$ is a continuous linear operator mapping $C[0,1]$ on itself. Since $A$ is linear from linearity of integrals. Also $A$ is bounded since $K$ is continuous on a compact set $[0,1]\times[0,1]$ and thus bounded by some $M$. Therefore,
$$|Af(x)|=\left|\int_0^1K(x,y)f(y)dy\right|\leq \int_0^1|K(x,y)||f(y)|dy\leq\int_0^1M\|f\|=M\|f\|.$$
Now, if I am correct about the above,  $|Af(x)|\leq x\|f\|$ for $K(x,y)=x$.
$$\|A\|=\sup_{f(x)\neq0}\frac{\|Af(x)\|}{\|f(x)\|}=\sup_{f(x)\neq0}\frac{\|Af(x)\|}{\|f(x)\|}\leq\|f\|?$$ is $\|A\|=\sup|Af(x)|$? Is the final answer an inequality? I am confused about this.
Comment: The final answer is a specific positive real number, a supremum of a bounded set. Since $1$ bounds $K$, you also already know that this supremum is $\le 1$. If you find a function (or a sequence of functions) of norm $1$  that achieves (converges to) $1$, then you proved $\|A\|=1$.
Comment: Is this part two of a two-part problem, with the first part being "Show $A$ is bounded"?  You have a lot of extra work prior to "Now, if I am correct about the above", and then $|Af(x)| \leq x \|f\|$, while true, is currently unjustified.
Comment: Yes, you are correct @BrianMoehring. Part a was: Prove that A is a continuous linear operator mapping C[0, 1] into itself.
Answer: By rearranging what you have written (and remembering to divide by the norm of $f$ in your expression), you have shown the inequality $\|A\|\leq 1$, and in this instance, this is actually the norm.
To see this, note that the norm is achieved by $Af$, for $f\equiv 1$.
Comment: $$\|A\|=\sup_{f(x)\neq0}\frac{\|Af(x)\|}{\|f(x)\|}\leq||f||$$ since $||Af(x)||=sup_{f(x)\leq1}|Af(x)|=sup_{f(x)=1}|Af(x)|$ and $||f(x)||=sup_{x=1}|f(x)|$ then $||A||=1$.
Answer:
Is $\|A\|=\sup|Af(x)|$?

This isn't even clear what you mean by the supremum, but I'm apt to say no*.  The definition is $$\|A\| = \sup_{\|f\|=1} \|Af\| = \sup_{f\neq 0} \frac{\|Af\|}{\|f\|}$$ Since you also have the norm
$$\|Af\| = \max_{0 \leq x \leq 1} |Af(x)| = \sup_{0 \leq x \leq 1} |Af(x)|$$
floating around, you need to be more clear about your intentions when you write the supremum.
[*If you meant $\|A\| = \sup_\limits{\|f\|=1 \\ 0 \leq x \leq 1} |Af(x)|$, then the answer would be "yes", but it would be an irregular use that doesn't match anything else you've written]

Is the final answer an inequality?

If you fix a couple notational issues (and one error) in your solution, you'll have shown an inequality $\|A\| \leq 1$. However, this is not the final answer, since you are tasked with actually computing $\|A\|$.

Let's clean up the notation.  I'll run through a full solution (in particular, note where I've included $x$ and where I didn't):
First, setting $K(x,y)=x$, we have
$$|Af(x)| = \left|\int_0^1 xf(y)\,dy\right| \leq x\int_0^1|f(y)|\,dy \leq x\int_0^1\|f\|\,dy =  x\|f\|$$
Therefore
$$\|Af\| = \max_{0\leq x \leq 1}|Af(x)| \leq \max_{0\leq x \leq 1} x\|f\| = \|f\|$$
and
$$\|A\| = \sup_{f \neq 0}\frac{\|Af\|}{\|f\|} \leq 1,$$
To show the other direction, we need to go back to the definition.  Noting that $f_0(x) = 1$ implies $\|f_0\| = 1$ and $Af_0(x) = x$, we have
$$\|A\| \geq \frac{\|Af_0\|}{\|f_0\|} = \|Af_0\| = \max_{0 \leq x \leq 1} |Af_0(x)| = \max_{0 \leq x \leq 1} |x| = 1$$
so $\|A\| = 1$.

Find $\|A\|$ for the operator $A$


Como ativar o VirtualEnv no prompt de comando do Windows?

Question: No Linux eu consigo executando
. bin/activate

Tentei o mesmo comando no Windows, mas não funcionou. Como faço para ativar o virtualenv no Windows?
Comment: Olá, Ana. Importante [edit] sua pergunta e fornecer um [mcve]. Veja também o  [Guia rápido sobre como fazer perguntas](https://pt.stackoverflow.com/help/how-to-ask)
Answer: Quando você cria o VirtualEnv pelo Windows, a estrutura de pastas criada será:
D:\projeto\venv
│   pyvenv.cfg
│
├───Include
│       ...
├───Lib
|       ...
└───Scripts
        activate
        activate.bat
        Activate.ps1
        deactivate.bat
        easy_install-3.9.exe
        easy_install.exe
        pip.exe
        pip3.9.exe
        pip3.exe
        python.exe
        pythonw.exe

Ou seja, o caminho que tentou executar, bin/activate, não existirá. Mesmo se existisse não funcionaria, pois esse arquivo possui instruções para a configuração de ambientes Linux.
No Windows, você pode utilizar o arquivo activate.bat ou ainda o activate.ps1 se estiver utilizando o PowerShell.
Exemplo:
D:\projeto> .\venv\Scripts\activate.ps1
(venv) D:\projeto>


Total number of illegal states in Tower of Hanoi

Question: I have found that there are 27 (3^n) legal states in the 3-disk, 3-peg puzzle.
I was wondering if there's a way to calculate the number of illegal configurations or the amount of all possible configurations (and then deduct the legal ones).
Thank you!
Comment: What do you mean by ilegal states?
Comment: a state where a disk is placed upon a smaller disk
Comment: Try using a combination tree, there can be 1 disk on each peg, 2 on the first and 1 on the second or third, and so on, in each of this states there are 6 configurations, then sum all of them. I can not find an easier way right now.
Answer: In the general case, with $n$ disks and $k$ posts, there are $$n!\binom{n+k-1}{k-1}$$ possible positions.  To see this note that we can create all positions but arranging the disks in a line in one of $n!$ ways, then splitting the row into $k$ groups and placing the disks in each group on the corresponding peg, in the order they lie in the row.  There are $\binom{n+k-1}{k-1}$ ways to do this, by stars and bars.  Since there are $k^n$ legal positions, the number of illegal positions is $$n!\binom{n+k-1}{k-1}-k^n$$
When $n=k=3$ this gives $33$.
Answer: To calculate the total number of states, we consider cases on how many discs there are in one stack.
If there are three discs in one stack, there are five ways to stack them illegally, and three places for the stack to go, leading to $15$ illegal positions.
If there are two discs in one stack and one in another, there are three ways to choose two discs, exactly one order to make them illegal, and then six ways to choose how to place the stack of size one and the stack of size two, leading to $18$ illegal positions.
If there are three stacks of one disc each then the position is legal.
So there are $33$ illegal positions.


AngularJS and option change text

Question: I have a select lists with currencies. Its made like this:
<select ng-model="model.currency">
    <option value="USD">Amercian Dollars</option>
    <option value="EUR">Euro</option>
</select>

I need to find a way so that the option text changes when I select an option. I tried an ng-change but I cant find a way to set the option text. Just to clarify:

The value should be the currency code
The selected text shown should be the currency code
If I click on my select the list of options should be the fullname

So whats missing in the scenario above is to set the value as text when selecting it.
Answer: select is a special directive in AngularJS. You need to declare ng-options and set options in controller.
Comment: yepp, I done that in other places, but still I dont know how to display the value when selected and the text when the select is active (eg. clicked)
Comment: create jsFiddle with issue and I will show you how to solve it.
Comment: When I select American dollars I want the selected option in the select to say USD. When I select Euro I want the selected option to say EUR (eg. replace American dollars to USD and Euro to EUR when I select it. I only want the full name in the list, but short name to display when selected)
Comment: so do it, what are u waiting for? I'm not your employee, go learn by example and do what u need.

AngularJS and option change text


In the figure, OB is the perpendicular bisector of line segment DE

Question: In figure, $OB$ is perpendicular bisector of line segment $DE$, $FA$ perpendicular to $OB$ and $FE$ intersects $OB$ at the point $C$, then find the sum $\displaystyle \frac{OC}{OA}+\frac{OC}{OB}$
I have proved the similarity of the triangles FAC~EBC and DBO~FAO
please help after that.
Answer: From $\triangle FAC \sim \triangle EBC$:
$$\frac {BE}{AF} = \frac {BC}{AC}$$
From $\triangle DBO \sim \triangle FAO$:
$$\frac {DB}{FA} = \frac {OB}{OA}$$
Since $OB$ is the perpendicular bisector of $DE$, we have $BD = BE$. Therefore:
$$\frac {BO - CO}{CO-AO} = \frac{BC}{AC} = \frac {BE}{AF} = \frac {DB}{FA} = \frac {OB}{OA}$$
$$OA\times OB - OA \times OC = OB \times OC - OA \times OB$$
$$2 \times OA \times OB = OA \times OC + OB \times OC$$
Thus
$$\frac {OC}{OA} + \frac {OC}{OB} = \frac {OB \times OC + OA \times OC}{OA \times OB} = 2$$
Answer: Observe that, $$\frac {AC}{BC}=\frac {AF}{EB}=\frac {AF}{BD}=\frac {OA}{OB}$$ and thereafter $$\frac {AC}{OA}=\frac {BC}{OB}$$.
Therefore, $$\frac {OC}{OA} + \frac {OC}{OB}=\frac {OA+AC}{OA}+\frac {OB-BC}{OB}=2+\frac {AC}{OA}-\frac {BC}{OB}=\boxed {2}$$


Decompressing zip

Question: I want to decompress zip file in console application in c#. When I Googled it the solutions I found was using
System.IO.Compression.ZipFile

But when I try to use it I get error "the namespace 'ZipFile' does not exist in the namespace 'System.IO.Compression'"
What am I missing?
Comment: What version of .Net are you targeting?
Comment: .net 4.5 and a solution from the linked post helped. thank you!
Answer: Make sure you're using .NET 4.5 and your project has a reference to System.IO.Compression.FileSystem.
See https://msdn.microsoft.com/en-us/library/system.io.compression.zipfile(v=vs.110).aspx

Decompressing zip


Small problem on minus sign $({-5}+{9}x)y'={4}x+{9}y$

Question: I have the equation $$({-5}+{9}x)y'={4}x+{9}y$$
So I am trying to solve it in the way need to solve linear differential equation.
I recognise that I can write it as : $$({-5}+{9}x)y' -{9}y={4}x$$
now I dont know what I should do, I know that I could write $(({-5}+{9}x)y)^\prime=\int4xdx$
if just my expression was different by minus sign. so what is the thechnique in such problems? this is not the first time I getting in a situation like that.
Answer: Have you heard of the integrating factor?  Divide the equation by $9x-5$ and change the minus sign to a plus sign by distributing $-1$ to the $9x-5$ when you divide $9y$ by it:
$$y'+\frac{9}{5-9x} y=\frac{4x}{9x-5}$$
Then this is just a standard integrating factor problem.
Multiply both sides of the equation by:
$$exp\left(\int \frac{9}{5-9x} \; dx \right)= \frac{1}{5-9x}$$
$$\left(\frac{y}{5-9x}\right)'=\frac{-4x}{(9x-5)^2}$$
Lastly, integrate both sides and don't forget the constant.
Answer: Hint: divide both sides by $-5+9x$, and rewrite the ODE in the form: $y' + Py = Q$, and use the 1st ODE formula to proceed .
Answer: $$({-5}+{9}x)y' -{9}y={4}x$$
No you can't write this:
$$(({-5}+{9}x)y)^\prime=4x$$
Since $(fg)'=f'g \color {red}{+}fg'$ but you can try to have something like:
$$\left ( \dfrac f g\right)'=\dfrac {f'g\color {red}{-}fg'}{g^2}$$
$$\left ( \dfrac y {9x-5}\right)'= \dfrac {4x}{(9x-5)^2}$$
And integrate both sides.


What's the most common and recommended directory for a web application on FreeBsd?

Question: I have a website on a FreeBSD server which is reachable from the Internet. I know I can run it from whichever directory I wish. But still, which directory is more right, common and recommended? At the moment I'm running it from /usr/local/my_website123
Your advice?
Comment: It is a very flavor thing. I typically prefer to have a /srv directory, where all services are running from. But it is a linux custom, freebsd likes /usr/local .
Answer: Such questions are asked to man hier, but it doesn't say anything about /www.
Apache runs its default host from /usr/local/www/apache2x/data, so I guess /usr/local/www/my_website is generally fine.
Comment: And the most web applications installed into `/usr/local/www` so I suggest this directory too.


How do I map active directory group membership (ldap authorization) to og groups in open atrium?

Question: I can successfully bind to the ldap server, and I have set up authentication successfully - ldap users can log in to my open atrium site. However, the authorization mappings for the groups aren't coming through.
I have this as a mapping under:
admin/config/people/ldap/authorization/edit/og_group
CN=Human Resources,OU=Groups,OU=Domain Users,OU=Domain Controllers,DC=domainname,DC=com|node:100:6

Where "100" is the node id for the open atrium space (og group), and "6" is a custom group admin role with a set of permissions defined in:
admin/config/group/roles/node/oa_space
However, when I log in with a user that is confirmed to have this "memberof" attribute in active directory, the user does not have the corresponding access to the organic group.
I have tried both "Convert full dn to value of first attribute before mapping" checked and unchecked with the same results.
The mapping is shown to be enabled here:
admin/config/people/ldap/authorization
I'm finding the documentation a little lax here. Am I mapping the correct og role id? Does the og role id translate to the role id in admin/config/group/roles/node/oa_space? Is this set somewhere else? Where? Is there anything else I have to do to bring these mappings over?
Answer: I had this same problem recently whereby this was originally working:
GroupA|IT:member
GroupA_Admins|IT:member
GroupA_Admins|IT:administrator member

During this course of development this stopped working and on alternate logins a user in that LDAP group would either be a member of the organic group, or not (but never an administrator of that group).
I eventually worked out that it had stopped working because I had since overridden the permissions of the space, which meant that the OG role ids were different, even though they had the same name.
Therefore:
GroupA|IT:member
GroupA_Admins|IT:member
GroupA_Admins|IT:administrator member

was being automatically converted to
GroupA|IT:member (raw: node:3:5)
GroupA_Admins|IT:member (raw: node:3:5)
GroupA_Admins|IT:administrator member (raw: node:3:6)

when actually since it was no longer using the default roles, it should have been using 8 and 9 instead of 6 and 7.
Rewriting the mapping to explicitly use the ids for the overriding roles rather than their names worked:
GroupA|node:3:8
GroupA_Admins|node:3:8
GroupA_Admins|node:3:9

I know this is a very old post to reply to, but I was struggling with this yesterday so hope it helps someone else in future.


Get a difference in dates and aggregate results over a third column

Question: +-----------+------------+------------+
| ACCOUNT   | PAID_DATE  | DUE_DATE   |
+-----------+------------+------------+
| 103240005 | 2010-07-22 | 2009-11-30 |
| 103240005 | 2010-07-22 | 2007-09-30 |
| 103240005 | 2010-07-22 | 2008-09-30 |
| 103240006 | 2010-07-22 | 2009-09-30 |
| 103240006 | 2010-07-22 | 2007-07-22 |
| 103240007 | 2010-07-22 | 2008-07-22 |
| 103240008 | 2010-07-22 | 2009-08-31 |
| 103240009 | 2010-07-22 | 2007-12-31 |
| 103240009 | 2010-07-22 | 2008-12-31 |
| 103240005 | 2010-07-22 | 2009-12-31 |
+-----------+------------+------------+

The above sample dataset is from a banking application I am building.
I would like to get per account, the amount of records where the payments were made on time, i.e DATEDIFF(DUE_DATE, PAID_DATE)  = 0. Please note that there are multiple entries per account.
Here is my problematic query:
select ACCOUNT_NUMBER, count(DATEDIFF(PAID_DATE, DUE_DATE) as diff) as diff_count
from TRANSACTIONS
where diff=0 group by ACCOUNT_NUMBER;

Answer: Assuming the paid_date and due_date are of date type, you can use:
select account_number,
  sum(paid_date = due_date) as diff_count
from transactions
group by account_number;

if the two dates are equal, the result will be true which is taken as 1 by mysql and 0 for false.
EDIT:
You can further add more aggregates as needed. For e.g. - count where the overdue is 10 or more days, you can use:
select account_number,
  sum(paid_date = due_date) as diff_count,
  sum(datediff(paid_date, due_date) >= 10) as overdue,
from transactions
group by account_number;

Comment: Thank you, but I would like to extend this query to say, return all records where the 'overdue time' is 10 days, etc.
Comment: @dkay_ - You can add a similar condition for that scenario. Updated the answer.
Comment: It works great. The only edit required is the second 'variable name' for the second aggregator, e.g diff_count2. So your edited query would look like this:

select account_number,
  sum(paid_date = due_date) as diff_count,
  sum(datediff(paid_date, due_date) >= 10) as diff_count2,
from transactions
group by account_number;


Problems with Double Integrals

Question: I have two problems which I have not been able to solve using double integrals in polar coordinates.
The first one is to find the volume of the solid above the cone $z = r$ and below the sphere $z^2 = 1-r^2$.
The second question is the volume of the solid bounded by the paraboloids $z = 3r$ and $z = 4-r$.
In both the main problem was finding and defining the limits of integration.
Thanks in advance!
Comment: You sure that $z=4-r$ or $z=3r$ are  paraboloids?
Comment: Have a look at (http://mathhelpforum.com/calculus/144482-how-work-out-volume-between-sphere-cone.html).
Answer: For the first one -  You can use rectangular coordinates to get, perhaps, a closer feeling of what's going on:
The cone is $\;z=\sqrt{x^2+y^2}\;$, the sphere is $\;x^2+y^2+z^2=1\;$. You can restrict yourself to the what happens in the first octant and then multiply by four due to symmetry ( draw it if this helps):
$$\int_0^{1/\sqrt2}\int_0^{\sqrt{\frac12-x^2}}\int_{\sqrt{x^2+y^2}}^{\sqrt{1-x^2-y^2}}dzdydx$$
Of course, nobody really expects anyone who isn't a masochist to do the above that way, so we can switch to cylindrical coordiantes, say, and get (don't forget the Jacobian!):
$$\int_0^{1/\sqrt2}\int_0^{\pi/2}\int_r^{\sqrt{1-r^2}}r\,dz\,d\theta\,dr=\frac\pi2\int_0^{1/\sqrt2}\left[r\sqrt{1-r^2}-r^2\right]dr=$$$${}$$
$$=\left.-\frac\pi4\frac23(1-r^2)^{3/2}\right|_0^{1/\sqrt2}-\frac\pi2\left.\frac13r^3\right|_0^{1/\sqrt2}=-\frac\pi6\left(\frac1{2\sqrt2}-1\right)-\frac\pi6\left(\frac1{2\sqrt2}\right)=$$
$$=-\frac\pi{6\sqrt2}+\frac\pi6\implies\text{ the volume wanted is}\;\;\frac{2\pi}3\left(1-\frac1{\sqrt2}\right)$$
Now try a similar reasoning for the other one. Observe that changing to rectangular coordinates isn't really necessary, but sometimes it makes things easier to grasp.
Comment: I thank you! I was able to solve the other one.
Answer: Let us find the projection in the $xy$ plane. Note $z=r$ and $z^2=1-r^2$ our are two surfaces. By setting values of $z$ equal we should find the boundary of the projection in $xy$ plane, draw the region to see this.
Note the first surface implies $z^2=r^2$. This implies,
$$1-r^2=r^2$$
Which implies $r=\frac{\sqrt{2}}{2}$ is the boundary of the projection in the $xy$ plane. Then the volume is,
$$V=\int_{0}^{2\pi} \int_{0}^{\frac{\sqrt{2}}{2}} \int_{r}^{\sqrt{1-r^2}} r dz dr d\theta$$
For the the second integral we repeat the procedure.
$$4-r=3r$$
$$r=1$$
$$V=\int_{0}^{2\pi} \int_{0}^{1} \int_{3r}^{4-r} rdz dr d\theta$$
If you haven't learned triple integrals then what you want to compute is $\iint_{D} (\text{top_Surface}-\text{bottom_Surface}) dA$ to compute the volume. So for example the integral above can be equivalently thought of as the double integral,
$$\int_{0}^{2\pi} \int_{0}^{1} ((4-r)-3r) r dr d\theta$$
Answer: The first integral is:
$$\int_{0}^{{\sqrt{2}\over{2}}}\int_{0}^{2\pi}\int_{r}^{{\sqrt{1-r^2}}}r \space dzd\theta dr$$
The second is:
$$\int_{0}^{1}\int_{0}^{2\pi}\int_{3r}^{4-r}r \space dzd\theta dr$$
You should make a graph and find the intersections to figure out the radius. The angle has no limitations and $z$ is already defined

Problems with Double Integrals


Is the real part of a positive definite Hermitian matrix invertible?

Question: Suppose $X$ and $Y$ are real matrices such that $A=X+iY$ is Hermitian and positive definite.
Does invertability of $A$ imply invertability of $X$?
Are all Hermitian positive definite matrices invertible?
Comment: To answer your second question: yes, all Hermitian positive definite matrices are invertible
Answer: The answer is yes.  In particular, it suffices to note that
$$
X = \frac 12A + \frac 12 \overline{A}
$$
is a sum of positive definite matrices.


Como usar a função preventDefault em um evento click dentro em um iframe?

Question: Eu manipulo o DOM do iframe da seguinte forma: (http://api.jquery.com/contents/)
$('iframe').contents().find('a').função();

Costumamos utilizar a função preventDefault assim:
$( "a" ).click(function( event ) {
  event.preventDefault();
});

Dúvida:
Como faço para utilizar a função preventDefault() em um evento click para todos as tags de link $('a') dentro do iframe? Basicamente preciso que nenhum link possa ser clicado dentro do iframe.
Já testei da seguinte forma, porém não funciona:
$('iframe').contents().find('a').click(function (e) {
   e.preventDefault();
});

Comment: Acho que podes marcar uma das respostas como certa :)
Answer: Se a iFrame estiver num dominio diferente essa sua solução com jQuery não vai funcionar pois viola uma regra de segurança e os Browsers não permitem isso.
Uma solução que vejo é bloquear a iFrame com uma div na sua página, que fique por cima da iFrame, e assim "tapar" a interação com a iFrame.
Outra opção, ainda melhor (para browsers modernos) é a solução do renan com pointer events.
Exemplo:
(repare que dei uma border na div bloqueadora só para ser visivel)

#bloqueador {
    position: absolute;
    top: 0px;
    border: 2px solid #ccf;
    height: 300px;
    width: 300px;
}

Comment: @GustavoPiucco vou apagar os comments aqui para limpar. Se fizer o mesmo seria ótimo e poupamos tempo dos moderadores
Answer: Uma solução somente usando CSS seria usar a propriedade pointer-events no . Só precisa ficar atento a quais navegadores suportam.

iframe {
  pointer-events: none
}

MDN
Answer: Para resolver o problema, caso a iFrame seja do mesmo domínio que a página mãe, é necessário adicionar o evento .ready() ao iframe, pois o mesmo deve ser carregado por completo antes de aplicar o evento .click(). Ficando da seguinte forma:
$(document).ready(function() {
    $("#id_do_iframe").ready(function () {
        $('#id_do_iframe').contents().find('a').click(function (e) {
             e.preventDefault();
        });
    });
});


Add new line to bottom of StringJoiner

Question: I have the following method
public String toIndentedString() {
    StringJoiner sj = new StringJoiner("\n");
    sj.add(rootValue.toString());
    for (Tree<T> child : children) {
        String childString = child.toIndentedString();
        sj.add(childString.replaceAll("(?m)^", "  "));
    }
    return sj.toString();
}

The output it is returning is slightly off, here is an image which shows the output it requires.

Could someone please tell me what I need to change to get this to work?
Answer: The idea of StringJoiner is that you can use the constructor to specify the paramaters

delimiter - the sequence of characters to be used between each element
added to the StringJoiner prefix - the sequence of characters to be
used at the beginning suffix - the sequence of characters to be used
at the end

so you could do
StringJoiner sj = new StringJoiner("\n", "", "\n");

Comment: Doing this still seems to produce a pretty wild result, there are various new lines throughout the output
Comment: hmm, I have just noticed that this is a recursive method, so you probably want to create your `StringJoiner` outside of this method
Answer: One solution is to wrap each value with newlines and remove the extra one in the parent:
public String toIndentedString() {
    return "\n" + rootValue + children.stream()
            .map(Tree::toIndentedString)
            .map(s -> s.substring(0, s.length() - 1)) // strip trailing newline
            .map(s -> s.replaceAll("\n", "\n  "))
            .collect(Collectors.joining())
            + "\n";
}

Ideone
Alternatively, you can separate the indentation logic from line insertion like this:
public String toIndentedString() {
    return indentChildren()
            .collect(Collectors.joining("\n", "\n", "\n"));
}

private Stream<String> indentChildren() {
    return Stream.concat(Stream.of(rootValue.toString()),
            children.stream()
                    .flatMap(Tree::indentChildren)
                    .map("  "::concat));
}

Answer: Here is the solution, I needed to put the StringJoiner into another method. Then call that method and append a new line "\n". The code has also been changed to use StringBuilder as it is simpler. Special thanks to 4castle for helping me with this!
public String toIndentedString() {
    return _toIndentedString() + '\n';
}

private String _toIndentedString() {
    StringBuilder sb = new StringBuilder(rootValue.toString());
    for (Tree<T> child : children) {
        sb.append('\n');
        sb.append(child._toIndentedString().replaceAll("(?m)^", "  "));
    }
    return sb.toString();
}

Comment: Shouldn't it start with a newline?

Add new line to bottom of StringJoiner


Override user pages with a view

Question: Is it possible to override a user page with a view? I would like to override the user page to show all the nodes created by that user.
Answer: Views is not the right tool to use here, as views is for listing of content.
What you probably want is to use panels to take over the user page and display anything, like a view in it.
Comment: The OP is about a page listing all the nodes created by the user, which is content. It's not true that the Views module is for listing just content; it can create a list of users, and even a list of modules.
Comment: Might be better to use standard blocks than get Panels involved, it's a lot of bloat for such a simple thing
Comment: Well sure views is for listing things, but most users understand it much easier if you don't abstract that too much.
Comment: Whether panels is a lot of bloat is definitive not clear as it is an intelligent system in contrast to block rendering.
Answer: I found the answer to this!
In Views under relationship, select Content: Author
Then in under Contextual Filters select Content Author UID
Use the following settings for Content Author UID:

Relationship: Nodes
WHEN THE FILTER VALUE IS NOT AVAILABLE: Provide
Default Value / User ID from URL WHEN THE FILTER VALUE IS AVAILABLE
OR A DEFAULT IS PROVIDED: Specify Validation Criteria / Validator:
User / Allow both numeric UIDs and string usernames

Then simply create a block and display it on the user page (Go to block settings and set the path to users/*
I hope that helps someone!
Answer: Might not be the answer but try this module
http://drupal.org/sandbox/AshishThakur/1511158
Answer: There is a way to replace the content of user page with views page (Tested)
function MODULE_menu_alter(&$items){
  $views_router = menu_get_item('path/to/my/views');
  if( $views_router ){
    $items['user/%user']['page callback'] = $views_router['page_callback'];
    $items['user/%user']['page arguments'] = $views_router['page_arguments'];
    $items['user/%user']['access callback'] = $views_router['access_callback'];
    $items['user/%user']['access arguments'] = unserialize($views_router['access_arguments']);
  }
}

Flush the cache and check the views accessibility settings.
Visit the user page for effective results.

Override user pages with a view


Sharing non control related data between WPF ViewModel and UserControl

Question: I'm new to WPF and the MVVM pattern so keep that in mind.
The project I'm tasked with working on has a view and a view model.  The view also contains a user control that does NOT have a view model.  There is data (custom object ... Order) being passed to the view model that I also need to share with the user control.
It looks like the UserControl does share data between the view model already via DependencyPropertys but this data is just text boxes on the user control that look to be bound back to propertys on the view model.
I need to share data that will NOT be represented by a control on the user control.  Is there a good way to pass this data (complex Order object)?  Maybe I do need some kind of hidden control on my user control to accomplish this but I'm just not that sure being new to this.  Any advice would be appreciated.
Comment: can you please give an example? "I need to share data that will NOT be represented by a control on the user control" frase in confusing...
Comment: @Tigran I think he means things that won't be displayed, for example if you had a validation user control with a regex you wouldn't display the regex but you might be given it from a view model.  Although I agree it's not entirely clear.
Comment: @Tuskan360, Yes this is what I mean.  I have an Order object in my view model that I will use to populate a Viewport3D object in my user control.  My order object is just data being passed from my view model to my user control but is not directly being displayed in my user control.  Most examples that I see of sharing data like this are text boxes or something similar.  That's why I was saying that my data would not be represented by a control on the user control.
Comment: @Cole that clarifies things a lot, do the answers below help or is something still not clear?
Answer: There is no need for hidden fields (or any such concept in WPF) as you can add any custom properties you want to a user control.
In the user control, create a new dependancy property like this but with MyUserControl set apropriately:
    public Order CurrentOrder
    {
        get { return (Order)GetValue(CurrentOrderProperty); }
        set { SetValue(CurrentOrderProperty, value); }
    }

    // Using a DependencyProperty as the backing store for CurrentOrder.  This enables binding, etc.
    public static readonly DependencyProperty CurrentOrderProperty =
        DependencyProperty.Register("CurrentOrder", typeof(Order), typeof(MyUserControl), new PropertyMetadata(null, OnCurrentOrderPropertyChanged));

    public static void OnCurrentOrderPropertyChanged(DependencyObject Sender, DependencyPropertyChangedEventArgs e)
    {
        var sender = Sender as MyUserControl;
        var NewValue = e.NewValue as Order;
        var OldValue = e.OldValue as Order;
        if (OldValue != null && sender != null)
        {
            //Use old value as needed and use sender instead of this as method is static.
        }
        if (NewValue != null && sender != null)
        {
            //Use new value as needed and use sender instead of this as method is static.
        }
    }

In you're parent view where you use the usercontrol you then write something like:
<local:MyUserControl CurrentOrder="{Binding ViewModelOrder}" />

Where CurrentOrder is the dependancy property on the usercontrol and ViewModelOrder is the name of the property in the view model you would need to replace local:MyUserControl with your control name/namespace.
Comment: +1 Very good clear explanation.  Thanks for clearing this up for me. Makes perfect sense now.  It works now!
Answer: You can simply create a dependency property in the class of your UserControl and bind to it in the View that uses the control. There is no need to internally bind the dependency property to one of the controls in the UserControl.


Is it possible to for the Cesàro means to converge but the Fourier series to diverge?

Question: I was just wondering if it is possible for the Cesàro means to converge but the Fourier series to diverge.
In class we learned that if the Fourier series were to converge, then this limit must equal the limit of the Cesàro means. So, I was just wondering if the converse is also true.
Thanks.
Comment: In general Cesaro convergence does not imply convergence. However it is a theorem of Tauber that if a sequence were $o(1/n)$, then the Cesaro convergence of the corresponding series implies the convergence of the series. This can be applied to functions whose Fourier coefficients $\hat{f}_n$ are such that $n\hat{f}_n \to 0$.
Comment: in general, if $\sum_n a_n$ converges, then $\frac{1}{N}\lim_{n\to\infty}(\sum_{n=1}^Na_n)$ converges.  however the converse doesn't hold, eg $a_n=(-1)^n$.  you can probably come up with specific examples in fourier series, take the fourier series of bad functions probably
Answer: The Cesàro means of a countinuous function $f$ converge uniformly to $f$. But there are continuous functions whose Fourier series diverges at some points (even at a dense set of points). See for instance the answers to this other question. However, if the Fourier series of a continuous function $f$ converges at a point $x$, then its sum is $f(x)$.


What does it mean to downconvert signals within a bandwidth, centered at another bandwidth?

Question: So, conceptually, when a book talks about down-converting signals within a bandwith of say, $25$ MHz, with the bandwidth centered at say, $50$ MHz, down to baseband, what exactly does it mean?
Answer: I'll use some different numbers to avoid coincidences between $25$ and $50$.  It is also much more common for the band center to be much higher than the bandwidth.  If the band center is $900$ MHz and the bandwidth is $50$ MHz, the signal is contained in the region $875-925$ MHz.  If you mix it with a fixed sine wave you get the sum and difference frequencies.  You can then filter out the high ones and be left with the low ones.  Baseband is some low frequency that is convenient.  The bandwidth stays the same, only the center frequency is changed.  If we wanted, we could mix the above signal with an $800$ MHz carrier and take the difference frequency to get a signal that ranged between $75$ and $125$ MHz for our baseband signal.
Answer: That means that the signal is originally between 37.5 MHz and 62.5 MHz. So the bandwidth is 62.5 - 37.5 = 25 MHz, whereas the center is at (37.5 + 62.5) / 2 = 50 MHz.
To down-convert it means to do a "frequency translation" so the signal ends up centered at 0 Hz and still 25 MHz wide, i.e., from -12.5 to 12.5 MHz.
Why might this be common? Often, to transmit a signal through a channel, e.g., over RF, the signal may be up-converted to some carrier/center frequency for multiple reasons, e.g., the transmission needs to be within a certain band (because the system is using licensed spectrum at that band). Then at the receiver, you down-convert to get back the original signal.


When were random effects historically introduced to account for unobserved heterogeneity?

Question: In the course of doing some recent research on factors associated with exiting unemployment, I have found that only more recent papers try to account for unobserved heterogeneity using random effects, with older ones far more cautious about benefits and drawbacks of attempting to incorporate such a component.
For example, while paper [1] below debates the issue at length and ultimately decides not to account for unobserved between-subject differences, paper [2] includes random effects without much discussion, and compares results obtained with and without them.
Without wishing to get too deep, I was wondering what the seminal papers on random effects have been, and when they date back to.
[1] Narendranathan, W. & Stewart, M.B., 1993. Modelling the Probability of Leaving Unemployment: Competing Risks Models with Flexible Base-Line Hazards. Journal of the Royal Statistical Society. Series C (Applied Statistics), 42(1), pp. 63-83.
[2] Rotaru, C.I., 2014. Transitioning Out of Unemployment: Analysis Using the ABS Longitudinal Labour Force Survey File. Australian Journal of Labour Economics, 17(2), pp. 111-137.
Comment: I would recommend defining "heterogeneity", which I don't think is used that way outside of economics.
Comment: Ok, but it would be good to know what you would use instead. "Unexplained variability" or perhaps "within-subject correlation"? These are useful, and may be de-facto synonyms, but neither is a direct conceptual substitute. What do you suggest?
Comment: I don't know, because I still don't know what economists mean when they say that.
Answer: Its going to be hard to pin down as models involving random effects come out of a number of areas; repeated measures in the design literature,  multivariate analysis (especially with missing data), analysis of growth curves, and variance component analysis and Model II ANOVA (and likely more that I have neglected).
[Then there's the added difficulty in the different way terms like 'fixed effects' and 'random effects' are used in say econometrics vs biology. We need to be clear what we're talking about when we use some terms]
At the site "Earliest Known Uses of Some of the Words of Mathematics", in the section on words starting with "V" (http://jeff560.tripod.com/v.html) it has under the entry on Variance/ANOVA

The later literature found two models in Fisher's statistical work and produced contrasting terms for them. C. Eisenhart in "The Assumptions Underlying the Analysis of Variance," Biometrics, 3, (1947), 1-21 called them Model I and Model II analysis of variance. Eisenhart also used the terms fixed effects and random effects, though more informally. These appear with greater ceremony in H. Scheffé's "Alternative Models for the Analysis of Variance," Annals of Mathematical Statistics, 27, (1956), 251-271. Components of variance, another common term, was introduced by H. E. Daniels in 1939 in his "The Estimation of Components of Variance," Supplement to the Journal of the Royal Statistical Society, 6, 186-197.

Taking a quick look at Daniels' paper, he's clearly discussing models / situations with random effects.
So this suggests the term "Components of Variance" and models with random effects were being used no later than the 1930s. However old random effects models are, they're pretty old.
[Still backtracking. Based on the quote above, I am guessing we'd find Fisher perhaps at some time in the early 30s somewhere discussing random effects in relation to ANOVA]
Comment: Thank you for that overview. That makes it more than clear that the different approaches I have seen are a matter of different styles of approach rather than some concrete development over the last ten years. It's interesting how one researcher makes no fuss over an issue which for another is to be approached with great thoroughness.


Does zero covariance imply independence of random variables here?

Question: I have two random variables $X$ and $Y$. Both are distributed according to $N(0,1)$. If their covariance is 0, are they independent?
I know that this is not true for other distributions, say the Wikipedia example: $X$ chosen uniformly in $[-1,1]$ and $Y=X^2$.
Answer: http://en.wikipedia.org/wiki/Normally_distributed_and_uncorrelated_does_not_imply_independent
Comment: Thanks for the quick response.


Node.js FS saving object

Question: I received this JSON form client API
{
  COD: '100',
  ATD: '838',
  PAG: '246',
  VENC: '2017-01-27 00:00:00',
}
I saved this JSON in var object, then I try save this variable object like this:
fs.writeFile("boleto.txt", object, 'utf8', function(err){
        if(err){
            console.log(err);
        } else {
            console.log("Log salvo");
        }
    });

But the result in BOLETO.TXT is this: [object Object]
And I need this:
COD: '100',
  ATD: '838',
  PAG: '246',
  VENC: '2017-01-27 00:00:00'
What I'm doing wrong?
ps.: When i call console.log(object) the log is correct.
Comment: JSON.stringify it. Files are just a bunch of bytes - basically a big string. Even binary files. They can't store objects. You need to serialize your object just like what you need to do to send objects across the network. There are several serialization options: xml, asn1, bencoding (torrent files) but in js the easiest way is to simply output JSON.
Answer: //This will work JSON.stringify, JSON.stringify converts json object into a string that can be writable in text file instead of [object object]
fs.writeFile("boleto.txt", JSON.stringify(object), 'utf8', function(err){
        if(err){
            console.log(err);
        } else {
            console.log("Log salvo");
        }
    });

Comment: While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value.
Answer: You need to stringify your JSON first.
fs.writeFile("boleto.txt", JSON.stringify(object, null, 2), 'utf8', function(err){
    if(err){
        console.log(err);
    } else {
        console.log("Log salvo");
    }
});

JSON.stringify(object, null, 2) allows you to skip lines between your key/values, i.e. having a more readable JSON.

Node.js FS saving object


How do I write the equation of an ARIMA (1,1,2)?

Question: I obtained the following output from the function auto.arima():

Is this the correct way to write the equation?

Or should it be like this?
Answer: Hi: you don't difference the error terms. So, the arima(1,1,2) is:
$ y_{t} - y_{t-1} = \mu + \phi (y_{t-1}-y_{t-2}) + \theta_{1} \epsilon_{t-2} + \theta_2 \epsilon_{t-1} + \epsilon_t$.
So, the left side is for the $d=1$ term. The first term is the mean ( what you refer to as drift ? ), the second term is the $p= 1$ term and the third and fourth terms are the $q=2$ MA terms.
Sometimes there is the possibility the $\mu$ is put as part of the $\phi$ term rather than alone but I'd have to look at the code for auto.arima in R and don't have time at the moment. I hope this  helps.


How many $3$ digit even numbers can be formed by using digits $1,2,3,4,5,6,7$, if no digits are repeated?

Question: How many $3$ digit even numbers can be formed by using digits $1,2,3,4,5,6,7$, if no digits are repeated?
ATTEMPT
There are three places to be filled in _ _ _
I wrote it like this
_ _ $2$
_ _ $4$
_ _ $6$
Now each of the two blanks can be filled in $P(6,2)$ ways. So adding results of three cases i have $3$. $P(6,2)$ which gives me $90$ ways. But the textbook states $60$ ways. Can someone suggest how ?
Thanks.
Comment: I think that your textbook is wrong. I also get $90$ numbers.
Comment: In each you have, altogether, $5\cdot 4\cdot 3$ possibilities, or $60$.
Comment: $60$ is correct if you only have numbers $(1,2,3,4,5,6)$ to chose from. Or numbers $(2,3,4,5,6,7)$,
Answer: For the first digit you only have $3$ possibilities, $2,4$ or $6$. For the second digit, having chosen the first digit you only have $6$ possibilities left. For the third digit, having chosen the first two digit you have $5$ possibilities left. In total you have $3 \times 6 \times 5$ possibilities.
Comment: Normally you would call the rightmost digit 'last' or 'third', not 'first'.
Comment: That depends on how you look at things. :)
Comment: @BeniBogosel yeah right .thanks