Fourier cosine transform of $\arctan(1/x)/x$

Question: Consider
$$
\int_{-\infty}^{\infty}\cos(\omega x)\frac{\arctan\left(\frac{1}{x}\right)}{x} dx, \quad \text{for } \omega > 0,
$$
although for $\omega \in \mathbb{C}$ would be interesting. What is the above cosine transform? Does it exist?

My attempt so far: for $x \in \mathbb{R}$ we know that
$$
\arctan(x) + \arctan(1/x) = \text{sign}(x)\pi/2,
$$
and we know that
$$
\int_{-\infty}^{\infty}\cos(\omega x)\frac{\arctan(x)}{x} dx = \pi \Gamma(0,|\omega|),
$$
where $\Gamma$ is the upper incomplete Gamma function. Using this, then
$$
\begin{align}
\int_{-\infty}^{\infty}\cos(\omega x)\frac{\arctan\left(\frac{1}{x}\right)}{x} dx
&= \int_{0}^{\infty}\cos(\omega x)\frac{\arctan\left(\frac{1}{x}\right)}{x} dx + \int_{-\infty}^{0}\cos(\omega x)\frac{\arctan\left(\frac{1}{x}\right)}{x} dx \\
&= -\int_{-\infty}^{\infty}\cos(\omega x)\frac{\arctan\left(x\right)}{x} dx -\frac{\pi}{2}\int_{-\infty}^{0}\cos(\omega x)\frac{1}{x} dx + \frac{\pi}{2}\int_{0}^{\infty}\cos(\omega x)\frac{1}{x} dx \\
&= -\pi\Gamma(0,|\omega|) - \pi\int_{0}^{\infty}\cos(\omega x)\frac{1}{x} dx.
\end{align}
$$
But the integral on the right does not make sense. I assume this is not the correct approach.
Comment: The original integral diverges at x=0.
Comment: @Svyatoslav Yes, I understand, although that doesn't mean the FT doesn't exist
Answer: If I am not running completely nuts, we can attack this via fantasy and brute force. First of all notice that the integral is even, hence we can write it as
$$2\int_0^{+\infty} \cos(\omega x) \dfrac{\arctan(1/x)}{x}\ \text{d}x$$
Now we call this integral $F(\omega, x)$.
Let's now differentiate wrt $\omega$:
$$\dfrac{\partial F}{\partial\omega} = -2\int_0^{+\infty} \sin(\omega x) \arctan\left(\dfrac{1}{x}\right)\ \text{d}x$$
This integral can be computed (there are lots of ways to do this, also it is absolutely convergent), and we have:
$$\dfrac{\partial F}{\partial \omega} = -2\left(\frac{\pi  e^{-\frac{\omega}{2}} \sinh \left(\frac{\omega}{2}\right)}{\omega}\right)$$
This result holds iff $\omega > 0$ if $\omega\in\mathbb{R}$, or as I wrote in the comment, for $\Im(\omega)\leq 0$ but we can manage to extend it for every $\omega \in \mathbb{C}$.
If you master a bit of elementary calculus techniques, you can easily find that
$$\left(\frac{\pi  e^{-\frac{\omega}{2}} \sinh \left(\frac{\omega}{2}\right)}{\omega}\right) = \frac{\pi -\pi  e^{-\omega}}{2 \omega}$$
To get $F(\omega)$ we now integrate this with respect to $\omega$:
$$F(\omega) = -2\int \frac{\pi -\pi  e^{-\omega}}{2 \omega}\ \text{d}\omega$$
The integration is rather easy, and it does make a Special Function to pop out: the Exponential Integral Special Function:
$$-2\int \frac{\pi -\pi  e^{-\omega}}{2 \omega} = -\pi  (\log (\omega)-\text{Ei}(-\omega))$$
You can find more on the Exponential Integral here: https://en.wikipedia.org/wiki/Exponential_integral
P.s. In a more rigorous way, we should attack the first part with the principal value method, just to be sure. But eventually it leads to the same result.
Comment: Just a small comment - the integral should be $F(\omega)$ only, not $F(\omega,x)$. Otherwise great answer.
Comment: $\omega$ is complex. What does it mean $w>0$?
Comment: @Raffaele The OP did not specify $\omega \in \mathbb{C}$. In any case the same result still holds for $\omega \in \mathbb{C}$. One can show that it holds perfectly for $\Im(\omega)\leq 0$, and then to $\Im(\omega) >0$ (I guess this part will be left to the very curious man)
Comment: Inverse cosine transform given by *Mathematica* is quite different from the original function $$\gamma  \pi ^2 \delta (x)+\frac{\pi ^2 \theta (x)}{2 x}-\frac{\pi  \arctan x}{x}$$
Comment: @Raffaele Uhm, I will check it again then. Perhaps I used too much fantasy :D
Comment: @Raffaele is that $x$ in place of $\omega$?
Comment: @Spaceman No, it's the *Inverse* Cosine Transform I computed to verify Turing's answer
Comment: It seems that this integral diverges. Experimenting with \omega = 1 with Wolfram Alpha confirms this. I wonder where the proof may fall through.

Also, thank you very much for a wonderful answer
Answer: I fact the initial integral $g(\omega)=\frac{1}{2}\int_{-\infty}^{\infty}\cos(\omega x)\frac{\arctan\left(\frac{1}{x}\right)}{x} dx=\int_{0}^{\infty}\cos(\omega x)\frac{\arctan\left(\frac{1}{x}\right)}{x} dx$ diverges at a point $х=0$ logarithmically - even in a principal value sense.
Indeed, the integrand is even, and at $x\to0$ behaves as $\sim 1*\frac{\pi}{2}*\frac{1}{x}$. To investigate the integral in more details let's make a regularisation at $x\to0$, for example by adding the second term.
Let's consider $$f(\omega) =g(\omega)-\frac{\pi}{2}\int_{0}^{\infty}\cos(\omega x)\frac{\exp(-ax)}{x} dx$$ This integrand does not have a singularity at $x=0$ and, as soon as $a\to{\infty}$ $f(\omega)\to{g(\omega)}$.
Differentiating by $\omega$  we get:
$\frac{df}{d\omega}=-\int_{0}^{\infty}\sin(\omega x)\arctan(\frac{1}{x}) dx+\frac{\pi}{2}\int_{0}^{\infty}\cos(\omega x)\exp(-ax) dx$.$$\frac{df}{d\omega}=\frac{\pi}{2}\left(\frac{\exp(-\omega)-1}{\omega}+\frac{\omega}{a^2+\omega^2}\right)$$
$f(\omega=0)=\frac{\pi}{2}\int_{0}^{\infty}\frac{\arctan(\frac{1}{x})}{x}dx-\frac{\pi}{2}\int_{0}^{\infty}\frac{\exp(-ax)}{x}dx$.
Integrating by parts we get: $f(0)=\int_{0}^{\infty}\frac{\log(x)}{1+x^2}dx-\frac{\pi}{2}a\int_{0}^{\infty}\log(x)\exp(-ax)dx=\frac{\pi}{2}\log(a)-\frac{\pi}{2}\int_{0}^{\infty}\log(x)\exp(-x)dx$
$$f(0)=\frac{\pi}{2}\log(a)+\frac{\pi}{2}\gamma$$ where  $\gamma=-\int_{0}^{\infty}\log(x)\exp(-x)dx$ - Euler constant.
$f(\omega)=f(0)+\int_{0}^{\omega}\frac{df}{dx}dx=\frac{\pi}{2}\log(a)+\frac{\pi}{2}\gamma+\frac{\pi}{2}\int_{0}^{\omega}\left(\frac{\exp(-x)-1}{x}+\frac{x}{a^2+x^2}\right)dx$.
Finally we get:
$$f(\omega)=\frac{\pi}{2}\left(\log(\omega)(\exp(-\omega)-1)+\frac{1}{2}\log(a^2+\omega^2)-\int_{\omega}^{\infty}\log(x)\exp(-x)dx\right)$$

$a\to{\infty}$ (we get the initial integral without regularisation):
$$f(\omega)\to{g(\omega)}\to\frac{\pi}{2}\log(a)\to\infty$$ as expected

$\omega\to{\infty}$ and $ (a\lt{\infty})$ $$f(\omega)\to-\frac{\pi}{2}\frac{\exp(-\omega)}{\omega}\to{0}$$
Answer: The function $f(x)=\frac{\arctan(1/x)}{x}$ is not locally integrable and is, therefore, not a tempered distribution.  We can define, however, a distribution that permits our defining the Fourier Transform.
We define the distribution $\psi(x)$ such that for any $\phi\in \mathbb{S}$ (i.e., $\phi$ is a Schwarz Space function)
$$\langle \psi, \phi\rangle = \int_{|x|\le 1}\left(\phi(x)-\phi(0)\right)\frac{\arctan(1/x)}{x}\,dx+\int_{|x|\ge 1}\phi(x)\frac{\arctan(1/x)}{x}\,dx\tag1$$
Equipped with the distribution defined in $(1)$, we proceed to determine the Fourier Transform of $\psi(x)$.

Applying $(1)$, we see that the Fourier transform, $\mathscr{F}\{\psi\}$ is defined as
$$\begin{align}
\langle \mathscr{F}\{\psi\},\phi\rangle &=\langle \psi,\mathscr{F}\{\phi\}\rangle\\\\
&=\int_{-\infty}^\infty \frac{\arctan(1/x)}{x}\int_{-\infty}^\infty \phi(k)\left(e^{ikx}-\xi_{[-1,1]}(x)\right)\,dk\,dx\\\\
&=\int_{-\infty}^\infty \phi(k)\int_{-\infty}^\infty \arctan(1/x)\frac{e^{ikx}-\xi_{[-1,1]}(x)}{x}\,dx\,dk\\\\
&=\int_{-\infty}^\infty \phi(k)\int_{-\infty}^\infty \arctan(1/x)\frac{\cos(kx)-\xi_{[-1,1]}(x)}{x}\,dx\,dk\\\\
&=2\int_{-\infty}^\infty \phi(k)\int_0^\infty (\pi/2-\arctan(x))\frac{\cos(kx)-\xi_{[-1,1]}(x)}{x}\,dx\,dk\\\\
&=\pi \int_{-\infty}^\infty \phi(k) \int_0^\infty \frac{\cos(|k|x)-\xi_{[0,1]}(x)}{x}\,dx\,dk\\\\
&-2\int_{-\infty}^\infty \phi(k) \int_0^\infty \arctan(x) \frac{\cos(|k|x)-\xi_{[0,1]}(x)}{x}\,dx\,dk\\\\
&=-\pi  \int_{-\infty}^\infty \phi(k) (\gamma +\log(|k|))\,dk\\\\
&-2\int_{-\infty}^\infty \phi(k) \int_0^\infty \arctan(x) \frac{\cos(|k|x)}{x}\,dx\,dk\\\\
&+2\int_{-\infty}^\infty \phi(k) \int_0^1 \frac{\arctan(x)}{x}\,dx\,dk\\\\
&=-\pi  \int_{-\infty}^\infty \phi(k) (\gamma +\log(|k|))\,dk\\\\
&-\pi \int_{-\infty}^\infty \phi(k) \Gamma(0,|k|)\,dk\\\\
&+2G\int_{-\infty}^\infty \phi(k)\,dk
\end{align}$$
where $G$ is Catalan's Constant, from which we conclude that in distribution,
$$\bbox[5px,border:2px solid #C0A000]{\mathscr{F}\{\psi\}(k)=2G-\pi (\Gamma(0,|k|)+\gamma+\log(|k|))}$$
Comment: Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackexchange.com/rooms/127719/discussion-on-answer-by-mark-viola-fourier-cosine-transform-of-arctan1-x-x).


Can I make an assumption about arbitrary numbers in a proof?

Question: Assume  $ x_1, x_2... x_{10} $ are different numbers and $ y_1, y_2... y_{10} $ are some arbitrary numbers. Prove that there exists some unique polynomial of degree not exceeding 9 such that:
$P(x_1)=y_1,P(x_2)=y_2...P(x_{10})=y_{10}$
Proof to the problem rests on the assumption that there is some polynomial Q(x) of degree not exceeding 9 such that:
$ Q(x_1)=y_1,Q(x_2)=y_2...Q(x_{10})=y_{10}$.
Is it a valid assumption in a proof of this sort?
Comment: Where $Q$ is what exactly? A polynomial? Of degree less than or equal to 9? If so, then no this only gets half the proof: that any such polynomial is unique. To assert the existence of a thing you want to prove the existence of invalidates any proof of existence.
Comment: Yes, a polynomial of degree < 9. Your second sentence is incomprehensible to me. Could you elaborate?
Comment: No, you may not assume anything that you can't prove (or your lecturer / teacher hasn't proved). Can you prove that $Q$ exists? (Hint: try to find $P_1$ with $P_1(x_1) = y_1$ and $P_2$ with $P_2(x_2) = y_2$, and combine them somehow to find $P$ with $P(x_1) = y_1$ and $P(x_2) = y_2$.)
Answer: Your assumption is incorrect because proving the existence of such a polynomial is an important part of the problem you are working on.
Here is a hint: Suppose you were given the problem with only two pairs $(x_1,y_1)$ and $(x_2,y_2)$. Then how would you find such a polynomial? Think in terms of a straight line. You are given two distinct (since $x_1 \neq x_2$) points so there always exists a straight line that passes through these points and the equation of that line will be polynomial of the required degree.
If you were given $3$ points then a parabola passes through it and so on.
If you are still unable to make progress then look for Lagrange Interpolation.
Answer: You need to prove two things: that there is such a polynomial and that there is only one.  To prove that there is one, you can show a way to construct it.  Can you find a way to construct a polynomial $Q_1(x)$ of degree not exceeding $9$ such that $Q_1(x_1)=y_1,Q_1(x_2)=0...Q_1(x_{10})=0$?  Now if you construct nine other polynomials with similar conditions and add them together, you get the $Q(x)$ you want.  Linearity is wonderful.  Now you need to prove it unique.  Assume there is another polynomial $R(x)$ of degree at most $9$ that satisfies the requirement.  How many roots does $R(x)-Q(x)$ have?


How to override subtheme settings (inheritance)?

Question: I am having some difficulty overwriting my subtheme code using my own theme.css file (located in sites>all>themes). I can find the code that results in the display of whichever css style property I'm trying to change (e.g., font-family in the header region) easily, using the chrome DevTool, but when I go to target that area in my own css file it seems not to have any effect on the display. Is there any general methodology with which I can go about inheriting my adjustments to the theme styles? FYI I have renamed my subtheme's files so that is not the issue.
Any help would be wonderful.
Answer: Assuming you've cleared the cache and all that before trying to inspect any changes, it sounds like your base theme (the theme you've based your sub-theme on) is one of those themes where the configuration is for a large part done by means of the administrative interface. This means that edits done to the .css fileshave no effect, as they're overridden by settings the administrative interface.
A number of popular themes has this property, including the Adaptive Themes family and Omega 3.
To check out if this is the case, navigate to Administration » Appearance » Settings for your theme (or sub-theme).  If there is a lot of settings for fonts, etc., hacking the .css files will not help much and you need to use the administrative interface for styling.


Supressing type-checking for a particular function in racket that uses eval

Question: I need to bypass the typechecker for a particular function but have the function's type signature available for type-checking other parts of the program. I think generally cast would be used, but that fails here because of variable number of return values.
I'm serializing a set to a string, and then using eval to convert it from a string to set again. Eval evilness aside (I trust source of input), how do I handle this in typed racket?
This is what my implementation is:
(: string->set (-> String (Setof Symbol)))
(define (string->set s)
  (eval (read (open-input-string s))))

And this is the error that type checker throws at me:
Type Checker: type mismatch;
;  mismatch in number of values
;   expected: 1 value
;   given: unknown number
;   in: (eval (read (open-input-string s)))
; [Due to errors, REPL is just module language, requires, and stub definitions]

I essentially need to have the typechecker to:

Not try to typecheck this method, and
Trust the type signature that it returns a set when it's given a string argument, and continue typechecking rest of the code.

How can I make that happen?
Answer: There are two problems here. First, eval, returns multiple values while your function returns only one. Second, of the values eval returns, it has Any type for each value, while your function promises something more specific.
The first problem can be solved with call-with-values, which allows you to convert multiple values into just a single value (using (lambda x x)).
The second problem can be used with cast. It does dynamically check to make sure the type fits, but otherwise lets you dynamically fit a value into a type.
Provided that you know the eval statement will only return one value (or you only care about the first value returned), you can use the following code:
(: string->set (-> String (Setof Symbol)))
(define (string->set s)
  (define ret
    (first (call-with-values (λ () (eval (read (open-input-string s))))
                             (λ args args))))
  (cast ret (Setof Symbol)))

Alternatively you could use use nocheck in Typed Racket. I would recommend against doing that though. As it disables all type checking in the entire module.


How should I use the  directive in .htaccess?

Question: I'm trying to add a conditional statement using Apache's If directive in my .htaccess file.
I have referenced this page http://httpd.apache.org/docs/trunk/mod/core.html#if but it doesn't elaborate much / give many examples. Two incomplete examples it gives are:

<If %{REQUEST_METHOD} IN GET,HEAD,OPTIONS>

and

<If "$req{Host} = ''">

So I've tried to add this to my .htaccess file:

<If %{SERVER_PORT} IN GET,HEAD,OPTIONS>
   #nothing here yet
</If>

But I keep getting Error 500 when I try and load the page. This is on my local install, and it was working fine previously (or if I remove that code). I believe I have AllowOverride All set up globally, and the context for the If directive should let it be present in .htaccess ("Context: server config, virtual host, directory, .htaccess").
Can someone give me some examples of how to properly use the <If> directive, or some guidance as to why it is not working for me?
Thanks!
Comment: If you're getting a 500 error, that means that Apache has logged something to your error log.  What does it say?  Also, your test for `SERVER_PORT` in `GET,HEAD,OPTIONS` doesn't make any sense (`SERVER_PORT` is going to be the number port number on which the request was received).
Comment: Thanks, larsks. Looks like I am running apache 2.0 which does not support the  directive. Maybe I need to look into upgrading to 2.3. At least this explains why there are no examples anywhere (b/c the feature is so new). Thanks for the advice.
Answer: The <If> directive is only available in Apache 2.4+ and not 2.2 or earlier.
http://httpd.apache.org/docs/2.4/mod/core.html#if
Documentation not present in 2.2:
http://httpd.apache.org/docs/2.2/mod/core.html#if
Answer: <If> is only available in Apache 2.4+, so firstly make sure that you have that version.
Examples
# Compare the host name to example.com and redirect to www.example.com if it matches
<If "%{HTTP_HOST} == 'example.com'">
  Redirect permanent "/" "http://www.example.com/"
</If>

<If "%{HTTP_HOST} =~ /regex/">
  SecFilterEngine Off
  SecFilterScanPOST Off
</If>

<If "%{REQUEST_URI} =~ m#/regex/including/slashes/#">
  SecFilterEngine Off
  SecFilterScanPOST Off
</If>

Alternatives to <If>
There are a few other solutions for doing conditional statements in Apache 2.2 if you're still stuck with that.

You can set environment variables via:

Apache configuration
SetEnvIf
mod_rewrite's RewriteMatch

Then you can perform conditional statements using
<IfDefine MyEnvironmentVar>
   ...
</IfDefine>

Example:
# Set environment variable if we're on staging site
SetEnvIf Host staging ROBOTS_NOINDEX

# Set environment variable if we're within a specific folder
SetEnvIf Request_URI ^/app/webroot/files/ ROBOTS_NOINDEX

# Send custom header if environment variable is set
Header set X-Robots-Tag "noindex" ENV=ROBOTS_NOINDEX

Comment: Test but not work! in the document from apache, `` directive only parse at startup and the `parameter-name` is only can passing by command promp using `httpd -Dx=y`
Comment: Your "Alternatives to If" were working fine for me, nice example.


Objective-C probe a bluetooth device that requires a pairing code but that has horrible/opaque docs

Question: I am trying to write an app to connect to a bluetooth medical device. The company that makes the device sent me a 300 page manual and basically told me to read all of it. I did an exploratory peripheral detection with CoreBluetooth and found the following device info:
centralManager:didDiscoverPeripheral:advertisementData:RSSI:
(null) with {
    kCBAdvDataIsConnectable = 0;
    kCBAdvDataManufacturerData = <8c0001e2 91d3a2d4 eb1f2417 da260263 3acf359c 3c206159 09>;
    kCBAdvDataServiceUUIDs =     (
        FEFD
    );

I then tried searching the pdf the company provided me for FEFD thinking that was the service identifier and would help me find the juicy bits of the manual...no dice.
This is my first bluetooth project, and I'm wondering how to go through this most efficiently. I need to pair with the device with an authorization code, and then I need to retrieve the measurements on the device. Is there any chance I can simply probe the device with Core Bluetooth. How would an experience bluetooth programmer go about this?
thanks for any advice.
Comment: You can use the LightBlue app from the App Store to connect and see what is has in terms of services and characteristics.
Comment: @Paulw11 thanks a lot for this tip!
Comment: did you find any code to pair BLE devices ?
Answer: (I think it should be comment, but I can't write them yet.)
You can use Hardware IO Tools for XCode. You can install it from Apple Developer pages. It has something called Bluetooth Explorer and could be really helpful with probing bluetooth devices. I don't know if it will be able to help in your case (medical equipment), but it was really nice tool when I used it with simple Bluetooth devices.
It's program for Mac, so your Mac has to have Bluetooth module to use it.
Comment: Thanks a lot for this tip!


Accessing google spreadsheet API restrictions in PHP issue

Question: I've created a spreadsheet, which I managed to successfully update with some data using the google api library and by creating a service accounts credentials from Google console -> Api & Services -> Credentials.
My problem is to try to restrict the access of the spreadsheet file. If don't allow to be publicly available for everyone with Editor roles, it will not work. I m getting this message:
{
  "error": {
    "code": 403,
    "message": "The caller does not have permission",
    "errors": [
      {
        "message": "The caller does not have permission",
        "domain": "global",
        "reason": "forbidden"
      }
    ],
    "status": "PERMISSION_DENIED"
  }
}

If I allow for everyone to access my spreadsheet, like in the image below , it will work .

I am also running my script, which updates the spreadsheet via a cronjob. Also this is the code where I do the auth part and I'm using the data from my Service Contract:
        $client = new Google_Client();
        $client->setApplicationName('Google Sheets and PHP');
        $configuration = '{
  "type": "'.$apiConfig['keyFile']['type'].'",
  "project_id": "'.$apiConfig['projectId'].'",
  "private_key_id": "'.$apiConfig['keyFile']['private_key_id'].'",
  "private_key": "'.$key.'",
  "client_email": "'.$apiConfig['keyFile']['client_email'].'",
  "client_id": "'.$apiConfig['keyFile']['client_id'].'",
  "auth_uri": "'.$apiConfig['keyFile']['auth_uri'].'",
  "token_uri": "'.$apiConfig['keyFile']['token_uri'].'",
  "auth_provider_x509_cert_url": "'.$apiConfig['keyFile']['auth_provider_x509_cert_url'].'",
  "client_x509_cert_url": "'.$apiConfig['keyFile']['client_x509_cert_url'].'"
}';

        $client->setAuthConfig(json_decode($configuration, true));
        $client->setScopes([Google_Service_Sheets::SPREADSHEETS]);
        $client->setAccessType('offline');

        return new Google_Service_Sheets($client);

Does anyone have any clue how can I restrict the access? and still have this work?
Thanks a lot for any suggestions
Answer: Finally I got it work by adding this email address :

To the Share with people and groups. See image from my post(question) .


Primes in $\mathbb Z[i]$

Question: I've been trying to proof that if $\pi\in Z[i]$ and $\pi$ is prime, then $\pi\overline \pi$ is a prime in $\mathbb Z$ or is the square of a prime  in $\mathbb Z$.
I took a prime $p$ in $\mathbb Z$ such that $\pi|p$, then $\overline \pi |p$, which is why $\pi\overline\pi |p^2$. I am stuck in that, so I need that $\pi\overline \pi=p^2,p$.
Thanks in advance :).
Comment: Well, what are the divisors of $p^2$?
Comment: They are $1,p$ and $p^2$
Comment: Have you shown that $\pi\overline{\pi}\in\Bbb{Z}$?
Comment: Yes, I have shown it
Answer: You have shown that $\pi\overline{\pi}$ divides $p^2$ and that $\pi\overline{\pi}\in\Bbb{Z}$, so it remains to show that $\pi\overline{\pi}\neq1$. But this is clear because $\pi$ is prime, hence by definition it is not a unit.
Answer: Let  $\pi=a+bi$, $a,b$ integers.Suppose that it is a prime. First check  that $\bar\pi=a-bi$ is also a prime.
Let $n=|a+bi|=a^2+b^2$. Let $r$ be a prime dividing integer $n$. So $a^2\equiv -b^2 \mod r$. If $r\equiv 3\mod 4$, then the only possibility is that $a\equiv b\equiv 0\mod r$, so $n$ is divisible by $r^2$.
If $r\equiv 1 \mod 4$, then $r=c^2+d^2$ for some integers $c,d$, so $c+di | (a+bi)(a-bi)$ which contradicts the fact that $a+bi$ (hence $a-bi$) is prime.
So we need to consider only the case  that $n=m^2$ where $m$ is a product of primes $p_1...p_k$, each $p_i\equiv 3\mod 4$. Again, if $k>1$, then $p_1$ is a prime dividing the  product of two primes $(a+bi)(a-bi)$ which is impossible, so $k=1$.
Thus $n$ is either a prime or a square of a prime.
The opposite implication is obvious.

Primes in $\mathbb Z[i]$


R - How to display X axis values on barplot from data frame

Question: I have a data Frame that looks like the following,
str(data2)
'data.frame':   516 obs. of  2 variables:
 $ Jobs      : num  2 1 5 0 0 0 0 0 0 0 ...
 $ Time         : chr  "06:00" "06:01" "06:02" "06:04" ...

I am trying to create a barplot from this data Frame.
If I run,
barplot(data2$Jobs,
    col="orange",
    xlab="Time of Day",
    ylab="Files With Jobs",
    main="Jobs by Time of Day Received")

This is fine, and gives me the barPlot, but the X axis is blank. I need to have the Time column showing on the X Axis.
I tried,
barplot(data2$Time,data2$Jobs,
    col="orange",
    xlab="Time of Day",
    ylab="Files With Jobs",
    main="Jobs by Time of Day Received")

But this gives me,

Error in -0.01 * height : non-numeric argument to binary operator

What is the correct way to do this?
Answer: Use the names.arg argument to barplot:
barplot(data2$Jobs,
        names.arg=data2$Time,
        col="orange",
        xlab="Time of Day",
        ylab="Files With Jobs",
        main="Jobs by Time of Day")

Answer: You can also use ggplot:
data<- data.frame(jobs=c(2, 1, 5, 0), Time=c("06:00", "06:01", "06:02", "06:04"))
data$Time <-  strptime(data$Time, format="%H:%M")

ggplot(data=data,aes(x=Time,y=jobs)) +
  geom_bar( stat="identity", colour = "brown1", size = 1.5)+
  theme(axis.text.x = element_text(angle = 90,hjust=1,vjust=0.3))+
  xlab("Time of Day") +
  ylab("Files With Jobs")


Postfix still forwarding emails even after I've removed the address from all configuration files

Question: I'm having a strange problem that can only be explained by caching or some kind of hidden variables.

I was forwarding mail to my gmail account with a virtual alias file, /etc/postfix/virtual.
I decided to change this behavior, so I removed that line. But it still forwards to my gmail address.
I removed the entire virtual alias file. It still forwards to my gmail address. (I do postmap /etc/postfix/virtual after every change.)
Confused, I put the virtual file back and tried putting a different address in instead. This worked, and started forwarding to the new address.
When I removed the new address, it started forwarding to the original address again, despite the fact that that address is nowhere to be found anywhere and hasn't been through several changes.
I blank out the virtual_alias_domains and virtual_alias_maps lines altogether in main.cf. It still forwards to the original gmail address.
It's not in /etc/aliases either, by the way, although I did newalises and checked that the timestamp updated just in case.

I am lost here, and stumped. I've been checking timestamps on the virtual alias database file, and the aliases database file (virtual.db and aliases.db) after each refresh to make sure that they are in fact being updated.
I don't know where it's getting my gmail address from. Most bizarre to me is how when I changed the address to a new one, it updated correctly, but then when I removed the new address it went back to using the old one.
I even resorted to doing a grep of my email address on the entire system, but it shows up in too many places, and that won't even find it if it's in a binary database file.
Comment: Look at a file named `.forward` in your home directory.
Comment: @MichaelHampton THAT WAS IT! Thank you! Please make it a regular answer so I can accept it! --- Now I'll have to try to undo everything I've done this week in trying to fix it.
Answer: Look for a file named .forward in your home directory. This file lets ordinary users set up their own email forwarding without involving the system administrator.


Show that the union $\{e_k \mid k \in \mathbb N\} \cup \{(1/k)_{k \in \mathbb N}\}$ is linearly independent on $\ell^\infty(\mathbb C)$

Question: Let $e_k$ be the standard unit sequence, where all elements but the $k$th one are zeroes, and the remaining element is $1$. Show that the union
\begin{equation}
\{e_k \mid k \in \mathbb N\} \cup \{(1 / k)_{k \in \mathbb N}\}
\end{equation}
is linearly independent on $\ell^\infty(\mathbb C)$,
where the sequence space
\begin{equation}
\ell^\infty(\mathbb C) = \left\{ (x_k)_{k\in\mathbb N} \in \ell(\mathbb C) \mid \sup_{k\in\mathbb N} |x_k| < \infty \right\}\,.
\end{equation}
An infinite set of vectors is said to be linearly independent, if the vectors of all its finite subspaces are linearly independent.
Some thoughts
Looking at the set $\{(1/k)_{k \in \mathbb N}\}$ and the standard unit sequences $e_k$ it would seem that the harmonic sequence should be expressable in therms of these unit sequences. This is because multiplying $e_k$ by $1/k$ and then summing the resulting sequences together results in the harmonic sequence.
How could I use the fact that we are operating on $\ell^\infty(\mathbb C)$ to counteract this issue?
Comment: The thing is that you would need an infinite sum to express the harmonic sequence as a linear expression of $e_i$. Linear dependence doesn't work over infinite sums.
Comment: I don;t know where you got the problem from, but the notation is appalling: the set comprehension on the right of the union looks nothing like the singleton set containing the sequence $\langle 1/1, 1/2, 1/3, \ldots \rangle$.
Answer: Hint Assume that a finite linear combination of $(e_k)$ and $s=(\frac{1}{n})$ is zero. This means
$$c_1e_{k_1}+....+c_ne_{k_n}+cs=0$$
with $c$ potentially being $0$.
Look first at the "entry" $m$, where $m > k_1,.., k_n$ to deduce that $c=0$.
Next, look individually at each of the entries $k_1,...,k_n$.
Comment: The point is that once $m>k_n,$ the $m$th component of the vector sum is $c/m$ and since each component is zero, $c=0.$ And then all the other coefficients are zero because the $\{e_k\}$ are linearly independent.
Comment: @SeSodesa The entry of the linear combination. If $c_1e_{k_1}+....+c_ne_{k_n}+cs=0$ then the $m$th entry of $c_1e_{k_1}+....+c_ne_{k_n}+cs$ is zero.
Comment: The first entry $m$ of the linear combination, as in $c(1/k)_{k \in \mathbb N}$, or the $m$th entry of the harmonic sequence itself? The latter makes more sense.
Comment: Right, I got it after thinking about it a little bit. I sort of forgot, that the sequences are not finite, even if we have a finite set of them.


Wordpress usernames with special characters using wp_get_current_user() returns nothing

Question: I have a wordpress installation with a login system. The usernames are company names, which might include the danish characters Å,Æ,Ø.
When loggin in, these characters do not cause a problem. But when the user is logged in, and i try to get the currently logged in user, the current user_login and role is not displayed. This has worked before, and stopped working recently. I am using the following code:
<?php
function visbruger(){

      $current_user = wp_get_current_user();

        $BrugerRolle = "";
        $Rolle = implode(', ', $current_user->roles);

        if($Rolle == 'Light'){
            $BrugerRolle = "CE- mærkning";
        }
        else if($Rolle == 'Normal-1'){
            $BrugerRolle = "FPC Light";
        }
        else if($Rolle == 'Normal-2'){
            $BrugerRolle = "FPC Normal";
        }
        else{
         $BrugerRolle = implode(', ', $current_user->roles);
        }

       echo 'Logget ind som: ' . $current_user->user_login . " "." | "." ";
       echo 'Abonnement: ' . $BrugerRolle . "\n";

}

add_shortcode('brugervis', 'visbruger');
?>

This function should return something like this:
Logget ind som: Company name | Abonnement: FPC Normal

But when using æ,ø,å in the username, it returns:
Logget ind som: | Abonnement:

Like wp_get_current_user() can't get users with special characters in their username. How do I fix this problem? Thanks in advance.
Answer: user_login is sanitized with  sanitize_user() when inserting user. That means such special characters would be stripped out. See what characters are allowed in user_login after cleanup. https://developer.wordpress.org/reference/functions/sanitize_user/
Rather than displaying $current_user->user_login in your function, you can display $current_user->display_name so that such special characters are displayed correctly.
Comment: I'm filtering sanitize_user() in functions.php, so that the special characters are allowed in user_login. In the database the user_login is displayed correctly with the special characters.


Moving an google cloud vm instance gives error Code '6562453592928582321' and instance is gone

Question: After executing
gcloud compute instances move instance-ba --zone us-east1-b --destination-zone us-east1-c

and waiting for about 5 minutes the following error was thrown
Moving gce instance instance-ba...failed.
ERROR: (cloud.compute.instances.move) Code: '6562453592928582321'

and the instance was gone from the web interface as well as from zone us-east1-b and us-east1-c
I tried to start the instance with
cloud compute instances start instance-ba --zone us-east1-b

and
cloud compute instances start instance-ba --zone us-east1-c

but none was working.
Thank you in advance for your help.
I have to say that this instance is quite important and I appreciate every input to solve this issue.
Edit
In the Stackdriver Logging I am seeing the following commands executed alternating:

Compute Engine setDiskAutoDelete us-east1-b:instance-ba
compute.instances.setDiskAutoDelete

As it seems the instance has been deleted from us-east1-b but not transferred to us-east1-c.
I do not see any error at all. All logs have severity "INFO" or lower.
Edit 2
I recall my steps which preceeded the moving error as follows

I tried adding a second Tesla P100 to my instance which gave at startup the error that the resources are not enough to fulfill the request
I tried moving the instance which gave the "TERMINATED" error so I
tried to reset the machine with the reset command which gave the "instance not ready" error
I removed the second Tesla P100 so that I could start the machine
I did the restart command over and over until it worked and the machine was able to start
Since I needed a second GPU I tried to moved this instance (without the second GPU) from us-east1-b to us-east1-c which finally did not work and gave the error

Edit 3
After some research I found that the procedure actually made a snapshot from my instance and the data is not lost.
However I will keep this question updated concerning the error and the response to it from google.
Comment: 1) Does Stackdriver show anything? 2) Open a support ticket with Google even if you must pay for a support subscription - appeal the charges later. 3) Please update this thread if you learn anything.
Comment: @John Hanley
1) I updated the question regarding the Stackdriver but the error is not shown in the log
2) I will open an support ticket
Thanks for your support.
Comment: Is there any settings that you made on the instance at creation? I just moved an instance several times with no issue.
Comment: I edited my answers giving the steps that preceded the moving.
Answer: According to the documentation, you have a short specification for when to use the manual or the automatic move. As the procedure says, use the manual move when:
"Your VM is not RUNNING."
"You are moving your VM to a different region and your VM belongs to a subnetwork."
"Your instance has GPUs or local SSDs attached."
In your case, you had one GPU attached to your instance. So the correct way to move it is the following:

Stop your instance
Edit the instance, on the "Machine type" click customize and select "none" numbers of GPU. More details here.
Start your instance
Use the gcloud command to move the instance between zones:

$ gcloud compute instances move example-instance --zone us-central1-a --destination-zone us-central1-f

Once the instance is migrated stop it again.
Add the GPU and start the instance.

Keep in mind that every zone has different GPUs available and new projects have limits for GPUs.
"To protect Compute Engine systems and users, new projects have a global GPU quota, which limits the total number of GPUs you can create in any supported zone. When you request a GPU quota, you must request a quota for the GPU models that you want to create in each region, and an additional global quota for the total number of GPUs of all types in all zones."
Comment: Thanks for your reply. I think you did a good gob summarizing the procedure. Nevertheless I have to say that my procedure (with detours) was similar to yours (see Edit 2).
Comment: You can have 2 Tesla P100 on us-east1-b, you are getting the error "resources are not enough to fulfil the request" because you have limits for GPUs. Check [this](https://cloud.google.com/compute/docs/gpus/#restrictions). "you must request a quota for the GPU models that you want to create in each region". There is a [Stackoverflow post](https://stackoverflow.com/questions/45227064/how-to-request-gpu-quota-increase-in-google-cloud) for requesting quota for GPU.
Comment: Oh I think now I get what you are saying. It would have been possible to start the instance in the region but my quota was too small.
Do you think this fact has to do with the error code given above (but I removed the GPUs and still got the error)?
Comment: Just to give some more information: I opened an issue at Issue Tracker. About a week ago the error above got replicated (by moving an instance between two regions). I will keep this thread updated. In the meantime I solved my problem (by creating a new instance from the snapshot) and requested the quota (see Edit 3).
Comment: I keep thinking that the first error that you get was for trying to move the instance with a GPU attached to it and the second one was for not having enough quota. The post is for the error "6562453592928582321" as my answer for evading it. I recommend you to open another question for the second error.
Comment: You mean by first error "TERMINATED" and second error "6562453592928582321"?
Comment: First error "6562453592928582321", that happens if you migrate an instance with a GPU attached.
Second error "resources are not enough to fulfil the request": happens when you don't have enough quota and you need to [ask for quota](https://cloud.google.com/compute/quotas#requesting_additional_quota)
Comment: So you are saying, the error "6562453592928582321" happened because I tried to move the _instance with GPU_? I think this comment does answer the question. If you post this as answer/edit your answer I will accept it. I do not accept your current answer since it does not refer to my problem.
Comment: Exactly, I recreated It myself and if you don't remove the GPU before migrating you will get this error. That is why I answer with the right procedure for migrating machines with GPU's attached.
Comment: I will mark your question as answer. Nevertheless it would be more helpful if you directly referenced the errors since in the question more than one error was mentioned.


Windows Console .exe won't run if it's downloaded from the internet

Question: I have a nightly job on Windows Server 2003 that automatically updates itself by downloading its .exe from Amazon S3.  I've noticed that when it performs the download and tries to run the newly downloaded .exe, it  is immediately kicked back to the command line without actually running anything.
I can verify this by sticking the new version of the code directly on the server and watching it execute successfully, then uploading it to the "update" server, running the bootstrapper then running the .exe and observing it fail to execute.
I can only assume that this is due to Windows protecting me from running code from outside its trusted zone.  How does a fella go about configuring it to allow code from this particular external location to execute?
Thanks!
Answer: Windows tracks whether or not a file has been downloaded from the internet (or expanded from a zip file, even) by use of file streams. There is a stream associated with the .exe which effectively says "I came from www.example.com".
If you want to disable it for that file, and since it is a batch job anyway, you can delete the stream using
http://www.microsoft.com/technet/sysinternals/utilities/Streams.mspx
HTH
Answer: Maybe by adding your S3 URL to your Trusted Zone?
Answer: Try this: go to the newly downloaded file, right-click and bring up the properties, check if there's a button 'Unblock'.  If you download an executable, you need to specifically permit it to to run.  I'm not sure how to do this in script, so this won't fix your problem but may get you a bit closer.
Answer: If you want to disable zone checking set the environment variable SEE_MASK_NOZONECHECKS=1, but don't.  Run your executable via this script instead:
<code>set oShell= CreateObject("Wscript.Shell")

set oEnv = oShell.Environment("PROCESS")

oEnv("SEE_MASK_NOZONECHECKS") = 1

oShell.Run "c:\myexecutablepath\myexecutable.exe",0,True

oEnv.Remove("SEE_MASK_NOZONECHECKS")
</code>


How to dynamically add button to jQuery-UI button-set?

Question: I am looking for a way to add a button to a jQuery button-set at run-time with JavaScript.
        if(response.success) {
            var menuItem = document.createElement('a');

            $(menuItem).attr('href', response.href);
            $(menuItem).attr('category-id', response.id);
            $(menuItem).text(title);

            $("#menu-buttonset").append(menuItem);
        }

I am adding the hyperlink to the div container of the button-set using JavaScript, and then re-calling buttonset() on the container.
 $("#menu-buttonset").buttonset();

This however does not seem to rebuild the button-set as I expected.
I am not seeing any function in the jQuery API for this either.
Can anyone provide some insight?
Resolved:
Using refresh method as suggested, rebuilt the button-set.
$('#menu-buttonset').buttonset('refresh');

Comment: Is $(categoryItemSelector).parent() same as $("#menu-buttonset")?
Comment: Yes it is the same, the example has been updated to make this more clear.
Answer: It seems to me like buttonsets use radiobuttons or checkboxes, not links:
http://docs.jquery.com/UI/Button
Take a look here: http://jsfiddle.net/Fe9Tx/1/
(Fixed it so selection works)
Comment: After several minutes of searching - this was the exact answer I was looking for. zsalzbank - thanks for taking the time!!
Answer: You need to call the refresh method after adding an new item to the button set.
$("#menu-buttonset").append(menuItem).buttonset('refresh');

I cannot find any documentation for this method in jquery, but it is available.
Comment: Thanks, I'm not sure how I missed that in the documentation.
Comment: [Button API Documentation - Refresh](http://api.jqueryui.com/button/#method-refresh) is available now in documentation.


How to include image in downloading PDF from database on Laravel 8?

Question: I successfully downloaded the pdf but the image isn't. Instead, it displays "Image not found or type unknown" The image being displayed. How should I fix it?, I did "myfolder/{{$database->image}}" and my data type in my database is LONGBLOB. The image is visible in loadview but every time I download it "Image not found or type unknown" is displayed. What am I missing? and what should I do? These are the images in my LoadView and PDF Inside my LoadView and the content after I download it as PDF
These are the things I've did and tried.

Implementing the PDF

Command for install package for PDF :   composer require barryvdh/laravel-dompdf
Then go to config/app.php and make some changes

'providers' => [
    ....
    Barryvdh\DomPDF\ServiceProvider::class,
],
'aliases' => [
    ....
    'PDF' => Barryvdh\DomPDF\Facade::class,
],

The image which I've seen and tried from other tutorials/website

//The logo which also getting displayed in my LoadView but not getting download as PDF

//The image stored in my folder and database which displays it in my LoadView but doesn't display it or download it together with other data in the PDF
prod_img}}">

//I also did this but it's not being displayed now in my loadview nor every time I download the pdf
prod_img')}}">

Inside my database the data type before was varchar(255) now I've changed it to LongBLOB Image of the structure

My route Route::get("/downloadPDF",[EmpController::class,"downloadPDF"]);

The code in my controller

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Receipt;
use PDF;
class EmpController extends Controller
{
    public function getReceipts(){
        $data = receipt::all();
        return view('downloadReceipt', compact('data'));
    }

    public function downloadPDF(){
        $data = receipt::all();
        $pdf = PDF::loadView('downloadReceipt', compact('data'))->setOptions(['defaultFont' => 'arial']);
        return $pdf->download('data.pdf');
    }
}

and the code in my blade file
<!DOCTYPE html>

  <link rel="stylesheet" href="assets/css/design.css">

~Customer Receipt~

                    Product
                    Quantity
                    Paid Amount
                    Total Fee
                    Date
                    Image

                @foreach($data as $data)

                    {{$data->prod_name}}
                    {{$data->prod_qty}}
                    {{$data->paid_fee}}
                    {{$data->total_fee}}
                    {{$data->date}}
                    prod_img}}">

                @endforeach

I'm so confused. What am I missing? What should I do or try next?
Comment: Instead of  - You need to use full path for images. You can use {{ asset('assets/images/logo.png') }}.  Similarly for other image as well.
Comment: thanks, I've tried it but unfortunately the result is still the same. It is displayed in loadview but after I download it as pdf there aren't images.
Comment: try `{{ asset('storage/assets/images/logo.png') }}`
Comment: @maha unfortunately it doesn't work for me. Nothing is displayed in the LoadView as well as downloading pdf
Answer: This solved the logo problem,

and the ones I am retrieving from mydatabase
<img src="data:image/png;base64,<?php echo base64_encode(file_get_contents(base_path('public/productimage/'.$data->prod_img))); ?>" width="120">


Buying flat based on historical data

Question: import pandas as pd
df = pd.read_csv("past.csv")
df.info()

print()

town_unique = df[['town']].drop_duplicates()
print('List of towns:')
print(*town_unique['town'], sep = "\n")

town_choice = str(input('Enter a town from above: ')).upper()

for town_choice in df.columns[10:].values:
    print(f'The price range of flats in {town_choice} is between ${df[town_choice].min():,.0f} and ${df[town_choice].max():,.0f}.')

print()

min_price = int(input('Enter a minimum flat price: '))
max_price = int(input('Enter a maximum flat price: '))
print('The types of flats available are:')

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 80374 entries, 0 to 80373
Data columns (total 11 columns):
 #   Column               Non-Null Count  Dtype
---  ------               --------------  -----
 0   month                80374 non-null  object
 1   town                 80374 non-null  object
 2   flat_type            80374 non-null  object
 3   block                80374 non-null  object
 4   street_name          80374 non-null  object
 5   storey_range         80374 non-null  object
 6   floor_area_sqm       80374 non-null  float64
 7   flat_model           80374 non-null  object
 8   lease_commence_date  80374 non-null  int64
 9   remaining_lease      80374 non-null  object
 10  resale_price         80374 non-null  float64
dtypes: float64(2), int64(1), object(8)
memory usage: 6.7+ MB

List of towns:
TOWN A
TOWN B
TOWN C
TOWN D
TOWN E

Enter a town from above: TOWN A
The price range of flats in **resale_price** is between **$140,000** and **$1,258,000**.

Enter a minimum flat price: 100000
Enter a maximum flat price: 20000
The types of flats available are:

After entering TOWN A, the input came out as resale price iso TOWN A. The min and max values reflected are the min and max of all towns iso the input town. How can I get the min and max of the input town only?

I need to list the available flat types based on the town input and the value of the min and max flat price that the user have keyed.

User will then select the room type and a list of the past transaction will be listed out in the table as so:
'No.' 'Block' 'Street Name' 'Storey Range' 'Size(sq m)' 'Price($)'

Can anyone help? I am so lost.
Comment: welcome to SO! re: "resale price" iso "TOWN A": i don't know the language but maybe 'flats in {town_choice} is between' should be 'flats in ${town_choice} is between' ? (with a dollar sign)
Comment: please edit the question to add the missing bit after 'print('The types of flats available are:')'

also, can you include the input data (CSV file) or a reference to it?
Comment: Thank you for the welcome! :)

Here is the link to the excel - https://drive.google.com/file/d/1N9k9k6xB-Q8JBIEedmxfWpjotZtyb2uS/view?usp=sharing
Comment: and this is the link to the desired output - https://drive.google.com/file/d/1MmgwDEbkVBhfdGZrVeheAWdCjkKFXDrl/view?usp=sharing
Answer:
You weren't using town_choice to filter the dataset. I do that below to create one_town, containing just the rows from the town picked.

In creating flat_types, I used a compound binary expression to filter for just the rows in the price range, and .loc to select just the flat_type column of those rows.

I'm leaving the 3rd part, 'user selects a type, all flats of that type are listed', for you. It'll use the same techniques.

import pandas as pd
df = pd.read_csv("past.csv")
df.info()

print()

town_unique = df[['town']].drop_duplicates()
print('List of towns:')
print(*town_unique['town'], sep = "\n")

# hardcode the choice to make edit/run/debug iteration faster
#town_choice = str(input('Enter a town from above: ')).upper()
town_choice = "HOUGANG"

one_town = df[df["town"] == town_choice]
print(f'The price range of flats in {town_choice} is between ${one_town["resale_price"].min():,.0f} and ${one_town["resale_price"].max():,.0f}.')

print()

# hardcode the choices to make edit/run/debug iteration faster
min_price = 383500 # int(input('Enter a minimum flat price: '))
max_price = 384500 # int(input('Enter a maximum flat price: '))

flat_types = one_town.loc[(one_town["resale_price"] >= min_price) & (one_town["resale_price"] <= max_price), "flat_type"].drop_duplicates()

print('The types of flats available are:')
print(*flat_types, sep = "\n")
print()

Comment: Thank you so much! I managed to get it! :D
Comment: glad that helped! it was a fun exercise. feel free to 'accept' my answer so i get a few points of rep..
Comment: Btw, would you be able to help? I tried to print the table out for the selected flats but I only wanted selected columns.

Am i missing out something here?

`flat_list = df.loc[(df['town'] == town_choice) & (df['flat_type'] == desired_flat) & (df['resale_price'] >= min_price) & (df['resale_price'] <= max_price)]
df1 = df[['block', 'street_name', 'storey_range','floor_area_sqm','resale_price']]
print(flat_list)`

Buying flat based on historical data


draggable columns in ReactJs Antd table causes multi renders of useEffect

Question: I am using antd for create a table in reactJs.
I added eventListener to th tag because I want to be able to drag the columns.
I do it with useRef to get all the th tags:
const [cols, setCols] = useState(columns); // -> columns is static array of object
const tableRef = useRef(null);

useEffect(() => {
    if (tableRef.current) {
      let elems = tableRef.current.ownerDocument.querySelectorAll('th');
      for (let i = 0; i < elems.length; i++) {
        elems[i].setAttribute('draggable', true);

        elems[i].addEventListener('dragstart', (e) => {
          handleDragStart(e);
        });

        elems[i].addEventListener('dragover', (e) => {
          handleDragOver(e);
        });

        elems[i].addEventListener('drop', (e) => {
          handleOnDrop(e);
        });
      }
    }
  }, [cols]); // -> cols is the updated columns after change order

const handleDragStart = (e) => {
    const { innerText } = e.target;
    const idx = cols.findIndex((x) => x.title === innerText);
    e.dataTransfer.setData('colIdx', parseInt(idx));
  };

  const handleDragOver = (e) => {
    e.preventDefault();
  };

  const handleOnDrop = (e) => {
    const { innerText } = e.target;
    const droppedColIdx = cols.findIndex((x) => x.title === innerText);
    const draggedColIdx = parseInt(e.dataTransfer.getData('colIdx'));
    setCols(() => {
      const tempCols = [...cols];
      tempCols.splice(droppedColIdx, 0, tempCols.splice(draggedColIdx, 1)[0]);
      return tempCols;
    });
  };

My problem:
The columns are draggable and I can move them.
If in the useEffect dependency I add cols array, in the first drag the useEffect will call one time, in the second drag the useEffect will call 2 times, in the third drag the useEffect will call 4 times, in the fourth drag the useEffect will call 8 times and so on.
That is every time the useEffect is call, it multiple the call in 2.
If I remove cols array from useEffect dependency, after the first drag everything is ok, but in the second drag my cols reset and initialized to columns.
Thank you for helping me.
Answer: You need to remove the listeners in the return of the useEffect in the following manner:
useEffect(() => {
    const handleClick = event => {
      console.log('Button clicked');
    };

    const element = ref.current;

    element.addEventListener('click', handleClick);

    //  remove the event listener when component unmounts
    return () => {
      element.removeEventListener('click', handleClick);
    };
  }, []);

Comment: Thank you very much, it absolutely solved my problem!


How to differentiate the state when a contextual filter is applied?

Question: Hello to all the Drupal community. I've recently faced a challenge to visually modify some parts of my view's template for the state when its contextual filter is applied. Some details are as follows:

I have a View of the articles previews list. Each article has several
tag names (taxonomy terms) applied.
This view has a Contextual filter set up to filter the list based on
the taxonomy Term (tag name). The Term is provided by adding term_id
to URI (like mysite/blog/12). If no Term is provided - it just prints
all articles.
I have a separate views block with "Featured article" content, which
is placed above my Articles list view and is limited to being visible
on "mysite/blog" URI. This was made to avoid it from displaying on
full articles pages by addressing "mysite/blog/article-name..."

Questions:

How can I add some class names to the views TWIG template to indicate
that this view has contextual filters applied from URI?
How can I show the Featured article block on the "mysite/blog" and
"mysite/blog/TID" pages but not for "mysite/blog/article-name..."?
Answer:
How can I add some class names to the views TWIG template to indicate that this view has contextual filters applied from URI?

The easiest way to do this is inside the views-view-DISPLAY_TYPE.html.twig templates (e.g. views-view-table or  views-view-unformatted, whatever display type you are using,...)
In that template you have access to the view variable, which contains the entire views object of the current page. The contextual filter values are stored in the args variable of that object, so you need something like
{% if view.args %}...your logic here...

How can I show the Featured article block on the "mysite/blog" and "mysite/blog/TID" pages but not for "mysite/blog/article-name..."?

It seems you have placed that block in regions on the global block layout, while you want to show it only on your views page. So the easist way is to add the block in the view page, and not in one of the theme regions. You can place any block, even other views, in the header of a views page in the Views UI.
Comment: Thanks a lot. I will dig into your proposal


Implementação de um Analisador Léxico

Question: Olá, galera! Estou fazendo a implementação de um analisador léxico de uma gramática que eu criei (utilizando o Gals). A validação da gramática foi feita utilizando o conceito de autômatos finitos, conforme a imagem:

No momento eu tenho os seguintes códigos:
Arquivo lexico.py:
with open("transicao.txt", "r") as programa:
    arquivo = programa.readlines()
    lista = []
    for linha in arquivo:
        line = linha.strip('\n').replace(' ', '')
        for i in line:
            lista.append(i)

    with open("tokens/transicao.txt", "r") as arquivo:
        linhas = arquivo.readlines()

    def concatenar(list):
        return ''.join(list)

    def ftransicao(s, l):
        for v in linhas:  # Navega pelas linhas do arquivo de transição
            linha = v.split(',')  # Divide a string em 3 partes (estado atual, letra, próximo estado)
            if linha[0] == s:  # Se o primeiro valor da string dividida for igual o estado atual
                for z in linha[1]:  # É navegado apenas pelos valores das letras da função transição
                    if z == l:  # Se a letra lida no arquivo for igual a letra lida da palavra então é retornado o próximo estado
                        # print('{} contém {} então vai para {}'.format(s, l, linha[2]))
                        return linha[2].strip()
        return None

    atual = 'q0'
    efinal = ['q3', 'q7', 'q28', 'q9', 'q15', 'q18', 'q25', 'q33', 'q34', 'q35',
              'q36', 'q37', 'q39', 'q41', 'q42', 'q43', 'q44', 'q45', 'q46', 'q47', 'q51', 'q53']
    lexema = []

    for i in range(len(lista)):

        atual = ftransicao(atual, lista[i].strip())
        lexema += lista[i]

        if atual in efinal:
            print('Caractere identificado [ {} ]'.format(concatenar(lexema)))
            atual = 'q0'
            lexema.clear()
            continue
        elif atual is None:
            atual = 'q0'
            print('Caractere não identificado [ {} ]'.format(lista[i]))
            lexema.clear()
            continue

Arquivo transicao.txt que contém um exemplo da gramática:
run
integer f = 22;
integer g = 3;
integer n;
display();
input(n);
while(g <= numero){
f = f * i;
g = g + 1;
}
display(f);
exit

E a função transição descrita conforme a imagem:
q0,r,q1
q1,u,q2
q2,n,q3

q0,e,q4
q4,x,q5
q5,i,q6
q6,t,q7

q4,l,q26
q26,s,q27
q27,e,q28

q0,i,q8
q8,f,q9
q8,n,q10
q10,t,q11
q11,e,q12
q12,g,q13
q13,e,q14
q14,r,q15

q10,p,q16
q16,u,q17
q17,t,q18

q0,d,q19
q19,i,q20
q20,s,q21
q21,p,q22
q22,l,q23
q23,a,q24
q24,y,q25

q0,w,q29
q29,h,q30
q30,i,q31
q31,l,q32
q32,e,q33

q0,-,q34
q0,+,q35
q0,*,q36
q0,/,q37

q0,<,q38
q38,=,q39

q0,>,q40
q40,=,q41

q0,=,q42
q42,=,q43

q0,(,q44
q0,),q45
q0,{,q46
q0,},q47
q0,;,q53

O problema é o seguinte. De que forma eu posso fazer a validação da String, dos dígitos, identificadores conforme a imagem mostrada? Os outros estão funcionando perfeitamente e está sendo reconhecido na listagem.
Obrigado a quem puder ajudar. Boa noite!
Answer: A sua linguagem é complexa demais para ser definida numa gramática regular. Você deve usar uma gramática livre de contexto, dessa forma você poderá inclusive definir a procedência dos operadores matemáticos e verificar parênteses balanceados.
Depois que criar a sua GLC, crie um parser LL para validar a sintaxe e gerar a AST.

Implementação de um Analisador Léxico


Erro ao carregar XML no Laravel

Question: Estou recebendo o erro abaixo ao carregar o XML usando o Laravel. Testei a importação com PHP puro e foi normalmente. Alguém tem ideia do que pode ser? Entendo que esse " é aspas, mas não achei no XML.
simplexml_load_file(): I/O warning : failed to load external entity ""

Linha de código onde ocorre o erro:
$xml = simplexml_load_file($request->file('publicacao')); dd($xml

Comment: Segundo essa [pergunta](https://stackoverflow.com/questions/21661593/simplexml-i-o-warning-failed-to-load-external-entity), o `simplexml_load_file()` espera um  `filename`, você está passando isso?
Comment: Sim. Tem outra alternativa a ele?
Comment: Posta o trecho de código completo, inclusive a linha que retorna esse erro, facilita pra entendermos melhor o problema.
Comment: $xml = simplexml_load_file($request->file('publicacao'));
dd($xml);
Uso laravel.
Comment: Coloque qual é o conteúdo de `$request->file('publicacao')`.
Comment: Não da. O arquivo é muito grande. Tentei colocar o conteúdo no PasteBin, mas excedeu o tamanho máximo.
Answer: Até aonde entendo do $request->file() (retorna Illuminate\Http\UploadedFile) do Laravel não retorna uma string, inclusive se olhar na documentação vai notar que não existe nenhum __toString que deveria ser o minimo para o primeiro para retornar o caminho temporário do arquivo que esta fazendo upload, veja a documentação:

https://laravel.com/api/5.6/Illuminate/Http/UploadedFile.html

Então provavelmente ao passar o valor para simplexml_load_file ele esta buscando um arquivo que não seja o arquivo correto, provavelmente o que esta entre "", o que foi tentando passar foi um objeto, assim provavelmente:
object(Illuminate\Http\UploadedFile)#1 (0) {
}

É bem provável que os erros de warning estejam desligados ou ocultos, mas se estivesse ligado iria exibir algo como:

PHP Warning:  simplexml_load_file() expects parameter 1 to be a valid path, object given

A frase object given quer dizer que pegou um objeto, a frase anterior diz, o parametro 1 precisa ser um caminho valido, ou seja objeto não é caminho e nem string.

Como ler o conteudo de UploadedFile do laravel
Provavelmente o correto seria usar UploadedFile::get() + simplexml_load_string(), assim:
$xml = simplexml_load_string($request->file('publicacao')->get());
dd($xml);

Erro ao carregar XML no Laravel


Piano fingering recommendation for an f# minor arpeggio in the left hand?

Question: I can't seem to find a comfortable fingering for the bass part of this. Everything I try feels weird.

How can I transfer from the F# on the fourth line to the rest?
I'm trying this:

F# C# F# A    C# A F# A
5  3  1  3    2  3 4  3

Any better fingering?
Comment: I'd generally see that it was going up to the C# and that I'd want my 1st on that note for the next phrase, so just use all my fingers: 5-4-3-2-1 and if my hand wasn't big enough, possibly do a little jump from the initial F# to the first C#, even using the sustain to mask the gap. But that's just me; in general I think Poben's answer is good.
Comment: Just a general comment: one easy trap to fall into when devising fingerings is to use the same finger for the same note when it reoccurs, possibly as part of the same sequence.  In your example, you use 3 for the f♯ consistently.  When you view every repetition as an opportunity to improve your approach to the following notes, you sometimes arrive at better solutions.  I don't have a piano at hand (and usually don't play it, anyway), but if you try patterns like 5-3-1-3-1-2-4-1 (assuming that the next measure is similar), then you are more flexible in finding smooth continuations.
Answer: It really depends on the size of your hands, but for me (with an average-ish hand span), this is the 'best' way of doing it:

5 - 3 - 2 - 1 - 3 (over) - 1 - 2 - 1

That just fell under my fingers when I sightread the passage - it may not work for you. Other pianists can only recommend fingering, since everyone's hands are different. However, you can often take the fingering of other pianists and adapt it to make it more comfortable for you.
If you find that you are struggling to stretch that, you could try switching fingers mid-note (i.e. playing a note with 3 but holding and swapping 3 with 4, so you can reach further). Also, you should try to avoid playing a black note with 1, since the thumb is not ideally positioned for it. Where possible, replace it with 2; it makes for far easier playing. (Sometimes you can't avoid playing a #/b with the thumb, and it often takes a lot of practice to get it right. Avoid it if you can.)
Hopefully this points you in the right direction.
Comment: 5321-is the only correct answer. The 3-1 is not correct if the piece is slow, but this is evident to an expert pianist. Look at Chopin's Prelude #23; you will find the same issue! This figure is very easy!
Answer: I'd take a page from Chopin for this one.
Chopin felt that there were two separate technical problems with arpeggios, one for within the octave, one for larger than the octave (see Eigeldinger, JJ. Chopin, Pianist and Teacher).  For larger than the octave, Chopin advocated deciding on a pivot finger around which the hand turned. This is one of the technical elements that needs to be mastered for his Etude op. 10 no 1.
I agree with 5-3-2-1 but if you are still not comfortable, try pivoting around 3, so that the tip of 3 stays roughly (not exactly) the same place in space, and the hand pivots around it.
Answer: As others have said, a lot of it depends on the size of your hands.  However, a lot of it also depends on where you're going next.
I can hit all the tenths except the major tenths with a black and white note, and I would finger the first set as Poben has it.  As Jeffrey has it would be hard for me, but if you can almost hit an octave between 3 and 5 it's probably the best.  Now, if I had a student with small enough hands that Poben's fingering was difficult I would suggest having a look at 5-1-2-1-2 for the first five notes.
Regarding thumb on black notes, this usually isn't the best if you need afterwards to pass a finger over it to a white note, and especially the reverse.  However, otherwise thumb on black notes is fine.
Now, let's suppose you are repeating the same set of 8th notes again.  In this case, you want to wind up on the thumb on the A, so you can make it easily to the next F#.  For the last four 8th notes, I would use 2-3-5-1, or possibly 4 instead of 3 (if you're using Jeff's fingering, then 1-2-3-1 is best).  There is a bit of work to keep the 3rd/4th from getting tangled up when you're trying to get the thumb on the same note two notes later, but in the end it will be easer to control than using 2-1-2-1 or something similar.
On the other hand, if the next notes are the same as the last four, or perhaps something higher up in the treble clef, then probably 2-4-5-4 is best to position the hand for those notes.


Como comparar dois tons de cores e dar a porcentagem de similaridade (Java)?

Question: Como pegar imagens com mesmas dimensões (imagens de dois quadrados iguais) e analisar os tons delas para dizer o quão parecidas são (retornar uma porcentagem da similaridade entre os dois tons das imagens)? Isso é possível?
Eu estou fazendo o código que vai receber uma imagem e compará-la com outras imagens já definidas no código, dizendo se ela é igual a alguma das imagens. Essa parte do código, já tenho. O problema é que agora queria não apenas dizer se ela é igual, mas quantos % ela é igual as imagens definidas. E o tipo de código que estou fazendo é voltado para imagens com as mesmas proporções, tanto a de entrada quanto a de saída. São imagens com cores únicas, apenas, e queria que o código desse, por exemplo, a similaridade entre imagem azul claro e azul escuro, rosa choque e rosa bebê.
Comment: Poderia especificar melhor o que deseja? Um exemplo dos dois quadrados, se já tem algo feito, se possui algum conhecimento sobre o assunto... Tudo isso é relevante para "nos ajudar a te ajudar".
Comment: Relacionado: [Como funciona o recurso "Buscar por imagem semelhantes" do google?](http://pt.stackoverflow.com/questions/61165/como-funciona-o-recurso-buscar-por-imagem-semelhantes-do-google)
Answer: Vou referenciar esta outra resposta minha:

Composição de cores
É importante ter em mente que embora o branco seja o resultado da soma do vermelho, do verde e do azul, isso não significa que cada uma destas três cores representa um terço do branco. Isso não é verdade, e pode ser percebido facilmente de forma empírica ao notar-se que o verde puro é brilhante, enquanto que o vermelho puro é fosco e o azul puro é escuro.
Na verdade, a proporção exata da composição da luz branca depende da disposição das diferentes células receptoras na retina do olho do observador, condições de saúde, cansaço, idade e stress do observador, das condições de iluminação, do brilho e contraste da tela, do ângulo e direção entre o plano da tela e a linha de visada do observador, do tipo da tela (reflexiva ou anti-reflexiva, CRT, LED, plasma, LCD, retroprojetor, kindle, etc), entre muitas outras variáveis, podendo até mesmo variar de um olho para outro em uma mesma pessoa com visão normal e saudável.
Mas, desconsiderando-se estas variáveis que estão fora do controle do programador e pressupondo que o usuário tenha uma visão saudável e esteja usando uma tela de boa qualidade em um ambiente com iluminação adequada, há uma fórmula que vi em um livro uma vez há alguns anos que dava a seguinte proporção:

É uma pena que não lembro o título, mas o bfavaretto deu três referências para isso nos comentários: 1, 2 e 3, embora existam pequenas variações nos fatores exatos.
Ter em mente estes fatores da composição do brilho é importante para o caso de você quiser fazer um algoritmo de anti-aliasing que considere que os subpixels têm diferentes cores.
Essa mesma fórmula dada acima para a cor branca, pode ser usada para medir-se o brilho de uma determinada cor a partir de seus componentes vermelho, verde e azul. De acordo com esta página, a fórmula recomendada pela W3C (parecida com essa anterior) é:

Entretanto, essa mesma página diz que essa fórmula pode falhar ainda. Por exemplo, a cor (240, 0, 30) é um pouco mais brilhante que (80, 80, 80), sendo que por essa fórmula da W3C, a primeira teria um brilho de 75,18 enquanto que a segunda teria 80 ([![vermelho e cinza][2]][2]). O motivo disso é que o brilho é na verdade a distância que uma cor tem em relação ao preto, e não apenas a soma ponderada dos valores das suas tonalidades.
Se considerarmos todas as cores dispostas como diferentes pontos internos em um paralelepípedo onde um dos vértices é o preto, o vértice oposto é o branco, os vértices adjacentes ao preto são o vermelho, o verde e o azul e os vértices opostos a esses são o ciano, o magenta e o amarelo (nesta ordem), teríamos que uma das dimensões corresponde ao valor do componente vermelho, a outra do componente verde e a outra do componente azul. Se definirmos o tamanho de cada uma das dimensões desse paralelepípedo como a intensidade do componente da cor correspondente, então poderíamos usar a distância euclideana do ponto ocupado por uma cor qualquer dentro desse paralelepípedo até o vértice da cor preta como uma medida do brilho. Assim, para calcular a intensidade de uma cor, basta usar o teorema de Pitágoras. Se usarmos os valores da W3C, chegaríamos a esta fórmula:

Nesta fórmula, os brilhos das cores acima seriam 131,62 e 80.

Com base nisso, se o brilho de uma cor é a distância que essa cor tem da cor preta, tal como explanado acima, então podemos medir a diferença entre duas cores a partir dessa distância. A fórmula seria a última que foi dada acima, só que os valores das variáveis vermelho, verde e azul são as diferenças entre os valores das duas cores.
Em Java, isso seria assim:
public static double distanciaCores(int r1, int g1, int b1, int r2, int g2, int b2) {
    int dr = r1 - r2;
    int dg = g1 - g2;
    int db = b1 - b2;
    return Math.sqrt(0.299 * dr * dr + 0.587 * dg * dg + 0.114 * db * db);
}

O método getRGB(int,int) retorna em Java cores no formato ARGB como um int (32 bits). Neste int, os 8 bits mais significativos são o alpha (opacidade), os 8 bits seguintes são o componente vermelho, depois mais 8 bits do componente verde e finalmente 8 bits do componente azul. Assim sendo, podemos sobrecarregar o método acima para trabalhar com as duas cores codificadas cada uma dentro de um int já pensando em usar o formato retornado pelo getRGB posteriormente. Métodos auxiliares para separar cada um dos componentes (ignorando-se o alpha) também são utilizados:
public static double distanciaCores(int a, int b) {
    return distanciaCores(red(a), green(a), blue(a), red(b), green(b), blue(b));
}

public static int red(int c) {
    return (c >> 16) & 0xff;
}

public static int green(int c) {
    return (c >> 8) & 0xff;
}

public static int blue(int c) {
    return c & 0xff;
}

Para fazer isso em uma imagem inteira, compara-se pixel por pixel e normaliza-se de acordo com a área da imagem:
public static double diferencaImagens(BufferedImage a, BufferedImage b) {
    int h = a.getHeight();
    int w = a.getWidth();
    if (w != b.getWidth() || h != b.getHeight()) throw new IllegalArgumentException();

    double dif = 0.0;

    for (int y = 0; y < h; y++) {
        for (int x = 0; x < w; x++) {
            int c1 = a.getRGB(x, y);
            int c2 = b.getRGB(x, y);
            dif += distanciaCores(c1, c2);
        }
    }

    return dif / (h * w);
}

O único detalhe é que esse algoritmo só funciona bem quando os pixels da primeira imagem coincidem com o da segunda, o que é útil para medir-se imagens onde tenha versão preto e branca vs colorida, imagens utilizando filtros diferentes, diferentes brilhos e contrastes, focalização, etc. Isso não vai dar bons resultados caso as posições dos pixels não coincidam (casos de rotações, deslocamentos, ampliações e reduções de imagens, etc).
Comment: @diegofm É isso: https://meta.stackexchange.com/q/291947/176034 e isso: https://meta.stackexchange.com/q/292058/176034
Comment: Agradeço muito a explicação, entendi uma boa parte! Só fiquei confuso no segundo bloco de código, o que ele faz?
Comment: @BrunoAlmeida Resposta editada. Está melhor?
Comment: Sim, entendi! Muito obrigado!


Get groups a user belongs to for both local and domain accounts

Question: I'm trying to list all the groups that a given user belongs to, and I want to support both local machine accounts and domain accounts. I can get the groups for domain accounts with the following code:
public void ListAllGroupsDomain()
{
    ListAllGroups(ContextType.Domain,
                  "myDomain",
                  "myDomainUser",
                  "myDomainPassword");
}

public void ListAllGroups(ContextType contextType
                          string name,
                          string username,
                          string password)
{
    using (var context = new PrincipalContext(contextType,
                                              name,
                                              username,
                                              password))
    {
        using (var findByIdentity = UserPrincipal.FindByIdentity(context, "testedit"))
        {
            if (findByIdentity != null)
            {
                var groups = findByIdentity.GetGroups(context);
                var results = groups.Select(g => g.Name).ToArray();
                Console.WriteLine("Listing {0} groups", results.Count());
                foreach (var name in results)
                {
                    Console.WriteLine("{0}", name);
                }
            }
        }
    }
}

However, if I try to call for an account local to the machine, I get a COM exception saying that my username or password is incorrect (which they aren't):
public void ListAllGroupsMachine()
{
    ListAllGroups(ContextType.Machine,
                  "myMachine",
                  "myMachineUser",
                  "myMachinePassword");
}

I'm guessing that I'm using the FindByIdentity incorrectly for machine accounts. So I tried a slightly different approach that doesn't use FindByIdentity:
public void ListAllGroups2(ContextType contextType
                          string name,
                          string username,
                          string password)
{
    using (var context = new PrincipalContext(contextType,
                                              name,
                                              username,
                                              password))
    {
        using (var userContext = new UserPrincipal(context))
        {
            var results = userContext.GetGroups();
            Console.WriteLine("Listing {0} groups:", results.Count());
            foreach (var principal in results)
            {
                Console.WriteLine("{0}", principal.Name);
            }
        }
    }
}

This version didn't throw any exceptions, but the call to GetGroups() also didn't return any results. How can I get the groups a particular user belongs to that is reliable for both machine and domain accounts?
Answer: Thanks to a little help I gleaned from https://stackoverflow.com/a/3681442/1222122, I figured out what I was doing wrong. I was setting up the PrincipalContext incorrectly. I didn't need to give it the domain, username, or password, just the ContextType. The following code works for both local machine accounts and domain accounts:
public void ListAllGroupsDomain()
{
    ListAllGroups(ContextType.Domain, "myDomainUsername");
}

public void ListAllGroupsMachine()
{
    ListAllGroups(ContextType.Machine, "myMachineUsername");
}

public void ListAllGroups(ContextType contextType, string userName)
{
    using (var context = new PrincipalContext(contextType))
    {
        using (var findByIdentity = UserPrincipal.FindByIdentity(context, userName))
        {
            if (findByIdentity != null)
            {
                var groups = findByIdentity.GetGroups(context);
                var results = groups.Select(g => g.Name).ToArray();
                Console.WriteLine("Listing {0} groups", results.Count());
                foreach (var name in results)
                {
                    Console.WriteLine("{0}", name);
                }
            }
        }
    }
}

The only thing I needed to be sure to do was to strip out the domain from the username before I passed it to ListAllGroups because the function that was providing it to me would prepend it to the username in some cases.
Comment: This is exactly what I'm looking for atm, but I'm getting really slow access to the .FindByIdentity and .GetGroups calls. Did you experience performance issues with this?
Comment: How slow is slow for you, Spikeh? I tried several different methods when I was working on this, and I seem to remember some being nearly instantaneous, and some taking 10+ seconds. It's been so long, though, that I couldn't tell you much more than that.
Comment: FindByIdentity takes about 4 seconds (using ContextType.Machine) and GetGroups takes about 6 seconds. I'm not on a domain, though - Windows 8.1, running through IISExpress. Time for some caching, methinks.


My c++ Bubble sort function is not working

Question: I need to create a function called bubbleSort by passing the value instead of passing an array. But the bubbleSort function doesn't work at all. It still output the unsorted numbers which is the one that I assign to the only array in main(). The result should be shown as ascending order.
<code>#include <iostream>

using namespace std;
void bubbleSort(int, int);

int main(){
    const int size = 10;
    int numbers[size] = { 100, 33, 49, 23, 84, 2, 72, 17, 82, 64 };

    for (int i = 0; i < size; i++) {
        cout << numbers[i] << " ";
    }

    for (int i = 0; i < size; i++) {
        for (int j = i+1; j < size; j++) {
            bubbleSort(numbers[i], numbers[j]);
        }
    }
    cout << "\n";
    for (int i = 0; i < size; i++) {
        cout << numbers[i] << " ";
    }
    return 0;
}

void bubbleSort(int i, int j) {
    int temp;
    if (i > j) {
        temp = i;
        i = j;
        j = temp;
    }
}
</code>
the result is shown like this
<code>100 33 49 23 84 2 72 17 82 64
100 33 49 23 84 2 72 17 82 64
</code>
Comment: In C++ arguments are by default passed *by value*. That means the value in the call (like `bubbleSort(numbers[i], numbers[j])`) are *copied* into the local arguments variables of the functions. Modifying these local variables will only modify these variables, not the original values used in the call.
Comment: The function you named `bubbleSort` is better called `swap`. The problem is however not in the name, but in the fact that it accepts its parameters by value, and cannot have any effect on anything outside. Please search what "pass by value" and "pass by reference" mean, and how to express the latter in C++.
Comment: Your issue is no different than this very simple program:  `void foo(int x) { x = 10; } int main() { int x = 0; foo(x);  std::cout << x; }`  You will be surprised that on output, `x` is still 0 after calling `foo`.  Basic C++ fundamentals, but for whatever reason, you were not aware of this.
Answer: You must pass the parameter function of your Babel sort function to the function as a call-by-reference to be applied to the array you defined in the mine after completing the operation function.
like under :
<code>#include <iostream>

using namespace std;
void bubbleSort(int&, int&);

int main()
{
    const int size = 10;
    int numbers[size] = { 100, 33, 49, 23, 84, 2, 72, 17, 82, 64 };

    for (int i = 0; i < size; i++)
    {
        cout << numbers[i] << " ";
    }

    for (int i = 0; i < size; i++)
    {
        for (int j = i+1; j < size; j++)
        {
            bubbleSort(numbers[i], numbers[j]);
        }
    }
    cout << "\n";
    for (int i = 0; i < size; i++) {
        cout << numbers[i] << " ";
    }
    return 0;
}

void bubbleSort(int &i, int &j) {
    int temp;
    if (i > j) {
        temp = i;
        i = j;
        j = temp;
    }
}

for example:
input :  100 33 49 23 84 2 72 17 82 64
out put :  2 17 23 33 49 64 72 82 84 100
</code>
For further reading, you can refer to the following site.
https://www.tutorialspoint.com/cplusplus/cpp_function_call_by_reference.htm


JSTL request attribute in c:if

Question: I set a request attribute in my action class as follows:
request.setAttribute("xFg", Boolean.TRUE);

I want to retrive this in my JSP. I want to retrive them using JSTL tags. I tried this :
<c:if test="${requestScope.xFg}">
    <c:set var="showlist" value="true" />
</c:if>

But c:if didnt work, I mean it didn't go to c:set.
I tried to print the same using c:out but nothing got displayed. What is wrong or how should I test request attribute value? I haven't used requestScope so far. Is requestScope the option to get the request value?
Comment: try this `test="${requestScope['xFg']}"`
Comment: What happens when you do ``?
Comment: Check that the JSTL core library is declared at the top of your JSP. Check the generated HTML code, and se if you don't have unprocessed c:if and c:set tag inside.
Answer: Make sure to activate EL evaluation in your JSP page by specifying the attribute isELIgnored="false" in the page directive as follows:
<%@ page isELIgnored="false" %>

JSTL request attribute in c:if


Mysql where 1= 0 confusion

Question: In simply sql book, there is portion of code mentioning if I use where 1 = 0, i can safely add an OR conditions like:
WHERE
   1=0
   OR name LIKE '%Toledo%'
   OR billaddr LIKE '%Toledo%'
   OR shipaddr LIKE '%Toledo%'

I didnt get it why when i use where 1 = 0 i can safely add an OR statement
Can i just use something like below?
WHERE
   1=1
   OR name LIKE '%Toledo%'
   OR billaddr LIKE '%Toledo%'
   OR shipaddr LIKE '%Toledo%'

I understand that where 1=1 is a shortcut to add an And statement.
I understand that because where 1 =1 will return true.Can i use it for Or statement too?
Istill didnt get the part where 1 = 0
Any explaination would be great.
Comment: Note that for readability you can also just use `where false or` & `where true and`.
Answer: This depends on the type of boolean operations you're working on. If you want to add a variable number of AND statements, then you use a statement that invariably evaluates to true, such as 1 = 1. On the other hand, if you want to do the same with OR statements, then you should use a statement that evaluates to false, such as 1 = 0.
Let's say you have a boolean variable x with an indeterminate truth value (it might be true, or it might be false. You don't know.) Now, if you find the value of x AND false, you get false, regardless of what the value of x is.
On the other hand, if you look at x OR true, you'll get true. Again, this is regardless of the truth value of x.
In your statement, you want the hard-coded value to have no effect on the logic of the query. Since false OR a OR b OR c is logically equivalent to a OR b OR c, the hard-coded statement has no effect. In the other case, true AND a AND b AND c is equivalent to a AND b AND c.
Answer: MySQL uses short-circuit boolean evaluation.
As soon as the result resolves to a definite TRUE or FALSE MySQL stops evaluating the rest of the rows.
TRUE OR ? OR ? will always be TRUE, so MySQL will only look at the first item and not test anything else.
FALSE AND ? AND ? will always be FALSE, so again MySQL will not look at the other tests.
This has the (unintended) side-effect that MySQL will never look at your table with the LIKE, but instead return all rows in the following query:
SELECT * FROM atable
WHERE
   1=1                         /* <--- this makes the whole OR set always true*/
   OR name LIKE '%Toledo%'     /* therefore the like tests are never done     */
   OR billaddr LIKE '%Toledo%' /*and all rows are returned */
   OR shipaddr LIKE '%Toledo%'

In this query:
SELECT * FROM atable
WHERE
   1=0                          /* false OR ? has an unknown outcome so */
   OR name LIKE '%Toledo%'      /* MySQL has to evaluate the LIKE tests */
   OR billaddr LIKE '%Toledo%'  /*only some rows will be returned*/
   OR shipaddr LIKE '%Toledo%'

This works exactly in reverse with AND
Answer:
Can i just use something like below?

WHERE
   1=1
   OR name LIKE '%Toledo%'
   OR billaddr LIKE '%Toledo%'
   OR shipaddr LIKE '%Toledo%'

that will return every row (since it's always true), so no...

Mysql where 1= 0 confusion


Optimal Stopping Example

Question: I've got a very basic question about optimal stopping.  It may have just been me, but I feel like my professor didn't do a great job of explaining the topic too well.  I was hoping one of you would be able to step me through this simple example:
Consider a simple random walk with absorbing boundaries on {0, 1, 2, ..., 10}.  Suppose the following payoff function is given
$$[0, 2, 4, 3, 10, 0, 6, 4, 3, 3, 0].$$
Find the optimal stopping rule and give the expected payoff starting at each site.
Any help is greatly appreciated.  Thanks!
Comment: Reference: This is Exercise 4.1 (page 98) in Gregory Lawler's "Introduction to Stochastic Processes (2nd edition)".
Answer: Clearly you should stop at $4$, with value $10$, and have to stop at $0$ or $10$ with value $0$.  We can decompose this into two games, $[0,2,4,3,10]$ and $[10,0,6,4,3,3,0]$  Taking the first, we should play at $3$ as we gain either way.  On average, we can't lose playing at $1$.  Letting $a,b,c$ be the values of $1,2,3$ we have $a=\frac b2, b=\max(4, \frac {a+c}2), c=5+\frac b2$.  So $b=\max (4,\frac {5+b}2)\ge \frac 92$, so we should play at $2, b=5, a=\frac 52, c=\frac {15}2$, and the expected payoff is $[0,\frac 52,5,\frac {15}2,10]$  with a stopping rule of only stop at $0$ and $4$.  The fact that the expectations are linear in position reflects that we never stop midway.  The second is similar.

Optimal Stopping Example


How to deduce if a type is lambda?

Question: how to deduce a type is lambda ? like std::is_function ?  I've also tried std::is_invocable, but it need exactly types of parameters.
Comment: It's just an indication that you need to rethink the broader problem you are trying to solve, and find another way that doesn't depend on knowing whether a type is a lambda.
Comment: @VeNToR: I strongly suspect this is [an XY problem](https://meta.stackexchange.com/q/66377/322040). *Why* do you think you need to do this? What problem are you solving?
Comment: Lambdas *are not special* in C++. There is never any reason to write a function that can *only* take a lambda. Functions should accept any particular callable object appropriate to its use.
Comment: @BrianBi: Yeah, by my understanding a lambda is syntactic sugar for a standard functor class which a user could write by hand (the captures are constructor arguments, the arguments are the arguments to `operator()`); at best, with RTTI, you might be able to do terrible heuristics to figure out if the underlying name is something the cat spat up (probably a compiler generated name for the lambda) vs. a vaguely human name (though with the name-mangling compilers apply, it's going to look a lot like cat sick too). But even if you can, and even if heuristics work, there's never a reason to do it.
Comment: @VeNToR: I'm not asking for all your code. Just an explanation for why you think it's important to *specifically* identify lambdas and handle them differently from other functors, which they are drop-in equivalents for. The explanation could lead to an answer that solves your actual problem; the whole point of XY problems is that you've settled on a bad solution to your real problem, and you're trying to make the bad solution work, neglecting to describe the real problem that has a good solution.
Comment: @VeNToR Well, since string_view doesn't have contains() until C++23 what about this: https://godbolt.org/z/d39Ed69nW
Comment: You can check whether it is invokable with specific parameter types. There are arcane techniques for checking whether it has *any* `operator()`, but this is usually not a valid thing to check. In any case, you can't check whether it's specifically a lambda type.
Comment: @BrianBi, I think that is sad but true :(.  I tried many ways...
Comment: @ShadowRanger: my code is very long to share it.  I wish I could share ?
Comment: With https://stackoverflow.com/a/56766138/2193968 you can do https://godbolt.org/z/G9dWrMaW4
Comment: @JerryJeremiah, thanks but this uses runtime processing...
Answer: You cannot check for every invocable types without having the exact parameters. Take this for example:
auto my_lambda = [](std::integral auto number) {};

There are few properties that make it hard to check without knowing the parameter types:

You cannot take the address of operator() since it's a template. You could take the address of operator()<int> but you'd have to know the type in advance
You cannot try the lambda with a "convert to anything" type, since it's not an integral
There are no other observable properties of the type that can be observed.

That makes it really hard to have a is_lambda trait. Also, you could have something like that:
struct A {
    void operator()(int) const {}
};

This would be indistinguishable from a lambda.

There are however, very arcane ways to check if a type is a lambda or not.
I would strongly recommend not to do that.
You could theorically check the name of the type by using __PRETTY_FUNCTION or __FUNCSIG__, and check if the name look like a compiler generated name for a lambda, but that would exclude any other user defined callable types, which are, and should be accepted like lambda.
I leave the implementation as an exercise to the reader.

How to deduce if a type is lambda?


Differential Equation for a schematic harmonic oscillator.

Question: Differential Equation for a schematic harmonic oscillator.

here are some pictures that i tried to solve but i don't know it is true or completely wrong.
Comment: What have you tried?
Comment: Welcome to Math SE!  When posting questions like this it is customary to include information about what you have tried before expecting any helpful responses.
Comment: Presumably this is an exercise from some course of study that you're undertaking. I'll bet that there was an example of this sort of problem earlier in the material somewhere. Even if you can't solve the resulting equation, you should at least be able to formulate a differential equation for this system by analogy with that example. You write that you didn't find any solutions: did you at least get that far? If so, where did you run into difficulty in solving the equation? Edit your question to show those efforts.
Comment: Can anyone help me out of this?
Comment: I tried it but actually I didn't find any solution
Comment: You should've edited [your original question](https://math.stackexchange.com/q/3289140/265466) with this additional information instead of cloning it.
Answer: Hint.
Calling $X = x - x_0$ with $x_0 = \frac{m g}{k}$ we have
$$
m\ddot X = F - c\dot X - k X
$$