Comparisons between count data for all states in the US

Question: I have counts of infections reported in all states in the United States, and I want to test whether the rate at which infections are reported in each state is different.  What is the appropriate test for this?
Answer: You can formulate this as an generalized linear model with log link function, also known as poisson regression. The response variable will be the observed counts of infections, then you should include as an offset the logarithm of exposure. Exposure could be population of state, or some relevant subpopulation, or even persondays.  You could use a poisson model, or, if overdispersion is an issue (which it probably is), negative binomial regression.  Then the residual deviance from this model can be used for hypothesis testing.
For some more details on poisson regression see Goodness of fit and which model to choose linear regression or Poisson


How many solutions are there to this modified conformality equation?

Question: $\newcommand{\id}{\operatorname{Id}}$
$\newcommand{\tr}{\operatorname{tr}}$
Let $d \in \mathbb{N}, d \ge 2$. Let $D \in M_d$ be a non-zero diagonal matrix.
Consider the equation $\Sigma^2=(\det \Sigma)^{\frac{2}{d}}\id+D$
where $\Sigma$ is a diagonal real $d \times d$ matrix with non-negative values.
I found two necessary conditions for the existence of a solution:

(1) $\tr(D) > 0$.
(2) Not all the diagonal elements (of $D$) are positive.

(Proofs are at the end).

Question: Suppose $\tr(D) > 0$, and that not all the elements of $D$ are positive. Is there a solution? How many solutions are there?
Can the solutions be expressed "nicely" in terms of $D$?

For the case $d=2$, I showed below that indeed these conditions are sufficient, and when they hold there is a unique solution:
Denoting $D=\begin{pmatrix} \lambda_1 & 0 \\\ 0 & \lambda_2 \end{pmatrix}$, the solution is given by
$$\Sigma=\begin{pmatrix} \frac{|\lambda_1|}{\sqrt{\tr(D)}} & 0 \\\ 0 & \frac{|\lambda_2|}{\sqrt{\tr(D)}} \end{pmatrix} \tag{1}=\frac{|D|}{\sqrt{\tr(D)}}.$$
Any ideas how to solve the general case?
(For the interested, I got to this equation after studying the modified conformality equation $ A^TA=|\det A|^{\frac{2}{d}}\id+B$ and using its orthogonal invariance).
Proofs of the necessary conditions:

(1): $\tr(D) > 0$.

Indeed, denoting $\Sigma=\operatorname{diag}(\sigma_1,...,\sigma_d)$, $\sigma_i^2=\alpha_i$ we take the trace:
$$ \tr(\Sigma^2)=\sum_{i=1}^d \alpha_i = d(\Pi_{i=1}^d \alpha_i)^{\frac{1}{d}}+\tr(D),$$
hence
$$ \frac{\tr(D)}{d} =\frac{\sum_{i=1}^d \alpha_i}{d}-(\Pi_{i=1}^d \alpha_i)^{\frac{1}{d}} \ge 0,$$ and equality holds if and only if $\alpha_1=\alpha_2=\dots=\alpha_d$ (This is the AM–GM inequality).
In the equality case, we get $\alpha_i=\alpha,\sigma_i=\sigma=\sqrt{\alpha}$, so $\Sigma =\sigma \id$ is conformal, so $D=0$ which contradicts our assumption.

(2): Not all the diagonal elements are positive.

Denote $D=\operatorname{diag}(\lambda_1,...,\lambda_d)$. Then the equation is $$\sigma_i^2-(\Pi_{i=1}^d \sigma_i)^\frac{2}{d}=\lambda_i,i=1,\dots,d$$
If all the $\lambda_i$ are positive, then each $\sigma_i$ is greater than their geometric mean, which is impossible.

General observation:
Denoting $\Sigma=\operatorname{diag}(\sigma_1,...,\sigma_d),D=\operatorname{diag}(\lambda_1,...,\lambda_d)$ the equation reduces to: $$\sigma_i^2-(\Pi_{i=1}^d \sigma_i)^\frac{2}{d}=\lambda_i, i=1,...,d$$
In particular $\sigma_1^2-\sigma_j^2=\lambda_1-\lambda_j$. Since $\sigma_i \ge 0$, $\sigma_1$ determines  all the other $\sigma_j$.

Analysis of the $2D$ case:
Recall that $D=\begin{pmatrix} \lambda_1 & 0 \\\ 0 & \lambda_2 \end{pmatrix}$, and that we assumw $\tr(D)=\lambda_1+\lambda_2 >0$:
$\sigma_i^2- \sigma_1\sigma_2=\lambda_i,$ so $ \sigma_1^2-\sigma_2^2=\lambda_1-\lambda_2,(\sigma_1-\sigma_2)^2=\lambda_1+\lambda_2$.
Since we assumed $D \neq 0$, $\sigma_1 \neq \sigma_2 $ so we divide an obtain
$$ \frac{\sigma_1+\sigma_2}{\sigma_1-\sigma_2}=\frac{\lambda_1-\lambda_2}{\lambda_1+\lambda_2}:=\lambda,$$
hence
$\sigma_1+\sigma_2=\lambda\sigma_1-\lambda\sigma_2 \Rightarrow \sigma_1(1-\lambda)=-\sigma_2(\lambda+1)$.
Now we divide into cases:
(1) $\lambda_1=0$: This forces $\lambda_2 > 0$. Then $\sigma_1(\sigma_1-\sigma_2)=0 \Rightarrow \sigma_1=0 \Rightarrow \sigma_2^2=\lambda_2$.
In this case $\sigma_2=\sqrt{\lambda_2}$, i.e $\Sigma = \sqrt{D}$.
(2) $\lambda_1 \neq 0$: Then $1+\lambda \neq 0$, so $ \sigma_2=\sigma_1\frac{\lambda-1}{\lambda+1}=-\frac{\lambda_2}{\lambda_1}\sigma_1$.
From the equation
$\sigma_1^2- \sigma_1\sigma_2=\sigma_1^2(1+\frac{\lambda_2}{\lambda_1} ) =\sigma_1^2(\frac{\lambda_1+\lambda_2}{\lambda_1} )=\lambda_1$, so
$$\sigma_1^2 = \frac{\lambda_1^2}{\lambda_1+\lambda_2}=\frac{\lambda_1^2}{\tr(D)}.$$
Finally,
$$ \sigma_1 = \frac{|\lambda_1|}{\sqrt{\tr(D)}},\sigma_2 = -\frac{\lambda_2}{\sqrt{\lambda_1+\lambda_2}}=\frac{|\lambda_2|}{\sqrt{\tr(D)}}. \tag{2}$$
We observe that the solution in case $(1)$ is in fact in the form of $(2)$.
Answer: This is not a question about linear algebra. Let
$D=diag(d_i),\Sigma=diag(\sigma_i),m=(\Pi_i{\sigma_i}^2)^{1/d}$.
Necessarily $m\geq \sup_i(-d_i)$ and $\sigma_i=\sqrt{m+d_i}$.
Case 1. $m=0$. Then, for every $i$,$d_i\geq 0$, there is $j,k$ s.t.
$d_j=0,d_k\not= 0$ and, for every $i$, $\sigma_i=\sqrt{d_i}$.
Case 2. $m>0$. Then, let $K=\{j|d_j\not= 0\}$.
For every $j\in K$, $1+d_j/m>0$ and $\Pi_{j\in K}(1+d_j/m)=1$. We
consider the continuous function
$$f:x\in[\sup_i(-d_i),+\infty[\rightarrow \Pi_{j\in K}(1+d_j/x).$$
 We look for $m$ s.t. $f(m)=1$. When $x\rightarrow +\infty$,
$f(x)=1+trace(D)/x+o(1/x)$ and, since $trace(D)>0$,
$\lim_{x\rightarrow +\infty}=1+$.
i) For every $i$, $d_i\geq 0$ and there is $j$ s.t. $d_j=0$. Then
${\sigma_j}^2=m$ and for every $i$, ${\sigma_i}^2\geq m$.
Consequently, the $(\sigma_i)$'s are equal, that is contradictory (cf.
the OP's post).
ii) There is $i$ s.t. $d_i<0$; then, $\sup_i(-d_i)>0$; thus
  $f(\sup_i(-d_i))=0$ and we are done.
EDIT 1. (To Asaf Shachar). I just read your last post. Unfortunately,
$f$ is not monotone because it is decreasing in a neighborhood of
$+\infty$ (its derivative is $\approx -trace(D)/x^2$). Then, I proved
only that the equation $f(x)=1$ has at least one solution.
EDIT 2. To @ Asaf Shachar. Now I prove (with the help of a colleague)
that there is exactly one solution; it suffices to show that the
function
$$f'/f:x\in ]\sup_i(-d_i),+\infty[\rightarrow \sum_{j\in
K}(\dfrac{1}{x+d_j}-\dfrac{1}{x})$$
 has exactly one zero.
Proof. We assume that $d_1<\cdots<d_p<0<d_{p+1}<\cdots <d_k,\sum_{i\leq k}\alpha_id_i>0$, where $\alpha_i$ is the "multiplicity" of $d_i$. We consider the function
$$g:x\notin \{-d_j|j\leq k\}\rightarrow \sum_{j\leq k
}\dfrac{\alpha_jd_j}{x(x+d_j)}.$$
Note that $g(x)=\dfrac{P_{k-1}(x)}{x\Pi_i(x+d_i)}$, where $degree(P_{k-1})=k-1$, and $g(x)=0$ iff $P_{k-1}(x)=0$, that is, $g$ has at most $k-1$ roots. Considering the ($\lim_{x\rightarrow \pm -d_i}g(x)$)'s, wee obtain that $g$ has at least a root in $]-d_k,-d_{k-1}[,\cdots$, in $]-d_{p+1},-d_p[$, in  $]-d_{p-1},-d_{p-2}[,\cdots$, in $]-d_2,-d_1[$; moreover, we know that $g$ has at least a root $>-d_1$ and thus, we have our $k-1$ roots and we are done.
Comment: Thanks. If I understood correctly, In case $2$ you meant to say the following?:  $\lim_{x\rightarrow +\infty}f(x)=1+$, so $f(x) > 1$ for $x$ large enough. On the other hand $f(\sup_i(-d_i))=0$, so by the intermediate value theorem, there exist an $m$ s.t $f(m)=1$. Since $f$ is monotone this $m$ is *unique*. So, to summarize: If there exist a $d_i<0$, then there exist a *unique* solution where $m>0$. Otherwise (when all the $d_i \ge 0$, the only solution is when $m=0$. So, in any case (no matter what $D$ is) there is a unique solution, right?
Comment: BTW, I agree with you this is not related so much to linear algebra (so I removed the tag). Your idea to "separate" the question to finding the determinant and the "elements" separately is very nice. Thanks again for your effort.
Answer: $\newcommand{\diag}{\operatorname{diag}}$
I am merely clarifying some points regarding loup blanc's answer:
Denote $D=\diag(d_i),\Sigma=\diag(\sigma_i),m=(\Pi_i{\sigma_i}^2)^{1/d}$, and suppose $\sigma$ is a solution to the equation fir $D$. Then, necessarily $$m\geq \sup_i(-d_i) \, \, \text{and} \, \,  \sigma_i=\sqrt{m+d_i} \tag{1}.$$
Note that in any case $m \ge 0$.
A first observation:
$m=0 \iff d_i \ge 0$ for all $i$.
Proof:
$m=0 \Rightarrow d_i \ge 0$: Obvious from equation $(1)$.
$d_i\ge 0 \Rightarrow m= 0$:
Suppose by contradiction that $m > 0$.
The assumption $d_i\ge 0$ implies $\sigma_i^2 \ge m$, so $m^d=\Pi_{i=1}^d \sigma_i^2 \ge m^d>0$, but this can happen only if $\sigma_i=m$ for all $i$, and then $\Sigma$ is conformal, a contradiction.
Back to the main proof:
We want to prove that for all $D$ satisfying the conditions stated in the question, there is a unique solution. We separate into cases"
(1) $d_i \ge 0$ for all $i$.
The n $m=0$, so equation $(1)$ reduces to $\sigma_i=\sqrt{d_i}$.
(2) There exist an $i$ such that $d_i < 0$.
Then loup blanc's argument shows that there exist a solution. Let's show there is a unique solution:
We need to show the function $$f:x\in[\sup_i(-d_i),+\infty]\rightarrow \Pi_j(1+d_j/x) $$ obtain the value $1$ at most at one point.
We already know that $f(\sup(-d_i))=0, \lim_{x \to \infty}f(x)=1$ and that $f(x) > 1$ for $x$ sufficiently large. Also, it is easy to see $f'(\sup(-d_i))>0$. Hence, if we will show $f'(x)$ has only one zero than this would imply $f$ obtaines the vlaue $1$ exactly at one point.
For $x > \sup(-d_i)$, $$ f'(x)=-\sum_j \frac{d_j}{x^2}\Pi_{i\neq j}(1+\frac{d_i}{x})=-\sum_j \frac{d_j}{x^2}\Pi_{i}(1+\frac{d_i}{x})\frac{1}{1+\frac{d_j}{x}}=-\sum_j \frac{d_j}{x^2}f(x)\frac{1}{1+\frac{d_j}{x}},$$
so $$f'(x)=-\frac{f(x)}{x^2}\sum_j d_j\frac{1}{\frac{x+d_j}{x}}=-\frac{f(x)}{x^2}\sum_j \frac{d_jx}{x+d_j}.$$ Hence, for $x > \sup(-d_i)$, $f'(x)=0$ if and only if $h(x):=\sum_j \frac{d_jx}{x+d_j}=0$. Assume by contradiction that $h$ has two zeroes. Than, $h'(x)=0$ for some $x$ but
$$h'(x)=\sum_j \frac{d_j^2}{(x+d_j)^2}$$ which is impossible.


How can I find a list of fields output by a view block?

Question: FINAL UPDATE
Success! Apparently there were field-level permissions set on several of the CCK fields I needed, in spite of the original developer telling me that content permissions were not enabled. Once I allowed anonymous viewing of the required fields, they displayed with no problem.

I've created a view with a block display. The view has a grouping field, and in the views ui preview, the output displays as grouped by that field:

When I display the block using my template, though, it's not printing out the grouping info (Advanced Learning Session or General Session). That field is not a standard one, like title - it's a CCK text field on my content type. How do I access that field in my template? I've tried the solutions shown here to get a list of available fields, but none of them work.
Edited after trying @schnippy's answer
When I mouse over the field, I see this:

So I tried adding
<?php print "session type: ".$fields['field_session_type_value']->content; ?>

to my template, but although the "session type:" string prints, there's no value coming through after it. I've also tried writing just the value to the error log, in case there was something weird about combining it with a text string, but still nothing.
Edit again...
Just to provide a bit more info, if it will help - I'm using the mobile jquery theme, which has a views-view-list.tpl.php file to display views where the output is HTML List. That template looks like this:
<?php
// $Id: views-view-list.tpl.php,v 1.3 2008/09/30 19:47:11 merlinofchaos Exp $
/**
 * @file views-view-list.tpl.php
 * Default simple view template to display a list of rows.
 *
 * - $title : The title of this group of rows.  May be empty.
 * - $options['type'] will either be ul or ol.
 * @ingroup views_templates
 */

?>

<?php print $title; ?>

  <<?php print $options['type']; ?> data-role="listview">

    <?php foreach ($rows as $id => $row): ?>

      <li class="<?php print $classes[$id]; ?>"><?php print $row; ?>

    <?php endforeach; ?>
  </<?php print $options['type']; ?>>

I have a number of views that are being displayed via blocks with this template, and for the most part it's fine because they all are grouped by a title field. But for one view, the records are grouped by a CCK field called field_session_type_value, and if the value of that field matches a specific value, I want to print that field instead of $title.
Another update
According to views-view.tpl.php, $rows is the variable that views sends out as the results of the view query. Now, if I have multiple fields, I would expect that doing a print_r on $rows would return a multi-dimensional array - each record or row would be an array containing a key/value pair for each field. Like so:
Array (
  [0] => array('title'=> 'Advanced Consumer and Shopper Insight - An Interactive Symposium',
               'session' => 'general-session'),
  [1] => array('title' => 'Creating a Powerful Brand One Dirty Job at a Time',
               'session' => 'advanced-learning')
)

(Yes, I realize my pseudocode array is not formatted correctly. But you get the idea.) But that's not what I'm getting. What it's sending back is a single-dimension array, containing just the titles:
Array (
  [0] => Advanced Consumer and Shopper Insight - An Interactive Symposium
  [1] => Creating a Powerful Brand One Dirty Job at a Time
)

What do I need to do to make sure it sends all the fields through in the $rows array?
Answer: You're using the 'row style' type 'fields' here, correct? The field you are grouping on should also be added as a field in your 'fields' list in order for this to be showing correctly in your preview so all you need to do is find the name, which can be tricky to guess depending on the cck field type. One way you can do this is by hovering over the 'link' in the fields editor within views:

and get the name of the field from the url in your browser status bar, ex.
../view_name/display/field/<your field name>

and then you just print out the rendered view content of your field in your tpl with:
<?php print $fields['<your_field_name>']->content; ?>

Comment: Thanks. I just tried that, and it's returning nothing. I'm editing the OP with more info.
Answer: Apparently there were field-level permissions set on several of the CCK fields I needed, in spite of the original developer telling me that content permissions were not enabled. Once I allowed anonymous viewing of the required fields, they displayed with no problem.
Lesson learned; always check for field-level permissions.


What kind of cadence is this?

Question: I'm currently learning about periods and there is a question in the book, asking for the closure in m. 4.

The book says it's a half cadence, but it ends on a I (or I64). The only half cadence I see at that point would be the one, ending on the downbeat of m. 4 (I6 - vii°).
Any ideas?
Comment: Just realized that the vii° is actually a V6. Butt Doesnt a half cadence need a dominant triad in root position?
Answer: In a comment, you ask whether the half cadence doesn't need a dominant triad in root position.  You have one: D F# A.
I 6/4 is a bad analysis of the cadential 6/4.  It is not I but V, because this pattern behaves as a (decorated) dominant. The upper parts are appoggiaturas.
In simple terms, I feels like home, and V doesn't. If you were to remove the F# A, extend the G B to the length of a crotchet, and stop the music there, would it feel at all final? No, because of the D in the bass part. This chord still feels like it wants to go somewhere.
Here is a typical example from harmony.org.uk of a good way of writing this progression:

If you are taking a course that requires you to label this progression with I, then you will have to stick it out, but it is misleading and widely criticized.
Comment: Ah, I think I've heard about that before, thanks for pointing it out. I gotta remember that the sustained count too, thanks :)
Comment: FWIW: there's nuance here. In this case, where the 6th and 4th over the bass immediately settle to the 5th and 3rd, writing V 6-5/4-3 is definitely correct. But I had my freshman theory go too far in the other direction: if a cadential 6/4 was interrupted by some extra chords between that chord and the root position V, I was still supposed to write V 6/4, which is ostensibly wrong, as it isn't a 2nd inversion V. So in the case of double appoggiatura, V 6-5/4-3. In the case of extended cadential 6/4, I write a C 6/4. And in the weird case of actual I 6/4 I write it. (Also, passing 6/4.)
Comment: I think it is useful to understand why a cadential I 6/4 works the way it does, pulling down into V.  The upper notes above the bass definitely act like non-chord tones. As far as labeling goes, every school is different.
Answer: I'd interpret this as an imperfect cadence. Especially due to the dominant pedal crotchet note (a feature used by many Baroque and Classical composers) the chord definitely does not feel finished and wants to move somewhere else.
Comment: I believe the Americans call an imperfect cadence a half cadence, so you are in agreement with the book's term.

What kind of cadence is this?


spring mvc, form:select not working

Question: I have got problem with binding some fields to the form.
My example (sorry for mistakes in code - I have written it from head)
Question is:
Can I bind form:select from class - there is Map with my data?
JSP page doesn't render dropdown list... other fields are rendered (for example: input type="text")
<code>    Class FormDocument
    {
    private Map<Integer, String> docsMap;

    public Map<Integer, String> getDocsMap()
        {
        this.docsMap = new HashMap<Integer, String> ();
        this.docs.put(1, "Document01");
        this.docs.put(2, "Document02");
        this.docs.put(3, "Document03");

        return docsMap;
        }

        // other setter, getters
    }
</code>
Jsp "formPage.jsp":
<code>    <form:form >
    <form:select path="docsMap" items="docsMap" />
    </form:form>
</code>
Controller:
<code>    @RequestMapping("/formShow")
    public String getFormPage(Model model)
    {
    model.addAttribute("command", new FormDocument());

    return "formPage";
    }
</code>
If I add line in Controller:
model.addAtribute("docsMap", AND HERE IS Map);
It will render my select box...
Comment: The `path` is the attribute inside the FormDocument. The items is the list of items to render which is basically the collection of all items which are selectable.
Answer: Perhaps this tutorial on Spring data binding will help:
http://howtoprogramwithjava.com/session35

spring mvc, form:select not working


Have the three goalkeepers of a squad ever been used during a World Cup?

Question: Usually, the same goalkeeper plays all the games during the competition, and I rarely saw the second goalkeeper playing, even less the third one.
Have there been occurrences of teams having their three goalkeepers having played during the competition?
Answer: Four teams (France, Belgium, Czechoslovakia and Greece)  used their three goalkeepers:

In all, only four teams have ever used three goalkeepers in a single
World Cup tournament. That's out of 371 teams to have qualified for
the finals – surely time for Fifa to change the rules.
First to use a trio of keepers were France in 1978. The No1 was
Jean-Paul Bertrand-Demanes who played in Les Bleus' opening game
against Italy. In the second group game against Argentina,
Bertrand-Demanes smashed either his back or head (it varies between
reports) on a post after pulling off a save and had to be replaced by
Dominique Baratelli, a 31-year-old who had made sporadic appearances
since 1969. He conceded the winning goal against Argentina and was
replaced for France's final group game by Dominique Dropsy. The game
against Hungary was Dropsy's debut and he would go on to win another
16 caps. Neither Baratelli nor Bertrand-Demanes would ever play for
the national side again.
Belgium went into the 1982 tournament with the eccentric (he served a
three-month ban in 1980 after elbowing a linesman in a Belgian Cup
match) but hugely talented Jean-Marie Pfaff as their first choice.
Pfaff had been welcomed, somewhat apprehensively, back to the fold
after missing the 1978 European Championships because of his practical
joking, but he couldn't keep his inner comedian under wraps. He was
dropped following the first group stage after apparently pretending to
drown in the swimming pool at the team hotel. His replacement in
Belgium's opening game in the second group stage was Theo Custers,
whose performance against Poland was so abject it was his last
("Custers's last stand," notes the World Cup historian Cris Freddi).
For the Belgian's final game Jacky Munaron took the gloves.
Also in 1982, Czechoslovakia used three keepers. Zdenek Hruska played
from start to finish against Kuwait, but Stanislav Seman was preferred
for the Czech's game against England. A calamitous performance – it
would be his last for the national side – lasted 75 minutes before he
broke a finger and was replaced by third-choice Karel Stromsik, who
kept the No1 spot for the final group game.
The most recent team to use three goalkeepers in a single tournament
were the hapless Greece side of 1994. The Greeks had gone undefeated
through qualifying and named the experienced Antonis Minou, who had
conceded only twice in five qualifiers, as No1 for the opening game
against Argentina. A 4-0 defeat saw 25-year-old AEK keeper Elias
Atmatsidis in goal against Bulgaria. Another 4-0 defeat followed and
he was replaced by 24-year-old Christos Karkamanis for the final group
game. That brought a slight improvement in fortunes – a 2-0 defeat to
Nigeria.

Source: The Guardian (Internet Archive).
Answer: There already is an answer which provides several occurrences of this happening. (And which probably is complete until the source of that answer was published, which is shortly before 2010 FIFA World Cup.)
Let us collect collaboratively in this community wiki answer other occurrences that we are able to find.

At 2018 FIFA World Cup, Saudi Arabia used all three goalkeepers in the group stage: Abdullah Al-Mayouf, Mohammed Al-Owais and Yasser Al-Mosailem.
At 2018 FIFA World Cup, all three Tunisian goalkeepers Mouez Hassen, Farouk Ben Mustapha and Aymen Mathlouthi played in the group stage.
At 2015 FIFA Women's World Cup, all
three Japan goalkeepers Erina Yamane, Ayumi Kaihori and Miho Fukumoto played in the group stage.
Kaihori played in all matches in the knockout stage.


div tag confusion trying to center an input form

Question: I am having trouble with two div classes in my CSS document.  The classes are named homeBody and signupBody.
I am trying to center an input form for my website but when I change the div tags from homeBody to signupBody, my header disappears.  I copy and pasted the homeBody class to create the CSS rules for the signupBody class so I don't know why the are having different effects.
All I want to do is center the margin for the signupBody class, if someone could let me know what I'm doing wrong I would greatly appreciate it.
<?php
    session_start();
?>
<!DOCTYPE html>

        <meta charset="utf-8">
        <meta name="description" content="This is an example of a meta description.  This will often show up in search results.">
        <meta name=viewport content="width=device-width, initial-scale=1">
        <title>TAG</title>
        <link rel="stylesheet" type="text/css" href="style.css">

            <?php
                if (isset($_SESSION['userID'])) {
                    echo    '

                                <form action="includes/logout.inc.php" method="post">
                                    <button type="Submit" name="logout-submit">Logout</button>
                                </form>

                                <form action="upload.php" method="POST" enctype="multipart/form-data">
                                    <input type="file" name="file">
                                    <button type="submit" name="submit">New Post</button>
                                </form>

';
                }
                else {
                    echo    '

                                <form action="includes/login.inc.php" method="post">
                                    <input type="text" name="mailuid" placeholder="Username/E-mail">
                                    <input type="password" name="password" placeholder="Password">
                                    <button type="Submit" name="login-submit">Login</button>
                                </form>

                                or Signup

';
                }
            ?>

<?php
    require "header.php";
?>

Signup

            <?php
                if (isset($_GET["error"])) {
                    if ($_GET["error"] == "emptyfields") {
                        echo '
Fill in all fields!
';
                    }
                    else if ($_GET["error"] == "invalidemail") {
                        echo '
Invalid Email!
';
                    }
                }
                else if (isset($_GET["signup"])) {
                    if ($_GET["signup"] == "success") {
                        echo '
Signup Sucessful!
';
                    }
                }
            ?>
            <form action="includes/signup.inc.php" method="post">
                <input type="text" name="firstName" placeholder="First Name">

                <input type="text" name="lastName" placeholder="Last Name">

                <input type="text" name="userName" placeholder="User Name">

                <input type="text" name="email" placeholder="E-mail">

                <input type="password" name="password" placeholder="Password">

                <input type="password" name="pwd-repeat" placeholder="Repeat password">

                <button type="submit" name="signup-submit">Signup</button>
            </form>

<?php
    require "footer.php";
?>

Home

Activity

Trending

Chat

.button{
background-color:#333;
color:#fff;
padding:10px 15px;
border:none;
}
.button: hover{
    background:red;
    color:#fff;
}
#footerContainer{
    background-color:#333;
    bottom: 0px;
    left: 0px;
    padding: 10px 0px;
    position: fixed;
    text-align: center;
    width: 100%;
}
#footerContainer .footerList{
    display: inline;
    list-style: none;
    padding: 10px 10px;
}
#footerContainer .footerList a{
    color: white;
    text-align: center;
    text-decoration: none;
}
#footerContainer .footerList a: hover{
    color: red;
}
#headerContainer {
    background-color:#333;
    height: 60px;
    width: 100%;
    position: fixed;
}
.homeBody {
    margin: 60px 0px 40px 0px;
}
.signupBody {
    margin: 60px auto 40px auto;

}
#loginForm {
    position: absolute;
    top: 10px;
    right: 5px;
}
#logoutForm {
    position: absolute;
    top: 10px;
    right: 5px;
}
.upload {
    position: absolute;
    top: 20px;
    right: 0px;
}
#signupForm a {
    color: white;
    text-decoration: none;
    position: absolute;
    top: 35px;
    right: 5px;
}

Answer: You'll need to set a width for .homeBody and set margin to auto.
Comment: Yes, that was it.  Another issue I ran into after that was that chrome was storing some kind of cache and it wasnt updating properly.  thank you for your help :)
Comment: i checkmarked it and upvoted, my upvotes dont count yet but thank you again!


How do I add managed images to the Media Module browser stored locally through a remote URL?

Question: This question has been asked lots of other places and I was quite determined to make it happen. The use case is copy and paste a URL for an image on the web into the Media Module file browser. The Remote Stream Wrapper module does something similar except the images are not stored on the local server. Instead the metadata about the image is stored in the database while Image Cache stores images locally. I really wanted to import images I have access to onto my server.
Answer: First, a form is built. Then the elements in the form array are expanded during drupal_process_form(). The default value of each element is set during this stage. The file.module has a callback hook added during the set element value stage which other form elements do not have, '#file_value_callbacks`.
I simply added a textfield element to the upload form for the media browser and registered a callback. If there is an URL in the textfield, drupal_http_request() is used to pull the data / image and save it passing the file ID as the value of the upload widget element to finish processing the image.
It seems to work as expected. There are some gaping security holes which need to be cleaned up. Nonetheless, this implementation will greatly increase the efficiency of workflow for my next project.

Here is my solution:
/**
 * Implements hook_form_FORM_ID_alter()
 */

function helper_form_file_entity_add_upload_alter (&$form, &$form_state, $form_id) {
  // Keep the textfield clear if there is a file ID
  // We only have to upload the image once then who cares?
  if (!empty($form['upload'])){
    $form['upload']['#file_value_callbacks'][] = 'helper_file_value_callback';
    $form['url'] = array(
      '#type' => 'textfield',
      '#title' => 'Enter image URL',
    );
  }
}

function helper_file_value_callback (&$element, &$input, &$form_state) {
  global $user;

  // Make sure that there is a $url
  if (empty($input['fid']) && valid_url($url = $form_state['input']['url'])) {

    $upload_name = implode('_', $element['#parents']);
    $destination = $element['#upload_location'];
    $parsed_url = parse_url($url);
    $path = str_replace('///', '//', "$destination/") . drupal_basename($parsed_url['path']);

    // Make sure that there is a directory.
    if (isset($destination) && !file_prepare_directory($destination, FILE_CREATE_DIRECTORY)) {
      watchdog('file', 'The upload directory %directory for the file field !name could not be created or is not accessible. A newly uploaded file could not be saved in this directory as a consequence, and the upload was canceled.',
          array('%directory' => $destination, '!name' => $element['#field_name']));
      form_set_error($upload_name, t('The file could not be uploaded.'));
      return FALSE;
    }

    // Download file and make sure that return code is 200 or else abort!
    $result = drupal_http_request($url);
    if ($result->code != 200) {
      drupal_set_message(t('HTTP error @errorcode occurred when trying to fetch @remote.',
          array('@errorcode' => $result->code, '@remote' => $url)), 'error');
      return FALSE;
    }

    // Construct the $file object
    // file_save() adds the timestamp and filesize on save
    // file_unmanaged_save_data posts message on error
    if ($uri = file_unmanaged_save_data($result->data, $path, FILE_EXISTS_RENAME)){
      // Create a file object
      $file = new stdClass();
      $file->fid = NULL;
      $file->uri = $uri;
      $file->filename = trim(drupal_basename($parsed_url['path']));
      $file->filemime = file_get_mimetype($file->uri);
      $file->uid = $user->uid;
      $file->status = 0;

      if (file_save($file)){
        $input['fid'] = $file->fid;
      }
    }

  }
}


Outside Database

Question: I have an outside database called "panels" that stores our company articles/blog posts/products etc... in it.
Is there a good module to use, or I could write a custom module to hook into the outside database to display these content types?
All changes would be done through our in house system, I am only looking to display them onto the drupal site we made for our store front.
Comment: Just for clarification, so you have two databases? One which contains Drupal for your store front and the other outside one?
Comment: Or do you have 1 database that you want to be in a different location from your files folder, php, mysql etc..
Comment: I have 2 databases.  One which is the drupal site/store front as we refer to it and the other that is separate and holds our company content that feeds 4 sites.  We have the non drupal sites displaying our content, just trying to find out the best way for my drupal stores to display them.
Comment: I guess what I'm saying is one database is for products, and is the drupal store database, the other database never saves into a node but only displays, like a feed.
Comment: For anyone else interested in using an outside source to display info but not have it save in the Drupal database the best solution I found was to write your own hooks and use Views/Page Manager to display the info.
Comment: http://barcelona2012.drupaldays.org/sessions/displaying-external-data-fly-views-and-ctools
Comment: That was the base I used to write my own code to accomplish my needs.  Great presentation I hope someone else looking into this can find his presentation and make use of it.
Answer: You may have some success with Migrate which will enable you to import data from an external source into a Drupal content type. You could set up a cron task to run the migration on a regular basis.
Comment: This seems promising, as all I really need it to do is take the data I pull into a block and then display control where it outputs through page manager or contexts.
Answer: Maybe consider the Forena module? It is built of the idea of using SQL to get data out of a database and use XHTML and CSS to format it into web reports. Visit the Forena HowTos page for some links (near the bottom) to some live demo / showcase links.
DBMSs that are supported are the Drupal DB itself (of course), but also MySQL, Oracle, MS SQL, Postgress, Sqite, anything PDO compliant.
Disclosure: I'm a co-maintainer of Forena,
I hope this does not violate the site's policy on self-promotion.
Comment: Forena is something I am looking into and it may serve my needs.  I will research more into this module and Migrate and see what fits our needs.

Outside Database


Aggregate dados no R com função própria

Question: Gostaria de obter o R² fazendo a regressão linear para cada agrupamento do meu banco de dados. Meu código esta assim, mas não consigo rodar.
x <- dados$area.ACM
y <- dados$Largura
model <- lm(log(y)~log(x))
novosdados <- aggregate(dados, by = list(rotulo = dados$Rótulos.de.Linha), FUN = model)

Meus dados:
dados
              Categoria ORDEM area.ACM Largura
1                   0     1    90.10    3.78
2                   0     2   239.20   13.61
3                   0     3   639.62   22.21
4                   0     4  1104.40   28.85
5                   0     5  1665.04   28.69
6                   0     6  2266.62   33.95
7                   0     7  3109.09   45.40
8                   0     8  3975.05   45.76
9                   0     9  4936.68   49.43
10                  0    10  5999.67   57.04
11                  0    11  7145.59   57.45
12                  0    12  8265.30   50.14
13                  0    13  9241.26   48.64
14                  0    14 10096.26   43.93
15                  0    15 11178.55   57.80
16                  0    16 12469.35   69.46
17                  0    17 13835.76   67.89
18                  0    18 15005.12   59.41
19                  0    19 16204.52   57.11
20                  1     1   333.22   21.72
21                  1     2   755.98   23.24
22                  1     3  1148.70   15.46
23                  1     4  1483.86   23.16
24                  2     1   188.40    9.76
25                  2     2   381.31    9.73
26                  2     3   586.00   11.37
27                  2     4   860.24   20.45
28                  2     5  1267.64   18.74
29                  2     6  1599.34   11.66
30                  2     7  1924.61   23.68
31                  2     8  2478.65   33.26
32                  2     9  3125.11   30.71
33                  2    10  3795.50   32.33
34                  2    11  4412.67   34.42

Comment: Pode, por favor, **editar a pergunta** com a saída de `dput(dados)` ou, se a base for muito grande, de `dput(head(dados, 20))`?
Comment: Depois de ter editado a sua [pergunta anterior](https://pt.stackoverflow.com/questions/551657/regress%c3%a3o-n%c3%a3o-linear-para-cada-agrupamento-de-dados-no-r) com os dados, ficou muito melhor e muito melhor que esta versão. Ponha aqui os dados tal como pos lá mas em vez do `>` antes de `dados`, formate-os como código.
Comment: Obrigada pela edição!
Answer: Eis uma solução. Mas com a função by, não com aggregate.
A função by divide a tabela por Categoria e aplica o lm a cada sub-base x. Depois o ciclo lapply cria uma lista de sumários, onde se incluem os R2. Finalmente, extraem-se os R2 e usam-se esses valores para extrais os modelos com R2 acima de 0.85 (ou outro valor).
x <- '              Categoria ORDEM area.ACM Largura
1                   0     1    90.10    3.78
2                   0     2   239.20   13.61
3                   0     3   639.62   22.21
4                   0     4  1104.40   28.85
5                   0     5  1665.04   28.69
6                   0     6  2266.62   33.95
7                   0     7  3109.09   45.40
8                   0     8  3975.05   45.76
9                   0     9  4936.68   49.43
10                  0    10  5999.67   57.04
11                  0    11  7145.59   57.45
12                  0    12  8265.30   50.14
13                  0    13  9241.26   48.64
14                  0    14 10096.26   43.93
15                  0    15 11178.55   57.80
16                  0    16 12469.35   69.46
17                  0    17 13835.76   67.89
18                  0    18 15005.12   59.41
19                  0    19 16204.52   57.11
20                  1     1   333.22   21.72
21                  1     2   755.98   23.24
22                  1     3  1148.70   15.46
23                  1     4  1483.86   23.16
24                  2     1   188.40    9.76
25                  2     2   381.31    9.73
26                  2     3   586.00   11.37
27                  2     4   860.24   20.45
28                  2     5  1267.64   18.74
29                  2     6  1599.34   11.66
30                  2     7  1924.61   23.68
31                  2     8  2478.65   33.26
32                  2     9  3125.11   30.71
33                  2    10  3795.50   32.33
34                  2    11  4412.67   34.42'

dados <- read.table(textConnection(x), header = TRUE)

model_list <- by(dados, dados$Categoria, FUN = \(x) lm(log(Largura)~log(area.ACM), x))
smry_list <- lapply(model_list, summary)
rsq <- sapply(smry_list, `[[`, 'r.squared')
rsq
#>          0          1          2
#> 0.88588363 0.04933031 0.78306697

model_list[rsq > 0.85]
#> $`0`
#>
#> Call:
#> lm(formula = log(Largura) ~ log(area.ACM), data = x)
#>
#> Coefficients:
#>   (Intercept)  log(area.ACM)
#>      -0.03155        0.44718

Created on 2022-05-04 by the reprex package (v2.0.1)
Comment: Otimo! Solucao simples e eficiente! Muito obrigada
Comment: Tentei extrair o valor do Coeficiente 'log', da mesma forma. Alterei apenas a linha a seguir: expoente <- sapply(smry_list, `[[`, 'log') Mas nao funcionou
Comment: @Clarissa Para extrair os dois coeficientes tente `lapply(model_list, coef)`. Ou `sapply`, para ter uma matrix de coeficientes.
Answer: Se quer apenas os valores de R² por categoria, sem armazenar as listas com o resultado das regressões, pode se valer da lógica "separa/aplica" (split/apply). Pacotes dplyr e data.table facilitam esse tipo de operação.
Com data.table
library(data.table)

setDT(dados)

dados[, .(r.squared = summary(lm(log(area.ACM) ~ log(Largura)))$r.squared), Categoria]
#>    Categoria  r.squared
#> 1:         0 0.88588363
#> 2:         1 0.04933031
#> 3:         2 0.78306697

Com dplyr
library(dplyr)

dados %>% group_by(Categoria) %>%
  summarise(r.squared = summary(lm(log(area.ACM) ~ log(Largura)))$r.squared)
#> # A tibble: 3 x 2
#>   Categoria r.squared
#>       <int>     <dbl>
#> 1         0    0.886
#> 2         1    0.0493
#> 3         2    0.783

R base
reslm <- lapply(split(dados, dados$Categoria),
  function(x) summary(lm(log(area.ACM) ~ log(Largura), x))$r.squared)
#> $`0`
#> [1] 0.8858836
#>
#> $`1`
#> [1] 0.04933031
#>
#> $`2`
#> [1] 0.783067

Dados
dados <- structure(list(Categoria = c(0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L,
    0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 1L, 1L, 1L, 1L, 2L,
    2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L), ORDEM = c(1L, 2L, 3L,
    4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L, 13L, 14L, 15L, 16L, 17L,
    18L, 19L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L,
    10L, 11L), area.ACM = c(90.1, 239.2, 639.62, 1104.4, 1665.04,
    2266.62, 3109.09, 3975.05, 4936.68, 5999.67, 7145.59, 8265.3,
    9241.26, 10096.26, 11178.55, 12469.35, 13835.76, 15005.12, 16204.52,
    333.22, 755.98, 1148.7, 1483.86, 188.4, 381.31, 586, 860.24,
    1267.64, 1599.34, 1924.61, 2478.65, 3125.11, 3795.5, 4412.67),
    Largura = c(3.78, 13.61, 22.21, 28.85, 28.69, 33.95, 45.4,
    45.76, 49.43, 57.04, 57.45, 50.14, 48.64, 43.93, 57.8, 69.46,
    67.89, 59.41, 57.11, 21.72, 23.24, 15.46, 23.16, 9.76, 9.73,
    11.37, 20.45, 18.74, 11.66, 23.68, 33.26, 30.71, 32.33, 34.42
    )), class = c("data.table", "data.frame"), row.names = c(NA,
    -34L), .internal.selfref = <pointer: 0x55c3543ae220>)

Comment: Obrigada pelas opções de resolução!

Aggregate dados no R com função própria


Alternate approach to show $|\sum_{i \leq n} \frac{\mu(i)}{i}| \leq 1$?

Question: I am doing a question out of H. E. Rose's A Course In Number Theory (Chapter 2, problem 2) which I have been struggling with for some time. However I found a solution which strays from the way advised by the author, and I would just like some validation as to whether it is correct.
The question starts by asking to prove $\sum_{i \leq n} \mu(i) \big[ \frac{n}{i} \big] = 1$, which I have done in a method similar to the approach as seen here:
Prove $\sum_{d \leq x} \mu(d)\left\lfloor \frac xd \right\rfloor = 1 $
Now from this, it is asked to show $|\sum_{i \leq n} \frac{\mu(i)}{i}| \leq 1$. Asked like this I assume the author is asking you to use a method or result from the preceding part to prove this. However my alternate route was as follows:
$-1 \leq \mu(i) \leq 1$
$\sum_{i \leq n} (-1) \leq \sum_{i \leq n} \mu(i) \leq \sum_{i \leq n} (1)$
By summing all values of $i$ from 1, upto and including $n$. Now using the fact $\sum_{i \leq n} (1) = n$;
$-n \leq \sum_{i \leq n} \mu(i) \leq n$
Taking the absolute value;
$|\sum_{i \leq n} \mu(i)| \leq n$
Now multiplying through by $\sum_{i \leq n} \frac{1}{i}$ which is strictly positive (and hence it can be taken inside the absolution), giving;
$|\sum_{i \leq n} \frac{\mu(i)}{i}| \leq n \sum_{i \leq n} \frac{1}{i}$
From here, you can use Euler's integral theorem;
$|\sum_{i \leq n} \frac{\mu(i)}{i}| \leq n\big(\ln(n) + \gamma +O(\frac{1}{n}) \big)$
$|\sum_{i \leq n} \frac{\mu(i)}{i}| \leq n\ln(n) + n\gamma +O(1) $
As $n \gamma$ is constant, this can be absorbed into the $O(1)$;
$|\sum_{i \leq n} \frac{\mu(i)}{i}| \leq n\ln(n) + O(1) $
This is where I make an assumption; $\ln(n) = o(\frac{1}{n})$ then substituting this in;
$|\sum_{i \leq n} \frac{\mu(i)}{i}| \leq n(o(\frac{1}{n})) + O(1) = o(1)$
Thus, finally giving;
$|\sum_{i \leq n} \frac{\mu(i)}{i}| \leq 1$
Thank you.
Comment: What is $\mu(i)$?
Comment: The Mobius mu function
Comment: But $n\sum_{i\le n}1/i=n+n/2+\cdots n/n\ge n+1$, and not $\le 1$ before Euler's theorem in your proof. In fact, the bound is $\log(n)n$ which certainly is bigger than $1$ for $n$ large.
Comment: $\ln(n)$ is certainly not $o(\frac{1}{n})$. It's not even $O(1)$. It is, however, $o(n)$.
Answer: There are quite a few mistakes happening here.

You get $|\sum_{i\leq n}\mu(n)|\leq n$ and you multiply it by $\sum_{i \leq n} \frac{1}{i}$, getting on the left hand side $|\sum_{i \leq n} \frac{\mu(i)}{i}|$. You seem to be using a rule of a sort $(\sum_{i\leq n}a_n)(\sum_{i\leq n}b_n)=\sum_{i\leq n}a_nb_n$, which is not correct - the latter sum doesn't include terms like $a_1b_2$ (to be exact - it misses $a_ib_j$ for $i\neq j$).
$n\gamma$ is not a constant. This is a strictly increasing function of $n$. Hence it's incorrect to absorb it into $O(1)$ term.
This is I believe the most important: your assumption that $\ln(n)=o(\frac{1}{n}$ is very, very wrong. $\ln(n)$ is an increasing function which tends to infinity, while every function which is $o(\frac{1}{n})$ decreases to zero moderately fast.
In second to last equation you write $n(o(\frac{1}{n}))+O(1)=o(1)$. Left hand side of this equality is clearly $o(1)+O(1)$, but this need not be $o(1)$. Indeed, $o(1)+O(1)$ is exactly the same thing as $O(1)$.
After you get $|\sum_{i \leq n} \frac{\mu(i)}{i}|=o(1)$ you conclude $|\sum_{i \leq n} \frac{\mu(i)}{i}|\leq 1$. However, that the sum of $o(1)$ only tells you that the absolute value of the sum is eventually less than or equal to $1$, so this would only establish that the sum is less than or equal to $1$ _for $n$ large enough.

Lastly I wanted to ask, what is exactly the "Euler's integral theorem" you are refering to? The asymptotic you provide for $\sum_{i\leq n}\frac{1}{i}$ is correct, I'm just asking for what the theorem you refer to states.
Comment: This really was a shot in the dark; the book I am working from seems to be going to great lengths to omit facts and explanations. I will quickly run through your amendments. The Euler integral theorem, as it is stated in the book states explicitly; $\int^{x}_{1} \frac{dt}{t} = \ln(x) + \gamma + O(\frac{1}{x})$, and later goes onto say this is equivalent to $\sum_{t \leq x} \frac{1}{t}$
Comment: I've tried another approach, using the definition that $\frac{\phi(n)}{n} = \sum_{d|n} \frac{\mu(d)}{d}$. Using the Mobius inversion formula from here to get: $\frac{\mu(n)}{n} = \sum_{d|n} d \frac{\mu(d) \phi(\frac{n}{d})}{n} \implies \sum_{n\leq x} \frac{\mu(n)}{n} = \sum_{n \leq x} \sum_{d|n} d \frac{\mu(d) \phi(\frac{n}{d})}{n}$ But from here I keep getting the RHS equalling one due to the $\sum_{d|n} \mu(d) = 1 (n=1$ only). I just cant make the last step (if this is more on track?)
Answer: Your estimate somehow arrives at the bound $n\log(n)+O(1)$ which is certainly not $\le 1$ for large $n$ - where you say, "This is where I make an assumption", it is not true.
Comment: It's not even showing this, because of absorbing $n\gamma$ into a constant.


qemu, kvm: Guest: No DHCPOFFERS received

Question: I'm trying to set up a virtual machine (guest) wich should act as router (ubntu 14.04). The host is a CentOS 7 machine (4x LAN). The guest should get a public ip address over it's eth0 (guest), wich is connected to enp0s20f0 (host) over br0 (host).
The Problem is, that the guest doesn't get an ip address.

More informations:

All interfaces of the host (enp0s20f0 - enp0s20f3) are connected over bridges br0 - br3 (host) to eth0 - eth3 (guest).
The LAN interfaces (host) don't have a bootproto
The bridges (host) don't have a bootproto, except br2: there is bootproto=static so I can connect the host to the guest and then to the internet

Sketch:

+---------------------------------------------------------------------------------------------------------+
|host: CentOS 7, KVM, qemu                                                                                |
|  +------------------------------------------------------------------------------------+  + - - - - - -+ |
|  |guest (VM): ubuntu 14.04 router, firewall                                           |  |other guests  |
|  |                                                                                |       (VM)    | |
|  | +--------------------------------------------------------------------------------+ |  |              |
|  | |                                                                                | |               | |
|  | |                                     firewall                                   | |  |              |
|  | |                                                                                | |               | |
|  | ++------------+---------+-------------+-------+-------------+------+------------++ |  |              |
|  |  +------------+         +-------------+       +-------------+      +------------+  |               | |
|  |  |PROBLEM:    |         |             |       |             |      |            |  |  |              |
|  |  |eth0        |         |eth1         |       |eth2         |      |eth3        |  |  + - - - - - -+ |
|  |  |dhcp        |         |static       |       |static       |      |static      |  |      X          |
|  +------------------------------------------------------------------------------------+    X            |
|     |not working |         |lan zone     |       |dmz          |      |wlan zone   |     X              |
|     +----+-------+         +-----+-------+       +-------+-----+      +-----------++   X                |
|          |                       |                       |                        |  X                  |
|          |                       |                       |             X  X  X  X |X                    |
|   +------+---------+       +-----+------------+        +-+-------------X--+      ++-----------------+   |
|   |                |       |                  |        |                  |      |                  |   |
|   |                |       |                  |        |                  |      |                  |   |
|   |     br0        |       |      br1         |        |    br2           |      |      br3         |   |
|   |                |       |                  |        | BOOTPROTO=static |      |                  |   |
|   |  BOOTPROTO=none|       | BOOTPROTO=none   |        | IP: a local ip   |      |  BOOTPROTO=none  |   |
|   +-------+--------+       +---------+--------+        +----------+-------+      +---------+--------+   |
|           |                          |                            |                        |            |
|           |                          |                            |                        |            |
|           |                          |                            |                        |            |
|   +-------+--------+       +---------+--------+        +----------+-------+      +---------+--------+   |
|   |                |       |                  |        |                  |      |                  |   |
|   |enp0s20f0       |       |enp0s20f1         |        |enp0s20f2         |      |enp0s20f3         |   |
+---------------------------------------------------------------------------------------------------------+
    |                |       |                  |        |                  |      |                  |
    |                |       |                  |        |                  |      |                  |
    +--------X-------+       +---------X--------+        +---------XX-------+      +----------XX------+
             XXXXX                     X                            XXXXXX                      XX
                 XX  loc LAN  XXX      X           other server (dmz)    XXX     wlan zone       XX
                  X             XXXXXXXX                      X       XXXXXX        XXX           X
     internet XXXXX                                           XXXXXXXXX               XXXXXXXXX XXX

Configs:
Guest:

cat /etc/network/interfaces
#[...] lo [...]
# The primary network interface
auto eth0
iface eth0 inet dhcp

# The lan
auto eth1
iface eth1 inet static
        address 192.168.x.y
        netmask 255.255.255.0
        broadcast 192.168.x.255

# the dmz
auto eth2
iface eth2 inet static
        address 10.0.p.q
        netmask 255.255.255.0
        broadcast 10.0.p.255

# The wirelles zone
auto eth3
iface eth3 inet static
        address 192.168.v.w
        netmask 255.255.255.0
        broadcast 192.168.v.255

Host:

cat /etc/sysconfig/network-scripts/ifcfg-*

NAME=br0                    DEVICE=br0                  NAME=br2                   NAME=br3
TYPE=Bridge                 NAME=br1                    TYPE=Bridge                TYPE=Bridge
ONBOOT=yes                  TYPE=Bridge                 BOOTPROTO=static           ONBOOT=yes
BOOTPROTO=none              ONBOOT=yes                  ONBOOT=yes                 BOOTPROTO=none
NM_CONTROLLED=no            BOOTPROTO=none              IPADDR=10.0.0.10           NM_CONTROLLED=no
DELAY=0                     NM_CONTROLLED=no            NETMASK=255.255.255.0      DELAY=0
DEFROUTE=no                 DELAY=0                     GATEWAY=10.0.p.q           DEFROUTE=no
PEERDNS=no                  DEFROUTE=no                 DNS1=10.0.p.q              PEERDNS=no
# PEERROUTES=yes            PEERDNS=no                  NM_CONTROLLED=no           # PEERROUTES=yes
# IPV4_FAILURE_FATAL=no     # PEERROUTES=yes            DELAY=0                    # IPV4_FAILURE_FATAL=no
# IPV6INIT=no               # IPV4_FAILURE_FATAL=no     DEFROUTE=yes               # IPV6INIT="no"
# IPV6_AUTOCONF=no          # IPV6INIT=no               PEERDNS=yes                # IPV6_AUTOCONF=no
# IPV6_DEFROUTE=no          # IPV6_AUTOCONF=no          # PEERROUTES=yes           # IPV6_DEFROUTE=no
# IPV6_PEERDNS=no           # IPV6_DEFROUTE=no          # IPV4_FAILURE_FATAL=no    # IPV6_PEERDNS=no
# IPV6_PEERROUTES=yes       # IPV6_PEERDNS=no           # IPV6INIT=no              # IPV6_PEERROUTES=yes
# IPV6_FAILURE_FATAL=no     # IPV6_PEERROUTES=yes       # IPV6_AUTOCONF=no         # IPV6_FAILURE_FATAL=no
DEVICE=br0                  # IPV6_FAILURE_FATAL=no     # IPV6_DEFROUTE=no         DEVICE=br3
                            DEVICE=br1                  # IPV6_PEERDNS=no
                                                        # IPV6_PEERROUTES=yes
                                                        #IPV6_FAILURE_FATAL=no
                                                        DEVICE=br2

NAME=enp0s20f0              NAME=enp0s20f1              NAME=enp0s20f2             NAME=enp0s20f3
HWADDR="ab:cd:ef:gh:ij:kl"  HWADDR=ab:cd:ef:gh:ij:mn    HWADDR=ab:cd:ef:gh:ij:op   HWADDR=ab:cd:ef:gh:ij:qr
UUID="[...]"                UUID=[...]                  UUID=[...]                 UUID=[...]
TYPE=Ethernet               TYPE=Ethernet               TYPE=Ethernet              TYPE=Ethernet
BOOTPROTO=none              BOOTPROTO=none              BOOTPROTO=none             BOOTPROTO=none
ONBOOT=yes                  ONBOOT=yes                  ONBOOT=yes                 ONBOOT=yes
BRIDGE=br0                  BRIDGE=br1                  BRIDGE=br2                 BRIDGE=br3
NM_CONTROLLED=no            NM_CONTROLLED=no            NM_CONTROLLED=no           NM_CONTROLLED=no
# PERSISTENT_DHCLIENT=1     # DEFROUTE=no               # DEFROUTE=no              # DEFROUTE=no
# DEFROUTE=no               # PEERDNS=yes               # PEERDNS=yes              # PEERDNS=yes
# PEERDNS=yes               # PEERROUTES=yes            # PEERROUTES=yes           # PEERROUTES=yes
# PEERROUTES=yes            # IPV4_FAILURE_FATAL=no     # IPV4_FAILURE_FATAL=no    # IPV4_FAILURE_FATAL=no
# IPV4_FAILURE_FATAL=yes    # IPV6INIT="no"             # IPV6INIT=no              # IPV6INIT=no
# IPV6INIT=no               # IPV6_AUTOCONF=no          # IPV6_AUTOCONF=no         # IPV6_AUTOCONF=no
# IPV6_AUTOCONF=no          # IPV6_DEFROUTE=yes         # IPV6_DEFROUTE=yes        # IPV6_DEFROUTE=yes
# IPV6_DEFROUTE=no          # IPV6_PEERDNS=yes          # IPV6_PEERDNS=yes         # IPV6_PEERDNS=yes
# IPV6_PEERDNS=yes          # IPV6_PEERROUTES=yes       # IPV6_PEERROUTES=yes      # IPV6_PEERROUTES=yes
# IPV6_PEERROUTES=yes       # IPV6_FAILURE_FATAL=no     # IPV6_FAILURE_FATAL=no    # IPV6_FAILURE_FATAL=no
# IPV6_FAILURE_FATAL=no     DEVICE=enp0s20f1            DEVICE=enp0s20f2           DEVICE=enp0s20f3
DEVICE=enp0s20f0

All ip route and all ifconfig / ip addr are returning the correct values, except for eth0 (guest).
On running ifup eth0 the guest trys to get an ip address (DHCPDISCOVER on eth0 to 255.255.255.255 port 67 interval [...]) and ens with No DHCPOFFERS received.

I'm happy about every idea...
Comment: Does your ISP actually provide a public IP via DHCP over Ethernet? If you unplug the cable into `enp0s20f0` and plug that cable into something else which requests a DHCP address, does it work?
Comment: Ah yes my ISP gives me a public IP over DHCP and this works on other devices and even on the host system, when I use a apt network-script for ```enp0s20f0```
Comment: If you don't intend for the interface to be configured with its own IP on the _host_, then you should use macvtap instead of a bridge.
Comment: No Michael, he was just testing on the host. He wants the public IP to be on the router VM.
Comment: It's possble that your ISP's device doesn't give DHCP addresses to a MAC address which is not directly connected to it. You'd need to call your ISP to confirm this. If so, you could use ebtables to spoof the MAC of the VM, like this: https://wiki.debian.org/BridgeNetworkConnections
Comment: Thank you for your ideas. @suprjami: this sounds good. I'll check this soon and report the result ;) @ MichaelHampton: I didn't heared of macvtap before. I'll test this if it isn't the mac-problem
Comment: @suprjami: Thank you :D I never would have thought of something like that. How can I thank you? :D

I edited the vm via virsh and wrote the LAN interfaces MAC address into the guests bridge with virsh. After some reboots and reconnects it worked :D
Comment: Cool, glad to hear it's all working fine. I added my comment as an Answer, feel free to mark its as correct and upvote :)
Answer: It's possble that your ISP's device doesn't give DHCP addresses to a MAC address which is not directly connected to it. You'd need to call your ISP to confirm this.
If so, you could use ebtables to spoof the MAC of the VM, like this:
http://wiki.debian.org/BridgeNetworkConnections


Using delprof in command prompt remotly. Which user will it be run as if no user is specified?

Question: If i use delprof2 and cmd to remotly delete profiles, which user would this be run under if no other user is given?
Many thanks
Dan
Answer: If you run something as yourself and try connect to a remote computer, Windows will normally use your account permissions. The two common ways around this are if the program has a place to give specific login details then do that, or for you to run the program as another account using Run As.
I expect delprof2 is no exception, but I haven't used it.
Comment: Thanks. Does this mean that if i give the technician user that we will be using the correct privilidge then it should run?
Comment: Yes, I think so, but I don't know what those would be; from reading about it, it can edit system level registry entries as part of the delete, as well as clearing the filesystem.
Answer: As TessellatingHeckler stated in his answer, a Windows application runs under the context of the user who launches the application, unless configured otherwise via credentials options in the application, or by using Run As.
Note that I'm not referring to system components, services, or web applications here, I'm only referring to applications launched interactively by a user.


How can I determine a general formula for the nth derivative of any continuous function $f(x)$ differentiable at least $n$ times?

Question: I know how to do it with easier functions, but is there a universal method which can be applied to all continuous functions differentiable at least $n$ times(introduced to in a second year calculus class)?
I can do it for easy ones like $\sin(x)$ and $\cos(x)$, but $\sin(x^2)$ and $\tan(x)$ and $\ln(1+x^2)$ are proving to be very difficult.
Thanks.
Answer: There are four parts in this answer.
Part I
The Faa di Bruno formula (see Theorem 11.4 in the book [1] and Theorem C on page 139 in the monograph [2] below) can be described in terms of the Bell polynomials of the second kind $B_{n,k}\bigl(x_1,x_2,\dotsc,x_{n-k+1}\bigr)$ by
\begin{equation}\label{Bruno-Bell-Polynomial}\tag{1}
\frac{\textrm{d}^n}{\textrm{d}x^n}f\circ h(x)=\sum_{k=0}^nf^{(k)}(h(x)) B_{n,k}\bigl(h'(x),h''(x),\dotsc,h^{(n-k+1)}(x)\bigr), \quad n\ge0.
\end{equation}
In Theorem 5.1 of the paper [3] and Section 3 of the paper [4] below, it was found that
\begin{equation}\label{Bell-x-1-0-eq}\tag{2}
B_{n,k}(x,1,0,\dotsc,0)
=\frac{1}{2^{n-k}}\frac{n!}{k!}\binom{k}{n-k}x^{2k-n}, \quad n\ge k\ge0,
\end{equation}
where $\binom{0}{0}=1$ and $\binom{p}{q}=0$ for $q>p\ge0$. Consequently, as an example, we have
\begin{equation*}
\Bigl(e^{x^2}\Bigr)^{(n)} =e^{x^2}\frac{n!}{(2x)^n} \sum_{k=0}^{n}\binom{k}{n-k}\frac{(2x)^{2k}}{k!}, \quad n\ge0.
\end{equation*}
Similarly, by virtue of the formulas \eqref{Bruno-Bell-Polynomial} and \eqref{Bell-x-1-0-eq}, general formulas for the $n$th derivatives of the functions $\sin\bigl(x^2\bigr)$ and $\ln\bigl(1+x^2\bigr)$ can be derived readily as
\begin{equation}\tag{+}
\bigl[\sin\bigl(x^2\bigr)\bigr]^{(n)}
=\frac{n!}{(2x)^n}\sum_{k=1}^n\binom{k}{n-k}\frac{(2x)^{2k}}{k!} \sin\biggl(x^2+\frac{k\pi}{2}\biggr), \quad n\ge0
\end{equation}
and
\begin{equation}\tag{#}
\bigl[\ln\bigl(1+x^2\bigr)\bigr]^{(n)}
=\frac{n!}{(2x)^n}\sum_{k=1}^n\binom{k}{n-k}\frac{(-1)^{k-1}}{k}\frac{(2x)^{2k}}{(1+x^2)^{k}}, \quad n\ge1.
\end{equation}
Part II
In Theorem 1.2 of the paper [5] below, it was derived that
\begin{multline}\label{bell-sin-eq}\tag{3}
B_{n,k}\biggl(-\sin x,-\cos x,\sin x,\cos x,\dotsc, \cos\biggl[x+\frac{(n-k+1)\pi}{2}\biggr]\biggr)\\
=\frac{(-1)^k\cos^kx}{k!}\sum_{\ell=0}^k\binom{k}{\ell}\frac{(-1)^\ell}{(2\cos x)^\ell}
\sum_{q=0}^\ell\binom{\ell}{q}(2q-\ell)^n \cos\biggl[(2q-\ell)x+\frac{n\pi}2\biggr]
\end{multline}
and
\begin{multline}\label{bell-sin=ans}\tag{4}
B_{n,k}\biggl(\cos x,-\sin x,-\cos x,\sin x,\dotsc, \sin\biggl[x+\frac{(n-k+1)\pi}{2}\biggr]\biggr)\\
=\frac{(-1)^k\sin^{k}x}{k!}\sum_{\ell=0}^k\binom{k}{\ell}\frac1{(2\sin x)^{\ell}}
\sum_{q=0}^\ell(-1)^q\binom{\ell}{q}(2q-\ell)^n \cos\biggl[(2q-\ell)x+\frac{(n-\ell)\pi}2\biggr]
\end{multline}
for $n\ge k\ge0$. Since $\sin\bigl(x\pm\frac{\pi}{2}\bigr)=\pm\cos x$ and $\cos\bigl(x\pm\frac{\pi}{2}\bigr)=\mp\sin x$, the formulas \eqref{bell-sin-eq} and \eqref{bell-sin=ans} are equivalent to each other.
These two formulas \eqref{bell-sin-eq} and \eqref{bell-sin=ans} can be applied to establish general formulas of the $n$th derivatives for functions of the types $f(\sin x)$ and $f(\cos x)$, such as $\sin^\alpha x$, $\cos^\alpha x$, $\sec^\alpha x$, $\csc^\alpha x$, $e^{\pm\sin x}$, $e^{\pm\cos x}$, $\ln\cos x$, $\ln\sin x$, $\ln\sec x$, $\ln\csc x$, $\sin\sin x$, $\cos\sin x$, $\sin\cos x$, $\cos\cos x$, $\tan x=-(\ln\cos x)'$, and $\cot x=(\ln \sin x)'$, if the general formula for the $n$th derivative of $f$ is computable.
Part III
Define the falling factorial of $\alpha\in\mathbb{C}$ by
\begin{equation*}%\label{Fall-Factorial-Dfn-Eq}
\langle\alpha\rangle_n=
\prod_{k=0}^{n-1}(\alpha-k)=
\begin{cases}
\alpha(\alpha-1)\dotsm(\alpha-n+1), & n\ge1;\\
1,& n=0.
\end{cases}
\end{equation*}
In Remark 3.1 on page 88 in the paper [17] below, the formula
\begin{equation}\label{Bell-1-lambda}\tag{5}
B_{n,k}\Biggl(1, 1-\lambda, (1-\lambda)(1-2\lambda),\dotsc, \prod_{\ell=0}^{n-k}(1-\ell\lambda)\Biggr)
=\frac{(-1)^k}{k!} \sum_{\ell=0}^k (-1)^{\ell} \binom{k}{\ell} \prod_{q=0}^{n-1}(\ell-q\lambda)
\end{equation}
for $\lambda\in\mathbb{C}$ and $n\ge k\ge0$ was concluded. In Theorem 2.1 on page 165 in the paper [11] below, it was discovered that
\begin{equation}\label{Bell-fall-Eq}\tag{6}
B_{n,k}(\langle\alpha\rangle_1, \langle\alpha\rangle_2, \dotsc,\langle\alpha\rangle_{n-k+1})
=\frac{(-1)^k}{k!}\sum_{\ell=0}^{k}(-1)^{\ell}\binom{k}{\ell}\langle\alpha\ell\rangle_n
\end{equation}
for $\alpha\in\mathbb{C}$ and $n\ge k\ge0$. These two formulas \eqref{Bell-1-lambda} and \eqref{Bell-fall-Eq} are equivalent to each other.
By virtue of the Faa di Bruno formula \eqref{Bruno-Bell-Polynomial} and any one of the formulas \eqref{Bell-1-lambda} and \eqref{Bell-fall-Eq}, one can establish general formulas of the $n$th derivatives for functions of the type $f(x^\alpha)$ for $\alpha\in\mathbb{R}$, such as $e^{x^\alpha}$, $\sin[(a+bx)^\alpha]$, and $\ln(1\pm x^\alpha)$, if the $n$th derivative of the function $f$ is computable.
Part IV
The $n$th derivative formulas for the tangent function $\tan x=\dfrac{\sin x}{\cos x}$ and the cotangent function $\cot x=\dfrac{\cos x}{\sin x}$ can also be computed by the formula
\begin{equation}\label{Sitnik-Bourbaki}\tag{7}
\frac{\textrm{d}^k}{\textrm{d}z^k}\biggl(\frac{u}{v}\biggr)
=\frac{(-1)^k}{v^{k+1}}
\begin{vmatrix}
u & v & 0 & \dotsm & 0\\
u' & v' & v & \dotsm & 0\\
u'' & v'' & 2v' & \dotsm & 0\\
\dotsm & \dotsm & \dotsm & \ddots & \dotsm\\
u^{(k-1)} & v^{(k-1)} & \binom{k-1}1v^{(k-2)} &  \dots & v\\
u^{(k)} & v^{(k)} & \binom{k}1v^{(k-1)} & \dots & \binom{k}{k-1}v'
\end{vmatrix}.
\end{equation}
For details on the formula \eqref{Sitnik-Bourbaki}, please refer to https://math.stackexchange.com/a/4261705/945479.
The texts in the first three parts above are extracted and modified from Sections 1.3, 1.4, and 1.6 in the paper [6] below.
References

C. A. Charalambides, Enumerative Combinatorics, CRC Press Series on Discrete Mathematics and its Applications. Chapman & Hall/CRC, Boca Raton, FL, 2002.
L. Comtet, Advanced Combinatorics: The Art of Finite and Infinite Expansions, Revised and Enlarged Edition, D. Reidel Publishing Co., 1974; available online at https://doi.org/10.1007/978-94-010-2196-8.
F. Qi and B.-N. Guo, Explicit formulas for special values of the Bell polynomials of the second kind and for the Euler numbers and polynomials, Mediterr. J. Math. 14 (2017), no. 3, Art. 140, 14 pages; available online at https://doi.org/10.1007/s00009-017-0939-1.
F. Qi and M.-M. Zheng, Explicit expressions for a family of the Bell polynomials and applications, Appl. Math. Comput. 258 (2015), 597--607; available online at https://doi.org/10.1016/j.amc.2015.02.027.
F. Qi, Derivatives of tangent function and tangent numbers, Appl. Math. Comput. 268 (2015), 844--858; available online at https://doi.org/10.1016/j.amc.2015.06.123.
Feng Qi, Da-Wei Niu, Dongkyu Lim, and Yong-Hong Yao, Special values of the Bell polynomials of the second kind for some sequences and functions, Journal of Mathematical Analysis and Applications 491 (2020), no. 2, Paper No. 124382, 31 pages; available online at https://doi.org/10.1016/j.jmaa.2020.124382.
Bai-Ni Guo, Dongkyu Lim, and Feng Qi, Series expansions of powers of arcsine, closed forms for special values of Bell polynomials, and series representations of generalized logsine functions, AIMS Mathematics 6 (2021), no. 7, 7494--7517; available online at https://doi.org/10.3934/math.2021438.
Bai-Ni Guo, Dongkyu Lim, and Feng Qi, Maclaurin's series expansions for positive integer powers of inverse (hyperbolic) sine and tangent functions, closed-form formula of specific partial Bell polynomials, and series representation of generalized logsine function, Applicable Analysis and Discrete Mathematics 16 (2022), no. 2, in press; available online at https://doi.org/10.2298/AADM210401017G.
Feng Qi and Dongkyu Lim, Closed formulas for special Bell polynomials by Stirling numbers and associate Stirling numbers, Publications de l'Institut Mathematique (Beograd) 108 (2020), no. 122, 131--136; available online at https://doi.org/10.2298/PIM2022131Q.
Feng Qi, Pierpaolo Natalini, and Paolo Emilio Ricci, Recurrences of Stirling and Lah numbers via second kind Bell polynomials, Discrete Mathematics Letters 3 (2020), 31--36.
Feng Qi, Da-Wei Niu, Dongkyu Lim, and Bai-Ni Guo, Closed formulas and identities for the Bell polynomials and falling factorials, Contributions to Discrete Mathematics 15 (2020), no. 1, 163--174; available online at https://doi.org/10.11575/cdm.v15i1.68111.
Feng Qi, Dongkyu Lim, and Bai-Ni Guo, Explicit formulas and identities for the Bell polynomials and a sequence of polynomials applied to differential equations, Revista de la Real Academia de Ciencias Exactas Fisicas y Naturales Serie A Matematicas 113 (2019), no. 1, 1--9; available online at https://doi.org/10.1007/s13398-017-0427-2.
Feng Qi, Dongkyu Lim, and Yong-Hong Yao, Notes on two kinds of special values for the Bell polynomials of the second kind, Miskolc Mathematical Notes 20 (2019), no. 1, 465--474; available online at https://doi.org/10.18514/MMN.2019.2635.
Feng Qi, Da-Wei Niu, and Bai-Ni Guo, Some identities for a sequence of unnamed polynomials connected with the Bell polynomials, Revista de la Real Academia de Ciencias Exactas Fisicas y Naturales Serie A Matematicas 113 (2019), no. 2, 557--567; available online at https://doi.org/10.1007/s13398-018-0494-z.
A.-M. Xu and G.-D. Cen, Closed formulas for computing higher-order derivatives of functions involving exponential functions, Appl. Math. Comput. 270 (2015), 136--141; available online at https://doi.org/10.1016/j.amc.2015.08.051.
A.-M. Xu and Z.-D. Cen, Some identities involving exponential functions and Stirling numbers and applications, J. Comput. Appl. Math. 260 (2014), 201--207; available online at https://doi.org/10.1016/j.cam.2013.09.077.
Bai-Ni Guo and Feng Qi, Viewing some ordinary differential equations from the angle of derivative polynomials, Iranian Journal of Mathematical Sciences and Informatics 16 (2021), no. 1, 77--95; available online at https://doi.org/10.29252/ijmsi.16.1.77.
Answer: The functions that you list, $\sin(x^2)$ and $\tan(x)$ and $\ln(1+x^2)$ are indeed infinitely many times differentiable, you just need to learn differentiation rules, e.g. product, quotient, chain, power rule, etc, and differentiate these functions as many times  as you wish (and, perhaps, in some cases find a general formula for the $n$th derivative).
Well, for some functions it will indeed be difficult to find a general formula. You may take the first few derivatives, and try to guess the formula for the $n$th derivative in each specific case. If you guess is correct, then you may prove it by induction.
Comment: "as Suzu indicated there are continuous functions that are not differentiable" - he has already fixed that mistake.
Answer: No there is no universal method for differentiating functions, if you want to get other functions out. If you reduce it to a Taylor series, then you can do that, but the output of the process is another Taylor series.
Answer: Find the Taylor series, and use that to evaluate at the nth value?
Comment: To find the taylor series, I would need to evaluate the nth derivative in the first place...
Comment: Not necessarily, you can work out Taylor series of many functions without differentiation.
Comment: Try substitutions of the Taylor series of known polynomials, and use that the find the nth derivative?
Answer: Consider e.g. the Elementary functions, the Liouvillian functions, some of the Special functions and/or algebraic operations.
The set of the function terms of the Elementary functions is closed regarding differentiation.
The set of the function terms of the Liouvillian functions is closed regarding differentiation.
Let $m,n\in\mathbb{N}_0$ denote variables.
Some functions have an $n$-th derivative that is equal to its $m$-th derivative.
There are rules for the $n$-th derivative of some elementary standard functions. See e.g. Bronshtein/Semendyayev/Musiol/Mühlig: Handbook of Mathematics, Springer, table 6.3.
As for the first derivative, there are higher sum rule, higher factor rule, higher product rule (General Leibniz rule) and higher chain rule (Faà di Bruno's formula) to calculate the $n$-th derivatives.
You have to build your given function term hierarchically from smaller function terms and algebraic operations (unary or multiary algebraic functions) to apply the higher differentiation rules above.
$sin(x^2)$ and $ln(1+x^2)$ can be represented as compositions.
$tan(x)=\frac{sin(x)}{cos(x)}$ can be represented as quotient.
Apply higher chain rule and higher quotient rule respectively and hope that the smaller function terms have known general terms for their n-th derivatives.
In 2012, I wrote a still unpublished article "On partial Bell polynomials for the higher derivatives of composed functions".
Comment: Isn't my answer worth to be upvoted?


TensorFlow KeyError Input_1

Question: I am trying to make retraining Tensorflow MobileNetV2 but I am getting a Keyerror Input_1 when I run below code
for test_image, test_label in train_dataset.take(1):break

print(base_model(test_image).shape)

Error Log
Any Solution much appreciated. Thank you
Comment: Please copy & paste the error message rather then making screenshots.
Answer: In the input tensor, add name attribute and set it to Input_1.
Comment: `input_layer =  tf.keras.layers.Input(shape=image_shape, batch_size=None, name = "image")` You mean this one ? please helpme @Abhishek Verma

TensorFlow KeyError Input_1


Linking webview with another activity

Question: My problem is a link that i create in webview didn't work, and then when i click it, it wont go to another Activity, so where's my error?
Help, please!!! Thank you
prknln1.loadDataWithBaseURL("file:///android_asset",Perkenalan,"text/html","utf-8",null);
        prknln1.setWebViewClient(new WebViewClient() {
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                Intent i;
                {
                    if (url.equalsIgnoreCase("TabHiragana")) {
                        i = new Intent(getApplicationContext(), TabHiragana.class);
                        startActivity(i);
                    } else if (url.equalsIgnoreCase("TabKatakana")) {
                        i = new Intent(getApplicationContext(), TabKatakana.class);
                        startActivity(i);
                    } else if (url.equalsIgnoreCase("Kanji")) {
                        i = new Intent(getApplicationContext(), List_Kanji.class);
                        startActivity(i);
                    }
                }
                Log.e("URL", "URL" + url);
                return true;
            }
        });

Comment: Your question is not clear
Comment: i create link to another activity in webview, when i use loadData it works, but when i change it to loadDataWithBaseURL it doesn't work, and there's no error warning. So where's the problem about my code... Thank you
Comment: what you are getting in `Log.e("URL", "URL" + url);` in logs when clicking on link inside webView?
Comment: i'm sorry, i didn't run it on emulator but in my cellphone, so i didn't know what i got in logs. But now my problem has been solved, i only change equalsIgnoreCase with contains. Thank you for ur time... :)
Answer: I think you will be checking the particular word in the url, for that you need to use contains method.
prknln1.loadDataWithBaseURL("file:///android_asset",Perkenalan,"text/html","utf-8",null);
        prknln1.setWebViewClient(new WebViewClient() {
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                Intent i;
                {
                    if (url.contains("TabHiragana")) {
                        i = new Intent(getApplicationContext(), TabHiragana.class);
                        startActivity(i);
                    } else if (url.contains("TabKatakana")) {
                        i = new Intent(getApplicationContext(), TabKatakana.class);
                        startActivity(i);
                    } else if (url.contains("Kanji")) {
                        i = new Intent(getApplicationContext(), List_Kanji.class);
                        startActivity(i);
                    }
                }
                Log.e("URL", "URL" + url);
                return true;
            }
        });

Comment: i'll try, but when i use loadData only on first line it works, but when i use loadDataWithBaseURL why it doesn't work?? Can you explain it... thank you Mr. Kumar
Comment: with loadData(String data, String mimeType, String encoding) we can't able to specify the base url, but with loadDataWithBaseURL(String baseUrl, String data, String mimeType, String encoding, String historyUrl) we can able to specify the base url. For example  path to asset folder.
Comment: yeayyy!!!... It works. Thank you, but
What's the different between contains and equalsIgnoreCase?
Comment: **contains** will check whether  that particular string is present or not(it may be a part of the string), but the **equalsIgnoreCase** will try to match complete strings by ignoring the case.
Comment: contains() checks if a String contains another String while equalsIgnoreCase() checks if two Strings are equal. That was your issue
Answer: To open an activity and pass a parameter to it:
In your text data (myText), have the url:
"" + word + ""

Load data:
webView.loadDataWithBaseURL("file:///android_asset", myText, "text/html", "utf-8", null);

setWebViewClient:
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (url.startsWith("file")) {
                    Intent intent = new Intent(MyActivity.this, MyActivity.class);
                    intent.putExtra("word", Uri.parse(url).getLastPathSegment());
                    startActivity(intent);
                    return true;
                } else
                    return false;
            }
        });

Linking webview with another activity


Showing Database call result in Struts 2

Question: Short Question, Is it possible to make a database call in the first load of home page using Struts 2? I have this old project of mine, just a simple online shop(wasn't able to finish it though) and i recalled that i was having a hard time with my home page outputting products listed in the database since struts needed to trigger an action before doing anything. Can you like preload some actions before proceeding to the home JSP? I'm a beginner in struts and could just do simple redirect and other basic actions.
Comment: trigger the action on the page load..
Comment: i think i figured out what i really need. Have to make a ServletContextListener for it to initialize data while deploying the app
Comment: Action -> JSP. Not other way around.
Answer: You have many ways to do it. But most easiest way is mapping a action with the home page URL. Action class should do whatever database loading or other logic and forward to the JSP page.
Answer: Use a list method with s:iterator on your home.jsp.
Answer: You can use the s:action tag in your home page. There are 2 different ways it could be approached.

the only thing in your home page is the <s:action/> tag and let it render the result of the action: executeResult="true" attribute.
specify the var="myaction" attribute and set executeResult="false".  You can then access everything from the action through the var name.  for example <s:property value="%{myaction.myproperty}"/>

The docs for the s:action tag can be found here: https://struts.apache.org/docs/action.html


$AG,AF$ are perpendiculars to the internal bisectors $CG,BF$ and $GF$ extended intersects $AB,AC$ at $H,I$

Question: In the figure $AG,AF$ are perpendiculars to the internal bisectors $CG,BF$ and GF extended  intersects $AB,AC$ at $H,I$ respectively.Find $5GF-HI$ if $c=AB=7,a=BC=8,b=CA=5$
I know we can calculate the internal bisectors length by stewarts formula as $$BD=\frac{2\sqrt{s(s-b)}}{a+c}$$ And similarly for the other  bisector.From here we can also calculate $AF,AG$.I am stuck otherwise..it  looks like $GF$ is parallel to $BC$ but  i cant prove it..
Answer: Extend $AF$ and $AG$ until it touches $BC$.

Since $CG, BF$ bisects $\angle ACB$ and $\angle ABC$, and $AF \perp BF$, $AG \perp GC$:
$\triangle AGC \cong \triangle G'GC$ and $\triangle AFB \cong \triangle F'FB$ by considering common sides and AAS.
Hence $BF'=7, CG'= 5$ and $F,G$ are midpoints of $AF', AG'$ respectively.
By midpoint/midline theorem, $FG // F'G'$ and $FG = \frac12 F'G' = \frac12(8-(8-7)-(8-5))=2$.
By considering the parallel lines, similar triangles and using midpoint/midline theorem again, we see that $HI$ is also half of $BC$, giving $HI = 4$. Therefore $5GF - HI =6$.


Table doesn't render on ajax command

Question: I have a function that returns a render array for a table;
  private function _files_table($job_id){
    $files = $this->_query("
      select *
      from JC_Documents_Recent_Revisions
      where Job_ID=".$this->sqs($job_id).";
    ");

    $rows = array_map(function($row){
      return [
        (string)$row['Job_ID'],
        $row['Document_Name'],
        $row['Document_Type'],
        $row['File_Name'],
        ($row['Uploaded_Date'] != NULL ? $row['Uploaded_Date']->format("Y-m-d H:i") : 'Unknown Date'),
        $row['Uploaded_By'],
        new FormattableMarkup('show', [':link' => (Url::fromRoute('JobFileUpload.Serve', ['file_id' => (int)$row['FileID']]))->toString()]),
        new FormattableMarkup('revise', [':link' => (Url::fromRoute('JobFileUpload.Revise', ['file_id' => (int)$row['FileID']]))->toString()]),
        new FormattableMarkup('delete', [':link' => (Url::fromRoute('JobFileUpload.Delete', ['document_id' => (int)$row['DocumentID']]))->toString()])
      ];
    }, $files);

    $header = [
      t('Job ID'),
      t('Document Name'),
      t('Document Type'),
      t('File Name'),
      t('Uploaded Date'),
      t('Uploaded By'),
      t('Download'),
      t('Revise'),
      t('Delete')
    ];

    return [
      '#theme' => 'table',
      '#header' => $header,
      '#rows' => $rows
    ];
  }

and two occasions where I wish to render the table. The first is in buildForm:
  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state, $job_id=NULL) {
    $jobs = $this->_query("
      select *
      from Active_Job_List;
    ");

    $formatted_jobs = [];
    $len = count($jobs);
    for($i=0; $i<$len; $i++){
      $formatted_jobs[$jobs[$i]['Job_ID']] = $jobs[$i]['Job_Name'];
    }
    natsort($formatted_jobs);

    $form['job_id'] = [
      '#weight' => 1,
      '#title' => t('Job'),
      '#type' => 'select',
      '#options' => $formatted_jobs,
      '#ajax' => [
        'callback' => '::showFiles',
        'wrapper' => 'ajax-wrapper'
      ],
      '#required' => TRUE,
      '#default_value' => $job_id
    ];

    $form['jobfiles'] = $this->_files_table($job_id);
    $form['jobfiles']['#weight'] = 2;

    if($job_id != null){
      $form['newfile'] =  [
        '#weight' => 3,
        '#title' => t('Upload new file'),
        '#type' => 'link',
        '#url' => Url::fromRoute('JobFileUpload.UploadForm', ['job_id' => $job_id])
      ];
    }

    return $form;
  }

The second is in showFiles:
  public function showFiles(array &$form, FormStateInterface $form_state) {
    $job_id = $form_state->getValue('job_id');

    $output = $this->_files_table((int)$job_id);
    // $output['link'] = new FormattableMarkup('Upload a new file...', [':link' => (Url::fromRoute('JobFileUpload.UploadForm', ['job_id' => $job_id]))->toString()]);

    $renderer = \Drupal::service('renderer');

    $response = new AjaxResponse();
    $response->addCommand(new HtmlCommand('#ajax-wrapper', $renderer->render($output)));

    return $response;
  }

The buildForm method works just fine, and I get a table with the files in it. But when I call the same render array function on an output for the AjaxResponse (in ::showFiles), I don't even get an error, and the table does not show up. Anyone got an idea of what I'm doing wrong here?
Answer: I think the problem was not specifying an id attribute for my table when I first render it, so there was nothing to replace.
This seems to work:
  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state, $job_id=NULL) {
    $jobs = $this->_query("
      select *
      from Active_Job_List;
    ");

    $formatted_jobs = [];
    $len = count($jobs);
    for($i=0; $i<$len; $i++){
      $formatted_jobs[$jobs[$i]['Job_ID']] = $jobs[$i]['Job_Name'];
    }
    natsort($formatted_jobs);

    $form['job_id'] = [
      '#weight' => 1,
      '#title' => t('Job'),
      '#type' => 'select',
      '#options' => $formatted_jobs,
      '#ajax' => [
        'callback' => '::showFiles',
        'wrapper' => 'ajax-wrapper'
      ],
      '#required' => TRUE,
      '#default_value' => $job_id
    ];

    $form['jobfiles'] = $this->_files_table($job_id);
    $form['jobfiles']['#weight'] = 2;

    if($job_id != null){
      $form['newfile'] =  [
        '#weight' => 3,
        '#title' => t('Upload new file'),
        '#type' => 'link',
        '#url' => Url::fromRoute('JobFileUpload.UploadForm', ['job_id' => $job_id]),
        '#attributes' => [
          'id' => ['new-file']
        ]
      ];
    }

    return $form;
  }

  public function showFiles(array &$form, FormStateInterface $form_state) {
    $job_id = $form_state->getValue('job_id');
    // $form_state->setRedirectUrl(Url::fromRoute('JobFileUpload.OverviewWithJobId', ['job_id' => $job_id]));

    $table = $this->_files_table((int)$job_id);
    $link = [
      '#type' => 'markup',
      '#markup' => new FormattableMarkup('Upload a new file...', [':link' => (Url::fromRoute('JobFileUpload.UploadForm', ['job_id' => $job_id]))->toString()
      ])
    ];
    $renderer = \Drupal::service('renderer');

    $response = new AjaxResponse();
    $response->addCommand(new HtmlCommand('#ajax-wrapper', $renderer->render($table)));
    $response->addCommand(new HtmlCommand('#new-file', $renderer->render($link)));

    return $response;
  }

Table doesn't render on ajax command


Is there a term for when a soloist plays a passage, followed by the tutti repeating it?

Question: I was listening to Weber's Turandot Overture. A flute (or piccolo?) plays a theme, and then the entire orchestra plays the same thing. Is there a name for this?
Comment: chanting, maybe? there is a word for it in other languages I know, but I can't translate it to english.
Comment: Copycat :-)  .   How about "call and response"
Comment: In call and response, the response is an answer to the call, not merely a repeat. (Call= Shave and a haircut, response= six bits)
Answer: More common in a solo concerto, this is a "tutti repeat" or "orchestral repetition", where the entire orchestra echos the statement of a melodic subject in the solo.
Answer: No special term, beyond variations on the (perfectly clear) description you've already given.  'The theme is stated by solo flute, then repeated by full orchestra.'


What are the non-identity symmetries of the determinant in $\mathbb{R}^{n \times n}$?

Question: I am curious if the determinant has any symmetries (i.e. transformational invariants). That is mappings $f: \mathbb{R}^{n \times n} \mapsto \mathbb{R}^{n \times n}$ such that
$$\det (f(X)) = \det (X)$$
notwithstanding the identity map. The map $f$ doesn't necessarily need to be representations or actions of well-known algebraic structures such as groups.
Neither Wikipedia or MathWorld give any examples.
What are the non-identity symmetries of the determinant in $\mathbb{R}^{n \times n}$?
Comment: Any mapping with determinant 1 should suffice.
Comment: @ilikemath Ah right, I forgot about the $\det (AX ) = \det (A) \det (X)$ property! Thanks. Feel free to post this as an answer so I can give you credit.
Answer: The determinant is invariant under transpose $X \mapsto X^T$ and under conjugation / similarity $X \mapsto AXA^{-1}$. These are probably the most well-known examples and are distinguished by the fact that they play the most nicely with multiplication: transpose reverses multiplication and conjugation preserves it. (And Wikipedia mentions this fact about the transpose. And about conjugation but you have to scroll down further.) (And Mathworld mentions both of these facts as well.)
More generally the determinant is invariant under $X \mapsto AXB$ as long as $\det(A) \det(B) = 1$; this describes all linear maps leaving the determinant invariant. Most of these don't play nicely with multiplication though. This includes row and column operations as a special case (except the ones involving multiplying by a scalar), which is a common thing to play around with when evaluating determinants.
Much dumber examples preserving even less structure are possible, especially if you don't require $f$ to be invertible. For example, we can take $f(X)$ to be any block matrix of the form $\left[ \begin{array}{cc} \det(X) & 0 \\ 0 & g(X) \end{array} \right]$ where $g(X)$ is an arbitrary $(n-1) \times (n-1)$ matrix with determinant $1$. This isn't really good for anything, though, and in particular is totally unhelpful for evaluating determinants since we have to know what the determinant is already.


How can we get next month date in C# in scheduled backup case

Question: I'm trying to create a monthly backup setup. So if someone scheduled some particular date, then It should execute monthly on the same date.
If I have scheduled a backup at 31-Dec-2018, I want it to be executed on the same date of every month. In Jan will get 31 It's executed but In Feb what can we do, It's throwing an exception because 31 is not present in this month.
And what can we do for other months and how we get the next backup date?
I have tried using DateTime.Day property first gets the scheduled backup day and after that get the current day of this month and compare both if the current day is greater than an already scheduled day, then add one month in the current day which will be the next backup month otherwise next backup will happen in the current month.
DateTime scheduledDate = new DateTime(2019,1,31);
DateTime currentDate = DateTime.Now;

NextBackupdate  = currentDate;

int scDay = scheduledDate.Day;
int cDay = currentDate.Day;

if(cDay > scDay)
{
    NextBackupdate = NextBackupdate.AddMonths(1);
}

In this case, we can get the next month but how can we get the day.
Answer: you can execute the bukcup the last day of every month, I think it's more sense because in february you will have problem with 29, 30 and 31.
Look here one example to get the last day of current month
        var actualMonth = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);
        var nextMonth = actualMonth.AddMonths(1);
        var lastDayOfMonth = nextMonth.AddDays(-1);

Answer: You may find using a couple extension methods (or the underlying code) helps with getting the last day of any given DateTime. Take note of the DaysInMonth method:
///
/// Get last day of month based on date
///
/// <param name="value"></param>
/// <returns></returns>
public static DateTime LastDayOfMonth(this DateTime value)
{
    return new DateTime(value.Year, value.Month, DateTime.DaysInMonth(value.Year, value.Month));
}

///
/// Get the first day of month based on date
///
/// <param name="value"></param>
/// <returns></returns>
public static DateTime FirstDayOfMonth(this DateTime value)
{
    return new DateTime(value.Year, value.Month, 1);
}

So in your case to get the last day of next month you could simply write
NextBackupdate.FirstDayOfMonth().AddMonths(1).LastDayOfMonth();

Granted you would only have to do this if the day of the job is > 28.
Answer: Get the months from the original date to the current date and use that in the AddMonths()
DateTime scheduledDate = new DateTime(2019, 1, 31);
int months = ((DateTime.Now.Year - scheduledDate.Year) * 12) + DateTime.Now.Month - scheduledDate.Month;

DateTime nextbackupDate = scheduledDate.AddMonths(months);
Console.WriteLine(nextbackupDate.ToString());


Creating view on top of a subquery in mysql

Question: I have a query which fetches the max date time from on column and also the corresponding data of the other columns from the table. But for selecting the max date time I have to use a subquery so that i get the corresponding value of other columns. But since I have used a subquery with an alias I am unable to make a view on top of that. So can my query be modified to give me my desired result and also I am able to make my view with that query.
The sql query which I have made for my requierment is below.It gives me the desired result but I am unable to make a view on top of the query.Hence I am forced to make to separete views to get the desired result. Can the query be modified to give me the result and also I am able to make the view on top of the query.
SELECT SD.a_n, SD.t_c, SD.ppl, date_time FROM (SD JOIN (SELECT SD.t_c, MAX(date_time) AS MDT FROM SD GROUP BY t_c)wn_m_d_t ON (((SD.t_c = wn_m_d_t.t_c) AND (SD.date_time = wn_m_d_t.MDT)))) WHERE ((SD.t_c IN('drep','sred')))
Answer: Your query in a bit more readable format is:
SELECT SD.a_n, SD.t_c, SD.ppl, date_time
FROM SD JOIN
     (SELECT SD.t_c, MAX(date_time) AS MDT
      FROM SD
      GROUP BY t_c
     ) wn_m_d_t
     ON SD.t_c = wn_m_d_t.t_c AND SD.date_time = wn_m_d_t.MDT
WHERE SD.t_c IN ('drep', 'sred');

MySQL has a string restriction that views cannot contain subqueries in the from clause.  You seem to want to get the records in SD with the most recent date for each t_c.  Here is another approach:
SELECT SD.a_n, SD.t_c, SD.ppl, SD.date_time
FROM SD
WHERE SD.t_c IN ('drep', 'sred') AND
      NOT EXISTS (select 1
                  from sd sd2
                  where sd2.t_c = sd.t_c and
                        sd2.date_time > sd.date_time
                 );

And, this will work in a view.  Subqueries are allowed in the select and from clauses.
This says, "Get me all rows in SD where there is no record with the same t_c and a bigger date_time."
Comment: This query is giving the desired result but it is taking very long time to fetch the records. So is there any way to improve it's performance.
Comment: An index on `sd(t_c, date_time)` should help.
Comment: Already index is present on the table on the two columns. But still the query is taking long time.
Answer: I think this query is possible without using a subquery too.
SELECT SD.a_n, SD.t_c, SD.ppl, SD.date_time
FROM SD
LEFT JOIN SD AS sd2
 ON sd2.t_c = SD.t_c
 AND sd2.date_time > SD.date_time
WHERE SD.t_c IN ('drep', 'sred') AND sd2.t_c IS NULL


How to replace "default" with website domain name during drush user-login

Question: When I run drush user-login username, drush prints a url like http://default/user/reset/1/32323933.... How do I replace default with the actual website name?
Comment: Not tried it so posting a quick comment, the variable `site_name` is used to save the name of the site in Drupal 6, the command `drush vget site_name` would give out the same, so probably `drush vset site_name WHATEVER_NAME_TO_SET` should do the work...
Answer: You can use option --url:

-l <http://example.com:8888>,             URI of the drupal site to use (only needed in multisite environments or when running on an alternate port).
--uri=<http://example.com:8888>

$  drush uli -l yoursite.dev

Or create a record in your aliases.drushrc.php file:
$aliases['yoursite-dev'] = array(
  'root' => '/vhosts/yoursite.dev',
  'uri' => 'yoursite.dev',
);

Now you have an alias @yoursite-dev and can use it:
$ drush use @yoursite-dev
$ drush uli

Update:
Now I prefer to create sites/default/drushrc.php file for each Drupal folder:
<?php
$options['l'] = 'http://yoursite.dev';
$options['r'] = '/vhosts/yoursite.dev';

More info about drushrc.php: https://raw.githubusercontent.com/drush-ops/drush/8.x/examples/example.drushrc.php
Answer: I used this command for login into my local site:
drush uli --uri=http://your_local_url

Answer: You can set the uri in a drush site alias file to avoid getting http://default at the beginning of your password reset links.
ie. drush/sites/example.sites.yml
live:
   host: server.example.com
   user: user
   ssh: '-p 22'
   root: /home/user/public_html/docroot
   uri: 'http://example.com'
test:
   host: server2.example.net
   user: user2
   ssh: '-p 22'
   root: /home/user2/public_html/docroot
   uri: 'http://test.example.net'
dev:
   host: localhost
   user: docker
   root: /var/www/docroot
   uri: 'http://example.dev.example.com'

Then use the Drush site alias in the command for the password reset link:
drush @example.dev uli

The example after the @ symbol in the Drush site alias comes from the first part of the Drush site alias filename. The second part comes from the site entry in the file.
Answer: You could also export the environment variable DRUSH_OPTIONS_URI.
export DRUSH_OPTIONS_URI=http://example.com
Answer: I work with lando and I threw together the following function:
duli() {
    sitename=$(lando info|grep -E https|tail -n1|cut -d \' -f2)
    lando drush uli -l $sitename;
}


Como dar zoom em uma imagem ao passar o mouse em cima?

Question: Eu estou criando um site de tattoos que contém uma galeria de fotos. Eu gostaria que quando o usuário passasse o mouse por cima de uma imagem ela fosse ampliada para um tamanho maior.
Sou iniciante em montagem de sites, entendo um pouco de HTML e CSS; no entanto, não tenho conhecimento de JavaScript.
Comment: Tem uns plugins jQuery bem bacanas pra fazer essas coisas. Um dos mais interessantes que já ví é o [jQuery Zoom](http://www.jacklmoore.com/zoom/). Além de bonito e funcional a sua "instalação" é bem fácil, tem o passo-a-passo ali no site. Se tiver problemas avise.
Answer: Existem diversas formas de resolver seu problema, mesmo todas derivando de uma única. Pode usar soluções prontas - pesquisando no Google, encontrará várias bibliotecas livres e/ou pagas - ou criá-las do zero.
Aqui proponho um exemplo para que você possa trabalhar em cima. Ele apenas amplia/reduz a imagem sem grande beleza envolvida.

var entidade = document.getElementById('imagem');

// Altere o número para a apliação/redução desejada
var fator_lupa = 2;

entidade.onmouseover = function () { this.style.width = (this.clientWidth * fator_lupa) + "px"; };

entidade.onmouseout = function () { this.style.width = (this.clientWidth / fator_lupa) + "px"; };

Aqui tem um link do JSFiddle para exemplo do código em funcionamento no caso da pré-visualização do SOpt não funcionar: JSFiddle
Espero ter ajudado!
Answer: É possível fazer sem uso JavaScript, o que acho mais bacana. Usando a propriedade transform:scale do CSS3:
img {
    -webkit-transition: all 1s ease; /* Safari and Chrome */
    -moz-transition: all 1s ease; /* Firefox */
    -ms-transition: all 1s ease; /* IE 9 */
    -o-transition: all 1s ease; /* Opera */
    transition: all 1s ease;
}

img:hover {
    -webkit-transform:scale(1.25); /* Safari and Chrome */
    -moz-transform:scale(1.25); /* Firefox */
    -ms-transform:scale(1.25); /* IE 9 */
    -o-transform:scale(1.25); /* Opera */
     transform:scale(1.25);
}

Fonte com mais informações.
Answer: HTML:

CSS:
img:hover{
   height: 50%;
   width: 50%;
  }