Show $\cos \pi z=\prod\limits_{-\infty}^\infty \left(1-\frac{2z}{2n-1}\right) e^{\frac{2z}{2n-1}}$

Question: I have already shown $\cos \pi z=\prod\limits_{n=1}^{\infty}\left(1-\frac{4z^2}{(2n-1)^2}\right)$. Here is what I have after that,
\begin{equation*}\begin{split}
\cos(\pi z)   & = \prod_{n=1}^{\infty}\left(1-\frac{2z}{(2n-1)}\right)\left(1+\frac{2z}{(2n-1)}\right)\\
     & = \prod_{n=1}^{\infty}\left(1-\frac{2z}{(2n-1)}\right)\prod_{n=1}^{\infty}\left(1+\frac{2z}{(2n-1)}\right)\\
     & = \prod_{n=1}^{\infty}\left(1-\frac{2z}{(2n-1)}\right)\prod_{-\infty}^{n=-1}\left(1-\frac{2z}{(2n+1)}\right)\\
     & = \prod_{n=1}^{\infty}\left(1-\frac{2z}{(2n-1)}\right)\prod_{-\infty}^{n=0}\left(1-\frac{2z}{(2n-1)}\right)\\
     & = \prod_{n=-\infty}^{\infty}\left(1-\frac{2z}{(2n-1)}\right)
\end{split}\end{equation*}
I'm not sure where the exponential comes from.
Comment: It turns out that the exponential factors are absolutely necessary for convergence purposes.
Comment: you cannot split $\prod_{n=1}^{\infty}  \left(1-\frac{2z}{(2n-1)}\right)\left(1+\frac{2z}{(2n-1)}\right)$ into
$\prod_{n=1}^{\infty}\left(1-\frac{2z}{(2n-1)}\right)\prod_{m=1}^{\infty}\left(1+\frac{2z}{(2m-1)}\right)$ without checking that it converges, and it doesn't,
Comment: this is why you need the $e^{\frac{2z}{(2n-1)}}$ terms :
$\prod_{n=1}^{\infty}  \left(1-\frac{2z}{(2n-1)}\right)\left(1+\frac{2z}{(2n-1)}\right) $ $ = \prod_{n=1}^{\infty}\left(1-\frac{2z}{(2n-1)}\right)e^{\frac{2z}{(2n-1)}}\left(1+\frac{2z}{(2n-1)}\right)e^{-\frac{2z}{(2n-1)}} =$ $ \prod_{n=1}^{\infty}\left(1-\frac{2z}{(2n-1)}\right)e^{\frac{2z}{(2n-1)}}\prod_{m=1}^{\infty} \left(1+\frac{2z}{(2m-1)}\right)e^{-\frac{2z}{(2m-1)}} $
Answer: We have $$
\begin{align}
\csc\left(z\right)-\frac{1}{z}= &\sum_{k\in\mathbb{Z},\, k\neq0}\left(-1\right)^{k}\left(\frac{1}{k\pi}+\frac{1}{z-k\pi}\right) \\ = & \sum_{k\in\mathbb{Z},\, k\neq0}\left(\frac{1}{2k\pi}+\frac{1}{z-2k\pi}\right)-\sum_{k\in\mathbb{Z}}\left(\frac{1}{\left(2k-1\right)\pi}+\frac{1}{z-\left(2k-1\right)\pi}\right)
\end{align}$$ so if we integrate we have $$
\begin{align}
\left.\log\left(\frac{\tan\left(z/2\right)}{z}\right)\right|_{0}^{2x}= & \sum_{k=-\infty}^{\infty}\left.\left(\log\left(z-2k\pi\right)+\frac{z}{2k\pi}\right)\right|_{0}^{2x} \\ - & \sum_{k=-\infty}^{\infty}\left.\left(\log\left(z-\left(2k-1\right)\pi\right)+\frac{z}{\left(2k-1\right)\pi}\right)\right|_{0}^{2x}
\end{align}
 $$ then $$\frac{\sin\left(x\right)}{x\cos\left(x\right)}=\frac{\prod_{k=-\infty}^{\infty}\left(1-\frac{x}{\pi k}\right)\exp\left(\frac{x}{k\pi}\right)}{\prod_{k=-\infty}^{\infty}\left(1-\frac{2x}{\pi\left(2k-1\right)}\right)\exp\left(\frac{2x}{\pi\left(2k-1\right)}\right)}.
 $$ With the same method, from $$\cot\left(z\right)-\frac{1}{z}=\sum_{k\in\mathbb{Z},\, k\neq0}\left(\frac{1}{k\pi}+\frac{1}{z-k\pi}\right)
 $$ it is possible to prove that $$\frac{\sin\left(x\right)}{x}=\prod_{k=-\infty}^{\infty}\left(1-\frac{x}{\pi k}\right)\exp\left(\frac{x}{\pi k}\right)
 $$ (and we recall that the term $k=0
 $ is omitted) hence $$\cos\left(x\right)=\prod_{k=-\infty}^{\infty}\left(1-\frac{2x}{\pi\left(2k-1\right)}\right)\exp\left(\frac{2x}{\pi\left(2k-1\right)}\right).
 $$
Comment: and why would you assume that we know such a pole decomposition of $\csc(z)$ ?...
Comment: @user1952009 I can't predict what you know or not. The question is to prove an identity and this is a way.
Comment: this is not the question, and if you wanted to give a complete proof, you didn't since your formula for $\csc(z)$ is "magic" (at least explain why starting from $\csc(z)$ or $\cot(z)$ would be easier...)
Comment: Title: "Show $\cos(\pi z)$=...". In the question: "I'm not sure where the exponential comes from." So I think my answer shows how the exponential comes from. We always need to start from something to start a proof. I can find a reference for the two identities (with the proofs) but I wouldn't call it "magic".
Comment: I'm sorry but the exponential only comes to make the product convergent... the true product is without the exponential, by grouping the terms by two. when you change the order of summation, you have to add the exponentials to make the logarithm of the product absolutely convergent. you didn't show that, (read my comment above to see what was the answer to his question) and I'm ensure you know all the possible ways to prove the product formula for $\cos(z)$ and the series formula for $\cot(z)$ (with the residue theorem or the https://en.wikipedia.org/wiki/Weierstrass_factorization_theorem )
Comment: or even the Liouville theorem applied to $\cot(z) - \sum \ldots$
Comment: Sorry but I don't see the point. I used $$\log(z-2k\pi)+\frac{z}{2k\pi}=$$ $$\log\left((z-2k\pi)\exp\left(\frac{z}{2k\pi}\right)\right)$$ and so here we have the exponential. What you said is right, it makes the product absolutely convergent but I only shows a way to see how it comes out. If there are some mistakes I will delete the answer without problems :)
Comment: see my comments just below the OP question
Comment: and note that exactly in the same way : $\displaystyle \cot\left(z\right)-\frac{1}{z}=\sum_{k\in\mathbb{Z},\, k\neq0}\left(\frac{1}{k\pi}+\frac{1}{z-k\pi}\right) = \sum_{k=1}^\infty\left(\frac{1}{z-k\pi} + \frac{1}{z+k\pi}\right)$
Comment: and to prove that, you can prove first that $\cot(z) - \frac{1}{z} - \sum_{k=1}^\infty\left(\frac{1}{z-k\pi} + \frac{1}{z+k\pi}\right)$ is an entire function (it has no pole and it is everywhere complex differentiable), and that it is bounded when $|z| \to \infty$, hence it is constant by the [Liouville theorem](https://en.wikipedia.org/wiki/Liouville%27s_theorem_(complex_analysis)).
Comment: I have to agree with user1952009 in this case. It is circular to use that pole decomposition without first deriving it which is essentially just as hard as what I was trying to show. The "correct" answer is that the exponentials make the product absolutely convergent.


solving for $X$ the following linear equation, is the solution a unique rectangular matrix?

Question: I have an invertible matrix $A$ of size $n \times n$ and a matrix $U$ of size $n \times m$, for $m < n$. Matrix $U$ is orthonormal, meaning, the rows are orthonormal vectors. I also have an $m \times m$ diagonal matrix $\Sigma$ with positive values on the diagonal.
I want to find the solution for the equation
$$X A U = \Sigma.$$
Since $U$ is orthonormal, then $U^T U = I$, and therefore, for $X = \Sigma U^T A^{-1}  $, we have:
$$X A U = \Sigma U^T A^{-1} A U = \Sigma.$$
I would like to know if this is the only solution, and if so, how to show it.
Comment: @copper, I am confused by your answer. I stared a bit at the equation and guessed the solution. My problem is that even though $U'U = I$, we don't have $UU' = I$ because $m < n$. So we can't multiply both sides by $U'$.
Comment: Is $U$ in the first line the same as $B$?  Is $\Sigma$ the $m \times m$ diagonal matrix and you are solving for $X$?
Comment: @Ross, terribly sorry. I fixed the question. Yes to both of your questions.
Comment: @kloop: OOps, sorry, I didn't check your calculation. I will delete my comment momentarily.
Comment: The title is rather extraordinary in that it's so general that it could be the title for almost any question, but it doesn't actually fit this particular question, since you're not in fact asking how to find a solution; you've already found one and want to know whether it's unique. Please try to choose titles that summarize the question.
Comment: @joriki, absolutely right. I changed the title to fit better the question.
Comment: Now the title fits the question, but it still doesn't summarize it :-) Imagine what the main page would look like if all titles were as general as this one. How about something like "uniqueness of the solution of an equation for a rectangular matrix"?
Comment: If rows of $U$ are orthonormal, we should have $UU^T=I$, right? not $U^TU=I$
Comment: @chaohuang: Yes; also the rows can't be orthonormal, since $m\lt n$, so they're linearly dependent. I think everything would be OK if "rows" is replaced by "columns" in the question.
Comment: @copper.hat: How do you mean? $X$ is $m\times n$ with $m\lt n$. In fact it's clearly rectangular in your own answer?
Comment: @joriki: Sorry, I spaced out again, I (mis-)read rectangular as square. All matrices are rectangular, of course. I will delete my comment shortly.
Answer: Since $\Sigma$ and $A$ are invertible, from $\Sigma^{-1}XAU=I$, we can characterize the solution set as the set of all matrices $X$ of the form $\Sigma VA^{-1}$, where $V$ is any matrix with $VU=I$. For $m\lt n$ there are matrices other than $U'$ with this property.
Comment: thanks. that seems correct. but why can we "characterize the solution set as the set of all matrices $X$ of the form ..." ?
Comment: Write $V=\Sigma^{-1}XA$. Then your equation is $VU=I$. Since $\Sigma$ and $A$ are invertible, there's a one-to-one correspondence between $V$ and $X$; being invertible, $\Sigma$ and $A$ merely "translate" between the two. So for any $V$ with $VU=I$, there's exactly one solution $X=\Sigma VA^{-1}$, and conversely, for every solution $X$, your equation requires $VU=\Sigma^{-1}XAU=I$.
Answer: Take $\Sigma = \begin{bmatrix} 1 \end{bmatrix}$, $A=\begin{bmatrix} 1 & 0 \\ 1 & 1 \end{bmatrix}$, $U = \begin{bmatrix} 1 \\ 0 \end{bmatrix}$. Then the equation above becomes
$$\begin{bmatrix} x_1 & x_2 \end{bmatrix} A U = \Sigma$$
and all solutions satisfy $x_1+x_2 = 1$. So the solution is not, in general, unique.


How to show only the videos from my account - youtube api v3

Question: I'm using the youtube api v3 and got the following order:
I have private videos on my account, some users logarão in my system for a web log off google but when this user is logged on my system it will show private videos that are on my account through youtube api.
The problem is that the examples that caught api videos that are listed is the person who is logged on at that moment and that's not what I want.
The example I'm following is this:
<?php
// Call set_include_path() as needed to point to your client library.
require_once 'Google_Client.php';
require_once 'contrib/Google_YoutubeService.php';
session_start();

/* You can acquire an OAuth 2 ID/secret pair from the API Access tab on the Google APIs Console
  <http://code.google.com/apis/console#access>
For more information about using OAuth2 to access Google APIs, please visit:
  <https://developers.google.com/accounts/docs/OAuth2>
Please ensure that you have enabled the YouTube Data API for your project. */
$OAUTH2_CLIENT_ID = 'REPLACE_ME';
$OAUTH2_CLIENT_SECRET = 'REPLACE_ME';

$client = new Google_Client();
$client->setClientId($OAUTH2_CLIENT_ID);
$client->setClientSecret($OAUTH2_CLIENT_SECRET);
$redirect = filter_var('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'],
  FILTER_SANITIZE_URL);
$client->setRedirectUri($redirect);

$youtube = new Google_YoutubeService($client);

if (isset($_GET['code'])) {
  if (strval($_SESSION['state']) !== strval($_GET['state'])) {
    die('The session state did not match.');
  }

  $client->authenticate();
  $_SESSION['token'] = $client->getAccessToken();
  header('Location: ' . $redirect);
}

if (isset($_SESSION['token'])) {
  $client->setAccessToken($_SESSION['token']);
}

if ($client->getAccessToken()) {
  try {
    $channelsResponse = $youtube->channels->listChannels('contentDetails', array(
      'mine' => 'true',
    ));

    $htmlBody = '';
    foreach ($channelsResponse['items'] as $channel) {
      $uploadsListId = $channel['contentDetails']['relatedPlaylists']['uploads'];

      $playlistItemsResponse = $youtube->playlistItems->listPlaylistItems('snippet', array(
        'playlistId' => $uploadsListId,
        'maxResults' => 50
      ));

      $htmlBody .= "
Videos in list $uploadsListId

";
      foreach ($playlistItemsResponse['items'] as $playlistItem) {
        $htmlBody .= sprintf('
%s (%s)
', $playlistItem['snippet']['title'],
          $playlistItem['snippet']['resourceId']['videoId']);
      }
      $htmlBody .= '
';
    }
  } catch (Google_ServiceException $e) {
    $htmlBody .= sprintf('
A service error occurred: %s
',
      htmlspecialchars($e->getMessage()));
  } catch (Google_Exception $e) {
    $htmlBody .= sprintf('
An client error occurred: %s
',
      htmlspecialchars($e->getMessage()));
  }

  $_SESSION['token'] = $client->getAccessToken();
} else {
  $state = mt_rand();
  $client->setState($state);
  $_SESSION['state'] = $state;

  $authUrl = $client->createAuthUrl();
  $htmlBody = <<<END

Authorization Required

You need to authorize access before proceeding.

END;
}
?>

<!doctype html>

    <title>YouTube Search</title>

    <?=$htmlBody?>

So how to quue api if atentique with a single account and bring the videos this account instead of authenticating with the user account in question?
Answer: click on your youtube video. Below video will show emabed code. paste into your web page where you want to show.
Comment: not solve this friend, what I really wanted is to bring private videos from one account in particular not the users who access the system.

Private videos may not be part of simple embeds or iframes


AngularJs-Material como alterar a lingua para portugues do md-datepicker

Question: Estou tentando trocar a linguagem do md-datepicker para português pois os dias da semana e o meses estão em inglês, portanto fica confuso para o usuário... Existe alguma forma de trocar esta linguagem? Formatar os campos para Português?

Standard date-picker

                            <md-datepicker ng-model="ctrl.myDate" md-placeholder="Enter date"></md-datepicker>

Answer: Para corrigir as datas é necessário configurar o $mdDateLocaleProvider
fica dessa forma:

.config(function($mdDateLocaleProvider) {
   $mdDateLocaleProvider.shortMonths  = ['Jan', 'Fev', 'Mar', 'Abril','Maio', 'Jun', 'Jul','Ago', 'Set', 'Out','Nov','Dez'];
   $mdDateLocaleProvider.Months  = ['Janeiro', 'Fevereiro', 'Março', 'Abril','Maio', 'Junho', 'Julho','Agosto', 'Setembro', 'Outubro','Novembro','Dezembro'];
   $mdDateLocaleProvider.days = ['Domingo','Segunda', 'Terça', 'Quarta', 'Quinta','Sexta', 'Sabado'];
   $mdDateLocaleProvider.shortDays = ['D', 'S', 'T', 'Q', 'Q','S','S'];
  });


Optimization problem & stochastic dominance

Question: Let $z^*(F):= \arg\max_z (1-F(z)) \times g(E_F[x|x>z]) + F(z) \times g(E_F[x|x\leq z])$, where $F$ is the CDF of a continuous distribution, and $g'>0, g''>0$.
Could someone help me prove/verify that if $F_1$ first order stochastic dominates $F_2$, then $z^*(F_1)>z^*(F_2)$? If it is easier, let $g(x):=x^{1/(1-\alpha)}$, where $0<\alpha<1$.
Thank you!
Answer: I figured the answer out! :)
Assume $g(x)=x^{1/(1-\alpha)}$, where $0<\alpha<1$.
Proof:
Step 1: By taking the derivative of the maximand, we get $z^*= \Phi(z^*;F)$, where $\Phi(z;F):=\alpha \frac{(E_F[x|x>z])^{1/(1-\alpha}-(E_F[x|x\leq z])^{1/(1-\alpha}}{(E_F[x|x>z])^{\alpha/(1-\alpha}-(E_F[x|x\leq z])^{\alpha/(1-\alpha}}.$
It thus suffices to show that $\Phi(z;F_1)>\Phi(z;F_2)$ for all $z$.
Step 2: Since $F1$ fosd $F2$, it follows that $E_{F_1}[x|x>z]>E_{F_2}[x|x>z]$ and $E_{F_1}[x|x\leq z]>E_{F_2}[x|x\leq z]$
Step 3: Lemma: if $g$ is such that $g',g''>0$, and if $x_1>y_1,x_2>y_2$ and $x_1>x_2$, $y_1>y_2$, then $\frac{g(x_1)-g(y_1)}{x_1-y_1}>\frac{g(x_2)-g(y_2)}{x_2-y_2}$. Proof is a bit lengthy but straightforward.
The three steps complete the proof.


$A =\{ 1/(n+1): n \in \mathbb N \} $ is a nowhere dense subset

Question:
Prove that the set $A =\displaystyle \left \{ \frac{1}{n+1} : n \in \mathbb N \right \} $ is a nowhere dense subset of $\displaystyle{ \mathbb R }$.

I have think two ways but I can't finish it. Here it is

I tried to prove that $ \text{int} (\bar{A}) = \emptyset$. For this it is enough to prove that $ \bar A =\mathbb Q $ but I can't show this.
I tried to prove that every interval of $ \mathbb R$ contains a subinterval whose intersection with $A$ is the empty set.

Any help?
Thank's in advance!
Comment: Kindly do not use `\displaystyle` in title as it breaks the layout of the list of questions
Comment: You want to prove that the closure of $A$ is a set that's not closed?
Comment: The closure of $A$ cannot be $\mathbb{Q}$ because $\mathbb{Q}$ is not closed while the closure of $A$ is.
Answer: You couldn't prove that $\operatorname{cl}A=\Bbb Q$ because it's not true. Try proving instead that $\operatorname{cl}A=A\cup\{0\}$.
By the way, it's also possible to use your second approach: the key step is showing that if $0<x<1$, there is an $n\in\Bbb N$ such that $$\frac1{n+2}<x\le\frac1{n+1}\;.$$
Added: If you've not already done so, draw a picture:
Comment: You're too fast!
Comment: Can you give some hint how to prove $\operatorname{cl}A=A\cup\{0\}$ ? And why is this the key using the second approach?
Comment: @passenger: I assume that you've no trouble proving that $0$ is a limit point of $A$. Let $x\in\Bbb R\setminus (A\cup\{0\})$. If $x<0$ or $x>1$ you should have no trouble finding an open interval around $x$ disjoint from $A$. If $0<x<1$, show that $$\frac1{n+2}<x<\frac1{n+1}$$ for some $n\in\Bbb N$. (Doing this should answer your other question for you as well.)
Comment: Done! Thank you very much for your time!


Am I interpreting this coefficient correctly?

Question: I'm trying to get caught up in some notes, and the topic is pooled, cross-sectional data. If we have the regression: $$\log{wage_i}=\beta_0+\beta_1\text{married}_i+\delta_0\text{yr10}_i+\delta_1\text{married}_i\times \text{yr10}_i+\varepsilon_i$$ Where $\text{married}$ is a dummy variable which $=1$ if a person is married and $0$ if not, and $\text{yr10}$ is a dummy variable indicating whether the observation was recorded in the year 2010, as opposed to being recorded in the year 2000. There's a blank spot in the notes that I didn't get, and it asks: How do we interpret $\delta_1$?
I think it's correct to say that $\delta_1$ measures how the return on whether or not someones married has changed in the past $10$ years. Is that correct? Or am I wrong? I read a little bit in my textbook and I think that's what it's saying.
Comment: Nice question and nice answer from @scortchi. But why are some coefficients $\beta$ and some $\delta$? (Just curious).
Comment: @PeterFlom that is just the way my professor likes to distinguish between new variables that she is adding. We originally had a simple regression without the $yr10_i$ and the interaction term. Then just to make a clear distinction she added the $\delta$'s.
Comment: @PeterFlom Actually I didn't explain that very precisely. My professor adds the $\delta$'s depending on the topic. Here it happened to be panel cross sectional data and she used the $\delta$ for the year as a dummy variable (because it was either observed in 2000 or 2010. And anything associated with the $\delta$ she also uses $\delta$ as a coefficient. Not that this is the most important thing, I just wanted to be more correct.
Answer: You're correct & that's a nice way of putting it. Perhaps worth adding that it's a multiplicative return because the independent variable is log wage. If you want to convince yourself put some numbers into the equations.
More precisely $\mathrm{e}^{\delta_1}$ is the ratio of the factor by which changing year from 2000 to 2010 increases wage for married people to the factor by which changing year from 2000 to 2010 increases wage for unmarried people.
Comment: Yes I agree wih Peter +1 for the second sentence.
Comment: A little more precision would help this answer, because I'm sure you don't mean that either the wage or the log wage are multiplied by $\delta_1$! More subtly, it also is not the case that the wage is multiplied by $1 + \delta_1$.


Does the studying of theory and scales eventually turn into muscle memory?

Question: I notice that when I whistle or hum to a song I can always "jam" along and I'm almost always in the key. I think this trait is built into humans or something as I could do this since I was a kid, and I'm sure everyone else can. Irrespective of understanding keys or theory.
So my question is, is studying keys really just a "hack" to get to a point where you can "whistle" with your fingers when playing piano. Just like we innately know the key with our mouths without having to study theory? And at that point all theory becomes meaningless?
Comment: This sounds like the Levitin Effect (https://en.wikipedia.org/wiki/Levitin_effect).
Comment: @ToddWilcox - having taught thousands of kids in choirs, and in ordinary classes, where most would have little or no theory, I agree with Foreyez that most people can sing in tune, whilst being blissfully unaware of which key they're in. Most - not all ! Don't see how theory knowledge helps anyone sing in key, particularly youngsters.
Comment: Actually most humans can't do that. I'm surprised you're so confident that everyone can. I knew how to play in a key on piano many years before I could hum on key or even whistle at all. I had to practice for like a year before I even knew how to make single note when whistling.
Comment: most people can hum. my point is, if you play any song for them say off youtube, they'll be able to hum along with it irrespective of key. for example, take the "canon in d major" on youtube. I would suspect most people, once they hear the song once, won't have a problem humming along with it. and they can do it with whatever key you throw at them without knowing anything about theory.
Comment: @Tim I wonder if the classes you taught were mandatory or voluntary. If voluntary, there could have been a selection bias. Most adults I know have a hard time hitting the right notes when singing songs like "Happy Birthday". Maybe it's just bad luck in my social circles.
Comment: @ToddWilcox - run of the mill classes, multi-cultural inner city kids, not really the sort whose mummies and daddies would pay for private music lessons - in the Midlands in UK. Maybe you just mix in the wrong circles!  Only kidding.
Comment: It would appear that a lot of us humans come ready hard-wired to sing and/or whistle. It sort of makes sense, since we're born with a mouth that could well have been designed for those purposes, as well as speaking.
Comment: @Tim yes, it's hard-wired in us, in all scales, both major and minor, I find. for example, listen to any song (even songs you aren't familiar with) and while you're listening you can actually jam to it (via humming/whistling) without knowing what the scale is. so learning an instrument is just practicing to hit the right note you *already have in your mind* with your fingers.
Comment: @Tim if the kids inherently knew it then what's the point of learning scales,chords. is it just to develop muscle memory for an instrument? the more I play the more I'm leaning to forgetting all about theory. it seems detrimental after a certain point. same with talking english, at some point you forget about the grammar rules and you just talk.
Comment: Only to an extent. Chatting, maybe. But trying to explain something more intricate, it still goes through my mind to use exactly the words, in the right order, that are needed to convey the idea. Too many people talk sloppily, and we are expected to translate it into intelligable terms. I get a lot of laughs using peple's badly put together sentences. I don't feel that sloppy music is the way forward. When I play, theres always a bit of theory going on in the back of my mind.
Answer: If you are talking about hearing a note and being able to hit the key on the piano blindly, no, most people cannot do that, unless they have perfect pitch, which seems to be something you are either born with or not.
If you are talking about hearing a song and being able to know what the chords and intervals are and how you would play them (once you have figured out what key it is in), this does require a certain skill sometimes referred to as "relative pitch" (as opposed to perfect). In conservatory we took classes ("aural skills") to develop this ability; a certain minimal ability to transcribe music by ear was required for graduation. Most musicians can develop this skill over time.

Is studying keys really just a "hack" to get to a point where you can "whistle" with your fingers when playing piano.

All forms of practicing an instrument are a "hack." The reason we practice scales is to train our hands so they become second nature. One of the reasons we study theory and listen to music is to train our ear so that we can hear harmonic motion and musical structure as a second nature as well. It can help your performance to know which notes are leading tones or which voice is the suspension.

And at that point all theory becomes meaningless?

I wouldn't say that. Music theory has other applications too, e.g. in musicology or composition, and having a common language helps you communicate ideas to others in your ensemble.
Answer: You are confusing music theory and proficiency.  We don't learn grammar in order to talk, but in order to be able to analyze talk.  While the study may also lead to a bit of literacy as a side effect, the principal aim is on analysis rather than synthesis.
Scale exercises may be concocted using music theory but their execution has rather little to do with it: it's a means for gaining proficiency in "talking" through a keyboard.
Answer:
I notice that when I whistle or hum to a song I can always "jam" along and I'm almost always in the key. I think this trait is built into humans or something as I could do this since I was a kid, and I'm sure everyone else can. Irrespective of understanding keys or theory.

I think many people can, but I've met plenty that have some difficulty in confidently repeating or following a melody. Nevertheless I think you're right to conclude that for most people, the ability to know what a melody sounds like, and predict and generate a melody, isn't something that derives primarily from studying theory.

So my question is, is studying keys really just a "hack" to get to a point where you can "whistle" with your fingers when playing piano..?

Any scale patterns (including those implied by keys) are abstractions - a way of looking at something from a certain angle by considering only a certain amount of the information at any one time - in this case, the set of notes being used by a piece of music.
Abstractions are useful to help people notice relationships between things, classify things, and remember them. The idea of using abstractions is a hack that we all use every day to do (some) things better than we did yesterday.
In the case of music, learning scale patterns can help us learn how to whistle or play an instrument, because it gives us the chance to make more mental connections between the things we observe.
We all make up our own abstractions even in the absence of formalized theory, but the advantage of using agreed, formalized abstractions is that it also helps us to communicate with others.

And at that point all theory becomes meaningless?

Depends what you mean by 'meaningless', I guess! Is a hammer meaningless once you've used it to put up a fence and then put it away in the toolbox and forgotten it? Arguably it is, until your fence blows down in a storm and you need it again. We need musical knowledge to be able to do music, and formalized theory can be an important part of that knowledge.
Answer: Yes, you can develop excellent 'busking' skills, where a known song just 'comes out of your fingers'.  Or you can develop excellent sight-reading skills, where a sheet of music seems to go straight from eyes to fingers, with little conscious intervention from the brain!   Or you can even scan a music sheet, recognise the musical content and play something appropriate to the musical situation - but NOT the literal notes on the page.  In fact, I often have to pull myself up for doing this - play what it SAYS, don't paraphrase it!
But why do you feel this makes theory meaningless?  Rather it's the practical application of one aspect of music theory.
Comment: because if I could do with my piano or guitar as I do with my whistling I'd be considered a prodigy. yet I could whistle since I was a kid without knowing any theory whatsoever. I could even hum the harmony as well. I do think theory is important and interesting though. but I think it might be a crutch for muscle memory. meaning, if you can produce what your brain wants to "hear" with your fingers that's about all that's needed. I think the brain already knows what's needed though.
Comment: Not a progidy, just a reasonably accomplished musician, with an ability to 'play by ear'.  Not every good player has this, but it's not an unusual skill.
Answer: I find in my own experience, that any type of information is only useless if I don't know how to use it. And if I don't know how to use it, I probably need more information. I personally enjoy the process of learning about music, how to understand it, how to play it, the variations available to me when I'm playing it, all of it. It all adds to my enjoyment. It's work that I thoroughly enjoy, and when I'm doing other things, it's something I'm still thinking about. I still go about my other activities, but music and it's study are something that contributes to my enjoyment of my life. It may be a hack to some folks, but I don't think of it that way.


Show that $\frac{1}{2}(|z|+|w|)|\frac{z}{|z|} + \frac{w}{|w|}| \le |z+w|$ with $z \neq 0$ and $w\neq0$

Question: Let $z,w \in \mathbb{C}$ Show that $\frac{1}{2}(|z|+|w|)|\frac{z}{|z|} + \frac{w}{|w|}| \le |z+w|$ with $z \neq 0$ and $w\neq0$
I know that $|z+w|\le |z| + |w|$
And that $z \cdot\bar z = |z|^2$
I tried to change values in the inequality but can't get anything.
According to Proving result of complex numbers I think that proving $0 \le |\frac{z}{|z|} + \frac{w}{|w|}| \le 2$Would prove the inequality. Note: I couldn't prove this either.
Could anybody give me a hint? Thank you
Comment: Another one: https://math.stackexchange.com/q/2803069/42969
Answer: So we have to prove: $$\Big|z+w+{|w|z\over |z|}+{|z|w\over |w|}\Big|\leq 2|z+w|$$
By triangle inequality we have $$\Big|\color{red}{z+w}+\color{blue}{{|w|z\over |z|}+{|z|w\over |w|}}\Big|\leq |\color{red}{z+w}|+\Big|\color{blue}{{|w|z\over |z|}+{|z|w\over |w|}}\Big|$$
so it is enough to check if $$\Big|{|w|z\over |z|}+{|z|w\over |w|}\Big|\leq |z+w|$$ is true.
Let $u=z/w$ then we have to prove $$\Big||u|+{u\over |u|}\Big|\leq |1+u|$$ or $$||u|^2+u|\leq |u||1+u|$$
but this is actually even equalty so the claim is proven.
Comment: Thank you very much, your answer is the easiest I've seen
Answer: Let $z=re^{i\theta},w=se^{i\psi},\;r,s\in\mathbb R^+,\theta,\psi\in\mathbb R$. The inequality can be rewritten as $$\frac{r+s}2\cdot|e^{i\theta}+e^{i\psi}|<|re^{i\theta}+se^{i\psi}|$$
We first work on the right side of the inequality. We note that $$|re^{i\theta}+se^{i\psi}|=\sqrt{(r\cos\theta+s\cos\psi)^2+(r\sin\theta+s\sin\psi)^2}$$$$=\sqrt{r^2+s^2+2rs\cos(\theta+\psi)}$$Then, note that $$|e^{i\theta}+e^{i\psi}|=\sqrt{2+2\cos(\theta+\psi)}$$$$\frac{r+s}2\cdot|e^{i\theta}+e^{i\psi}|=\sqrt{\frac{(r+s)^2}2\cdot(1+\cos(\theta+\psi))}$$The rest is just simple algebra. Can you take it from here?
Comment: Thank you, that was helpful.


Find string nearest to character 250, and split

Question: So I have a really long string that's a list of TV station call letters. The CRM which I'm putting this into has a character limit of 250 per field. I've created a few fields as a result. I'd like to split a string to 250 characters, then I'd like to find the last occurrence of ", "
str = "WPXN, KPXN, WCPX, WPPX, KPXD, KKPX, WBPX, WPXA, WWPX, WPXW, KPXB, WPXD, KPPX, WXPX, KPXM, WPXM, WVPX, KPXC, WOPX, KSPX, KPXG, KPXG-LD, WINP, WIPX, WRPX, WFPX, WNPX, WHPX, KPXE, KUPX, WPXE, KPXL, WPXP, WZPX, WPXH, WPXV, KOPX, WGPX, WPXC, WPXJ-LP, WPXX, WPXJ, WPXQ, WPXL, WQPX, WYPX, WPXK, KTPX, WUPX, WLPX, WPXR, KFPX, KPXO, WSPX, KPXR, WEPX, WTPX"

str[0...250]
# returns "WPXN, KPXN, WCPX, WPPX, KPXD, KKPX, WBPX, WPXA, WWPX, WPXW, KPXB, WPXD, KPPX, WXPX, KPXM, WPXM, WVPX, KPXC, WOPX, KSPX, KPXG, KPXG-LD, WINP, WIPX, WRPX, WFPX, WNPX, WHPX, KPXE, KUPX, WPXE, KPXL, WPXP, WZPX, WPXH, WPXV, KOPX, WGPX, WPXC, WPXJ-LP, WPXX"

# leftover_string = do something here
# returns ", WPXX"

appropriate_length_string = str[0...250].chomp(leftover_string)
longer_string = str[251..-1]
longer_string.insert(leftover_string + ", ",0)
# recusrively run until all strings are in an array or something.

Make sense? I don't know how to do the "do something here" part.
Comment: This sounds like an [X-Y problem](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem/66378#66378). How are you going to present the records to a user? Typically we'd use an array to populate a drop-down or list, not a string.
Comment: This isn't for a user... it's for entering data into another system.
Answer: Using regular expression (String#[regexp]):
str[0,250][/,[^,]*$/]
# => ", WPXX"

using String#rindex:
s = str[0,250]
s[s.rindex(',')..-1]
# => ", WPXX"

Alternative that use String#rpartition suggested by Cary Swoveland:
str[0,250].rpartition(',')[1..2].join
# => ", WPXX"

Comment: Also `str[0...250].rpartition(',').first`
Comment: @CarySwoveland, Do you mean `str[0...250].rpartition(',')[1,2].join`? I added this to the answer. Thank you for the suggestion.
Comment: I misread the question.  I thought the substring was wanted.  I also didn't read your answer very carefully.  Shame!
Comment: and if we make use of string's structure, `str.scan(/, \w{4}/)[(250-11)/6] # => ", WPXX"`.
Answer: I think you have to loop or recurse. Here's a quick looping example that most probably could be improved.
str = "WPXN, KPXN, WCPX, WPPX, KPXD, KKPX, WBPX, WPXA, WWPX, WPXW, KPXB, WPXD, KPPX, WXPX, KPXM, WPXM, WVPX, KPXC, WOPX, KSPX, KPXG, KPXG-LD, WINP, WIPX, WRPX, WFPX, WNPX, WHPX, KPXE, KUPX, WPXE, KPXL, WPXP, WZPX, WPXH, WPXV, KOPX, WGPX, WPXC, WPXJ-LP, WPXX, WPXJ, WPXQ, WPXL, WQPX, WYPX, WPXK, KTPX, WUPX, WLPX, WPXR, KFPX, KPXO, WSPX, KPXR, WEPX, WTPX"

chunk_size = 30
pos1 = 0
pos2 = pos1 + chunk_size
result = []

while pos2 < str.size do
  pos2 = str[pos1..pos2].rindex(",") + pos1
  result << str[pos1..pos2].strip
  pos1 = pos2 + 1
  pos2 += chunk_size
  result << str[pos1..pos2].strip if pos2 > str.size
end

p result


vuexfire firestore orderBy descending is not working, works in acending

Question: This code works in default ascending but as soon as I feed desc in orderby, it returns empty.
return bindFirestoreRef(
        'codesBatch',
        codeCollection
          .orderBy('createdOn', 'desc')
          .limit(payload.limit || 3)
          .startAfter(state.loadMoreLastCode || null),

Comment: What do you mean by "orderBy descending is not working". What exactly doesn't work? Please edit your question and add your database structure as a screenshot.
Answer: .orderBy() 'desc' doesn't work with .startAfter() null.
The first call has to be without .startAfter() and for later, the above code will work.


Project target does not exist com Ionic (android)

Question: Boa tarde.
Estou criando um novo aplicativo Ionic (Android).
Quando vou rodar o código: ionic cordova prepare android --prod ou ionic cordova build android ele acaba gerando erro de target e não sei nem por reza como arrumar.
Comment: Bem vindo ao SO-PT! Para que outros usuários possam te ajudar com mais facilidade, recomendo que você leia [aqui](https://pt.meta.stackoverflow.com/questions/5483/manual-de-como-n%c3%83o-fazer-perguntas?cb=1) e [aqui](https://pt.stackoverflow.com/help/how-to-ask) para ter umas dicas de como fazer uma boa pergunta.  Sugiro, também, que você forneça mais detalhes do seu código, dizendo o que ele faz, o trecho em que está, etc.
Comment: Faça `ionic cordova platform add android` Refência: https://ionicframework.com/docs/cli/commands/cordova-platform
Answer: Qual versão está usando?
Existe um bug reportado, mas já corrigido em uma posterior versão
npm install -g @ionic/cli@latest

execute a atualização e tente novamente caso esteja abaixo da v6.19.0
Comment: Eu rodei o código seu para atualizar, eu estava na 6.18.1.
Agora esta na v6.19 porém não deu feito nenheum criei o projeto... ao dar o prepare android ele da o mesmo erro ...
Comment: consegue postar suas dependências? seu cordova e ionic cli, quais versões estão instaladas? tem android e java sdk instalados?
Answer: Você precisa adicionar os builders:
ng add @ionic/cordova-builders


Unpublished file still downloadable

Question: I have a file attached to a node via a link. The node is published but the file is unpublished. The link on the node points to the file /sites/default/files/file.txt
The file is still downloadable by anonymous users.
I would assume the file, being unpublished, would be unavailable to download. This is not the case.
The anonymous permissions are set to view published content.
Is this expected behaviour? What would be the best way to not allow the file to be downloaded once it's unpublished?
Comment: That is a direct link to a physical file, there is nothing checking user access first, and its in the public files directory so the web server has no reason not to serve it.
Comment: Thanks Kevin. Would you be able to advise what the best method for overcoming this is?
Comment: For clarification, which version of Drupal are you running?
Comment: I am using Drupal 8.
Answer: You need to setup a private file system in settings.php:
<code>/**
 * Private file path:
 *
 * A local file system path where private files will be stored. This directory
 * must be absolute, outside of the Drupal installation directory and not
 * accessible over the web.
 *
 * Note: Caches need to be cleared when this value is changed to make the
 * private:// stream wrapper available to the system.
 *
 * See https://www.drupal.org/documentation/modules/file for more information
 * about securing private files.
 */
# $settings['file_private_path'] = '';
</code>
Files stored in the private file system will be served by Drupal and you can control which users are allowed to access the files.

Unpublished file still downloadable


usar variavel em comando cmd com python

Question: Queria fazer um programa que abra e leia um arquivo de texto. Depois executar ou comando no cmd usando o que ele tinha lido no arquivo de texto mais ou menos assim:
import os
nome = open ('nome.txt')
nome1 =nome.readline()
nome.close()
comando =os.system ('netsh wlan export profile name="AQUI FICA O VALOR DA VARIAVEL NOME1" folder="G:\WLess" key=clear'
)

Comment: O que tentou fazer e por quê não deu certo?
Comment: eu iria escrever o nome da wifi no arquivo nome.txt .o programa iria ler esse arquivo armazenar na veriavel nome1 depois ele irar da um comando no cmd : netsh wlan export profile name="AQUI FICA O VALOR DA VARIAVEL NOME1"  ...
Comment: Mas qual a dificuldade? Em jogar o valor da variável dentro do comando?
Comment: exatamente. eu queria jogar a variável no comando os
Answer: Sendo que a dificuldade é apenas inserir o valor da variável nome1 no comando, a solução é utilizar o método format de objetos tipo string.
>>> nome1 = "nome_no_arquivo"
>>> "O valor da variável é {}".format(nome1)
O valor da variável é nome_no_arquivo

Para o seu caso específico:
comando =os.system ('netsh wlan export profile name="{}" folder="G:\WLess" key=clear'.format(nome1))

Answer: Podes fazer assim:
import os

with open('nome.txt', 'r') as f:
    nome = f.readlines()[0].strip()
    cmd = os.system('netsh wlan export profile name="{}" folder="G:\WLess" key=clear'.format(nome))

usar variavel em comando cmd com python


Backstack and memory leakage

Question: I have developed a small API for dialog fragments based on Google support library with very simple requirements:

API could add (or replace) a modal dialog
API could dismiss dialog programmatically or user can dismiss dialog by pressing button

Does my API creates a memory leakage by constantly adding fragments to backstack?
public class DialogFragmentUtils {

private static final String DIALOG_TAG = "dialogTag";

public static void showDialogFragment(@Nullable Activity activity, @NotNull Fragment fragment) {
    if (activity instanceof FragmentActivity) {
        FragmentActivity fragmentActivity = (FragmentActivity) activity;
        FragmentManager fm = fragmentActivity.getSupportFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        Fragment prev = fm.findFragmentByTag(DIALOG_TAG);
        if (prev != null && prev.isAdded()) {
            ft.remove(prev);
        }
        ft.add(fragment, DIALOG_TAG);
        ft.addToBackStack(null);
        ft.commit();
    }
}

public static void dismissDialogFragment(@Nullable Activity activity) {
    if (activity instanceof FragmentActivity) {
        FragmentActivity fragmentActivity = (FragmentActivity) activity;
        FragmentManager fm = fragmentActivity.getSupportFragmentManager();
        DialogFragment dialog = (DialogFragment) fm.findFragmentByTag(DIALOG_TAG);
        if (dialog != null) {
            dialog.dismiss();
        }
    }
}
}

Comment: Why won't you just check? Create several dialogs and dismiss them in various ways (back/ok). Then run a heap dump using Eclipse MAT and search the heap for instances of your dialog.
Comment: How many dialogs are we talking about since your concerned about memory leak?
Answer: Yes, its prone to low memory, not memory leak though. All back stack Fragment are kept in memory with hard references. So if you are keeping a ridiculous amount of Fragments in back stack then you will get out of memory.
Have a look here: When a Fragment is replaced and put in the back stack (or removed) does it stay in memory?
UPDATE: I see your DIALOG_TAG is not changing so you are keeping only one Fragment in backstack at a time, because you remove old one if it exists. In this case you might not have the issue of low memory.
Comment: Where is he removing the old one? `dismiss()`ing it is not the same as removing it! I'm reasonably sure the backstack just grows in this case.
Comment: Look at his `showDialogFragment()` method where he calls `ft.remove(prev);`. He removes previous one before adding.
Comment: Oops, sorry, missed it the first time.
Answer: I believe it wont leak but to be sure you need to test it. As talkol said, you should use Eclipse MAT to analyse this issue. There is a good guide by vogel here and a good guide on the Android blog here. Create and close a bunch of dialogs and see if it makes a difference.
On a side note why do you use ft.close() instead of prev.dismiss() in your showDialogFragment() method. The correct way of closing dialogs is dismiss().
Comment: I do not use ft.close(). I use ft.remove() to remove from back stack.

Backstack and memory leakage


How can I use DPDK to write a DNS server?

Question: I want to write a high performance DNS server using Intel DPDK. How can I use Intel DPDK to process TCP packets effectively?
Sure, implement a net stack on DPDK is the solution.  But it's too complicated.
As DNS server handles much more UDP queries than TCP queries, I intend to use DPDK to handle UDP queries and use linux net stack to handle TCP queries.
How can I do this on a single machine?
Comment: Your title directly contradicts your question. Surely what you really want is implementations of IP *over* DPDK?
Comment: Yes, UDP/IP layer over DPDK. Any suggestion?
Answer: What Gabe has suggested is correct -- However there is a better way to achieve what you really want. You need to use a bifurcated driver.
The problem with using a KNI as suggested by Gabe is this:
Its your software in user space that will decide what it needs to retain (UDP) and what all needs to be routed via a network stack (TCP). You will then pass them to the kernel via DPDK software rings that would consume CPU and memory cycles.
There will be a memory copy between your mbuf and the kernel socket buffer which will affect your KNI performance.
Also note that if you handle UDP in your user space then you need to construct the L2 header before pushing the packet out. This means that you also perhaps need to trap all ARP packets so that you can build your ARP cache, as you will need that to construct the L2 header.
Answer: Look at the KNI documentation and Kernel NIC Interface example in the DPDK.
After allocating your KNI device, in you main DPDK polling loop you will pull packets off of the NIC.  You'll have to parse the header yourself, or you could get fancy and set up multiple RX queues and then use RSS 5-tuple filters to send UDP packets to your processing queue, and the rest to the default queue.
Anyway, regardless of the method chosen, if it is a UDP packet
you can handle it your self (like you requested); otherwise, you will queue the packet on to the KNI thread.  You will also need the other half of the KNI interface as well, where you poll packets off of the KNI thread, and send it out the interface.
This is exactly the way we do it in our application where we still want a linux networking stack for all operations other than our specific traffic.


Blob Storage Azure and javascript, how to list all snapshots for a specific blob

Question: Beginning a nodejs project, I need to retrieve the latest snapshot (and its metadata) for a specific blob. I'm using the Azure Blob storage client library v12 for JavaScript.
I'm not sure but I only found a method linked to the ContainerClient permitting to list all the blobs and snapshot within the container. Imo it's not for me very efficient in term of performance.
Is there a way to directly get the latest snapshot of a known blob or at least get all the snapshots ?
//construct of the blob storage connection
const blobServiceClient = new BlobServiceClient(
    `https://${account}.blob.core.windows.net/`,
    sharedKeyCredential
);
//target application container
let containerClient = blobServiceClient.getContainerClient(app);
blobClient = containerClient.getBlobClient(filename); //ok
//blobSnapshots = containerClient.getSnapshots(filename); // nok

The method in the last commented line for sure doesnt exist but is there an equivalent method ?
Answer:
Is there a way to directly get the latest snapshot of a known blob

Unfortunately no. You will need to list all snapshots of a blob and sort them reverse chronologically based on snapshot date/time and pick the 1st blob. That would be the latest snapshot.

or at least get all the snapshots ?

You will need to call listBlobsFlat method with the following options:

prefix: This should be the name of the blob.
includeSnapshots: Value of this parameter should be true.
Comment: I've not tried it but you should get the snapshot URL in the blob's URL. If not, then just add "?snapshot=" to the blob URL.
Comment: great it should do the job. And how do I get the snapshot url ?


When does MLB use instant replay?

Question: I was inspired to ask this question given instant replay was mentioned in this thread: Why is FIFA against adding instant replay to the game?
For the 2012 season, has baseball changed any rules regarding instant replay?
Also, does the MLB use instant replay at all and in which cases do they use instant replay to review officiating?
Comment: Especially in the play-offs, IR needs to be implemented in close calls.Umpires after all are human.
Answer: According to Wikipedia, the MLB has had instant replay since Aug. 28, 2008. It is used for determining:

Fair (home run) or foul.
Whether the ball actually left the playing field.
Whether the ball was subject to spectator interference.

For the 2012 season:

Instant Replay will expand to include fair and foul calls and balls that was [sic] caught, or trapped by the player catching the ball. It will also expand interference reviews beyond the home run boundary to all walls.
Answer: Instant replay is also used to determine if a player is safe or out in close calls at a base or home plate. So according to Kevin's answer, it's used to determine fair or foul ball, whether the ball left the playing field, whether the ball was subject to spectator interference, plus the situation given by me above. My reference for the first part was my knowledge from watching countless hours of baseball on TV.

When does MLB use instant replay?


Resolving git repo with master branch and a second branch name MASTER

Question: When switching back from a local branch, I accidentally checked out a new branch, MASTER, and pushed it to origin. Now the repo has master and MASTER as branches. How do I safely rename MASTER and rebase it into master?
Thanks!
Answer: There's really no need to rename it. Simply merge or rebase your new changes in MASTER onto master, then delete the MASTER branch.

git merge master MASTER will add a merge commit to master, along with the history of individual commits.
If you'd rather do a rebase, use git rebase master MASTER.

After either one of those, run git branch -d MASTER to delete your local MASTER branch. To delete the remote branch, run git push origin :MASTER (via this page). And be sure to push it all to origin afterwards.
Edit If you really do want to rename it, like if you maintain links to your topic branches, delete the remote branch, rename it locally using git branch -M MASTER foobar and push it to the remote.
Comment: Perfect! Thank you so much. I'm still learning git and really love what I've seen so far. I'll let you know how it goes.

Thanks again!
Comment: Yep. That worked perfectly. Thank you so much! You just resolved a major headache.


Windows CMD Line - Syntax Error- Parameter format not correct when trying to run command "del ..\C\D"

Question: I have 4 folders, with A being the parent, B and C being the child of A, and D being the child of C.
A -> B
A -> C -> D
In folder B I want to generate a build via NPM and then to move the new folder over to D after deleting the previous version.
So to do this I'm trying to run the following script in the command line:
react-scripts build && rd /s/q ../C/D  && move build ../C/D
Upon running this command however, I receive the following error:
Parameter format not correct - "C".
What is causing this error in particular and what would be the proper syntax to run this command?
Answer: Windows cmd prompt often requires paths to be in double quotes.
C:\Users\Me>mkdir c/d
The syntax of the command is incorrect.

C:\Users\Me>mkdir "c/d"

Windows powershell will accept the paths without quotes.
PS C:\Users\Gordon> mkdir c/d

    Directory: C:\Users\Me\c

Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
d-----         7/20/2022  11:51 AM                d

Answer: In your example, just swap / (forward slash) with \ (backward slash) and you would probably be good to go...
react-scripts build && rd \s\q ..\C\D && move build ..\C\D

If your folder or file has empty spaces in the name you'd want to surround it with quotes.


OpenBSD 7.2: Mailbox file in users' home directory - use Postfix or stick to default sendmail?

Question: I need to setup a mail server with a bit unusual requirements:

OpenBSD is a must. Probably latest version, 7.2.
All mails have to be stored in aa Mailbox file located in user's home directory.

Well, it does not look difficult, as I did it before using other systems. But I used Postfix for this task, as I'm quite familiar with it and I just like Postfix.
Taking OpenBSD's top security into account, I started to consider using default MTA (sendmail) instead of Postfix (and this is an opportunity to get familiar with OpenBSD too, as I have no previous experiences with it), but I didn't found a simple solution. I know I can setup mail.local to put mails into Mailbox files, but in /var/mail/user. I did not find any option to store mails in users' home directories.
Could you please tell me, do I miss something obvious? Assuming I do, is it reasonable to configure default MTA for this task, or using Postfix is acceptable/recommended? Or maybe any other MTA is generally better for such purposes and this particular operating system?
Thank you in advance!
Comment: The default MTA in OpenBSD is OpenSMTPD. It is configured in [`smtpd.conf`](https://man.openbsd.org/smtpd.conf).
Answer: Sendmail - mailbox location
Sendmail does not deliver email to local mailboxes itself.  Sendmail uses "local mailer" program/mailer.  It is typically procmail program on Linux
(or sensible-mda which means procmail when procmail is installed).
To check "local mailer" used by sendmail look for line starting with Mlocal in /etc/mail/sendmail.cf
You can configure default mailbox location used by procmail in ~/.procmailrc (or /etc/procmailrc).

Anyway: My current recommendation for sendmail use is "KEEP" - do not switch to sendmail if you do not have (a lot of) sendmail experience.
Comment: Anyone interested in how OpenBSD uses `sendmail` I would encourage to read the [man page](https://man.openbsd.org/sendmail), which along with [`smtpd`](https://man.openbsd.org/smtpd) and [`smtpd.conf`](https://man.openbsd.org/smtpd.conf), demonstrates the above answer is not applicable to OpenBSD.


Android JIT compiler: when are methods compiled/optimized

Question: From my knowledge the Java JIT compiler traces called methods and after a certain amount of method/loop executions compiles the code or optimizes it based on the executed code paths so far. The number of method executions is something like 10000 (depends on JVM and settings) with some aging.
I am wondering when the Android JIT compiler actually kicks in (number of method invocations and other metrics). The reason is that I logged the used CPU time for a code part with android.os.Process.getElapsedCpuTime() and now wonder when I should expect to see some improvements (if any at all).
Answer: Maybe this will give you some insight if you haven't watched it already: http://www.google.com/events/io/2010/sessions/jit-compiler-androids-dalvik-vm.html


Equation of a ray passing through the camera center and an image point

Question: If C is the camera center in homogeneous world coordinates and x is a point on the image plane, the ray passing through C and x is said to be:
$$ X(\lambda) = P^{+}x + \lambda C $$
where P is the camera matrix that maps world points to the image plane:
$$ x = PX $$
$P^{+}$ is the pseudo inverse of the 3x4 camera matrix.
My question is this:
Why is the above equation true?
Should it not be:
$$ X(\lambda) = (1-\lambda)P^{+}x + \lambda C $$
Is it perhaps a consequence of homogeneous coordinates that:
$$ X(\lambda) = X(\lambda)/(1-\lambda) = P^{+}x + \lambda C/(1-\lambda)  $$
Then we can define $X(\lambda_2) = P^{+}x + \lambda_2 C$ where $\lambda_2 = \lambda/(1-\lambda) $
Answer: The reason the answer I put in is not correct is because:
The x and C in the equation $X(\lambda) = P^+x + \lambda C$ are homogeneous vectors and don't live in $R^2$. You cannot get the direction of the line between x and C by subtracting the homogeneous representations of x and C. You get the line by doing a cross product instead. So the wrong derivation shown is a result of applying principles to homogeneous space that are incorrect. (Namely, the incorrect principle is that direction of a line between two points can be computed by subtracting the coordinates of the two points)
The derivation of $X(\lambda) = P^+x + \lambda C$ is a lot simpler than I thought it was and has nothing to do with finding directions of lines:
Consider a system $Ax = b$ where A is a 4x3 matrix.
To invert the relationship we initially find that $x = A^+b$. That is not the only solution though as A has a kernel of dimension one. The kernel is $\lambda C$. The set of solutions is then $x = A^+b + \lambda C$
To understand this a bit further, let us agree that we can change the coordinate systems of x and b in such a way that the only nonzero elements A has are on the diagonal. This will now look like:
$$\begin{bmatrix}b_1\\b_2\\b_3\end{bmatrix} = \begin{bmatrix}a & 0 & 0 & 0\\0 & b & 0 & 0\\0 & 0 & c & 0\end{bmatrix}\begin{bmatrix}x_1\\x_2\\x_3\\x_4\end{bmatrix}$$
It is now easy to see that to get x:
$$\begin{bmatrix}x_1\\x_2\\x_3\\x_4\end{bmatrix} = \begin{bmatrix}1/a & 0 & 0\\0 & 1/b & 0\\0 & 0 & 1/c\\0 & 0 &0\end{bmatrix}\begin{bmatrix}b_1\\b_2\\b_3\end{bmatrix} + \lambda \begin{bmatrix}0\\0\\0\\1\end{bmatrix}$$
The above looks nice because we were able to choose nice coordinate frames for x and b. We could now undo the transformation on the coordinate frames and get a map directly from x to b in their original frames.
Comment: This is actually not completely correct (I think). I'll post why in a little bit.
Answer: This is confusing... but both:
$$ X(\lambda) = P^{+}x + \lambda C $$
$$ X(\lambda) = (1-\lambda)P^{+}x + \lambda C $$
Are rays that pass through P+x and C. First of all, the reason why this is so confusing is because, as you stated, these are homogeneous coordinates, not euclidean coordinates, so the intuition you use for adding euclidean vectors doesn't really hold up because after you add them, you need to divide by the last coordinate to bring them back to euclidean space, which is how the ray is defined (it's a line in euclidean space, but with homogenous coordinates).
Because this is so confusing, I just decided the easiest way to show this is correct is to just program it out and plot the results.
The first equation:
import numpy as np
import matplotlib.pyplot as plt

c = np.array([1,2,1]) # center
p = np.array([4,5,1]) # point

# Try out the equation `X(lambda) = p + lambda*c`
ls = np.linspace(-500, 500, 1000)
Xs_lambda = np.array([p + l*c for l in ls])

plt.plot(c[0]/c[2], c[1]/c[2], 'gs')
plt.plot(p[0]/p[2], p[1]/p[2], 'rs')
plt.plot(Xs_lambda[:,0]/Xs_lambda[:,2], Xs_lambda[:,1]/Xs_lambda[:,2], '-r')

Results in:

# Now try out the equation `X(lambda) = lambda*p + (1-lambda)*c`
ls = np.linspace(-1, 2, 1000)
Xs_lambda = np.array([l*p + (1-l)*c for l in ls])

plt.plot(c[0]/c[2], c[1]/c[2], 'gs')
plt.plot(p[0]/p[2], p[1]/p[2], 'rs')
plt.plot(Xs_lambda[:,0]/Xs_lambda[:,2], Xs_lambda[:,1]/Xs_lambda[:,2], '-r')

Results in:

These are both lines passing through P+x and C and parameterized by l.
Now, returning to the math in the 2D case, let:
$$ X = [x_1, x_2, 1] $$
$$ Y = [y_2, y_2, 1] $$
Now adding a linear combination of the two:
$$ k_1*X + k_2*Y $$
$$ [k_1*x1 + k_2*y_1, k_1*x_2 + k_2*y_2, k_1+k_2] $$
The resulting first coordinate in euclidean coordinates is now:
$$ (k_1*x_1 + k_2*y_1)/(k_1+k_2) $$
Simplifying further...
$$ (k_1/(k_1+k_2))*x_1 + (k_2/(k_1+k_2))*y_1 $$
So this means only the relative ratios between k_1 and k_2 matter and the resulting value is a linear combination of X and Y with coefficients that sum to 1, meaning it will form a line between X and Y as long as the relative ratio between k1 and k2 are varied which is true for both equations at the top.


Can a series of polynomials converge non-uniformly?

Question: Is there an example of a series of polynomials, say, the degree equals the index and converges non-uniformly? In other words, does point-wise convergence of a polynomial series imply uniform convergence?
Answer: No, uniform convergence is stronger even for polynomials. In fact, one of the classic examples of a sequence of continuous functions which converges pointwise but not uniformly is a sequence of polynomials: it is $f_n(x)=x^n$ on $[0,1]$. This converges pointwise to a function which is $0$ except at $1$, where it is $1$.
In light of the Weierstrass approximation theorem, if this were not the case, then pointwise convergence of any sequence of continuous functions would imply uniform convergence.


Paste id into href

Question: I have a lot of streams.
name_1
name_2
...
name_99

I want to hide "http://server/stream99/parameters"
How to do a function to paste "id" into href
eg:
name_1

using something like
function somefunction(a) {
   document.getElementById('a').innerHTML = '';
}

Javascript or jquery will make the link and paste the "id".
Or perhaps I can somehow use a different method to hide links?
Comment: it's a little bit unclear what you're asking. can you clarify
Comment: Not really sure what you want to achieve
Comment: Clarify please !
Comment: Also note, document.getElementById('a') >> the id is not 'a' but 'stream1', 'stream2' etc..
Comment: totally unclear question - describe exactly what is the point here. We'll be glad to help
Comment: @PaoloFalomo totally clear question. Use your imagination :)
Comment: use.htaccess redirection instead
Answer: Like this - do note that this is easy to decipher by inspecting the code.
Alternatively use a server redirect and just send some encrypted ID

$(function() {
  $(".stream").on("click", function(e) {
    e.preventDefault();
    location = "http://server/" + this.id + "/parameters";
  });
});

name_1

name_2

name_3

name_4

Paste id into href


Efficiently collapsing rows in an R data frame

Question: I have the following toy data.frame:
> df
  Fragments   a    b    c    d    e
1       0.5 0.2 0.20 0.20 0.20 0.20
2       1.5 0.2 0.20 0.20 0.20 0.20
3      22.0 0.4 0.15 0.15 0.15 0.15
4       5.1 0.6 0.10 0.10 0.10 0.10
5       4.2 0.4 0.15 0.15 0.15 0.15
6      10.0 0.6 0.10 0.10 0.10 0.10

and I'd like to collapse it by rows in which all but the first column are identical (i.e., columns "a" to "e" in this example) and taking the sum over the first column (the "Fragments" column in this example) in these collapsed row. So the result will be this data.frame:
> collpased.df
  Fragments   a    b    c    d    e
1       2.0 0.2 0.20 0.20 0.20 0.20
2      26.2 0.4 0.15 0.15 0.15 0.15
3      15.1 0.6 0.10 0.10 0.10 0.10

I'm looking for the most efficient solution as in my real data the number of rows and columns is very large. The aggregate function seems too slow.
Answer: Do as Jilber says if you know the data.table package. If not, just use
aggregate().
result = aggregate(df[,1],df[,-1],sum)

In this case the result will end up in the last column.
EDIT: You state that aggregate() is too slow. The main problem that you will have with data.table is that the initialization cost of data.table(df) is quite big, so you need to amortize it. Casting a data.table only for that operation and nothing else, is just not worth it.
So my advice stays the same. If you know the package and you will use its potential several times during the session then use it. If not, stick to aggregate().
Comment: +1. I personally prefer the `formula` syntax though: `aggregate(Formula ~ ., df, sum)`
Answer: If you already tried using aggregate and found it too slow, then you might want to try data.table from data.table package.
> library(data.table)
> dt <- data.table(df)
> dt[,list(Fragments=sum(Fragments)), by=list(a,b,c,d,e)]
     a    b    c    d    e Fragments
1: 0.2 0.20 0.20 0.20 0.20       2.0
2: 0.4 0.15 0.15 0.15 0.15      26.2
3: 0.6 0.10 0.10 0.10 0.10      15.1


Is there a way to select/apply a (or multiples) taxonomy value(s) to a particular asset using the governance Api?

Question: According to the documentation of the wso2greg , wso2greg provide different api types that enable us to interact with the registry , such as the registry-Api and the governance-Api, am already used the governance-Api to create some artifacts (wsdl ,xsd and serviceSoap with there dependancies) with java code and i already defined a taxonomy hierarchy via the WSO2 G-Reg Management , the next step is to select a taxonomy value(s) for an asset for example a soapService .
Am wondering if there's a way to do such a thing using the governance-Api.
Answer: As far as I know, requested operation is yet to implement in G-Reg. Which means WSO2 haven't implemented API to do taxonomy operations. You can always log an issue in GitHub on this. If not you can checkout the code from GitHub build your own API for this. Please refer this link if you want to build that.
Comment: Thanks man , i really appreciate your answer , i guess i will try to build my own API


Null Pointer Exception in Text Game

Question: I am making a simple text adventure game. I have a room class and an item class.
Each room has multiple items, and I am trying to make a method called addItem to store theitems in an ArrayList, but I get a NullPointerException when I try to add an item.
Room class
public class Room
{
    private String description;
    private HashMap<String, Room> exits;
    private ArrayList<Item>items;

    /**
     * Create a room described "description". Initially, it has
     * no exits. "description" is something like "a kitchen" or
     * "an open court yard".
     * @param description The room's description.
     */
    public Room(String description)
    {
        this.description=description;
        exits = new HashMap<String, Room>();
        items = new ArrayList<Item>();
    }

    /**
     * Define an exit from this room.
     * @param direction The direction of the exit.
     * @param neighbor  The room to which the exit leads.
     */
    public void setExit(String direction, Room neighbor)
    {
        exits.put(direction, neighbor);
    }

    /**
     * @return The short description of the room
     * (the one that was defined in the constructor).
     */
    public String getShortDescription()
    {
        return description;
    }

    /**
     * Return a description of the room in the form:
     *     You are in the kitchen.
     *     Exits: north west
     * @return A long description of this room
     */
    public String getLongDescription()
    {
        return "You are " + description + ".\n" + getExitString();
    }

    /**
     * Return a string describing the room's exits, for example
     * "Exits: north west".
     * @return Details of the room's exits.
     */
    private String getExitString()
    {
        String returnString = "Exits:";
        Set<String> keys = exits.keySet();
        for(String exit : keys) {
            returnString += " " + exit;
        }
        return returnString;
    }

    /**
     * Return the room that is reached if we go from this room in direction
     * "direction". If there is no room in that direction, return null.
     * @param direction The exit's direction.
     * @return The room in the given direction.
     */
    public Room getExit(String direction)
    {
        return exits.get(direction);
    }
    /**
     * adds new item to the room
     */
    public void addItem(String description)
    {
        Item Iitem = new Item(description);
        items.add(Iitem);
    }
}

Item Class
public class Item
{
   private String description;

    /**
     * Constructor for objects of class Item
     */
    public Item(String description)
    {
        this.description=description;
    }
    /**
     * gets description of the item
     */
    public String getDescription()
    {
        return description;
    }

}

Comment: where are you getting exception ?? please post the exception trace
Comment: On a side note. Do you really want `Item` to extend `Room`? I mean, with your current code, every `Item` has a `getExit` method... as well as `setExit`, `addItem`, etc.
Comment: -1 for indicating the failing line.
Comment: yeah.. i figured that it doesnt have to extend.. its all ok
Comment: without the "extend" you cannot call "super"... And by the way, is your question answered? If yes, please accept an answer by clicking the hollow check mark :)
Comment: yeah.. i fixed it.. will update the code
Answer: You never initialized items, so it's null.
items = new ArrayList<Item>();

Also I suggest you use interface for declaration, instead of a specific implementation
private Map<String, Room> exits;        // stores exits of this room.
private List<Item> items;

Comment: oh yeah :) my bad.. i knew i was missing something obvious
Comment: Usually the stacktrace of the exception gives you all the information you need to fix it. I suggest you learn to read them ;)
Comment: http://fr33kk0mpu73r.blogspot.com.es/2013/11/reading-java-exception-stacktraces.html
Comment: @user3401005: I just downloaded BlueJ and tried to instantiate your class and call a method, and when I do so a "Terminal window" opens where the lower part (error console) shows in red the stack trace and it can be copied there and also individual lines can be clicked to open the code.
Answer: You have not initialize the ArrayList<Item> items
You need to do:
ArrayList<Item> items = new ArrayList<Item>();

Comment: 100% sure. You can try and see.
Comment: @m0skit0 Are You sure?
Comment: @m0skit0 Well, it didn't, and whatever.
Comment: Lool your comment was after my edit, so i asked you that are you sure, then you insisted that it throw a warring.

Null Pointer Exception in Text Game


Calculating $\sum_{k=1}^{\infty} { \frac{(3k-3)!}{(3k)!} }$

Question: I was studying series ( accent on power series ) and came across this one:
$$S =\sum_{k=1}^{\infty} { \frac{(3k-3)!}{(3k)!} }$$
To be precise, the problem originally states:

Inspect the series convergence for $\frac{1}{2*3} + \frac{1}{4*5*6} + \frac{1}{7*8*9}+ \dots$ and calculate series sum.

Of course the sum above can be written as:
$$S =\sum_{k=1}^{\infty} { \frac{1}{3k(3k-2)(3k-1)} }$$
Which seems like a neat thing to separate into partial fractions..But wait. $\sum_{k=0}^\infty\frac{A}{3k}$ diverges for any $A\in \mathbb{R}\backslash \{0\}. $
And of course, this is the slippery slope that causes sum of divergent series to be convergent. But how do I calculate the sum of this series. I hoped that taking a peek at the final result will give me some ideas but when i saw
$$S = \frac{1}{12}(\sqrt{3}\pi - 3\ln{3})$$
I decided to give up.  Can anyone give me a hint on where to start with this.
Comment: Compare with the answers [here](http://math.stackexchange.com/questions/112161/showing-sum-n-0-infty-frac13n13n2-frac-pi3-sqrt3), and [here](http://math.stackexchange.com/questions/367770/how-to-show-that-sum-n-1-infty-frac12n12n22n3-ln2-1-2?lq=1).
Comment: @DietrichBurde Interesting. The accepted answer does split the expression into partial fractions and then ( i assume ) uses the power series representation of $\frac{1}{3n+1}$ but what do i do with the term $\frac{A}{3k}$?
Comment: Look at the second link how to do it with three terms. See [here](http://math.stackexchange.com/questions/197595/how-to-show-that-that-sum-n-1-infty-left-frac13n-1-frac13n-2) for almost the same question.
Comment: @DietrichBurde Oh yes... I got so catched on that harmonic series that i thought i couldn't solve this...Thank you.
Answer: $$S =\sum_{k=1}^{\infty} { \frac{1}{3k(3k-2)(3k-1)} }=\sum_{k=1}^{\infty}\frac{1}{2} \left(\frac{1}{3k}-\frac{2}{3k-1}+\frac{1}{3k-2}\right)$$
$$=\sum_{k\ge1}\frac{1}{2}\int_0^1(x^{3k-1}-2x^{3k-2}+x^{3k-3})\,dx=\sum_{k\ge1}\frac{1}{2}\int_0^1x^{3k-3}(x^2-2x+1)\,dx$$
$$=\frac{1}{2}\int_0^1\sum_{k\ge1}(1-x)^2x^{3k-3}\,dx=\frac{1}{2}\int_0^1\frac{(1-x)^2}{1-x^3}\,dx$$
$$=\frac{1}{2}\int_0^1\frac{1-x}{1+x+x^2}\,dx$$
This can then be finished off through a sequence of standard techniques for dealing with such integrals ($x=\frac{-1}{2}+\frac{\sqrt{3}}{2}\tan\theta$, etc.)
Comment: Yes, this is almost the same answer as [here](http://math.stackexchange.com/questions/197595/how-to-show-that-that-sum-n-1-infty-left-frac13n-1-frac13n-2).
Comment: Good to hear there's precedent. I must have started writing before I saw your post above - thanks in any case.
Answer: Euler's beta function gives an approach with a straightforward generalization:
$$\begin{eqnarray*}\sum_{k\geq 1}\frac{(3k-3)!}{(3k)!}=\sum_{k\geq 1}\frac{\Gamma(3k-2)}{\Gamma(3k+1)}&=&\frac{1}{\Gamma(3)}\sum_{k\geq 1}B(3k-2,3)\\&=&\frac{1}{\Gamma(3)}\int_{0}^{1}\sum_{k\geq 1}(1-t)^2 t^{3k-3}\,dt\\&=&\frac{1}{2}\int_{0}^{1}\frac{(1-t)^2}{1-t^3}\,dt\\[0.2cm]&=&\color{red}{\frac{\pi\sqrt{3}-3\log(3)}{12}}.\end{eqnarray*}$$
Answer: $\newcommand{\angles}[1]{\left\langle\,{#1}\,\right\rangle}
 \newcommand{\braces}[1]{\left\lbrace\,{#1}\,\right\rbrace}
 \newcommand{\bracks}[1]{\left\lbrack\,{#1}\,\right\rbrack}
 \newcommand{\dd}{\mathrm{d}}
 \newcommand{\ds}[1]{\displaystyle{#1}}
 \newcommand{\expo}[1]{\,\mathrm{e}^{#1}\,}
 \newcommand{\half}{{1 \over 2}}
 \newcommand{\ic}{\mathrm{i}}
 \newcommand{\iff}{\Longleftrightarrow}
 \newcommand{\imp}{\Longrightarrow}
 \newcommand{\Li}[1]{\,\mathrm{Li}}
 \newcommand{\ol}[1]{\overline{#1}}
 \newcommand{\pars}[1]{\left(\,{#1}\,\right)}
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\ul}[1]{\underline{#1}}
 \newcommand{\root}[2][]{\,\sqrt[#1]{\,{#2}\,}\,}
 \newcommand{\totald}[3][]{\frac{\mathrm{d}^{#1} #2}{\mathrm{d} #3^{#1}}}
 \newcommand{\verts}[1]{\left\vert\,{#1}\,\right\vert}$
\begin{align}
\color{#f00}{S} & =
\sum_{k = 1}^{\infty}{\pars{3k - 3}! \over \pars{3k}!} =
\sum_{k = 0}^{\infty}{1 \over \pars{3k + 3}\pars{3k + 2}\pars{3k + 1}}
\\[3mm] & =
\sum_{k = 0}\bracks{%
{1 \over 6\pars{k + 1}} + {1 \over 2\pars{3k + 1}} - {1 \over 3k + 2}}
\\[3mm] & =
{1 \over 6}\sum_{k = 0}^{\infty}\pars{{1 \over k + 1} - {1 \over k + 1/3}} +
{1 \over 3}\sum_{k = 0}^{\infty}\pars{{1 \over k + 1/3} - {1 \over k + 2/3}}
\\[3mm] & =
{1 \over 6}\bracks{\Psi\pars{1 \over 3} - \Psi\pars{1}} +
{1 \over 3}\bracks{\Psi\pars{2 \over 3} - \Psi\pars{1 \over 3}}
\\[3mm] & =
\fbox{$\ds{\
\color{#f00}{-\,{1 \over 6}\,\Psi\pars{1 \over 3} + {1 \over 6}\,\gamma +
{1 \over 3}\,\Psi\pars{2 \over 3}}\ }$}
\end{align}

$\ds{\gamma}$ and $\ds{\Psi}$ are the Euler-Mascheroni constant and the Digamma Function, respectively. Note that $\ds{\Psi\pars{1} = -\gamma}$.

Also $\ds{\pars{~\mbox{see}\ \mathbf{8.366}.6.\ \mbox{and}\ \mathbf{8.366}.7.\ \mbox{in  Gradshteyn & Rizhik, page}\ 905,\ 7^{\mathrm{th}}\ \mbox{ed.}~}}$,
\begin{align}
&\left\lbrace\begin{array}{rcl}
\ds{\Psi\pars{1 \over 3}} & \ds{=} &
\ds{-\gamma - {\root{3} \over 6}\,\pi - {3 \over 2}\,\ln\pars{3}}
\\[2mm]
\ds{\Psi\pars{2 \over 3}} & \ds{=} &
\ds{-\gamma + {\root{3} \over 6}\,\pi - {3 \over 2}\,\ln\pars{3}}
\end{array}\right.
\\[5mm]
\mbox{which leads to}\quad &\
\color{#f00}{S} =
\sum_{k = 1}^{\infty}{\pars{3k - 3}! \over \pars{3k}!} =
\color{#f00}{{1 \over 12}\bracks{\root{3}\pi - 3\ln\pars{3}}} \approx 0.1788
\end{align}


Is there no easy way to use the Hyper-V Manager remotely?

Question: At my workplace we've been using VMware vSphere as our VM server which uses the vSphere client to connect. Using a simple port forwarding rule on our router we've been able to allow all employees to access the VMs from anywhere they have internet access with just a username and password to log in.
I'm building a new VM server and I was testing Hyper-V to see if it will fit our needs better. I like the newer features of Hyper-V Enhanced Session Mode as they would greatly help with our workflow.
However I'm running into one huge problem -- there seems to be no easy way to use the Hyper-V Manager remotely. With VMware we are able to do everything by simply installing 1 client program on each client and forwarding only 2 ports on the router.  The Hyper-V Manager seems to require a big confusing list of ports (which I found here). But it doesn't end there--even if I forward all of the proper ports I still cannot connect due to Windows security.
Even within the same LAN with Windows Firewall disabled you cannot connect to another server using the Hyper-V Manager unless you are on the same Windows Domain and you add the client user account to the Hyper-V Administrators group on the server.  At my workplace we do not use a Windows Domain as we are a fairly small team of developers and we work primarily remotely.
From what I've read about getting Hyper-V to work with a Workgroup is that you need identical user accounts on both the client and the server and the password needs to match -- which is a nightmare to manage.
I was able to find a configuration script here to simplify the set up but it seems like a lot of micromanagement and it still doesn't address trying to connect over the internet.
Why is this so hard? When I want to use Remote Desktop to take control of a server I need to only forward a single port and it asks me for a username and a password of an account on the server.  Why can't the Hyper-V Manager do the same?  Is there not an intuitive way to do this?
EDIT:
To follow up: I have, for testing purposes, modified my router's port forwarding settings for forward all UDP/TCP ports to my Hyper-V Server.  I also disabled Windows Firewall on both the client and the server.  Then I created an identical username/password account on both the server and my client.  And I enabled "Anonymous DCOM" as per the instructions above in John Howard's articles.  I'm still getting an error "the operation on computer xxx failed".
The same steps were working for connecting to the server over the LAN.  And with all ports being forwarded and no firewalls in place I don't see why it shouldn't be working over the internet.
I am tempted to setup a VPN just for using Hyper-V Manager -- but according to my research even connecting over a VPN is troublesome according to this article here!
Comment: Have you considered remote desktop into the server and using it "locally". You can even use RemoteApp to make the remote application appear "local".
Comment: @chutz: Only 1 person can RDP into the server at a time.  I may have 3-6 people using the Hyper-V Manager at one time.  I would have to create a new local VM for each user just to run the Hyper-V Manager to access other VMs.  This is what I have decided I will end up doing if there is no other option.
Answer: Microsoft has a tecnet article on how to configure Hyper-V for remote management in a workgroup (without a domain), you can find that here.


How to explain sudden increase in Daily Sessions and decrease in Queries?

Question: Our educational Action suddenly had Daily Sessions increased from 28 to 208 (8 times more).
Also the Queries per session decreased from 6.4 to 1.5 (4 times less).
This happened on 6/20/2019.
Here's a graph from Analytics page in DialogFlow console:

There were no changes to our Action and no recent marketing has been done.
How to find out what caused these dramatic changes?
Comment: Check for `Discovery` section under `Analytics`. Google is giving suggestions based on your intent keyword phrases. I have not shared my action with anyone still it has 900 conversation in just a week.
Comment: I see "Your app had no implicit discoveries for the selected time period" when you go to Discovery section under Analytics.
Answer: Turns out Google Health Checks (about 8 per hour) started to be included in session count.


how to enable audit framework in arch linux 3.12 kernel?

Question: I want to use audit framework on my latest arch linux, but running sudo auditctl -w /home/ in console gives me
Error - audit support not in kernel
 Cannot open netlink audit socket
I tried to enable of course audit via kernel boot params setting audit flag: GRUB_CMDLINE_LINUX_DEFAULT="quiet audit=1" but nothing changes after reboot, still the same error.
Anybody knows how to fix it?
Comment: Can you see `"audit=1"` in `/proc/cmdline` in booted kernel?
Comment: yes, `BOOT_IMAGE=/boot/vmlinuz-linux root=UUID=59c7ed3d-5c1a-464e-8da0-6bcf76bc19d2 rw quiet audit=1`, also there's a mistake, I have 3.18.2 kernel.
Comment: audit=      [KNL] Enable the audit sub-system
            Format: { "0" | "1" } (0 = disabled, 1 = enabled)
            0 - kernel audit is disabled and can not be enabled
                until the next reboot
            unset - kernel audit is initialized but disabled and
                will be fully enabled by the userspace auditd.
            1 - kernel audit is initialized and partially enabled,
                storing at most audit_backlog_limit messages in
                RAM until it is fully enabled by the userspace
                auditd.
Comment: May be you also need to set `audit_backlog_limit=` in cmd line.
Comment: audit_backlog_limit= [KNL] Set the audit queue size limit.
            Format:  (must be >=0)
            Default: 64
Comment: don't think so, because even getting this value via `sudo auditctl -s` gives me `Error - audit support not in kernel`
Comment: Recompile kernel with audit support then.
Answer: Recompile a kernel using ABS to get audit support.
You will need to add CONFIG_AUDIT=y in the config file before makepkg -s.
P.S. Compilation might take very long.
Comment: Yes, I did just what you suggested, with ABS arch linux kernel compilation tool, thx. I just forgot about this question, and didn't answer it by myself. Anyway, audit framework gave me too bad performance on my machine, so I vanished using it.
Comment: I was trying to do that in order to use e4rat. i


Detect Touch on Edge of the UIVIEW

Question: How to detect the touch on the edge or border of the view in iOS Swift. I want to increase UIView width and height when the user drags the border of the UIView.
Comment: You might want to take a look at the following SO thread - http://stackoverflow.com/questions/8460119/how-to-resize-uiview-by-dragging-from-its-edges It pays to do some searching before you ask a question :)
Comment: Possible duplicate of [How to resize UIView by dragging from its edges?](http://stackoverflow.com/questions/8460119/how-to-resize-uiview-by-dragging-from-its-edges)
Comment: @ Fahim, I'm guessing it actually isn't a duplicate because the OP is asking how to *detect the touch on the edge* of a UIView, and this question addresses a UIView with "handles". That said, I'd advise the OP to both (1) look at this question and (2) consider how virtually every other CocoaTouch app does it - by using the pinch gesture. Detecting a touch is not very user-friendly... Apple suggests making your buttons 40x40 in size minimally. Can you really expect the same exactness that a mouse pointer yields? You should either use handles or the pinch gesture.
Comment: @ Fahim, that question solution is detecting the touch on corners of the UIView where as I want to detect the touch on the edges.
Comment: @dfd  that's what I want to know, do I need to add 4 different invisible views to detect the touch on the edges, is this the right view or there is any another way?
Comment: Consider that Apple, back in 2007, and after a few years of user testing, concluded that the average touch hit needs a 40x40 button. (Or in other words, people have fat fingers.) Now consider what a "normal" edge of a UIView is, 1 point. My question for *you* is - what constitutes an edge? If you create *visible* handles, a user will see them and have the right cues to use them. If you use a pinch gesture, users have had 10 years to know it resizes. I suggest to you that you are not only fighting the known ways to do it, you are also not yet defining what a view's "edge" is.
Comment: @dfd if you check facebook iOS app, when we edit crop an image, the rectangle can be resized by touching on edge, so I want to implement the same.
Answer: got the solution Modified How to resize UIView by dragging from its edges? solution.
Swift Version and code to detect edges as well as corners
<code>class OverlayView: UIView {

    /*
    // Only override draw() if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func draw(_ rect: CGRect) {
        // Drawing code
    }
    */

    static var kResizeThumbSize:CGFloat = 44.0
    private typealias `Self` = OverlayView

    var imageView = UIImageView()

    var isResizingLeftEdge:Bool = false
    var isResizingRightEdge:Bool = false
    var isResizingTopEdge:Bool = false
    var isResizingBottomEdge:Bool = false

    var isResizingBottomRightCorner:Bool = false
    var isResizingLeftCorner:Bool = false
    var isResizingRightCorner:Bool = false
    var isResizingBottomLeftCorner:Bool = false

        //Define your initialisers here

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        if let touch = touches.first {
            let currentPoint = touch.location(in: self)

            isResizingBottomRightCorner = (self.bounds.size.width - currentPoint.x < Self.kResizeThumbSize && self.bounds.size.height - currentPoint.y < Self.kResizeThumbSize);
           isResizingLeftCorner = (currentPoint.x < Self.kResizeThumbSize && currentPoint.y < Self.kResizeThumbSize);
            isResizingRightCorner = (self.bounds.size.width-currentPoint.x < Self.kResizeThumbSize && currentPoint.y < Self.kResizeThumbSize);
            isResizingBottomLeftCorner = (currentPoint.x < Self.kResizeThumbSize && self.bounds.size.height - currentPoint.y < Self.kResizeThumbSize);

            isResizingLeftEdge = (currentPoint.x < Self.kResizeThumbSize)
            isResizingTopEdge = (currentPoint.y < Self.kResizeThumbSize)
            isResizingRightEdge = (self.bounds.size.width - currentPoint.x < Self.kResizeThumbSize)

            isResizingBottomEdge = (self.bounds.size.height - currentPoint.y < Self.kResizeThumbSize)

            // do something with your currentPoint

        }
    }

    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        if let touch = touches.first {
            let currentPoint = touch.location(in: self)
            // do something with your currentPoint
        }
    }

    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        if let touch = touches.first {
            let currentPoint = touch.location(in: self)
            // do something with your currentPoint

            isResizingLeftEdge = false
             isResizingRightEdge = false
             isResizingTopEdge = false
             isResizingBottomEdge = false

             isResizingBottomRightCorner = false
             isResizingLeftCorner = false
             isResizingRightCorner = false
             isResizingBottomLeftCorner = false

        }
    }
</code>

Detect Touch on Edge of the UIVIEW


How can i return two objects in javascript

Question: As an example
I have two arrays
const tempData = [
          { day: "Mon", temp: 33.6 },
          { day: "Tue", temp: 34.6 },
          { day: "Wed", temp: 33.1 },
          { day: "Fri", temp: 35.6 }
        ];
const coughData = [
          { day: "Mon", count: 2 },
          { day: "Wed", count: 1 },
          { day: "Thur", count: 1 },
          { day: "Fri", count: 3 },
          { day: "Sat", count: 1 }
        ];

I need to merge these arrays into one so that if the day matches the count value adds to that object if it doesn't match it adds both objects to the array.
Don't know if the explanation isn't so clear but
The expected result should be like this:
const data = [
          { day: "Mon", temp: 33.6, count: 2 },
          { day: "Tue", temp: 34.6 },
          { day: "Wed", temp: 33.1, count: 1 },
          { day: "Thur", count: 1 },
          { day: "Fri", temp: 35.6, count: 3 },
          { day: "Sat", count: 1 }
        ];

I am trying to use map function like so but can't understand how do I return both the objects if they don't match:
const data = tempData.map(temp => {
          coughData.map(cough => {
            if (temp.day === cough.day) {
              return (temp.count = cough.count);
            } else {
              return cough;
            }
          });
          return temp;
        });

Comment: ```Array.map``` will transform array rows, it's name is map, So you have to use ```Array.reduce```.
Answer: You could collect all data grouped by day in an object and get the values as result set.

const
    addToCollection = (collection, key) => o => Object.assign(collection[o[key]] ??= {}, o),
    tempData = [{ day: "Mon", temp: 33.6 }, { day: "Tue", temp: 34.6 }, { day: "Wed", temp: 33.1 }, { day: "Fri", temp: 35.6 }],
    coughData = [{ day: "Mon", count: 2 }, { day: "Wed", count: 1 }, { day: "Thur", count: 1 }, { day: "Fri", count: 3 }, { day: "Sat", count: 1 }],
    collection = {};

tempData.forEach(addToCollection(collection, 'day'));
coughData.forEach(addToCollection(collection, 'day'));

console.log(Object.values(collection));
.as-console-wrapper { max-height: 100% !important; top: 0; }
Answer: You can first merge the objects of the arrays, and then use .reduce() along with a Map to accumulate the values. The Map can be keyed by the day property, which will allow you to group related object properties together. You can then use Array.from() to transform your Map back into an array of objects like so:

const tempData = [{ day: "Mon", temp: 33.6 }, { day: "Tue", temp: 34.6 }, { day: "Wed", temp: 33.1 }, { day: "Fri", temp: 35.6 }];
const coughData = [{ day: "Mon", count: 2 }, { day: "Wed", count: 1 }, { day: "Thur", count: 1 }, { day: "Fri", count: 3 }, { day: "Sat", count: 1 }];

const arr = [...tempData, ...coughData];

const result = Array.from(arr.reduce((map, {day, ...rest}) => {
  const seen = map.get(day) || {day};
  return map.set(day, {...seen, ...rest});
}, new Map).values());

console.log(result);
Comment: If you add a `day` key instead of empty object literal here: `map.get(day) || { day }`, you can get `Array.from(mapFromReduce.values())`. No need for the additional operation of `([day, obj]) => ({day, ...obj})`
Comment: @adiga Nice, that's much nicer, thanks :D
Answer: let newArray = Array();
let longer = (tempData.length <= coughData.length) ? coughData.length :
tempData.length;
for(let i = 0, j = 0; i < longer; ++i, ++j) {
    newArray.push(Object.assign(coughData[i], tempData[j]));
}

Print to console:
[ { day: 'Mon', count: 2, temp: 33.6 },
{ day: 'Tue', count: 1, temp: 34.6 },
{ day: 'Wed', count: 1, temp: 33.1 },
{ day: 'Fri', count: 3, temp: 35.6 },
{ day: 'Sat', count: 1 } ]

Answer:

const tempData = [
    { day: "Mon", temp: 33.6 },
    { day: "Tue", temp: 34.6 },
    { day: "Wed", temp: 33.1 },
    { day: "Fri", temp: 35.6 }
];
const coughData = [
    { day: "Mon", count: 2 },
    { day: "Wed", count: 1 },
    { day: "Thur", count: 1 },
    { day: "Fri", count: 3 },
    { day: "Sat", count: 1 }
];

const tempRes = [...tempData, ...coughData];
const result = tempRes.reduce((acc, curr) => {
    const { day, ...rest } = curr;
    acc[day] = acc[day] ? Object.assign({}, acc[day], rest) : curr
    return acc;
}, {})
console.log(Object.values(result))
.as-console-wrapper { max-height: 100% !important; top: 0; }
Answer: You can use Object.assign() javascript function.
The Object.assign () method is used to copy the values of all the enumerable properties of one or more source objects to a target object. This method will return the target object
Like so:

const target = { a: 1, b: 2 };
const source = { b: 4, c: 5 };

const returnedTarget = Object.assign(target, source);

console.log(target);
// expected output: Object { a: 1, b: 4, c: 5 }

console.log(returnedTarget);
// expected output: Object { a: 1, b: 4, c: 5 }

https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Object/assign


How to create a module to allow for multiple instances of the same module with different variable parameters

Question: How do you create a module to allow for multiple instances of the same module block with different variable parameters. I know how to create global parameters but that will apply to that block across the site.
this is an image of opening up the settings for the block on the panel
Answer: Generate your blocks same way block module does: appending an id. Then store your configuration indexed by this id. You can store your values in a custom table (see schema api and install file syntax) or in the variable table (using variable_get() and variable_set()).
Whenever an operation with a block happens you receive the block id. Use the block id to access or set your configuration data. For example, the code for rendering a block should be the same for all your custom blocks, but you feed that code with different configurations that you read from your custom table or variable table using the provided block id.
Comment: very cool, I will do that. Is it a specific menu hook that I need to use to have this property show up when a user clicks settings within the panel?
Comment: Yes, use hook_block_configure:

https://api.drupal.org/api/drupal/modules!block!block.api.php/function/hook_block_configure/7

Keep in mind that what I've called id is the delta parameter. Also, check other block hooks (view, info, save, etc)
Comment: This works for setting usettings in the block page but when I go to a panel and hit the settings on the content it still only shows the title as editable. Any other thoughts?
Comment: I think that question is more related to Panels, but I'm not used to panels. Check for existing Panels hooks that allow you to change those settings.
Comment: Ok thanks, someone mentioned creation a c tools plugin.


GRUB_DEFAULT seems to be ineffectual when trying to boot a custom kernel by ID on Debian 8

Question: I've built a custom kernel on a Debian 8 machine, and I want to set it as the default. A seemingly simple task, but I can't get it to work for the life of me.
I built my kernel using the official source code (via git), not using the vendor tarball provided my debian. Once built, I installed the kernel and modules with:
$ sudo make modules_install install

This installed a new menu entry into grub, which indeed works if you manually select it at boot time. So that's good.
Now, to get this to boot by default, I must edit /etc/default/grub and change GRUB_DEFAULT. At the top of the file is a comment pointing the user to an info page, which says:
'GRUB_DEFAULT'
     The default menu entry.  This may be a number, in which case it
     identifies the Nth entry in the generated menu counted from zero,
     or the title of a menu entry, or the special string 'saved'.  Using
     the id may be useful if you want to set a menu entry as the default
     even though there may be a variable number of entries before it.

     For example, if you have:

     menuentry 'Example GNU/Linux distribution' --class gnu-linux --id example-gnu-linux {
        ...
     }

     then you can make this the default using:

          GRUB_DEFAULT=example-gnu-linux

     Previously it was documented the way to use entry title.  While
     this still works it's not recommended since titles often contain
     unstable device names and may be translated

     If you set this to 'saved', then the default menu entry will be
     that saved by 'GRUB_SAVEDEFAULT' or 'grub-set-default'.  This
     relies on the environment block, which may not be available in all
     situations (*note Environment block::).

     The default is '0'.

First, it's unclear from the prose if an "id" is the same as a "title". That aside, it looks like I should use the string after the --id in the generated grub config.
So, make install inserted the following into /boot/grub/grub.cfg:
    menuentry 'Debian GNU/Linux, with Linux 3.16.36krunsystickless+' --class debian --class gnu-linux --class gnu --class os $menuentry_id_option 'gnulinux-3.16.36krunsystickless+-advanced-197f20c1-1808-41b5-831f-b85a40358757' {
        load_video
        insmod gzio
        if [ x$grub_platform = xxen ]; then insmod xzio; insmod lzopio; fi
        insmod part_msdos
        insmod ext2
        set root='hd0,msdos1'
        if [ x$feature_platform_search_hint = xy ]; then
          search --no-floppy --fs-uuid --set=root --hint-bios=hd0,msdos1 --hint-efi=hd0,msdos1 --hint-baremetal=ahci0,msdos1  197f20c1-1808-41b5
-831f-b85a40358757
        else
          search --no-floppy --fs-uuid --set=root 197f20c1-1808-41b5-831f-b85a40358757
        fi
        echo    'Loading Linux 3.16.36krunsystickless+ ...'
        linux   /boot/vmlinuz-3.16.36krunsystickless+ root=UUID=197f20c1-1808-41b5-831f-b85a40358757 ro  quiet console=ttyS0,115200n8 intel_psta
te=disable
        echo    'Loading initial ramdisk ...'
        initrd  /boot/initrd.img-3.16.36krunsystickless+
    }

Where, earlier in the file $menuentry_id_option is set:
if [ x"${feature_menuentry_id}" = xy ]; then
  menuentry_id_option="--id"
else
  menuentry_id_option=""
fi

So presumably, I should set GRUB_DEFAULT in /etc/grub/default to:
gnulinux-3.16.36krunsystickless+-advanced-197f20c1-1808-41b5-831f-b85a40358757

Then run:
$ sudo update-grub
Generating grub configuration file ...
Found linux image: /boot/vmlinuz-3.16.36softdevnohzfullall
Found initrd image: /boot/initrd.img-3.16.36softdevnohzfullall
Found linux image: /boot/vmlinuz-3.16.36krunsystickless+
Found initrd image: /boot/initrd.img-3.16.36krunsystickless+
Found linux image: /boot/vmlinuz-3.16.36krunsystickless+.old
Found initrd image: /boot/initrd.img-3.16.36krunsystickless+
Found linux image: /boot/vmlinuz-3.16.0-4-amd64
Found initrd image: /boot/initrd.img-3.16.0-4-amd64
done

Before finally rebooting.
But this does not seem to work. The same kernel as before is instead booted. Does anyone know why?
Other things I have tried:

Numeric index GRUB_DEFAULTS -- seem to have no effect.
Escaping the plus in the kernel id.
grub-set-default

I'm going to look into feature_menuentry_id now, but I have a feeling it will be a red herring. If anyone can put me out of my misery in the meantime, I will be most grateful.
Thanks
Comment: Have you tried using the "grub2-set-default" command?
Comment: `sudo grub-set-default gnulinux-3.16.36krunsystickless+-advanced-197f20c1-1808-41b5-831f-b85a40358757` does not work. There is no `grub2-set-default` command on my system.
Comment: For what it's worth, the `GRUB_DEFAULT=saved` and `GRUB_SAVEDEFAULT=true`  (i.e. save what I choose next time) hack worked this time, but for the next server I won't have access to the grub menu (no management console on that one), so I'd still like to sort this out.
Comment: After using the `saved` hack, the file `/boot/grub/grubenv` contains `saved_entry=gnulinux-advanced-197f20c1-1808-41b5-831f-b85a40358757>gnulinux-3.16.36krunsystickless+-advanced-197f20c1-1808-41b5-831f-b85a40358757`. It's likely this is the value `GRUB_DEFAULT` was expecting, although I have no idea how I was supposed to infer this from the info page :(
Answer: In the end I managed to boot my kernel with the following line in /etc/default/grub:
GRUB_DEFAULT=gnulinux-advanced-197f20c1-1808-41b5-831f-b85a40358757>gnulinux-3.16.36krunsystickless+-advanced-197f20c1-1808-41b5-831f-b85a40358757

The documentation is misleading. You cannot simply put the ID into GRUB_DEFAULT if there is a sub-menu involved. You have to think in terms of navigating the grub menu using (potentially many) ids. The > above (which I've not found in the docs btw) means "go into this sub-menu".
I hope this helps others confused by this same issue.
Cheers