Decision after draw in extra time in field hockey

Question: I saw a play-off match in some national field-hockey league and the match ended with the teams level.
I always thought that draws were decided based on a penalty series (like soccer). In this case however, the game ended with a shoot-out where one player starts far from the goal, and tries to beat the goal keeper in a solo rush (like hockey).
Is this a new official rule, or is this a try out for this league?
Comment: I saw that also on some championship. we should check the rules about it.
Comment: I've re-added the specific date here; "yesterday" I'd confusing because this event happened in 2012, not 2018 (or 2019 or 2020...)
Comment: @PhilipKendall And I removed it earlier because it looks silly. The whole date is irrelevent to the whole question. Also, the question already lists the date it is asked, so it is superfluous.
Comment: Please see the [current discussion on meta](https://sports.meta.stackexchange.com/questions/862/is-it-ok-to-use-words-such-as-yesterday-this-seasons-etc).
Answer: The FIH trialled the one-on-one shootout method (as opposed to "from-the-spot" shots) in the 2010 Champions Trophy and Champions Challenge as well as the Azlan Shah playoffs on the 15th May 2011.
These trials were to see if it was a suitable alternative to put in place for the 2012 London Olympics.

In the shoot-out, the striker starts the one-on-one attack against the goalkeeper from 23 yards. The striker has eight seconds to enter the striking circle and score. He is allowed to flick, push, drive or dribble past the custodian, who can come off the goalline to try and deny him a goal.
Like the penalty-strokes tie-breaker, if the deadlock persists after the five mandatory attempts by each team, the shoot-out will go into sudden-death.

Following the successful trials, the FIH has adopted this rule for all classification fixtures.
See this briefing which has more detail.


Is the set of functions from $X$ to $\Bbb C$ with sup norm Banach?

Question: Let $X$ be a nonempty set.
Define $F(X)= \{f:X\longrightarrow \Bbb C , f\text{ is a function}\}$ and $\|f\|=\sup|f|$. Then $(F(X),\|.\|)$ is a Banach space? If not why?
Comment: It's not even a normed space. Maybe you imply that $F$ consists of $f$ such that $||f|| < \infty$?
Comment: It is true if $X$ is finite. However, if $X$ is not finite, it will not be a Banach space (not even a normed space), see the hint of Robert Israel.
Answer: Hint: What if $f$ is unbounded?
Answer: As stated, $\lVert f\rVert$ could be infinite, so it's not even a norm. What is true is that if $V$ is a Banach space (either real or complex), and $X$ a non-empty set, then the
set of bounded functions
\begin{align}
B(X,V):= \{f:X\to V| \, \, \text{$f$ a function with $\lVert f\rVert_{\infty}:=\sup_{x\in X}\lVert f(x)\rVert_V < \infty$}\}
\end{align}
is a Banach space with the norm $\lVert \cdot\rVert_{\infty}$. In particular you can take $V=\Bbb{C}$ to get a complex Banach space $B(X,\Bbb{C})$.


Funções no HEREDOC PHP

Question: Eu estou tentando faz um tempo mas não consigo obter o resultado esperado, segue o exemplo:
<?php
$titulo = "Título";
$foo = "foo";
function foo(){
    $i = 1;
    while($i <= 10){
        echo $i++;
    }
}
echo <<<EOT

{$titulo}

Um texto qualquer

Chamada da função foo() {$foo()}

EOT;
?>

Bom no exemplo acima, eu tenho a função foo() com o retorno de um loop, até aí tudo bem, mas quando eu chamo a função no HEREDOC, o resultado retorna acima da string, ele não retorna onde a função foi chamada, ele retorna no início da string, existe um meio de eu resolver esse problema com o HEREDOC?
Answer: O echo não funciona como return, quando uma string está sendo processada primeiro todos valores e funções são processados, portanto foo() será executado antes da string gerada em <<<EOT EOT; exisitr.
Quero dizer, no momento que isso é executado {$foo()} o echo com HEREDOC ainda "não existe", porque é processado tudo antes para formar a string ou valor qualquer.
O mesmo vale para operações aritméticas, como:
echo foo() * bar() - baz();

O calculo é feito e só depois devolvido ao echo, para resolver você deve usar return, assim:
<?php
$titulo = "Título";
$foo = "foo";

function foo(){
    $output = '';

    $i = 1;
    while($i <= 10){
        $output .= $i++;
    }

    return $output;
}
echo <<<EOT

{$titulo}

Um texto qualquer

Chamada da função foo() {$foo()}

EOT;

Faça o teste online: https://repl.it/@inphinit/outpur-while-for-in-return#main.php

Funções no HEREDOC PHP


Swift deleting file from folder in documents directory

Question: I appreciate some assistance. I created a folder inside my documents directory named "MyPhotos". I added three image files to the folder. No issues.
Next I'm attempting to construct some code that will delete the files when needed but can't get it right. I can append the MyPhotos folder to the search path but can't subsequently append the file name to the path after multiple tries. tempPhotoTitle is a variable. Thank you for helping.
let fileManager = FileManager.default

       let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory,.userDomainMask,true)[0] as NSString

        let destinationPath = documentsPath.appendingPathComponent("MyPhotos")

        let finalPath = destinationPath.appending(tempPhotoTitle)

        do {
            try fileManager.removeItem(atPath: finalPath)
        }
        catch {
            print(error)
        }

Answer: The issue there is that you are working with strings (paths) and not adding the slash. I recommend always working with URLs this way you dont need to worry about adding the slash to your path.
do {
    let tempPhotoTitle = "filename.jpg"
    let documents = try FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
    let photos = documents.appendingPathComponent("MyPhotos")
    let fileURL = photos.appendingPathComponent(tempPhotoTitle)
    try FileManager.default.removeItem(at: fileURL)
} catch {
    print(error)
}

Answer: Leo Dabus's answer of working with URLs is the better one. However, it's worth mentioning that when working with Strings, if you bridge to NSString again, appendingPathComponent is available:
let finalPath = (destinationPath as NSString).appendingPathComponent(tempPhotoTitle)


Prove that f is differentiable

Question: Prove that if $f$ satisfies $|f(x,y)| \leq (x^2 + y^2)$ then $f$ is differentiable at $(0,0)$.
I understand how to prove this: one can deduce that $f(0,0)=0$, and then we can assume that $L_{(0,0)} (x,y)=0$, then prove that $\lim_{(x,y) \to (0,0)} \frac{R_{1,(0,0)}(x,y)}{\sqrt{x^2+y^2}} =0$.
However, how do we deduce that $f_x(0,0)$ and $f_y(0,0)$ both equal zero? Sorry if this seems like a silly question.
Answer: A couple of conceptual points first:
We can't assume that the derivative at the origin is the zero map, as you imply. Rather if you can show the derivative $L_{(0,0)}$ is the zero map, then you have calculated the derivative. It is certainly true however that $f(0,0) = 0$, as $|f(0,0)| \leq 0^2 + 0^2$.
Also, having shown the derivative is the zero map, it follows immediately that the partial derivatives at the origin are also zero, because if the derivative exists at a point, then the partial derivatives are equal to the entries of the matrix that defines the derivative as a linear map.

So to show that $L_{(0,0)} = \bf 0$, by the definition of the derivative, you need to show that
$$\lim_{(x,y)\to(0,0)} \frac{\left|\,f(x,y) - f(0,0) - L_{(0,0)}((x,y)-(0,0))\right|}{||(x,y) - (0,0)||} = 0$$
As $f(0,0) = 0$ and by hypothesis $L_{(0,0)} = \bf 0$, establishing this limit is equivalent to showing
$$\lim_{(x,y)\to(0,0)} \frac{|f(x,y)|}{||(x,y)||} = 0$$
This last result is true. Can you take it from here?
Comment: Yes, I've just edited my question - I meant "... differentiable at (0,0)".
Comment: I think I have a gap in knowledge. I'm not sure what the zero map is, and I haven't seen the matrix that defines derivatives as a linear map.
Comment: The derivative of a function $\mathbb R^2 \to \mathbb R$  at a point $p$ is a linear map from $\mathbb R^2 \to \mathbb R$ considered as vector spaces. If the derivative of a function $f : \mathbb R^2 \to \mathbb R$ exists at some point $p$, write it as $L_p$. Then in the standard basis, $L_p = (f_x \ f_y)$ by which I mean applying $L_p$ to a vector $v = (a,b) \in \mathbb R^2, L_p(v) = af_x + bf_y$. In other words, the derivative gives the partial derivatives. In any case, the way to find the derivative here isn't to find the partial derivatives, but to show $L$
Comment: ...has the property I gave above. That's the definition of the derivative. If $L_{(0,0)}$ is the zero map, then $L_{(0,0)}(x,y) = \bf 0$ for all points $(x,y)$. That's why in the second limit that term disappears.
Comment: But derivatives at $(0,0)$ can be other than $0$. I think I'm misunderstanding something.
Comment: In general, yes, the derivative could be any linear function $\mathbb R^2 \to \mathbb R$. But here the derivative is zero.
Answer: Hint: (based on one of the answers below):
 $0\leq \dfrac{|f(x,y)|}{||(x,y)||} \leq \sqrt{x^2+y^2}$
Comment: Yes, but how do we deduce from this that $f_x(0,0) = 0$ and $f_y(0,0) = 0$?

Prove that f is differentiable


Is there a way to address multiple apps on nginx without DNS?

Question: I bought a dedicated virtual server on hetzner so now I got an IP address for it. I'm a rookie in server and DNS stuff so I'm sure I got some fundamental misunderstandings in domain.
For the moment I've got one rails-unicorn app running on the server. I have not bought any Domain name yet therefore it can be accessed just by my IP.
I want to deploy one more app to this server and I don't understand how can it be done (or how to distinguish requests for nginx so it can redirect to requested app). I suppose there two ways: redirect to different upstreams based on ports: e.g. user hit in browser 220.127.116.11:3000 and get one app and for 18.104.22.168:80 get another.
And the second way to "subdomain" my IP: user hit 220.127.116.11/app1 or 126.96.36.199/app2 and get diff apps
Am I wrong about that alternatives? If I am, what is the right answer? thank you guys!
Answer: If this is just for your own testing, for the mean time until you buy the domain, i would suggest editing the hosts file (of your own pc/laptop) and adding the domain names, tricking you own pc (only) to think that this domain actually exists
the path in windows is C:\windows\system32\drivers\etc\hosts
in linux it's /etc/hosts
and just add a record like
220.127.116.11 mydomain.com

The other method of 184.108.40.206/app1 would work too, but it's not really a subdomain, it's a subdirectory, in nginx they will all be contained inside 1 single server { }
Also you could use a service like dyndns.org and assign a host to your server (it's a free service, you don't need to pay for the offers you'll find on the site)


Accelerando in poly-tempo

Question: The question is - does accelerando used in parts with different tempo? How to rhythmically align them after that / during that? (Without accelerando it would be enough to keep parts tempo at some fixed ratio)
For example:
<code>   S1 :  e - e - e - e - e - e - e

        [accel from 60 to 120 bpm]
   S2 :  q  -  q  -  q  -  q

         t0                t1=??
</code>
where S1,S2 - stave 1,2; e - eight note; q - quarter
How to properly calculate start time and duration time of each beat during accelerando? [It is not that important if song have only one tempo, because all beats will have same timings regardless of how we calculate accelerando]
Comment: I think the confusion comes from some odd grammar: are you asking "does accelerando GET used in poly-tempo" or are you asking HOW it is used? Or are you just asking for proper notation?
Comment: I have no idea what you're asking here.  Can you clarify?
Comment: @BenI. I'm asking, does accelerando used in poly-tempo music?
Comment: @PatMuchmore At first "does accelerando GET used in poly-tempo",  at second "HOW it is used". Also I wonder - is it possible to somehow synchronize staves in different tempo AFTER accelerando in only one of them?
Answer: Yes, composers who write poly-tempo music may well ask for independent tempo changes, sudden or gradual.  Yes, in live performance, it will be impossible to conduct, and the players will find it tricky to get everything ending at the same time!   But they'll manage, somehow.  Sometimes, in my experience, by cheating.  But as, in this sort of music, the concept tends to be more important than what it actually SOUNDS like, it probably doesn't matter.
Comment: I'm reading Elaine Gould's "Behind Bars" now. She writing about switching from score's tempo to part's own tempo and back (parts have pieces in their own tempo, but then they sync back to common tempo) [example around p.614 if you have one]. Part's tempos in her examples are at ratios with score tempo. The question is - is it possible somehow to back  to common score tempo (synchronize) after part's accelerando? May be there is some special symbol, which marks - wait/sustain for beat at other stave (like dotted bar between staves, at sync point)?
Comment: Just stop doing whatever notation you had contrived to show the un-synchronised section and go back to normal notation with shared barlines.

Accelerando in poly-tempo


PHP Select statement need quick correction

Question: My echo statement at the end is certainly wrong, I've put it in just to show what I am trying to do, I'd simply like to to call these three variables as set previously. What would be the right way to do that?
$table_id = 'mynewtable';
$query = "SELECT id,name,price FROM $table_id";
$result_set= mysql_query($query);

$id = "SELECT id FROM $table_id";
$name = "SELECT name FROM $table_id";
$price = "SELECT price FROM $table_id";

if ($result_set){

$record= mysql_fetch_row($result_set);
$idrecord= mysql_fetch_row($id);
$namerecord= mysql_fetch_row($name);
$pricerecord= mysql_fetch_row($price);

        foreach ( $record as $value){
        echo "
 $idrecord $namerecord $pricerecord
	";
    }
}

Answer: There's no point to fetch each of the elements separately. Use mysql_fetch_assoc to get an array with the columns specified in SELECT statement, as keys. this way you can easily get the echo you're after, without querying the database unnecessarily
$table_id   = 'mynewtable';
$query      = "SELECT id,name,price FROM $table_id";
$result_set = mysql_query($query);

if($result_set)
{
    while ($row = mysql_fetch_assoc($result_set)) {
        echo "
" .$row["id"]
        . " ". $row["name"]
        . " " .$row["price"] . "
	";
    }

}

Comment: Thanks this works great. Much appreciated. Many of the other guys also gave correct and viable information. Thanks everyone.
Answer: Your $resultset is coming only from the first query ($query = "SELECT id,name,price FROM $table_id";) and not the others?
This section:
$id = "SELECT id FROM $table_id";
$name = "SELECT name FROM $table_id";
$price = "SELECT price FROM $table_id";

is actually useless, as it is just assigning strings to $id, $name and $price.
Did you mean?:
$result_set= mysql_query($query);
while ($row = mysql_fetch_assoc($result_set))
{
    echo "
 ".$row['id']." ".$row['name']." ".$row['price']."
	";
}

Comment: @Wiseguy Very well spotted. Corrected the `foreach` to use the `$result_set` as you correctly eagle-eyed :)
Comment: @Wiseguy Sorry, I normally copy and paste my PDO functions. It has been eons since I used the `mysql_*` functions :(
Comment: @wiseguy C'mon, throw me a bone here, it's midnight, I have had a few glasses of red and my brain can't flick back to procedural PHP and mysql_ functions.
Comment: @Wiseguy Thanks for putting me out of my misery there good sir!
Comment: Quite welcome. As the problems are now fixed, I've removed my no-longer-applicable comments.
Comment: @Wiseguy Appreciated, and +1'ed elsewhere on a worthy answer.
Answer: $table_id = 'mynewtable';
$query = "SELECT id,name,price FROM $table_id";
$result_set= mysql_query($query);

if (mysql_num_rows() > 0){

    while($row = mysql_fetch_array($result_set)) {
        echo $row['id'] .", ". $row['name'] .", ". $row['price'];
    }

}

Please start using mysqli_* instead of mysql_*
Answer: why not
$table_id = 'mynewtable';
$query = "SELECT id, name, price FROM $table_id";
$result_set= mysql_query($query);

if ($result_set){
        while( $row = mysql_fetch_array(result_set)){ ?>

 <?php echo $row['id'] . ' ' $row['name'] . ' ' . $row['price']; ?>

<?php
    } // end of while
} // end of if

Answer: You do not need to have three separate selects for id, name and price. Just use:
if ($result_set) {
    $row = $result_set -> fetch_assoc();
    $id = $row['id'];
    $name = $row['name'];
    $price = $row['price'];
}

Then you can input it into your table or do whatever you would like with the info.
The fetch_assoc() will only work if you are using MySQLi. mysql_fetch_assoc is deprecated and you should switch to either PDO or MySQLi
Answer: <?php
$query = "SELECT id,name,price FROM mynewtable";
$result_set = mysql_query($query);

if ($result_set!==false){
    while( $row = mysql_fetch_assoc( $result_set ) ) {
     echo '' $row['id'] . ' ' . $row['name'] . ' ' . $row['price'] . '	';
    }
}
else {
    echo "Something went wrong with the query:";
    echo mysql_error( );
}

That seems more like it should work :)
EDIT: by the way, use of mysql_* is highly discouraged, as they will disappear in upcoming versions of PHP. Start using PDO or MySQLi instead.


Fade effect is removed from dynamically added tabs

Question: I want to use Bootstrap's togglable tabs (http://getbootstrap.com/javascript/#tabs) with the fade effect. Which works just fine when I create a static HTML file.
However, when dynamically adding tabs via jQuery, the fade class is removed from the respective DOM nodes and the tab-panes no longer fade in and out when switching between tabs. I can re-add the fade class to the tab-panes using the browser's developer tools ('elements' in Chrome) to make it work as expected again. So it's really not clear to me why the fade class gets removed at all. :(
What do I have to do so that the fade class is not removed when inserting the tab-pane?
Following fiddle demonstrates the problem: http://jsfiddle.net/zabbarob/44VDD/
The code I use in the fiddle is

and
function appendTab(title) {
    $('#tabs > .nav').append(
        '
'
        + title + '
'
    );
    $('#tabs > .tab-content').append(
        '
'
        + 'tab pane of ' + title + '
'
    );
}
appendTab('First');
appendTab('Second');

Answer: Your resulting html markup is missing several things to work.
1.) right now you are giving every div element the fade in class, but just the active one needs it, every other needs just the fadeclass.
2.) you are not declaring an active element in the navigation list
3.) you are not marking the active element as active in the content area
working example
In my example I choose the first element to be the one marked active via a counter. Modify your function (call), so that it suits your needs. The first element that calls your function gets marked as active now.
Comment: great! that not only solved my problem :-) but also made me understand what i did wrong! thanks a lot!


What events should I handle in express response (stream) object to handle when the response finishes?

Question: I'm trying to automatically log when a request finishes.
I have something like this:
function (req, res, next) {
    var startTime = clock.now();
    res.on('end'. function() {
        logger.trace("END ...", req.path, res.statusCode, clock.now() - startTime, ...);
    });
    res.on('error'. function() {
        logger.trace("END ...", req.path, clock.now() - startTime, ...);
    });
    nest();
}

Does doing that cover all the cases? (e.g. when a request get's interrupted)
Will I be called at most once for every request?

If any of the answers is no, please include how to do it.
Comment: Is this package not good enough for your use case? https://github.com/expressjs/response-time
Comment: It's not. It just set's a response header with the time. I want to be able to log when a request ends. __That includes when it's interrupted by the client__. The module you mentioned uses `on-headers`, which decorated the `res.writeHead` function. The onHeaders function should not get called on interrupted requests. @1461269 @arjabbar
Answer: Try setting up finish event according to the documentation:
Here is a sample implementation:
app.use(function(req, res, next) {
    res.on('finish', function() {
        console.log('the response has been sent', res.statusCode);
    });
    next();
});


Inference and predictive models

Question: Some people in my line of work are interested in the coefficients that results from developing predictive regression models(prm).
I'm somewhat reluctant to use these coefficients to explain an effect a predictor may or may not have on the response. What is sometimes useful is the variable importance, although this seems to be of less interest.
I feel like the difference between predictive and causal analysis is not clear cut for some of the people I report to with my models.
My question is:

is it legit to use coefficients from a prm for inference?

The prm's I usually use at work are the following:

Elastic Net/LASSO - Gaussian and logit
Boosted GAMLSS

A lot is telling me that the coefficient are too unreliable and shouldn't be considered, especially for large models.
And if there is a lot of interest for causal effects, then there  should be a priority to make additional causal models.
PS: my department is conservative and old fashion with a lot of old people(no offense) and many enjoy working with SAS(offense)
Comment: One note of distinction is that in predictive/prognostic settings, the predictors need not be causally related, only correlated. Causation should therefore be viewed in light of this and any underlying theory for your context. As a general rule, the clinicians I work with are usually not interested in the estimated effect size of any one coefficient, and if so, then a prospective study should be designed to collect this information.
Comment: Slide 17:  http://statweb.stanford.edu/~tibs/sta305files/Rudyregularization.pdf
Answer: I see two somewhat unrelated questions in this question.

Is it possible to draw reliable inference about individual coefficients in predictive models, especially if we have a large number of predictors and use some form of variable selection and/or regularization?
Can the coefficients in a predictive model be interpreted causally?

My short answer to the first question is yes, that's possible, but it's not straightforward to do correctly, and it's the subject of intense current research.
To the second question I find that the safe answer is no, the coefficients in a predictive model don't generally have a causal interpretation. This point should be made very clear to collaborators/clients, who may not have a strong training in causal models.
Inference
Emmanuel Candes gave the 2017 Wald Lectures at the Joint Statistical Meetings entitled What's happening in Selective Inference?, which offers a great starting point for learning what the challenges are, and what the status is.
A main challenge, especially when the number of predictors is large, is how to compute and report uncertainty correctly, when the model/predictors have been selected by the data.
Candes explains at length his contributions (mostly with Rina Barber) on the knockoff filter, which is a very nice idea for controlling the false discovery rate of selected predictors.
Another question is how to reliably compute confidence intervals for the coefficients. Candes touches upon this in his talk, but see the paper
Exact post-selection inference, with application to the lasso by Lee at al. for more details, and see also the paper Valid post-selection inference by Berk et al.
The R package Selective Inference implements these ideas. Another relevant R package to consider is hdi, see also the paper High-Dimensional Inference: Confidence Intervals, p-Values and R-Software hdi by Dezeure et al.
Note that there is a non-trivial discussion in selective inference about what the target parameter actually is! Is it the (theoretical) coefficient in the model with the selected predictors, or is it the coefficient in the model with all predictors included? Read the paper by Berk et al. for some discussion on this difference.
I would typically investigate uncertainty of reported coefficients and selected predictors via simulations/bootstrapping (remembering to include the full variable selection procedure within the bootstrapping), but it may actually require some work to make sure that e.g. bootstrapped confidence intervals are appropriate, see Bootstrapping Lasso Estimators by Chatterjee and Lahiri.
I should say that the challenges discussed above are fundamentally frequentistic of nature. See e.g. Gelman's post Bayesian inference completely solves the multiple comparisons problem for a more Bayesian perspective.
Causality
Regression models have been used in econometrics and epidemiology, to mention some areas, to estimate causal effects from observational data. This, I find, has historically not always been done with a crystal clear discussion of what actually constitutes a causal effect. Causality has been thought justified by appealing to "no unmeasured confounders" and other similar properties of the setup, in an attempt to argue that the regressors included are precisely those that are needed to justify a causal interpretation of estimated coefficients. But often without a clear conceptual or mathematical framework for defining causality and causal effects.
The history of how Simpson's paradox has been treated in the statistical literature illustrates the problems as described by Pearl in his paper   Understanding Simpson's Paradox.
What is crystal clear to me is that causality is a concept beyond a probabilistic model, and this can be formalized using frameworks such as counterfactuals, structural equation models or graphical models (DAGs). These are not unrelated frameworks, but offer slightly different concepts and languages to introduce the fundamental parameters of interest: the causal effects.
In some situations it might be possible to interpret coefficients from a predictive (regression) model as causal effects, but I would say it's unlikely to be the case if the model is optimized for purely predictive performance from a vast number of potential predictors using observational data.
The forthcoming Causal Inference Book by Hernan and Robins is a great place to learn about the causal models. Part II of the book deals specifically with the use of models for causal inference.
Causal effects can sometimes be estimated using predictive models, but it may require some ingenuity. Inverse probability weighting relies on a predictive model of probability weights, as Hernan and Robins describe. The recent paper Causal inference by using invariant prediction: identification and confidence intervals by
Peters, Bühlmann and Meinshausen relies on the causal model being invariant under different (unspecified) interventions, whereas non-causal associations are not.
In any case, I would strongly advice against careless interpretations of (regression) coefficients as causal effects. If causal effects are of interest, this should be taken seriously, and appropriate methods should be employed to estimate the effects of interest.
Answer: Frank Harrell, in his 'Regression Modeling Strategies' (2015) offers a range of possible modeling strategies (section 4.12, if you are able to obtain a copy), some of which may be considered facetious ('develop a black box model that performs poorly and is difficult to interpret'), but he then goes on to develop a strategy for regression models which provide accurate predictions, and then discusses how this model may be improved to allow accurate effect estimation, commenting 'estimation of effects for these models must involve accurate prediction of overall response values'. Effectively it seems doubtful that you can have an accurate estimate of the value of a predictor's effect size if you don't have a model that accurately predicts your target.
Harrell points out some useful considerations needed to ensure that a model providing good accuracy can provide good estimates of predictor effects. For example, one is strict attention to interaction effects. Another is the role of imputation for missing data, especially if a variable whose effect size is a high priority has many missing values e.g. it might be sensible to impute the missing values if model accuracy is the only goal, but not sensible if estimating that particular effect is the goal.
At the same time, the above implies that it is possible to achieve a level of accuracy with respect to the target without having achieved accurate estimates of each predictor's effect. You also mention causal analysis, and one of the commenters rightly observes that you can achieve accurate estimates of correlations without accurately understanding causal relationships.
Overall, it begins to look like a hierarchy, where a strong predictive model forms the foundation for accurate estimation of predictor effects, and accurate predictor estimates of predictor effects could then be the beginning of an analysis of causation. Then the answer to your main question is 'yes, it is legitimate to use the coefficients from a predictive model for inference, under the condition that the model has been analysed carefully to ensure the legitimacy of the effects estimates'.
Comment: I'm still not completely convinced. One reason is that you have to trade bias for less variance when you optimize for the best possible predictions, hence you are not getting the BUE.  Also there are issues such as multicollinearity and reverse causality that may be problematic for a causal analysis but does not affect the predictions. These kinds of issues are likely to occur in large models and not unlikely to occur in small models. The coefficients in a predictive model may thus be very biased and in worst cases misleading.
Comment: My contention is that a predictive model that achieves a decent amount of accuracy is a necessary but not sufficient foundation for a model that is useful for inference. Similarly, a model that is useful for inference is a necessary but insufficient condition for a causal analysis. Alternatively, I would put it as 'you must use a good predictive model to analyse for inference, but not every good predictive model will be suitable'. Start with your existing prm and analyse for the problems you mention, and alter it/ reject it if necessary.
Comment: Predictive models can be helpful to test out results from causal analyses, but I'm not sure if I'm following why predictive models are a necessary foundation for inference. If I was concerned with effects then I would probably make a very different model then if I was concerned predictions. Using predictive optimization methods that produce variable importance is however one way to gain some causal insight, although I wouldn't use it to verify theories in research per se. Could you refer me to a chapter I Harrels' book? It seems like it's a very discussable topic :)
Comment: @Nesvold I've always wondered this, but have never got a solid answer: "One reason is that you have to trade bias for less variance when you optimize for the best possible predictions, hence you are not getting the BUE".  Why is unbiasedness so important for this type of applications (causal analysis)?  Wouldn't a high variance estimate of an effect, causal or not, be just as bad, maybe worse?
Comment: @MatthewDrury Thats a good point, especially if you are more Bayesian inclined. However asymptotic theory supports the fact that your BUE will in fact converge to the population parameter as long as the variation exists. Still, I think the main issue is very much up for discussion. I'm interested in theory that backs up the use of coefficients in predictive models, even though I'm more inclined to dismiss them.

Inference and predictive models


Cron error: LogicException : Render context is empty

Question: In a custom module (sel), I have this code:
<code>function sel_cron()
{
  $accountSwitcher = Drupal::service('account_switcher');
  $account = \Drupal\user\Entity\User::load(1);
  $accountSwitcher->switchTo($account);

  $query = \Drupal::entityQuery('service_category');
  $dLastExtractionDate = strftime("%Y-%m-%d", strtotime("- 1 week", strtotime(\Drupal::state()->get('sel.NextEmailForNewServices'))));
  $view = views_embed_view('sel_services', 'embed_2', $dLastExtractionDate);
  $view = \Drupal::service('renderer')->render($view);   <--------------------- problem here

  $accountSwitcher->switchBack();
}
</code>
The expected result of the view is a table but when the result is empty (because of the value of the contextual filter), an unfiltered text ("Nothing to display today. Too bad!") should be displayed instead.
But in this case, I get this error logged:

LogicException: Render context is empty, because render() was called
  outside of a renderRoot() or renderPlain() call. Use
  renderPlain()/renderRoot() or #lazy_builder/#pre_render instead. in
  Drupal\Core\Render\Renderer->doRender() (line 243 of
  /Users/efalzon/Sites/JdP8/web/core/lib/Drupal/Core/Render/Renderer.php).

How to fix that?
Comment: Oh ok, in that case you want to use `renderPlain`, not `render`. See https://drupal.stackexchange.com/questions/292171/what-is-the-difference-between-renderplain-and-renderroot
Comment: That's a cron job though - where are you expecting it to render?
Comment: The result of the view becomes the body of an email sent with `\Drupal::service('plugin.manager.mail')->mail(some params);`
Answer: <code>$view = \Drupal::service('renderer')->renderPlain($view);
</code>
instead of
<code>$view = \Drupal::service('renderer')->render($view);
</code>
was the solution!
Thanks to @Clive


How to configure xymon hobbit with nginx instead of apache

Question: i installed xymon on debian 7 with an apt-get install xymon
now i can't find how to configure nginx.conf to make it work
i tried this but not working when i try to access http://debian.local/xymon, error 404:
# /etc/nginx/sites-available/debian.local.conf
# HTTP server
server {
    listen   80; ## listen for ipv4; this line is default and implied
    #listen   [::]:80 default_server ipv6only=on; ## listen for ipv6

    # Make site accessible from http://localhost/
    server_name debian.local localhost ;
    # On redirige toutes les requêtes vers HTTPS
    #rewrite ^ https://$server_name$request_uri? permanent;

location ^~ /glpi {
  root /home/cedric/web;
  index index.php;

        location ~ /glpi(/.*\.php) {
        include /etc/nginx/fastcgi_params;
        fastcgi_pass    unix:/var/run/php5-fpm.sock;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_index index.php;
        }
}

location ^~ /xymon/ {
                root /usr/lib/hobbit/server/www ;
                index index.html ;
        }

location /cgi-bin/ {
                root /usr/lib/hobbit/cgi-bin/;
}

location /cgi-secure/ {

                alias /usr/lib/hobbit/cgi-secure/ ;
}

}
server {
    listen 443 ssl;
    server_name debian.local localhost ;

    root html;
    index index.html index.htm;

    # Use a self-signed certificate to ensure
    # secure connexion to phpmyadmin
    ssl_certificate debian.local.crt;
    ssl_certificate_key debian.local.key;

    ssl_session_timeout 5m;

    # Access only latest browsers
    ssl_protocols TLSv1.2;
    ssl_ciphers ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv3:+EXP;
    ssl_prefer_server_ciphers on;

    location / {
        try_files $uri $uri/ =404;
    }

location /zabbix {
        if ($scheme ~ ^http:){
            rewrite ^(.*)$  https://$host$1 permanent;
        }
        alias                   /usr/share/zabbix;
        index                   index.php;
        error_page              403 404 502 503 504  /zabbix/index.php;

        location ~ \.php$ {
                if (!-f $request_filename) { return 404; }
                expires                 epoch;
                include                 /etc/nginx/fastcgi_params;
                fastcgi_index   index.php;
                fastcgi_pass    unix:/var/run/php5-fpm.sock;
    }

        location ~ \.(jpg|jpeg|gif|png|ico)$ {
                access_log      off;
                expires         33d;
        }

}

 location /phpmyadmin {
           root /usr/share/;
           index index.php index.html index.htm;

           location ~ ^/phpmyadmin/(.+\.php)$ {
                try_files $uri =404;
                root /usr/share/;
                fastcgi_pass unix:/var/run/php5-fpm.sock;
                fastcgi_index index.php;
                fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script;
                include /etc/nginx/fastcgi_params;
           }
           location ~* ^/phpmyadmin/(.+\.(jpg|jpeg|gif|css|png|js|ico|html|xt))$ {
                   root /usr/share/;
           }
    }
    location /phpMyAdmin {
           rewrite ^/* /phpmyadmin last;
    }

    ## Xcache admin pages
    location /xcache {
        alias /usr/share/xcache/;
        try_files $uri $uri/ /index.php;

        location ~ ^/xcache/(.+\.php)$ {
            fastcgi_pass unix:/var/run/php5-fpm.sock;
            fastcgi_param SCRIPT_FILENAME $request_filename;
            include fastcgi_params;
        }
    }
}

some help please.
Thank you
Answer: made it work with this nginx config file:
    location ^~ /hobbit {
                alias /usr/lib/hobbit/server/www/ ;
                index index.html ;
        }

location /cgi-bin/ {
                alias /usr/lib/hobbit/cgi-bin/;
}

location /cgi-secure/ {

                alias /usr/lib/hobbit/cgi-secure/ ;
}


What WYSIWYG editor allows me to select styles from a dropdown 'out the box'?

Question: I have installed the WYSIWYG module in Drupal 7 and have tried it with CKEditor and TinyMCE. I want users to pick styles from the template css when editing, but here appears to be a bug with the WYSIWYG module (drupal.org/node/1069356) that prevents the style dropdown from working. CKeditor seems to have a similar issue (drupal.org/node/746524), although there does seem to be a patch for this. I am not confident enough to deply the patch though.
Is there a WYSIWYG editor that is able to do this successfully out the box?
Answer: CK Editor is the best in my opinion, and it should provide this option out of the box - it is a shame about the bug. In Drupal 6 I use drop down styles for all the line stuff and templates for including more complex block level elements such as jQuery show/hides. I really cant recommend enough how well it works. I suggest that you try the patch before ditching ck editor and seeking an alternative...
Drupal 7 is still pretty new so you will encounter small issues such as you describe, if you are dealing with bleeding edge this is something you have got to expect... otherwise use Drupal 6


In a right triangle, the perimeter is equal to 30. How many integer values can the hypotenuse take?

Question: (Answer:2)
I did:
$a+b+h = 30\rightarrow a+b = h-30\\
a^2+b^2 = h^2 \rightarrow h = \sqrt{a^2+b^2}\\
a-b<h<a+b \rightarrow a-b < h < \sqrt{a^2+b^2}-30...\\
\text{I didn't find other relationships...}
 $
Comment: @EthanBolker from the question I deduce that only the hypotenuse has to be integral.
Comment: There are not many small integer right triangles. They start with $3-4-5$ which has perimeter $12$. You can list them all. You don't need any more algebra than $a + b < 30$.
Comment: With a perimeter of 30, $h\in \{11,12,13,14\}.$ Solve for each of them $a^2+(30-a-h)^2=h^2.$
Comment: I am not sure how the answer is $2$. Only $13$ works as hypotenuse. I do not see any other.
Answer: Lower bound: use AM-QM inequality:
$$\frac{h^2}{2}=\frac{a^2+b^2}{2}\ge\left(\frac{a+b}{2}\right)^2=\frac{(30-h)^2}{4}$$
Solving the quadratic inequality for positive $h$ will give to you $h\ge 30(\sqrt{2}-1)= 12.42\ldots$ (lowest $h$ is achieved when the triangle is isosceles)
Upper bound: use $a+b>h$
$30=a+b+h>h+h=2h$
Therefore $h<15$
So the integral values of $h$ are $13$ and $14$
You can verify by solving $a+b=30-h$ and $a^2+b^2=h^2$
For $h=13$ you will get the well-known Pythagorean triplet $5,12,13$
For $h=14$ you will get $8-\sqrt{34},8+\sqrt{34},14$
Comment: Why downvote the answer?
Answer: The sides of a general triangle are the roots of the cubic equation
\begin{align}
 x^3-2\rho x^2+(\rho^2+r^2+4rR)x-4\rho r R&=0
 \tag{1}\label{1}
\end{align}
where $\rho,r$ and $R$ are the semiperimeter, the inradius and
the circumradius, respectively, of the corresponding triangle.
We are given that $\rho=\tfrac{30}2=15$ and also,
since $c$ is the hypotenuse, $c=2R$. So, \eqref{1} transforms to
\begin{align}
c(r+c-15)^2&=0
\tag{2}\label{2}
\\
\text{or just}\quad
c&=15-r
\tag{3}\label{3}
,
\end{align}
so the integer values of $c$ are defined by integer values of $r$.
Also, since for any valid non-degenerate non-equilateral triangle
\begin{align}
r&\in(0,\tfrac R2)
\tag{4}\label{4}
,
\end{align}
we must have
\begin{align}
15-r&> 4r
\tag{5}\label{5}
\\
\text{or }\quad
r&<3
\tag{6}\label{6}
\end{align}
and we have only two options left:
\begin{align}
r_1&=1
,\quad
c_1=14
\tag{7}\label{7}
\\
\text{and }\quad
r_2&=2
,\quad
c_2=13
\tag{8}\label{8}
.
\end{align}
So, the answer is indeed, $2$, we don't even have to find the other side lengths.
However, it's trivial, since by factoring \eqref{1} they can be found
as a roots of quadratic
\begin{align}
x^2-(30-c) x+450-30c&=0
\tag{9}\label{9}
,
\end{align}
hence for $c_1=14$ two other sides are
$8\pm\sqrt{34}$
and for
$c_2=13$ two other sides are
$5$ and $12$.

Edit
Using geometric approach, when $c=|AB|$ is fixed, the third point $C$
must be located at the intersection of the circle centered at
$O$, the midpoint of $AB$, and the ellipse focused at $A,B$
for which $|AC|+|BC|=30-|AB|$. These are only two possible solutions, that corresponds to $c_1$ and $c_2$.
\begin{align}
\begin{array}{ccc}
R            & \text{major semi-axis} & \text{minor semi-axis}
\\ \hline
7 & 8 & \sqrt{15}
\\
6.5 & 8.5 & \sqrt{30}
\\ \hline
\end{array}
\end{align}
Answer: The sides of a right triangle with integer sides are of the form
$a(m^2-n^2), 2amn, a(m^2+n^2)$
for integer $a, m, n$
with $m > n$.
We therefore want
$p
=2a(m^2+mn)
=2am(m+n)$
where $p=30$ here,
or
$p/2
=am(m+n)$.
For p=30,
possible values for $a$ are
1, 3, 5, 15.
For these,
$m(m+n)
=15, 5, 3, 1
$.
If
$m(m+n)=15$
with $m > n$,
$m=3, n=2,$
sides $=5, 12, 13$.
If
$m(m+n)=5, 3, 1$,
no solutions.
Here are bounds on
$m$ and $n$
with $m > n$
and
$m(m+n)=r$
in terms of $r$.
If
$m(m+n)=r$,
$n
=\dfrac{r}{m}-m
$
so,
since $m > n$,
$\dfrac{r}{m}-m
\lt m$
or
$r < 2m^2$
or
$m > \sqrt{r/2}
$
and $m | r$.
Also,
if
$m(m+n)=r$,
$m^2+mn-r=0$,
$m
=\dfrac{-n+\sqrt{n^2+4r}}{2}
$.
Since $m > n$,
$-n+\sqrt{n^2+4r}
\gt 2n$
or
$n^2+4r > 4n^2
$
or
$n < \sqrt{4r/3}
$.
Similarly,
$r \ge m(m+1)$
or
$4r+1 \ge 4m(m+1)+1
=(2m+1)^2
$
so
$m \le \sqrt{4r+1}/2
=\sqrt{r+\frac14}
\lt \sqrt{r}+\frac12
$.
Answer: There are indeed not enough restrictions. We can write $\cos(\theta) = \frac a h$, $\sin(\theta) = \frac b h$, hence $h\cos(\theta)+h\sin(\theta)+h=30$, or $\cos(\theta)+\sin(\theta)+1 = \frac{30}h$.
$\cos(\theta)+\sin(\theta)$ is equal to $\sqrt 2\sin(\theta +\frac{\pi}4)$, so we get $\sqrt 2 \sin(\theta +\frac{\pi}4) = \frac2 {\sqrt 2}(\frac{30}h-1)$ or $\theta = \sin^{-1}(\frac2 {\sqrt 2}(\frac{30}h-1))-\frac{pi}4$, which has solutions for more than two values of $h$.
If we have the requirement that all sides are positive integers, there's only one solution.
All Pythogorean triples are of the form $2kmn$, $k(m^2-n^2)$, $k(m^2+n^2)$ for some positive integers $k,n,m$. $k$ has to be a factor of $30$, so that gives $1,2,3,5,6,10,30$. The smallest Pythogorean triplet is $3,4,5$, which adds up to $12$, for $k=2.5$, which doesn't work because $k$ needs to be an integer. All larger $k$ are prohibited (a larger $k$ would means that the reduced triples is smaller, but $3,4,5$ is smallest). The only smaller $k$ is $1$, so we now know that any solution must be of the form $2mn$, $m^2-n^2$, $m^2+n^2$. Adding those together, we get $2m^2+2mn=2m(m+n)$, thus $m(m+n)=15$. The only factorizations of $15$ are $15\cdot1$ and $5\cdot3$. The factorization $15\cdot1$ would require $m=1$, which doesn't work ($m>n$, so if $m=1$, $n=0$, but $m$ and $n$ both have to be positive), so that leaves $5\cdot3$. Since $m+n>m$, the $3$ must be $m$ and the $5$ is $m+n$, so $n=2$. That gives $5,12,13$.
Comment: You have a computational error there; s/b $\sqrt{2}\sin(\theta+ \pi/4)$. Also you haven't shown how many of those solutions give positive values for $a$ and $b$.


How to grep a word exactly

Question: I'd like to grep for "nitrogen" in the following character vector and want to get
back only the entry which is containing "nitrogen" and nothing of the rest (e.g. nitrogen fixation):
varnames=c("nitrogen", "dissolved organic nitrogen", "nitrogen fixation", "total dissolved nitrogen", "total nitrogen")

I tried something like this:
grepl(pattern= "![[:space:]]nitrogen![[:space:]]", varnames)

But this doesn't work.
Comment: So you just want the index/indices of the values that exactly equal "nitrogen"?  Does `which(varnames == "nitrogen")` give you what you want?
Comment: Dason: can you make your comment an answer so Sabsirro can accept?
Answer: Although Dason's answer is easier, you could do an exact match using grep via:
varnames=c("nitrogen", "dissolved organic nitrogen", "nitrogen fixation", "total dissolved nitrogen", "total nitrogen")

grep("^nitrogen$",varnames,value=TRUE)
[1] "nitrogen"

grep("^nitrogen$",varnames)
[1] 1

Comment: Danson's answer is not just easier, it is also faster.
Comment: It works, but it's slow. Unless you're constructing `regex`es dynamically, there's no much sense in doing `^someword$`.
Answer: To get the indices that are exactly equal to "nitrogen" you could use
which(varnames == "nitrogen")

Depending on what you want to do you might not even need the 'which' as varnames == "nitrogen" gives a logical vector of TRUE/FALSE.  If you just want to do something like replace all of the occurances of "nitrogen" with "oxygen" this should suffice
varnames[varnames == "nitrogen"] <- "oxygen"

Answer: Or use fixed = TRUE if you want to match actual string (regexlessly):
v <- sample(c("nitrogen", "potassium", "hidrogen"), size = 100, replace = TRUE, prob = c(.8, .1, .1))
grep("nitrogen", v, fixed = TRUE)
# [1]   3   4   5   6   7   8   9  11  12  13  14  16  19  20  21  22  23  24  25
# [20]  26  27  29  31  32  35  36  38  39  40  41  43  44  46  47  48  49  50  51
# [39]  52  53  54  56  57  60  61  62  65  66  67  69  70  71  72  73  74  75  76
# [58]  78  79  80  81  82  83  84  85  86  87  88  89  91  92  93  94  95  96  97
# [77]  98  99 100

Dunno about the speed issues, I like to test stuff and claim that approach A is faster than approach B, but in theory, at least from my experience, indexing/binary operators should be the fastest, so I vote for @Dason's approach. Also note that regexes are always slower than fixed = TRUE greping.
A little proof is attached bellow. Note that this is a lame test, and system.time should be put inside replicate to get (more) accurate differences, you should take outliers into an account, etc. But surely this one proves that you should use which! =)
(a0 <- system.time(replicate(1e5, grep("^nitrogen$", v))))
# user  system elapsed
# 5.700   0.023   5.724
(a1 <- system.time(replicate(1e5, grep("nitrogen", v, fixed = TRUE))))
# user  system elapsed
# 1.147   0.020   1.168
(a2 <- system.time(replicate(1e5, which(v == "nitrogen"))))
# user  system elapsed
# 1.013   0.020   1.033

Comment: He, tanks for that detailed answer. It is good to know about this differences.

How to grep a word exactly


Expected value of expression involving multinomial random variables and Heaviside step function of said variables

Question: Question 1
I have the following expression:
$H/S$,
where $H=\begin{cases}0,& \text{ if } rm\leq dj \\ 1, & \text{ if } rm>dj \end{cases}$ and $S=n-j$, and both $m$ and $j$ are drawn from the same multinomial distribution with number of trials $n$. The support of the multinomial distribution includes three discrete random variables: $m$, $d=S-m$, and $j$, which occur respectively with probabilities $x$, $y$, and $z=1-x-y$. I want to take the expected value of this expression. I know that $E[tu]\neq E[t]E[u]$ in general.
So my first question is, how do I compute the expected value of $H/S$, i.e., $E[H/S]$?
Question 2
In a related question, what is the expected value of $H$? Is it
$E[H]=\begin{cases}0,& \text{ if } rE[m]\leq dE[j] \\ 1, & \text{ if } rE[m]>dE[j] \end{cases}$?
Thank you, CV.
(Also, that is the most $\LaTeX$ I've written in a single document so far. Go me!)
Comment: Did you mean $H$ to be $E[H]$ in the very last occurrence of it in your post? Or did you intend something else?
Comment: @cardinal You mean when I say "...is it..." etc? If so, yes, thanks!
Comment: @cardinal BTW, I edited it.
Comment: I doubt that the standard sum (as per the definition of expected value) can be simplified into something short like $np$ for a binomial random variable. Of course, if you have numerical values for $n$ etc, then various statistical programming packages will make short work of it, but I suspect you want something short and sweet instead of $E[H/S] = \text{humonguous sum}$.
Comment: @DilipSarwate I'm happy to take the answer as a humongous sum. I am passing these expected values for $H/S$ and $H$ as part of a payoff function in an evolutionary game, which I will simulate. I am extending a game for which there is a simple(ish) solution (not short and sweet, but not a humongous sum). Only in that case, there weren't any discontinuous functions like those in $H$.
Answer: If the random variable $H = H(X,Y,Z)$ is a function of three integer-valued random variables $X, Y$, and $Z$ that take on values in $[0, n]$
and whose joint probability mass function is
$$p_{X,Y,Z}(n_1,n_2,n_3) = P\{X = n_1, Y = n_2, Z = n_3\}, ~0 \leq n_1,n_2,n_3 \leq n,$$
then
$$E[H] = \sum_{n_1=0}^n\,\sum_{n_2=0}^n\,\sum_{n_3=0}^nH(n_1,n_2,n_3)p_{X,Y,Z}(n_1,n_2,n_3).$$
It is not necessary that $H$ be expressible as a "nice" formula
such as $X+Y+Z$ in order to use the above formula.
Here,
$$p_{X,Y,Z}(n_1,n_2,n_3) =
\begin{cases}\dfrac{n!}{n_1!n_2!n_3!}x^{n_1}y^{n_2}(1-x-y)^{n_3},
& \text{if}~ n_1 + n_2 + n_3 = n,\\
\quad\\
0, & \text{otherwise},\end{cases}$$
is a $(n+1)\times(n+1)\times(n+1)$ array with lots of zeroes in it,
as is $H(n_1,n_2,n_3)$ which is an array of zeroes and ones.  Thus,
$E[H]$ is actually the probability of an event.
Similarly, $H(n_1,n_2,n_3)/S(n_1,n_2,n_3)$ is an array with lots of zeroes
in it but the nonzero entries are $1/S(n_1,n_2,n_3)$ and
$$E\left [\frac{H}{S}\right]
= \sum_{n_1=0}^n\,\sum_{n_2=0}^n\,\sum_{n_3=0}^n
\frac{H(n_1,n_2,n_3)}{S(n_1,n_2,n_3)}p_{X,Y,Z}(n_1,n_2,n_3).$$
Comment: I'll review this soon. Thanks. Blasted iPhone cuts off the margins of SO web pages.
Comment: Thanks! Very useful so far as I can tell. I suspected Otto be the case that $H$ was the probability of an event. Is it the probability that $rm > dj$? And as for the expected $H/S$, it reduces to the sum of $1/S(...)$ over those cases when $rm>dj$ times the probability of that case?


If b is algebraic over F(a), and a is algebraic over F, then is b algebraic over F?

Question:
If $b$ is algebraic over the field $F(a)$ then is it algebraic over the field F?

I would like to find a proof if it is true or a counter example if it is not.
The only thing I could think of was trying to show that if b is a zero of a polynomial $p(x)$ in $F(a)$ then there would be a way to turn it into a polynomial in $F$ which $b$ is also a zero of.
Comment: Is $a$ algebraic over $F$ ?
Comment: And if it isnt then no.
Comment: If $a$ isn't algebraic, this isn't true - $\sqrt{\pi}$ is algebraic over $\mathbb Q(\pi)$
Comment: I was thinking of a as algebraic. It did not occur to me that the transcendental case would be different.
Comment: Could someone please provide a proof for the algebraic case because that is really what I wanted.
Comment: if a is algebraic yes, the classic proof $F(a)$ has a finite basis $(e_1,..,e_n)$ over $F$, if $F(b,a)$ has basis $(f_1,...,f_l)$ over $F(a)$, $(e_if_j)$ generates $F(a,b)$ over $F$.
Comment: Notice that $\pi$ is algebraic over $\mathbb{Q}(\pi)$.
Comment: @Maxwell.For the case where $a$ is algebraic: Tomorrow, if someone else hasn't done it . It's near midnight here.
Answer: Counterexample: We can extend $\mathbb{Q}$ by $\pi$. In this case $\pi$ is algebraic over $\mathbb{Q}[\pi]$ but not over $\mathbb{Q}$.
Answer: Let $K = F(a)$.  Since $K$ is a field containing $F$, $K$ is a vector space over $F$.  Assume $a$ is algebraic over $F$.  In this case, we have:
Lemma: If $F$ is a field, and $c$ is algebraic over $F$, then the field $F(c)$ is a finite dimensional vector space over $F$.
I hope you've already been introduced to this lemma, if not, it's a good exercise which makes use of the division algorithm.  Anyway, $K$ is a finite dimensional vector space over $F$.
Let $L$ be the field $K(b)$. Since $b$ is algebraic over $K$ by hypothesis, you can apply the lemma again, and so $L$ is a finite dimensional vector space over $K$.
Lemma 2: If $F_1 \subseteq F_2 \subseteq F_3$ are fields, then $\textrm{Dim }_{F_1} F_3 = (\textrm{Dim }_{F_1} F_2)\cdot (\textrm{Dim }_{F_1} F_3)$.
This isn't difficult to prove if you haven't seen it before.  You can just show that if $\{v_i\}$ is a basis for $F_2$ over $F_1$, and $\{w_j\}$ is a basis for $F_3$ over $F_2$, then the set of products $\{v_iw_j\}$ forms a basis for $F_3$ over $F_1$.  Apply linear independence in two steps.  Anyway, by this lemma, $L$ is a finite dimensional vector space over $F$ with dimension say, $m$.
Now $L$ is a field containing the element $b$.  The $m+1$ elements $1, b, b^2, ... , b^m \in L$ are linearly dependent over $F$, so there must exist scalars $c_0, c_1, ... , c_m \in F$, not all zero, such that $$c_0 + c_1b + \cdots + c_mb^m = 0$$ But now $b$ is a root of the nonzero polynomial $f(X) = c_0 + c_1X + \cdots + c_mX^m$, which lies in $F[X]$.  Let me know if you have any questions.


Stars and Bars problem involving odd restriction, and equal or greater than restriction.

Question: I just had this question in an exam and was unsure how to complete some parts using the Stars and Bars method.
Problem as follows:
How many solutions has the equation:
$x_1 + x_2 + x_3 + x_4 + x_5 + x_6 = 78$
If $x_1, x_2, x_3, x_4, x_5, x_6$ are non-negative integers and:
a) there are no further restrictions
b) all of $x_1, x_2, x_3, x_4, x_5, x_6$ are odd numbers
c) at least one of $x_1, x_2, x_3, x_4, x_5, x_6$ is greater than or equal to 30.

My attempts if they are worth anything, I believe I'm not familar enough with the method which lead to me misusing it:
a) This one was straight foward, I got $\binom{83}{5}$, by defintion of the method.
b) I'm certain I got this part wrong. I used my result from part (a), and minused it by the number of solutions where $x_1 + x_2 + x_3 + x_4 + x_5 + x_6 = 78$ is even. I.e. where we $x_1, x_2, x_3, x_4, x_5, x_6$ represent two stars such that $x_1 + x_2 + x_3 + x_4 + x_5 + x_6 = 39$.
So the final calculation was $\binom{83}{5}$ - $\binom{44}{5}$, but this doesn't make numerical sense.  $\ddot\frown$
c) Not too sure about this one either. I tried 'reserving' 30 stars such that $x_1 + x_2 + x_3 + x_4 + x_5 + x_6 = 48$, so $\binom{53}{5}$.
Similarly for the other case where there is some $x_i$ and $x_j$ are both greater than 30 so I 'reserve' 60 stars such that $x_1 + x_2 + x_3 + x_4 + x_5 + x_6 = 18$ so $\binom{18}{5}$.
Then I added the two together such that $\binom{18}{5} + \binom{53}{5} $
Comment: In c) the reserved $30$ can be added to $6$ candidates, giving a factor $6$ for the number of possibilities. Secondly the twice reserved $30$ gives likewise a factor $\binom{6}{2}=15$. Thirdly (in my view the most tricky) there is a double counting. A possibility where $30$ is added can be the same as one where $30$ is added twice.
Answer: Hint on b)
Find the number of solutions of $z_{1}+\cdots+z_{6}=36$ under no
restrictions.
This comes to the same as finding the number of solutions
of $y_{1}+\cdots+y_{6}=72$ under condition that all numbers are even.
And on its turn it comes to the same as finding the number of solutions of $x_{1}+\cdots+x_{6}=78$ under condition that all numbers are odd.
This by taking $y_i=2z_i$ and $x_{i}=y_{i}+1=2z_{i}+1$.


CORS blocked when invoking 3rd party API wrapped with Azure API Management

Question: I have an issue that has been bothering me for almost 1 month. I'll be honest, I am not  front end developer. So here is the issue.
I have a Azure API Management that wrap 3rd party maps provider. That APIM consumed by front end developed with React.js + Axios. Every time the front end invoke API that wrapped with Azure APIM, it will be resulted error with detail:

Access to XMLHttpRequest at [APIM URL] from origin [FE ORIGIN] has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Here is my Azure APIM policy that implemented on all operation:
    <policies>
    <inbound>
        <base />
        <cors allow-credentials="false">
            <allowed-origins>
                <origin>[FE ORIGIN]</origin>
                <origin>http://localhost:3000/</origin>
                <origin>http://localhost:3001/</origin>
            </allowed-origins>
            <allowed-methods preflight-result-max-age="300">
                <method>GET</method>
                <method>POST</method>
                <method>DELETE</method>
                <method>OPTIONS</method>
                <method>PUT</method>
            </allowed-methods>
            <allowed-headers>
                content-type
                accept
                transactionId
                authorization
                userId
                oid
                userRoles
            </allowed-headers>
        </cors>
    </inbound>
    <backend>
        <base />
    </backend>
    <outbound>
        <base />
        <set-header name="Access-Control-Allow-Origin" exists-action="override">
            <value>@(context.Request.Headers.GetValueOrDefault("Origin",""))</value>
        </set-header>
        <set-header name="Access-Control-Allow-Credentials" exists-action="override">
            <value>false</value>
        </set-header>
    </outbound>
    <on-error>
        <base />
    </on-error>
</policies>

And here is the part of Axios code:
  const handleSearch = useMemo(() => {
    const searchHandler = (value: string) => {
      if (value.length >= DELAY_CHAR) {
        const searchUrl = `${BASE_URL}?q=${value}&at=-0.789275,113.921327&limit=${MAX_ROW}`;
        axios
          .get(searchUrl)
          .then((res) => {
            const { items } = res.data;
            if (items && items.length > 0) {
              const opts: Opts[] = [];
              items.forEach((r) => {
                opts.push({
                  position: r.position,
                  value: r.address.label,
                });
              });
              setOptions(opts);
            }
          })
          .catch(() => {
            return null;
          });
      }
    };

    return debounce(searchHandler, DELAY_IN_MS);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [DELAY_IN_MS]);

I've try many options even wrapping the 3rd party API in newly created API. So I any helps really means a lot to me. Thank you very much before and I hope the information is enough.
Comment: Does this answer your question? [Access from origin 'https://example.com' has been blocked even though I've allowed https://example.com/](https://stackoverflow.com/questions/70353729/access-from-origin-https-example-com-has-been-blocked-even-though-ive-allow)
Comment: @jub0bs I'm afraid your link does not answer my question since the origin already without trailing dash. I'm just curious, do I need to add certain header on Axios side?
Comment: Two of the origins values (`http://localhost:3000/` and `http://localhost:3001/`) listed in your Azure APIM config have trailing  slashes, which leads me to suspect that the third one (which you've redacted) also has one.
Comment: Trailing slash should not make any difference in allowed-origins as only authority is compared between what's condifured and contents of Origin header. @WulungTriyanto, can you confirm that value in Origin header matches one of the origins configured in the policy? Scheme, hostname, and port, if specified, must match exactly.
Answer: So, after hours spend for trial and errors, we've finally find the root cause.
Notice the <base /> on <inbound> part, we remove that part and viola, it success. I'll be honest I don't understand why but it solve the issue. Here is the final inbound policy:
<policies>
<inbound>

    <cors allow-credentials="false">
        <allowed-origins>
            <origin>[FE ORIGIN]</origin>
            <origin>http://localhost:3000/</origin>
            <origin>http://localhost:3001/</origin>
        </allowed-origins>
        <allowed-methods preflight-result-max-age="300">
            <method>GET</method>
            <method>POST</method>
            <method>DELETE</method>
            <method>OPTIONS</method>
            <method>PUT</method>
        </allowed-methods>
        <allowed-headers>
            content-type
            accept
            transactionId
            authorization
            userId
            oid
            userRoles
        </allowed-headers>
    </cors>
</inbound>
<backend>
    <base />
</backend>
<outbound>
    <base />
    <set-header name="Access-Control-Allow-Origin" exists-action="override">
        <value>@(context.Request.Headers.GetValueOrDefault("Origin",""))</value>
    </set-header>
    <set-header name="Access-Control-Allow-Credentials" exists-action="override">
        <value>false</value>
    </set-header>
</outbound>
<on-error>
    <base />
</on-error>
</policies>


Fields in page.tpl.php

Question: I want to display in my page.tpl.php 3 custom fields form the latest content type added to my website.
I have a custom content type called "Articles" with three custom fields, field_1, field_2, field_3.
How can I display on every page of my website those three fields from the latest content added to "articles"?
I want to do this without using views.
Comment: Is this a exercise in ideology? Views is very well suited to this task, why not use it?
Comment: Are you interested in an answer for Drupal 6, or Drupal 7?
Comment: Hi, I already built this with views but I used views only for this small feature on the website and I was curious if there is an simple alternative.
Comment: I used Drupal 7
Answer: I don't have the exact answers for you, but I do have some directions to point you. Try something like this:

In template.php, in a THEMENAME_preprocess_page() function, construct a query to get the node ID of the most recently created node. Look up Drupal's Database API to see how to do this. (A more permanent solution would be to use a custom module for the query, but let's start at the theme layer to get this working.)
Do a node_load() to get the entire contents of that node, which will contain your three fields, and more.
Create variables (inside the $variables[] array) to hold the rendered content of your custom fields.
Use those new variables in page.tpl.php, or page-article.tpl.php
Comment: It is not necessary to load a node inside a page preprocess function; if `$vars` is the argument passed to the function, then `$vars['node']` already contains the node object, when the page being preprocessed is a node page.
Comment: @kiamlaluno it will only be there if you are on a node page, the question is about placing node content on every page.
Answer: Since I'm going to assume you have some kind of religious opposition to the Views module- I would opt for the custom module method.
A simple module could create a block that can be displayed on any page you like.
I would start here,  http://drupal.org/node/206753. We're talking 6.x right? Of course we are. Once you have the .info and .module file setup, you can skip down to Declaring Block Content, (http://drupal.org/node/206758), and then onto Generating content (http://drupal.org/node/206759 )... this is where it gets interesting...
function yourModuleName_block($op='list', $delta=0) {
  // set up the block
  $block = array();

  if ($op == "list") {
    // This is what it will be listed as in your list of blocks
    $block[0]["info"] = t('On This Date');
  }
  else if ($op == 'view') {
     $block['content'] = yourfunctionToGetNewArticalContent();
  }
}

Then create your function to return anything you want, For that you''ll want to take a look over here..
 http://api.drupal.org/api/drupal/includes--database.mysql-common.inc/function/db_query/6
Comment: It wasn't tagged as Drupal 7 when I answered and Drupal 6 is still far more common.

Fields in page.tpl.php


Regular neighbourhoods of non-orintable surfaces in $S^4$

Question: Suppose that $F \subset S^4$ is a non-orientable surface. Let $N \subset S^4$ be a regular neighbourhood of $F$. Clearly, the boundary of $N$ is a circle bundle over $F$. Which is its Euler number? My guess is that it is equal to zero, I wish to know a proof...
Comment: It's a bundle whose *fiber* is a circle, but it's not a $U(1)$-bundle, so I don't know what the Euler number means. Thinking of it as an $O(2)$-bundle, I could take its $w_1$, $w_2$, which you can calculate in terms of those of the surface...
Comment: I mean $\partial N$ is a Seifert manifold fibering over $F$ without singular fibers, so it has its associated Euler number (describing completely its topology)
Comment: I do not think there is a well defined Euler number in this situation. You may want to spell out exactly how you are defining this invariant. The definition of Euler number for Seifert bundles requires the bundle to become trivial after deletion of singular fibers (which you do not have) and one point (in case there are no singular fibers). But lack of orientability makes this impossible.
Comment: Check this book https://books.google.hu/books/about/Algorithmic_and_Computer_Methods_for_Thr.html?id=bjcZAQAAIAAJ&redir_esc=y Page 235
Comment: $Homeo^+(S^1)$ retracts on $SO(2)$, so I think that $\partial N$ can be thought as an $U(1)$-bundle.
Answer: This is an answer which I am not comfortable assessing the correctness of as I cannot find all the relevant sections of Whitney's paper and I don't understand Massey's.
This apparently a somewhat well-known question of Hassler Whitney. It seems the Euler number can be nonzero. I think the Euler number (with twisted coefficients) here https://projecteuclid.org/download/pdf_1/euclid.pjm/1102978058 agrees with the Seifert invariant definition. The proof critically uses the famous Atiyah-Singer index theorem.
This apparently unfinished preprint claims to prove that the Euler numbers from Massey's paper are precisely the ones realized by any embeddings of such Seifert fibred spaces into $S^4$ (without the condition that the embedding comes from the regular neighborhood of a surface). Both sources claim that the Euler numbers realized are $$\{2\chi-4,2\chi,2\chi+4,\dots,4-2\chi\}$$ where $\chi$ is the Euler characteristic of the surface.


Help on interpreting the results when significane level change, but not the coefficient

Question: I am studying the effect of employment on population growth using barroregressions. The dependent variable is thus the average log population growth in Norwegian regions between 1995 and 2013.
The controls are log population in 1995 (initial population to see if there were divergence in Norwegian regions in the period 1995-2013),
share of the workforce with a higher education degree and employment in a sector (where a sector is either the production sector, the business sector or the service sector).
In the next regression I change the employment variable to be a so called "shift-share" variable after Bartik (1991). This variable removes the idiosyncratic "shocks" in the employment growth variable, and is constructed from a period before our study period. The variable is constructed for the period 1970-1990.
When we use the employment in the production variable as a control, the coefficient is 0.16 and significant at a 5%-significance level.
When we use the Bartik variable instead, the coefficient is still 0.16, but more significant (at 1%).
What does the higher significance level imply, and why doesn't the coefficient change you think?
Answer: Possibly, by removing shocks in the employment growth, you remove variation in the independent variable's ability to predict the outcome. The overall fitted model might give the same line with the same slope (and therefore the same coefficient), but the extent to which the model fits is improved by removing noise in the predictive ability of the independent variable. Therefore, the p-value would decrease: the independent variable is more informative for the outcome.


Robocopy: How to copy assets from multiple locations to a single location and maintain a log

Question: I have multiple folders containing assets (each folder has subfolders containing these assets .mp3, .txt, .png, etc). I want to copy all this assets along with the subfolder to a single location/folder. I was able to successfully run a robocopy command to achieve copying of assets along with subfolders from one folder to another folder:

robocopy source target /s

I will be running a scheduler once daily to copy the assets. Also I wanted to store the name of all the copied assets in a log file. The name of the log file should be in the form of

log_currentDate.txt

for example if the today's date is 20th Oct 2015... the name of the log file should be:

log_20151020.txt

The next day i.e. 21st Oct 2015, it should be:

log_20151021.txt

This log file should contain the name of all the copied assets on 20th Oct 2015, 21st Oct 2015 and so on. I created a batch command (thanks to @DavidPostill) to create a log as follows:
@echo off
for /f "tokens=1-3 delims=/ " %%a in ('date /t') do (
set _date=%%a%%b%%c
)
echo robocopy source target /log:D:\ABC\log%_date%.txt

This creates a log with the name "logTue2010.txt" (i.e. logdayddmm format). Problem:

Where does this log file gets stored? To make visible this log file, I have to write a separate command everyday as follows:

robocopy source target /log:D:\ABC\logWed1021.txt /tee /s

How do I ensure that a separate copy of log is obtained each day?
Also with the current command, the log file contains the entire output displayed on the cmd window. I just want it to contain the name of the asset with its extension.

EDIT: As per @JosefZ I edited my batch file as follows:
@echo off
for /f "tokens=2 delims==" %%G in ('wmic OS get LocalDateTime /value') do set "_date=%%G"
set "_date="%_date:~0,8%
echo robocopy source target /log:D:\ABC\log\log_%_date%.txt
robocopy source target /log:D:\ABC\log\log_%_date%.txt /S

I received the following output:
D:\ABC>D:\ABC\copy1.bat
robocopy source target /log:D:\ABC\log\log_.txt
Log File : D:\ABC\log\log_.txt

Answer: Get YYYYMMDD-formatted date independently of locale and regional settings using for /F loop against wmic (Windows Management Instrumentation Command) and environment variable substring:
@echo off
for /f "tokens=2 delims==" %%G in ('wmic OS get LocalDateTime /value') do set "_date=%%G"
set "_date=%_date:~0,8%"

There are more robocopy logging options:

            /L : List only - don't copy, timestamp or delete any files.
           /NP : No Progress - don't display % copied.
      /unicode : Display the status output as Unicode text.   #
     /LOG:file : Output status to LOG file (overwrite existing log).
  /UNILOG:file : Output status to Unicode Log file (overwrite)
    /LOG+:file : Output status to LOG file (append to existing log).
 /UNILOG+:file : Output status to Unicode Log file (append)
           /TS : Include Source file Time Stamps in the output.
           /FP : Include Full Pathname of files in the output.
           /NS : No Size - don't log file sizes.
           /NC : No Class - don't log file classes.
          /NFL : No File List - don't log file names.
          /NDL : No Directory List - don't log directory names.
          /TEE : Output to console window, as well as the log file.
          /NJH : No Job Header.
          /NJS : No Job Summary.

robocopy B Bcopy /log:D:\ABC\log\log_%_date%.txt /S /NP /NDL /NJH /NJS /NS /NC

Above command (note /NP /NDL /NJH /NJS /NS /NC switches) will suppress almost all except (full-qualified) file names  in robocopy output. However, file names are indented with some Tab and Space characters. Next code snippet should make output as desired:
>D:\ABC\log\log_%_date%.txt (
for /f "tokens=*" %%G in ('
    robocopy B Bcopy /S /NP /NDL /NJH /NJS /NS /NC
  ') do echo(%%G
)

For > explanation, see redirection. And the log file gets stored in specified folder (D:\ABC\log\); to ensure this, try
type D:\ABC\log\log_%_date%.txt

Comment: do I have to replace "/value" with something?
Comment: @YashSaraiya no, the `/value` is a `/FORMAT` switch moniker. `wmic OS get /VALUE` is the same as `wmic OS get  /FORMAT:"C:\Windows\System32\wbem\textvaluelist.xsl"`. Note fully qualified filename in last command; `/FORMAT:textvaluelist.xsl` should suffice
Comment: Did you see the "EDIT" in my question? Please check and give update
Comment: @YashSaraiya Sorry, adjusted wrong `set "_date="%_date:~0,8%` to right `set "_date=%_date:~0,8%"`, see position of double quotes. Accidental mistake of copy&paste
Comment: It is working fine now... But I have mentioned other issues too... like currently my log contains everything that is shown up in the cmd upon firing a command... I want only the name of the assets that are copied and not the entire summary of cmd
Comment: @YashSaraiya `/NP /NDL /NJH /NJS /NS /NC` switches will suppress almost all except (full-qualified) file names.


Materiliaze view in oracle

Question: How to create/refresh materialize view in oracle 10g.
Answer: Oracle documentation here
Comment: Can you please provide me syntax and basic rules.
Answer: CREATE:
CREATE MATERIALIZED VIEW example_mview
AS
SELECT * FROM table_name

REFRESH:
REFRESH is simply used like exec dbms_mview.refresh('example_mview');
or within the structure like
REFRESH + refresh how
  CREATE MATERIALIZED VIEW example_mview
  REFRESH COMPLETE
  AS
  SELECT * FROM table_name

ex.
REFRESH FAST
REFRESH COMPLETE
REFRESH FAST ON DEMAND

See the documentation for other options.

Materiliaze view in oracle


How do I get distance out of a fairway bunker?

Question: I'm a long-time watcher and a short-time player of golf.
Whilst only a beginner, I am actually fairly good at getting out of greenside bunkers.  I open the club face, I aim an inch behind the ball and follow right through.
However, I can't seem to get any distance out of fairway bunkers.  Currently, I'm adopting the same approach as when I play the greenside bunkers but with a longer iron.
The problem is that I don't get any distance.  I either "top" it and I come out hard and low or I get under it but all the power is lost.
What should I be doing out of the sand here?
Answer:
However, I can't seem to get any distance out of fairway bunkers.
  Currently, I'm adopting the same approach as when I play the greenside
  bunkers but with a longer iron.

Oh no.....I'm cringing ;) You open your stance, the clubface of your long iron, and strike the sand an inch behind the ball to get out of fairway bunkers? The reason this is done in greenside bunkers is to get the ball out of the bunker while landing it softly enough to hold the green, let alone stopping the ball as close as you can to the hole (and if you can spin the ball, that's a huge plus!).

The problem is that I don't get any distance.

Playing a shot from a greenside bunker is not a distance shot.
How to play a shot out of a fairway bunker:

Take one or two extra clubs.
Place the ball a little farther back in stance than normal.
Dig in a little (sand is slippery if you don't get to the bottom    of it!)
Swing while keeping your lower body as still as possible.

Above is a list I got from the following article. Throughout my normal swing, my left leg flexes. During my bunker shot, my left leg is (athletically - slightly bent) stiff until I make contact. I will admit, it takes an enormous amout of leg strength to keep your lower body as still as possible.
Also, another thing that isn't listed above is to strike the ball first. Keep in mind how high the lip is before you choose your club. If the lip is high, I would take a higher club to move the ball forward and out of the bunker. Aside: Striking the ball first is also crucial for shots off pine straw.
EDIT: (based on KeithS's comment) If the ball is buried, just get the ball out of the bunker and give yourself a better look for your next shot. It is not practical to strike the ball first in a buried lie or fried egg. If more than the bottom quarter of the equator of the ball is buried, I would just pitch out.
Comment: +1 a fairway bunker is not the same as a green one..
Comment: One thing; it is not always practicable to strike the ball first. If your ball has buried itself in the bunker, abandon all hope of distance and play a normal, square, full-swing sand wedge shot with the aim of just getting out of the bunker.
Comment: @KeithS Another good point. I would hope common sense tells me to get out and give myself a shot ;)
Answer: One more thing I might add to edmastermind29's great answer is choke up on your club slightly to account for when you dig into the sand (the ball will be higher in relation to your feet). This will help to prevent you from catching too much sand and either leaving it in the bunker, or ending up short of where you're trying to hit it.
Also note it's one of the harder shots in golf so don't feel obligated to go for the green (edmastermind29 alluded to this already). Course management, knowing when to take risks and when to play it safe, can save you a ton of strokes.
Good luck!
Comment: +1 @eeyyo made a great point, choking down on the grip promotes control. Unless we're Dustin Johnson, who can blast a 230-yard bunker shot, the main thing we're going for is to get it out of the bunker, even if it is a 50-100 yard pitch out. Another honorable mention for course management.


Do i need to close the connection when using parametrised connection

Question: I have a piece of code shown below where I open connection and execute a command on it. Do I have to close this connection or what is the best way to write this piece of code?
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ToString());

if (con.State == ConnectionState.Closed)
{
    con.Open();
}

string sql = "INSERT INTO RegisterUser(Name,LastName,email,Nationality,Country) VALUES (@param1,@param2,@param3,@param4,@param5)";

SqlCommand cmd = new SqlCommand(sql, con);

cmd.Parameters.Add("@param1", SqlDbType.NVarChar, 200).Value = txtName.Text;
cmd.Parameters.Add("@param2", SqlDbType.NVarChar, 100).Value = txtLastName.Text;
cmd.Parameters.Add("@param3", SqlDbType.NVarChar, 50).Value = txtEmail.Text;
cmd.Parameters.Add("@param4", SqlDbType.NVarChar, 50).Value = ddCountry.SelectedItem.Value.ToString();
cmd.Parameters.Add("@param5", SqlDbType.NVarChar, 50).Value = txtCountryCode.Text;

cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();

Will the above code not release memory in case connection need to be closed?
Comment: yes, or you could use the using statement - see [link](https://msdn.microsoft.com/en-us/library/dw70f090(v=vs.110).aspx) and [link](http://stackoverflow.com/questions/4389506/ado-net-closing-connection-when-using-using-statement)
Comment: So now there are 4 people giving you the exact same answer. If you get 3 answers and 1 comment within 2 minutes with the exact same answer, maybe you did not search at all before asking this question?
Comment: As an aside, you probably meant to say "parameterised query", not "parameterised connection".
Answer: Yes you need always to close the connection. Also you don't need the first if.
using(SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ToString()))
{

    con.Open();

    string sql = "INSERT INTO RegisterUser(Name,LastName,email,Nationality,Country) VALUES (@param1,@param2,@param3,@param4,@param5)";

    SqlCommand cmd = new SqlCommand(sql, con);
    cmd.Parameters.Add("@param1", SqlDbType.NVarChar, 200).Value = txtName.Text;
    cmd.Parameters.Add("@param2", SqlDbType.NVarChar, 100).Value = txtLastName.Text;
    cmd.Parameters.Add("@param3", SqlDbType.NVarChar, 50).Value = txtEmail.Text;
    cmd.Parameters.Add("@param4", SqlDbType.NVarChar, 50).Value = ddCountry.SelectedItem.Value.ToString();
    cmd.Parameters.Add("@param5", SqlDbType.NVarChar, 50).Value = txtCountryCode.Text;

    cmd.CommandType = CommandType.Text;
    cmd.ExecuteNonQuery();
}

So using will automatically close your connection for you. This will happen even if your code throws an exception. using represents try/catch/finally block. In this way you are guaranteed that the connection is return to Connection Pool if error happens.
try
{
    Sqlconnection conn = new SqlConnection("your conn string");
}
catch(Exception ex)
{
    throw;
}
finally
{
    conn.Close();
}

Comment: Generally yes, but you don't know when that is going to happen. Also, it might never happen, e.g. in case of killing a process.
Comment: Does .net automatically release resources if they are not released as in my case of example.. I mean after sometime
Comment: How can i check if query exceuted successfully
Comment: @Learning Just read https://msdn.microsoft.com/en-us/library/8xx3tyca(v=vs.110).aspx about Connection Pool. I think this will make your questions cleared.
Answer: You should close it or otherwise underlying resources would remain used until the finalizer is executed.
The best option is to actually dispose the connection (which is equal to closing it in particular case of database connection object):
using (SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ToString()))
{
    con.Open();

    string sql = "INSERT INTO RegisterUser(Name,LastName,email,Nationality,Country) VALUES (@param1,@param2,@param3,@param4,@param5)";

    SqlCommand cmd = new SqlCommand(sql, con);
    cmd.Parameters.Add("@param1", SqlDbType.NVarChar, 200).Value = txtName.Text;
    cmd.Parameters.Add("@param2", SqlDbType.NVarChar, 100).Value = txtLastName.Text;
    cmd.Parameters.Add("@param3", SqlDbType.NVarChar, 50).Value = txtEmail.Text;
    cmd.Parameters.Add("@param4", SqlDbType.NVarChar, 50).Value = ddCountry.SelectedItem.Value.ToString();
    cmd.Parameters.Add("@param5", SqlDbType.NVarChar, 50).Value = txtCountryCode.Text;

    cmd.CommandType = CommandType.Text;
    cmd.ExecuteNonQuery();
}

Comment: What if i am not using try catch ..finali.. block
Comment: Object will be disposed when it leaves the `using` block. If `using` is inside the `try` block, and an exception occurs, then the connection would be disposed *before* execution moves to `catch`/`finally`.
Answer: You could use 'using'
using(SqlConnection(System.Configuration.ConfigurationManager
                          .ConnectionStrings["ConnectionString"].ToString())){
    if (con.State == ConnectionState.Closed)
    {
        con.Open();
    }

    string sql = "INSERT INTO RegisterUser(Name,LastName,email,Nationality,Country) VALUES (@param1,@param2,@param3,@param4,@param5)";

    SqlCommand cmd = new SqlCommand(sql, con);
    cmd.Parameters.Add("@param1", SqlDbType.NVarChar, 200).Value = txtName.Text;
    cmd.Parameters.Add("@param2", SqlDbType.NVarChar, 100).Value = txtLastName.Text;
    cmd.Parameters.Add("@param3", SqlDbType.NVarChar, 50).Value = txtEmail.Text;
    cmd.Parameters.Add("@param4", SqlDbType.NVarChar, 50).Value = ddCountry.SelectedItem.Value.ToString();
    cmd.Parameters.Add("@param5", SqlDbType.NVarChar, 50).Value = txtCountryCode.Text;

    cmd.CommandType = CommandType.Text;
    cmd.ExecuteNonQuery();
}


Core/Uncore voltage on Android device with adb

Question: There is a way to get core and/or uncore voltage from Android device with adb on Linux terminal?
Comment: There is no standard way. There are too many `PMIC` options available.
Answer: Finally, I got the answer.
To view current core voltage:
<code>shell@msm8994:/ # cat /sys/class/regulator/regulator.3/microvolts
785000
</code>


Which is better, mean or median?

Question: I have a large number of data. If i have to represent the data by the central tendency, which one i have to use, mean or median? The value of standard deviation is so huge too. Thanks.
Comment: What do you mean by "better"?
Comment: I think you are asking the wrong question. You have to ask yourself what do you want first.
Comment: "Better" has no formal definition in mathematics or statistics. What do you want to represent? Do you have outliers? How skewed is your distribution? Is the data a discrete variable or continuous? Do you want the measure of central tendency to take one of the possible values of the data?
Comment: @AnnaSdTC i mean which one is better between mean and median since it has a huge standard deviation.
Comment: @MedNait I want represent my data, but i confuse which one i should use
Comment: There are other options too like the mode (as @AnnaSdTC hints). Why do you think that (a) your standard deviation is huge (b) that the size of the standard deviation is relevant here?
Comment: when i get the mean value, and also the std dev is huge, is that okay for me to use the mean value, or i have to use another central tendency like median or mode? @mdewey
Comment: @AnnaSdTC i have outliers. the data is continous. yes, i want to measure of central tendency to take one of the possible values of the data
Comment: Since the mean is very sensitive to outliers and it does rarely take one of the values of the data (i.e., the mean of kids per women can be 2.3 or any other non-integer), then you may want to use the median.
Comment: @AnnaSdTC Thanks a lot. I wanna ask something. if i want to measure of central tendency to take one of the possible values of the data, can i consider that by std deviation?
Comment: The standard deviation does not measure central tendency but deviation.
Comment: @AnnaSdTC Oooh. I get it. Thanks. It really helps me :)
Comment: If you have outliers you may prefer to summarise using the median and inter-quartile range rather than mean and sd.
Answer: As comments have pointed, mean an median answer different questions. I give an example:
There are 4 people in a very little country. The only available food is imported pizza, and one of the villagers eat one pizza a day but the other three don't eat at all. Mean of eaten pizzas is 0.25 pizzas/day/inhabitant but median is 0 pizzas/day/inhabitant.
The local food dealer needs to know how many pizzas he needs to import to the country. He would use the mean (0.25) and multiply for the population (4) and get the right daily number of pizzas to import every day (1).
The local health organisation is likely more interested in knowing how well feed is the population. The median (0) shows that at least half of the population is starving, while the mean (0.25) wouldn't show it.
In general, when we are interested in aggregate values, mean is more useful, but sometimes median is more interesting when we are more interested in the typical values.
And of course no single number can summarize the whole information of a distribution. Sometimes mean or median will be enough for a given purpose, or we can need standard deviation, histograms, percentiles and so.

Which is better, mean or median?


Por que dizem que o $_GET no PHP é inseguro contra sql injection?

Question: Bom, a minha dúvida, é simples.
Tenho andado ultimamente, a ouvir muitas histórias a dizer que o $_GET no PHP é inseguro contra sql injection.
Poderiam-me dizer porquê?
Comment: Você pode deixar uma porta aberta para um ataque SQL-Injection que nada mais é do que a inserção de um código SQL em um parâmetro da URL que será enviado diretamente para o banco
Answer: Não é o $_GET que é inseguro, o problema é como usa ele.
Os dados podem vir por $_GET, $_POST, $_COOKIE ou até uma string gravada previamente em um arquivo e posteriormente adicionada a execução de uma query.
O problema está em como passar diretamente os valores na query (concatenando na string), por exemplo:
"SELECT * FROM tabela WHERE nome LIKE '%{$_GET['nome']}%'"

Desta forma seria possível fazer algo como http://site/pagina.php?nome=';QUERY e geraria isto:
SELECT * FROM tabela WHERE nome LIKE '';QUERY'

Claro que no caso acima no máximo obteria uma falha de sintaxe, no geral a API não permite múltiplas queries, agora imagine que os dados de uma SELECT são baseados em um id salvo na sessão e os produtos que o usuário pode visualizar em um painel são somente os com a ID (id_dono) dele:
"SELECT * FROM produtos WHERE id_produto={$_GET['idproduto']} AND id_dono={$_SESSION['idautenticado']}"

Mas se digitar isso acessar isto http://site/pagina.php?idproduto=6 -- e geraria isto:
SELECT * FROM produtos WHERE id_produto=6 -- AND id_dono=5

Desta maneira o usuário ignorou tudo que vier depois de -- e pode obter os dados privados de produtos de outros usuários em um suposto painel aonde controlaria os seus produtos.
Outro exemplo seria manipular qualquer coluna de uma tabela:
"UPDATE dados SET nome='%{$_GET['nome']}%' WHERE id={$_GET['id']}"

Suponhamos que temos colunas que não deveria poder ser alteradas, mas se você fizer algo como http://site/pagina.php?id=1&nome=',outracoluna='xxxxxx você irá ter controle sobre qualquer coluna da tabela, pois vai gerar algo como:
UPDATE dados SET nome='',outracoluna='xxxxxx' WHERE id=1

Leia isto de como evitar:

Como prevenir injeção de código SQL no meu código PHP?

Um exemplo simples é usar o bindValue ou bindParam:
PDO+bindValue:
$db = new PDO('mysql:host=localhost dbname=teste', 'usuario', 'senha');

$stmt = $db->prepare('SELECT * FROM tabela WHERE nome LIKE ?');

$stmt->bindValue(1, '%' . $_GET['busca'] . '%'); // passado diretamente

$stmt->execute();

PDO+bindParam:
$stmt = $db->prepare('SELECT * FROM tabela WHERE nome LIKE :consulta');

$stmt->bindParam(':consulta', $nome);

$nome = '%' . $_GET['consulta'] . '%';

Mysqli+bind_param:

mysqli só trabalha com bind_param, ou seja não existe um bind_value

$db = new mysqli('localhost', 'usuario', 'senha', 'teste');

$stmt = $db->prepare('SELECT * FROM tabela WHERE nome LIKE ?');

if(!$stmt){
    echo 'erro na consulta: '. $db->errno .' - '. $db->error;
} else {
    $stmt->bind_param('s', $nome);

    $nome = '%' . $_GET['consulta'] . '%';

    $stmt->execute();
}

bindValue e bindParam

bindParam trabalha com referencias, ou seja só deve-se usar variáveis e constantes. Se for uma variável o valor pode ser alterado posteriormente, mas antes do execute

bindValue trabalha com qualquer tipo de valor, variável constante ou passado diretamente

Leia mais em: Qual a diferença entre bindParam e bindValue?
Comment: @Gonçalo muitas destas duvidas já tem resposta no site, de qualquer forma adicionei a resposta.
Comment: Excelente resposta, Obrigado!
Comment: Concretamente o que faz o bindValue?


Alter menu item markup in Drupal 8

Question: I am trying to play around with Drupal 8 menu. How I understand now menu is a service, so how to alter menu output in Drupal 8? Is there any documentation? Because googling show no useful results.
What I am trying to achieve is move active class from  element to parent
 element, this should be possible to do in .twig template (I wouldn't like that) so how to get menu in Drupal 8 and alter it's attributes?
Comment: http://drupal.stackexchange.com/a/126483/10157 might help?
Answer: There is one central problem: the active class is not always added in PHP, but
for non-anonymous users its calculated using some javascript, see "active-link.js".
For anonymous users, its calculated in
\Drupal\system\Controller\SystemController::setLinkActiveClass
Answer: I have a complete example for twitter bootstrap, I use:
Note: this code is incomplete, maybe broken with beta update, but it's an example/introduction.
function nature_menu_link(array $variables) {
  $element = $variables['element'];
  $sub_menu = '';

  if ($element['#below']) {
    // Prevent dropdown functions from being added to management menu so it
    // does not affect the navbar module.
    if (($element['#original_link']['menu_name'] == 'management') && (module_exists('navbar'))) {
      $sub_menu = \Drupal::service('renderer')->renderRoot($element['#below']);
    }
    elseif ((!empty($element['#original_link']['depth'])) && ($element['#original_link']['depth'] == 1)) {
      // Add our own wrapper.
      unset($element['#below']['#theme_wrappers']);
      $sub_menu = '
' . \Drupal::service('renderer')->renderRoot($element['#below']) . '
';
      // Generate as standard dropdown.
      $element['#title'] .= ' ';
      $element['#attributes']['class'][] = 'dropdown';
      $element['#localized_options']['html'] = TRUE;

      // Set dropdown trigger element to # to prevent inadvertant page loading
      // when a submenu link is clicked.
      $element['#localized_options']['attributes']['data-target'] = '#';
      $element['#localized_options']['attributes']['class'][] = 'dropdown-toggle';
      $element['#localized_options']['attributes']['data-toggle'] = 'dropdown';
    }
  }
  // On primary navigation menu, class 'active' is not set on active menu item.
  // @see https://drupal.org/node/1896674
  if (($element['#href'] == '<front>' && drupal_is_front_page()) && (empty($element['#localized_options']['language']))) {
    $element['#attributes']['class'][] = 'active';
  }
  $output = l($element['#title'], $element['#href'], $element['#localized_options']);
  return '
' . $output . $sub_menu . "
\n";
}

After I have my view nammed "menu--main.html.twig" :
{#  https://api.drupal.org/api/drupal/core!modules!system!templates!menu.html.twig/8
    menu_name: The machine name of the menu.
    items: A nested list of menu items. Each menu item contains:
      attributes: HTML attributes for the menu item.
      below: The menu item child items.
      title: The menu link title.
      url: The menu link url, instance of \Drupal\Core\Url
      localized_options: Menu link localized options.
#}

      <button class="navbar-toggle" type="button" data-toggle="collapse" data-target=".navbar-collapse">
      Toggle navigation

      </button>
      Site Name : {{ site_name }}

      {# All menu and submenu items #}

        {% for item in items %}
          {# Menu with submenu #}
          {% if item.below %}

              {{ item.title }}

                {# Menu -> Submenu #}
                {% for item in item.below %}
                  {% include "@nature/snippet/menu-infinite-child.html.twig" with { 'item': item } %}
                {% endfor %}

          {# Menu without submenu #}
          {% else %}
            {# Menu - Link #}

{{ item.title }}

            {# Menu - Separator #}
            {% if loop.last == false %}

{% endif %}
          {% endif %}
        {% endfor %}

      <form class="navbar-form navbar-left" role="search">

          <input type="text" class="form-control" placeholder="Search">

        <button type="submit" class="btn btn-default">Submit</button>
      </form>

          Dropdown 3

Action

Another action

Something else here

Separated link

This view call "menu-infinite-child.html.twig" for unlimited infinite child (submenu) :
{# Submenu -> Submenu #}
{% if item.below %}

    {{ item.title }}

      {% for item in item.below %}
          {% include "@nature/snippet/menu-infinite-child.html.twig" with { 'item': item } %}
      {% endfor %}

{# Submenu without Submenu #}
{% else %}

{{ item.title }}

{% endif %}

Note: I use this configuration with bootstrap-submenu http://vsn4ik.github.io/bootstrap-submenu (MIT license).

Alter menu item markup in Drupal 8


Naive Bayes Python implementation differences

Question: Am currently using Naive Bayes for a multi labelled text document classification problem.
But I would like to know the differences (advantages and disadvantages) of using SkiLearn Naive Bayes or NLTK?
SkiLearn seems to have flexibility in parameter setting more than NLTK, but I'm think my thoughts on this being the only difference is quite naive.
Also what cases would you select one over the other?
Any help appreciated.
Answer: Scikit learn has several Naive bayes. Naive bayes is usually a quick and dirty way to do classification.
The different ones used are:
Gaussian Naive Bayes: which normally used
Bernoulli Naive Bayes: used for things with 2 variables (heads or tails, yes or no)
Multinomial Naive Bayes: Usually used for text processing, where you have a smoothing parameter for missing data.
Here is a good explaination of the Naive bayes with +1 smoothing https://www.youtube.com/watch?v=0hxaqDbdIeE
Not sure about NLTK but sklearn is optomized based on this paper:http://www.cs.unb.ca/profs/hzhang/publications/FLAIRS04ZhangH.pdf
Also sklearn's algorithms are further optimized using cython.


H/w suggestions for 24 port PoE switch

Question: I am looking for a 24 port PoE(IEEE 802.3af) switch to power some Snom phones that I have. Please suggest some appliances. I just need basic L2 functions and wouldn't want to go for a expensive Cisco switch. Here are my requirements:
1) IEEE 802.3af PoE
2) 802.1q VLAN
3) Full-Duplex
I'd like a CLI also if possible, I've looked at Vyatta, but buying their 24 port appliance is way more expensive than a d-link or a netgear one. Thanks for your suggestions
Edit:
I've shortlisted the following(not had a look at HP so far)... I'd appreciate reviews if anybody is using any of these switches in production.
D-Link: DES1228P
Cisco: SRW224G4P, SFE2000P
Netgear: FS728TP
Comment: What's your budget?
Comment: Have you considered mid-span devices? You can use them with your existing switches and replace either as your needs dictate.
Comment: budget is around 500$...
Answer: i'm happy with hp procurve. take a look at J9138A#ABB / 2520-24 POE. i did not used this particular one [ i did not needed PoE ], but i never had problems with hp's managed / smart switches.
btw cli interface of hp devices is very similar to Cisco's ios.
Answer: I'm using quite a lot (20-25, various clients) of Linksys/Cisco SLM224P (half-poe, only 12 ports PoE) and SRW224P to power Linksys phones, and only one had problems (2-3 lockups in a year).

H/w suggestions for 24 port PoE switch