How do I use Lebesgue's theorem to find $\lim_{n \to \infty} \int_{\{|f(t)|\le1/n\}}f(t)^2 dt$?

Question: As a final step of a functional analysis exercise, we arrive to the following limit integral that is shown to go to zero using Lebesgue's dominated convergence theorem:
$$\lim_{n \to \infty} \int_{\{|f(t)|\le1/n\}}f(t)^2 dt=\lim_{n \to \infty} \int_0^1nf(t)^2 1_{\{|f(t)|\le1/n\}}dt$$
To use the theorem we need a bounding function independent from n to bound the integrand:
$$nf(t)^2 1_{\{|f(t)|\le1/n\}} \le n(1/n^2) \le 1$$
and the pointwise limit of the integrand:
$$nf(t)^2 1_{\{|f(t)|\le1/n\}} \to 0$$
I don't understand how to bound the function and how to find that limit.
It looks like I may get an indeterminate form in the limit:
Since when $n\to \infty$, $ |f|\le 0 $inside the indicator set:
$\lim_{n \to \infty} nf(t)^2 1_{\{|f(t)|\le1/n\}} = \infty 0^21$
Anyway this type of calculation looks pretty informal
Can someone please explained it  in a-step-by-step rigourous way?
Answer: You're close! The main thing to do is wait until the last second to actually evaluate your limit. Try to simplify the stuff you're limiting first, as otherwise you get meaningless quantities like "$\infty 0^2 1$" (which at least you recognize as meaningless).
First, the bound. I'm not sure where your misunderstanding is, since what you've written appears fine to me. To apply the dominated convergence theorem, we need to know that there is a dominating function $g$ so that

$|f_n| \leq g$ for every $n$
$\int |g| < \infty$

We're interested in the sequence $f_n = n f^2 1_{\{|f(t)| \leq \frac{1}{n}\}}$. We want to upper bound this by some function $g$. Well, let's follow our nose:
$1_{\{\text{blah}\}} \leq 1$ always, so it will never make $f_n$ bigger. But it's extremely useful because it lets us restrict attention to the set where $|f(t)| \leq \frac{1}{n}$ (do you see why?). So we get
$$
|f_n| = n |f|^2 1_{\{|f(t)| \leq \frac{1}{n}\}} \leq n \left (\frac{1}{n} \right )^2 1 = \frac{1}{n}
$$
So we always have $|f_n| \leq \frac{1}{n}$ on $[0,1]$. We want a bound $g$ that doesn't depend on $n$, so we take $g = \frac{1}{1} = 1$, since that bounds everything.
Now we have condition $1$ from before. $|f_n| \leq g$ for each $n$. We also have condition $2$, since we're working on $[0,1]$ and $\int_0^1 g \ dx = \int_0^1 1 \ dx = 1 < \infty$.
Then we can apply the dominated convergence theorem, and we see
$$\lim_{n \to \infty} \int_0^1 f_n \ dx = \int_0^1 \lim_{n \to \infty} f_n \ dx$$
Of course, what is $\lim_{n \to \infty} f_n$? Well we showed earlier that $|f_n| \leq \frac{1}{n}$ (while we were looking for an upper bound). Taking $n \to \infty$ shows
$$\lim_{n \to \infty} |f_n| \leq \lim_{n \to \infty} \frac{1}{n} = 0$$
So we must have $\lim_{n \to \infty} |f_n| = 0$ (by the squeeze theorem, if you like, since $0 \leq |f_n|$ for each $n$). Now by continuity of $|\cdot|$, this means $\left | \lim_{n \to \infty} f_n \right | = 0$
But the only way to have $|\text{blah}| = 0$ is if $\text{blah}$ itself is $0$. So we see that $\lim_{n \to \infty} f_n = 0$, which is exactly what you were trying to show.
Usually we don't go into anywhere near this much detail, but it's important to sometimes see all the moving parts laid out in front of you.

I hope this helps ^_^
Comment: Thanks the problem was that I was trying to simplify the expresion (not bound it)by observing what happens in the indicator set when n grows$(|f|\le 1/n \to 0$, so $|f|\to 0$ but at the same time $n\to \infty$) and that my professor explained this with  very confusing words. She said "Or the f(t)= 0 and so everything goes to 0, or $f(t)\neq 0$, but then eventually (for big n) it will be greater that 1/n an so the integrand will be zero anyway"
Answer: Consider the cases $|f(t)| \leq \frac  1n$  and$|f(t)| >\frac 1n$. In  the first case $nf^{2}(t)1_{|f(t)| \leq \frac 1 n}=nf^{2}(t) \leq n(\frac  1{n^{2}})=\frac  1n$.  What happens in the second case?
Comment: So in the first case the limit is not found dealing with the LHS dirrectly, but simply using the sandwich theorem?.
Comment: In the second case, the indicator is 0, but at the same time there's n outside, how come we take the limit after simplying to 0 and not at the same time?
Comment: @J.C.VegaO $n$ multiplied by $0$ is $0$ and limit of $0$ is $0$.
Answer: Let $h_n(t)=nf(t)^2 1_{\{|f|\leq \frac 1 n\}}(t)$.
For the Lebesgue Dominated Converge theorem to apply, you need

An integrable function $g\geq 0$ that dominates $h_n$ for all $n$. That is $|h_n|\leq g$ almost everywhere.
The limit pointwise to exist: $h_n\rightarrow h$ almost everywhere for some integrable function $h$.

The key observation is that

if $t$ is such $|f(t)|\leq \frac 1 n$, then $|h_n(t)|\leq n\frac 1 {n^2} = \frac 1 n$.
if if $t$ is such $|f(t)|> \frac 1 n$, then $1_{\{|f|\leq \frac 1 n\}}(t)=0$ and thus $h_n(t)=0$.

So the value of $h_n(t)$ is either bounded by $\frac 1 n$, or is equal to $0$.  Therefore you can pick $g(t)=1$ since it will work in both cases. Also, the same reasoning implies that pointwise, $h_n(t)$ tends to $0$.


How to show that any LP in equational form can be reduced to an optimization problem on the regular simplex?

Question: An LP is given in the form :
$max\langle c,x\rangle$ subject to $Ax=b,x\geq 0$.
I'm trying to show that any such problem can be reduced to a problem of the form
$max\langle c,x\rangle$ subject to $Ax=b,x\geq 0,\displaystyle \sum {x_j}=1$.
I think I'll somehow have to modify the problem by dividing by some quantity. However, I can't quite show this. Please help.
Answer: This is not true. For example, $\max_{x\in\mathbb{R}^{n}}\mathbf{1}^{T}x$
subject to $x\geq0$ is of this form. The problem is unbounded. However,
any problem with the convex combination constraint $\sum x_{j}=1$
is bounded.
Answer: Assume that $Ax=b$, $x\ge 0$ is a bounded set. Then $\exists M>0\colon \sum x_k\le M$. Introduce
$$
t=1-\sum\frac{x_k}{M}\ge 0,\qquad\text{and}\qquad z=\left[\matrix{\frac{x}{M}\\ t}\right].
$$
Then the problem becomes
$$
\max\left[\matrix{Mc\\ 0}\right]^Tz\qquad\text{subject to}\qquad [A\ 0]z=\frac{b}{M},\ z\ge 0,\ \sum z_j=1.
$$


How to run a batch process in regular interval

Question: I need  to Unpublish the nodes which are all not Updated for more than some specified time.
I'm having the query to fetch nodes and by using a batch process I will Unpublish those nodes one by one.
Now I want to schedule this operation to be run every day. How can I achieve that? using drush or something.
I have cron running at regular intervals. I need to run these scripts apart from the cron job i.e as a separate one.
Answer: You can use cron to do this, set a cron time in admin/config/system/cron for your site.
there is a hook_cron() is available in your drupal . using that hook you can configure your batch process to invoke.
Comment: To schedule your task to run at particular intervals cron is the correct one. you can use http://drupal.org/project/elysia_cron to get a fine grain control over each task. You can do your particular batch operation alone. why you are trying to run these scripts apart from the cron job?
Comment: Cron is already running at regular intervals. I want to run this one apart from cron. Will update the question also.
Comment: But un-publishing 10K nodes using node_save in cron will not be good :)
Comment: i mean use hook_cron to invoke your batch process
Comment: you can write your batch process function in a menu call back, and add the particular path in cron job with help of elysya cron
Comment: Found out the solution. Its possible with cron as you mentioned with some changes. Added my answer too :)
Answer: I can achieve it by using a Cron job and Batch/Queue as mentioned by Anoop Joseph with some changes
Method I - Using Cron and queue

Cron will run the query and push the list of nodes to the queue
queue will pick the items one by one and Unpublish them

Method - II Using Cron and batch

Cron will run the query and push the list of nodes to the Batch process
Batch process will be launched programmatically using background_process module

In both methods Cron can be configured in such way that It runs the query once for every day by storing the last run time in a variable
Answer: The batch api is primary design to work with forms and it depends what is the purpose of your use, but you can create a function that mimic form submission, and then you can use batch together with cron, assume you have function that will be triggered by a rule on cron run, so this function is function1:
<code><?php
function function1 () {
    $form_state = array();
    $form_state['values']['hidden_value'] = 1;
    $form_state['values']['op'] = 'Test';
    $form_state['values']['submit'] = 'Test';
    drupal_form_submit('function1_batch_form',
    $form_state);
}
function function1_batch_form($form, &$form_state) {
  $form['hidden_value'] = array(
    '#type' => 'hidden',
    '#value' => 1,
  );
  return $form;
}
function function1_batch_form_submit($form, &$form_state) {
  if ($form_state['values']['hidden_value'] == 1) {
    $batch = function1_batch_process($date);
    batch_set($batch);
  }
}
?>
</code>
Answer: I know this is an old thread, but if you really need things running at different times I might tackle it like this:
Start by setting up a rule with a custom rules action. You can use any logic you want here (because it's in a module using hook_action), I would check for a cache of nodes and process up-to X number of them if a cache is found or create a new cache and process up to X number of them if there is no cache.
The next part would be to set up the rule to happen on a specific page load and request that page with cron at whatever interval you want.


How to reproduce php Crypt() in java for custom sha256 rounds

Question: I have a php script that store crypt() results with a custom rounds off 10000 and some already existing salt.
The code look like that :
echo crypt('rasmuslerdorf', '$5$rounds=10000$usesomesillystringforsalt$');

And the output is

$5$rounds=10000$usesomesillystri$CaVZTpnmHfz9Fi6zjGJmSAAwwABsSqSJbtzdlfvVC10

Witch is not a hash in hexa nor in binary, it seem to be a Crypt3 output.
Question is "How to get this same string for the same input in Java ?"
For now all MessageDigest & SO answers tested don't work, as it print directly the hash in hexa (aka lot of pain to compare).
Answer: Ok, finally able to find a way to get the same output.
Using the Apache Commons Crypt I get the same output with the salt round and everything.
import org.apache.commons.codec.digest.Crypt;
return Crypt.crypt("rasmuslerdorf", "$5$rounds=10000$usesomesillystringforsalt$");

Will get me my :

$5$rounds=10000$usesomesillystri$CaVZTpnmHfz9Fi6zjGJmSAAwwABsSqSJbtzdlfvVC10


Feature selection with genetic algorithm in R

Question: I'm looking for a R-package that does feature selection using a genetic optimization algorithm. I couldn't find one on CRAN and I wonder whether there is a free one. I would be very appreciative for any help.
Comment: Have you seen this page : http://cran.r-project.org/web/views/MachineLearning.html
Answer: There are packages for assessing models (like caret), and for GA, like genalg and GA; you can use them to easily build a GA for FS, just put binary vector of whether particular feature is used in model as a chromosome and some assessment of accuracy as a fitness function, done.
Still, there is a fair cause why no-one had made a package doing this: it is a straight way into overfitting, thus a terrible idea.
Why? Exhaustive search for a set of features on which your model will score maximally well according to some assessment scheme is likely to find just that, and in p>>n noisy data set the chance that it will be accidently also a set of relevant attributes is close to zero.
Comment: Still, I doubt it will work, unless you have tons of cases; so please proceed with caution and validate well.


Huge difference in regression standard error after log transformation of dependent variable

Question: I try to learn which transformations are better for model and I am trying to compare models that I build. The first model is
Call:
lm(formula = log(medv) ~ log(crim) + zn + log(indus) + chas +
log(nox) + log(rm) + log(age) + log(dis) + log(rad) + log(tax) +
log(ptratio) + log(black) + log(lstat), data = Boston)

Residuals:
Min       1Q   Median       3Q      Max
-0.95001 -0.10118 -0.00198  0.10961  0.82680

Coefficients:
           Estimate Std. Error t value Pr(>|t|)
(Intercept)   5.3504375  0.4336744  12.337  < 2e-16 ***
log(crim)    -0.0314413  0.0111790  -2.813 0.005112 **
zn           -0.0011481  0.0005828  -1.970 0.049410 *
log(indus)    0.0037637  0.0224508   0.168 0.866935
chas          0.1011952  0.0362298   2.793 0.005423 **
log(nox)     -0.3659159  0.1074552  -3.405 0.000715 ***
log(rm)       0.3843709  0.1094673   3.511 0.000487 ***
log(age)      0.0410625  0.0223547   1.837 0.066833 .
log(dis)     -0.1438053  0.0356083  -4.039 6.24e-05 ***
log(rad)      0.0949062  0.0220954   4.295 2.10e-05 ***
log(tax)     -0.1759806  0.0477668  -3.684 0.000255 ***
log(ptratio) -0.5895440  0.0912645  -6.460 2.52e-10 ***
log(black)    0.0532854  0.0126549   4.211 3.03e-05 ***
log(lstat)   -0.4186032  0.0258019 -16.224  < 2e-16 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 0.1988 on 492 degrees of freedom
Multiple R-squared:  0.7697,    Adjusted R-squared:  0.7636
F-statistic: 126.5 on 13 and 492 DF,  p-value: < 2.2e-16

Second Model is
Call:
lm(formula = medv ~ log(crim) + zn + log(indus) + chas + log(nox) +
log(rm) + log(age) + log(dis) + log(rad) + log(tax) + log(ptratio) +
log(black) + log(lstat), data = Boston)

Residuals:
Min       1Q   Median       3Q      Max
-13.3551  -2.5733  -0.2924   2.0704  22.8158

Coefficients:
           Estimate Std. Error t value Pr(>|t|)
(Intercept)   7.449e+01  9.307e+00   8.004 8.74e-15 ***
log(crim)     7.002e-02  2.399e-01   0.292 0.770524
zn           -1.257e-04  1.251e-02  -0.010 0.991983
log(indus)   -8.557e-01  4.818e-01  -1.776 0.076366 .
chas          2.480e+00  7.775e-01   3.190 0.001514 **
log(nox)     -1.160e+01  2.306e+00  -5.030 6.90e-07 ***
log(rm)       1.374e+01  2.349e+00   5.850 8.98e-09 ***
log(age)      8.034e-01  4.798e-01   1.675 0.094658 .
log(dis)     -6.327e+00  7.642e-01  -8.280 1.17e-15 ***
log(rad)      1.972e+00  4.742e-01   4.158 3.78e-05 ***
log(tax)     -4.277e+00  1.025e+00  -4.172 3.57e-05 ***
log(ptratio) -1.357e+01  1.959e+00  -6.927 1.35e-11 ***
log(black)    1.005e+00  2.716e-01   3.701 0.000239 ***
log(lstat)   -9.654e+00  5.537e-01 -17.433  < 2e-16 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 4.266 on 492 degrees of freedom
Multiple R-squared:  0.7904,    Adjusted R-squared:  0.7849
F-statistic: 142.7 on 13 and 492 DF,  p-value: < 2.2e-16

The difference between models is only log transformation of dependent variable. When I compare I saw that residual standard error is very high in the second model but R-squared is also high in the second model. I did not understand which model is better. The high reduction in the standard error is due to log transformation of dependent variable or not?
Comment: On the `medv` scale the first model is multiplicative and the second one is additive. These models are not even similar. Since the residual standard errors are not on the same scale, you can't compare them. Also, due to the large number of predictors you are probably overfitting and should test for multicollinearity.
Comment: I'm curious where you got your data from and if it's freely available.
Comment: Yes, it is free. It is R data in MASS package. http://www.clemson.edu/economics/faculty/wilson/R-tutorial/analyzing_data.html @TrynnaDoStat
Answer: @Tim is right that the log is changing the residual standard error and that comparing this on the two errors is meaningless.  Why is this so? Consider a much simpler case: Suppose the DV is income (in dollars) and one scale predicts Joe's income to be \$100,000 when his real income is \$90,000.  Error is $10,000. Take log (base 10) and get a predicted value (even if everything else stays the same) of 5 and an actual value of 4.95 and an error of 0.05  (this isn't exactly what's going on, but I think it gives you a feel for the reason things change).
Whether you should transform your DV should depend on substantive reasons more than statistical ones. You didn't say what MEDV and the other variables are, but it looks like MEDV is median value and this is predicted cost of a house or something like that.
When the DV is a dollar amount, taking logs often makes sense because we often think of these amounts on a multiplicative scale.  That is, the difference between a \$100,000 house and a \$200,000 house is huge.  The difference between a \$1,000,000 house and a \$1,100,000 house is much smaller.
Comment: Yes, I think so.  Although you might want to take log in actual dollars and base 10.  One problem with log transformation is that the interpretation isn't quite as obvious as with raw data, but, in my experience, log10(raw value) is easier than other methods. The conclusions shouldn't change.
Comment: Thank You. Yes, medv is  Median value of owner-occupied homes in $1000's. I think taking log of dependent variable is still meaningful based on what you said right?
Answer: Yes, the log transformation of the dependent variable is what is reducing your standard error, so comparison of the standard errors of the residuals is meaningless.
Based on r-square alone, the second model is better.  But, to make a sensible choice between the models you need to be working out which of the models has a more sensible interpretation in your area of application (e.g., the first model's coefficients are elasticities, which makes a lot of sense in economics and marketing, but may not in your field; and, which model's coefficients have the more sensible signs and magnitudes?), and comparing the various standard diagnostics (e.g., outliers, normality of residuals).
Comment: I strongly advise against automatic anything.
Comment: A Box Cox transformation is the most straightforward approach, but I tend to agree with @Peter Flom.
Comment: @tyer I think you should educate yourself about machine learning approaches. Especially you should focus on the topic of model validation.
Comment: "Based on r-square alone, the second model is better": but one is on a log scale and the other is not! *So we should not compare the $R^2$ values. They are incomparable.* See e.g. Gujarati's "Basic econometrics", which deals with this point in a section on "comparing two $R^2$ values" immediately after introducing $R^2$ for multiple regression. (He suggests if you have one model using $\log Y_i$ and another for $Y_i$, then obtain fitted $\hat {\log Y_i}$ from the 1st model, antilog them, then find the $R^2$ between the result and $Y_i$. This $R^2$ can then be compared to $R^2$ of 2nd model.)
Comment: I studied machine learning approaches I know after building model I should do cross-validation right? @Roland
Comment: Hi, Thank you for your answer. We want to make automatic model selection for linear regression. Because there will be program analyzing data and build model automatically. Do you suggest any way of  selection transformation for regression model automatically for computer. Since we will build many models for neighbourhoods in our country. @Tim
Comment: Can I ask why? I think that maybe computer can try quadratic polynomial regression, linear regression and linear regression with log transformation of independent variables, and then choose the model which has lowest standard error. Is it make sense? Also I will try to do automatically regression diagnostics. @Peter Flom
Comment: Also maybe I will add some interaction terms to the models
Comment: @tyer What is your goal here? Inference, prediction or something else?
Comment: I try to predict home prices with building models based on neighbourhood.  every neighbourhood can need different model so, I want to make model selection automatically since there are huge amount of neighbourhood @Roland
Answer: I will try to help you because i do not speak English very well
a short answer: Your log dependent variable cannot be compare directly. What you have to do is create a new variable called "mi". mi=exp(log (yi)) where yi are the fitted values by regression over your X(s) variables (log model).
Then, an objective way to compare both models is using a new R2' estimator of the log model comparable with the normal linear:
R2' = cor(yi,mi)^2 where, yi is the vector of the original dependent variable, and cor is the correlation function. if R2'>R2(linear model), log model is better.
For forecasting purposes, yo cannot predict a value using the exp function over a predicted log value, you will be systematically sub-estimating the expected value of y.
(source: Wooldridge, Introductory econometrics 2012)


Im trying to run an app but im getting an error which says "could not find translocated node" in Xcode

Question: [default] LSPrefs: could not find untranslocated node for <FSNode 0x600003002ae0> { isDir = ?, path = '/private/var/folders/k7/zdtfstr13gxcrwg98wc0k1dm0000gn/X/14ADFEAC-68C8-59CF-AC5B-21F464164A42/d/Wrapper/Dicee-iOS13.app' }, proceeding on the assumption it is not translocated: Error Domain=NSPOSIXErrorDomain Code=1 "Operation not permitted"
Answer: I am getting similar messages in the console when running an iOS app from XCode on the target myMac (Designed for iPad).
However, as far as I am concerned, this is just a warning that does not prevent the app from running.
More information on translocation here: https://eclecticlight.co/2021/04/19/ios-apps-are-translocated-when-run-in-macos/
Comment: I noticed this, after recently switching to Xcode on an M1, and have not found any functional problems. Hopefully it is just a warning. I created some new projects in Xcode 13, and they don't have this error, but I haven't isolated why my old (circa iOS10) projects show this. If I find something conclusive I'll add a new answer.
Answer: I also had a similar error on the target My Mac (Designed for iPad).
M1 Mac, Xcode 14.0.1, MacOS Monterrey 12.6.
The app builds fine on all other targets.  It started crashing on the Mac target when I added MKLookAroundViewController to the storyboard, as shown at 36:00 in https://developer.apple.com/videos/play/wwdc2022/10035/
To solve this, I deleted the Look Around view controller from the storyboard and added it programmatically instead.


Sorting logic with anonymous function does not work

Question: This question is related to my previous question about how to change the sort order in a view. Since this is a new question I thought I better post a new one.
My new problem is that I use hook_views_pre_render() as suggested, but I am having trouble getting the views sort order right. I use an anonymous function like this to change the views order:
/**
* Implementation of hook_views_pre_render. Sorts the nodes under "Givare"
 */
function mysite_views_pre_render(&$view) {
    if ($view->name === 'related_items' && $view->current_display === 'probes') {
        $node = node_load(arg(1));
        $sortorder = array();
        $groups = $node->field_lagg_till_givargrupp['und'];
        foreach($groups as $group){
            $group_nid = $group['nid'];
            $group_node = node_load($group_nid);
            $probe_nids = $group_node->field_koppla_givare['und'];
            foreach($probe_nids as $probe_nid){
                $sortorder[] = $probe_nid['nid'];
            }
        }

        usort($view->result, function ($a, $b) use ($sortorder) {
            $cmpa = array_search($a->nid, $sortorder);
            $cmpb = array_search($b->nid, $sortorder);
            dsm($a->nid." ".$b->nid." ".$cmpa." ".$cmpb);
            if($cmpa === $cmpb) {
                return 0;
            }
            return ($cmpa < $cmpb) ? -1 : 1;
        });
    }
}

The variable $sortorder contains an array with nids in the wanted order. But the resulting $views_result does not follow that order (but it is altered, just in the wrong way). Can anyone see what I am doing wrong?
EDITED: added context – the view in question is a block display with a grid setting (there are several of these block displays in the same view and these block displays are used by Quick Tabs to render each block under a tab as related items.) In this particular block display I have tested to omit exposed filters, to deselect grouping by title etcetera to see if that would impact the sorting, but with no luck. I was surprised that this block needed sorting at all because I give the order explicitely with a contextual filter. See this question for the contextual filter:
Sort criteria is ignored in Views
Also, as I added the row dsm($a->nid." ".$b->nid." ".$cmpa." ".$cmpb); I can see that there are more than one hundred value pairs, but there are only 22 items to be rendered(!). The first few rows of that dsm() looks like this, where for example the nid 20726 is repeated several times:

20726 20693 7 12
21863 20726 5 7
20726 20695 7 4
20726 20697 7 0
20726 20699 7 15
20861 20726 21 7
20860 20726 20 7
20859 20726 19 7
20858 20726 23 7
20857 20726 22 7
20768 20726 2 7
Comment: I added your code to a hook_views_pre_render() hook and it works correct. I suggest you look for the error elsewhere. This code is likely in a theme's template.php file. Is it added to the right theme's file (admin or frontend)? Are you looking at the result of the sort by inspecting the value of the $view->result within the hook or are you looking at the rendered output? PS i was tempted to vote to close this as it is PHP code, but as the code works the error is in some other place making it a Drupal question again and I suggest you give more context
Comment: Yes, it's in the template.php file and there is only one theme, so no mistake there. Also I check both the the rendered output and within the hook itself. I can't see what is wrong, but thanks for confirming that the snippet works.
Comment: usort uses [Quickort](https://en.wikipedia.org/wiki/Quicksort) so all as expected. Check your hook signature. It should be hook_views_pre_render(&$view)
Comment: Yes, the signature is correct. And the function does alter the sorting in the correct view display, but not as expected. Above I have added the whole function instead of just the sorting snippet.
Comment: My only conclusion is that $sortorder is suspect and either contains duplicates or is not inclusive of the values of $view->result nids.
Comment: Move to [chat](http://chat.stackexchange.com/rooms/327/drupal-answers)
Answer: PROBLEM SOLVED. As J. Reynolds pointed out there were missing nid values in $view->result before the sorting was made.
There was also an issue with the nids because I had forgotten to set the field mapping (migrate d2d) to "do not create automatic URLs" for pathauto during a an earlier migration from D6 to D7 of the group nodes that contained the items in question. So the item nids were fetched from the wrong group entity. My mistake :-(.
But everything is sorted out now. Thanks for your input!


colocar uma imagem abaixo de colunas no Bootstrap

Question: A estrutura esta correta, o problema, quando eu tento colocar uma imagem, a imagem vai lá para baixo junto com o footer, esse print que postei, é como é para ficar o resultado final. O código que estou postando está igual o print, exceto a imagem.
Código PasteBin
SRC para adicionar a imagem:
src="http://placehold.it/450x150"

Tem alguma classe do bootstrap para adicionar a imagem em baixo da coluna 1 e coluna 2 ou tenho que fazer pelo css??
Answer: Segue um exemplo do que você pode fazer: JSFiddle.
Você tem que subdividir as colunas dessa forma:
|              col-md-8             |       col-md-4       |
| coluna 1 (md-6) | coluna 2 (md-6) | coluna 3 (col-md-12) |
|              imagem (md-12)       |


How do I stop erroneous processes from php code that no longer exists?

Question: I am running xubuntu 12.04 with apache2 as a local server. I recently wrote a while loop statement in 'testing.php' that was supposed to retrieve a remote xml file from a url and save that to a file located on the local server. I ran this code not realizing that the loop was infinte. The browser starts to load, and a few seconds after my computer starts to obviously slow down to the point of ceasing to function swiftly. I restart my computer. I check the error.log file, loading of this file takes ~30 seconds, unusual compared to other accesses. Once the 'error.log' file loads it starts to display hundreds of lines of errors relating to this while loop. So I immediately delete that line of code and fix it completely. Now the program is fixed and works properly, yet every time I open 'error.log', it takes a while to open and the same errors are being logged. Even when I have not ran 'testing.php' prior to opening the 'error.log'
Here are some of the errors being logged, keep in mind I know why I got the errors, I just do not know why the errors are still being logged:
[Sun May 27 22:07:49 2012] [error] [client 127.0.0.1] PHP Notice:  Undefined variable: count in /home/sebastian/jasone_co/Testing/testing.php on line 96
[Sun May 27 22:07:49 2012] [error] [client 127.0.0.1] PHP Warning:  file_get_contents(jasoneatherly.tumblr.com/api/read/?type=photo&&start=0&&num=25): failed to open stream: No such file or directory in /home/sebastian/jasone_co/Testing/testing.php on line 85
[Sun May 27 22:07:49 2012] [error] [client 127.0.0.1] PHP Warning:  fopen(/home/sebastian/jasone_co//Testing/Test-XML/TumblrXML_0-25.xml): failed to open stream: No such file or directory in /home/sebastian/jasone_co/Testing/testing.php on line 86
[Sun May 27 22:07:49 2012] [error] [client 127.0.0.1] PHP Warning:  fwrite() expects parameter 1 to be resource, boolean given in /home/sebastian/jasone_co/Testing/testing.php on line 87
[Sun May 27 22:07:49 2012] [error] [client 127.0.0.1] PHP Warning:  fclose() expects parameter 1 to be resource, boolean given in /home/sebastian/jasone_co/Testing/testing.php on line 88
[Sun May 27 22:07:49 2012] [error] [client 127.0.0.1] PHP Warning:  simplexml_load_file(): I/O warning : failed to load external entity "/home/sebastian/jasone_co//Testing/Test-XML/TumblrXML_0-25.xml" in /home/sebastian/jasone_co/Testing/testing.php on line 90
[Sun May 27 22:07:49 2012] [error] [client 127.0.0.1] PHP Notice:  Trying to get property of non-object in /home/sebastian/jasone_co/Testing/testing.php on line 91
[Sun May 27 22:07:49 2012] [error] [client 127.0.0.1] PHP Notice:  Trying to get property of non-object in /home/sebastian/jasone_co/Testing/testing.php on line 91
[Sun May 27 22:07:49 2012] [error] [client 127.0.0.1] PHP Notice:  Undefined variable: count in /home/sebastian/jasone_co/Testing/testing.php on line 96
[Sun May 27 22:07:49 2012] [error] [client 127.0.0.1] PHP Warning:  file_get_contents(jasoneatherly.tumblr.com/api/read/?type=photo&&start=0&&num=25): failed to open stream: No such file or directory in /home/sebastian/jasone_co/Testing/testing.php on line 85
[Sun May 27 22:07:49 2012] [error] [client 127.0.0.1] PHP Warning:  fopen(/home/sebastian/jasone_co//Testing/Test-XML/TumblrXML_0-25.xml): failed to open stream: No such file or directory in /home/sebastian/jasone_co/Testing/testing.php on line 86
[Sun May 27 22:07:49 2012] [error] [client 127.0.0.1] PHP Warning:  fwrite() expects parameter 1 to be resource, boolean given in /home/sebastian/jasone_co/Testing/testing.php on line 87
[Sun May 27 22:07:49 2012] [error] [client 127.0.0.1] PHP Warning:  fclose() expects parameter 1 to be resource, boolean given in /home/sebastian/jasone_co/Testing/testing.php on line 88
[Sun May 27 22:07:49 2012] [error] [client 127.0.0.1] PHP Warning:  simplexml_load_file(): I/O warning : failed to load external entity "/home/sebastian/jasone_co//Testing/Test-XML/TumblrXML_0-25.xml" in /home/sebastian/jasone_co/Testing/testing.php on line 90
[Sun May 27 22:07:49 2012] [error] [client 127.0.0.1] PHP Notice:  Trying to get property of non-object in /home/sebastian/jasone_co/Testing/testing.php on line 91
[Sun May 27 22:07:49 2012] [error] [client 127.0.0.1] PHP Notice:  Trying to get property of non-object in /home/sebastian/jasone_co/Testing/testing.php on line 91
[Sun May 27 22:07:49 2012] [error] [client 127.0.0.1] PHP Notice:  Undefined variable: count in /home/sebastian/jasone_co/Testing/testing.php on line 96
[Sun May 27 22:07:49 2012] [error] [client 127.0.0.1] PHP Warning:  file_get_contents(jasoneatherly.tumblr.com/api/read/?type=photo&&start=0&&num=25): failed to open stream: No such file or directory in /home/sebastian/jasone_co/Testing/testing.php on line 85
[Sun May 27 22:07:49 2012] [error] [client 127.0.0.1] PHP Warning:  fopen(/home/sebastian/jasone_co//Testing/Test-XML/TumblrXML_0-25.xml): failed to open stream: No such file or directory in /home/sebastian/jasone_co/Testing/testing.php on line 86
[Sun May 27 22:07:49 2012] [error] [client 127.0.0.1] PHP Warning:  fwrite() expects parameter 1 to be resource, boolean given in /home/sebastian/jasone_co/Testing/testing.php on line 87
[Sun May 27 22:07:49 2012] [error] [client 127.0.0.1] PHP Warning:  fclose() expects parameter 1 to be resource, boolean given in /home/sebastian/jasone_co/Testing/testing.php on line 88

I have also tried to locate any zombie or defunct processes to no avail. Here is what I get when I run ps -C apache2:
sebastian@Lucight:~$ ps -C apache2
  PID TTY          TIME CMD
 2875 ?        00:00:00 apache2
 2880 ?        00:00:00 apache2
 2881 ?        00:00:00 apache2
 2882 ?        00:00:00 apache2
 2883 ?        00:00:00 apache2
 2884 ?        00:00:00 apache2
 2901 ?        00:00:00 apache2
 2903 ?        00:00:00 apache2
 2904 ?        00:00:00 apache2
 2905 ?        00:00:00 apache2
 2906 ?        00:00:00 apache2

As I stated before, restarting my computer does nothing to fix this.
Comment: i am an uber noob my apologies...
Comment: Those log entries are from Sunday, are you sure it's still logging the error now  How about `tail -f` on the log file, is it still adding new lines?
Comment: Do the errors just populate when I open the error.log? it just seems like the errors are happening when I open the file, maybe I just need to clear the log file.
Comment: and it does not add new errors, I think due to the mass amounts of errors from that single bad call causes this poor load time. I will try to clear the error.log file.
Comment: The only problem you have is that you have poorly written code. It really is that simple. Fix your code and the errors will no longer be logged. Why you chose Sf to post this is a mystery to me. Please read our FAQ.
Answer: First try to see what is the size of that file. Maybe its so big and opening it need time.
Execute tail -f error.log to see if script still generates errors.
Executing tail error.log should also tell from what date are the last entries.
If tail shows that no errors are loging you can safely delete that file if its to big. (some errors logs can have sizes in GB).
You can clean that error.log using command cat /dev/null > error.log
But if tail shows that error are still loging ...hmm then I would say that there somewhere are still errors that need to be fixed.
My answare is much more guessing because the information you have given are not clear as to the cause
Comment: I will try clearing the log.
Comment: The size of the error.log file is ~596mb. I tried the cat /dev/nll > error.log command it didn't seem to clear it.
Comment: I ended up editing the the error.log file using gksudo gedit /var/log/apache2/error.log, deleted all the contents and all seems well. thanks for everyone's help. I am a noob.


What's the meaning of the numbers printed below the message of console.log?

Question: I'm doing some testing in chrome debugger tool, I find some strange numbers are printed below the texts output by console.log:

I didn't log in the console, why are they there? what are these numbers? what does it mean?
Answer: The Chrome console logs the value of the last expression executed. In the first example above, the last line, i++; logs 9. In the second example, i+=1; logs 10.


ggplot2: How to format the sec.axis properly in R

Question: I am trying to plot 3 lines using geom_line() in my ggplot graph. One of the variables has a different scale so I am trying to use the sec.axis in order to show it as well.
library(ggplot2)
library(reshape2)

tab <- data.frame(year = seq(1979,2010), freq = runif(32, 212,283), max =
runif(32, 962.1, 993.4), med = runif(32, 972.1, 989.3), min = runif(32,
955.7, 978.3))

summary(tab) # the column freq (frequency) has a different scale comparing with the other ones

Some code I've tried.
tab <- melt(tab, id = c("year")) # melt the data

ggplot(tab, aes(x = year, y = value)) +
theme_bw() +
scale_colour_manual(values =c('red','blue', 'green')) +
geom_line() +
scale_y_continuous(limits = c(900,1000), sec.axis = sec_axis(~. *0.3)) # I am using limits in order to control the extent for the other variabiles besides 'freq'.

This shows the second y_axis but the variable 'freq' is missing. So far, I could not find an example showing how to plot multiple lines using a sec.scale as well for one variable. Also, I am not sure if I need to transform the 'freq' variable first or only to control the sec.axis for it so if anyone can explain me, I will be grateful.
Thanks!
Answer: You can also use geom_pointrange, without melting the data. I changed the data little bit to make the graph nicer, but you can adapt it later for your data.
tab <- data.frame(year = seq(1979,2010), freq = runif(32, 280,300), max =
                    runif(32, 975.1, 993.4), med = runif(32, 972.1, 975.3),
                  min = runif(32,955.7, 971.3))

ggplot(data = tab, mapping = aes(x = year)) +
  geom_pointrange(mapping = aes(y=med,ymin = min, ymax = max),size=0.5,color='blue',fatten = 1)+theme_bw()+
  geom_point(aes(x=year,y=freq/0.3), inherit.aes = FALSE,color='red')+
  scale_y_continuous( name = 'range and median', sec.axis = sec_axis(~. *0.3,name = "frequency"))+
  theme(axis.text.y  = element_text(color = 'blue'),
    axis.title.y = element_text(color='blue'),
    axis.text.y.right =  element_text(color = 'red'),
    axis.title.y.right = element_text(color='red'))

Answer: You are looking for something like this?
tab %>%
  mutate(value = if_else(variable == 'freq', value + 700, value)) %>%
  ggplot(aes(
    x = year,
    y = value,
    color = variable
  )) +
  theme_bw() +
  scale_colour_manual(values = c('red', 'blue', 'green', 'black')) +
  geom_line() +
  scale_y_continuous(sec.axis = sec_axis(
    trans = ~ . - 700,
  ))


Feature importance for ANN

Question: I have a multi-class classifier ANN with ~11000 input features, two hidden layers and a softmax output.
I would like to know which features are most important to drive the network towards predicting one class vs another.
I have seen saliency maps used to define per-class pixel importance in convolutional networks that classify images; however, I seem to struggle to find something similar for a 1D/non-CNN case.
Can someone suggest methods to solve this problem (references and examples would be greatly appreciated!)?
Answer: Something simple like Shapley values (or alternatives) should do the trick if you are looking for instance explanation.
https://www.yourdatateacher.com/2021/05/17/how-to-explain-neural-networks-using-shap/
The example uses a sklearn MLP but similar implementations should also exist for PyTorch and Tensorflow
Comment: Thanks for this, I'll have a look; from a first look, however, I'm left wondering about the feasibility of this approach when I have ~11k input features.
Comment: It is probably quite computationally expensiv, but it works for CNNs as well and they also have equal or more features
https://medium.com/mlearning-ai/demystifying-neural-nets-with-shapley-values-cca29c836089

Feature importance for ANN


Closed Sets VS. Complete Sets

Question: Let $(X,d)$ be a metric space. If   $K⊆X$, and $K$
 is a closed set. Does that mean any Cauchy sequence in $K$ converges in $K$?
If no, could someone give an example?
If yes, then what is the difference between complete sets and closed sets?
Comment: No. Take $(\mathbb Q,d)$. Then $\mathbb Q$ is closed but not every Cauchy sequence converges. E.g take a sequence $(x_n)$ in $\mathbb Q$ converging in $\mathbb R$ to $\pi\notin\mathbb Q$.
Comment: Great, What about if the inclusion is strictly?
Comment: My example shows that the case will not be changed if the inclusion is strict. $(-\sqrt11,\sqrt11)$ is closed in $\mathbb Q$ but you can let $x_n\in(-\sqrt11,\sqrt11)$
Comment: Aha, Thank you so much.
Comment: If $(X,d)$ is complete metric space, and $K\subseteq X$ is closed in $X$, then it is complete. [Proof](http://www.planetmath.org/AClosedSubsetOfACompleteMetricSpaceIsComplete).
Comment: Also, complete subspace of _any_ metric space is closed. When you combine with my previous comment, if $(X,d)$ is complete, closed subsets are the same as complete subspaces.
Comment: @Ennar  thank you so much Ennar.
Answer: The rationals are closed in the rationals, but obviously not complete. For strict inclusion, take $\mathbb{Q} \cap [0,1]$ in $\mathbb{Q}$. Also not complete, but closed.
Incidentally, complete implies closed. Just look at limit points and sequences.
Comment: Great, What about if the inclusion is strictly?

Closed Sets VS. Complete Sets


apache , php , sendmail not working

Question: I am using apache, php and sendmail. I can send mail from command line with sendmail.
However, in php file, mail function is not working.
Then, I run that php email test file from command line. It works.

#>php mail_test.php

I thought it is apache issue and I changed httpd_can_sendmail on. But it is still not working. I checked sendmail permission and it is 666.
I checked httpd error log and I found this:

sh: /usr/sbin/sendmail: Permission denied.

I don't know where to change permission anymore.
Comment: The permission cannot be 666, for then the sendmail binary is not executable.
Comment: yes 777 now but not working yet Thanks . Error must be somewhere else
Comment: What do logs say now?
Comment: Still the error log
[Fri Jan 27 06:25:23 2012] [notice] SELinux policy enabled; httpd running as context unconfined_u:system_r:httpd_t:s0
[Fri Jan 27 06:25:23 2012] [notice] suEXEC mechanism enabled (wrapper: /usr/sbin/suexec)
[Fri Jan 27 06:25:28 2012] [notice] Digest: generating secret for digest authentication .
[Fri Jan 27 06:25:28 2012] [notice] Digest: done
[Fri Jan 27 06:25:29 2012] [notice] Apache/2.2.15 (Unix) DAV/2 PHP/5.3.3 mod_ssl/2.2.15 OpenSSL/1.0.0-fips SVN/1.6.11 mod_perl/2.0.4 Perl/v5.10.1 configured -- resuming normal operations
sh: /usr/sbin/sendmail: Permission denied
Comment: What is the user:group of php/apache ?
Comment: Btw what are you using as a mail agent? When I used mail() in PHP to pass mail to Postfix, I found out that it ignored SMTP settings completely and passed the mail of to the `pickup` daemon. So if you have not handled pickup in your `master.cf` file, well ... you won't be able to send mail.
Comment: Try chmod -v 2755 /usr/sbin/sendmail. Also do you have any symlinks to this?
Answer: This thread (look at the bottom) suggests that it may be a problem with SELinux permissions. Do you have SELinux enabled?
Comment: Thanks ,It was. Now I changed it to SELinux disabled . But Still no luck.

apache , php , sendmail not working


middleware not working when passing parameters

Question: Middleware File -
const access_validation_middleware  = async function(action:any, resource:any){
   console.log("came inside")
   return async (req:any, res:any, next:any) => {
      console.log("came inside async")
      try {
         //   const permission = roles.can(req.user.role)[action](resource);
           // Do something
           next();
       }
       catch (error) {
           next(error)
       }
   }
}
export default access_validation_middleware;

Controller -
const usersRouter = Router();
usersRouter.get('/',access_validation_middleware, UserController.list)
export default usersRouter

When I am using this middleware, API keeps loading. it doesn't even reaches till the anonymous function in access_validation_middleware.
When I remove the middleware, it is giveing response well.
Comment: Remove `async` for `access_validation_middleware`, then, use it like `usersRouter.get('/',access_validation_middleware('create', 'tag'), UserController.list)`.
Answer: I think you should add another middleware that puts action and resource on req like this
export const putPayload = async(req,res,next)=>{ if(validateRequest(req)){ req.action = whateverAction; req.resource = whateverResource; next();} else {res.status(400).json({message:"bad request!"});}}

and before this define a validation function like this anywhere:
export const validateRequest(req)=>{if(DO_YOUR_VALIDATION) return true; return false;}

then change your middleware access_validation_middleware to :
export const access_validation_middleware = async (req, res, next) => {
  console.log("came inside async")
  try {
     //   const permission = roles.can(req.user.role)[req.action](req.resource);
       // Do something
       next();
   }
   catch (error) {
       next(error)
   }
}

then in your router do like this:
const router = express.Router();
router.route("/").get(putPayload , access_validation_middleware , UserController.list)

I hope it helps


Probability: Understanding Random Variables

Question: I am using Ross' A First Course In Probability (4th). On page 113, Example 1d states the following:

Independent tirals consisting of the flipping of a coin having
  probability $p$ of coming up heads are continually performed until
  either a head occurs or a total of $n$ flips is made. If we let $X$
  denote the number of times the coin is flipped, then $X$ is a random
  variable taking on one of the values 1, 2, 3, ..., n with respective
  probabilities
$P\{X=1\} = P\{H\} = p$
$P\{X=2\} = P\{(T,H)\} = (1-p)p$
$P\{X=3\}=P\{(T,T,H)\} = (1-p)^2p$
.
.
.
$P\{X=n-1\}=P\{(T,T,...,T,H)\}=(1-p)^{n-2}p$
$P\{X=n\}=\{(T,T,...,T,T),(T,T,...,T,H)\}=(1-p)^{n-1}$

There are a couple of things that are confusing to me here. To my understanding, they are defining $X$ to be "the number of times the coin is flipped until a head occurs or a total of $n$ flips is made." Then, We would have $P\{X\}$ to be
$P\{X = n\} = \sum\limits_{i=1}^n (1-p)^{i-1}p^i + (1-p)^i$    , isn't it?
Also, wouldn't $P\{X=n\} =(1-p)^{n-1}p$? How does it turn out to be $(1-p)^{n-1}$?
Any help would be appreciated.
Comment: What is $P\{X\}$? As for your second question, that you flip a head or a tale on the $n$-th trial is irrelevant. Hence you could think of $P\{X=n\}$ as being the probability that you flip $n-1$ tales, simply. The formula given is correct. Another way to get $(1-p)^{n-1}$ is to calculate $(1-p)^n+(1-p)^{n-1}p$.
Comment: My mistake, I meant. $P\{X=n\}$. Post updated.
Comment: What is the reasoning behind the first formula you propose? If $p=1$, for example, then $P\{X=1\}=1$ and $P\{X=i\}=0$ for $i=2,3,\ldots,n$. But your formula would give $P\{X=n\}=1$ which is incorrect.
Comment: I'm getting confused, but will give it more thought. My reasoning was that because $X$ represents "the number of times the coin is flipped until either a head occurs or a total of $n$ flips is made", then the combined probability would be $P\{X=n\} = Sum of P\{ith\,toss = H\} (with\, i = 1,..,n) + P\{n\,flips \,are \,made\}$ (which I believe is $(1-p)^n$).
Comment: Hum, $P\{X=n\}$ is only the last term of your sum, that is, $P\{n\text{ flips are made}\}$. I already gave two ways to get $(1-p)^{n-1}$. The second way I gave is just $P\{n\text{ tales are flipped}\}+P\{n-1\text{ tales are flipped and }1\text{ head is flipped}\}$. A third way would be to calculate $1-\sum_{i=1}^{n-1}P\{X=i\}$. In all cases the result is $(1-p)^{n-1}$.
Comment: Had to reread the book and reread your posts a couple of times and now I get it a little bit better. Now, they start with $P\{X=1\}=P\{H\}=p$, but if we plug in the final formula "$P\{X=n\}=(1-p)^{n-1}$", we would get 1, which makes me wonder whether they started wrong.
Comment: If we plug what? How would we get 1?
Comment: In the very first line of formulas, they have " P{X=1} = P{H} = p ". If we plugin in the general formula " P{X=n}=$(1-p)^{n-1}$ " for n = 1, we would get 1, which is not equal to $p$, which makes me wonder whether they are wrong on the first line.
Comment: $n$ is not an index! $n\geq1$ is a *given* fixed number. $P\{X=n\}$ is not a general formula. A general formula is given in the answer below by **Graham Kemp**. Notice that he uses the index $k$.
Comment: It started making sense and now I am getting confused again. If we were given the fixed number n to be 4, then $X$ would be the random variable that denotes we either flipped 4 times (with no success) or a head occured at our 4th toss. Then, it would make sense for me to think of it as P{X=4} = $q^4 + q^3p$ with q = 1-p. How is it not a general formula o.O? By the way, thanks for the replies so far!
Comment: Suppose $n=4$. Do the experience a number of times. Maybe the first time you will flip a head on the first trial. Then $X$ takes the value $1$ for this realization of the experience. Maybe the second time, you will flip a head for the first time only on the third trial. Then $X$ takes the value $3$ for this realization of the experience. Maybe the third time you will not have flipped a head in the first three trials. Then the experience is over and $X=4$. The probability $P\{X=k\}$ is $(1-p)^{k-1}\cdot p$ where $k\in\{1,2,3,4\}$ and $0\leq p\leq1$ is supposed to be known.
Comment: Thanks so much! Your last post helped me figured it out. I guess I was confusing the concepts used or maybe RVs are supposed to be this confusing for people who don't know about them, hah. Anyway, thanks a lot!!
Comment: You're very welcome.
Answer: We are running a series of Bernoulli trials, with a probability of success being $p$, and a probability of failure being $1-p$, until we encounter either a success or reach the $n^\text{th}$ trial.   $X$ is the count of trials we perform during a run.
For $0\leq k < n$ we have $\mathsf P\{X=k\} = (1-p)^{k-1}\color{silver}{\cdot}p$, which is the probability of $k-1$ consecutive failures followed by $1$ success.
However, for $k=n$ we want the probability of $n-1$ consecutive failures preceding the $n^\text{th}$ trial.   The last trial may either be a failure or a success because we'll terminate the run either way.   Thus: $\mathsf P\{X=n\}= (1-p)^{n-1}\color{silver}{\cdot 1}$


Como ativar o Migrations usando o Entity Framework Core = Windows Forms C#

Question: Estou testando o EF Core em um projeto Windows forms seguindo o padrão DDD. Na camada de repositório eu criei meu contexto e em meu domínio já tenho as classes Models definidas. Como faço para ativar o Migrations no EF Core e de maneira que eu não precise ter que criar cada migração manualmente e ficar dando os updates? Queria que o  Migrations ficasse habilitado e eu só desse o update-database...

public class PersistContext : DbContext
    {
        public PersistContext()
        {
        }

        public PersistContext(DbContextOptions<PersistContext> Options)
            :base(Options)
        {
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.ForSqlServerUseIdentityColumns();
            modelBuilder.HasDefaultSchema("SistemaComercial");

            PessoaTipoMap(modelBuilder);
        }

        public DbSet<PessoaTipo> PessoaTipo { get; set; }

        private void PessoaTipoMap(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<PessoaTipo>(pt =>
            {
                pt.ToTable("tblPessoaTipo");

                pt.HasKey(ptk=> ptk.PessoaTipoId);
                pt.Property(ptp => ptp.PessoaTipoId)
                            .ValueGeneratedOnAdd();//Checar se o auto incremento funciona.

                pt.Property(ptp => ptp.Descricao)
                            .HasColumnName("Descricao")
                            .HasColumnType("Varchar")
                            .HasMaxLength(25)
                            .IsRequired();
            });
        }
    }

 public class FactoryPersistContext : IDbContextFactory<PersistContext>
    {
        private string ConnectionString = ConfigurationManager.ConnectionStrings["SistemaComercial"].ConnectionString;

        public PersistContext Create(DbContextFactoryOptions options)
        {
            var constructor = new DbContextOptionsBuilder<PersistContext>();
            constructor.UseSqlServer(ConnectionString);
            return new PersistContext(constructor.Options);
        }
    }
Answer: Essa opção não existe no Entity Framework Core.
Você pode fazer algo parecido fazendo com que a migração seja feita sempre que a aplicação for iniciada, pra fins de desenvolvimento.
Possivelmente se eu fosse usar esta opção ainda faria alguma verificação pra ter certeza que a aplicação está realmente em modo de desenvolvimento, mas como não sei o contexto não vou opinar sobre isso
Coloque este trecho no código de inicialização da aplicação (provavelmente no Startup.cs)
using (var contexto = new Contexto())
{
    contexto.Database.Migrate();
}


Will win8 boot if I disable UEFI?

Question: I'd like to disable UEFI mode in case if something will go wrong with my laptop and I will need to load another OS to it. However it would be very unfortunate if switching of UEFI prevented win8 from booting.
Does anybody know if it is safe to disable UEFI junk?
Comment: UEFI isn't really junk...it allows you computer to stop pretending its 1999.
Comment: Why do you want to disable UEFI now in case you may want to boot some legacy OS at some point in the future? (I'm not sure disabling UEFI is actually even a thing, I guess you would rather enable [CSM](http://en.wikipedia.org/wiki/Unified_Extensible_Firmware_Interface#CSM_booting))
Comment: The only way I found to get into BIOS is through windows Shift-Restart; ordinary restart with F1 did not let me get into BIOS. I do not know what will happen if Windows go down.
Answer: If you installed the OS when UEFI was enabled, then your system disk uses a GUID Partition Table.
BIOS can't boot from these partitions, and even if it could, your current system installation has no BIOS-compatible bootloader, so you would just be stuck on a black screen right after the BIOS if you disabled UEFI.
If you still want to disable it, you'd have to reinstall your system and reformat your system disk, however there is no need to disable UEFI if you system works fine with it, which I assume it does.

Will win8 boot if I disable UEFI?


How do I convert the number of Julian days into the Julian date? 44332 into May 17 2021?

Question: I am able to convert a regular date such as 05/19/2021 into Julian date number 44334 (the amount of days passed since year 1990).
However, I am required to now do the opposite, and I just have no idea how.
Could you please help me out on logic here?
Comment: You just invert your calculation. Not even a programming problem, just solving an equation for a different variable. High-school stuff.
Comment: Since you already have the code to convert `05/19/2021` to `44334`, you can just reorganize your code structure to have an intermediate representation of the date, then do the opposite would be easy.
Comment: See [github example](https://github.com/JohannesBuchner/libnova/blob/master/src/julian_day.c) and many other examples to draw from.
Comment: There's a terminology issue here.  The Julian day number is a count of days since November 24, 4714 BC, in the proleptic Gregorian calendar (https://en.wikipedia.org/wiki/Julian_day).  A Julian date is a date in the Julian calendar (https://en.wikipedia.org/wiki/Julian_calendar).  05/19/2021 is only 11461 days after 01/01/1990.  What you're looking for is the number of days after 1899-12-31.  This is often referred to as an Excel date as it was the measure used in Microsoft Excel.
Answer: You can use date.h or its C++20 implementation in case you already use it.
using namespace date;
using namespace date::literals;

This will do the trick.
year_month_day ymd(1990_y/01/01); // Create a date object. '_y' is a literal like 'f' for float which comes with `date::literals` or `chorno::literals`.
sys_days total_days = (sys_days)ymd; // Convert it to a time_point.
total_days += days(44334); // Add the days.
year_month_day later = total_days; // Convert it back to an object.

I found help here:
std::chrono add days to current date
Comment: @Codeissimple What is still missing?


isomorphism between factor ring of matrices and Z

Question: I have a commutative ring R= $\begin{pmatrix}a & b \\ 0 & a \end{pmatrix}$ (R is a 2x2 matrix, a, b $\in$ Z), I=$\begin{pmatrix}0 & b \\ 0 & 0 \end{pmatrix}$ is an ideal.
I need to prove that R/I is isomorphic to Z.
I was trying to show that I is a maximal ideal but couldn't figure it out properly. Anyone, please, help.
or I should be prime…
Comment: I believe it is implicit in your question, but you should mention that the elements $a$ and $b$ belong to $Z$.
Answer: We can use the first isomorphism theorem to prove this.
Let $\phi : R \to \mathbb{Z}$ denote that mapping $\begin{pmatrix} a&b\\ 0&a \end{pmatrix} \to a$. It can be shown that $\phi$ is a homomorphism.
Then $\ker \phi = I$. And $\phi (R) = \mathbb{Z}$.
This is all we need for the first isomorphism theorem to say $R/I \cong \mathbb{Z}$.
Comment: Look at two elements of $R$, say $\begin{pmatrix} a&b\\ 0&a \end{pmatrix}$ and $\begin{pmatrix} c&d\\ 0&c \end{pmatrix}$. Suppose their product is in $I$. Then, if you multiply them, you get that $ac = 0$, so either $a$ or $c$ is $0$. Thus, one of them is in $I$. That proves that $I$ is prime.
Comment: That is what I am currently trying to figure out. It is easy enough to show that $R/I$ is an (infinite) integral domain with characteristic $0$. I suppose one could look up the basic axioms of the integers and show that $R/I$ follows them. See http://www.math.niu.edu/~jthunder/Courses/2009Fall/420/sec1/aug24/intaxioms.pdf. (this doesn't use prime ideals either . . .)
Comment: I did it the same way, but the professor, who assigned this problem, wants it to be solved through maximal/prime ideals. That's where I got stuck…
Comment: Hint: $I$ cannot be maximal since $\mathbb{Z}$ is not a field, but $I$ has to be prime since $\mathbb{Z}$ is an integral domain. Of course this is only known after the theorem is proven -- but it may provide some direction.
Comment: Is there a way to prove that I is prime? Then by theorem R/I will be an integral domain as well..
Comment: I was thinking maybe because the entries of R/I would be integers that somehow leads that the whole int.domain is isomorphic to Z..
Comment: let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/11812/discussion-between-eric-thoma-and-nika)


Minimize $K(p||q)$, when $q$ is not normalizable?

Question: Let $K(p||q)$:
$$K(p||q) = \int p(x) \log \frac{p(x)}{q(x)} \mathrm{d} x$$
where the integral goes over the common support of $p$ and $q$.
The distribution $p$ that minimizes this is $p = q$. However, if $q$ is not normalizable, is there a distribution $p$ that minimizes $K(p||q)$?
Comment: So $q$ is not a proper distribution?  Are we to assume anything about it?
Comment: If $q$ is normalizable over the support of $p$, then yes, you can just "renormalize" it. In general case, I suspect, KL is unbounded from below: for example take $q(x) = a \forall x \in \mathbb{R}$ and $p_\beta(x) = \tfrac{1}{2\beta} [|x| \le \beta]$ (square brackets evaluate to 0 or 1). Then KL is effectively minimized by maximum entropy distribution on real line with no constrains, and for our family $p_\beta$ we have $H = \log(2 \beta) = -KL$
Answer: No.
"Not normalizable" must imply integrable and non-negative but with divergent integral.  Thus, there exists a sequence of measurable sets $ \mathcal{A}_i,\ i=1,2,3,\ldots$ for which $i \le C_i =\int_{\mathcal{A}_i} q(x)dx \lt \infty$.  Define
$$p_i(x) = \frac{1}{C_i} q(x),\ x \in \mathcal{A}_i,$$
and $p(x)= 0$ otherwise.  By construction, $p_i$ is a PDF but
$$K(p_i||q) = \frac{1}{C_i}\int_{\mathcal{A}_i} q(x) \log\left(\frac{1}{C_i}\right) dx = -\log(C_i) \lt -\log(i).$$
Since the sequence $-\log(i)$ has no lower bound, there can be no minimum value of $K(p_i||q)$, QED.


Calculate the integral $\int_1^{10}x^xdx$

Question: $$\int_1^{10}x^xdx$$
I figured it with a relative error of 1% and I have a response $$≈0.3*10^{10}$$
But I don´t know how to accurately calculate it ...
Comment: The problem of course with using power series is that they suck at approximating far away from the point of expansion. I would actually just suggest using numerical quadrature if one wants accurate values.
Comment: You cannot find a closed form for $\int x^{x}dx$ (see http://math.stackexchange.com/questions/155/how-can-you-prove-that-a-function-has-no-closed-form-integral/2329#2329 )
Comment: @Tavares, you don't need to find the antiderivative of a function to accurately calculate its integral, there are many ways to find a convergence series.
Comment: If you just want more accuracy or to check the accuracy of any method, Wolfram alpha can help you out. `http://www.wolframalpha.com/input/?i=int_0^10+x^x`
Comment: @Haengel, I know. My comment was an information in case OP was trying to  find a closed form.
Answer: One way to solve this problem is to expand in terms of a power series as follows:
First notice that
$x^x = e^{\ln(x) x} = \sum_{n=0}^\infty \frac{(\ln(x) x)^n}{n!} $
Integrating on both sides from $1$ to $10$ gives
$\int_1^{10} x^x dx = \sum_{n=0}^\infty \frac{1}{n!} \int_1^{10} x^n \ln(x)^n dx $
The function $x^n ln(x)^n$ is monotonically increasing, so the integral inside the sum is bounded by:
$ \frac{1}{n!} \int_1^{10} x^n \ln(x)^n dx < \frac{9}{n!} \cdot \ln(10)^n \cdot 10^n $
So if you want the sum to whatever precision, you can use that expression to determine how small the remainder term is. Next, how on earth do you compute that integral? Well it looks ugly but there is a recursive formula. Let $k, l$ be positive integers. Then using integration by parts
$ \int_1^{10} x^k \ln(x)^l dx = \frac{x^{k+1} ln(x)^l}{k+1} \Bigr \vert_1^{10} - \frac{l}{k+1} \int_1^{10} x^k \ln(x)^{l-1} dx $
Since you chose the limits of integration to be from $1$ to $10$ you might have to take quite a few terms in this series in order to compute an accurate value, but that is to be expected as $x^x$ blows up so quickly.
Comment: The problem with this approach is that not only do you have to take a lot of terms (for instance, using the fact that $n! \approx (n/e)^n$, we see that the terms don't even get back to unity until n is roughly 60 or so), the terms themselves are immensely large and the negation involved in the integration by parts means they'll have to be calculated extremely precicely to navigate cancellative effects.  Much better, as J.M. mentioned, to just use quadrature.


Como esconder o scrollbar

Question: Como esconder o ScrollBar com o CSS? Não estou conseguindo.
Já tentei em vários editores, porém não consigo. O que eu faço?
Comment: É sempre bom incluir na pergunta o código que vc tem tentado fazer e que não está funcionando, e incluir mais detalhes para maior clareza. Por exemplo: vc não especificou qual scrollbar quer esconder (existem 2).
Answer: Se for a scrollbar da viewport faz assim com o CSS:
body{
overflow: hidden;
}

para um elemento HTML:
elemento, .classe, #id {
overflow: hidden;
}

/* BARRA HORIZONTAL */
body{
overflow-y: scroll;
overflow-x: hidden;
}

para um elemento HTML:
elemento, .classe, #id {
overflow-y: scroll;
overflow-x: hidden;
}

Answer: .suaClasse{
overflow: hidden;
}
Answer: overflow-y: hidden

ou
overflow-x: hidden

Como esconder o scrollbar


Expectation of $(X + Y)^2$ where $X$ and $Y$ are independent Poisson random variables

Question: I would really appreciate anyone's help with this problem:
(let $E$ denote expectation)

Suppose $X$ and $Y$ are independent Poisson random variables, each with mean $1$.
  Find:
  $E[(X + Y)^2]$ "

My question is why can't I expand the $(X + Y)^2$ to get $E(X^2 + 2XY + Y^2)$ and then use linearity to get $E(X^2) + 2E(X)E(Y) + E(Y^2)$. Then since $X$ and $Y$ are independent, this would give $E(X)^2 + 2(1)(1) + E(Y)^2 = 1 + 2 + 1 = 4$. But the answer is 6.
I can get the correct answer through this method: $E[(X+Y)^2] = Var(X + Y) + E[(X+Y)]^2$ and noting that $X + Y$ has a Poisson distribution with mean $2$. But why doesn't the first method work?
Please help! I'd really appreciate it.
Comment: Recall the formula for the variance of X: `Var(X) = E[X^2] - E[X]^2`. Now, the only way that E[X^2] would be equal to E[X]^2 is if X does not vary at all (i.e. it's a constant).
Comment: In general, E[X^2] != E[X]^2
Comment: Okay, I see now that was a pretty silly question. Sorry! But thank you all so much (especially @Dason for completely addressing my issue).
Comment: X can't just be 'independent'.  Independence is a property of a set of random variables.  You can use independence of X and Y (notice that that is independence with respect to both the variables) to say that E[XY] = E[X]E[Y].  But it doesn't make sense to say that X is "independent" because the natural next question would be "independent of what?".  It can't be independent of itself which is what you would need to say that E[X^2] = E[X*X] = E[X]E[X].
Comment: But they are equal if X is independent, correct?
Answer:
why can't I expand the $(X + Y)^2$ to get $E(X^2 + 2XY + Y^2)$

You can.

and then use linearity to get $E(X^2) + 2E(X)E(Y) + E(Y^2)$

You can

Then since $X$ and $Y$ are independent,

right ... but you already used independence in the previous step when you wrote $E(XY)$ as $E(X)\,E(Y)$.

this would give $E(X)^2 + 2(1)(1) + E(Y)^2 = 1 + 2 + 1 = 4$.

Nope. You just went $E(X^2) = E(X)^2$; that's not true. You got this manipulation right when you did it the other way. Note that:
$E(X^2) = \text{Var}(X) + E(X)^2 = 1 + 1 = 2$
and then the result follows.
(It would be easiest to add the random variables first and then find the expectation of the square, but it's quite doable by expanding the square)
Answer: You cannot say $E(X^2)=E(X)^2$ since $X$ is not independent of $X$.
For this problem you can set $Z=X_1+X_2 \sim \text{Poisson}$ with mean $2$. Than you can find $E(Z^2)$ easily.


Tags not saving or showing, why?

Question: I am using acts-as-taggable-on and without any luck been trying to figure this out for awhile now. For some reason i cannot get my tags to show up or save inside of the database.I really need some help, i looked online and the documentation is intermediate or not newbie friendly. Here is my code:
Devise User Model:
class User < ActiveRecord::Base

  has_many :products, :dependent => :destroy
  acts_as_tagger
end

Products Model:
class Product < ActiveRecord::Base
    attr_accessible :name, :date, :price, :tag_list

    acts_as_taggable_on :tags

    belongs_to :user
end

Form:

    <%= f.label :tag_list %>
    <%= f.text_field :tag_list %>

Show View:

    Tags:
    <%= @product.tag_list %>

EDIT WITH UPDATED AND WORKING CODE:
I am using Devise and letting only the current_user (user_id in products table) do actions such as create,destroy,update tags,etc.
User Model:
class User < ActiveRecord::Base
  has_many :products,        :dependent => :destroy
  acts_as_tagger
end

Product Model:
class Product < ActiveRecord::Base
    attr_accessible :name, :date, :price, :tag_list, :longitude, :latitude

    acts_as_taggable_on :tags
end

Products Controller:
class ProductsController < ApplicationController
  before_filter :authenticate_user!

  def index
    @products = Product.all

    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @products }
    end
  end

  def show
    @product = Product.find(params[:id])

    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @product }
    end
  end

  def new
   @product = Product.new

    respond_to do |format|
      format.html # new.html.erb
      format.xml  { render :xml => @product }
    end
  end

  def edit
    @product = current_user.products.find(params[:id])

    @product.user = current_user
  end

  def create
    @product = current_user.products.build(params[:product])
    @product.user = current_user

    respond_to do |format|
      if @product.save
        format.html { redirect_to(@product, :notice => 'Product was successfully created.') }
        format.xml  { render :xml => @product, :status => :created, :location => @product }
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @product.errors, :status => :unprocessable_entity }
      end
    end
  end

  def update
    @product = current_user.products.find(params[:id])
    @product.user = current_user

    respond_to do |format|
      if @product.update_attributes(params[:product])
        format.html { redirect_to(@product, :notice => 'Product was successfully updated.') }
        format.xml  { head :ok }
      else
        format.html { render :action => "edit" }
        format.xml  { render :xml => @product.errors, :status => :unprocessable_entity }
      end
    end
  end

  def destroy
    @product = current_user.products.find(params[:id])
    @product.destroy

    respond_to do |format|
      format.html { redirect_to(products_url) }
      format.xml  { head :ok }
    end
  end
end

products/index.html.erb:
<%= product.tag_list %>

products/show.html.erb:

    Tags:
    <%= @product.tag_list %>

Comment: Whats the ERB look like for that form and what does the controller look like for the Product?
Comment: I updated it to show you my Products Controller.
Comment: Are lines like this `#@product = Product.new(params[:product])` commented out in your app? That means that nothing gets saved. You need to fix your devise/cancan roles if that is the reason you commented them out.
Comment: @Devin M Yeah it seems to be a problem with my roles so i uncommented them and they started working but now i have to figure out my Devise set up becuase CanCan is all screwed up. I am trying to get it so the Current User only can do all of  the above actions. Anyways, thanks for the help Devin!
Comment: Post another question about cancan if you want and I should be able to help. Just give me a link here when its up.
Comment: @Devin M I got rid of CanCan just in-case i have conflicts with future code because i don't understand Ruby or Rails enough yet and don't want to be "gem-dependent". I defintely will be asking questions in the future that deal with acts-as-taggable-on though, Thanks for the help!
Answer: Try using this code in your view:

    Tags:
    <%= @product.tags %>

Comment: I will give you credit for this because it lead me to the answer!
Answer: I ran into something similar. I hadn't added :tag_list to my events_controller (I'm making a bare-bones meetup clone for my youth group) -
private
        def event_params
            params.require(:event).permit(:title, :text, :user_id, :event_start, :time_begin, :location, :address, **:tag_list**)
        end
end

Wasn't throwing any other errors than that, luckily I thought of this too.

Tags not saving or showing, why?


What is $\arctan(x) + \arctan(y)$ if $xy=1$

Question: We know that
$$\arctan(x)+\arctan(y) = \begin{cases}\arctan\left(\dfrac{x+y}{1-xy}\right), &xy < 1 \\[1.5ex]
\pi + \arctan\left(\dfrac{x+y}{1-xy}\right), &x>0,\; y>0,\; xy>1 \\[1.5ex]
-\pi + \arctan\left(\dfrac{x+y}{1-xy}\right), &x<0,\; y<0,\; xy > 1\end{cases}$$
My question is: What is $\arctan(x) + \arctan(y)$ if $xy=1$
Comment: https://math.stackexchange.com/questions/304399/are-mathrmarccotx-and-arctan1-x-the-same-function
Answer: It is $\frac\pi2$ (assuming that $x,y>0$), because $\arctan(1)+\arctan(1)=\frac\pi2$ and$$\left(\arctan(x)+\arctan\left(\frac1x\right)\right)'=0.$$
Answer: If $x>0$, then $0<\arctan x<\pi/2$, and if $t=\arctan x$, then $\cot t=1/\tan t=1/x$, so that $\arctan(1/x)=\pi/2-t$. If $x>0$,
then $\arctan x+\arctan (1/x)=\pi/2$.
As $\arctan$ is an odd function, if $x<0$,
then $\arctan x+\arctan (1/x)=-\pi/2$.


Find the maximum value of $P= \frac2{1+a^2}-\frac2{b^2+1}+\frac3{c^2+1}$

Question: The problem is, given that $a,b,c>0$ and $abc+a+c=b$, then find the maximum value of
\begin{align}
P= \frac2{1+a^2}-\frac2{b^2+1}+\frac3{c^2+1}
\end{align}
One thing I know for sure is that $a,c$ are symmetric, or so I thought.
In the condition, clearly $a,c$ are symmetric, and thus I guessed that if (a,b,c) satisfies P is maximum then (c,b,a) should also be one. But unfortunately, in $P$, the role of $a$ and $c$ are irreversible.
So how should I approach this problem?
Any help is appreciated!
Comment: Are you familiar with the theory of [lagrange multipliers](https://en.wikipedia.org/wiki/Lagrange_multiplier)?
Answer: Following a tip by a previous answer, we set $a=\tan \theta~,~ c=\tan\phi$ and we find by solving the constraint that, surprisingly:
$$b=\tan(\theta+\phi)$$
which allows us to write
$$P=\frac{3}{2}+\cos 2\theta -\cos (2\theta+2\phi)+\frac{3}{2}\cos2\phi$$
where $\theta,\phi,\theta+\phi \in (0,\pi/2)$. Taking derivatives and solving the simple trigonometric equations yields a maximum in the interior of the $(\theta,\phi)$ region at
$$\cos 2\theta_0=\frac{1}{3}~~,~~ \cos 2\phi_0=\frac{7}{9}$$
and after comparing with the various boundary values of the function we finally conclude that
$$P\leq P(\theta_0, \phi_0)=\frac{10}{3}$$
Comment: Nice way to do it ! $\to +1$.
Answer: You have two ways to solve the problem without changing variables.
First way
From the constraint, we have, for example, $b=-\frac{a+c}{a c-1}$. Replacing in $P$ and simplifying
$$P=\frac{a^2 \left(3-2 c^2\right)+4 a c+2 c^2+3}{\left(a^2+1\right)
   \left(c^2+1\right)}$$ Computing the partial derivatives
$$\frac{\partial P}{\partial a}=-\frac{4 c \left(a^2+2 a c-1\right)}{\left(a^2+1\right)^2 \left(c^2+1\right)}=0\tag 1$$
$$\frac{\partial P}{\partial c}=-\frac{2 \left(a \left(5 a c+2 c^2-2\right)+c\right)}{\left(a^2+1\right)   \left(c^2+1\right)^2}=0\tag 2$$
From $(1)$, $c=\frac{1-a^2}{2 a}$. Plug in the numerator of $(2)$ to obtain
$$-4 a^3-2 a+\frac{2}{a}=0 \implies -\frac{2 \left(a^2+1\right) \left(2 a^2-1\right)}{a}=0\tag 3$$ So, taking into account the conditions
$$a=\frac{1}{\sqrt{2}} \implies c=\frac{1}{2 \sqrt{2}} \implies b=\sqrt{2}\implies
P=\frac{10}{3}$$
Second way
Using Lagrange multipliers, consider
$$F=P+\lambda(abc+a+c-b)$$
$$\frac{\partial F}{\partial a}=\lambda  (b c+1)-\frac{4 a}{\left(a^2+1\right)^2}=0\tag 4$$
$$\frac{\partial F}{\partial b}=\lambda  (a c-1)+\frac{4 b}{\left(b^2+1\right)^2}=0\tag 5$$
$$\frac{\partial F}{\partial c}=\lambda  (a b+1)-\frac{6 c}{\left(c^2+1\right)^2}=0\tag 6$$
$$\frac{\partial F}{\partial \lambda}=abc+a+c-b=0\tag 7$$
But, for this case, it is quite tedious to solve equations $(4,5,6,7)$ but it leads to the same results with $\lambda=\frac{16 \sqrt{2}}{27}$.


Can i respond to the notification POST from SagePay with a POST

Question: I am integrating SagePay with Sitefinity, specifically the server low profile integration and i am a little stuck.
I have created a custom offline payment provider in Sitefinity, and this class has the relevant Notification hooks (Sitefinity has its own dedicated Notification Url which handles processing so you don't have to run your own).
The issue i have, is Sitefinity wants to POST the relevant information back (Status, RedirectUrl) but in the integration guides the notification paid seems to flush itself and just present itself as the plain text representation of the required return values.
Is there a URL i can post the notification response too, or does it have to be the Plain text response?
Comment: What version of sitefinity? Also were you not able to use the built in SagePay payment options?
Comment: 7.2 but will go to the latest version on release. Need to use the Server integration (offsite) for this project. Have an idea will give it a try in the morning.
Comment: Did you get this resolved?
Comment: Kind of, but it is not complete and had to go way outside the Sitefinity way of doing this.
Answer: For anyone else, i would speak to Sitefinity to see if they have a route for this, there current setup i think deals with most situations but mainly from a direct point of view where you are directly able to POST and receive specific responses.
The current setup of the Server integration from SagePay is not like that, in that it needs some form of notification page to output a specific format as part of its response output (so basically the response needs to be "rendered" to the page") for SagePay to pick it up and complete the transation.
This was a custom cart implementation so i had a bit more scope, think it would be a PITA if i had to do it via the built in checkout.

On my Payment page, if the user selected Card payment i would register SagePay via the code library they supply (if JavaScript is enabled i did this via a Web Api Call and responded with the next URL)
Created a notification.aspx page in a publically available area on the site and passed that to SagePay as the notification point
After payment is confirmed i have a confirmation step in my checkout that deals with setting all the required values pulled back from SagePay, it has no output, it just processes the order and payment together before redirecting to the success step

Should have been much more simple then this, but they would have to update their internal notification page to respond with a plain text response in order for this to work.


Are JavaScript iifes (Immediately-invoked function expressions) still relevant?

Question: My understanding of the concept is that iifes allow you to simulate a "private" scope which prevents the global scope from becoming cluttered.
Now that ECMAScript 6 has seen fairly widespread implementation and given us access to block level scoping via const and let, is any other reason to use the iife pattern? (beyond the need to provide backward compatibility..)
Comment: Most uses for IIFE's have disappeared because block scoped variables solve the most common thing that IIFE's are used for.  That said, there are still some less common reasons to occasionally use one (though I haven't encountered one of those in my code yet).
Comment: This is mostly an opinion based question but I'd imagine they'll still be relevant for a while. I think Immediately invoked async and generator functions are relevant IMO.
Comment: one advantage of a function is being able to use `return` to halt execution early. you can also alias surrounding lexical variables with parameters+arguments. Functions can also name the program to use for debugging. Lastly, you can recurse/restart a named IIFE from within, whereas there's no reference to blocks.
Comment: @dandavis - All of those benefits can also be achieved by just using a named function which is how most languages handle this.  Perhaps there is a usefulness to sometimes being inline for accessing parent scoped variables.
Answer: One of the benefits to an IIFE that a plain block cannot achieve is the ability for its output to be assigned to a const. For example:

const output = (() => {
  // some calculations that take a few lines
  const now = new Date();
  return now.getMinutes() + ':' + now.getSeconds();
})();
console.log(output);

Let's say we wanted to enclose the now variable in an IIFE because it's only relevant for calculating output, and is not needed anywhere else. If one were to use a plain block for this purpose instead, it would only be possible if output was declared with let rather than const:

let output;
{
  // some calculations that take a few lines
  const now = new Date();
  output = now.getMinutes() + ':' + now.getSeconds();
}
console.log(output);

Because const significantly improves the readability of code (in my opinion), this arguably a potential reason to prefer the IIFE over the plain block, though of course code styles differ.
That said, if one were to extract till you drop, some might say to avoid IIFEs and declare a standalone function, which can then be imported and called:

function getTimeStr() {
  const now = new Date();
  return now.getMinutes() + ':' + now.getSeconds();
}

// another file:
// import getTimeStr from './getTimeStr';
const output = getTimeStr();
console.log(output);

As in the above snippet, the use of a modern code bundler such as Webpack (or, perhaps, ES6 modules) may have more of an impact on less usage of IIFEs than than the ES6 ability to use plain blocks. It depends on the coding style one prefers, but using IIFEs is certainly a possible option one might choose.
Comment: I don't get your first point.  `const now = new Date(); const output = now.getMinutes() + ':' + now.getSeconds();`.  Sure, `now` is not needed elsewhere, but who cares?  It's `const` and can't be mucked with anyway.  This does not seem like a rationale for an IIFE in any common or useful way.  Why complicate the code to hide one temporary variable?
Comment: The example as you show it cries out to be made into a reusable named function.  It might be possible to come up with a more complicated example with lots of intermediate variables and lots of access to parent scoped variables that is not so easy to make into a named function.  But, at that point, the code probably just needs to be simplified in other ways and still probably an IIFE isn't the right solution.
Comment: It's just an example. For just one variable and two lines, yes, it does look pretty silly, but if the calculations needed to determine the output were more involved and there were more intermediate variables needed to come up with the final `output`, enclosing all of that calculation in one function (perhaps in an IIFE) would make more sense. This would be especially true if the function/block the whole code is contained in is *long* (though, of course, better to avoid long functions in the first place, if possible). Fewer variables in scope can mean (slightly) less cognitive overhead.
Comment: The point was just that it's a *possible option* one might choose. Still, I'd prefer to extract into a named function in most cases
Comment: If you are using an IIFE to create a value that persist the way you have it, why not just create a closure..?
Answer: Pretty much all the common reasons for using an IIFE in my code have been replaced with block-scoped variables.
The ONE use I have seen in real code is to simulate top-level await:
(async function() {
    try {
        const data1 = await something1();
        const data2 = await something2(data1);
        ...
     } catch(e) {
        ...
     }
})();

The remaining reasons I see for an IIFE are when you want the advantages of a function such as using return or throw to stop execution of a defined portion of the remaining code (without nesting in an if) or when you want to call something recursively.  But, of course, you could get all of those advantages with a locally scoped named function too.
But, if the code in your function benefits heavily from accessing parent scoped variables, then it really wants to be inline and that creates a possible reason for an IIFE to combine the advantages of being in a separate function with inline access to parent scope.
Now, in reality, most/all of these cases can also be solved with a little refactoring to either define the named function in the local scope (so it still has access to parent scoped variables) or just pass things from the parent scope to a named function so it has access to them that way and, in fact, that's what we all do in other languages.  The only cost to that is one more local function name (which can even be locally scoped if you want to hide it).


JobScheduler and JobIntentService

Question: I am working on an app that supports Android API version 21 and above. Most of my background tasks have been designed with JobScheduler introduced in API 21.
I have recently come across JobIntentService introduces in API 26. The documentation says "When running on Android O or later, the work will be dispatched as a job via JobScheduler.enqueue. When running on older versions of the platform, it will use Context.startService."
What I want to understand is, why android is using JoScheduler only from API 26 and not from API 21. Is there a difference in JobScheduler on API 26 and above from that of the one introduced in API 21. Do I need to change any code to improve efficiency/avoid mistakes, converting my background jobs to use JobIntentService instead of Job Schedulers. I guess I do not understand the intention of what JobIntentService is trying to achieve.
Answer:
I do not understand the intention of what JobIntentService is trying to achieve

JobIntentService is meant to be a replacement for the IntentService/WakefulBroadcastReceiver combination, for background tasks that might take more than a minute (but less than ten) and for which you do not wish to use a foreground service.

why android is using JoScheduler only from API 26 and not from API 21

Only Google can answer that, which is why questions of the form "why did Developer X make Decision Y?" are not good for Stack Overflow.
Note that the "more than a minute" issue arises with the background limitations on API Level 26+; on previous versions, there was no such limit.

Is there a difference in JobScheduler on API 26 and above from that of the one introduced in API 21

There have been changes, including some extensions that enable JobIntentService to work.

Do I need to change any code to improve efficiency/avoid mistakes, converting my background jobs to use JobIntentService instead of Job Schedulers

I do not know why you would switch from your own JobService to JobIntentService. JobIntentService is a replacement for IntentService, not for JobService.

JobScheduler and JobIntentService


Is there a more specific term for this blues sound? (5 and ♯4)

Question: I like the crunchy, janky texture of playing a note with the note a semitone under it in a melodic voice, usually on the dominant scale degree. For example, in the original Thomas the Tank Engine TV show theme's intro.

---------E♭-E♭------E♭-----E♭-E♭
---A♭---D--D----E♭----A♭-D---D

Is there a name for this? I can't find one.
Edit: Sorry, I should have been more clear. I'm advanced enough at theory to know my specific intervals; I know it's a minor second. I'm looking for a more specific term to describe the texture/effect of using minor seconds in the melody. Looking for more of a blues term than a theory term.
Comment: What is a "blues term," and why would you want one for a device found in the theme from Thomas the Tank Engine? That doesn't sound like a blues to me. It is unclear to me what you are looking for. Can you provide an example of the kind of term you seek for some other musical device?
Answer: There are a couple of things going on there. The Ab-D gives you a tritone, and you might think of this as a Lydian sound. But what you are probably more interested in is the D-Eb dyad. That interval is a minor second. I don't know of any name for that other than minor second, but it is a sound that was used a lot by the great jazz pianist Thelonious Monk. It is a great sound, and you can often bring it out in voicings of Maj7 chords, Lydian chords, or altered chords.
Minor seconds can be used to provide very pretty, but somewhat astringent, shimmering sounds. In the case in question, the already angular tritone movement from Ab to D is underlined by the astringent quality of the minor second dyad D-Eb. It is the combination of these two devices that results in the "janky texture" that you describe.
Answer: Yes - it's called a minor second if they are in the same octave, and a flat nine if they aren't.  It's a pretty dissonant interval - in your example I think it's an effort to mimic a train whistle.
To find the name of any interval, count the number of letters between them, beginning with "one" as the number for the lower pitch; ignore any sharps or flats.  Then compare the upper note with the major scale of the lower one...
if the upper note is the tonic, fourth, or fifth of the lower note's major scale:

it's perfect if it's in the scale
it's augmented if it's as half step above the scale tone
it's diminished if it's a half step below the scale tone

if the upper note is the 2nd, 3rd, 6th or 7th of the lower note's major scale

it's major if it's in the scale
it's minor if it's a half step below the scale tone
it's augmented if it's a half step above the scale tone
it's diminished if it's a whole step below the scale tone

you can also have doubly-augmented or doubly-diminished intervals, like C-Fx or C#-Gb


Driven harmonic oscillator: Why does the phase of the driver have such a big impact on the solution?

Question: Consider the equation for a driven harmonic oscillator,
$$\frac{d^2 x}{d t^2} + \omega_0^2x(t) = f(t),$$
with initial conditions
$$x(0)=\left.\frac{dx}{dt}\right|_{t=0}=0.$$
If we assume $\omega_0\ne\omega$ then
$$x(t)=x_0\omega^2\begin{cases}
\frac{\omega_0\sin(\omega t) - \omega \sin(\omega_0 t)}{\omega_0(\omega_0^2 - \omega^2)}, & f(t)=x_0\omega^2\sin(\omega t), \\
\frac{\cos(\omega t) - \cos(\omega_0 t)}{\omega_0^2 - \omega^2}, & f(t)=x_0\omega^2\cos(\omega t).
\end{cases}$$
In the limit $\omega\rightarrow \infty$,
$$x(t)\rightarrow x_0\begin{cases}
\frac{\omega}{\omega_0}\sin(\omega_0 t), & f(t)=x_0\omega^2\sin(\omega t), \\
\cos(\omega_0 t) - \cos(\omega t), & f(t)=x_0\omega^2\cos(\omega t).
\end{cases}$$
This shows that depending on the phase of the driver the amplitude can be infinite or finite. Do you know a physical reason why this might be, or have I made a mistake in the maths somewhere?
Answer: Consider the easier differential equation
$$ \frac{d^2x}{dt^2} = f(t) $$
with $x(0) = \frac{dx}{dt}\Big|_{t=0} = 0$.  If $f(t) = x_0 \omega^2 \sin(\omega t)$ we get
$$ x(t) = x_0 \omega t - x_0 \sin(\omega t) .$$
If $f(t) = x_0 \omega^2 \cos(\omega t)$ we get
$$ x(t) = x_0 - x_0 \cos(\omega t) .$$
Again, the phase of the driving term determines whether the amplitude blows up or stays bounded.
It basically boils down to the constant terms.  In the first case, there is a net velocity in the motion, which causes the solution to drift to infinity.  In the second case, you 'get lucky' and the drift is exactly zero.


How to set list of values as parameter into hibernate query?

Question: For example, I have this query
 select cat from Cat cat where cat.id in :ids

and I want to set ids to list (1,2,3,4,5,6,17,19).
This code doesn't work
session.createQuery("select cat from Cat cat where cat.id in :ids")
       .setParameter("ids", new Long[]{1,2,3,4,5})

As the result I would like to have SQL query like id in (1,2,3,4)
Answer: Use setParameterList(). You'll also have to put parenthesis around the list param.
session.createQuery("select cat from Cat cat where cat.id in (:ids)").setParameterList("ids", new Long[]{1,2,3,4,5})

Comment: `setParameterList` is depcreated in newer hibernate.  How do we pass this in?  I tried using `setparameter` and didn't get correct behavior...
Comment: yes setParameterList is deprecated and i could not get correct behavior too, any update?


Conditional expectation of a product of random variables

Question: I have two independent continuous random variables $X$ and $Y$ with

pdf's : $f(x)$ and $f(y)$
cdf's : $F(x)$ and $F(y)$
a constant $a$

I am trying to express using the given pdf/cdf functions the following expressions:

$Pr(X\cdot Y > a)$
$E(X\cdot Y | (X\cdot Y < a))$

The question becomes trivial if I find the pdf/cdf of a variable $Z = X\cdot Y$
This corresponds to the product distribution, however I am not sure how to use it to derive the cdf of $Z$ in order to find expression 1. and  2.
Comment: $$f_Z(z)=\int f_X(x)f_Y\left(\frac{z}x\right)\frac1{|x|}dx$$
Answer: In general if we let $X=g(U,V), Y=h(U, V)$ (and assuming this is a one-to-one coordinate transfer) we can use the Jacobian formula:
$$\begin{align}f_{U,V}(u,v)=&~ \Big\lvert\dfrac{\partial (x,y)}{\partial (u,v)}\Big\rvert\,f_{X,Y}(x,y) \\[1ex] =&~ \Big\lvert\dfrac{\partial (g(u,v), h(u,v))}{\partial (u,v)}\Big\rvert\,f_{X,Y}(g(u,v), h(u,v))\end{align}$$
Where $\dfrac{\partial (x,y)}{\partial (u,v)}$ is shorthand for the determinant of the Jacobian matrix $$\Big\lvert\dfrac{\partial (x,y)}{\partial (u,v)}\Big\rvert=\begin{Vmatrix}\partial x/\partial u & \partial x/\partial v \\ \partial y/\partial u & \partial y/\partial v \end{Vmatrix}$$

  In this specific case we take $U=X, V= XY$ (or $Z$), so $X=U, Y=V/U$ (or $Z/X$) ... and also $f_{X,Y}(x,y) = f(x)\,f(y)$ due to being independent and identically distributed

$$\begin{align}f_{X,Z}(x,z) =&~ \Big\lvert\dfrac{\partial (x,z/x)}{\partial (x,z)}\Big\rvert\,f(x)\,f(z/x)\\[1ex] =&~ \begin{Vmatrix}\partial x/\partial x & \partial x/\partial z \\ \partial (z/x)/\partial x & \partial (z/x)/\partial z \end{Vmatrix}\,f(x)\,f(z/x)\\[1ex] =&~ \begin{Vmatrix}1 & 0 \\ -z/x^2 & 1/x \end{Vmatrix}\,f(x)\,f(z/x)\\[1ex] =&~ \lvert \tfrac 1 x \rvert\,f(x)\,f(z/x)\end{align}$$

And hence the marginal is $\displaystyle f_{XY}(z) = \int_\Bbb R \lvert \tfrac 1 x \rvert\,f(x)\,f(z/x)\operatorname d x$


Giving an $A/I-$module $M$ is same as giving an $A-$module $M$ such that for each element $a\in I$ the $A-$module homomorphism $\phi_a:M\to M$

Question:
Let $A$ be a ring and $I$ be an ideal. Show that giving an $A/I$-module $M$ is same as giving an $A$-module $M$ such that for each element $a\in I$ the corresponding $A$ module homomorphism $\phi_a:M\to M$ (given by $\phi_a(m)=a\cdot m$) is zero.

I am unable to proceed.
Answer: Well, to proceed, you would have to figure out a likely candidate for an $A$ module structure and examine it. The most obvious one is what you want.
Hint:
You are given a multiplication $\phi_{a+I}:M\to M$ for each $a+I\in R/I$.
What would happen if you let $\phi_a=\phi_{a+I}$ for each $a\in R$?
Answer: Take the canonical surjection $\phi: A \to A/I$.
Consider by restriction of scalars, where an $A/I$ module $M$ is just an abelian group $M$ along with a ring morphism $\rho:A/I  \to \mathrm{End}  M$. In this case, $M$ can also be given a natural $A$-module structure by following morphisms: $\rho \circ \phi: A  \to \mathrm{End}(M)$. In this case, the morphism factors through $A/I$ so clearly $\rho \circ \phi(i)=0 \in \mathrm{End}(M)$ for any $i \in I$.
So, these things are "really the same."


How to send C-style array to objective-c method

Question: I am trying to send c-style array of integers to objective-c method, but in method I recieve only first element of array.
This is an example:
int a[3];
a[0] = 111;   a[1] = 222;   a[2] = 333;
[self getMatrix:a];

then
-(void)getMatrix:(int[3])matrix
{
    return;      -- breakpoint here
}

So, when debugging stops at breakpoint, i have matrix:
matrix  int *   0xbfffddd4
*matrix int 111

Where are other elements?
So, 2d-arrays become to 1d array, 3d-array become 2d-array etc.
What I am doing wrong?
Thanks!
P.S. NSArray is working fine ofc, but I can't imagine how to work with multidimensional (3d, 4d) NSArrays w/o writing tonns of code.
Comment: You can put `NSArrays` as elements of `NSArray`s. And for solving your problem you should have a look into call by reference.
Answer: -(void)getMatrix:(int[3])matrix
{
    int a = matrix[0];
    int b = matrix[1];
    int c = matrix[2];
}

You will see that the values are correct. There is nothing wrong. The debugger is only showing  *matrix which is the first element. Here matrix itself is a pointer to integer or int *.
Answer: You need to send pointer to first item and size of array through.
See how
- (void)setLineDash:(const CGFloat *)pattern count:(NSInteger)count phase:(CGFloat)phase
in NSBezierPath does this.
http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/ApplicationKit/Classes/NSBezierPath_Class/Reference/Reference.html


Fixed template sidebars position fixed

Question: I want to change the sidebars on the following template to have fixed position.
Is it possible to do it without using javascript and only css?
Template Demo
PS: Placing position fixed for the sidebards it is not an option because its changing the whole structure of the site and they are placed outside of content area.
Answer: you wanna like this??http://jsfiddle.net/kFBuD/1447/
overflow:hidden;

Comment: you can rewrite the scrollbar make it beautiful
Answer: You can using position:fixed
.sidebar1, .sidebar2 {
    background: red;
    height:100%;
    width: 100px;
    top:0;
    padding-top:60px;
    **position:fixed;**
    -moz-box-sizing:border-box;
    -webkit-box-sizing:border-box;
    -o-box-sizing:border-box;
    -ms-box-sizing:border-box;
    box-sizing:border-box;
}

Comment: No, that has some unwanted effect because its placing the two sidebars outside the content area.
Answer: you can use overflow property of HTML if you don't want it in CSS or JavaScript.
Comment: try something like this :

Fixed template sidebars position fixed


Bernoulli vs. Geometric distribution

Question: Suppose that in a sequence of independent bernoulli trails, the number of failures up to the first success is counted.
FIND: What is the frequency function for this random variable?
attempted SOLUTION:
We know that Bernoulli distribution where $f(k)=p^k(1-p)^{1-k}$ is the frequency function for number of successes in a single trial (??).
We also know that the geometric dirtribution models the number of failures up to the first success. Wouldnt be the frequency function for the random variable just be the geometric distribution with frequency function $f(k)=(1-p)^{k-1}p$ ?
provided SOLUTION
Our professor provided a solution to this exercises that states:
$f(k)=(1-p)^{k}p$
Is my approach wrong?
Comment: The distribution you provide, $f(k) = (1-p)^{k-1}p$, gives the Frequency function for the first success being in $k$-th run. This corresponds to $k-1$ failures, not $k$ failures, which you seek.
Comment: FYI, the name "Frequency function" does not exist.
Answer: If you choose k=1, the probability is (1-p)*p for (failure, success), so f(1)=(1-p)*p. So your proff. is right.

Bernoulli vs. Geometric distribution