How can I calculate this integral $\int_{-\infty}^{\infty} d k \frac{\sinh a k}{\sinh (\pi k) \sinh (\frac{\pi k}{2})}e^{ikx} $

Question: I have the following integral as:
$$
 \int_{-\infty}^{\infty} d k \frac{\sinh a k}{\sinh (\pi k) \sinh (\frac{\pi k}{2})}e^{ikx}
$$
where $0\leq a \leq \frac{\pi}{2}$.
Can any one help me calculataing this integral? Many thanks!
Comment: Are you familiar with contour integration?
Comment: Could $a \in (-3 \pi/2,3 \pi/2)$?
Comment: Not exactly, but the approach is the same (integration in the complex plane) https://math.stackexchange.com/questions/395822/integrate-int-0-infty-frac-sinh-ax-sinh-x-cos-bx-dx   or     https://math.stackexchange.com/questions/61605/tough-integral-involving-sinx2-and-sinh2-x
Comment: @RonGordon Yes it could be.
Comment: @MarkViola just a little bit, any hint will be appreciated.
Answer: $$J=\int_{-\infty}^{\infty}  \frac{\sinh a k}{\sinh (\pi k) \sinh (\frac{\pi k}{2})}e^{ikx}dk=\int_{-\infty}^{\infty}  \frac{\sinh a k}{2\sinh^2 (\frac{\pi k}{2}) \cosh (\frac{\pi k}{2})}e^{ikx}dk=\int_{-\infty}^{\infty}  \frac{\sinh 2a k}{\sinh^2 (\pi k) \cosh (\pi k)}e^{2ikx}dk$$
For the convenience we will evaluate the integral
$$J=\int_{-\infty}^{\infty}  \frac{\sinh a k}{\sinh^2 (\pi k) \cosh (\pi k)}e^{ikx}dk=\frac{1}{2}\int_{-\infty}^{\infty}  \frac{e^{ikx}}{\sinh^2 (\pi k) \cosh (\pi k)}\Bigl(e^{ak}-e^{-ak}\Bigr)dk=\frac{1}{2}\bigr(I(a)-I(-a)\bigl)$$
We will consider $I(a)$ and $I(-a)$ separately. This is not rigorous, but we know that at $a \in (-3 \pi/2,3 \pi/2)$ integral is convergent, and we don't have singularity at $x\to0$: due to the symmetry only $i\sin(kx)$ survive from $e^{ikx}$, what gives additional power of $x$ at $x\to0$ and makes $x=0$ a removable singular point.
$$I(a)=\int_{-\infty}^{\infty}  \frac{e^{ikx}}{\sinh^2 (\pi k) \cosh (\pi k)}e^{ak}dk$$
We choose the following contour in the complex plane:

To close the contour we also add two small half-circles ($C_1$ and $C_2$ above the point $x=0$ and below $x=i$ (we go counter clockwise in both cases) and vertical lines $1$ and $2$ at $R\to\pm\infty$
Integral along the closed contour looks
$$\oint =I(a)+\int_{C_1}+\int_1+\,\,e^{ia-x}I(a)+\int_{C_2}+\int_2=2\pi i \operatorname{Res}_{x=\frac{i}{2}}\biggl(\frac{e^{ikx}}{\sinh^2 (\pi k) \cosh (\pi k)}e^{ak}\biggr)$$
It can be shown that $\int_1$ and $\int_2\, \to0$ at $R\to\infty$. We have a single pole of first order inside the contour at $x=\frac{i}{2}$, so
$$I(a)(1+e^{ia-x})+\int_{C_1}+\int_{C_2}=-2\exp{(\frac{ia-x}{2})}$$
$$\int_{C_1}=\lim_{r\to0}\int_{-\pi}^0\frac{\exp{(are^{i\phi})}\exp{(ix re^{i\phi})}}{\bigl(\pi re^{i\phi}+\frac{(\pi re^{i\phi})^3}{3!}+...\bigr)^2}ire^{i\phi}d\phi=\lim_{r\to0}\int_{-\pi}^0\frac{1+re^{i\phi}(a+ix)+ O(r^2)}{\bigl(\pi re^{i\phi}+\frac{(\pi re^{i\phi})^3}{3!}+...\bigr)^2}ire^{i\phi}d\phi$$
Integral contains the divergent term, but it does not depend on $a$, so it will be canceled when we evaluate $I(a)-I(-a)$ - as it should be.
Keeping only converging terms we get:
$$\int_{C_1}=-\frac{i}{\pi} (a+ix)$$
In the same fashion we get
$$\int_{C_2}=\frac{i}{\pi} (a+ix)e^{ia-x}$$
Taking all together
$$I(a)=\frac{i}{\pi}\,(a+ix)\frac{1-e^{ia-x}}{1+e^{ia-x}}-2\frac{e^{\frac{ia-x}{2}}}{1+e^{ia-x}}$$
$$I(a)-I(-a)=\frac{2ia}{\pi}\frac{\sinh x}{\cosh x+\cos a}+\frac{2 ix}{\pi}\frac{\sin a}{\cosh x+\cos a}-4i\frac{\sin\frac{a}{2}\sinh \frac{x}{2}}{\cosh x+\cos a}$$
Taking one half and switching to the initial $a$ and $x$ ($a\to 2a$ and $x\to 2x$)
$$J=\frac{2i}{\pi}\,\frac{a\sinh 2x+x\sin 2a-\pi\sin a\sinh x}{\cosh 2x+\cos 2a}$$
Please check the calculations.
Comment: Just corrected several typos (lost $\frac{1}{\pi^2}$ in the first term - $\sinh^2\pi x=(\pi x)^2+...$ at $x\to0\,$)
Comment: First of all thank you very much @Svyatoslav for your detailed answer. I guess a minus sign is lost on the way $2\pi i Res_{x=\frac{i}{2}}=2\pi i (\frac{i}{\pi}e^{\frac{1}{2}(i a-x)})=-2e^{\frac{1}{2}(i a-x)}$. I think also that there is an extra pre-factor of 1/2 in the second definition of I(a) (just before the the contour plot ). By divergent term you mean : $\frac{i}{\pi^{2}r e^{i\phi}}$ ? Finally, I am having slightly different pre-factors in the final result. Your answer was very helpful for me ... Thanks a lot!
Comment: Thank you. This is good that you checked the result - I did only quick check ($I=0$ at $k=0$ and $a=0$). You are right: the factor $\frac{1}{2}$ just before the contour plot is extra (but, luckily, it is not used in the further calculations :) - I will remove it from the text. Divergent term - also correct. You are also right regarding the residual at $x=\frac{i}{2}$: $\,\sinh^2(\pi i/2)=-\sin^2(\pi/2)$ - I lost this sign. Sorry for these mistakes. Such calculations require attention and thoroughness...
Comment: Dear @Svyatoslav this is what I got as a final result : $\frac{i}{\pi} \frac{(2x-\pi)\sin(2a)+2a\sinh(2x)}{\cos(2a)+\cosh(2x)}$ and I hope I am not mistaken.
Comment: I'm afraid $I(x\to0)\to0$ - because of the symmetry (in fact we integrate $\sin kx$ from $e^{ikx}=\cos k x+i\sin kx$ in the nominator - integral with $\cos k x$ - wanish).
Comment: Another point is the change $x\to-ia$ and $a\to ix$ - integral should not change (due to $\sinh ka\sin kx\to \sin kx\sinh ka$)
Comment: if the solution has the term $\sin a\sinh x$ - these requirements are met.
Comment: Dear @Svyatoslav, your arguments are corrects. I checked again and your final expression is correct. I do not know how but I lost the factor 1/2 in the Res. on the way. I am sorry for the mistake and thank you again!
Comment: @HJames You did a great job. Now you can easily evaluate this type of integrals. Good luck!


Inverse trigonometry integration

Question: The magnitude of ans is correct but the sign is negative. Which is incorrect. But the procedure seem to be correct.
Comment: I suspect that the problem lies in the resolution of $\cos^{-1}(\sin(u))$ vs. $\cos^{-1}(\cos(u-\pi/2))$, but I'm not certain.
Comment: What is your question?
Comment: related: http://math.stackexchange.com/questions/1543142/why-does-arccossinx-look-like-this
Comment: The answer looks correct to me.  The area under the curve $y=u-\pi/2$ between $u=0$ and $u=1$ IS negative.  Draw the graph and see.
Answer: The problem lies in your choice of trig identity.
Cosine is an even function, so $\cos(\frac{\pi}{2}-x)$=$\cos(x-\frac{\pi}{2})$
The problem with your "cancelation" is that $y=\frac{\pi}{2}-x$ and $y=x-\frac{\pi}{2}$ are not the same graph. On interval $[0,1]$ one is above the axis and one below. That explains your answer off by a negative. So the best thing is to graph the original function first as to determine what trig identity should be used to rewrite the sine.
Comment: Yes cos(π/2-x)=cos(x-π/2) but if you plot   y=arccos(cos(π/2-x)) and y=arccos(cos(x-π/2)) it will be same.
Comment: @user408669. You are absolutely correct about that. HOWEVER: Once you enforce the cancellation property of the trig functions, things change. Try graphing the lines and see what happens! By the way, I upvoted your question, I think this is a great post...
Comment: Okk. I understand your point. But how do you suggest doing this in an exam hall without Mathematica.
Comment: If this question is on an exam, then that professor is mean...I probably would have done it wrong too just because the identity issue would not even occurred to me. Without any graph, this question would trick a lot of people and had this been a multiple choice question, certainly lot of people would have picked the wrong answer...
Answer: I think this is because of the property of cos to  absorb negative sign of angle.
If you write $\sin x = \cos(\frac π2 - x)$
You got $\frac π2 - \frac12$
Answer: The problem is the range of arccosine, which is between $0$ and $\pi$.  Therefore, $\cos^{-1}(\cos x)\ne x$ if $x$ is negative.
Comment: This is a very reasonable explanation. Thankyou

Inverse trigonometry integration


Joint raw moments of multivariate normal

Question: Let $X_1,X_2$ follow a bivariate standard normal distribution with some non-zero correlation coefficient, $\rho\neq 0$.
Let the function $f(z) = z^k,\; k=1,...$. By Stein's lemma, we have that
$$\text{Cov}(f(X_1),X_2) = \text{Cov}(X_1,X_2)\cdot E[f'(X_1)]$$
and in our case
$$\text{Cov}(X_1^k,X_2) =  E[X_1^k X_2] = \rho\cdot kE(X_1^{k-1})$$
Since $E(X_1^{k-1}) = 0$ when $k-1$ is odd, it follows that
$$\text{Cov}(X_1^k,X_2) = E[X_1^k X_2] = 0,\;\; \text{iff}\;\;\ k+1\;\;\text{is odd}$$
namely when the sum of the moment-orders is odd.
Moreover by Isserlis Theorem, if $X_1,...,X_n$ follow jointly a zero-mean multivariate normal distribution with dependence, we have for $m\leq n$
$$E[X_1\cdot ... \cdot X_m] = 0 \;\; \text{iff}\;\;\ m\;\;\text{is odd}$$
What I cannot seem to find anywhere is the generalized combination of the two results and its proof, namely that if $X_1,...,X_n$ follow jointly a zero-mean multivariate normal distribution with dependence, we have
$$E[X_1^{r_1}\cdot ... \cdot X^{r_m}_m] = 0 \;\; \text{iff}\;\;\sum_{j=1}^m r_j \;\;\text{is odd}$$
Do we?
Comment: The symmetry $(X_1, \ldots, X_m)\to (-X_1, \ldots, -X_m)$ preserves the distribution but changes the moment to $(-1)^{r_1+\cdots+r_m},$ *QED.*  Am I overlooking some subtlety?  It doesn't seem any of the quoted theorems are needed.
Comment: @whuber Good lord, that was painfully simple. So, if I understand correctly, we have the result I am after for _any_ multivariate distribution for which the symmetry you invoke holds, and not just for the multivariate normal? And that would be the spherical distributions that have moments?
Comment: That's right.  I'm glad you added that final condition, Alecos, because the argument's conclusion relies on the moments being defined and not infinite.
Comment: I vote for [Alecos](https://stats.stackexchange.com/users/28746/alecos-papadopoulos) and [whuber](https://stats.stackexchange.com/users/919/whuber) to write a joint academic paper on this!
Answer: To close this one, as whuber's comment pointed out, let a multivariate distribution be symmetric in the sense
$$(X_1, \ldots, X_m) \sim_d (-X_1, \ldots, -X_m)$$
Suppose also that moments exist. Then
$$E[X_1^{r_1}\cdot ... \cdot X^{r_m}_m] = E[(-X_1)^{r_1}\cdot ... \cdot (-X_m)^{r_m}]$$
$$\implies E[X_1^{r_1}\cdot ... \cdot X^{r_m}_m] = (-1)^{r_1+\cdots+r_m}\cdot E[X_1^{r_1}\cdot ... \cdot X^{r_m}_m]$$
If $r_1+\cdots+r_m $, the sum of moment-orders, is an even number, then $(-1)^{r_1+\cdots+r_m}=1$ and the relation holds always.
But if $r_1+\cdots+r_m $ is an odd number then we have
$$E[X_1^{r_1}\cdot ... \cdot X^{r_m}_m] = - E[X_1^{r_1}\cdot ... \cdot X^{r_m}_m]$$
and this can only hold if
$$E[X_1^{r_1}\cdot ... \cdot X^{r_m}_m] = 0$$


How to improve agility when Transposing?

Question: I'm a Big fan of C Major and enjoy improvising songs on C Major, even when the song is not in C, I Always "Transpose" the chord or arpeggio into C Major.
Unfortunately, when accompany someone, or playing with other people, we always "force" to play with different keys, and it slows me down significantly, and I can't improvise freely.
What practice do I need to improve agility when we do not play on "comfortable" keys?
Is there any hacks, guidelines, or even "universal arpeggio" that we can use?
Answer: Practice scales.
Piano teachers always ask their pupils to practice scales. It's seen as a chore, and many pupils wonder why they have to do it.
Well, the answer is, to solve your problem. Practising scales, arpeggios and ultimately chords and pieces in a particular key, teaches you the sharps and flats in that key. It teaches you the fingerings that work in that key.
Playing in C major is easy for beginners because you don't have to think about black keys. But at intermediate stage and beyond, it's not most players' favourite key because the position of the black keys in other keys can facilitate more fluid hand movements.
For example, you'll probably find that you can soon play a D major upward scale faster and more fluidly than a C major scale because as your third finger sits on F#, it leaves a bigger gap and a better angle for your thumb to reach G, than in the C major scale getting from E to F.
Which keys to practice first?

Books for beginners will introduce keys in a thought-out order
You could work around the circle of fifths as @Shevliaskovic suggests, learning keys with one sharp/flat, then two, then three etc.
If you're more interested in pop/rock, then you could concentrate on the commonest rock/pop keys, which tend to be influenced by what guitarists like: G, A, E, D etc. -- use the keys given in any transcriptions you use.

Perhaps you also want to be able to work out chord progressions on the fly. In that case you need to also learn "working sets" of chords for every key you learn. To start with, I, IV, V are enough. Maybe add the minor VI.

C, F, G, Am
D, G, A, Bm
E, A, B, C#m

... and so on.
For a pianist, this is pretty easy if you know the scale. You can take a few moments to remind yourself of those chords - which will all use only notes from the scale - before playing the piece. In more complex songs, more chords will crop up, but you can derive them on the fly as long as you know the scale.
Of course, there are more complicated pieces which break the rules and have accidentals. You just have to deal with these as you find them.
Comment: Yes. Learn scales, become familiar with your scales books. I thought they were garbage before I started improvising (and transposing). I thought I'd just mention the extreme usefulness of model scales in improvisation.
Comment: @reptildarat: for a quick result in a short term, try to focus on E flat for the next few days. Study the notes in that key and the chords. When you can figure out the 1,2,3 (do, re, mi) etc it would be easy. The iii minor chord will stay a iii minor chord even after you change key. So if you play a iii minor in C (which is the Em chord), after transposing to Eb it will become the iii of Eb... and the 3 (mi) of Eb key is the note G, so now you will play a Gm chord. That is G-Bb-D.
Comment: Then when you have gained some confidence(having successfully played in E flat), go back to @Shevliaskovic's suggestion re the circle of fifth.
Comment: You're right, well, I mostly play just for fun, but my friend who is piano jazz player, he love to play on E flat. Anyway, is there any exercise that can make us "fast" to guess the next chord progression?
Comment: Oh I see, you want to know chords on the fly. I will add something about that.
Comment: One reason for loving Eb is that a heck of a lot of jazz standards were written in that key. Cole Porter for one used it extensively.
Answer: I believe the only thing you can do is to do whatever you did on the C major. The same way you practised on C major, practise on other keys in order to get more comfortable.
You can start from C major and then move to the next scale (on the 'circle of fifths'(http://en.wikipedia.org/wiki/Circle_of_fifths))

If you move to the next scale(left or right), there will be only one different note from C major (either Bb or F#), so you won't find it really hard to improvise.
At first play the scale again and again, ascending and descending, play the chords of the scale and then when you feel comfortable enough, start improvising over some simple chords of the scale.
Practise the scale just like you did with C major,with which you now feel comfortable with and you'll be able to improvise after some time and practice.
Comment: Well, OP said he can improvise on C major. So I suggested that he started improvising on C major, then moving on to F major or G major, so as to have only one different note on his scale.(I, myself) find it more difficult to improvise on Ab major (if I could improvise mainly on C major) rather than F or G major
Comment: What is the relevance of the circle of fifths here?
Comment: That's my opinion/suggestion on how I could help him, it could be wrong -- *and then he could move on to the next scales** (forgot to add it to my answer)


On IIS, how do I patch the SSL 3.0 POODLE vulnerability (CVE-2014-3566)?

Question: How do I patch CVE-2014-3566 on a Windows Server 2012 system running IIS?
Is there a patch in Windows Update, or do I have to do a registry change to disable SSL 3.0?
Comment: I tried running Fix it 50495 on Windows 2008, and it failed with error "This Microsoft Fix it does not apply to your operating system or application version." Oh well.
Comment: There is a **Microsoft Fix it 50495** on the MS KB page you linked to.
Answer: There is no "patch". It's a vulnerability in the protocol, not a bug in the implementation.
In Windows Server 2003 to 2012 R2 the SSL / TLS protocols are controlled by flags in the registry set at HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\Schannel\Protocols.
To disable SSLv3, which the POODLE vulnerability is concerned with, create a subkey at the above location (if it's not already present) named SSL 3.0 and, under that, a subkey named Server (if it's not already present). At this location (HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\Schannel\Protocols\SSL 3.0\Server) create a DWORD value named Enabled and leave it set at 0.
Disabling SSL 2.0, which you should also be doing, is done the same way, except that you'll be using a key named SSL 2.0 in the above registry path.
I haven't tested all versions, but I think it's probably safe to assume that a reboot is necessary for this change to take effect.
Comment: reboot not necessary on Windows Server 2012 at least. you can verify before and after at http://poodlebleed.com/ by entering your URL and 443 for SSL port
Comment: Thanks, Do you know if I should disable PCT as well since its allegedly disabled by default and yet not disabled in this way ?
Comment: @Simon, is there something else you have to do to get the changes to take effect?  I just made the registry updates on a Server 2012 machine, but it's still getting reported that SSL3 is enabled.
Comment: I don't believe so. I'm assuming you're using iis and my Apache and you checked usjng that website. And you're sure you have the exact right registry key?
Comment: * NOT apache (I don't know where 'my Apache' came from!)
Answer: Just for ease of installation I derived this "disable ssl 2 and 3.reg" file from Evan's answer above:
Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 3.0\Server]
"Enabled"=dword:00000000

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 2.0\Server]
"Enabled"=dword:00000000

Answer: Powershell to disable SSL2 and SSL3:
2..3 | %{ New-ItemProperty -Path "HKLM:SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL $_.0\Server" -Name Enabled -PropertyType "DWORD" -Value 0 -Force }

Comment: Yup... see screenshot uploaded to: http://i.imgur.com/rctFH4D.png
Using PS 3.0 and WSMan 3.0.
Comment: Unfortunately the above only works if the registry subkeys are already present. Would be nice to see PS that can create them if not exists or update them if they do.
Comment: Are you sure? Mine creates them for me. It might differ on lower versions of Powershell and Windows (I'm using v2 on Server 2008 R2)
Answer: There is a free utility from Nartac that you can use to disable the protocols.
https://www.nartac.com/Products/IISCrypto/Default.aspx
Answer: Here's a PowerShell that will test for the presence of the registry keys, create them if needed, and then enter the necessary values to disable SSL 2.0 and SSL 3.0
$regPath1 = 'HKLM:SYSTEM\CurrentControlSet\Control\SecurityProviders\Schannel\Protocols\SSL 2.0'
$regPath2 = 'HKLM:SYSTEM\CurrentControlSet\Control\SecurityProviders\Schannel\Protocols\SSL 2.0\Server'
$regPath3 = 'HKLM:SYSTEM\CurrentControlSet\Control\SecurityProviders\Schannel\Protocols\SSL 3.0'
$regPath4 = 'HKLM:SYSTEM\CurrentControlSet\Control\SecurityProviders\Schannel\Protocols\SSL 3.0\Server'

If(!(Test-Path -Path $regPath1))
{
New-Item -Path $regPath1 -Force
}

If(!(Test-Path $regPath2))
{
New-Item -Path $regPath2 -Force
}
   New-ItemProperty -Path $regPath2 -Name DisabledByDefault -PropertyType DWORD -Value "1" -Force
   New-ItemProperty -Path $regPath2 -Name Enabled -PropertyType DWORD -Value "0" -Force

If(!(Test-Path $regPath3))
{
New-Item -Path $regPath3 -Force
}

If(!(Test-Path $regPath4))
{
New-Item -Path $regPath4 -Force
}
   New-ItemProperty -Path $regPath4 -Name DisabledByDefault -PropertyType DWORD -Value "1" -Force
   New-ItemProperty -Path $regPath4 -Name Enabled -PropertyType DWORD -Value "0" -Force

This can be deployed using SCCM or command line - just be sure to run the SCCM job or command line as Administrator.  Some websites with the registry information indicate that a reboot is required after the registry keys are created and/or modified.
Answer: Or grab a copy of IISCrypto and click the best practices button, then uncheck SSL 3.0 and then apply, then reboot
Answer: You don't have to disable SSL3. You can enable SSL3 and have POODLE mitigated.
# Copy and paste this in PowerShell then restart your server
$cipherSuitesOrder = @(
    'TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256_P256',
    'TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256_P384',
    'TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA_P256',
    'TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA_P384',
    'TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA_P256',
    'TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA_P384',
    'TLS_RSA_WITH_AES_128_CBC_SHA256',
    'TLS_RSA_WITH_AES_128_CBC_SHA',
    'TLS_RSA_WITH_AES_256_CBC_SHA256',
    'TLS_RSA_WITH_AES_256_CBC_SHA',
    'TLS_RSA_WITH_RC4_128_SHA',
    'TLS_RSA_WITH_3DES_EDE_CBC_SHA',
    'TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256_P256',
    'TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256_P256',
    'TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384_P384',
    'TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384_P384',
    'TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA_P256',
    'TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA_P384',
    'TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA_P256',
    'TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA_P384'
)
$cipherSuitesAsString = [string]::join(',', $cipherSuitesOrder)
New-ItemProperty -path 'HKLM:\SOFTWARE\Policies\Microsoft\Cryptography\Configuration\SSL\00010002' \
-name 'Functions' -value $cipherSuitesAsString -PropertyType 'String' -Force | Out-Null

With these settings you would still have IE6 support (with SSLv3 using RC4) and have a more than acceptable configuration security wise. Only IE6 and really old client would be using SSLv3 or RC4 ciphers.
Answer: There's a good PowerShell script that helps with IIS 7.5 & 8 configuration:

This PowerShell script setups your Microsoft Internet Information
  Server 7.5 and 8.0 (IIS) to support TLS 1.1 and TLS 1.2 protocol with
  Forward secrecy. Additionally it increases security of your SSL
  connections by disabling insecure SSL2 and SSL3 and and all insecure
  and weak ciphers that a browser may fall-back, too. This script
  implements the current best practice rules.

https://www.hass.de/content/setup-your-iis-ssl-perfect-forward-secrecy-and-tls-12
Comment: Hmm, not sure why this was down voted. I used that utility myself and it works perfectly.
Comment: This looks good but [at least one guy](https://serverfault.com/questions/660338/rdp-down-on-windows-server-what-to-do) has had problems after running it - don't know if it's isolated seen other people say it's great.


How increase number of files shown in Recently opened files list?

Question: After Eclipse starts I see only 4 recently opened files. Is it possible to see for instance 10 instead?
Comment: where u see only 4 file in eclipse... ex:- which are open ..?
Answer: You go to
     Window -> Preferences
Then select
     General -> Editors
and you'll find an option that says
     Size of recently opened files list
which you can change to whatever you see fit.
Comment: ... as long as `whatever <= 15` :] (at least in Eclipse 3.6)
Comment: Cannot see image in answer (HTTP Connection Failed).
Comment: Sorry about that. My server broke down and I will restore all my images as soon as my provider gets it up again. (Moved files to a temporary server)


Espelhamento de texto em PDF

Question: Estou tentando inverter um texto para que o texto espelhado seja salvo no PDF; no entanto, não tive êxito, tentei de várias maneiras e o que fazia mais sentido era girar 360º e inverter, mas o texto não mudou. .. Também tentei girar 180º e não funcionou, preciso desse espelhamento, porque ao imprimir a impressora inverte todo o conteúdo, por isso já tenho que enviá-la invertida para que possa ser impressa legivelmente. Estou usando o XTranform do ABCPDF
theDoc.Transform.Rotate(360, theDoc.Rect.Left, (theDoc.Rect.Bottom + theDoc.Rect.Width));
theDoc.Transform.Invert();
string textoPdf = "INSERT THE TEXT");
theDoc.FontSize = 8;
theDoc.AddText(textoPdf);

Resultado final -> ʇxǝʇ ǝɥʇ ʇɹǝsuᴉ
Comment: Se sua impressora imprime invertida, não basta apenas virar a folha?
Comment: o PDF é gerado normal, e a impressora imprime invertido pois a foto será colada em uma camisa, há outras informações na impressão como tamanho, data e etc que é necessario a leitura, não importe o que quanto você virar a folha voce não conseguirá ler o que está escrito legivel
Comment: Coloque 05/02/2019 14:44 Camisa Branca - M em algum html e me diga se será possivel uma leitura clara das informações na tela.. este é o meu problema, para a resolução necessito que seja enviado "errado" para a impressora que ela fará a correção invertendo o conteudo.
Answer: Solução:
theDoc.Transform.Magnify(-1, 1, theDoc.Rect.Left, (theDoc.Rect.Bottom + theDoc.Rect.Width));
theDoc.Transform.Invert();
string textoPdf = "INSERT THE TEXT");
theDoc.FontSize = 8;
theDoc.AddText(textoPdf);

Dica para as pessoas do futuro, se forem para responder com ignorancia, não comentem, todos ja fomos iniciantes um dia, se estamos com dificuldade em coisa X não responda com coisas obvias sobre o mundo humano, estamos aqui atras de códigos e não soluções como "É so não imprimir invertido".
Agradecido.

Espelhamento de texto em PDF


Como calcular a quantidade de conexões em uma Deep Network?

Question: Tenho exatamente esse cenário e preciso saber a quantidade de conexões que esse conjunto tem. Procurei em diversos lugares e não tenho certeza da resposta. Ou seja, não sei calcular o número de conexões da minha rede, isso ainda não está claro para mim. O que tenho é exatamente o seguinte:
**Tendo bias em tudo, menos no input
- Input: 784
- First hidden layer
  - Output: 400
- Second hidden layer
  - Output: 200
- Output layer
  - Output: 10
Eu calcularia isso da seguinte forma:
    ((784 * 400) + bias) + ((400 * 200) + bias) + ((200 * 10) + bias) = XXX
Não sei se isso está correto. Preciso de ajuda para entender como resolver isso, e se não for simplesmente algo matemático, qual a teoria para fazer esse calculo?
Obrigado.
Answer: Se você escrever isso como multiplicação de matrizes - ao meu ver - fica mais fácil de calcular o número de parâmetros (ou se você quiser chamar de conexões) da sua rede.
Suponha que o seu input X seja uma matrix X[n, 784] em que n é o número de observações.
Uma rede com 2 camadas uma com 200 neurônios e uma com 10. Ficaria algo +- assim:
Y[n, 10] = ativacao(X[n,784]*P1[784, 200] + B1[200])*P2[200,10] + B2[10]

Em que P1, P2, B1, B2 são matrizes de parâmetros.
Agora você consegue conferir se a sua conta está correta, basta contar o número de elementos das matrizes de parâmetros.
No caso: 784*200 + 200 + 200*10 + 10


Invalid CSRF token as a result of session cookie not being set when visiting login form directly

Question: Updating this post following further investigation to ensure it is focussed on the actual issue (also now raised at: https://github.com/symfony/symfony/issues/42691)
My Environment
I am running:

Symfony 5.3.6
PHP version 7.3
Debian 10 running on WSL2
Symfony development server on localhost, accessed via Chrome on the same machine

Description & What I'm Trying to Achieve

I am trying to implement a secure login form by following the Symfony tutorial (https://symfony.com/doc/current/security/form_login_setup.html).
I get the error message "Invalid CSRF token." on the first login attempt but not subsequent login attempts.
Following debugging (using Xdebug 3) it appears Symfony is not creating a session to link a CSRF token to.

Steps to Reproduce

Created a new Symfony project using symfony new test_project
Installed the maker bundle using composer require symfony/maker-bundle --dev
Followed the security set-up guide (https://symfony.com/doc/current/security.html) sections 1-2
Generated a login form using make:auth command following this guide https://symfony.com/doc/current/security/form_login_setup.html
Accessed https://localhost:8000/login
Submit the login form with a valid username and password pair, along with the hidden pre-generated CSRF token

The Outcome I Was Expecting

A registered user being able to login at https://localhost:8000/login

The Actual Outcome

When accessing https://localhost:8000/login, no cookie is set
When submitting the login form including the CSRF token, as there is no cookie with this request, Symfony finds no session, and so naturally finds no CSRF token
As there is no CSRF token Symfony throwns an exception "Invalid CSRF token.". The response headers of this include a cookie that represents a session (assuming automatically, as I have followed the Symfony tutorial)
When submitting the login form for the second time, as there is a cookie sent in the request headers, Symfony "finds" the CSRF token on the session and so the login works as expected
Comment: I usually have this problem when the form loads from cache. For example, logging out opens the login page again in my app and if the user just leaves that page open until they want to login the next time it will fail. Do you have any cache rules either in your response header or in your .htaccess?
Comment: Hi @fun2life thanks for your tip. I don't believe I have any cache rules in my response header, I haven't added any, but how would I check this? Regarding .htaccess files I found the following files:
`/home/lushawn/.cache/composer/.htaccess` `/home/lushawn/.config/composer/.htaccess`                                                                              `/home/lushawn/.local/share/composer/.htaccess`
All of which have "Deny from all" written in them. Could this be an issue?
Comment: Could you try to change your register.html.twig form to only "{{ form_start(registrationForm) }} {{ form_end(registrationForm) }}" and see if it works with the automatic rendering. Also try adding a SubmitType to the registration form instead of adding manually a submit button.
Comment: Not directly on topic but out of the box Symfony uses PHP's native session handler which on my linux system points to /var/lib/php/sessions.  The docs show how to point it to var/cache if you want.  Clearing it out might help though probably not.  Looks like you used the make:auth and make:registration-form commands which seem to work for me.  I assume you are using the Symfony development server?
Comment: Hello @alexcm thanks for your suggestion. I just tried this on the reg form and I get more strange behaviour. On initial registration attempt I get the following error:
`Key "errors" for array with keys "value, attr, form, id, name, full_name, disabled, label, label_format, label_html, multipart, block_prefixes, unique_block_prefix, row_attr, translation_domain, label_translation_parameters, attr_translation_parameters, priority, cache_key, clicked" does not exist.`

Then if I go back or navigate through links to the reg form and reattempt to register, it works... This is also repeatable
Comment: Try commenting this for now {%for error in child.vars.errors%}{{error.message}}{%endfor%} until you now for sure everything arrives to the view properly.
Comment: Interesting @Cerad , I am using the Symfony dev server yes. I also tried giving my caches a clear but no luck... I wonder, in my /var directory only contains a cache and a log subdirectory, does it seem like anythings missing?
Comment: This is all just guessing here but you might want to explicitly set your [session's save_path](https://symfony.com/doc/current/session.html#configuration) just to clear up one mystery.
Comment: Well, one way to check for caching problems would be to replace the hidden token field with a text field. After logging out (I guess you'll be redirected to the login page, otherwise just open the login page and follow this) remember the value, close your browser window and then open the page again and check the value. And your .htaccess in question would sit in your public folder next to index.php if there is one
Comment: Thanks for thank link @Cerad it was interesting, I tried changing some of the settings as well as setting up a path to save sessions to but no luck unfortunately. I think I may have to try completely redo my authentication and login/registration controllers etc. and see if that fixes it, I am using the guard authenticator (which I know is now deprecated) but I tried changing to the new Authenticator-based Security but this didn't seem to help.
Comment: Also @fun2life I tried checking this, the token seems to change on every attempt and every reload of the page, even after closing the tab.
Comment: Would you guys mind upvoting the post in hope that it gets more attention? Many thanks :)
Comment: Upvoting is not going to get more attention.  Your starting over plan is a good idea.  Fresh project, make:user, make:auth and make:registration-form.  Except for a slight tweak to the Authenicator everything should just work as is.  If not then check the project into github and post a question on the [Symfony Discussion](https://github.com/symfony/symfony/discussions/categories/q-a) board.
Comment: @Cerad Thanks for the advice, I've followed it and updated the question and also created an issue on Symfony's github.
Answer: After posting on Symfony's github, their response helped me uncover the issue. Here is my post for interest.
It appears the issue was that I was using PHP 7.3 which has reached its end of life. I managed to keep all my original configuration settings in security.yaml and framework.yaml the same and get my own Symfony project to now work. However, there was nothing in Symfony that alerted me that PHP 7.3 would be incompatible.
What I did

Upgraded to PHP 8.0.10 following this guide

The outcome

I no longer get the CSRF error and my login functionality all works as expected on my own Symfony project.


Term for conversion between different tonalities (C major to C minor, etc.)

Question: (Inspired by this recent question:)
If we theorists reserve "transposition" for shifting everything by specific intervals, like every note goes down by a minor 3rd, what do we say when someone transforms a piece in C major to C minor (like by lowering the thirds, etc.) or also potentially shifting everything by generic intervals (CDEFG becomes DEFGA, shifted by diatonic 2nds in the C major scale)?
Is there a term for this that I forgot or cannot recall? Or is there no specific term besides "converting", "transforming", or other general terms?
Comment: "Relative and Parallel Keys" might be the words you look for. I don't understand them enough to write an answer.
Comment: I'm not convinced, that this process is done frequently enough to have established a well-known word. One reason for this is, that not much of the character of the piece can be preserved during this process.
Comment: If you stay inside the cyclic group another generic term might be permutation (or group action if it acts on another set)
Comment: Isn't that a reharmonization?
Answer: I think you first want to use the wording change of mode to capture the major to minor change. You often read something like "...a change to the minor mode..."
Modulation is not a good choice, because the meaning of that word is very clear, and means only a change of tonic without any indication of what happens in the new tonic. I think the typical usage of modulate carries the expectation that new thematic material is presented in a larger form. You don't modulate a whole song from one tonic to another. A work modulates to a new tonic and introduces a new theme. That is the typical usage.
In contrast to transpose - changing the tonic, but not the mode, like Over the Rainbow in A flat major transposed to D major - the wording reinterpreted in minor may be a good choice. Over the Rainbow reinterpreted in G sharp minor.
I think reinterpret captures the important point that choices need to be made about which tones get changed. Putting the music into the minor mode is not as simple as changing only the major third of a major key to a minor third. The sixth and seventh scale degrees are variable in minor, and while there is conventional handling of those two degrees it isn't a matter of hard and fast rules. Different choices could be made for different expressive reasons.
Translation seems like a good description too. When a write translates a work of literature from one language to another choices are made for one wording over another. Two translators could translate the same book differently. The same could happen translating a musical work from major to minor. Two musicians could translate the music differently.
Answer: This is called Modulating to a parallel key.  Reference: https://www.musicnotes.com/now/tips/a-complete-guide-to-musical-modulation/.
Answer: Extraneous modulation is going from one key to an unrelated one. Parallel modulation would be a good term for going into the parallel major/minor.
Answer: The theory term must be modal interchange.
Like a borrowed chord is an example of modal interchange we have here the case that the whole scale adapted to the tune is modal changed.
https://music.tutsplus.com/tutorials/introduction-to-modal-interchange--audio-14142


Reading a text file into a char[][] array in Java

Question: I am trying to fill a char[][] array from a text file and I cannot seem to figure out how to do it. I've tried to use .toCharArray() but it doesn't seem to work. If you can give any insight on how to make this work that would be awesome!
String filename = "ArrayHW2.txt";
        int numTests = 6;
        char[][] testAnswers = new char[50][5];
        char[] key = new char[4];

        Scanner input = null;
        try
        {
            input = new Scanner(new File(filename));
        }
        catch(FileNotFoundException e)
        {
            System.out.println("Error Opening File");
            System.exit(1);
        }

        for(int row = 0; row < testAnswers.length; row++)
        {
            for(int col = 0; col < testAnswers[row].length; col++)
            {
                testAnswers[row][col] = input.next().toCharArray();
            }
        }
        input.close();

Comment: may we see the text file?
Comment: *but it doesn't seem to work* is not very descriptive.  Please edit your question to add information that describes your input, expected vs actual output, errors, etc.
Comment: Whats the error you get when you try to execute that code?
Comment: T. Wielgos, is your intent to create a 2D array where each row represents a line and each column represents a character on the given line?
Comment: The text file is 6 rows and 5 columns of letters that represent answers to a true-false test
Answer: The basic problem is that you are trying to assign a character array to something was meant to hold a character. You might think of char[] type as storing the location in memory where characters are recorded, and a char type as the character itself.
When you call toCharArray() on a String, the return type is char[]. It looks like you expect this array to have a single character, like the A, B, C, or D of a multiple-choice test. You could get the first (and only?) character of that array with something like ...toCharArray()[0], but this is wasteful because a new array is created, and characters are copied into it from the source string. It's simpler to use the getCharAt() method on the String directly.
String filename = "ArrayHW2.txt";
char[][] testAnswers = new char[50][5];
try (Scanner input = new Scanner(Paths.get(filename))) {
  for(int row = 0; row < testAnswers.length; row++) {
    for(int col = 0; col < testAnswers[row].length; col++) {
      String token = r.next();
      if (token.length() != 1)
        throw new IllegalArgumentException("Answers must be one character");
      testAnswers[row][col] = token.charAt(0);
    }
  }
} catch (IOException ex) {
  System.err.println("Error reading file: " + ex.getMessage());
  System.exit(1);
}

Comment: @DavidConrad I've modified that statement, but I maintain that it's useful to think of a `char[]` as a pointer to characters. Handles and offsets and JIT optimizations make this conceptualization imprecise, but not misleading in this context.
Comment: A `char[]` is not like the memory address at which a `char` can be found, it is an object which contains a fixed number of `char`s, stored contiguously in memory. Perhaps you're thinking of C where a `char[]` decays to a `char *` in certain contexts.
Comment: @erickson I understand what you mean, but I think that the explanation that an address can't fit in the 16 bits used by a char is a red herring. You can't assign a `long[]` to a `long` either, even though the size of an address probably _can_ fit in the space taken by a long. It is sufficient to just say you can't assign an array to a primitive.
Comment: Fair enough, but it could be confusing if the reader has a background in C. I do think it's useful for Java programmers to know an array is an Object.
Answer: String filename = "ArrayHW2.txt";
        int numTests = 6;
        char[][] testAnswers = new char[50][5];
        //char[] key = new char[4];

        Scanner input = null;
        try
        {
            input = new Scanner(new File(filename));
        }
        catch(FileNotFoundException e)
        {
            System.out.println("Error Opening File");
            System.exit(1);
        }
        int counter = 0;
        while(scanner.hasNext())
        {
            copyString(testAnswers[counter], scanner.nextLine());

        }

        input.close();

its been a while i haven't code in java and im not sure about the methods but consider it a pseudo code .
you can use this copy :
void copyString(char[] arr, String x)
{
   int size = x.length();
   for (int i=0; i<size; i++){
   arr[i] = x.CharAt(i);
}


Finding an uncountable chain of subsets the integers

Question: How to find an uncountable subset of $P(\mathbb{N})$ such that every two elements of it can be compared. In fact, give an uncountable subset of $P(\mathbb{N})$ such that has totality property. We mean by $P(\mathbb{N})$, the powerset of natural numbers set $\mathbb{N}$.
Comment: See also: http://math.stackexchange.com/questions/253192/chain-of-length-2-aleph-0in-p-mathbbn-subseteq
Answer: As mentioned in Uncountable chains (in the question itself), one can do this as follows:
Pick a bijection between $\mathbb{N}$ and $\mathbb{Q}$ so it suffices to find such a chain in the powerset of $\mathbb{Q}$. But $\mathbb{Q}\subseteq\mathbb{R}$ so for any real number $r$ we can define the subset $\Gamma_r = \{x\in\mathbb{Q}\mid x < r\}$. This then defines an injective order-preserving map from $\mathbb{R}$ to $\mathcal{P}(\mathbb{Q})$ (given by $r\mapsto \Gamma_r$), which gives us the uncountable chain.


Python3 script exit with any traceback?

Question: I have one Python3 script that exits without any traceback from time to time.
Some said in another question that it was caused by calling sys.exit, but I am not pretty sure whether this is the case.
So how can I make Python3 script always exit with traceback, of course except when it is killed with signal 9?
Comment: If you could add the code it would be easier to understand.
Answer: It turns out that the script crashed when calling some function from underlying so, and crashed without any trackback. .

Python3 script exit with any traceback?


Printing Single Item from ArrayList Created in Another Generic Class?

Question: Trying to get an understanding of generics in Java. I've created an ArrayList using non-generic methods and casting to print them out, everything works fine using the usual array.get(index) but when I use generics to create the list, the get method doesn't work. I can print the whole list just fine, but I want to pick out individual elements. I've tried a few different things which have made the code a little messy probably, so sorry about that. I know things could probably be done an easier way, I'm just trying to learn about Generics in Java and I ran into this issue. I've watched several different videos and found several examples, so I may be trying to put two concepts together the incorrect way. Tried researching, can't find the answer.
First class Generic.java is to create the generic ArrayList.
import java.util.ArrayList;
import java.util.List;

public class Generic<T> {

private ArrayList<T> data;

    public Generic() {
        data = new ArrayList<T>();
    }

    public void add(T element){
        data.add(element);
    }

    //Not even sure if I need these get/set but I put them in there for testing
    public ArrayList<T> getData() {return data;}

    public void setData(ArrayList<T> data) {this.data = data;}

    public String toString(){
        return data.toString();
    }
}

Second class is the main test class:
import java.util.ArrayList;
import java.util.List;

public class Test {

    public static void main(String[] args) {

        List nonGenericList = new ArrayList();
        nonGenericList.add("Enzo");
        nonGenericList.add(458);
        String nonGen1 = (String) nonGenericList.get(0);
        Integer nonGen2 = (Integer) nonGenericList.get(1);

        System.out.println(nonGen1);
        System.out.println(nonGen2);

        Generic<Object> genericList = new Generic<>();
        genericList.add("Enzo");
        genericList.add(458);

        //This is where the .get(0) isn't working for me
        System.out.println(genericList.get(0));
    }
}

Thanks for any help!
Comment: @3kings Yes, the method is undefined. I've never had to define the get method before, how do I do it?
Answer: Your Generic<T> class doesn't have the method get(int index), you should create the method if you want to call it...
Try adding this to your Generic<T> class
public T get(int index){
    return data.get(index);
}

Comment: Thanks, this did it. I've never had to define that method before, didn't think to do it here. Thanks!
Answer: You can define get method like this in your Generic class:
   public T get(int i) {return data.get(i);}

Answer: You do not have add method you have defined the getData() method,
so write
ArrayList a=genericList.getData();
System.out.println(a.get(0));


Checked values(names) from listview to another activity

Question: In my app I have some names(from mysql database) in listview there are 100 names corresponding with checkbox. Once I click on noe or more checkbox then corresponding name should be displayed in next activity listview.
How to do this? If anybody have codes please provide me.
I would be appreciated your help..
Thanks in advance..
Comment: No sir.. if u have anything related about this pls provide me..
Answer: Lets say you've created your List with simple adapter like this:
ListAdapter adapter = new SimpleAdapter(MyActivity.this,arraylist,R.layout.list_item,new String[]{"name"},new int[]{R.id.txtName});
            MyActivity.this.setListAdapter(adapter);

To pass "name" to second activity you can do this:
        final ListView lv = MyActivity.this.getListView();
        lv.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?>parent, View view, int position, long id){
                HashMap<String, String>hm = (HashMap<String, String>)lv.getItemAtPosition(position);
                String message=hm.get("name").toString();
                Intent in = new Intent(getApplicationContext(), SecondActivity.class);
                in.putExtra("nameToSend", message);

                startActivity(in);

            }
        });

Then in second activity you can catch name like this:
protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.second_layout);
                Intent in = getIntent();
        String name = in.getStringExtra("nameToSend");
....

    }

Comment: Hi sir.. When i click the checkox checked names should have to pass to next activity listview..
Comment: Oh, sorry I thought that you want to pass FROM listview to second activity
Comment: Its k sir.. pls provide the code for above said. I have stored names in arraylist and displayed those are in ActivityA list with checkbox when i click the checkbox then checked name should be displayed in ActivityB listview
Comment: I've found a solution for you on this page:     http://www.mysamplecode.com/2012/07/android-listview-checkbox-example.html                                           Pay attention to this sentence:" To find out what all checkboxes are selected just loop thru the ArrayList that is being maintained by listening to the onClick event for the checkbox"
Comment: K sir I will try this.. this one i needed I have seen it now.. I will modify it as my requirements.. Thanks for your quick response..


Django ModelForm

Question: I am trying to create a simple CRUD with ModelForm. It works fine except that every time I edit, saving creates a new instance of the data. So i edit and get an extra row in DB instead of an updated one. I am at a loss as to how it knows to save an existing charity as it does not store the PK (id) as a hidden field in the form. That is how I always did it before trying to use the 'fabulous' ModelForm!
It's driving me nuts, I have read everything and as far as I can tell I am doing everything right.
Here is my code..
Model:
from django.db import models
from django.conf import settings

COUNTRY_CHOICES = settings.COUNTRIES

class Charities(models.Model):
    charity_name            = models.CharField(max_length=100)
    country                 = models.CharField(max_length=4, choices=COUNTRY_CHOICES)
    registration_number     = models.CharField(max_length=100)
    address1                = models.CharField(max_length=100)
    address2                = models.CharField(max_length=100)
    city                    = models.CharField(max_length=30)
    zip                     = models.CharField(max_length=10)
    phone                   = models.CharField(max_length=20)
    email                   = models.EmailField()
    charity_logo_image      = models.CharField(max_length=100)
    charity_banner_image    = models.CharField(max_length=100)
    charity_accepted        = models.IntegerField()

    def __str__(self):
       return self.charity_name

    def __unicode__(self):
        self.charity_name

View:
def list(request):
    charities = Charities.objects.all()
    return render_to_response('charities_charity_list.html', {'charities': charities})

def add(request):
    return add_or_edit(request)

def edit(request, charity_id):
    return add_or_edit(request, charity_id)

def add_or_edit(request, charity_id=None):
    print "ID = " + str(charity_id)
    form = CharityForm(request.POST or None,
                   instance=charity_id and Charities.objects.get(pk=charity_id))

    # Save new/edited student
    if request.method == 'POST' and form.is_valid():
        print form
        form.save()
        return HttpResponseRedirect('/charities/list/')

    return render_to_response('charities_charity_edit.html', {'form': form})

Form:
class CharityForm(ModelForm):
    class Meta:
        model = Charities

Template:
{% extends "base.html" %}

{% block title %}Charities Add{% endblock %}
{% block content %}

<form method="post" action="/charities/add/" id="save">
{{ form.as_table}}
<input type="submit" value="Save"></form>
{% endblock %}

Answer: It doesn`t work because your template is always POSTing to the view that adds a new Charity. When you manually type a URL like /charities/edit/5, it creates the ModelForm with the right initial data, but then POSTs to /charities/add, thus creating a new instance. You need to POST to /charities/edit/5, for example. Take a look at the url template tag.
I suggest you use 2 templates, one for adding, another for editing. I know it may not be very DRY, but I believe it's clearer this way.
Add template:
{% extends "base.html" %}

{% block title %}Charities Add{% endblock %}
{% block content %}

<form method="post" action="{% url charities_app.views.add %}">
{{ form.as_table}}
<input type="submit" value="Save"></form>
{% endblock %}

Edit template:
{% extends "base.html" %}

{% block title %}Edit Charity{% endblock %}
{% block content %}

<form method="post" action="{% url charities_app.views.edit charity.id %}">
{{ form.as_table}}
<input type="submit" value="Save"></form>
{% endblock %}

You may also want to check the create_object and update_object generic views, they are very useful in simple cases like yours.
Comment: Hi Tiago, thanks for replying. I hadn't heard of the generic_update / create views before. i will read up on them. Just trying to get the existing method working, I can't seem to extract the ID from charity.id so as to append it to the edit URL. I tried form.id as well but it's just not in context. Also, what is charities_app? is this you just putting in a placeholder for me to substitute? In my member view I tried using {% url race.members.views.edit member.id %} but got error............... Caught ViewDoesNotExist while rendering: Tried home in module race.charities.views.
Comment: I stupidly forgot I could pass the member/ charity Id in via the context. So i now have the ID in the edit URL and it works of course. Thanks. Now i am just trying to understand how to replace the action URL with similar to your example {% url charities_app.views.edit charity.id %} . What is charities_app. Should it be the path to the view? do I need to have get_absolute_url defined?
Comment: Hi, in this case charities_app would be the name of the app that contains the Charities model. charities_app.view.edit is just the name of the view that's going to process the request. This url tag is useful because you don't have to hardwire the urls in your templates.. That way, if you choose to change the url mappings in urls.py, you don't need to update the templates :)

Django ModelForm


IS there an easy way to add 5 days delay to XMLGregorianCalendar date?

Question: I want to add 5 days delay to XMLGregorianCalendar date (date is coming from json request). I tried converting it first to LocalDateTime as follows, this works
LocalDateTime date = request.getDate().toGregorianCalendar().toZonedDateTime().toLocalDateTime().plusDays(5);
Timestamp ts = Timestamp.valueOf(date);

Another approach I tried was as follows, which is throwing below error
Timestamp date = DateUtil.convertToTimestamp(request.getDate().
                                           add(DatatypeFactory.newInstance().newDuration("P14D"));

Error:
Required type: XMLGregorianCalendar
Provided: void

Although, the LocalDateTime one does not give any errors, I am just wondering if there's an easy way to do this. Any help would be appreciated. Thanks in advance!
Comment: What's the problem with the first approach? It doesn't get more easy than that?
Comment: What *exactly* does `request.getDate()` return? Is that an `XMLGregorianCalendar` object?
Comment: Why the focus on `Timestamp`? Are you trying to write this to a database? If so, say so, as that affects the Answers.
Comment: @BasilBourque Yes, I'm trying to write the timestamp value to the database.
Comment: @Coder Then say so in your Question. Click "Edit" to, well, edit.
Answer: tl;dr
XMLGregorianCalendar ➡ GregorianCalendar ➡ ZonedDateTime ➡ OffsetDateTime
myPreparedStatement
.setObject(
    … ,
    myXMLGregorianCalendar
    .toGregorianCalendar()
    .toZonedDateTime()
    .plusDays( 5 )
    .toOffsetDateTime()
)

Avoid legacy date-time classes
When handed a legacy date-time object like XMLGregorianCalendar, immediately convert to the modern java.time classes. In java.time, the replacement class is ZonedDateTime.
To get to ZonedDateTime, go though another legacy class, GregorianCalendar.
ZonedDateTime zdt = myXMLGregorianCalendar.toGregorianCalendar().toZonedDateTime() ;

Add days
Add five days. Adjustments are automatically made for anomalies such as Daylight Saving Time (DST).
ZonedDateTime fiveDaysLater = zdt.plusDays( 5 ) ;

LocalDateTime is not a moment
Do not use LocalDateTime at all in this situation. That class lacks the context of an offset or time zone, so it cannot be used to represent a moment, a specific point on the timeline.
Database
If you are trying to write this value to a database, do not use the legacy Timestamp class. Use only java.time classes. To communicate a moment to a database, use java.time.OffsetDateTime.
OffsetDateTime odt = fiveDaysLater.toOffsetDateTime() ;
myPreparedStatement.setObject( … , odt ) ;

Retrieval.
OffsetDateTime odt = myResultSet.getObject ( … , OffsetDateTime.class ) ;
ZoneId zoneId = ZoneId.of( "Asia/Tokyo"" ) ;
ZonedDateTime zdt = odt.atZoneSameInstant( zoneId ) ;

Answer: Don't use the Timestamp class.  It doesn't do what you think it does.  In fact, it doesn't even do what it was originally intended to do all that well (represent a particular SQL type).
Just use the add method of GregorianCalendar:
XMLGregoriantCalendar xcal = request.getDate();

GregorianCalendar gcal = xcal.toGregorianCalendar();
gcal.add(Calendar.DATE, 5);

xcal = DatatypeFactory.newInstance().newXMLGregorianCalendar(gcal);


determine the stability of an equilibrium point(x,0).

Question: I would like to determine the stability of equilibrium point $(x,0)$ of the differential equation
$\dot x = Ax$
$ A=
\bigg[
\begin{matrix}
0&0\\0&a
\end{matrix}
\bigg]
$ and $  a >0 $
I got
$ x'(t) = 0\ $
$\ y'(t) = a*y$
So, the equilibrium point is $(x,0)$.
How can I determine the stability of these equilibrium points?
Here is the phase portrait:
Any help will be appreciated!
Comment: The entire $x$ axis is an equilibrium point.
Comment: @Moo I draw the phase portrait, and I think the equilibrium point is unstable.
Comment: Thanks! Please add.
Answer: We want to determine the stability of the equilibrium points of the system $\dot x = Ax$, where
$$ A=
\bigg[
\begin{matrix}
0&0\\0&a
\end{matrix}
\bigg], ~\text{with}~a >0 $$
The critical points are where we simultaneously have $x' = y' = 0$ and we get the entire $x-$axis as
$$(x, y) = (x, 0)$$
Since this system is decoupled, we can write
$$\begin{align} x'(t) &= 0 \implies x(t) = c \\  y'(t) &= ay \implies y(t) = c e^{a t} \end{align}$$
The phase portrait is

Using all of the information above, we determine that the critical point is unstable.


RadioButton em flutter com erro

Question: Estou tendo problemas com esse código, quando executo aparece o seguinte erro:

"Unimplemented handling of missing static target".

O que pode ser? Como posso resolver esse problema?
import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
          appBar: null,
          body: Container(
              child: Center(
            child: Radiobutton(),
          ))),
    );
  }
}

class Radiobutton extends StatefulWidget {
  @override
  RadioButtonWidget createState() => RadioButtonWidget();
}

class RadioButtonWidget extends State {
  String radioItem = '';

  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        RadioListTile(
          groupValue: radioItem,
          title: Text('Radio Button Item 1'),
          value: 'Item 1',
          onChanged: (val) {
            setState(() {
              radioItem = val;
            });
          },
        ),
        RadioListTile(
          groupValue: radioItem,
          title: Text('Radio Button Item 2'),
          value: 'Item 2',
          onChanged: (val) {
            setState(() {
              radioItem = val;
            });
          },
        ),
      ],
    );
  }
}

Comment: Já experimentou fechar o app por completo e rodar de novo? Não tenho certeza, mas o erro parece ser algo relacionado com isso.
Answer: Você criou o seu Widget da maneira errada:
class Radiobutton extends StatefulWidget {
  @override
  RadioButtonWidget createState() => RadioButtonWidget();
}

class RadioButtonWidget extends State<Radiobutton>{
  /// ...
}

Eis aqui uma leitura sobre Stateless e Stateful widgets que podem te ajudar, e também um pouco sobre a classe State.
A proposito, visto que a classe que contém o estato atual "State" nunca será instanciada diretamente por você, é boa prática usar um _ no nome da mesma, exemplo para o seu caso:
class RadioButton extends StatefulWidget

A implementação seria:
class _RadioButton extends State<RadioButton>

Comment: Deu Certo! Muito obrigado!
Eu nem sabia que precisaria fazer esse diamante na frente do State.

RadioButton em flutter com erro


IIS 404.4 for rewriting https to http

Question: I have two servers running IIS, trying to serve Power BI Report Server (if it matters).
As far as I can tell on both servers, I have the following:

Power BI Report server listening on 127.0.0.1:80 (http)
IIS listening on (all ips):443 (https)
IIS pointing at an empty directory to serve
A rewrite rule that matches (.*) and redirects to http://localhost:80/{R:1}

All versions of everything as far as I can tell are the same (IIS version 10, Windows server 2016, etc), but things work on one server, and don't on the other. I have also verified that the web.config files on the two servers are the same as well.
The error that I am getting back on the server that doesn't work is a 404.4, which after some research means that there is a missing handler? The actual error I have in the trace logs is that The filename, directory name, or volume label syntax is incorrect.
How can I fix this issue/figure out what is going wrong?
Comment: Mistake 3 https://blog.lextudio.com/the-very-common-mistakes-when-using-iis-url-rewrite-module-a2ab7e4fee59
Comment: I did install ARR. Is there a way to check if it is not installed properly/worked?
Comment: Enable FRT to see what's under the hood https://docs.microsoft.com/en-us/iis/extensions/url-rewrite-module/using-failed-request-tracing-to-trace-rewrite-rules
Comment: I did do that, but I am still not sure what I should be looking for
Answer: Figured out the issue.
For some reason, when I installed ARR, it was not set to enable the proxy (at the machine level, ARR Cache -> Server Proxy Settings -> enable.

IIS 404.4 for rewriting https to http


ApacheSolr - No Documents or Data in Index

Question: For reasons unknown to me, Apache Solr isn't indexing any of the Articles that I create.
I have about 10 articles, just for testing, and Solr tells me that no documents have been indexed, nor have any documents been sent to the server for indexing.
I've tried reinstalling everything and deleting the Solr & Search Index to no avail.
What am I doing wrong?
Comment: Do you have connected your Apache Solr to a solr server ?
Comment: Of course. That was one of the first things that I checked. I also checked the schema.xml. There were problems there, so I fixed it, but the original problem still hasn't been fixed.
Comment: Is your cron running or else do you have solr set to index immediately instead of on cron?
Answer: Fixed the problem by reinstalling Solr. I might have missed something along the way the first time.
As for the original issue, I have no idea, but I'm considering this solved.


Do I justify it well?

Question: I have a function that is of the form and I want to prove that it is always positive :
$$\sqrt{x^{4}-7x^{2}+16}$$
I say that I can study $x^{4}-7x^{2}+16$ by putting $X = x^{2}$, which gives me $X^{2}-7X+16$ so I find the discriminant of this : $\Delta=b^{2}-4ac = (-7)^{2}-4\times1\times16 = 49-64=-15$.
Because $\Delta < 0$, we can conclude that there are no roots to both $x^{2}-7x+16$ and $x^{4}-7x^{2}+16$.
Can I assume that $ax^{4}+bx^{2}+c$ is always positive if $\Delta < 0$ and $a>0$ ? Or do I need to add more justifications ?
Right now, because of that, I will assume that my function is always positive.
To conclude, I say that the square root of a positive number is always positive, and so that $\sqrt{x^{4}-7x^{2}+16}$ is always positive.
Are my explanations correct ?
Comment: You can also write $$x^4-7x^2+16=x^4-8x^2+16+x^2=(x^2-4)^2+x^2$$ which is always strictly positive for real $x$.
Comment: If the discriminant is negative, there are no real roots, no matter what $a$ is so in your case, the domain of your radical term is all real numbers and the outcome is indeed always positive
Comment: $x^4-7x^2+16=\left(x^2-\frac 72\right)^2+\frac{15}{4}.$
Comment: @imranfat Here what I want to prove is that my original function is always positive, so $a$ matters, doesn't it ?!
Comment: No, if the discriminant is negative, then there are no real roots!. Now that either means only positive outcomes OR negatives. In your case it is positive because $a>0$
Answer: If the discriminant is negative there are no real roots and the sign of the polynomial is the same sign as $a$, on the whole interval.
So, since $X^2-7X+16$ is always positive and not equal to $0$, so also $x^4-7x^2+16$, and since it is known that the square root is greater or equal to zero, we have that $\sqrt{x^4-7x^2+16}>0$
So, it is correct as you said!!
Comment: Ok! Thanks a lot! I'm reassured !
Answer: If the discriminant is negative, the curve $y=ax^2+bx+c$ never intersects the x-axis. So it is either positive or negative $\forall x$. You can check the value of $y$ at any $x$ to be sure of the sign of $y$.
Answer: Since
$$x^4-7x^2+16>x^4-8x^2+16=(x^2-4)^2$$
we have
$$\sqrt{x^4-7x^2+16}>\sqrt{x^4-8x^2+16}=\sqrt{(x^2-4)^2}=|x^2-4|\ge 0.$$

Do I justify it well?


How to read a traceback in R

Question: I have a large dataset of polygons and, with a loop, I am trying at some point to find, calculate and store intersections. On the 870th iteration, the loop stops and I get the error :
Error in RGEOSBinTopoFunc(spgeom1, spgeom2, byid, id, drop_lower_td, unaryUnion_if_byid_false,  :
  TopologyException: Input geom 0 is invalid: Ring Self-intersection at or near point 26.437120350000001 39.241770119999998 at 26.437120350000001 39.241770119999998

I use traceback() but I can not actually understand it:
4: .Call("rgeos_intersection", .RGEOS_HANDLE, spgeom1, spgeom2,
       byid, ids, PACKAGE = "rgeos")
3: RGEOSBinTopoFunc(spgeom1, spgeom2, byid, id, drop_lower_td, unaryUnion_if_byid_false,
       "rgeos_intersection")
2: gIntersection(combinations[[i]][[1, m]], combinations[[i]][[2,
       m]]) at #17 . Can anyone explain what to look in ` traceback`?

Can anyone explain me what to look in traceback?
Thanks
Answer: It literally shows you the way the functions were called and where the error occurred. Check this example:
a <- function(x) {
  b <- function(y) {
    c <- function(z) {
     stop('there was a problem')
    }
    c()
  }
  b()
}

When I call a():
> a()

Error in c() : there was a problem
4. stop("there was a problem")
3. c()
2. b()
1. a()

In the above example you can see that a called b which called c and then in c the error occurred. It shows you the calling environments.
Comment: Yes exactly. It starts with 1 and reaches 4 where it breaks. It is hard to say which of your functions is wrong though. Maybe you have a logical error at 1, which causes the function at 4 to fail. Syntactically though your function works well until it breaks.
Comment: So, please correct me if I am wrong, it starts with the general function in 1. and then on the last call/number (in that case 4.) it shows me the error? It does not actually means that the entire function is wrong.
Comment: Thank you very much, now I understand the way it works and I will try to solve my problem. Thanks!

How to read a traceback in R


No such file or directory appcenter.podspec.json in CocoaPods/CocoaPods

Question: trying to install Microsoft Appcenter for react-native iOS. I got this error:

We couldn't find any issues matching 'No such file or directory @ rb_sysopen - /Users/userName/Documents/Repo/bookombo-app-new/ios/Pods/Local Podspecs/appcenter.podspec.json' in CocoaPods/CocoaPods' after running Pod install since Updating react-native to 0.60.

"appcenter": "2.4.0",
"react-native": "0.60.6",
Comment: I got this error today as well since I did `pod update`
Answer: I solved this by making appcenter-pre-build.sh
and
only adding these two lines
gem uninstall cocoapods
gem install cocoapods -v 1.7.5
Answer: Run the following cmds
<code>yarn remove appcenter appcenter-crashes
cd ios && pod install && cd ..
yarn add appcenter appcenter-crashes
cd ios && pod install && cd ..
</code>
Answer: Updating cocoapods to the latest version (in my case1.8) solved the problem for me :)


Global variable is returning null in android studio

Question: I'm retrieving Hospital Data from firestore. I want to keep retrieved data to be global for the entire fragment, but the Map will return null after coming out from addOnSuccessListner().
I've declared the Map inside onCreateView()
static  Map<String, Map<String, String>> hospitals ;
public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_home, container, false);
        hospitals = new HashMap<>();
        .......
        .....

        return root;
}

Below is the code where I'm retrieving HospitalData.
private void readHospitalData() {
    CollectionReference collectionReference = fStore.collection("hospital Details");
    collectionReference.get()
            .addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
                @Override
                public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
                    for(QueryDocumentSnapshot queryDocumentSnapshot: queryDocumentSnapshots){
                        Map<String, String> map = new HashMap<>();
                        map.put("h_name", queryDocumentSnapshot.getString("h_name"));
                        map.put("h_email", queryDocumentSnapshot.getString("h_email"));
                        map.put("h_phone", queryDocumentSnapshot.getString("h_phone"));
                        map.put("h_road", queryDocumentSnapshot.getString("h_road"));
                        map.put("h_area", queryDocumentSnapshot.getString("h_area"));
                        map.put("h_city", queryDocumentSnapshot.getString("h_city"));
                        map.put("h_state", queryDocumentSnapshot.getString("h_state"));
                        map.put("h_pincode", queryDocumentSnapshot.getString("h_pincode"));

                        hospitals.put(queryDocumentSnapshot.getId(), map);
                    }
                    Log.d("MAP-->" , hospitals.toString());  // display the Map
                }
            });
    Log.d("MAP-->" , hospitals.toString());  // but here it will display null

}

Comment: It should not be null unless you are calling `readHospitalData` before `onCreateView` . It will be empty `collectionReference.get()` is an asynchronous call so you need to put Logs inside `onSuccess` only .
Comment: You might also check **[this](https://stackoverflow.com/questions/48499310/how-to-return-a-documentsnapshot-as-a-result-of-a-method/48500679#48500679)** out.
Answer: Firebase API calls that deal with reading and writing data are fully asynchronous. This means that the call always returns immediately, without blocking the code to wait for a result. The results come sometime later, whenever they're ready.
That's why you are getting null here
CollectionReference collectionReference = fStore.collection("hospital Details");
    collectionReference.get()
            .addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
    public void onSuccess(DocumentSnapshot snapshot) {
        // handle the document snapshot here
    }
});
task.addOnFailureListener(new OnFailureListener() {
    public void onFailure(Exception e) {
        // handle any errors here
    }
});
    Log.d("MAP-->" , hospitals.toString());

REASON FOR THIS TYPE OF BEHAVIOUR OF FIREBASE CONSUMER API:
->why make the consumer of an API go through the extra trouble of using an asynchronous API? Can't we just have simpler synchronous APIs instead? Well, Firebase could provide synchronous APIs for mobile apps, but then we'd inherit one of two problems that are both even worse than writing this extra code.
1.Calling a synchronous function on your app's main thread could freeze the app indefinitely, which is a terrible user experience. On Android, it could also soft-crash with an Application Not Responding (ANR) dialog.

To avoid blocking the main thread with the asynchronous method, we'd have to manage our own threads to call these APIs properly. This is even more code, and can be difficult to get right. Even expert engineers have challenges with correct threading behaviour.

Think async!
Firebase APIs are sensitive to the performance of your app's main thread. This means that any Firebase API that needs to deal with data on disk or network is implemented in an asynchronous style. The functions will return immediately, so you can call them on the main thread without worrying about performance. All you have to do is implement callbacks using the patterns established in the documentation and samples.
There is one solution for this problem that you have to use Kotlin-Flow for the synchronous call, go through this link: https://developer.android.com/kotlin/flow#callback
Answer: I solved this issue by using Callback
I created HospitalData.class and retrieved the data from firebase there. And by using the Callback interface I read the data in the Fragment
HospitalData.class
    public class HospitalData {

        FirebaseFirestore fStore = FirebaseFirestore.getInstance();
        Map<String, Map<String, String>> hospitals = new HashMap<>();
        HospitalCallback hospitalCallback;

        HospitalData(){
            // empty constructor
        }

        public void setHospitalCallback(HospitalCallback hospitalCallback) {
            this.hospitalCallback = hospitalCallback;
        }

        void getHospitalData(){
            CollectionReference collectionReference = fStore.collection("hospital Details");
            collectionReference.get()
                    .addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
                        @Override
                        public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
                            for(QueryDocumentSnapshot queryDocumentSnapshot: queryDocumentSnapshots){
                                Map<String, String> map = new HashMap<>();
                                map.put("h_name", queryDocumentSnapshot.getString("h_name"));
                                map.put("h_email", queryDocumentSnapshot.getString("h_email"));
                                map.put("h_phone", queryDocumentSnapshot.getString("h_phone"));
                                map.put("h_road", queryDocumentSnapshot.getString("h_road"));
                                map.put("h_area", queryDocumentSnapshot.getString("h_area"));
                                map.put("h_city", queryDocumentSnapshot.getString("h_city"));
                                map.put("h_state", queryDocumentSnapshot.getString("h_state"));
                                map.put("h_pincode", queryDocumentSnapshot.getString("h_pincode"));

                                hospitals.put(queryDocumentSnapshot.getId(), map);

                            }
                            hospitalCallback.DisplayHospitalData(hospitals);
                        }
                    });
        }

        interface HospitalCallback{
            public void DisplayHospitalData(Map<String, Map<String, String>> map);
        }
}

In my HomeFragment.class
public class HomeFragment extends Fragment implements HospitalCallback{

    static  Map<String, Map<String, String>> hospitals ;
    HospitalData hospitalData;

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_home, container, false);
        hospitals = new HashMap<>();
        hospitalData = new HospitalData();
        hospitalData.getHospitalData();
        hospitalData.setHospitalCallback(this);

        return root;

    }

    @Override
    public void DisplayHospitalData(Map<String, Map<String, String>> map) {
         Log.d("HOSPITAL DATA-->", map.toString());
    }

}


Função para imprimir a quantidade de caracteres em uma string bidimensional

Question: Pelo enunciado do exercício, preciso obrigatoriamente usar como o segundo argumento char **strings, acredito que aí esteja minha confusão, em manipulá-la para contar o tamanho da string. (Fiz outros testes com o segundo argumento como char strings[][str_size] e tudo correu bem, mas como disse, preciso usar o argumento como sendo char **strings.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define str_size 127

void imprimeTamString(int numStrings, char **strings)
{
    int i, j;
    int tamanho;

    printf("\n---Tamanhos---\n\n");
    for(i=0; i<numStrings; i++)
    {
        tamanho=0;
        for(j=0; j<str_size; j++)
        {
            if(strings[i][j]!='\0')
                tamanho=tamanho+1;
            else
                break;
        }
        printf("String %d - Tamanho = %d\n", i+1, tamanho);
    }
}

int main()
{
    int n;//numero de strings//

    printf("Deseja entrar com quantas strings? ");
    scanf("%d", &n);

    char *str1, **str2;
    char string[n][str_size];
    int i;

    for(i=0; i<n; i++)
    {
        printf("String %d = ", i+1);
        fflush(stdin);
        gets(string[i]);
    }

    str1=string[0];
    str2=&str1;

    imprimeTamString(n, str2);

    return 0;
}

Comment: E existe alguma restrição para não usar o `strlen()`?
Comment: Não há, mas também não consegui fazer usando strlen()
Comment: Chame com: imprimeTamString(n, string); que você estará chamando a função com um ponteiro para um ponteiro de char.
Comment: @MarcoAntonioSchneider e tem que ser mesmo `char**`? Algum motivo para ser sim: Você não está interpretando isso desta forma mas poder ser de outra?
Answer: Você pode simplificar bem o código e evitar alguns erros. Além de não usar um função que é inadequada para leitura de dados. Mas o que está complicando é que está criando um array no stack e depois lendo como ponteiro de ponteiros. Se puder mudar para ler como array de strings funcionará:
#include <stdio.h>
#include <string.h>
#define STR_SIZE 127

void imprimeTamString(int numStrings, char (*strings)[STR_SIZE + 1]) {
    printf("\n---Tamanhos---\n");
    for (int i = 0; i < numStrings; i++) printf("String %d - Tamanho = %d\n", i + 1, (int)strlen(strings[i]));
}

int main() {
    int numStrings;
    printf("Deseja entrar com quantas strings? ");
    scanf("%d", &numStrings);
    scanf("%*c");
    char strings[numStrings][STR_SIZE + 1];
    for (int i = 0; i < numStrings; i++) {
        printf("String %d = ", i + 1);
        fgets(strings[i], STR_SIZE, stdin);
        strings[i][strcspn(strings[i], "\n")] = 0;
    }
    imprimeTamString(numStrings, strings);
}

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Se tiver que ser ponteiro de ponteiro mesmo pode fazer assim, mas aí terá que alocar as strings no heap:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define STR_SIZE 127

void imprimeTamString(int numStrings, char **strings) {
    printf("\n---Tamanhos---\n");
    for (int i = 0; i < numStrings; i++) printf("String %d - Tamanho = %d\n", i + 1, (int)strlen(strings[i]));
}

int main() {
    int numStrings;
    printf("Deseja entrar com quantas strings? ");
    scanf("%d", &numStrings);
    scanf("%*c");
    char *strings[numStrings];
    for (int i = 0; i < numStrings; i++) {
        printf("String %d = ", i + 1);
        strings[i] = malloc(STR_SIZE + 1);
        fgets(strings[i], STR_SIZE, stdin);
        strings[i][strcspn(strings[i], "\n")] = 0;
    }
    imprimeTamString(numStrings, strings);
}

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Answer: Saudações
A sua função de contagem de caractere está funcionando corretamente. O que está ocorrendo ai é que você não está alocando de forma adequada a matriz que irá armazenar a sua String.
Esse é um erro muito comum cometido por pessoas que costumam trabalhar com linguagens que o simples fato de declarar uma variável já implica em sua alocação de memória, em C não é assim que funciona.
O que você terá que fazer ANTES de começar a usar o sua matriz chamada string é INICIALIZAR cada elemento com o número adequado de bytes para armazenar as strings que serão digitadas.
O que você que fazer é algo assim:
char* string[n];
for(int i=0; i<n; i++) {
  string[i] = (char*) malloc(sizeof(char)*str_size);
}

A passagem do parâmetro para a função está correto. Você não precisa usar & quando é string uma vez que o nome da variável já aponta para o ponteiro onde tem o primeiro caractere da string!
Boa sorte com o seu exercício!
Comment: Muitíssimo obrigado, o problema estava mesmo na falta de alocação
Answer: Você precisa entender alguns conceitos básicos antes, os quais são:
O que é uma matriz?

Matriz é a uma estrutura de dados do tipo vetor com duas ou mais dimensões. Os itens de uma matriz tem que ser todos do mesmo tipo de dado. Na prática, as matrizes formam tabelas na memória.

Como fazer a Declaração de Matrizes?

Você possui algumas formas de declarar a matriz, as quais são:

1) char matriz[LINHA][COLUNA]
2) int **matriz

Onde o (1) seria a mesma coisa que o (2), porém o (1) você é obrigado a inicializa-las com os seus tamanhos(LINHA & COLUNA). Logo o (2) não tem necessidade e você pode utilizar o mesmo para fazer alocação dinâmica.

Outras formas de declaração de Matrizes:

Caso você não necessite de uma entrada (input) de dados para a inserção na matriz, isto é, você tenha os dados fixos e que sempre serão constantes, você pode fazer desta forma:

const char matriz[5][5] = { {'A', 'B', 'C', 'D', 'E'}, { 'F', 'G', 'H', 'I', 'J' } }

Como acessar os elementos da Matriz?

Você precisará de um algoritmo O(n²), ou seja, dois for aninhados, um para a LINHA e outro para a COLUNA, como por exemplo:

const char matriz[5][5] = { {'A', 'B', 'C', 'D', 'E'}, { 'F', 'G', 'H', 'I', 'J' } }

for(int linha = 0; linha < 5; linha++) {
    for(int coluna = 0; coluna < 5; coluna++) {
        //CÓDIGO
    }
}

Utilize a biblioteca <string> para verificar o tamanho da mesma, como por exemplo:
string str ("Testando String");
cout << "TAMANHO DA STRING: " << str.size() << " bytes.\n";

FONTE OFICIAL: CPLUSPLUS - STRING SIZE
FONTE OFICIAL: PUCRS - VETORES & MATRIZES


vuejs getting the value of a datepicker after selected

Question: in vue js i want to get the result of 2 date-picker and get the different days between them but problem is i want to do it before form is submitted i mean when the user select dates i want to count the days and give price according to it i use a persian date picker i add it below if it may help :
https://github.com/talkhabi/vue-persian-datetime-picker

and here is my html markup :

                    start reserve
                    <date-picker :auto-submit="true" v-model="date" :max="available_end.toString()"
                                 :min="reserve_end.toString()"></date-picker>

                    end reserve
                    <date-picker :auto-submit="true" v-model="date2" :max="available_end.toString()"
                                 :min="reserve_end.toString()"></date-picker>

and here is the vuejs part :
data(){
return {
date: '',
date2:'',
}
},
 components: {
        datePicker: VuePersianDatetimePicker
    },

the code contains much more so i cut it for better reading  and
i tried to use the date and date2 but they dont seem to work .
Comment: I guess, you can achieve it using computed properties. Please add the code what you tried to do so far.
Comment: i really have no idea how to get the i just tried this this.dateDiff = this.value      this.$emit('input', this.dateDiff)
Answer: You should be able to add a @change="onChange()" event to your date picker. Also because you have a v-model on each date picker the values of this.date and this.date2 should be up to date at all times. Then in the onChange function you should be able to access this.date and this.date2 and perform your date difference calculation in there.
If you add the same @change="onChange()" to both date pickers then the calculation of date differences will be performed when either of them change.
p.s make sure you are accessing your data with this.propertyname


Fazendo uma div reaparecer

Question: Na div amarela (id="conteudo") há a div rosa (id="conteudo-interno") e uma imagem.
O botão faz com que a div amarela seja limpa, porém gostaria que sumisse tudo, exceto a div rosa (conteudo-interno)
Tem como eu guardar essa div em algum lugar e depois só chama-la para ela aparecer novamente?

function limpaConteudo() {
  $('.conteudo').empty();
}
#conteudo{
    width:300px;
    height:300px;
    float:left;
    background-color:#ff1;
    display: initial;
    margin: auto;
    z-index: 6;
    overflow: hidden;
}

#conteudo-interno{
    width:100px;
    height:100px;
    background-color:#f1f;
    float:left;
    display: initial;
    margin: 50 50;
}

  <button onclick="limpaConteudo()"> Press Here </button>

 Hello World!

Comment: @sora o conteúdo da sua div rosa é dinâmico ? se for algumas solução com conteúdo pré definido não te atenderão
Comment: Poderia usar um $('#conteudo img').hide() para desaparecer e um $('#conteudo img').show()  para voltar. Se o objetivo for somente esconder.
Comment: Então, é que nesse exemplo seria só uma imagem, mas em um caso real poderia ser diversas imagens entende? Aí creio que o correto seria apagar
Comment: Então, para a resolução do problema @Caique eu usei os princípios da resposta do @Felipe, onde usei a `.html`:
  function limpaConteudo() {
   $('.conteudo').empty();
   $('.conteudo').html(' Hello World! ');
  }
Comment: Entendido, veja a minha resposta tentei demonstrar que é possível armazenar o conteúdo mesmo se ele variar, no comentário acima se você fizer uma alteração na divRosa(conteudo-interno) automaticamente você teria que editar a linha $('.conteudo').html(' Hello World! '); causando uma repetição desnecessária.
Answer:

$('#btn').on('click', function(){
  $('#conteudo img').hide()
})

$('#back').on('click', function(){
  $('#conteudo img').show()
})
#conteudo{
    width:300px;
    height:300px;
    float:left;
    background-color:#ff1;
    display: initial;
    margin: auto;
    z-index: 6;
    overflow: hidden;
}

#conteudo-interno{
    width:100px;
    height:100px;
    background-color:#f1f;
    float:left;
    display: initial;
    margin: 50 50;
}

  <button id="btn"> Press Here </button>
    <button id="back">Voltar</button>

 Hello World!

Seria mais ou menos isso?
AT. Para esconder varias imagens (ou ate mesmo conteudo, div e etc), basta voce ter a classe img, que pode ser nomeada com outro nome, por exemplo ocultar e definir essa classe em todos os conteudos que quer esconder com o click, dessa maneira, irá fazer um trabalho só
Comment: Perfeito, era só essa parte de manter a div rosa !!!
Muito obg, vou estudar este código agora
Comment: @Sora se a resposta resolve seu problema, marque como resolvido. Qualquer duvida estamos a disposição.
Comment: Certo, neste caso você apenas escondeu a imagem certo??
É que em um caso real eu poderia ter diversas imagens, creio que o correto seria limpa-las da div mesmo...
Para eu clicar em resolver tenho que esperar 15 minutos
Comment: @Sora na verdade não, se voce quiser mostra-las novamente, tera que recoloca-las, vou editar o codigo para ver o funcionamento com varias imagens
Comment: Ah sim, entendi !! vou usar esta parte de esconder e mostrar novamente
as imagens em outro módulo, já vou estudando ela, valeu pela ajuda Rafa !!
Comment: @Sora de nada, estamos sempre ai ;)
Answer: Para sumir tudo menos a div rosa você deve clonar a div rosa e recria-la fora do DOM do elemento ou tirar a div rosa do elemento conteúdo para que ela não seja apagada. Ou fazer algo assim
function limpaConteudo() {
  $('.conteudo').empty();
  $('.conteudo').html('
 Hello World!
');
}

Comment: rss legau , so nao esquece de pontuar minha resp ^^
Comment: Entendi, posso clona-la e recria-la chamando o clone... ou posso tira-la do elemento conteúdo, é isso??
Comment: Perfeito !! Obrigado @Felipe pela ajuda !
Comment: sim ou ainda vc limpa tudo e recoloca a info dentro do elemento usando o `html();`
Comment: posta como vc resolveu isto depois
Comment: Esse jeito que você colocou é perfeito, pois limpa todas as imagens e chama a div conteudo interno novamente, vou usar ela.
Pois das outras formas terei de estuda-las e esconder as imagens creio que não seria o correto, pois imagine em um caso onde tem várias imagens entende?
Answer: A solução abaixo é similar a do @Felipe Avezani com a diferença de que a divRosa é salva no momento em que é solicitado a limpeza do conteúdo, ou seja, capturo o valor dela naquele momento, permitindo a restauração de um conteúdo que varia.
Imagine que você teve que alterar o conteúdo da divRosa, da forma como está a resposta atual você teria que editar ela no html e no javascript causando retrabalho.
No exemplo abaixo eu coloquei um input na divRosa, note que se você limpar e restaurar o conteúdo depois o valor digitado será mantido.

var divRosa;
function limpaConteudo() {
  divRosa = $("#conteudo-interno"); //Salvo a div rosa
  $("#conteudo").empty();
}

function restauraDivRosa(){
  $("#conteudo").html(divRosa);
}
#conteudo{
    width:300px;
    height:300px;
    float:left;
    background-color:#ff1;
    display: initial;
    margin: auto;
    z-index: 6;
    overflow: hidden;
}

#conteudo-interno{
    width:100px;
    height:100px;
    background-color:#f1f;
    float:left;
    display: initial;
    margin: 50 50;
}

  <button onclick="limpaConteudo()"> Limpa </button>
    <button onclick="restauraDivRosa()"> Restaura </button>

 Hello World!
        <input type="text" name="teste" value="" />

Comment: Entendi !!, bem melhor mesmo, assim não preciso fazer a repetição do comando `.html`, valeu @Caique pela aula !!

Fazendo uma div reaparecer