Unable to set default NSDateFormatter for RestKit object mapping serialization

Question: I'm unable to add a date formatter to the list of RKValueTransformers that is utilized when serializing dates because RKObjectMapping's initialize function always overrides it.
Basically in my apps didFinishLaunching I have the following code:
// Survey Mapping Mapping
RKEntityMapping * surveyRequestMapping = [RKObjectMapping requestMapping];;
[surveyRequestMapping addAttributeMappingsFromArray:@[@"key", @"version"]];

// Add a request descriptor for Surveys
[sharedManager addRequestDescriptor:
[RKRequestDescriptor requestDescriptorWithMapping:surveyRequestMapping
                                      objectClass:[Survey class]
                                      rootKeyPath:nil
                                           method:RKRequestMethodAny]];

// Update date format so that we can parse dates properly.
// 2013-11-09 14:51:27 +0000
NSDateFormatter *dateFormatter = [NSDateFormatter new];
dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss Z";
[[RKValueTransformer defaultValueTransformer] insertValueTransformer:dateFormatter atIndex:0];

Once I commented out the following line my NSDateFormatter was used.
https://github.com/RestKit/RestKit/blob/development/Code/ObjectMapping/RKObjectMapping.m#L140
Am I doing something incorrectly?
Answer: The code that causes you problems basically means that you need to make a call (vortex some other class needs to make a call) to RKObjectMapping before you try to install the formatter. Generally you will have a configuration method which creates your mappings, descriptors and manager and you can configure the formatter at the end of that process.
Comment: I moved the `insertValueTransformer` call to after the section of code where I'm creating my RKEntityMapping and I get the same error. I've updated my question to include my EntityMapping code.


How to implement a cancel button with required elements

Question: I have a form in which I have added a cancel button which looks like this:
<code>$form['cancel_button'] = array(
  '#type' => 'submit',
  '#value' => t('Cancel'),
  '#name' => 'cancel',
  '#access' => TRUE,
  '#submit' => array('mymodule_cancel'),
  '#limit_validation_errors' => array(),
);
</code>
This form has required elements in it as well and what is causing the problem. I thought that by having the #limit_validation_errors statement would prevent the required elements check, but that is not happening. How do I prevent the required elements from being checked?
EDIT: I found this answer on a different question Isn't it possible to have multiple buttons  along with a submit button?
This would explain the behaviour I am seeing but it seems to contradict the Drupal documentation about limiting error checking. This would really screw up people who want to save a draft of a form that has required fields. I am pretty sure I have seen this done before, so there must be away around this.
Comment: If it's just a simple redirect, I'd just add #markup as a regular link.
Answer: You can make something like this in your function validate :
<code>function FORM_validate(&$form, &$form_state) {
if ($form_state['values']['op'] == 'cancel')
{
 ///  Do something
/// drupal_goto() for example
}
}
</code>
Comment: Never depend on this 'op'.  It's translated and raw value. Use the trigger_element from $form_state.


Can Guitar pro 6 read files from a link?

Question: I am wondering if guitar pro 6 can read files from a link, I mean :

File/Open file
Copy paste my link where the tab is (IE : http://website.com/my_uber_tabs.gp5)

And bang, guitar pro downloads as TMP file, or in a folder dedicated to its tabs (I don't know, like in C://Users/Me/My Documents/GP6/Tabs), and Yey you can read and play your tab on GP6 !
Thanks
Comment: This question appears to be off-topic because it is about how windows reads files, which has nothing to do with music.
Comment: Why would you want that? Just download the file to your local machine...
Comment: Well, I'll just copy paste a link, and it downloads (or not), and open it. That would be easier than downloading it myself, then search in the containing folder, then open it myself. I want to open tabs from my own "cloud" filesystem through an URL.
Comment: I can't see the offtopic here. I am talking about a music software. You know that VLC a video player, can read from the web through an URL ? And that's not because of an operating system.
Answer: I've been a guitar pro 6 user for years now. You can't load files directly from the web like that, unless there is some hidden feature that allows you to, but not the way you mentioned.
However, what you can do is download your file through the browser and set the browser settings(or your download manager) to automatically open the file once done downloading. This will allow your GP6 to open the file once you get it.
Make sure your GP6 has its file associations working, if not you can do so under File->Restore File Associations
Comment: Well that can be a workarround. Thanks for your answer, I wish that Guitar pro team develops a feature like that, it would be awesome !


prove or disprove by counter example

Question: If $f$ is differentiable at $x=0$ and $\lim_{x\to0}{f(x)\over x}=3$ then $f(0)=0$ and $f'(0)=3 $.
so after a few failed counter examples I decided to prove this since it also kinda seems to be true...
this is where I got to:
$f$ is differentiable at $x=0\Rightarrow$ $f'(0)$ exists.
$f'(0)=\lim_{x\to0}{f(x)-f(0)\over x-0}=\lim_{x\to0}{{f(x)\over x}-{f(0)\over x}}$
$f'(0)-3=\lim_{x\to0}({{f(x)\over x}-{f(0)\over x})-\lim_{x\to0}{f(x)\over x}}=\lim_{x\to0}{-{f(0)\over x}}$
$\Rightarrow f'(0)=3-\lim_{x\to0}{{f(0)\over x}}$
now comes the part where i'm not sure about...
$\Rightarrow f'(0)={3\lim_{x\to0}{x\over x}}-\lim_{x\to0}{{f(0)\over x}}={\lim_{x\to0}{3x\over x}}-\lim_{x\to0}{{f(0)\over x}}=\lim_{x\to 0}{{3x-f(0)}\over{x}-0}$
which is by definition the derivative of the function $3x$ at $x=0$ which satisfies both $f'(0)=3$ and $f(0)=0$....
is this true? it seems a little stinky since I forced in a specific function....
cheers
Answer: The statement is true. $f$ is differentiable at 0 implies that
$$
f(x) = f'(0)x + f(0) + r(x),
$$
where $r(x)$ is a remainder term such that $\lim_{x\rightarrow 0}\frac{r(x)}{x} = 0.$
Thus
$$
\lim_{x\rightarrow 0}\frac{f(x)}{x} = \lim_{x\rightarrow 0}\left(f'(0) + \frac{f(0)}{x}+ \frac{r(x)}{x}\right).
$$
On LHS we get 3. On the RHS we have
$$
f'(0) + \lim_{x\rightarrow 0}\frac{f(0)}{x}.
$$
If $f(0) \neq 0$, then this term would be infinite, giving a contradiction.
Answer: In a neighborhood of $x=0$ we have $f(x)=3x+o(x)$, $f$ is differentiable and then continuous at $x=0$ and then $f(x)\to 0$ for $x\to 0$, i.e. $f(0)=0$ and $f'(0)=\lim_{x\to0}{f(x)\over x}=3$.

prove or disprove by counter example


commutant of a finite and semifinite von Neumann algebra

Question: When $M$ is a type I von Neumann algebra on a Hilbert space, then the commutant $M'$ is also type I.
The conclusion is also true for type II and type III von Neumann algebras.
My question is as following:
If $M$ is a finite(semi-finite,respectively) von Neumann algebra, can we conclude that $M'$ is also finite(semi-finite,respectively)?
Answer: This is answered in all von Neumann algebra texts.
The "major" type (I,II,III) is preserved in the commutant; so "semifinite" is preserved (note that the commutant of a direct sum/direct integral is the direct sum/integral of the commutants). The "minor" type (I$_n$, II$_1$, II$_\infty$) is not preserved. Indeed, it is very easy to construct examples. For instance when $M_6(\mathbb C)$ is seen as  $M_2(\mathbb C)\otimes M_3(\mathbb C)$, we have $M=M_2(\mathbb C)\otimes1$,  $N=1\otimes M_3(\mathbb C)$ two subalgebras with $M$ type I$_2$, $N$ type I$_3$, and $M'=N$.
The same happens with any finite algebra. If $M\subset B(H)$ is finite, then you can always consider $M\otimes 1\subset B(H\otimes \ell^2(\mathbb N))$ and then $1\otimes B(\ell^2(\mathbb N)) \subset (M\otimes 1)'$, showing that $M\otimes 1$ cannot be finite. In this situation the commutant of a II$_1$ algebra can be II$_\infty$ and the commutant of a I$_n$ can be I$_\infty$.


Issue with cropped images for an image gallery

Question: I have an image gallery. The thumbnails are 240px in width, but the heights vary. I tried cropping the images so that they are all 150 pixels high.
At the moment I've got this:
HTML

CSS
 .gallery {
 position:relative;
 }

 .gallery > div {
 position:absolute;
 }

 .gallery > div > a > img {
 position:absolute;
 top: 0;
 left: 0;
 clip: rect(0px,240px,150px,0px);
 overflow: hidden;
 border:none;
 }

This works with cropping the images to 150px, but only the images on the top row are aligned. The images on the other rows are not aligned because they are being placed directly below the original heights of the images on the row above. (The cropping doesn't get rid of the rest of the image. The rest of the image is not visible, but it's still there,). What do I need to add to my CSS to sort this out?
Comment: Please show the related HTML.
Comment: Where is the position:relative that sets your absolute positioning?
Comment: Have you tried something like `.gallery > div > a {  max-height: 150px;  overflow: hidden;  }` ?
Comment: ... try adding a display:block or inline-block ... otherwise A tags don't take the height: `.gallery > div > a { max-height: 150px; overflow: hidden; display: inline-block; }`
Comment: Could this possibly be jQuery issue? I have a js file which makes all images 240px in width and therefore makes the height proportional to that 240px as well.
Answer: Surely your code is a bit more complex of what you paste here, but please take in consideration this base css:
.gallery {  position: relative;  }
.gallery > div {  float: left;  }
.gallery > div > a {  max-height: 150px;  width: 240px;  overflow: hidden;  display: inline-block;  }
.gallery > div > a > img {  border: none;  }

Here a working example:
http://jsfiddle.net/3W7Xt/
Regards


Using the Validation Block of Enterprise Library with Entity Framework

Question: We've used the Validation Block of MS Enterprise Library for some time with great success in conjunction with custom DALs but we've recently started using the Entity Framework and can't get the Validation Block to work with it.  The objects are dynamically created in EF and putting attributes on top of them will simply get wiped out when the models are re-genned.
Can these two co-exist?  If not, does anyone have any recommendations for what validation library/simple rules engine would be a good candidate to use along with EF?
Thank you.
Comment: Don't forget to flag your favorite answer ;-).
Answer: You need a validator which supports a "buddy class" (like this example for Dynamic Data). This seems to be a work in progress for VAB. I can't find an example of anyone actually using it yet, but it might work.
Answer: Validation Application Block supports the concept of configuration based validation. This way you can separate your generated domain entities from validation. You can use the Enterprise Library configuration tool for this. Simply right-click on your configuration file and start adding validation configuration.
I advise you to read the VAB Hands on Lab document (ValidationHOL.pdf) which is included in the Hands On Lab download. After reading that document, read this article. It explains how to integrate VAB with Entity Framework.
Good luck.


QpushButtos com designes mais robustos

Question: Estou estudando PyQt5 e acho meio estranho o designe dos QpushButtons.
é possível colocar a descrição do botão no canto inferior e faze-lo mudar de cor quando o cursor está em cima dele ?
Answer: É possível sim! Para os estilos, há a função .setStyleSheet()
Para um estilo no botão, você pode escrever o código dessa forma:
btn.setStyleSheet("font: 15pt Arial;margin: 1px;
border-color: #0c457e; border-style: outset;
border-radius: 1px;border-width: 1px;color: white;
background-color:
qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #2198c0, stop: 1 #0d5ca6);
}QPushButton:pressed
{ background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #0d5ca6, stop: 1 #2198c0);")

Assim, o botão tem uma cor azul com gradiente quando normal e um novo estilo quando pressionado, com o a parte final do código:
QPushButton:pressed
    { background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #0d5ca6, stop: 1 #2198c0);")

Para que o botão mude apenas com o mouse em cima, basta adicionar um código da seguinte forma:
btn.setStyleSheet("QPushButton:hover:!pressed {border: 1px solid red;}")

Lembrando que você pode alterar o estilo como bem entender, como no modelo:
QPushButton:hover:!pressed
{
  border: 1px solid red;        # Nesse exemplo, as bordas ficam vermelhas
  color: white;                 # O texto fica branco
  background-color: black       # O fundo do botão fica preto
}

Para um texto quando o mouse está em cima do botão, deve-se adicionar uma ToolTip. Para isso, basta o código abaixo:
btn.setToolTip("Aqui vai a descrição do botão")

Comment: Muito obrigado por essa resposta completa, isso ajuda muito
Comment: mas que comando eu uso pra colocar o texto dentro do botão no canto inferior?
Comment: Você pode fazer assim: button.setStyleSheet("text-align: bottom") e o texto irá ficar no canto inferior do botão.
Comment: Muito Obrigado Guilherme
Comment: Por nada! Qualquer dúvida, só comentar aqui novamente.

QpushButtos com designes mais robustos


Which data are used at each step of Stochastic Gradient Boosting? Subsample of the original training set or gradient of the loss function?

Question: The bag.fraction parameter in SGB controls the size of the random subsample of the original training set on which each successive weak learner is fitted:

At each iteration a subsample of the training data is drawn at random
  (without replacement) from the full training data set. This randomly
  selected subsample is then used, instead of the full sample, to fit
  the base learner and compute the model update for the current
  iteration.

(Quote from the original SGB paper by Friedman).
What I don't get is how this is compatible with the fact that in Gradient Boosting, each successive base model is fitted directly on the residuals (or gradient of the loss function) of the current model.
In other words, how can we fit each new base model on the residuals of the current model and at the same time on a random subsample of the original training set? What is the link between these two key steps?
If someone with enough Python literacy could find the information from the code, that'd be great. Also, the R code is not useful as it is only a wrapper for a C implementation.
Comment: Please stop posting comments in other threads asking people to look at this one.  Some advice on drawing attention to your question is available at http://stats.stackexchange.com/help/no-one-answers.
Comment: I agree that it's a clear question (+1) and I applaud your decision to promote it with a bounty.  However, comments--no matter what their subject or purpose may be--that are not relevant to a particular thread are unwelcome as a matter of course (which is why yours have been raising flags and had to be deleted, one by one).  Boosting experts who frequent our site will already be well aware of your question, so attempting to contact them individually could backfire by annoying them.
Comment: I have met the two conditions on the link you provide (clear question + bounty). But I have not obtained a satisfying answer yet. This is why I am asking Boosting experts to have a look at my question. I don't see how that could be considered bad practice, but if it is I will stop of course.
Comment: Thanks for your explanation and upvote. Since my question has been out for more than 20 days (including 3 days of bounty), there are two options: (1) Boosting experts are not aware of my question; (2) Boosting experts don't care. I was opting for (1) which explains (but don't excuse) my behavior, but in light of your comment `Boosting experts who frequent our site will already be well aware of your question`, it seems that (2) may actually be true; which is actually rather depressing.
Comment: I could always be wrong about that :-).  Have you considered tweeting your post or otherwise drawing attention to it on social media?
Comment: this is an excellent suggestion, thks. I don't know if there are any ML groups on tweeter but I'm gonna look into this topic. There is an R user group on LinkedIn but I unsubscribed because it seemed to me it was nothing but a low quality substitute for CV, for those who did not want to take the time to write good/clear questions or to check existing answers. There was also a lot of spam.
Comment: I share your opinions generally about LI, but there are good people interacting there.  If you do attract some of those guys here then our voting and commenting system will soon sort them  into those who are providing useful answers and those who aren't.  You won't get any spam (or if you do, it will soon be eliminated).
Comment: I just posted a [link](https://www.linkedin.com/grp/post/77616-6057629786807767040?trk=groups-post-b-title) to my question on LinkedIn. Fingers crossed.
Comment: This looks like a very practical kind of question. Would the code of a project implementing SGB not reveal the correct answer (assuming they did it correctly).
Comment: @HenryE. Exactly. I have spent a lot of time trying to find this information in the [R](https://github.com/harrysouthworth/gbm/blob/master/R/gbm.fit.R) and [Python](https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/gradient_boosting.py) implementation, unsuccessfully.
Answer: I've implemented this here in a way that performs comparably to other implementations at least in my testing.
At each step you have a residual R calculated across the entire data set (before any base learners are fit its the residual from predicting the average).
You subsample without replacement and fit the learner to the values of R for the points in that subsample.
Then you apply that learner to get a prediction across the entire data set and update R using that prediction.
So you're still updating the residual across the entire data set, you're just randomizing the process of fitting each base learner a bit.
Answer: I tried to decipher the steps in the original Friedman 2002 paper. If I am not wrong, it appears that we actually both deal with the current residuals and the original training set. Especially, the algorithm is as follows:

Here is what I have understood, step by step. Please tell me if there is something amiss. See (*) below for some notation.

line 1: $F_{0}(x)$ is just an initial guess (and that's not what I'm interested in here)
line 4: we compute the current "pseudo-residuals" for a random subsample of the training set $(y_{\pi(i)},x_{\pi(i)})$ as the negative gradient of the loss function. By current, I mean that we want to add the $m^{th}$ base learner, and that the model so far is a sequence of $m-1$ base learners.
line 5: the $m^{th}$ base learner is a regression tree that partitions the space of the $x_{\pi(i)}$'s into $L$ disjoint regions $R_{lm}$ so that the within-region variance in terms of pseudo-residuals (computed at line 4) is minimized (this is how a tree works). The predictions $\bar{y}_{lm}$ made by the tree are the means of the current pseudo-residuals in each region. This is what I was referring to in my question by: how can we fit each new base model on the residuals of the current model...
line 6: within each region $R_{lm}$ found at line 5, we pick the expansion coefficient $\gamma_{lm}$ that minimizes the loss function (not its gradient, so we're not dealing with residuals here) evaluated on the random subsample of the target $y_{\pi(i)}$ and the corresponding predictions of the current model $F_{m-1}(x_{\pi(i)})$. This is what I was referring to in my question by: ...and at the same time on a random subsample of the original training set?
line 7: we add the (contribution of) the new base learner to the sequence as its expansion coefficients for each region multiplied by the learning rate. This final step is still a bit weird to me, as we are not directly adding the new base learner itself (unlike what the widespread belief about Boosting might suggest). But I guess this is equivalent, since the $\gamma_{lm}$'s inherently encode the information about the new base learner (they were estimated within each leaf of the tree).

*Some notation:

$(y_{i},x_{i})$ is the training set (target, predictor)
the goal of Boosting (like any other ML algo) is to approximate the
function $F(x)$ that maps $x$ to $y$
The approximation of $F$ proposed by Boosting takes the form
$F(x)=\sum_{m=0}^{M} \beta_{m}h(x,a_{m})$, where the $\beta$'s are
expansion coefficients and the $a$'s are parameters of the base
learners $h$'s (which are regression trees in Tree Boosting). So the $a$'s are the splits of the tree (optimizing the $a$'s=building the tree). $m$ is the number of base learners in the sequence. For trees, there is one $\beta_{m}$ per leaf, they are referred to as the $\gamma_{lm}$'s
$\Psi$ is any differentiable loss function. We want the $F$ that
minimizes the expected value of $\Psi(y,F(x))$.
At each step, $F_{m}(x)=F_{m-1}(x)+\nu\beta_{m}h(x,a_{m})$
Answer: The concept of residuals makes sense on any set of data for which:

You can use your model to make predictions and
You have a true response value on each record

So, if you, for example, split your full training data in two halves and then train on the first half, you can still predict on the second half and compute the residuals there.
I want to note though, that each base learner is fit to residuals in only the gaussian case of a gradient booster.  In the general case the weak learners are fit to the gradient of the loss function, which in the gaussian case turns out to be equivalent, but in all others are not.  You make this note as well, but I thought it was worth repeating.
Comment: Say I am adding a new tree to my current SGB model, in the regression case (squared error loss). It is clear that the fit should take into account the gradient of the loss function (=residuals here) somehow. My intuition would be that the tree is fitted on a subsample of the current residuals (squared diff between predictions of the current model and observations), but that can't be true per Friedman's quote in my question above (`each weak learner is fitted on a subsample of full original training set`). So on what data do we fit each new tree at each step?
Answer: I think you are confusing the features with the dependent variable. In gradient boosting models you fit the tree on the current gradient (which coincides with residuals for Gaussian models) using already existing features. Features do not change, only the gradient is changing at each step, because of the updating. Gradient is computed for each observation in the training set, so when you randomly select half of the training set it is easy to track which gradients to use. See Figure 2 in R package gbm vignette for better explanation, or the gradient tree boosting algorithm in section 10 in Elements of Statistical Learning.
Comment: From the original [paper](http://astro.temple.edu/~msobel/courses_files/StochasticBoosting%28gradient%29.pdf) by Friedman, it is clear that each tree is fitted on (a random subsample) of the full original training set:

`At each iteration a subsample of the training data is drawn at random
(without replacement) from the full training data set. This randomly
selected subsample is then used, instead of the full sample, to fit
the base learner and compute the model update for the current
iteration.`

Which means that the steps in my question above are completely wrong.
Comment: so, to stay focused about my question, by confirming that each tree is fitted on the current residuals, you're implicitly saying that the training set is indeed the current residuals? So, at each step, half of the residuals are randomly selected to fit the tree?
Comment: Yes. At each step half of the residuals are randomly selected to fit the tree.


css glow effect com CSS

Question: Neste site
https://nestpowerproject.withgoogle.com/
há um efeito de glow muito interessante; não sei se será feito com CSS
Alguém saberá dar-me algumas dicas sobre como fazer aquilo?
Grato
Comment: O efeito não é com CSS, é OpenGL ou WebGL.
Comment: Para mim, esse site só abre uma tela que, exceto por um logotipo discreto e uns botões bem simples nos cantos, é completamente preta. Não vi nenhum efeito de glow lá.
Answer: O efeito do sei muito provavelmente é com script, não achei referencias no CSS que se aproximem do efeito que está na tela. Acredito que tenha sido feito com canvas.
Para quem não conseguiu visualizar essa é a imagem retirada do site de exemplo.

Com CSS usando linear-gradiente, e filter:blur e @keyframes vc consegue algo bem próximo.

html,
body {
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 0;
}
body {
  display: flex;
  align-items: center;
  justify-content: center;
  background-image: linear-gradient(rgba(0,0,0,0.75) 0%, rgba(0,0,0,0.75) 100%), url(http://unsplash.it/300/180);
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  background-attachment: fixed;
}
        .glow {
      position: relative;
      width: 200px;
      height: 205px;
      background-image: linear-gradient(rgba(0,0,0,0.75) 0%, rgba(0,0,0,0.75) 100%), url(http://unsplash.it/300/180);
      background-attachment: fixed;
      background-size: 100%;
      background-position: center;
      background-repeat: no-repeat;
      border-radius: 50%;
    }
    .glow::after,
    .glow::before {
      content: "";
      position: absolute;
      background-image: linear-gradient(45deg, red, orangered, yellow, green, blue, purple, magenta);
      background-size: 400%;
      top: -2px;
      left: -2px;
      width: calc(100% + 4px);
      height: calc(100% + 4px);
      border-radius: 50%;
      z-index: -1;
      animation: anima 20s infinite linear, gira 20s infinite linear;
    }
    .glow::after {
      filter: blur(20px);
      border-radius: 50% 50% 50% 50%;
      opacity: .8;
    }
    @keyframes anima {
      0% {
        background-position: 0 0;
      }
      50% {
        background-position: 400% 0;
      }
      100% {
        background-position: 0 0;
      }
    }
    @keyframes gira {
      0% {
        transform: rotate(0deg) scale(1);
      }
      50% {
        transform: rotate(360deg) scale(.975);
        border-radius: 47% 53% 50% 55%;
      }
      100% {
        transform: rotate(0deg) scale(1);
      }
    }
    .wrapper {
      position: relative;
      z-index: 100;
    }

Comment: cara vc é mt bom com css.
Comment: @hunterxhunter cara até um ano atras meu CSS era MUITO limitado, ai resolvi estudar, ver exemplos, participar aqui do StackOverflow, e tenho melhorado muito no CSS, aprendo muito aqui, além de também poder por em prática coisas que nunca tinha aplicado em outro lugar. Essa é a vantagem de colabora, pode exercitar e colocar o conhecimento e pratica, muitas vezes errando e aprendendo...! Obrigado pelo elogio :D
Comment: Obrigado @hugocsl. Muitíssimo bom o exemplo :-)
Comment: @user1463905 sem problemas amigo, não é tão sofisticado quanto o do exemplo, mas é mais leve e fácil de implementar. Acho que pode te quebrar um galho. Boa sorte ai

css glow effect com CSS


How to run GitLab CI pipeline on every push to GitHub?

Question: I created a GitLab "CI/CD for external repo" and linked my GitHub.
I then set up mirroring to Pull from that GitHub.
I would have expected when I push to my GitHub, it would show the latest code in the GitLab and automatically start running my GitLab CI pipeline right away, but I noticed this only happens after about 1 hour delay, so I've been pressing the "Update Now" button every time.
This is extremely inconvenient, so am I missing a step to have it simply get the latest code and run the pipeline on every push to GitHub?
Answer: When mirroring a GitHub repository using GitLabs "CI/CD for external repo" feature, you must use an account with admin access on the GitHub repository so that GitLab can use your credentials to set up a web hook, which will notify GitLab when there are changes to be pulled.
The webhook URL will look like https://gitlab.com/api/v4/projects/12345678/mirror/pull. I don't think you can create this manually as it needs to be set up with a secret, so you probably need to remove the project from GitLab and reconnect it.


Numerical partial derivative of a composite function

Question: I have found the two similar questions:

Numerical derivative of composite function
Partial derivative of composite function

but don't know how to combine them properly.
I have
$x=[x_1,x_2]^T$
and
$F(x) = g(f_1(x), f_2(x)) = g(f_1(x_1,x_2), f_2(x_1, x_2))$
The goal is to compute $\frac{\partial F}{\partial x_1}$
My assumption is: $ \frac{\partial F}{\partial x_1} =\frac{F(x_1+h)-F(x_1-h)}{2h}=\frac{g(f_1(x_1+h,x_2),f_2(x_1+h,x_2))-g(f_1(x_1-h,x_2),f_2(x_1-h,x_2))}{2h}$, given the fact that $x_2$ is constant while $F$ is being differentiated by $x_1$.
Is this formula correct?
Comment: $∂F/∂_1$ = $∂g/∂f*∂f/∂_1$
Comment: Sure but i need numerical solution while you provide analytical.
Answer: Your formular is correct, you are using central finite differences applied to $F(x)$.
(There are many other possibilities to approximation the derivatives as well. It always depends on the application what is needed and what is useful.
In some applications, when the derivatives of $f$ and $g$ are known functions, it is useful to employ
$$
\frac{d F}{d x_1} = \frac{\partial g}{ \partial y_1}  \frac{\partial f_1}{ \partial x_1} +
 \frac{\partial g}{ \partial y_2}  \frac{\partial f_2}{ \partial x_1}
$$
Here I use the notation $g(y_1,y_2)$.
Using this chain rule iteratively allows to get exact derivatives in the computer and it is called automatic differentiation.)
Comment: Great, thanks, it works.


Encontrar arquivo no servidor

Question: Boa tarde, tenho um arquivo PHP que procura um txt para pegar as informações e subir no banco de dados SQL, porém esse arquivo é gerado pelo servidor aqui da empresa (onde minha máquina já está mapeada para R: ou \servidor\adm).
Hoje eu tenho que ir no R:, pegar esse arquivo (ATUALIZA.TXT), trazer para minha máquina na pasta do WAMP, onde está o arquivo PHP, e aí eu rodo o arquivo.
Porém queria deixar isso "automático", onde o meu programa PHP já procurasse no servidor diretamente sem precisar de eu jogar na minha máquina.
Hoje utilizo o fopen (ATUALIZA.txt, r)", para abrir o arquivo, e funciona normalmente. Estou recebendo este erro quando utilizo o caminha do servidor: fopen (\\servidor\adm\atualiza.txt):failed to open stream. permission denied in blá blá blá.
Alguém pode me ajudar a encontrar uma solução em como abrir esse arquivo na rede??
Obrigado.
Comment: Já checou se o usuário o qual o PHP esta executando possui acesso a esta pasta do servidor e ao compartilhamento?
Comment: Chequei. Este servidor local é utilizado para compartilhamentos de arquivos internos. Tenho total acesso sobre tal pasta. Possuo permissão para ler, alterar e deletar o arquivo.
Comment: Tem essa página aqui: http://support.ultimatelocator.com/index.php?/Knowledgebase/Article/View/60/0/php-session-problems-warning-session_start-opentmp-failed-permission-denied Verifica se vc seguiu os passos corretamente. As vezes é permissão na pasta, no servidor, ou o caminho da pasta no código. Att,
André.
Answer: Perdão não colocar isso como comentário, mas ainda não tenho reputação para tal...
Tive um problema parecido na empresa onde trabalho, onde o PHP criava o arquivo no servidor mas não o criava com as permissões de leitura devidas, a solução que acabei encontrando foi mudar a permissão do arquivo logo após sua geração, com o comando chmod, resolveu meu problema.
Veja um exemplo:
<?php
// Escrita e leitura para o proprietario, nada ninguem mais
chmod ("/somedir/somefile", 0600);

// Escrita e leitura para o proprietario, leitura para todos os outros
chmod ("/somedir/somefile", 0644);

// Tudo para o proprietario, leitura e execucao para os outros
chmod ("/somedir/somefile", 0755);

// Tudo para o proprietario, leitura e execucao para o grupo do prop
chmod ("/somedir/somefile", 0750);
?>

a função chmod retorna true ou false, e no teu caso bem podias fazer algo como:
<?php
if(chmod("ATUALIZA.TXT", 0644)){
  //instruções para lidar com o ficheiro
  ...
}
?>

Outra coisa é, porquê usar .txt se existem opções como JSON e XML ?
Comment: Não consegui utilizar esta função. Acho que pode ser algum problema com a rede, porque se eu fizer com o arquivo local, ele funciona, mas quando insiro o endereço do servidor ele não entende o caminho. O servidor está configurado para que qualquer user utilize os arquivos, permissão total a todos(alterei para realizar os testes)
Comment: A utilização de um ficheiro `.txt` é obrigatório ?
[XML](http://www.w3schools.com/xml/xml_server.asp) - Ver exemplos.
Answer: Como a função shell_exec() é muito perigosa para o sistema, aqui vai outra função que pode resolver seu problema.
Pela documentação do PHP, você pode utilizar o comando copy(), que ele irá copiar uma fonte para um destino.
copy ( 'R:\ATUALIZA.TXT' , 'c:\pata_do_wamp\seu_site\ATUALIZA.TXT' );

Comment: credo, porquê usar o `shell_exec` ? Esta é uma função que quando usada acarreta demasiados riscos se não for bem empregue.
Comment: O comando não funcionou pra mim neste caso. Se eu executo o comando pelo DOS ele funciona, copia o arquivo normalmente, mas pelo php ele não faz nada.
Comment: @Edilson como você mesmo disse, ``se não for bem empregue``, creio que este uso não acarretará danos nem riscos ao sistema.
Comment: @Edilson, ficou melhor utilizando a função copy()?
Comment: @MatheusDelatorre se não estou em erro, a função `shell_exec()` é desabilitada por padrão.
E @FranciscoCabral a função `copy()` serve para copiar um arquivo de um destino para outro, e o que o usuário quer, é obter os dados nesse arquivo.
Comment: @Edilson Ele havia dito que conseguia abrir o arquivo se ele movesse manualmente o arquivo para o diretório do site, logo eu procurei a solução mais rápida, copiar o arquivo.

Encontrar arquivo no servidor


Wrong sign in regression coefficient?

Question: I have been getting these extremely puzzling results in my logistic regression model. "New.Regs" is a dummy variable indicating whether or not an observation came after a certain law was passed.
The coefficients in the interaction model are extremely large. Without the interaction, the most important variable "New.Regs" is the wrong sign and has an odds ratio below 1 when in reality it has a positive effect. These results are not a symptom of complete separation (I have checked), and I also tried nonparametric smoothing for the Years variable (which is coded as a decimal, meaning an observation could for example be 2.7345 years after the first observation) but get the same results. Also, anova comparing models shows no evidence for non-linearity of Years. Also, n=250 before the law and n=40 after the law.
Any ideas? Some output is below. I know the graph isn't using the logit curve but you get the idea.
Model with interaction:
glm(formula = Quantified ~ New.Regs * Years, family = binomial(link = "logit"),
data = fws)
Coefficients:
                Estimate Std. Error z value Pr(>|z|)
(Intercept)      -1.5728     0.3260  -4.824 1.40e-06 ***
New.Regs       -126.1103    44.7100  -2.821  0.00479 **
Years             0.2359     0.0547   4.314 1.61e-05 ***
New.Regs:Years   12.7242     4.5394   2.803  0.00506 **
AIC: 368.2

Model without interaction:
glm(formula = Quantified ~ New.Regs + Years, family = binomial(link = "logit"), data = fws)

Coefficients:
                                              Estimate Std. Error z value Pr(>|z|)
(Intercept)                                   -2.94915    0.67265  -4.384 1.16e-05 ***
New.Regs                                      -1.25529    0.53753  -2.335  0.01953 *
Years                                          0.38922    0.07473   5.209 1.90e-07 ***
---

    Null deviance: 399.19  on 290  degrees of freedom
Residual deviance: 303.64  on 272  degrees of freedom
AIC: 341.64

Model with only dummy variable, no time variable:
Call:
glm(formula = Quantified ~ New.Regs,
    family = binomial(link = "logit"), data = fws)

Coefficients:
                                              Estimate Std. Error z value Pr(>|z|)
(Intercept)                                   -0.98523    0.50487  -1.951  0.05100 .
New.Regs                                       0.38726    0.41240   0.939  0.34771

Residual deviance: 335.95  on 273  degrees of freedom
AIC: 371.95

Answer: The nonparametric smoothing, although often a good idea, is just a distraction here, at least with your bandwidth choices.
The results look less puzzling if you

remember that a large negative constant in a logit model by itself just means a very small predicted probability

and above all plot the predictions.

With the assumption that your time range in years is from 0 to about 11 I get these curves from your estimates:

I hope that helps. Easy to say, but hard to fix: you have only a short length of data after the law was passed. Despite the reported P-values I have to wonder about over-fitting here.

Wrong sign in regression coefficient?


Interpretation of residual plot for mixed effect linear model

Question: I am trying to do mixed effect regression model with lme4.lmer function. The model has two fixed categorical variables, one random categorical variable and response is continuous variable (distance in meters). I am just puzzled with this residual plot.

I would like to ask:
1.) may I assume from this plot that the model is linear?
2.) there is heteroskedasticity, since variability in residual for smaller values is lower than for bigger values?
3.) According to points 1 and 2, can I use this method, or should I make some log transformation on response and check if this plot looks better, or should I use som other type of model (which?).
Comment: 1) An `lmer` model is always linear. 2) Yes, but the more serious problem appears to be that the residual distribution is not symmetric. 3) That depends on (the nature of) your data and your goal.
Answer: It looks like linear, because the mean of the residuals seems to be close to 0 for each level of the predicted values. If you want to make a more rigorous test, one way to go could be to add as predictors powers of the fitted values, and test whether their coefficients are different from zero (Ramsey RESET test).
However you are right about the heteroscedasticity: the variance in the residuals increase with the fitted values, which is a problem. Also, the distribution seems slightly asymmetrical, with a slightly heavier tail for positive residuals. One better way to check visually for the asymmetry is the normal quantile-quantile plot (function qqnorm in R).
Given the heteroscedasticity and asymmetry of the residuals, I would suggest to transform your data. You could try taking the log or the reciprocal of the dependent variable, fit the model and check again the residuals. As an alternative you could use also the Box-Cox transformation, which usually gives the best results. You can use the boxcox function of the MASS package to find the optimal value of lambda for your data. (Have a look also at this tutorial on R-bloggers)
Comment: @Mateo thank you very much, the Box-Cox transformation helped a lot, also ramsey test seems interesting...


probability of a sequence of event and their intersection with a an event whose liminf has probabilty 1

Question: Let $P_n=\times_{i=1}^n P$ denote a sequence of product probability measures and $E_n$ a sequence of measurable events such that $P_\infty(\liminf_{n\to \infty}E_n)=1$. Can we conclude that for any other sequence or measurable events $S_n$ we have
$$
\lim_{n \to \infty} \frac{P_n(E_n \cap S_n)}{P_n(S_n)}=1
$$
or not?
Answer: Would this be a counter-example? Apologies if I misunderstood the question.

$\forall n: E_n \cap S_n = \emptyset$ so the numerator is always $0$.
$\forall n: P_n(S_n) > 0$ so the denominator is always positive.
$\lim_{n \to \infty} P_n(S_n) = 0$

I am not exactly sure how to interpret $P_\infty (\lim \inf_{n \to \infty} E_n) = 1$ but the last bullet above should hopefully make it possible...?  Anyway, if all $3$ bullets can be satisfied then the ratio is always $0$ and its limit is also $0$.
Comment: Well, if $P$ has support in $\mathbb{R}$ and $P_\infty$ denotes the associated infinite product law, you could think of $E_n$ as an event of the form $\{|T_n -\theta|<\epsilon\}$, where $\theta \in \mathbb{R}$ and $T_n=f_n(X_1, \ldots,X_n)$, for a function sequence $f_n$ and $X_1,X_2,...$ independent and identically distributed according to $P$. In this case, you could interpret $P_\infty(\liminf_{n\to \infty}E_n)=1$ as $P_\infty(\theta-\epsilon<\liminf_{n\to \infty}T_n , \limsup_{n\to \infty}T_n<\theta+\epsilon)=1$.
Comment: oh sure, for a sequence of real numbers (like $T_n$) the meaning of $\lim \inf$ is standard.  I just wasn't sure what you meant by $\lim \inf E_n$ since $E_n$ is a sequence of _events_, not a sequence of reals.  Anyway, I'm glad my counter-example is general enough to work for your $T_n$.


Add/re-add buttons to toolbar in eclipse?

Question: I accidentally removed the "Create new Class" button in eclipse. How would I get it back onto the top toolbar? I've looked through all the menus and I cant find an option to do it.
Thanks
Answer: Just right-click on your perspective (top right corner default) and choose Customize.
There you can select and deselect toolbar icons.
Java Element Creation -> New Java Project/Package/Class
hf
Comment: Yes but I cannot add more types
Answer: In eclipse 4.4, choose Window->Customize perspective. First tab (Tool Bar Visibility) allows to customize toolbar buttons.


$f\cdot g$ is integrable, g is integrable, can we deduce that f is integrable?

Question: $f\cdot g$ is Lebesgue integrable,  g is Lebesgue integrable, can we deduce that f is Lebesgue integrable?
$f\cdot g$ is integrable,  g is integrable, can we deduce that f is finite a.e.?
Comment: What if $g=0$ ?
Comment: What are your thoughts on the problem?
Comment: @SilviaGhinassi $f\cdot g$  is finite a.e., so $f $is finite a.e?
Answer: For a nontrivial example, take $f=\frac{1}{x}\chi_{[1,+\infty)}$ and $g=\frac{1}{x^2}\chi_{[1,+\infty)}$. Then $fg$ is integrable, $g$ is integrable, but $f$ is not.
As for the second question, in general you can't conclude anything, as pointed out already.
Answer: If the support of $g$ and the support of $f$ have intersection with measure zero, you can't conclude anything.


Passing an EditText Value as IntentExtra from a different Layout in AdapterView Issue

Question: I'm using a AdapterView for a ListView, the activity where we can find the list view and an EditText.
When we click on one element of the ListView we go to the second activity, and I want to send the data of the selected item as an extra in a intent.This data will then be shown in the EditText
I tried this code, but it doesn't seem to work, it shows always the default value of the EditText.
here is the code of the adapter view :

public class adapterq extends ArrayAdapter<Questionaire> {
Bitmap image;

public adapterq(Context context, ArrayList<Questionaire> questionaires) {
   super(context, 0, questionaires);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {

   final Questionaire c = getItem(position);

   View  convertView2;
   if (convertView == null) {
      convertView = LayoutInflater.from(getContext()).inflate(R.layout.customquest, parent, false);
      convertView2 = LayoutInflater.from(getContext()).inflate(R.layout.activity_main, parent, false);
   }else{
    convertView2 = (View) convertView.getTag();
   }

   TextView q = (TextView) convertView.findViewById(R.id.textView1);
   final EditText name =     (EditText) convertView2.findViewById(R.id.editText1);

   q.setText(c.getLabel());

   convertView.setOnClickListener(new OnClickListener(){
 @Override
     public void onClick(View v) {
      Intent intent = new Intent();
      intent.setClass(getContext(), Questions.class);
      intent.putExtra("name", name.getText().toString());
      intent.putExtra("category", c.getCode());
      getContext().startActivity(intent);
      v.setBackgroundResource(R.drawable.yourbackground);
      ((Activity) getContext()).overridePendingTransition(R.anim.right_slide_in, R.anim.right_slide_out);

    }

    });
   convertView.setTag(convertView2);
   return convertView;
}

}
Comment: what values is set to editText `name`? and what are you doing inflatign 2 layouts in getView?
Answer: You should use the ListView.setOnItemClickListener() instead. The callback returns what position in the list was clicked and the view. The position is used to retrieve the data object Questionere.
The EditText may be retrieved using a findViewById().
ListView list = (ListView) findViewById(R.id.listview);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
     @Override
     public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
         Questionaire item = list.getItemAtPosition(position);
         String name = ((EditText) findViewById(R.id.editText1)).getText().toString();
         Intent intent = new Intent();
         intent.setClass(getContext(), Questions.class);
         intent.putExtra("name", name);
         intent.putExtra("category", item.getCode());
         startActivity(intent);
     }
});

Comment: I should use that on the MainActivity ?? where I have both of the ListView and the EditText ? Right ?
Comment: Yea. Launching another activity from within the adapter is not ideal. You may use a member field reference to the EditText initialized in your onCreate() instead of looking it up every time the onItemClick is called.
Comment: Okay, I will test it and I will let you know, thanks


How to float 3 divs side by side irrespective of length?

Question: So I want to float three divs side by side. Right now I have them with display: inline-block; and floating left, but when the window gets too small, the rightmost
 is forced to be below the other two.
Also I need it so that the rightmost and leftmost
 have a certain maximum width, and the center
 should change it's width to fill the window. (I'm giving you this information in case any solutions interfere with this). How do I achieve what I want?
Edit
The container for this
 (whether it be the body, or another
), has to be of width 100%. I need three side by side
s positioned like this:

This should keep it's form as I make the window smaller or larger. This is the HTML/CSS I have now:

.app-view-wrapper {
  display: inline-block;
  height: 100%;
}

.search-form {
  border-right: solid 1px #d1d2d4;
  display: inline-block;
  float: left;
  height: 100%;
  max-width: 300px;
  min-height: 900px;
  position: relative;
  width: 30%;
  background: #78787b;
}

.results-view {
  display: inline-block;
  height: 100%;
  padding-left: 10px;
  float: left;
  min-height: 900px;
  min-width: 200px;
  overflow-y: scroll;
  width: 55%;
}

.quick-viz {
  display: inline-block !important;
  position: relative;
  float: left;
  height: 100%;
  background: #78787b;
  overflow-x: scroll;
  margin-left: 10px;
}

Comment: a fiddle would be great!
Comment: why a max width to those divs? (without max width just use `width:33%;` or the like)
Comment: What are you working with so far? May I also suggest editing your 'question' to make it more applicable to the entire SO audience-- not just you.
Comment: _"How do I achieve what I want?"_ What have you tried?
Comment: er.. I told you what I tried - I'm working on a JS fiddle right now
Comment: OK, for some reason I can't get a fiddle to work - but I've posted my code now
Answer: Updated answer, exactly follows this structure (as requested):

Use a container:

CSS
.a, .b, .c {
    float: left;
    height: 200px;
    width: 21%;
    margin: 2%
}
.b {
    width: 46%;
}
.container {
    width: 100%;
    overflow: hidden;
}

DEMO: http://jsfiddle.net/dQQhz/4/
Comment: Updated after new details from OP


How are eigenfunctions found?

Question: Let's stick to the derivative operator and any other operators built up from it.  For instance, if $D = \frac{d}{dt}$, then the eigenfunction of $D$ is known to be $e^{at}$, associated with eigenvalue $a$.  However, what about for a more complicated operator?  Even something as simple as $1 + D$.
Is there a general method that works for any such operator?  For that matter, how was the eigenfunction for $D$ itself found?
Comment: @DHMO $T(f) = \color{blue}{\lambda} f$...?
Comment: In general, for an operation $T$, eigenfunctions are found by solving the functional equation $T(f) = f$.
Comment: Well...yes. I may not have been clear.  I think the question I had was: is there a general way to solve such an equation?
Comment: @mathreadler: I see, I guess much like differential equations.  I wonder, then, is there a suitable subset of operator equations that have a general method of solution, like the linear ODEs have?
Comment: Notice that linear ODEs /do/ comprise a class of operator equations, namely the class of equations of the form $P(D) f = g$, where $P$ is a polynomial with coefficients in an appropriate function space.
Comment: There are very many different methods to try and solve such equations.
Comment: $T(f) =\lambda f$ rather, for arbitrary $\lambda$. Then while solving the equation you get some additional conditions on $\lambda$, and then you would want to show that these are sufficient conditions for there to exist eigenvectors.
Comment: In this case, $D(f) = af$ is solvable through the integral $\int D(f)/f = at$, and eigenfunctions for your operator $1+D$  can be found in the same way
Comment: As long as we can represent the operator in question and the identity operator in some vector space we can try and solve it using linear algebra.
Comment: @mathreadler: I'd love to see an example of that, if you're willing (or can link it in).  I keep hearing that there is such a connection to vector spaces, but I've never been sure of how to set up the problem appropriately.
Answer: Eigenfunction of $D$
$$\begin{array}{rcl}
Df &=& af \\
\dfrac{\mathrm df}{\mathrm dt} &=& af \\
\dfrac{\mathrm dt}{\mathrm df} &=& \dfrac1{af} \\
t &=& \displaystyle \int \dfrac1{af} \ \mathrm df \\
t &=& \dfrac1a\ln f + C \\
f &=& ke^{at}
\end{array}$$

Eigenfunction of $1+D$
$$\begin{array}{rcl}
1+Df &=& af \\
Df &=& af-1 \\
\dfrac{\mathrm df}{\mathrm dt} &=& af-1 \\
\dfrac{\mathrm dt}{\mathrm df} &=& \dfrac1{af-1} \\
t &=& \displaystyle \int \dfrac1{af-1} \ \mathrm df \\
t &=& \dfrac1a\ln (af-1) + C \\
at-b &=& \ln(af-1) \\
f &=& \dfrac{1+e^{at-b}}a \\
\end{array}$$

In general
Apart from directly solving the equation, there are some general approaches.
For certain problems, one can use matrix to find eigenfunctions.
First, we choose a basis. A common basis is $\{1,x,x^2,x^3,\cdots\}$ (the polynomials). Then, we use a matrix to represent the operator, and then find the eigenvalue and the eigenvector of the matrix. The eigenvector represents the eigenfunction.
Limitations: Only works when the operator is linear, and obviously the basis cannot represent all functions.
Answer: For a minimal example an eigenfunction to the operator ${\bf T = D}^2+2{\bf D}$ on the space of $\{\sin(x),\cos(x)\}$.
The operator $D$ on this space is a matrix: $ {\bf D} = \begin{bmatrix}0&1\\-1&0\end{bmatrix}$
Therefore $${\bf T} = {{\bf D}^2+2{\bf D}} = \left[\begin{array}{cc}-1&2\\-2&-1\end{array}\right]$$
We can now solve $\det({\bf T}-\lambda {\bf I})$
$\lambda = -1\pm 2i$ $e = [\pm \sqrt{1/2} i , \sqrt{2}]^T$
So if we allow complex coefficients, apparently second derivative plus 2 times derivative of $$\left(\frac{\partial^2}{\partial x^2} +2 \frac{\partial}{\partial x}\right) \{i\sin(x)+\cos(x)\} = (-1+2i)(i\sin(x)+\cos(x))$$
And we can check it on Wolfram Alpha.
Comment: Fascinating.  So we require a vector space of functions to be defined as well.  That's what @DHMO was getting at, right, except they used an infinite dimensional space?  Very interesting.  Thanks

How are eigenfunctions found?


Pattern generation based on data frame in R

Question: I am looking to generate a pattern based on some columns of a data frame.
Sample data set could be :
domain <- c('ebay.com','facebook.com','auto.com')
id <- c(21000, 23400, 26800)
cost <- c(0.82,0.40,0.57)
rand_val <- c(0000807,0000808,0000809)
test_data <- data.frame(domain,id,cost,rand_val)

Based on COLUMNS of test_data i am looking to generate this pattern as text output:
if every domain = "ebay.com", id in (21000):
  rand_val:0000807
cost: 0.82
elif every domain = "facebook.com", id in (23400):
  rand_val:0000808
cost: 0.40
elif every domain = "auto.com", id in (26800):
  rand_val:0000809
cost: 0.57

How can i iterate based on number of rows in the data frame to produce this pattern.
Answer: You can  use paste with sep and collapse for this:
res <- paste('if every domain = "',test_data$domain, '", id in (', test_data$id, '):
  rand_val:', test_data$rand_val, '
cost: ', test_data$cost, sep="", collapse = "
el")
cat(res)

if every domain = "ebay.com", id in (21000):
  rand_val:807
cost: 0.82
elif every domain = "facebook.com", id in (23400):
  rand_val:808
cost: 0.4
elif every domain = "auto.com", id in (26800):
  rand_val:809
cost: 0.57

Comment: `if every domain = \"ebay.com\", id in (21000):\n  rand_val:807\ncost: 0.82\nelif every domain = \"facebook.com\", id in (23400):\n  rand_val:808\ncost: 0.4\nelif every domain = \"auto.com\", id in (26800):\n  rand_val:809\ncost: 0.57` this is what i get based your input, so i am getting a \n instead of a new line , and also this: \"ebay.com\", \"facebook.com\" as domains. can you help tweaking your code to produce the desirable result.
Comment: Yes this works perfectly, Thanks. However i saw we can use cat() function as well , which produces the same result.`cat(paste('if every domain = "',test_data$domain, '", id in (', test_data$id, '):\nrand_val:', test_data$rand_val, '\ncost: ', test_data$cost, sep="", collapse = "
el"))`. Anyways thanks for the help.


Changing a filter in a view without modifying the filter clone?

Question: I duplicated a block from view using clone display, but when I change the language on the block cloned filter, the filter is changed in the master view also. How to avoid this? I need 3 blocks, the block to master the English language and the other 2 blocks to English and Spanish.
Thank you
Answer: When you're changing a filter, before you apply there's a dropdown box. It's probably set to "All displays (except overridden)" by default. Before you hit Save, change that All Displays to "This display only"
Comment: Thanks for replying but in my view this option does not appear All Display. Must add that filter or it should come as standard on cloning?
Comment: Are you on Drupal 6 or 7? If on Drupal 6 then it's a bit different, you have to push the "Override" button when editing the filter.


SQL Server > How to query a sum from logs

Question: The table below contains state changes of three users over time.
I am trying to make a query that return the sum of the state of all users, but only from today most recent row.

idEvent | date   |    user     | state
5             | 05/22  |   client1 | 0       <- This number
4             | 05/22  |   client2 | 1       <- Plus this number
3            | 05/12  |   client1 | 0
2            | 05/12  |   client2 | 0
1            | 05/02  |   client3 | 1

With this data the sum of today most recent state from clients is 1 (client1 most recent state = 0 and client2 most recent state = 1).
So far i've come with

SELECT sum(a.states) FROM
(SELECT sum(state) AS states
FROM TABLE
WHERE day(date) = day(getdate()) AND month(date) = month(getdate()) AND year(date) = year(getdate())
group by user) a
but it sums every state of the day, not the most recent...
Can anyone help me ?
Cheers :)
Answer: One way is to use row_number() to find the most recent rows, as in:
select sum(t.states)
from (select t.*,
             row_number() over (partition by [user] order by [date] desc, idevent desc) as seqnum
      from [table] t
     ) t
where seqnum = 1;

This doesn't guarantee that they are from today.  For that, a where clause is needed:
select sum(t.states)
from (select t.*,
             row_number() over (partition by [user] order by [date] desc, idevent desc) as seqnum
      from [table] t
      where [date] >= cast(getdate() as date) and [date] < cast(getdate() + 1 as date)
     ) t
where seqnum = 1;

The where clause does not use any functions on the date column so appropriate indexes can be used (if available).
Comment: `user` must be in square brackets, otherwise the answer is wrong
Comment: @Aryadev . . . Yes (or double quotes).  No accounting for bad column names.  (Did you notice that the query in the question won't work for the same reason?)
Comment: yeah, it's interesting. It's the first time I see how poor column naming results in wrong query results :)
Answer: Use ROWNUMBER and PARTITION BY...
SELECT sum(STATE) FROM
(
SELECT *, ROW_NUMBER() OVER (PARTITION BY [USER] ORDER BY [DATE] DESC) AS ROWNUMBER
FROM #TEMP
) T
WHERE ROWNUMBER = 1


Como manter áudio de uma cena pra outra no Unity

Question: Preciso de ajuda.
Estou fazendo um jogo 2D no Unity. E gostaria de saber como faço pra manter o áudio (música de fundo) de uma cena pra outra e que ele continuasse de onde parou. E também como eu faria pra especificar as cenas que ele deve continuar, e as cenas que ele deve ser destruído.
Answer: Para reproduzir o áudio da sua música de fundo presumo que você tenha um game object na cena com um componente AudioSource anexado. Para manter este objeto existindo ao longo de outras cenas e mantê-lo reproduzindo a mesma música, você poder utilizar um script que o impeça de ser destruído durante o carregamento de cenas. Seria algo assim:
class DontDestroyThis : MonoBehaviour {

    void Start()
    {
        // Este método impede que o objeto
        // atual seja destruido durante o carregamento.
        DontDestroyOnLoad(gameObject);
    }
}

Simples assim, crie um script C# com o nome DontDestroyThis e utilize esta implementação no método Start. Anexe este script ao objeto que contém o AudioSource. Pronto, sua música de fundo continuará tocando ao longo das cenas.
Para definir quais cenas vc quer que ele continue tocando ou não, você poderia ter um outro script em cada uma das cenas que faria esse gerenciamento para você. Então você poderia usar os métodos Play, Stop, UnPause e Pause para controlar a reprodução do áudio. Exemplo:
using UnityEngine.SceneManagement;
class AudioManagerExample : MonoBehaviour
{
    private void Start()
    {
        // Obtém o objeto da cena que possui o AudioClip
        // é bom manter uma convenção para o nome deste objeto.
        // Neste exemplo BGM.
        GameObject audioSourceGameObject = GameObject.Find("BGM");

        // Obtém o componente AudioSource do objeto.
        AudioSource source = audioSourceGameObject.GetComponent<AudioSource>();

        // Utilize as linhas abaixo conforme necessário
        // para controlar a reprodução.
        source.Play();      // Inicia a reprodução do áudio.
        source.Stop();      // Pára a reprodução do áudio, inicia do começo quando for reproduzido novamente.
        source.UnPause();   // Despausa a reprodução previamente pausada. Similar ao Play após um audio ter sido pausado.
        source.Pause();     // Pausa a reprodução.

        // Exemplo:
        if(SceneManager.GetActiveScene().name == "NomeDaCenaDesejada")
        {
            source.Play();
        }
        else
        {
            source.Stop();
        }
    }
}

Para mais informações, você pode consultar a documentação da API de script do componente AudioSource diretamente no site da Unity:
https://docs.unity3d.com/ScriptReference/AudioSource.html


multivariable calculus - Proving that this limit exists with polar coordinates

Question: I have the following limit:
$\lim \limits_{(x, y) \to (0,0)} \cfrac{x^2y^2}{x^2+y^4}$
According to my book the limit is supposed to exist and be equal to 0, but I'm not sure what I'm doing wrong.
First, I try to approach it from two different directions, I'll skip this and say that I tried 3 different directions and got 0 everytime. Now onto polar coordinates:
$\lim \limits_{\rho \to 0} \cfrac{\rho cos^2 \theta \rho^2sin^2\theta}{\rho^2cos^2\theta+\rho^4sin^4\theta} = \lim \limits_{\rho \to 0} \cfrac{\rho^4cos^2\theta sin^2\theta}{\rho^2(cos^2\theta+\rho^2sin^4\theta)}$
Simplifying the above expression:
$\lim \limits_{\rho \to 0} \cfrac{\rho^2cos^2\theta sin^2\theta}{cos^2\theta+r^2sin^4\theta}$
Now, when $\rho \to 0$ the above function is dependant on theta, and even though the numerator tends to $0$ there's the chance of $\theta = k\pi-\cfrac{\pi}{2}$ meaning that we'd end up with $cos^2\theta = 0$ therefor we'd be in a $0/0$ situation. Because of that, the above limit is dependant on $\theta$ and not $\rho$, and that means that the function will assume different values on different directions, meaning that the limit does not exist, but according to my textbook the limit is 0. I really can't understand what I'm doing wrong.
Comment: Hint: you have 2 cases: the limit when $\cos \theta \neq 0$, which is easy to compute; and the case when $\cos \theta = 0$, which is also easy to compute.
Comment: I am writing an answer, I request you to wait.
Answer: Up till the quotient $\frac{\rho^2 \cos^2 \theta\sin^2 \theta}{\cos^2 \theta + \rho^2\sin^4 \theta}$ you are fine.

Now when $\rho \to 0$ the above function is dependent on $\theta$.

All right, but the dependency is not good enough to prevent the limit being zero!

there is a change of a $0/0$ at $k\pi - \frac{\pi}{2}$.

Indeed, note that at such values of $\theta$, the denominator is not zero because the sine term is not zero! Whatever path we approach $(0,0)$ from, the denominator cannot be zero, because one of the two terms will always be non-zero.

The function will assume different values in different directions, meaning that the limit does not exist.

Once again, not different enough to prevent convergence to zero. Yes, it behaves "very differently" if we approach along the lines $\theta = 15^\circ$ and $75^\circ$, but it doesn't matter : convergence to zero will happen.
The point is, that you haven't done anything wrong, but just panicked, thinking that the function could do different things for different $\theta$. Yes, it does do different things, but near $(0,0)$ those things aren't far off each other. What's the reason?
What you've got to see is this :what is the dominant term of the expression? Which term of the expression exerts the most influence on  the expression when your point is close to $(0,0)$?
Well, $\sin \theta$ and $\cos \theta$ are always confined to $[-1,1]$, so their behaviour is always limited, in that you can always bound their behaviour by the constants $-1$ and $1$. Let us use this fact.
How do we use it? Let us make a small transformation, where we take the $\rho^2$ to the denominator.
$$
\frac{\rho^2 \cos^2 \theta \sin^2 \theta}{\cos^2 \theta  + \rho^2 \sin^4 \theta} = \frac{\cos^2 \theta \sin^2 \theta}{\sin^4 \theta + \color{blue}{\rho^{-2}}\cos^{2} \theta}
$$
Now, we look at the numerator. Regardless of the value of $\theta$, we have that the numerator will be between $-1$ and $1$. So, the numerator doesn't really move here : all the big stuff is in the denominator.
In the denominator, the point is that $\mathit \rho$ is super super small, so $\rho^{-2}$ is super super big. Therefore, if $\sin \theta \neq 0$, the contribution of $\rho^{-2}\sin^4 \theta$ can be made much much larger than the contribution of $\cos^2 \theta$ by simply taking $\rho$ small enough.
If $\sin \theta = 0$ then $\cos \theta = 1$ so the denominator is $1$,  but then the numerator is zero, so the given expression is zero.
Either way, you see , at least geometrically, that independent of $\mathit \theta$, the given expression behaves very much like $0$ for $\mathit \rho$ chosen sufficiently small.
Of course, other answers will suggest how  to approach this rigorously, but your takeaway should be this : as long as there's a "controlling/dominating term" (imagine a policeman trying to prevent people getting out of their houses during a curfew), there's not much that varying $\theta$ can get you : the misbehaviour of the changing $\theta$ is only so much.
Which, of course, is also the content of the famous squeeze principle or sandwich theorem of limits. From a rigorous point of view, the answer to these sort of questions is to identify bounds for the non-dominating terms, and use the squeeze principle, as the others have done.
Comment: Thank you very much for your detailed response!
Comment: You are welcome! Please read carefully the details : I like the fact that you have seen this limit geometrically and then deduced it did not exist , because it allows me to correct you and show you the geometric picture better.
Comment: I saved your comment, it was an amazing explanation. Thanks again :)
Answer: If $\cos^{2}(\theta)=0$ then $sin^{2}(\theta) =1$ so you don't have  a $\frac 0 0$ situation.
Proof that the limit is $0$: $2xy^{2}\leq x^{2}+y^{4}$ so $|\frac {x^{2}y^{2}} {x^{2}+y^{4}}|\leq  \frac 1 2 |x| \to 0$.
Answer: Polar coordinates aren't necessary here. You may use the inequality

$\sqrt{ab} \leq \frac{a+b}{2}$ for $a,b\geq 0$
$\Rightarrow x^2 + y^4 \geq 2\sqrt{x^2y^4}=2|x|y^2$.
Note that if either $y= 0$ or $x= 0$ the expression is equal to zero anyways.

So, let's assume $xy \neq 0$:
$$\frac{x^2y^2}{x^2+y^4}\leq \frac{x^2y^2}{2|x|y^2}=\frac{|x|}{2} \stackrel{(x,y)\to (0,0)}{\longrightarrow}0$$


Why is a template being looked in a theme and not in my module?

Question: I have created a custom module. in that module I have create a custom twig template using hook_theme function
function mymodule_theme($existing, $type, $theme, $path) {
  return array(
    'mymodule_settings' => array(
      'variables' => array(
        'role' => NULL,
      )
    )
  );
}

Then I created a custom block using my module here is the code of the block
public function build() {
    $config = \Drupal::config('mymodule.config');
    $role = $config->get('role');
    return array(
      '#theme' => 'mymodule_settings',
      '#role' => $role,
    );
  }

I created a templates directory in my module and inside that directory I have created mymodule-settings.html.twig file.
Cleared the cache but Drupal gives me the following error.
Twig_Error_Loader: Template "themes/subtheme/templates/mymodule-settings.html.twig" is not defined (Drupal\Core\Template\Loader\ThemeRegistryLoader: Unable to find template "themes/subtheme/templates/mymodule-settings.html.twig" in the Drupal theme registry.). in Twig_Loader_Chain->getCacheKey() (line 45 of themes/basetheme/templates/block.html.twig).

My theme is a subtheme. Why Drupal is looking for the template in the theme and not in my module?
Comment: This should be working, are you sure it is nog a typo in the hook_theme name? Cleared cache?
Comment: The problem was, I was using the same name for custom module and my subtheme. Should I delete the question?
Answer: Try like this:
function mymodule_theme($existing, $type, $theme, $path) {
  return array(
    'mymodule_settings' => array(
      'variables' => array(
        'role' => NULL,
      )
      'template' => 'mymodule-settings',
    )
  );
}

You are missing to define template.
Comment: Template doesn't have to be defined, when omitted it searches for mymodule-settings.html.twig by default.
Comment: I think it searches by default in theme template folder, not module folder. I am not specific on this but for my case it happened and I defined template in hook_theme().


Absolutely convergent sequence, but no measure

Question: Let $(X, \mathcal A)$ a measure space, $\mu : \mathcal A \rightarrow (- \infty, \infty)$ a map with the following properties:
(i) $\mu(\emptyset) = 0$
(ii) For all pairwise disjoint families $(A_j)$ with $A_j \in \mathcal A$, $\sum \mu(A_j)$ converges absolutely and $\mu ( \cup A_j) = \sum \mu(A_j)$.
Then it does not necessarily follow that $|\mu|: \mathcal A \rightarrow [0, \infty)$ is a measure. But why?
Answer: Consider $X=\mathbb{R}$ and $\mu=\delta_1-\delta_0,$ were $\delta_x$ is dirac mass at $x$.
Then, $\mu$ clearly satisfies the given, but $|\mu|(\{0\})=|\mu|(\{1\})=1,$ while $|\mu|(\{0,1\})=|1-1|=0,$ so even finite additivity might fail.


tree has exactly $k$ nodes with degree $4$. Show that this tree has $2k+2$ leaves.

Question: Prove:
If a tree has exactly $k \geq 1 $ nodes with degree $4$, then this tree has at least $2k +2 $ leaves. ( nodes with degree $< 4 $ are only allowed for the leaves ).
So I think that we can solve this with induction.
$ k = 1$ :
So we have exactly one node with degree $4$. this node has to have at least $4$ leaves, because of the degree. Or am I wrong?
$ k \rightarrow k+1$:
We have a tree with $k$ nodes with degree $4$. We know that we have at least $2k+2$ leaves. We replace one of the leaves with a node and build a node of degree $4$. So we "lost" a leave but "gain" 3 new leaves. So we conclude that we have a tree with $k+1$ nodes with degree $4$ and $2k+2-1+3 = 2k+4 =2(k+1) +2 $ leaves. Am I right?
Answer: Your proof could be made to work but there is still more you need to do for it to be considered a proof.
The one detail you need to observe is that you can construct any tree w $k+1$ degree-4 nodes from one with $k$ nodes as you did. What if all nodes adjacent to a leaf have degree 5 or greater? A way around this is to conclude that a tree with $k''$ nodes of degree at least 4 has at least $2k''+2$ leaves.

An alternate proof: Let $F$ be a forest where every nonleaf vertex has degree at least 4. Let $n$ be the number of vertices in $F$. The number of edges that $F$ can have is at most $n-1$ with equality reached iff $F$ is a tree and not a forest with two or more connected components. [make sure you see why]
Let $k$ be the number of vertices of degree 4 and $k'$ the number of vertices of degree 5 or greater.
Letting $l$ be the number of leaves, then $n=l+k+k'$. So the number of edges that $F$ can have is at most $n-1 =$ $l+k+k'-1$.
The number of edges $F$ has however at least $\frac{1}{2} (5k'+4k+l)$ [this is $\frac{1}{2}$ times a lower bound on the sum of the degrees of the vertices of $F$, make sure you see why that is the number of edges in $F$]
Thus $2(l+k+k')-2 \ge 5k'+4k+l$ $\implies$ $l \ge 3k'+2k+2$.
*****If every interior vertex has degree 4 and the graph is a tree then this inequality is tight. Can you trace through the proof to see why?
*****You could trace through this proof to conclude: $l=\sum_{d \geq 2} (k_d-2)+2$, where $k_d$ is the number of vertices of degree $d$ $(d=2,3,\ldots$) if the graph is a tree, and $l=\sum_{d \geq 2} (k_d-2)+1+c$, if the graph is a forest with $c$ distinct connected components. From this the lower bound of $l \geq 2k_4+2$ for $l$, which is what you wanted to derive, is an immediate consequence.
Comment: I don't think your proof is correct.  A tree with $k$ vertices of degree $4$ may have vertices of degree $3$ for example.  So, $n=l+k$ is not correct.  Also, $F$ does not necessarily have $\dfrac{4k+l}{2}$ edges.
Comment: @Batominovski in general yes but the assumption by the OP is that only leaves have degree $<4$
Comment: What about vertices of degree more than $4$?  There is no restriction on that.
Comment: @Batominovski fixed it to allow for that possibility
Comment: For whatever reason I had read that every interior vertex has degree 4
Comment: I think you flipped the inequality.
Comment: Corrected......
Answer: I do not see why it is important to include the condition that only vertices of degree less than $4$ are leaves.  I am going to prove a general statement.  Note that this proof can be rewritten so that it is an inductive proof

Proposition.  Let $k\geq 1$ and $d\geq 2$ be integers.  Let $T$ be a (finite) tree with exactly $k$ vertices of degree $d$.  Then, $T$ has at least  $(d-2)k+2$ leaves.

Suppose on the contrary that, for some positive integer $k$, there exists a tree with exactly $k$ vertices of degree $d$ but with fewer than $(d-2)k+2$ leaves.  Take $T$ to be such a tree with the smallest possible $k$.  If $k>1$, then let $u$ be a vertex of $T$ with degree $d$.  Suppose that $v_1,v_2,\ldots,v_d$ are the neighbors of $u$.  Let $C_i$ be the connected component of $T-u$ containing $v_i$, for $i=1,2,\ldots,d$.  Take $T_i$ to be the tree with vertices from $C_i$ and an extra vertex $u_i$, which is a leaf and adjacent to $v_i$.
For a graph $G$, let $n_t(G)$ denote the number of vertices of degree $t\in\mathbb{Z}_{\geq 0}$ in $G$.  Clearly, we have
$$\sum_{i=1}^d\,n_1(T_i)=n_1(T)+d<\big((d-2)k+2\big)+d\,.$$
Since $T$ is a tree with the smallest $k=n_d(T)$ that violates the claim, we must have
$$n_1(T_i)\geq (d-2)\,n_d(T_i)+2$$
for all $i=1,2,\ldots,d$.  This shows that
$$\begin{align}\big((d-2)k+2\big)+d&>\sum_{i=1}^d\,n_1(T_i)\geq \sum_{i=1}^d\,\big((d-2)\,n_d(T_i)+2\big)
\\&=(d-2)\,\sum_{i=1}^d\,n_d(T_i)+2d=(d-2)\,(k-1)+2d\\&=\big((d-2)k+2\big)+d\,.\end{align}$$
This is absurd, so the assumption that $k>1$ cannot be true.  Hence, $k=1$.
However, it is easy to show that every tree with exactly $1$ vertex of degree $d$ as at least $d$ leaves.  Thus, $k=1$ cannot hold either, and the proposition must be true.  (Note that the minimum number of leaves $(d-2)k+2$ is achieved if and only if $T$ has only vertices of degree $1$ or $d$.  In such cases, $T$ has $(d-1)k+2$ vertices and $(d-1)k+1$ edges.)

Corollary.  For integers $d_1,d_2,\ldots,d_m$ with  $1<d_1<d_2<\ldots<d_m$, we have $$n_1(T)\geq \sum_{i=1}^m\,(d_i-2)\,n_{d_i}(T)+2$$ for every tree $T$ with at least two vertices.

As before, $n_t(G)$ denote the number of vertices of degree $t\in\mathbb{Z}_{\geq 0}$ in a finite graph $G$.  In the corollary, the equality holds iff $n_t(T)=0$ for every integer $t\geq 2$ such that $t\notin \{d_1,d_2,\ldots,d_m\}$.  In this case, $T$ has exactly $\displaystyle\sum_{i=1}^m\,(d_i-1)\,n_{d_i}(T)+2$ vertices and  $\displaystyle\sum_{i=1}^m\,(d_i-1)\,n_{d_i}(T)+1$ edges.
Comment: Yes indeed, if you know the number $n_d$ of nodes of degree $d$ for each $d \geq 3$ and the number $c$ of components in the forest, you can calculate exactly the number of leaves which is $1+c+\sum_{d \geq 3} n_d(d-2)$. A lower bound of $2n_4+2$ for a tree, which the OP was asked to establish, is an easy consequence from this formula. Good answer!


rsyslog: using message properties in a template

Question: I am running Docker with journald log driver, and I am using rsyslog (v8.29.0) to collect these messages and write them to a file annotated with information about the container.  The problem I have encountered is that I am not able to use message properties in the $! namespace in templates unless I first move them into e.g. the local $. namespace.
I started with this configuration:
module(load="imjournal" StateFile="imjournal.state")

template(name="ContainerTemplate" type="list") {
    property(name="timereported" dateFormat="rfc3339" caseConversion="lower")
    constant(value=" ")
    property(name="$!CONTAINER_NAME")
    constant(value=" ")
    property(name="$!CONTAINER_ID")
    constant(value=" ")
    property(name="msg")
    constant(value="\n")
}

if (strlen($!CONTAINER_NAME) > 0) then {
    action(type="omfile"
        file="/var/log/containers.log"
        template="ContainerTemplate")
}

Even when $!CONTAINER_NAME and $!CONTAINER_ID are defined, they expand to empty strings in the resulting template.  I can work around it like this, by explicitly setting new properties using the value of the existing properties:
template(name="ContainerTemplate" type="list") {
    property(name="timereported" dateFormat="rfc3339" caseConversion="lower")
    constant(value=" ")
    property(name="$.container_name")
    constant(value=" ")
    property(name="$.container_id")
    constant(value=" ")
    property(name="msg")
    constant(value="\n")
}

if (strlen($!CONTAINER_NAME) > 0) then {

    set $.container_name = $!CONTAINER_NAME;
    set $.container_id = $!CONTAINER_ID;

    action(type="omfile"
        file="/var/log/containers.log"
        template="ContainerTemplate")
}

This works fine...but, if I change the case of the local variables (i.e., if I use $.CONTAINER_NAME and $.CONTAINER_ID instead of the lower-case equivalents), it behaves the same as the original configuration (I get empty strings in the log even though I am explicitly setting the properties).
Do you know what's going on here?  According to the the docs, the property statement "can access all properties", so I am confused.
Answer: I ran into the same issue and fixed it by making the template case sensitive.
Alter the line
template(name="ContainerTemplate" type="list") {
into
template(name="ContainerTemplate" type="list" option.casesensitive="on") {


Progress 4GL - is CRC value of table fixed for repeated loading .df?

Question: I'm facing CRC error occurs with existing r-code after loading a .df file without adding the POSITION of the field in it.
Step 1:
I have loaded the .df file with adding POSITON of the field for the first time and compiled my .p program..The program was working fine without any issues
CRC value for table(4692) and .r (4692) matched.
Step 2:
I have loaded the same .df file but this time without adding the POSTION of the field in it.
I found CRC value for table(64665) and .r(4692) mismatched. so that I am getting CRC error.
Now my question here is that..is this CRC error will be fixed if I load the same .df(Step 1)?
If yes then after loading CRC value for table and .r will be matched? so that I dont need recompilation
Answer: Yes, if the df is the same, then the CRC will match.
There are certain changes that have no effect on CRC but that's not your question. :)
Comment: see https://knowledgebase.progress.com/articles/Article/20245 for changes that affect CRC
Comment: CRC calculations and related issues can also be sensitive to the version of Progress that you are using.
Comment: Please enlighten me what are certain changes that have no effect on CRC


Is using `@code_lowered` an effective way to troubleshoot performance issues in Julia?

Question: I want to see if there are any performance issues with the Julia code I have written. I know that the @code_lowered provides a good look into how the compiler is interpreting the code, but when exactly would this @code_lowered be most useful. Are there certain sorts of performance or other issues that it does well at highlighting (if you can understand the printouts) whereas in other cases it's less useful?
I also know there are other awesome profiling tools out there in Julia, I am just trying to generally understand the use cases for each.
julia> @code_lowered Int(1.0)
CodeInfo(
1 ─ %1  = -9.223372036854776e18 <= x
└──       goto #3 if not %1
2 ─       @_3 = x < 9.223372036854776e18
└──       goto #4
3 ─       @_3 = false
4 ┄       goto #6 if not @_3
5 ─ %7  = Base.round(x, Base.RoundToZero)
│         @_4 = %7 == x
└──       goto #7
6 ─       @_4 = false
7 ┄       goto #9 if not @_4
8 ─ %12 = Base.unsafe_trunc(Int64, x)
└──       return %12
9 ─ %14 = Base.InexactError(:Int64, Int64, x)
│   %15 = Base.throw(%14)
└──       return %15
)

Comment: All introspection macros can be useful, but IMHO `@code_warntype` is the most important. It shows you type instabilities (highlighted in red).
Answer: @code_lowered is not useful for understanding performance.
@code_warntype is best.
Basically the different steps:
Parsing:
Source code -> Abstract Syntax Tree (like what one manipulates with macros), blocks like loops and conditionals are branches in the tree.
You can see it by quoting the source code.
quote
    if x>1
       x=x-1
    end
end

Lowering:
Abstract Syntract Tree -> Lowered Intermediate Representatation (IR), which i think is best describnes as an abstract syntax list,
Basically nothing has been done to it, no optimization etc.
Just the tree form has become a list where nothing has subexpressesions, instread each temporary is on its own line. Loops and ifs becomes various kinds of jumps (like labels and conditional gotos)
A few things change to lowered representation like the end in  xs[end-1] becomes lastindex(xs)
This lowering can be done fully ahead of time, it doesn't need the JIT.
it is just a transform of the syntax
You can access it via @code_lowered f(x) for some function f taking argument x.
or if you have a Method then you can do Base.uncompressed_ast(method).
Specialization
The type information is made use of, and the optimizer runs.
Things get inlined, conditions that are always true or false are removed (e.g. checks on types).
The lowered IR gets turned into Typed IR.

@code_typed f(x) gets you this.
@code_typed optimize=false f(x) gets you this without the optimization step being run.
@code_warntype f(x) gets you this with extra helpful performance annotations highlighting type instabilities

This is one of the most useful layers to look at.
Probably second only to the source-code itself.
Code-generation (LLVM)
This is where we Typed IR becomes LLVM.
And LLVM internally goes through like a bunch of intermediate representations.
LLVM does a ton of optimization of its own.
e.g. various maths intrinstics constant propagate as this stage.
Access this via @code_llvm f(x)
This is the next most useful stage after Typed.
(Tying with Native Machine code, depending if you read LLVM IR better or worse than Assembly).
Code-generation (Assembly)
The LLVM becomes Assembly,
human readable machine code basically.
Access this via @code_native f(x)
After that there is only assumbling, to machine code.
Though I suspect that the assembly is normally bypassed as one goes straght from LLVM to machine-code since they are 1-1.

See also: https://stackoverflow.com/a/43456211/179081
Comment: What does IR stand for?
Comment: Intermediate Representatation
Comment: See also: https://stackoverflow.com/questions/43453944/what-is-the-difference-between-code-native-code-typed-and-code-llvm-in-julia


Removing external CSS files with hook?

Question: My theme is adding the following CSS below. How can I remove it? I know that with Drupal 6 you can do stylesheets[all][] = in the .info file but what about Drupal 7? Can hook_css_alter() be used on an external file?
<link type="text/css" rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" media="all" />

Answer: Yes, hook_css_alter can be used with external CSS.
Answer: You can use the following code to remove your external css
function hook_css_alter(&$css) {
  // Remove defaults.css file.
  unset($css['path of you external css']);
}

Answer: Use function hook_css_alter you can unset css
function hook_css_alter(&$css) {
  // Remove defaults.css file.
  unset($css[drupal_get_path('module', 'system') . '/defaults.css']);
}

Answer: You can use function hook_css_alter. This hook function will alter CSS files before they are output on the page.
//This hook function will unset css.
function hook_css_alter(&$css) {
    // Remove defaults.css file.
    unset($css['CSS FILE PATH']);
}

In additionally, you want to remove core css then follow below code:
function hook_css_alter(&$css) {
    $exclude = array(
        'misc/vertical-tabs.css' => FALSE
    );
    $css = array_diff_key($css, $exclude);
}

just add $exclude to your info to remove a CSS file. This is simple way to remove css file.
Let me know if there is any doubt/query from this.

Removing external CSS files with hook?


Ubuntu Server not rebooting but will power off

Question: I have 2 identical servers running Ubuntu 9.10 and I've been playing with Ubuntu's upstart system, trying to write a sort-of complex boot order for a few services.
I've also played with init scripts to try and achieve the required effect, but I've now removed all my initscripts.
I've been doing this only on one server.  Part way through my development of my upstart scripts, I noticed that the server wasn't rebooting properly - it kills off rsyslog-kmsg then just sits there.  If you run the reboot command again, it reboots.
I removed all traces of the scripts I created and still it won't reboot, so I'm now thinking of done something but I cannot work out what I've done that I haven't reversed.
The other server is perfectly fine.  I've compared the timestamp of the upstart scripts (in /etc/init) and copied over the init.d, rc[0-6].d directory contents onto the first server, but it still won't reboot.
The strange thing is, if you do halt instead of reboot, it powers off as normal - it just won't reboot.
There are no messages in dmesg or /var/log/messages after the boot process completes.
Any ideas?  I'd prefer not to have to re-install the OS as it's a remotely-hosted server.
Answer: Just as a follow-up, I found the Ubuntu net installer, so it was a lot quicker to re-install the OS.


How can I automatically log out all machines on a windows domain?

Question: Our Sophos Anti-virus scans each night, but complains about files it can't access. Files that are in use by Firefox or Outlook.
Is there a script we can configure to run each night before the scans, which logs the user out of the machine?
Ideally, this would bring up a prompt beforehand offering the user the chance to remain logged in, should they be working late.
Thanks,
Dean.
Comment: Time for a better virus scanner perhaps? One that doesn't require the user to be logged off in the middle of the night and loose everything that they might have open on their desktop so when they come back the next morning they have to spend 10 minutes re-opening all their programs...
Comment: Solved the problem by changing the reporting options to not complain when a file is in use...
Comment: Farseeker; great observation! Sometimes the answer to the question is not directly related to the original question. =)
Answer: EDIT: The following suggestion in my post only effects SMB connections and will not log off a user's interactive session like I thought it would. See this google cached Experts Exchange thread for a long discussion on it (scroll all the way down to see the thread past the filthy lies that you have to be logged in to see the thread). Thanks to Evan Anderson for setting me straight. It seems that a pstools script or batch file would be the only way to achieve this.
Someone feel like downvoting me to remove the undeserved points?

Maybe I'm missing something, but won't the domain policy "Automatically log off users when logon time expires" be applicable in this scenario? Just create the hours that you want people to be able to log on and then restrict them accordingly to have them all logged off. Be careful when applying this policy though. If I understand correctly, it can only be applied to the domain root and there are some other caveats. You may be better off applying a local group policy via a domain policy and a security template... ? Things are getting complex here. =)
If you have an Experts-Exchange account (you can get one genuinely for free if you look in their help pages hard enough in spite of their filthy lies that you have to pay to become a member; I've blogged about it here) you can read this thread about a similar situation and the solution.
You could also look into "How To Force Users to Quit Programs and Log Off After a Period of Inactivity in Windows XP" as per KB314999.
Comment: You can view the whole discussion here without having to give anything to the sex changers (just scroll to the bottom of the page): http://188.8.131.52/search?q=cache:7uHCPur91DsJ:www.experts-exchange.com/Security/Win_Security/Q_20444094.html+cached:http://www.experts-exchange.com/Security/Win_Security/Q_20444094.html&cd=2&hl=en&ct=clnk≷=au&client=firefox-a.
Comment: (thats a google cache link, btw, if you're wary about clicking a link with an IP address in it)
Comment: I am wary of IP address URLs, but -- frighteningly enough -- I thought the IP address looked somewhat familiar... =)
Answer: There's no built-in functionality to do what you want, so you're definitely going to have to have something coded.
I can't tell you about Vista or Windows 7, because I don't have one handy right now to test on, but a "shutdown -l" (as phuzion mentioned) on Windows XP run as SYSTEM (invoked by the "Task Scheduler" service) will cause the session for the interactive user to logoff. Conceivably this might be different on Vista and Windows 7.
You could probably rig something ugly with wprompt, a .BAT file, and "Scheduled Tasks", but you'll have to schedule it with the "AT" command to get it to interact with the Desktop, and you'll have an ugly command-promt window popping up. (Okay, okay-- I can think of a way to do it with VBScript and that wprompt utility that wouldn't cause an ugly command prompt window to pop up. It's still ugly, though.)
Comment: That setting has nothing to do with interactive logons. It affects the "Server" service and prevents clients from "mapping drives" or otherwise accessing shared resources on file server computers when the logon hours expire. I'm having a hard time finding a newer reference from Microsoft, but here's a reference that is old but still applies to newer versions of Windows: http://msdn.microsoft.com/en-us/library/ms814138.aspx
Comment: Does the "Automatically log off users when logon time expires" GPO option not apply to this situation like I thought it did?
Comment: Note you can use "shutdown -l -m \\computername" to do so remotely. You'll need to run this as a domain admin.
Comment: Thanks for the clarification, Evan! I edited my post accordingly.
Answer: You should be able to create a batch file that will log the user out, and execute it remotely with psexec.
The command you would want to include in the batch file would be:
<code>shutdown -l
</code>
I'd suggest against doing this though, as many people will be frustrated with you in the morning when they find out that their unsaved documents are completely gone.
Comment: no need to use PSEXEC.   We have the server run a single batch file that actually does a restart passing the computer name to the shutdown command
shutdown -r /m \\computer1...


Number of item in cart at theme level

Question: I have to display number of item in cart/basket in design where I can't use the menu. So my question is...how to access number of item of cart at theme level?
Is there any function for template file which can return me this, so that I can show it in page.tpl.php ?
Answer: You can use commerce_cart_order_load() to load the order for the current user, and an EntityMetadataWrapper to extract the relevant field data, and commerce_line_items_quantity() to get at the actual quantities. e.g.
if ($order = commerce_cart_order_load($GLOBALS['user']->uid)) {
  $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
  $quantity = commerce_line_items_quantity($order_wrapper->commerce_line_items);

  // Do something with $quantity...
}

This code can be used in a module or theme.
Comment: You took no time in responding & it works like charm...Thanks :)
Comment: You can also check out the implementation in commerce_cart_menu_item_title().

Number of item in cart at theme level


iPad book framework/platform/pattern available?

Question: I have just started with iOS development (getting close to finishing my first app).  For my next app I want to convert a children's book that my wife wrote and illustrated into a free iPad book.
I am wondering if anyone knows of a framework that would provide me a lot of the basics for handling page turns, basic audio, maybe a table of contents, gesture recognition, etc.
Thanks in advance!
Jason
Answer: Try the Baker Ebook Framework http://bakerframework.com/
Comment: Is it possible to do a full text search using this framework? If not how do i get to it if this functionality is needed in my app?
Answer:
free HTML5 ebook framework http://bakerframework.com/
laker http://www.lakercompendium.com/
pug pig  http://pugpig.com/
bakershelf https://github.com/nin9creative/baker


IReports, gerar número variável de subrelatorios

Question: estou utilizando o Jasper para geração de relatórios, utilizo o IReport para construir os Layouts .Possuo um relatório principal que possui um sub relatório (o motivo do meu problema), o meu relatório principal recebe uma lista de objetos, preciso gerar um subrelatorio para cada item desta lista e popular este subRelatorio com o respectivo item da lista. Alguém sabe como fazer isso, é possível fazer isso?
Answer: Você pode colocar um table no seu relatório principal.
Algo como:
<jr:table xmlns:jr="http://jasperreports.sourceforge.net/jasperreports/components" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports/components http://jasperreports.sourceforge.net/xsd/components.xsd">
                <datasetRun subDataset="ItemDataset" uuid="d3e1e03a-2c83-4436-9e50-79518bc3d337">
                    <dataSourceExpression><![CDATA[$P{ItemDataSource}]]></dataSourceExpression>
                </datasetRun>
                <jr:column width="130" uuid="dca8961f-ce2d-47ac-879c-b15847d170a9">
                    <property name="com.jaspersoft.studio.components.table.model.column.name" value="Column1"/>
                    <printWhenExpression><![CDATA[new Boolean(($V{REPORT_COUNT}.intValue()%2==0))]]></printWhenExpression>
                    <jr:tableHeader height="31" rowSpan="1">
                        <staticText>
                            <reportElement mode="Opaque" x="0" y="0" width="130" height="31" forecolor="#FFFFFF" backcolor="#3C8DCB" uuid="f60d1675-6fb6-4569-93ca-de32b3a8e861"/>
                            <textElement textAlignment="Center" verticalAlignment="Middle">

                            </textElement>
                            <text><![CDATA[Descrição]]></text>
                        </staticText>
                    </jr:tableHeader>
                    <jr:detailCell height="30" rowSpan="1">
                        <textField>
                            <reportElement mode="Opaque" x="0" y="0" width="130" height="30" backcolor="#FFFFFF" uuid="f1de366a-b36f-4200-9b1e-7a0009be5373"/>
                            <textElement textAlignment="Center" verticalAlignment="Middle"/>
                            <textFieldExpression><![CDATA[$F{nome}]]></textFieldExpression>
                        </textField>
                    </jr:detailCell>
                </jr:column>
                <jr:column width="140" uuid="980fffb5-1088-47a6-b00f-b5d08b7093c9">
                    <property name="com.jaspersoft.studio.components.table.model.column.name" value="Column2"/>
                    <jr:tableHeader height="31" rowSpan="1">
                        <staticText>
                            <reportElement mode="Opaque" x="0" y="0" width="140" height="31" forecolor="#FFFFFF" backcolor="#3C8DCB" uuid="16679b95-2e6e-4ca1-b8b6-dd7b74267c56"/>
                            <textElement textAlignment="Center" verticalAlignment="Middle">

                            </textElement>
                            <text><![CDATA[Valor]]></text>
                        </staticText>
                    </jr:tableHeader>
                    <jr:detailCell height="30" rowSpan="1">
                        <textField>
                            <reportElement mode="Opaque" x="0" y="0" width="140" height="30" backcolor="#FFFFFF" uuid="341e7faf-9680-4941-a9a4-ac78b8f4aae0"/>
                            <textElement textAlignment="Center" verticalAlignment="Middle"/>
                            <textFieldExpression><![CDATA[$F{valor}]]></textFieldExpression>
                        </textField>
                    </jr:detailCell>
                </jr:column>
            </jr:table>

e no Java você envia os dados da lista que quer que seja uma  tabela de resultados.
Comment: Funcionou, obrigado. Um forte abraço.
Comment: Vou tentar desta forma.


Inserir gráficos automaticamente no github pages

Question: ao criar um arquivo .md para a pasta _post do github pages com o rstudio os gráficos gerados com os comandos do R devem ser inseridos um a um via o comando:
![center](/nome_pasta_imagens_dentro_da_master/nome_da_figura.png)

Ou existe alguma forma de renderizar automáticamente os gráficos gerados sem criar um comando para cada um?
Desde já agradeço!
Comment: Você pode dar uma olhada nesse repositório https://github.com/yihui/knitr-jekyll
Answer: Existe uma forma muito fácil de fazer isso: coloque os códigos das figuras (em R) em um arquivo rmarkdown (Rmd) e compile para o formato markdown do Github.
Só para dar um exemplo, vamos criar um arquivo no rstudio a partir de um template compatível com o Github Flavored Markdown (vou me referir a ele como GFM).

O arquivo criado é o seguinte:
---
title: "Untitled"
output: github_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

## GitHub Documents

This is an R Markdown format used for publishing markdown documents to GitHub. When you click the **Knit** button all R code chunks are run and a markdown file (.md) suitable for publishing to GitHub is generated.

## Including Code

You can include R code in the document as follows:

```{r cars}
summary(cars)
```

## Including Plots

You can also embed plots, for example:

```{r pressure, echo=FALSE}
plot(pressure)
```

Note that the `echo = FALSE` parameter was added to the code chunk to prevent printing of the R code that generated the plot.

Veja que há um plot com o comando:
plot(pressure)

Clique no botão knit

que o arquivo será compilado para o markdown, no formato apropriado para o Github.
Untitled
================

GitHub Documents
----------------

This is an R Markdown format used for publishing markdown documents to GitHub. When you click the **Knit** button all R code chunks are run and a markdown file (.md) suitable for publishing to GitHub is generated.

Including Code
--------------

You can include R code in the document as follows:

``` r
summary(cars)
```

    ##      speed           dist
    ##  Min.   : 4.0   Min.   :  2.00
    ##  1st Qu.:12.0   1st Qu.: 26.00
    ##  Median :15.0   Median : 36.00
    ##  Mean   :15.4   Mean   : 42.98
    ##  3rd Qu.:19.0   3rd Qu.: 56.00
    ##  Max.   :25.0   Max.   :120.00

Including Plots
---------------

You can also embed plots, for example:

![](github_markdown_files/figure-markdown_github/pressure-1.png)

Note that the `echo = FALSE` parameter was added to the code chunk to prevent printing of the R code that generated the plot.

Você pode gerar quantas figuras você quiser a partir dos códigos em R que os arquivos em markdown apresentarão as figuras de forma apropriada. É importante notar que, após a compilação, o RStudio cria uma pasta no local com todas as figuras referenciadas no markdown, tal que se você for utilizar esse recurso no Github Pages você deve fazer o upload da pasta também.
Comment: Muito obrigado @FlavioBarros, ajudou muito!