Run-Time Check Failure #2 - stack around the variable 'osvi' was corrupted on mfc application

Question: I've been searching around the internet and I have no idea why this happens, it's not really an obvious array issue.
Here's the function:
BOOL IsOsCompatible()
{
    BOOL retVal = 0;
    OSVERSIONINFO osvi;
    ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX));
    osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
    GetVersionEx(&osvi);
    if(osvi.dwMajorVersion == 6)
    {
        if(osvi.dwMinorVersion == 0)
        {
            if(SendErrorM("This program has not been tested on Windows Vista(TM).\nAre you sure you want to use it?",MB_YESNO) == IDYES)
                retVal = 1;
        }
        else if(osvi.dwMinorVersion == 1)
        {
            retVal = 1;
        }
        else if(osvi.dwMinorVersion == 2)
        {
            if(SendErrorM("This program has not been tested on Windows 8(TM).\nAre you sure you want to use it?",MB_YESNO) == IDYES)
                retVal = 1;
        }
    }
    else
        SendErrorM("Your windows verison is incompatible with the minimum requirements of this application.",NULL);

    return retVal;

}

Any ideas?
Answer: An OSVERSIONINFOEX is larger than an OSVERSIONINFO, so
    ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX));

will write zeroes "outside" (around) osvi.
You want
OSVERSIONINFOEX osvi;
ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX));

or (often safer)
OSVERSIONINFOEX osvi;
ZeroMemory(&osvi, sizeof(osvi));

Comment: I couldn't agree more on this, the problem appeared when I tried to clean the code a little and changed `OSVERSIONINFOEX` into his smaller brother...
Answer: The extra X is your problem:
OSVERSIONINFO osvi;
ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX));

Windows A, W and X suck.
Avoiding Macros:
template <typename T>
inline void zero_memory(T& m) {
    std::memset(&T, 0, sizeof(T));
}

Comment: Yep, that was the issue indeed, I thought that they would match, but it seems that the EX one includes some more info resulting in a size mismatch, Thank you very much.


jQuery how to select an element from a element

Question: I want to select a table row from a special table.
HTML:

 ...

How do I select it? Maybe like this?
jQuery:
$("#player_table > tbody tr."+idOfPlayerRpwWhoWasClickedAtPlayersTable)

Comment: `.` selects a class, `#` selects an ID. `tr.` should be `tr#` but why not just `$("#"+idOfPlayerRpwWhoWasClickedAtPlayersTable)` ? IDs must be unique and preferrably not begin with a digit
Comment: @mplungjan: thanks for your help! THe problem is, I have this ID 2 times one time at my players Table and one time at the playerField section... i know this is not valid and not good! but how this 2 IDs has to give sometimes some data to each other...
Comment: Having repeated `id` is invalid HTML and a problem which you should really fix.
Comment: $("#player_table").find("#"+idOfPlayerRpwWhoWasClickedAtPlayersTable) you may use like it.
Answer: Id attribute must be unique for the elements in the page.
So you can reach the element like;
$('#'+idOfPlayerRpwWhoWasClickedAtPlayersTable);

Comment: i know but at the moment sometbody gave me the page and i have to fix these issues... and exactly in this moment its not possible to change the code to get only one time the ID unique...
Comment: So you have to start fixing the multiple ids


Security implications of mount --bind in a chroot environment

Question: Assume you have a chroot environment where you need a resource - an application or a library - which resides on the host (external to the chroot).
Which are the security implications (if any) of performing a mount --bind (from the host to the chroot) on that resource rather than installing it on the chroot - i.e. via an apt-get install -?
Answer: As I see it both a mount --bind of a directory and a hard link of a file share the same security problem: files in the chroot end up being the same (that is, pointing to the same inode) than files outside the chroot. So if the chroot user finds a way to modify these files inside the chroot they've essentially found a way to modify your files.
This may or may not be a serious security issue depending on the environment you're setting up, but you have to take it into account when making this choice.


Problem with this Galois Group

Question: Consider
$$K:=\Bbb{Q}(\{\root n\of2\mid n≥2\})⊆\Bbb{R},$$ find $Gal(K/\Bbb{Q})$.
So it would be at most $n!$ (infinite) number of $\Bbb{Q}$- automorphism over K. I should apply the simple extension theorem adding one by one element of $K$  but I know some of the roots get out of the precedesor field. So maybe I could use induction or maybe I can simplify K.
Thats exactly what happens with $Gal[\Bbb{Q}(2^{1/2},2^{1/4})/\Bbb{Q}]$ that is basically the same that $Gal[\Bbb{Q}(2^{1/4})/\Bbb{Q}]$ and this is basically because $\Bbb{Q}(2^{1/2},2^{1/4})=
\Bbb{Q}(2^{1/4})$ so I wish I can simplify $K$ like this too and I think the number of Q-automorphisms may be finite.
Thanks.
Comment: Hard to know what you're asking, 'cause your notation is pretty much unreadable. Sorry to be harsh, but you really need MathJax to get your ideas out.
Comment: @vitamind, please refrain from editing a question you don't understand. You may make matters worse, when you try to guess what was meant.
Comment: @wakasa Please check my edits and try and improve (and fix the residual errors). I think I'm good at guessing the intended meaning, but this was a bit challenging. And there are still unclear points. For example, the extension $K/\Bbb{Q}$ is not Galois because you don't adjoin all the roots of all the polynomials. You can still discuss the automorphism group of $K$, but because you later refer to all the zeros, it is rather unclear which field you are actually interested in.
Comment: @JyrkiLahtonen That's why I edited *nothing*. The only thing I did, was inserting dollar signs in math expressions. I was not removing nor adding *anything* mathematical.
Comment: @vitamind By adding dollar signs you made all the curly braces invisible, which was not what the OP intended. Also some parens (particular those around exponents) should have been replaced with curly braces.
Comment: @JyrkiLahtonen First of all I do understand the mathematical expressions the OP wanted to write. Also I admit that it's my mistake that I removed **two** curly braces. I think my edit was more of a help than harm. To end this: I'm sorry for removing two curly braces.
Comment: Guys thank you so much for your interest, sorry if I didn't express it correctly, I have improved it now. I'm asking for the group of Q-automorphisms over K that I think I was thought that was Gal(K/F)
Answer: It is still not clear to me what the field $K$ is supposed to be. But assuming that $K$ is the field gotten by adjoining all the real zeros of all the polynomials $x^n-2, n\ge2$, to $\Bbb{Q}$, then the conlusion is that

$K$ has no non-trivial $\Bbb{Q}$-automorphisms.

This is seen as follows. Let $\sigma$ be an automorphism of $K$. I claim that $\sigma(2^{1/n})=2^{1/n}$ for all $n\ge2$. Let's fix $n\ge2$. The polynomial $x^{2n}-2$ has two zeros in $K$, namely $\pm z_n$ with $z_n=2^{1/2n}$. We can thus deduce that $\sigma(z_n)=\pm z_n$. Therefore $\sigma(z_n^2)=z_n^2$, which is exactly the claim that
$$\sigma(\root n\of2)=\root n\of2.$$
Because $K=\Bbb{Q}(\{\root n\of2\mid n\ge2\}$), the claim follows.
Comment: Just wanted to get the ball rolling and a more definite reaction from the OP :-)
Comment: For the purposes of this question I adopted the convention that $Gal(K/\Bbb{Q})$ stands for the group of $\Bbb{Q}$-automorphisms of $K$. Some authors use the convention that this group should be denoted $Aut(K/\Bbb{Q})$ unless the extension is Galois. According to my reading of the question the OP uses the former convention also, but admittedly it is not clear.
Comment: Thank you so much for your effort. By that confusing notation I meant the positive real zeros of that set of polynomials, does the result changes or still the only Q-automorphism would be the identity?
Comment: @wakawa The other real zero is the negative of the positive zero, so that makes no difference to the field $K$.

Problem with this Galois Group


Finding the smallest max eigenvalues for related matrices?

Question: While messing around with a spectral approach to a graph coloring question, I happened upon a type of problem I hadn't seen before.
Suppose you have two symmetric $n$ x $n$ matrices in the form $$A= \begin{pmatrix}
&0&x_{1,1}&...&...&x_{1,(n-1)}\\
&x_{1,1}&0&x_{2,1}&\ddots&x_{2,(n-2)}\\
&\vdots &x_{2,1}&0&\ddots&\vdots\\
&\vdots &\ddots &\ddots&0&x_{(n-1),1}\\
&x_{1,(n-1)}&x_{2,(n-2)}&...&x_{(n-1),1}&0
\end{pmatrix}$$ and $$B=\begin{pmatrix}
&0&\left|x_{1,1}-1 \right|&...&...&\left|x_{1,(n-1)}-1 \right|\\
&\left|x_{1,1}-1 \right|&0&\left|x_{2,1}-1 \right|&\ddots&\left|x_{2,(n-2)}-1 \right|\\
&\vdots &\left|x_{2,1}-1 \right|&0&\ddots&\vdots \\
&\vdots &\ddots &\ddots&0&\left|x_{(n-1),1}-1 \right|\\
&\left|x_{1,(n-1)}-1 \right|&\left|x_{2,(n-2)}-1 \right|&...&\left|x_{(n-1),1}-1 \right|&0
\end{pmatrix}$$
with any $x_{i,j}=\begin{cases}
& 1\\
& 0
\end{cases}$, or, that is to say, $A+B$ is a matrix in the form $$A+B= \begin{pmatrix}
&0&1&...&...&1\\
&1&0&\ddots&\ddots&\vdots\\
&\vdots &\ddots &0&\ddots&\vdots\\
&\vdots &\ddots &\ddots&0&1\\
&1&...&...&1&0
\end{pmatrix}$$
Suppose that $\lambda_{1a}$ is the largest eigenvalue for matrix $A$ and $\lambda_{1b}$ the largest eigenvalue for matrix $B$.  How can I obtain the smallest possible $\lambda_{1a}$ and $\lambda_{1b}$ by manipulating the values of the entries in $A$ (which correspondingly change $B$)?
I know that for larger matrices, this will probably be impossible to analytically determine, but an approach for a numerical method has been difficult for me to come up with.  Considering that, if $A$ is empty, then $\lambda_{1b}$ will be its maximum value, it seems that the smallest largest eigenvalues for this system of matrices will be when $\lambda_{1a}\approx\lambda_{1b}$. What confuses me, though, is how to change the values in $A$ to most efficiently affect the desired changes in eigenvalues. Is there a name for this type of problem, or a best practice for approaching it numerically?
Thanks in advance for any info, input or ideas you can provide!
Comment: For a start it depends what you mean by "the smallest possible $\lambda_{1a}$ and $\lambda_{1b}$". Could you meand their sum? Their product?
Comment: Good question, sorry if that wasn't clear.  I mean that I want to simultaneously minimize the largest eigenvalue for both matrices, and since they are dependent on each other, that would imply that the difference between $\lambda_{1a}$ and $\lambda_{1b}$ is as close to zero as possible.
Answer: Suppose $\overline{G}$ is the complement of the graph $G$. Then
\[
  A(G)+A(\overline{G}) = J-I
\]
(where $J$ is the matrix with all entries equal to one). If $n=|V(G)|$, this implies that
\[
  \lambda(G)+\lambda(\overline{G}) \ge n-1.
\]
We get equality here if $G$ is a regular self-complementary graph. In particular if we take $G$ to be the Paley graph on $n$ vertices then
\[
  \lambda(G) = \lambda(\overline{G}) = (n-1)/2
\]
and your difference is zero. (Note that Paley graphs exist if and only if $n$ is a prime power congruent to 1 mod 4.)
Comment: Wonderful input, I hadn't thought about Paley graphs for some reason.  To clarify though, Paley graphs exist if and only if $n$ is a prime power congruent to 0 _or_ 1 mod 4, not just 1 mod 4.  I appreciate the response and your time!
Comment: No, you need $n$ congruent to 1 mod 4. This is also a necessary condition for a regular graph to be self-complementary.
Comment: Oh wow, my bad.  I must have gotten mixed up.  I should have spent more time checking my facts before posting that comment, my apologies Chris.


PowerShell New-GPLink is giving the errors on cross domains

Question: I am trying to write a PowerShell script to link my GPOs to several OUs on multiple domains. The issue I am having is with the New-GPLink cmdlet. When I run the command I get different errors. I can create and link GPOs in all domains in GPMC.
My domain is setup as a Forest with two domains under it (lets call them DomA and DomB). Then I have a third domain not under that forest (lets call it DomC).
My computer is in DomA and my account is in DomC.
The GPO is created in DomA and well call it GPO_Test_1.
The OU I want to link is at ou=Test,ou=GPO Testing,dc=DomA
If I run:
New-GPLink -Name "GPO_Test_1" -Target "ou=Test,ou=GPO Testing,dc=DomA" -LinkEnabled Yes

I get this error:
New-GPLink : The "GPO_Test_1" GPO was not found in the DomC domain.
Parameter name: gpoDisplayName
At line:1 char:1
+ New-GPLink -Name "GPO_Test_1" -Target "ou=Test,ou=GPO Testin ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (Microsoft.GroupPolicy.GPDomain:GPDomain) [New-GPLink], ArgumentExceptio
   n
    + FullyQualifiedErrorId : GpoWithNameNotFound,Microsoft.GroupPolicy.Commands.NewGPLinkCommand

So I can see its looking at the domain that my account is on. Not the one that my computer is on.
I tried different parameters resulting in different errors.
-Domain DomA
New-GPLink : A referral was returned from the server. (Exception from HRESULT: 0x8007202B)

-Server DConDomA
New-GPLink : Value does not fall within the expected range.

-Domain DomA -Server DConDomA
New-GPLink : Value does not fall within the expected range.

I read that this may be because my credentials are not passing correctly to the other domain. So I tried the below:
Invoke-Command -ComputerName DConDomA -scriptblock {New-GPLink -Name "GPO_Test_1" -Target "ou=Test,ou=GPO Testing,dc=DomA" -LinkEnabled Yes} -credential $c

The "GPO_Test_1" GPO was not found in the DomC domain.

Again the error referencing domain my account is on ...
Adding the -Server DConDomA inside the script block still gives this error.
New-GPLink : Value does not fall within the expected range.

Tried a few different DCs (including RIDMatser on DomA and DomC) but those results in the same type of errors.
I am not sure what I am missing or doing wrong here.
Answer: I found my own answer in is Microsoft documentation. Seems I just missed it. My Domain parameter has to be the FQDN where as I using the short name.
https://learn.microsoft.com/en-us/powershell/module/grouppolicy/new-gplink?view=windowsserver2022-ps
-Domain
Specifies the domain for this cmdlet. You must specify the fully qualified domain name (FQDN) of the domain.
This note explained why it was checking the domain where my account was as well.
"If you do not specify the Domain parameter, the domain of the user that is running the current session is used. If the cmdlet is being run from a computer startup or shutdown script, the domain of the computer is used. For more information, see the Notes section in the full Help."


Significant difference between two variables given a third

Question: Assume I have a number of subjects dividing into three profiles: 1, 2 and 3. For each subject I have recorded two attributes, age and height. First, I want to determine if there is a significant age-difference between the profiles. This can be done using a simple ANOVA test.
Now I want to determine if there is a significant age-difference between the profiles, given the height (as a covariate). How do I make this statistical test?
Answer: Assuming you are working in R:
<code>> require(car)
> fit <- Anova(lm(age ~ profile + height), type=3)
> summary(fit)
</code>
Don't forget to check that your data meets the assumptions for the tests you are using.
Comment: Should I check some additional assumptions here compared to just doing aov(age ~ profile) for the simple case?
Comment: Assumptions: http://en.wikipedia.org/wiki/Analysis_of_covariance#Assumptions_of_ANCOVA  Also, `Anova` in the `car` package allows marginal sums of squares whereas `aov` and `anova` default to sequential.


Delayed output to the very end of the output stream in PHP

Question: Say you have a big PHP web application doing echoing, output buffering, etc, all over the place. The end result is a finished HTML/XML document to the browser.
Now say you find yourself in a small function in a random place in a big PHP web application. Is there a simple way to output something, for example an HTML comment, in a way so that it is sent as the last thing to the browser?
Something like a hook for "when everything is finished send this piece of info as well to the browser"?

The end goal is basically to output some warnings or debug info in an easy way, without messing up the output.
Comment: http://php.net/manual/en/function.register-shutdown-function.php
Comment: Sometimes this site is like a slower version of google :)
Comment: Write your own hook that is executed at the end of the execution that displays store stuff and call that.
Comment: Woot!  Forgot that one @MarcB.
Comment: @MarcB That is indeed right. Thought for some reason that just had to do with crashing! Add it as an answer and I'll accept it :)
Answer: There's register_shutdown_function(), which would essentially be the very last thing executed by PHP before terminating your script.


A place to store file ( Ruby on Rails )

Question: I'm new to Rails, I wanted to make a website for uploading files: music, videos, pictures, text. What is a better way to store files? I've read about different methods: Database, as a file, Amazon S3?
There will be a lot of files around 1 kb to 20Mb each.
Thanks!
Answer: I don't think there is a right answer for that. I use heroku, so my only option is Amazon S3 (which has free quotas for the first year) and I'm pretty satisfied with it. I use carrierwave gem for uploading files and it's really easy to use. I really prefer it over Paperclip.
If your hosting provides a lot of space and bandwidth then you could give it a try.
But for the database, I really don't like the idea of storing files in it.
Updated
Reading a filename from the table should be faster than reading the file itself. The bigger the DB, the longer it will take to make a backup. And if you take heroku for example, you only get 20gb for a shared db. That's not much if you're gonna store 10-20mb files in there. Moving project to another hoster might be easier if you store files in the DB. But if you use an external service (such as S3), there would be no difference for you.
Comment: Thanks, I will try this gem. Why is database bad?
Answer: Storing files in a database is not bad, per se. It depends on the kind of database.
Storing files in a relational database is not view as a good practice by the reasons explained by bassneck.
But there are other kind databases that are specifically designed to store any kind of data, in a non-relational way, for example files of any kind. The answer of Dhruva highlight that, MongoDB is pretty good and its support for storing files using GridFS is awesome.
GridFS is very good, for example it can stream only parts of a file, pretty useful for video.
In your specific case – many small files of many kinds of data – GridFS is an real option. I use Heroku & mongohq.com and they work like a charm.
Answer: Amazon S3 integration on Heroku is relatively easy to setup and get working with the paperclip gem. Heroku has some documentation on how to get this up and running.
Take a look at their documentation and see if this is the kind of thing your looking for.
http://devcenter.heroku.com/articles/s3
Comment: I've enjoyed heroku. This is wonderful. But I've not heard about this integration. Thank you.
Answer: I will suggest you to also check out & consider MongoDB GridFS - http://www.mongodb.org/display/DOCS/GridFS+Specification. My experience with GridFS has been good. I cannot give you a comparative analysis with the other options, however I would like to know the same.
Answer: I would recommend you use amazon s3 to store your files. It is the best.

A place to store file ( Ruby on Rails )


Is there an efficient approach to setting distorted guitar EQ when mixing?

Question: Recently I've been running into brick walls with mixing distorted rhythm guitars. It seems that whatever I do the tone is either indistinct/muddy, fizzy, wimpy or over-processed.
Approaches tried (and failed):

Mixing in mono - I generally swear by this technique and it works well enough - for other instruments,
Sweep-and-cut - good for finding nasty resonant noise, but I find myself in a situation where applying a narrow notch gets rid of the resonance but makes the entire tone sound squashed, flat and generally over-processed, while getting rid of it means I'm suddenly hearing the resonant dirt twice as loud as before,
Dialing back the distortion - I'm aware that too much distortion washes out over all frequencies and kills the articulation of both the guitars and everything else, but cleaning up leads to a wimpy sound - not at all what I'm after,
Reamping - instead of getting one displeasing tone, I seem to end up with tens to choose from, none of which sound better than what I started with. To clarify, I am recording a completely unprocessed signal for this purpose.

Note: I am EQing in the mix at all times.
I suspect the fact that I'm playing in C# slack tuning is an issue - but an unavoidable one, given the material.
"Have a great tone coming in and do minimal EQ" is not really an answer, because if I did, I wouldn't be asking this question. Right now, the best I can do is sorta-kinda get what I want, hoping to chisel it into something that works in the mix.
I'm not looking for a canned solution along the lines of "this curve is quaranteed to work", because I know they don't exist. Rather, I would like to know whether there's a better way than trial-and-(mostly) error.
Comment: It isn't entirely clear if your "reamping" bullet point implies that in all cases listed you are recording dry signal and then applying distortion. If that is the case, then when you mention ducking EQ etc, is this before or after (both?) distortion? Also, do you have access to a piezo setup where the soundbox resonance will not be so prominent?
Comment: Afaik your second to last paragraph is the way of the world. Get it close during recording or you're going to be carving for hours and still not be happy. Note that you can't EQ in isolation. The EQ should serve the **mix**, not the guitar sound. The bigger the mix, the worse the different tracks usually sound when soloed.
Comment: @Yorik Edited to clarify. Soundbox resonance isn't the issue, because it's a solid body.
Comment: @ToddWilcox Oh, I am EQing in the mix (added note to that effect). As for getting a good sound when recording: doesn't that simply push the matter back a step? I'm already reamping, so in practice I am dialing the tone while mixing. An approach to setting up such a good sound would be an answer - given that amp/effect setup and mic placement *is* EQ, in a way. Otherwise, I'm stuck with "if you have a good sound that works in the mix you won't have to adjust it any more". I know that. It isn't very helpful.
Comment: Perhaps if you can post a sample of the whole mix we could give specific advice. Since each mix is different, how could anyone possibly know what your mix needs on any instrument? In terms of getting a good sound going in, that takes years of experience and practice, IME. An approach might be, decide the order of importance of each instrument, make the most important one big and tall, and make each less important one progressively smaller. Usually only a couple tracks can have a lot of low end. The more other tracks the less low end they can have.
Comment: @ToddWilcox I see what you're getting at, but what I'm after isn't so much a fix of the current mix (which is of limited benefit to anyone but me, right now), but rather a method - if one exists - to approach getting a good guitar sound, by whatever means. The currently posted answer is a good example of what I'm looking for - it addresses the specifics (tuning), highlights possible problems and offers guidelines on how to approach solving them. I don't know if it's the best answer this community can provide, yet, but it at least follows the basic pattern I'd expect from an expert answer.
Comment: Don't go for a good guitar sound. Go for a good mix sound. If you have to make the guitars sound terrible to make the mix sound good, then do it. I do that all the time. In fact I make my guitar sound less than great coming out of the amp so it meshes better with the bass during band practice.
Comment: This is something I wrote up about making a good mix that might be helpful: https://music.stackexchange.com/questions/30826/how-can-i-get-the-vocals-to-stand-out-better-in-the-mix-when-recording/30836#30836
Comment: @ToddWilcox Thanks for bringing that up. It's good general mixing advice (upvoted it).
Answer: C♯ slacktuning will be a contributor to the problem: for rhythm guitar rather than lead guitar, distortion can only be applied quite moderately or the chords get muddied out.  Instead of an actual distortion pedal, one rather tends to use the right pickups (close to bridge) in order to get "hard" harmonics to start with and then puts in a modestly amount of distortion via the amp.
Slack tuning cuts down considerably on the harmonic content particularly of the attack.  Maybe EQ a larger amount of high frequencies back in before applying distortion?  Or even split off high frequencies and amplify/distort only them?  Or try other schemes of band-specific distortion (which muddies the chord relations less than global distortion)?
Comment: +1 This does reflect my experiences to date and the pre-distortion EQ/crossover distortion techniques look very interesting.


Showing a solution to this differential equation is never zero

Question: Say I want to find a differentiable function $f: \mathbb{R} \rightarrow \mathbb{R}$ such that for some $k \neq 0$, $f' = kf$. Every time I have seen a book solve this, the expression is rewritten  as $$\frac{1}{f}f' = k$$ and then solved using u-substitution. To be technical though, must one first know that $f$ is never zero? If so, how could I go about showing that $f$ is never zero? I know that $f$ must be infinitely differentiable and if for some $a \in \mathbb{R}$, $f(a) = 0$, then for each $n \in \mathbb{N}_0$, $f^{(n)}(a) = 0$. I think I remember from complex analysis, if $f$ is holomorphic with this property, then $f$ is zero everywhere, but I'm not sure about the usual case of $\mathbb{R} \rightarrow \mathbb{R}$.
Comment: $(e^{-kx}f(x))'=0$ so $e^{-kx}f$ is a constant.
Comment: Wow that is really slick, thank you
Comment: You can prove that $f$ is non-zero everywhere provided it is non-zero at some point. Assume $f(a) \neq 0$ and consider $g(x) =f(a+x) f(a-x) $ and show that $g$ is constant and equals $f(a) f(a) >0$.
Answer: More generally, for an ODE of the form $f'=g(f)$, any zero $f^*$ of the function $g$ gives a constant solution $f(x)=f^*$. And if $g$ is nice enough so that one has uniqueness of solutions (say that $g$ satisfies a Lipschitz condition, so that the Picard–Lindelöf theorem applies), then any other solution can never be equal to $f^*$ at any point $x=x_0$, since that would mean that you would have (at least) two solutions to the initial value problem $f'=g(f)$, $f(x_0)=f^*$.
So when using separation of variables, you should always first note "by hand" the constant solutions $f(x)=f^*$, and only then proceed to find all the other solutions (which are never equal to any $f^*$, so that it's safe to divide by $g(f)$) from $\int \frac{df}{g(f)}= \int dx$.
Comment: This is nice. That was what I thought.
Answer: In addition to the many useful answers I may add this localization trick. Suppose $f(x_0)\neq 0$ at a particular $x_0$. By continuity of $f$ this is the case for all $x$ in an interval containing $x_0$. So, it is safe to divide by $f$ there. Then you proceed to find the solution. Only then does it turn out that the solution you've found is actually valid on the whole real line and that it is never zero!
BTW: You are completely right in being cautious about $f(a)=f'(a)=f''(a)=\cdots=0$ not implying $f=0$. This is because $f$ need not be equal to its Taylor series around $a$ for any value other than at $a$. If we knew $f$ was analytic this would have been the case.
Answer: $$\frac{df}{dx}=kf(x)$$
Obviously a trivial solution is $$f(x)=0.$$
So we cannot say that $f$ is never equal to $0$.
Then we solve the ODE in the cases of $f\neq 0$. Note that is not the same as assuming that $f$ is never equal to $0$.
No need to repeat here the classical solving leading to
$$f(x)=C\:e^{kx}$$
with $\quad C\neq 0\quad$ in order to respect the case $f\neq 0$ considered.
This solution is completed with the trivial solution $f=0$ which is consistent with $C=0$. This leads to the general soltion :
$$f(x)=C\:e^{kx}\quad\text{any}\quad C.$$


How can I check if someone already clicked on an area in pygame

Question: So i want to be able to know whether or not someone has clicked on a certain part of a pygame screen previously. Is this possible? If so, how do you do it?
ex.
area = pg.Rect(38, 34, 126, 132)
if #user has clicked within 'area' previously:
    print("You already clicked here")
else:
    #do whatever

sorry if this looks a little weird, This is my first time asking a question here
Answer: You can use pygames collidepoint to check if a point is in the rect
area = pg.Rect(38, 34, 126, 132)
mouse_x, mouse_y = pg.mouse.get_pos()
clicked_before = False

if click:
    if area.collidepoint(mouse_x,mouse_y):
        if clicked_before:
            print("you already clicked here before")
        else:
            clicked_before = True
            #do whatever

you can then do this for a list of areas
areas = [pg.Rect(38, 34, 126, 132)...]
clicked_before = [False...]

for i, area in enumerate(areas): #enumerate gets the object and its position
    if area.collidepoint(mouse_x,mouse_y):
            if clicked_before[i]:
                print("you already clicked here before")
            else:
                clicked_before[i] = True
                #do whatever


Android phone not listed by adb devices

Question: My USB-connected Android phone (a Redmi Note 4, not that it matters) is not being displayed by adb devices. I'm aware of this question on the subject. But in my case the odd thing is that the device is visible in Chrome devtools, and I can "Inspect" webviews. Obviously, I've set USB debugging on on the device. All my Windows USB drivers are installed properly. I've done adb kill-server && adb start-server. I've put the device into MTP/PTP USB mode. I've tried any number of combinations of cables and ports and sequences of plugging in and unplugging and turning USB debugging on and off again. The device is visible under "Portable Devices" in Device Manager.
Things were working fine up until a few days ago. I can think of nothing obvious that changed in the meantime.
After first posting this question, things started working again by accident--I cannot remember the sequence of things I did. Then just recently, the problem reared its ugly head again.
What could account for this state of affairs?
Comment: close all instances of `chrome` then do `adb kill-server` and then try `adb devices` again
Comment: Were you able to see it before, and it's just not working now? Or is it the case where you were never able to see it? Also, are you able to see it in your Windows devices list? In my experience, the device shows up as a flash drive
Comment: Sometimes you get prompted to allow a device debugging connection certificate on your phone. Has this maybe expired/cleared?
Comment: @AlexP Thanks, but that didn't help. Are you saying there may be some kind of interaction between Chrome and adb?
Comment: @Doomsknight Yes, that prompt comes up whenever I connect after revoking the permissions, so I am quite sure the PC and the device are talking at least that much, and that the permissions are in place.
Comment: Thanks @AlexP., that did the trick for me.
Answer: In Your case, the simple and tested solution for Xiaomi Phones.
Go to developer options, scroll down to bottom and turn of MIUI Optimization. It would then visible in your android studio.
Answer: Did you tried to add VendorID for your device ?
        for that please do the following:
        Run below on terminal to find your VENDOR ID;
            lsusb
    Find your phones vendor id (it will be probably without any company names) and type,

        sudo gedit ~/.android/adb_usb.ini

    and your adb_usb.ini file should look like:

    # ANDROID 3RD PARTY USB VENDOR ID LIST -- DO NOT EDIT.
    # USE 'android update adb' TO GENERATE.
    # 1 USB VENDOR ID PER LINE.
    # ie 0x2207
    0x<Add Your Vendor ID here>

    Disconnected and reconnected device and also needed to run below commands on terminal;

        sudo adb kill-server && adb start-server

Android phone not listed by adb devices


Understanding scipy Kolmogorov-Smirnov test

Question: I'm trying to understand the Kolmogorov-Smirnov test using a very simple example. I generate a set of random, uniform values between 0 and 1.0. I then test that these values are from a uniform distribution by using the scipy kstest function. I'm expecing a very small D value and a pvalue close to 1.0, but instead I get wildly varying pvalues every time I run the code. What am I missing?
<code>import numpy as np
import scipy
a = np.random.uniform(size=4999)
print(scipy.stats.kstest(a, 'uniform'))
</code>
Here are the outputs of a few consecutive runs:
<code>(0.0075523161200627964, 0.93798952050647577)
(0.013787195268362473, 0.29799260741344774)
(0.014359046616557847, 0.25402403230845855)
(0.012521820948675988, 0.41329007558099806)
(0.011159003477582918, 0.56216895575676396)
</code>
Comment: You are getting what you should. Look at this [CrossValidated thread](http://stats.stackexchange.com/questions/10613/why-are-p-values-uniformly-distributed-under-the-null-hypothesis)
Comment: You say widely varying p-values but are they all non-significant?
Answer: For the KS test the p-value is itself distributed uniformly in [0,1] if the H0 is true (which it is if you test whether it your sample is from $U(0,1)$ and the random number generation works okay). It therefore must "vary wildly" between 0 and 1, in fact its standard deviation is $1/\sqrt{12}$ which is roughly 0.3.
You can check this by looking whether the percentages of p values smaller or equal to some $p_0$ over your independent consecutive runs is close to said $p_0$.
See also Why are p-values uniformly distributed under the null hypothesis?
Comment: @ahmed No, in what I wrote, there is no significance to the value of $p_0$ at all. The percentages of p values smaller or equal to some $p_0$ should be close to $p_0$ regardless of the concrete $p_0$. That said, for very small $p_0$ one can encounter numeric problems when calculating the p-values.
Comment: Is there any advantage of choosing small $p_0$, like 1e-3 vs 0.5?


Is there a .NET namespace where I can find the WIN32 API message-related #defines, like WM_COMMAND, etc

Question: I'm overriding WndProc, so I want to write code like
if (m.Msg == WM_COMMAND)
    my special stuff
else
    base.WndProc(ref m)

Answer: AFAIK .NET does not ship with these constants. This site has all the values so is a matter of copy paste.
private const UInt32 WM_ACTIVATE           = 0x0006;
private const UInt32 WM_ACTIVATEAPP        = 0x001C;
private const UInt32 WM_AFXFIRST           = 0x0360;
private const UInt32 WM_AFXLAST        = 0x037F;
private const UInt32 WM_APP            = 0x8000;
private const UInt32 WM_ASKCBFORMATNAME    = 0x030C;
private const UInt32 WM_CANCELJOURNAL      = 0x004B;
private const UInt32 WM_CANCELMODE         = 0x001F;
private const UInt32 WM_CAPTURECHANGED     = 0x0215;
private const UInt32 WM_CHANGECBCHAIN      = 0x030D;
private const UInt32 WM_CHANGEUISTATE      = 0x0127;
private const UInt32 WM_CHAR           = 0x0102;
private const UInt32 WM_CHARTOITEM         = 0x002F;
private const UInt32 WM_CHILDACTIVATE      = 0x0022;
private const UInt32 WM_CLEAR          = 0x0303;
private const UInt32 WM_CLOSE          = 0x0010;
private const UInt32 WM_COMMAND        = 0x0111;
private const UInt32 WM_COMPACTING         = 0x0041;
private const UInt32 WM_COMPAREITEM        = 0x0039;
private const UInt32 WM_CONTEXTMENU        = 0x007B;
private const UInt32 WM_COPY           = 0x0301;
private const UInt32 WM_COPYDATA           = 0x004A;
private const UInt32 WM_CREATE         = 0x0001;
private const UInt32 WM_CTLCOLORBTN        = 0x0135;
private const UInt32 WM_CTLCOLORDLG        = 0x0136;
private const UInt32 WM_CTLCOLOREDIT       = 0x0133;
private const UInt32 WM_CTLCOLORLISTBOX    = 0x0134;
private const UInt32 WM_CTLCOLORMSGBOX     = 0x0132;
private const UInt32 WM_CTLCOLORSCROLLBAR      = 0x0137;
private const UInt32 WM_CTLCOLORSTATIC     = 0x0138;
private const UInt32 WM_CUT            = 0x0300;
private const UInt32 WM_DEADCHAR           = 0x0103;
private const UInt32 WM_DELETEITEM         = 0x002D;
private const UInt32 WM_DESTROY        = 0x0002;
private const UInt32 WM_DESTROYCLIPBOARD       = 0x0307;
private const UInt32 WM_DEVICECHANGE       = 0x0219;
private const UInt32 WM_DEVMODECHANGE      = 0x001B;
private const UInt32 WM_DISPLAYCHANGE      = 0x007E;
private const UInt32 WM_DRAWCLIPBOARD      = 0x0308;
private const UInt32 WM_DRAWITEM           = 0x002B;
private const UInt32 WM_DROPFILES          = 0x0233;
private const UInt32 WM_ENABLE         = 0x000A;
private const UInt32 WM_ENDSESSION         = 0x0016;
private const UInt32 WM_ENTERIDLE          = 0x0121;
private const UInt32 WM_ENTERMENULOOP      = 0x0211;
private const UInt32 WM_ENTERSIZEMOVE      = 0x0231;
private const UInt32 WM_ERASEBKGND         = 0x0014;
private const UInt32 WM_EXITMENULOOP       = 0x0212;
private const UInt32 WM_EXITSIZEMOVE       = 0x0232;
private const UInt32 WM_FONTCHANGE         = 0x001D;
private const UInt32 WM_GETDLGCODE         = 0x0087;
private const UInt32 WM_GETFONT        = 0x0031;
private const UInt32 WM_GETHOTKEY          = 0x0033;
private const UInt32 WM_GETICON        = 0x007F;
private const UInt32 WM_GETMINMAXINFO      = 0x0024;
private const UInt32 WM_GETOBJECT          = 0x003D;
private const UInt32 WM_GETTEXT        = 0x000D;
private const UInt32 WM_GETTEXTLENGTH      = 0x000E;
private const UInt32 WM_HANDHELDFIRST      = 0x0358;
private const UInt32 WM_HANDHELDLAST       = 0x035F;
private const UInt32 WM_HELP           = 0x0053;
private const UInt32 WM_HOTKEY         = 0x0312;
private const UInt32 WM_HSCROLL        = 0x0114;
private const UInt32 WM_HSCROLLCLIPBOARD       = 0x030E;
private const UInt32 WM_ICONERASEBKGND     = 0x0027;
private const UInt32 WM_IME_CHAR           = 0x0286;
private const UInt32 WM_IME_COMPOSITION    = 0x010F;
private const UInt32 WM_IME_COMPOSITIONFULL    = 0x0284;
private const UInt32 WM_IME_CONTROL        = 0x0283;
private const UInt32 WM_IME_ENDCOMPOSITION     = 0x010E;
private const UInt32 WM_IME_KEYDOWN        = 0x0290;
private const UInt32 WM_IME_KEYLAST        = 0x010F;
private const UInt32 WM_IME_KEYUP          = 0x0291;
private const UInt32 WM_IME_NOTIFY         = 0x0282;
private const UInt32 WM_IME_REQUEST        = 0x0288;
private const UInt32 WM_IME_SELECT         = 0x0285;
private const UInt32 WM_IME_SETCONTEXT     = 0x0281;
private const UInt32 WM_IME_STARTCOMPOSITION   = 0x010D;
private const UInt32 WM_INITDIALOG         = 0x0110;
private const UInt32 WM_INITMENU           = 0x0116;
private const UInt32 WM_INITMENUPOPUP      = 0x0117;
private const UInt32 WM_INPUTLANGCHANGE    = 0x0051;
private const UInt32 WM_INPUTLANGCHANGEREQUEST = 0x0050;
private const UInt32 WM_KEYDOWN        = 0x0100;
private const UInt32 WM_KEYFIRST           = 0x0100;
private const UInt32 WM_KEYLAST        = 0x0108;
private const UInt32 WM_KEYUP          = 0x0101;
private const UInt32 WM_KILLFOCUS          = 0x0008;
private const UInt32 WM_LBUTTONDBLCLK      = 0x0203;
private const UInt32 WM_LBUTTONDOWN        = 0x0201;
private const UInt32 WM_LBUTTONUP          = 0x0202;
private const UInt32 WM_MBUTTONDBLCLK      = 0x0209;
private const UInt32 WM_MBUTTONDOWN        = 0x0207;
private const UInt32 WM_MBUTTONUP          = 0x0208;
private const UInt32 WM_MDIACTIVATE        = 0x0222;
private const UInt32 WM_MDICASCADE         = 0x0227;
private const UInt32 WM_MDICREATE          = 0x0220;
private const UInt32 WM_MDIDESTROY         = 0x0221;
private const UInt32 WM_MDIGETACTIVE       = 0x0229;
private const UInt32 WM_MDIICONARRANGE     = 0x0228;
private const UInt32 WM_MDIMAXIMIZE        = 0x0225;
private const UInt32 WM_MDINEXT        = 0x0224;
private const UInt32 WM_MDIREFRESHMENU     = 0x0234;
private const UInt32 WM_MDIRESTORE         = 0x0223;
private const UInt32 WM_MDISETMENU         = 0x0230;
private const UInt32 WM_MDITILE        = 0x0226;
private const UInt32 WM_MEASUREITEM        = 0x002C;
private const UInt32 WM_MENUCHAR           = 0x0120;
private const UInt32 WM_MENUCOMMAND        = 0x0126;
private const UInt32 WM_MENUDRAG           = 0x0123;
private const UInt32 WM_MENUGETOBJECT      = 0x0124;
private const UInt32 WM_MENURBUTTONUP      = 0x0122;
private const UInt32 WM_MENUSELECT         = 0x011F;
private const UInt32 WM_MOUSEACTIVATE      = 0x0021;
private const UInt32 WM_MOUSEFIRST         = 0x0200;
private const UInt32 WM_MOUSEHOVER         = 0x02A1;
private const UInt32 WM_MOUSELAST          = 0x020D;
private const UInt32 WM_MOUSELEAVE         = 0x02A3;
private const UInt32 WM_MOUSEMOVE          = 0x0200;
private const UInt32 WM_MOUSEWHEEL         = 0x020A;
private const UInt32 WM_MOUSEHWHEEL        = 0x020E;
private const UInt32 WM_MOVE           = 0x0003;
private const UInt32 WM_MOVING         = 0x0216;
private const UInt32 WM_NCACTIVATE         = 0x0086;
private const UInt32 WM_NCCALCSIZE         = 0x0083;
private const UInt32 WM_NCCREATE           = 0x0081;
private const UInt32 WM_NCDESTROY          = 0x0082;
private const UInt32 WM_NCHITTEST          = 0x0084;
private const UInt32 WM_NCLBUTTONDBLCLK    = 0x00A3;
private const UInt32 WM_NCLBUTTONDOWN      = 0x00A1;
private const UInt32 WM_NCLBUTTONUP        = 0x00A2;
private const UInt32 WM_NCMBUTTONDBLCLK    = 0x00A9;
private const UInt32 WM_NCMBUTTONDOWN      = 0x00A7;
private const UInt32 WM_NCMBUTTONUP        = 0x00A8;
private const UInt32 WM_NCMOUSEMOVE        = 0x00A0;
private const UInt32 WM_NCPAINT        = 0x0085;
private const UInt32 WM_NCRBUTTONDBLCLK    = 0x00A6;
private const UInt32 WM_NCRBUTTONDOWN      = 0x00A4;
private const UInt32 WM_NCRBUTTONUP        = 0x00A5;
private const UInt32 WM_NEXTDLGCTL         = 0x0028;
private const UInt32 WM_NEXTMENU           = 0x0213;
private const UInt32 WM_NOTIFY         = 0x004E;
private const UInt32 WM_NOTIFYFORMAT       = 0x0055;
private const UInt32 WM_NULL           = 0x0000;
private const UInt32 WM_PAINT          = 0x000F;
private const UInt32 WM_PAINTCLIPBOARD     = 0x0309;
private const UInt32 WM_PAINTICON          = 0x0026;
private const UInt32 WM_PALETTECHANGED     = 0x0311;
private const UInt32 WM_PALETTEISCHANGING      = 0x0310;
private const UInt32 WM_PARENTNOTIFY       = 0x0210;
private const UInt32 WM_PASTE          = 0x0302;
private const UInt32 WM_PENWINFIRST        = 0x0380;
private const UInt32 WM_PENWINLAST         = 0x038F;
private const UInt32 WM_POWER          = 0x0048;
private const UInt32 WM_POWERBROADCAST     = 0x0218;
private const UInt32 WM_PRINT          = 0x0317;
private const UInt32 WM_PRINTCLIENT        = 0x0318;
private const UInt32 WM_QUERYDRAGICON      = 0x0037;
private const UInt32 WM_QUERYENDSESSION    = 0x0011;
private const UInt32 WM_QUERYNEWPALETTE    = 0x030F;
private const UInt32 WM_QUERYOPEN          = 0x0013;
private const UInt32 WM_QUEUESYNC          = 0x0023;
private const UInt32 WM_QUIT           = 0x0012;
private const UInt32 WM_RBUTTONDBLCLK      = 0x0206;
private const UInt32 WM_RBUTTONDOWN        = 0x0204;
private const UInt32 WM_RBUTTONUP          = 0x0205;
private const UInt32 WM_RENDERALLFORMATS       = 0x0306;
private const UInt32 WM_RENDERFORMAT       = 0x0305;
private const UInt32 WM_SETCURSOR          = 0x0020;
private const UInt32 WM_SETFOCUS           = 0x0007;
private const UInt32 WM_SETFONT        = 0x0030;
private const UInt32 WM_SETHOTKEY          = 0x0032;
private const UInt32 WM_SETICON        = 0x0080;
private const UInt32 WM_SETREDRAW          = 0x000B;
private const UInt32 WM_SETTEXT        = 0x000C;
private const UInt32 WM_SETTINGCHANGE      = 0x001A;
private const UInt32 WM_SHOWWINDOW         = 0x0018;
private const UInt32 WM_SIZE           = 0x0005;
private const UInt32 WM_SIZECLIPBOARD      = 0x030B;
private const UInt32 WM_SIZING         = 0x0214;
private const UInt32 WM_SPOOLERSTATUS      = 0x002A;
private const UInt32 WM_STYLECHANGED       = 0x007D;
private const UInt32 WM_STYLECHANGING      = 0x007C;
private const UInt32 WM_SYNCPAINT          = 0x0088;
private const UInt32 WM_SYSCHAR        = 0x0106;
private const UInt32 WM_SYSCOLORCHANGE     = 0x0015;
private const UInt32 WM_SYSCOMMAND         = 0x0112;
private const UInt32 WM_SYSDEADCHAR        = 0x0107;
private const UInt32 WM_SYSKEYDOWN         = 0x0104;
private const UInt32 WM_SYSKEYUP           = 0x0105;
private const UInt32 WM_TCARD          = 0x0052;
private const UInt32 WM_TIMECHANGE         = 0x001E;
private const UInt32 WM_TIMER          = 0x0113;
private const UInt32 WM_UNDO           = 0x0304;
private const UInt32 WM_UNINITMENUPOPUP    = 0x0125;
private const UInt32 WM_USER           = 0x0400;
private const UInt32 WM_USERCHANGED        = 0x0054;
private const UInt32 WM_VKEYTOITEM         = 0x002E;
private const UInt32 WM_VSCROLL        = 0x0115;
private const UInt32 WM_VSCROLLCLIPBOARD       = 0x030A;
private const UInt32 WM_WINDOWPOSCHANGED       = 0x0047;
private const UInt32 WM_WINDOWPOSCHANGING      = 0x0046;
private const UInt32 WM_WININICHANGE       = 0x001A;
private const UInt32 WM_XBUTTONDBLCLK      = 0x020D;
private const UInt32 WM_XBUTTONDOWN        = 0x020B;
private const UInt32 WM_XBUTTONUP          = 0x020C;


Terminology of "Regression forest", "Random forest", "Decision tree" and "Regresion tree"

Question: I am confused about the terminology of "regression forest", "random forest regression", "random forest", "decision tree" and "regression tree".
As far as I understood, random forest is a general term that can be used for both binary and continuous outcome variables.
For example, in this paper the term "random forest" is used for the prediction of a continuous variable: https://link.springer.com/article/10.1007/s11136-020-02667-3
However, there are also the terms "regression forest" and "random forest regression", which are, as I understand, more specific terms for random forests that are applied to a continuous outcome variable. For example, in the grf Package, Athey et al. call the function that predicts a continuous outcome a "regression forest". https://projecteuclid.org/journals/annals-of-statistics/volume-47/issue-2/Generalized-random-forests/10.1214/18-AOS1709.full
I suppose that the same logic holds for decision trees and regression trees (i.e. decision trees being a more general term and regression trees being a subset of decision trees).
So,
random forest = general term for an ensemble method that combines multiple decision trees
regression forest = general term for an ensemble method that combines multiple regression trees
Is this correct?
Answer: Yes, you are correct.
Random Forest is more generic and involves regression as well as classification tasks. (It can also be applied to other work like survival analysis or ranking) Regression forest is a shorter way of saying "random forests for regression", Breiman himself does use that term in his 2001 original paper on "Random Forests" so it is, by definition, correct.
The earliest use of the term "regression forest" outside Breiman's work seems to be in "Using protein expressions to predict survival in clear cell renal carcinoma" (2004) by Kim et al.


Equivalence Relations (Discrete Math)

Question: Hello I'm having trouble with this math problem on equivalence relations.
Let X be any subset of the set of positive integers Z. Define a relation ~ on X as follows:
I have reflexive proven, having trouble with transitivity and symmetric.
Comment: The question is useless if you remove the definition of the relation.
Answer: $\textbf{Symmetric-  }$If $a/b=2^k$ then $b/a=2^{-k}$
$\textbf{Transitive-}$ If $a/b=2^{k_1}$ and $b/c=2^{k_2}$ then $a/c=(a/b)(b/c)=2^{k_1+k_2}$
Comment: If you are satisfied, please don't forget to upvote and accept.. Thanks
Answer: Symmetric if: $\frac{a}{b}=2^n$ then what does $\frac{b}{a}$ equall?
Transitive: Start by saying what you know
$$ \frac{a}{b}=2^n$$
and
$$ \frac{b}{c}=2^k$$
What can you say about $\frac{a}{c}$?

Equivalence Relations (Discrete Math)


Hibernate - Como buscar todas as linhas de uma tabela com o Hibernate?

Question: Não estou conseguindo buscar todas as linhas de uma tabela com o Hibernate. Alguém sabe o nome do método que faz isto?
Comment: Olá Gabriel! Você teria algum código para nos mostrar? Sua dúvida não ficou clara, pois há diferentes maneiras de fazer isto: Criteria, JPQL ou consulta nativa. Se estiver usando algum framework (como o Spring), aparecem mais opções.
Answer: Supondo uma entidade chamada Pessoa, que está corretamente mapeada no seu sistema, e uma variável session em que você já iniciou uma sessão do Hibernate, você quer algo assim para recuperar todos os registros:
Query query = session.createQuery("from Pessoa");
List<Pessoa> list = query.list();

O Hibernate faz uso da linguagem HQL para consultas (é uma das opções, há outras). Saiba mais a respeito dando uma olhada na documentação.
Answer: Você pode fazer isso:
public <T> List<T> listarTodos(Class<T> tipo) {
    return em.createQuery("FROM " + tipo.getSimpleName(), tipo).getResultList();
}

Você usaria isso assim:
List<Pessoa> todasAsPessoas = listarTodos(Pessoa.class);
List<Empresa> todasAsEmpresas = listarTodos(Empresa.class);

Observe que o método é genérico. A lista que ele retorna tem o mesmo tipo do Class que você passa como parâmetro.
O em aqui é o EntityManager. Se você necessitar de algo mais complexo para obter uma instância do EntityManager, vai ter que adaptar esse código.
Observe que é usado o método createQuery(String, Class<?>) que devolve um TypedQuery<T> e tem dois parâmetros. Isso é preferível do que usar o método similar createQuery(String) que retorna uma Query sem tipo e só tem um parâmetro, pois nesse caso o getResultList() forneceria uma List bruta sem o tipo genérico.
Só tome cuidado para não usar isso em uma tabela com milhões de registros e consumir a memória toda construindo a lista de resultados, lembre-se que isso daí vai virar um SELECT sem WHERE e nem paginação. Algo parecido também acontece se a entidade buscada tiver um monte de relacionamentos que estejam marcados com @ManyToOne, @OneToOne e/ou fetchType = FetchType.EAGER que acabem praticamente provocando o carregamento do banco de dados inteiro na memória.
Answer: o código que faz isso se chama hql, resumindo seria um sql do Hibernate, sua sintaxe seria essa:
 Query q = em.createQuery("FROM Item_Pedido As a WHERE a.id_pedido = :para1");

No caso de uma lista para uma dataTable você faria assim, ja com passagem de parametros.
public List<Item_Pedido> listaItemPorPedido(Long id) {
      String aux = String.valueOf(id);
    Query q = em.createQuery("FROM Item_Pedido As a WHERE a.id_pedido = :para1");
    q.setParameter("para1", aux);
    return q.getResultList();
}

Espero ter ajudado.
Answer: Eu recomendo explicitar o SELECT ao invés de começar a consulta apenas com FROM:
String jpql = "SELECT pessoa FROM Pessoa pessoa";
Query query = em.createQuery(jpql);
List<Pessoa> pessoas = em.getResultList();

Também pode fazer isto usando query nativa:
String jpql = "SELECT pessoa.id, pessoa.nome FROM Pessoa pessoa";
Query query = em.createNativeQuery(jpql);
List<Object[]> pessoas = em.getResultList();

Por que não usar apenas o FROM, sem SELECT?
Não recomendo fazer a consulta começando pela claúsula FROM, como esta abaixo:
String jpql = "FROM Pessoa";
Query query = em.createQuery(jpql);
List<Pessoa> pessoas = em.getResultList();

O motivo? Se você resolver fazer um JOIN entre duas tabelas desta maneira, algo bem comum nas versões antigas do Hibernate quando as entidades não eram relacionadas:
String jpql = "FROM Pessoa pessoa, FROM Cliente cliente WHERE pessoa.cpf = cliente.cpf";

O Hibernate não vai retornar uma Pessoa, mas um array de objetos: Object[]. Na primeira posição terá a Pessoa e na segunda terá o Cliente. Isto pode acontecer quando você usa JOIN FETCH, por isto não recomendo omitir o SELECT.
Portanto, desde então, recomendo fazer consultas explicitando o SELECT.


What statistical significance test should I use in this situation with two variables?

Question: I have two variables: Wind speed (MPH) and passing yards in the NFL. I want to test if wind speed has a statistically significant effect on a player's passing yards.
I used independent t-test from scipy (this function) and got a p-value of 2.308298987276122e-84, which seems too low? I tested the function on some random variables that should have no connection (like 'year' and 'week of season') and got a p-value of 0, so am I misunderstanding the t-test or something?
Comment: It's not clear what you did - you might want to post your code.
Answer: That test is to see if the means of two samples are different from each other.  So what you really tested is if the average wind speed is different from the average number of passing yards.
If you want to see the effect of windspeed on passing yards, what I would suggest is building a linear regression model, where wind speed is the independent variable, and passing yards is the dependent variable (there are a bunch of good tutorials on how to do linear regression in python).  Then you can test if the wind speed coefficient is different from 0 using a t-test.  If it is, you can conclude that it's likely that wind speed has an effect on passing yards.
You can do this using linear regression from statsmodel in python.  Then you can print an output (using model.summary()) that looks like the following:

The coefficients are in the green, blue, and purple boxes.  The results of a t-test for significance of each coefficient is already done for you.  So where the blue box is, you'll see 'Wind speed'.  Then move across that row to the column 'P>|t|'.  If that value is less than 0.05, it's likely that wind speed has an effect on passing yards.  For reference, in the image posted, we would conclude that both Interest_Rate and Unemployment_Rate have an effect on the Stock_Index_Price, since we see 0.005 for P>|t| for Interest_Rate, and 0.046 for P >|t| for Umeployment_Rate, both of which are smaller than 0.05.
You should keep in mind that there might be lurking and/or confounding variables though.  There might be some other variables that are actually causing the changes in passing yards that you haven't accounted for.  Ideally, you'd fit a large model, with lots of variables (wind speed being one of them), and then see if wind speed is significant in estimating passing yards, or if passing yards is explained by other variables.
But if you're trying to keep it simple (and I'm not sure how much data you have either), I would start with a simple linear regression model with just passing yards and wind speed.
Comment: Thanks! Can you just elaborate on this part: "Then you can test if the wind speed coefficient is different from 0 using a t-test." I understand everything else other than this
Comment: Just updated my response to have some details on how to do the t-test (really it's already done for you - you just need to know how to interpret it, if you use statsmodel)


Python 2.7: L += branch_length results in NameError: name 'L' not defined

Question: It's a populations genetics program handed out by my professors and modified by the students.
Basically it's supposed to simulate the expected number of mutations twenty times with a given sample, population, and mutation rate (u). However, a critical piece is the total branch length (L), which is the sum of the various smaller branch lengths (branch_length). However, when I define L as below, it keeps coming back with the error:
  L += branch_length
NameError: name 'L' is not defined

I'm not sure what's wrong, since tree_depth is defined the same way and works flawlessly.
Here's the full code:
from random import expovariate
from pgen import poidev
K = 77       # sample size (number of gene copies)
twoN = 5000  # population size
u = .001

tree_depth = 0.0 # age of last common ancestor in generations

# Each pass through loop deals with one coalescent interval.

for A in range(20):
    while K > 1:
        h = K*(K-1)/(2.0*twoN) # hazard of a coalescent event
        t = expovariate(h)       # time until next coalescent event
        tree_depth += t
        branch_length = t*K
        K -= 1
        L += branch_length
    S = poidev(u*L)
    print "Simulation:", A+1, "Total Mutations:", S
print "Total tree depth (L):", L, "generations"

Am I just missing something really, really obvious? Thanks in advance.
Answer: L += x adds x to the existing L, but you haven't initialized L.  Presumably, you want L = 0 somewhere at the top of your file.
Comment: Working like a charm. I knew it was something simple.

Thank you!
Answer: You need to define L = 0 before doing L += x.
In general, before modifying you need to define the variable. For assignment, there is no problem because python will infer the type for you.
Some examples:
>>> a += 0 #Invalid
Traceback (most recent call last):
  File "<input>", line 1, in <module>
NameError: name 'a' is not defined
>>> a = 5 #Valid
>>> a += 0 #Now it's valid, because a is defined.
>>>
>>> my_list.append(5) #Invalid
Traceback (most recent call last):
  File "<input>", line 1, in <module>
NameError: name 'my_list' is not defined
>>> my_list = []
>>> my_list.append(5) #Now valid
>>> my_list
[5]
>>>
>>> my_list2 = [1, 2, 3, 4] #Valid, because it's an assignment.


Field index for queries not updating when value set programmatically

Question: My module creates a custom content item through the controller:
   private ContentItem createContentItem()
    {
        // Add the field
        _contentDefinitionManager.AlterPartDefinition(
            "TestType",
            cfg => cfg
            .WithField(
                "NewField",
                f => f
                    .OfType(typeof(BooleanField).Name)
                    .WithDisplayName("New Field"))
            );

        // Not sure if this is needed
        _contentDefinitionManager.AlterTypeDefinition(
            "TestType",
            cfg => cfg
                .WithPart("TestType")
            );

        // Create new TestType item
        var newItem = _contentManager.New("TestType");
        _contentManager.Create(TestItem, VersionOptions.Published);

        // Set the added boolean field to true
        BooleanField newField = ((dynamic)newItem).TestType.NewField as BooleanField;
        newField.Value = true;

        // Set title (as date created, for convenience)
        var time = DateTime.Now.ToString("MM-dd-yyyy h:mm:ss tt", CultureInfo.InvariantCulture).Replace(':', '.');
        newItem.As<TitlePart>().Title = time;

        return newItem;
    }

The end result of this is a new TestType item with a field that's set to true. Viewing the content item in the dashboard as well as examining ContentItemVersionRecord in the database confirms that the value was set correctly.
However, queries don't seem to work properly on fields that are set in this manner. I found the record IntegerFieldIndexRecord, which is what I assume projections use to fill query result pages. On this, the value of TestField remains at 0 (false), instead of 1 (true).
Going to the content item edit page and simply clicking 'save' updates IntegerFieldIndexRecord correctly, meaning that the value is now picked up by the query. How can the record be updated for field values set programmatically?
Relevant section of migration:
SchemaBuilder.CreateTable(typeof(TestTypePartRecord).Name, table => table
            .ContentPartRecord()
        );

        ContentDefinitionManager.AlterTypeDefinition(
            "TestType",
            cfg => cfg
                .DisplayedAs("Test Type")
                .WithPart(typeof(TitlePart).Name)
                .WithPart(typeof(ContainablePart).Name)
                .WithPart(typeof(CommonPart).Name)
                .WithPart(typeof(IdentityPart).Name)
            );

Edit: The fix for this is to manually change the projection index record whenever changing a field value, using this call:
_fieldIndexService.Set(testResultItem.As<FieldIndexPart>(),
     "TestType", // Resolves as TestTypePart, which holds the field
     "newField",
     "", // Not sure why value name should be empty, but whatever
     true, // The value to be set goes here
     typeof(bool));

Comment: Did you try to `_contentManager.Publish(TestItem)`?
Comment: The answers below fixed the problem. Looks like FieldIndexPart's handler isn't automatically changing the record when the field's value changes. Publishing should trigger it, but it doesn't.
Answer: In some cases a simple contentManager.Publish() won't do.
I've had a similar problem some time ago and actually implemented a simple helper service to tackle this problem; here's an excerpt:
public T GetStringFieldValues<T>(ContentPart contentPart, string fieldName)
{
    var fieldIndexPart = contentPart.ContentItem.As<FieldIndexPart>();
    var partName = contentPart.PartDefinition.Name;

    return this.fieldIndexService.Get<T>(fieldIndexPart, partName, fieldName, string.Empty);
}

private void SetStringFieldValue(ContentPart contentPart, string fieldName, IEnumerable<int> ids)
{
    var fieldIndexPart = contentPart.ContentItem.As<FieldIndexPart>();
    var partName = contentPart.PartDefinition.Name;
    var encodedValues = "{" + string.Join("},{", ids) + "}";
    this.fieldIndexService.Set(fieldIndexPart, partName, fieldName, string.Empty, encodedValues, typeof(string));
}

I've actually built this for use with MediaLibrary- and ContentPicker fields (they encode their value as string internally), so it might not be suitable for the boolean field in your example.
But it can't be that hard to implement, just look at the existing drivers and handlers for those fields.
Answer: There are 2 ways to fix this:
1) Ensure the newly created item is getting published by calling ContentManager.Publish() as Orchard.Projections.Handlers.FieldIndexPartHandler listens to the publish event to update the FieldIndexPartRecord
2) use IFieldIndexService to update FieldIndexPartRecord manually, see implementation of Orchard.Projections.Handlers.FieldIndexPartHandler to get in idea how to do this
Hope this helps.
:edit
Due to calling Create(...Published) the ContentManager.Published() won't do anything as the item is already considered published.
You can do the following to force the publish logic to run:
bool itemPublished = newItem.VersionRecord.Published;

// unpublish item first when it is already published as ContentManager.Publish() internally first checks for published flag and when set it aborts silently
//  -> this behaviour prevents calling publish listeners
if (itemPublished)
  _contentManager.Unpublish(newItem);

// the following call will result in calls to IContentHandler.Publishing() / IContentHandler.Published()
_contentManager.Publish(newItem);

or just create the item as a draft and publish it when everything is setup correctly.
Comment: I can confirm that publish wasn't the issue, but manually calling IFieldIndexService.Set every time I alter a field value does fix the issue with queries. I've added the exact call I make (which looks very similar to what Xceno posted) to the original post.
Comment: @ub3rman123 I think the publish call doesnt do anything for you because you are creating the item as published version already. There is a sanity check in the content manager which causes the method to do nothing when the item is already published. See my edited answer on how to solve this issue.


Probability the winners are split equally among certain underclassmen and upper classmen?

Question: At a certain university, 20% of all students are freshmen, 18% are sophomores, 21% are juniors, and 41% are seniors. As part of a promotion, the university bookstore is running a raffle for which all students are eligible. Ten students will be randomly selected to receive prizes (in the form of textbooks for the term).

What is the probability the winners consists of 2 freshmen, 2 sophomores, 2 juniors, and 4 seniors? I know this is 0.0305
What is the probability the winners are split equally among underclassmen (freshmen and sophomores) and upperclassmen (juniors and seniors)?
The raffle resulted in no freshmen being selected. This would be $1-.20^2$ right?
Comment: Not getting your formula.  Assuming that the class is large enough so that extracting a few students doesn't change the probabilities significantly, then the probability that any given student is a non-freshman is $1-.2=.8$ so the probability that the $10$ are all non-freshmen is $.8^{10}$.
Answer: I'm going to assume your part (a) is correct.
For part (b): Note that the probability of an upperclassman winning is $21\%+41\%=62\%,$ which also makes the probability of an underclassman winning $38\%.$ As a result, the probability of 5 upperclassmen and 5 underclassmen winning (an even split) is $\binom{10}{5}(0.62)^5(0.38)^5\approx\boxed{0.1829}.$
For (c): The easiest way to compute this is to actually determine the probability that one of the winners isn't a freshman $(100\%-20\%=80\%),$ and then raise this probability to the tenth power for each of the $10$ winners - this gives a probability of $(0.80)^{10}\approx\boxed{0.1074}.$


How to validate ids between XML documents in XSD?

Question: I'm trying to make a cross platform string management system, for both iOS and Android app (so I don't have to translate both app and I reuse string from one app into the other).
For this, I use the following flow :

XML storing cross platform string identifiers (with potentially attributes like comment or iOS-only, ...)

<identifiers>
   <id>button_signin_facebook</id>
   <id ios-only="true">button_signin_apple</id>
   ...
</identifiers>

And then I have N translations for the N supported languages :

<translation lang="en">
  <string id="button_signin_facebook">Continue with Facebook</string>
  <string id="button_signin_apple">Continue with Apple ID</string>
  ...
</translation>

A PHP script processes all of this and generate all translation files for both platform, after verifying integrity (see if some string are unused, see if we have created a string twice etc.)
Now my question is :
How to make a XSD for the translation_lang.xml files enforcing that the id attribute of string elements is a "enumeration" (or "reference" ?) from all the id in the identifiers.xml file ? (just like a foreign key in a database)
I'm new to XSD, and I found that I could make enumeration in XSD, but it's not what I want. (The identifiers values needs to be in the XML file identifiers.xml and not in a schema, because they are not fixed.)
Answer: XSD cannot express constraints between separate XML documents.
Alternative possibilities:

Write the cross-document validation constraints in XSLT, PHP, or another language.
Combine the separate XML documents into a single composite XML document for purposes of validating via XSD.
Comment: Thanks for your answer. Actually I verify all of this with PHP before the generation of platform string files, but XSD validation is really helpful for IDE auto completion. If I use solution 2, how can I express the foreign key within the single file ?
Comment: Once the identifiers and references are in a single file,  you can use `xsd:key` and `xsd:keyref` to validate such referential integrity constraints.  For example, see [Allow only other existing XML values in XSD? (xs:key and xs:keyref)](https://stackoverflow.com/q/51537997/290085).
Comment: Thank you I'll check it out :)
Comment: Another possibility for cross-document validation is to use XSD 1.1 assertions. Technically, the XPath assertions used in a schema can't reference external documents using the doc() function, but you may find that not all processors impose this restriction.


How to create applet that controls stop lights?

Question: I am working on a Java applet that will have three buttons:

Go
Stop
Slow

The buttons will control a stoplight which in turn controls a car. At this point I am unable to get the stop light to change colors while keeping the switch statement mandated by the class. Here is my code so far:
import java.awt.*;
import java.applet.*;
import javax.swing.*;
import java.awt.event.*;

public class lights extends JApplet implements ActionListener {

    JButton stop, go, slow;
    AudioClip ac;
    JPanel buttong;
    int x = 0;

    public void init() {
    }

    public void actionPerformed(ActionEvent ae) {
        Object obj = ae.getSource();

        if (obj == go) {
            x = 1;
        }

        if (obj == stop) {
            x = 2;
        } else if (obj == slow) {
            x = 3;
        }
    }

    public void paint(Graphics g) {
        super.paint(g);
        stoplight(g, 50, 50);
        buttons();

        switch (x) {
            case 1:
                g.setColor(Color.green);
                g.fillOval(50, 50, 10, 10);

                ac = getAudioClip(getDocumentBase(), "Hot rod start.wav");
                ac.play();
                break;
            case 2:
                x = 2;
                g.setColor(Color.red);

                g.fillOval(50, 70, 10, 10);
                break;
            case 3:
                g.setColor(Color.yellow);

                g.fillOval(x, 60, 10, 10);
                break;
        }
    }

    public void stoplight(Graphics grph, int x, int y) {
        Polygon box;
        box = new Polygon();
        box.addPoint(x, y);
        box.addPoint(x + 10, y);
        box.addPoint(x + 10, y + 30);
        box.addPoint(x, y + 30);
        grph.drawPolygon(box);
        grph.drawOval(x, y, 10, 10);
        grph.drawOval(x, y + 10, 10, 10);
        grph.drawOval(x, y + 20, 10, 10);
        Polygon pole;
        pole = new Polygon();
        pole.addPoint(x + 3, y + 30);
        pole.addPoint(x + 3, y + 70);
        pole.addPoint(x + 7, y + 70);
        pole.addPoint(x + 7, y + 30);
        grph.drawPolygon(pole);
    }

    public void buttons() {

        buttong = new JPanel(new FlowLayout());
        stop = new JButton("Stop");

        go = new JButton("Go");

        slow = new JButton("Slow");
        go.addActionListener(this);
        stop.addActionListener(this);
        slow.addActionListener(this);

        buttong.add(go);
        buttong.add(stop);
        buttong.add(slow);
        add(buttong);
    }
}

Comment: Why code an applet?  If it is due to spec by your instructor, please refer them to [Why CS teachers should **stop** teaching Java applets](http://programmers.blogoverflow.com/2013/05/why-cs-teachers-should-stop-teaching-java-applets/).
Comment: `ac = getAudioClip(getDocumentBase(),"Hot rod start.wav" ); ac.play();` We should never try to load resources in a `paint()` method!  Better to move `ac = getAudioClip(getDocumentBase(),"Hot rod start.wav" );` into the `init()` method.
Comment: DON'T add components (or actually modify the state of the component) within the `paint` method!!  Components should be added in the `init` method!
Answer: Problem #1
You are, repeatedly, adding your buttons whenever paint is called.  paint may be called for any number of reasons, may of which you don't control. Never modify the state of any UI component in the paint method.
Instead, call buttons in the init method.
Problem #2
You are not telling the UI to update itself when you change the state of the lights.  In your actionPerformed method, add repaint(); as the last statement, this will schedule a repaint of your component and paint will (eventually) be called
Better solution
Start by moving your custom painting to the paintComponent method of a JPanel.  This will allow you to isolate the painting and add the additional benefit of double buffering (stop the flickering updates)
Have a look at Performing Custom Painting for more details
Add your buttons to the BorderLayout.NORTH position of the applet and your lights panel to the BorderLayout.CENTER, this will prevent the buttons from interacting with your lights panel (overlapping it).
add(buttong, BorderLayout.NORTH);
add(lightsPane);

This will require you to supply methods to control the lights panel from the applet, but it will make your life much easier in the long run
Comment: I see what your saying as far as not calling the buttons method in the paint method but when I try to put it in the init my applet does not initialize. I will check out the oracle tutorial. Also I have to use flowlayout for the buttons as a requirement for the project.
Comment: The buttons are on a separate `JPanel`, which uses `FlowLayout` by default, I'm talking about putting the panel in the north position of the applet, which is using a `BorderLayout` by default
Comment: I got the the lights to work but thats after I deleted the audio file. My question now is how do i make the audio file play when go is pressed and also I need to have a car image that moves on go and stops on slow and stop.
Comment: The audio should be controlled from the `actionPerformed` method, so would state of the car.  For the car's animation, you would probably need a `javax.swing.Timer`
Comment: When I draw the image in the paint method, my applet no longer initializes. My audio wont play under in the actionpeformed method (the same code as was in it before just under the if(obj==go) section).
Comment: *"When I draw the image in the paint method, my applet no longer initializes"* makes no sense, as the `init` and `start` methods are called before the `paint` method.  Where are you loading the image?  The audio failing to play will have more to do with the inability for the applet to find the audio file then just about anything else.
Comment: I added the image in the paint method and solely after that addition my applet says failed to initialize at the bottom of its screen. I apologize for being hard to understand this is my first graphical project and also my first post on a coding forum. Also do I put the timer in the actionPerformed method where the go if statement is?
Comment: It's likely that the image failed to load and/or is `null`
Comment: Does this HAVE to be an applet.  This is going to cause you so many problems
Comment: Yes i have to upload it to a website as an applet
Comment: java.lang.NullPointerException
 at java.applet.Applet.getCodeBase(Applet.java:169)
 at lights.(lights.java:11)
 plus more
Comment: Are you running the applet in a browser or the applet viewer?
Comment: on ecipse so I think the applet viewer
Comment: In your `init` method add `System.out.println(getDocumentBase());` and see what it prints to the console
Comment: I get the same stuff in the console. Should I remove stuff so I'm back to a working applet and retry?
Comment: i get file:/home/charles/workspace/nevermind/bin/lights1406092171869.html
Comment: Okay, so I assume that your images and audio need to be stored in `/home/charles/workspace/nevermind/bin`
Comment: Sorry to say that they are there and it is still a null pointer
Comment: `BufferedImage img = ImageIO.read(new URL(getDocumentBase(), "image name"));` works just fine for more...
Comment: When I try that I get errors under bufferedimage imageio and URL do I need to import anything
Comment: You should be important `java.awt.image.BufferedImage` and `javax.imageio.ImageIO`.  `ImageIO.read` will also throw a `IOException`, which you need to catch and handle
Comment: Ok do I import java.net. URL for the URL and could you direct me to a tutorial for this type of error handling
Comment: [Reading/Loading an Image](http://docs.oracle.com/javase/tutorial/2d/images/loadimage.html)
Comment: I declared the buffered image under the class and put the try catch part in the init method


dns lookup at different dns servers

Question: when I perform a dig lookup to look for dns record for a domain name, server A gives a non empty dns record, but server B gives nothing. why? is there a more consistent approach?

server A

# dig cubagob.cu

; > DiG 9.8.2rc1-RedHat-9.8.2-0.30.rc1.el6_6.1 > cubagob.cu
;; global options: +cmd
;; Got answer:

;; flags: qr rd ra; QUERY: 1, ANSWER: 0, AUTHORITY: 0, ADDITIONAL: 0

;; QUESTION SECTION:
;cubagob.cu.            IN  A

;; Query time: 266 msec
;; SERVER: 126.96.36.199#53(220.127.116.11)
;; WHEN: Mon Feb 16 17:18:11 2015
;; MSG SIZE  rcvd: 28

server B

dig cubagob.cu

; > DiG 9.8.2rc1-RedHat-9.8.2-0.30.rc1.el6_6.1 > cubagob.cu
;; global options: +cmd
;; Got answer:

;; flags: qr rd ra; QUERY: 1, ANSWER: 0, AUTHORITY: 1, ADDITIONAL: 0

;; QUESTION SECTION:
;cubagob.cu.            IN  A

;; AUTHORITY SECTION:
cu.         2037    IN  SOA ns.ceniai.net.cu. cu-tech.ceniai.inf.cu. 2015021600 3600 1800 604800 3600

;; Query time: 161 msec
;; SERVER: 184.108.40.206#53(184.108.40.206)
;; WHEN: Mon Feb 16 17:18:29 2015
;; MSG SIZE  rcvd: 97
Comment: Is there any particular reason why you omitted the line containing `->>HEADER<<-`? Status codes are usually very pertinent when it comes to asking DNS questions.
Answer: Those are both empty responses with zero answers. (literally, both say ANSWER: 0) The only difference is whether those servers are providing you the AUTHORITY section as a courtesy.
If you want a consistent output, you should either use +short (for answers only) or disable all output settings with +noall and selectively enable what you want to see. That said, shell scripting against the output returned by dig leaves much to be desired. If you need to precisely extract data from reply packets, it's recommended that you use your favorite scripting/programming language and a library suited to the task.

dns lookup at different dns servers


How to show compiler errors in problems pane when using Maven in Eclipse?

Question: The way that I see compiler errors is right clicking my pom.xml and clicking "run as --> maven install" and a console output shows compiler errors.
Is it possible to make eclipse detect compiler errors in real-time and show them in the problems pane like it does when you are not using Maven?
Comment: have you got build automatically check box checked?? Enable it and try
Answer:
have you got build automatically check box checked?? Enable it and try


Pitfalls when updating a site without entering maintenance mode?

Question: Assuming there are no module updates that require doing a database update, if it's just an update to a newer minor release of Drupal core, as well as of contrib and custom modules, what potential pitfalls should I watch out for when updating without entering maintenance mode?
We have 3 load-balanced web servers that all point to the same database and file server. The updates are generally done by first putting all the 3 Drupal instances into maintenance mode, waiting for a minute or two (not sure if this is necessary), then literally overwriting the entire application root directory with the newer version on each server, then clearing the caches on each of the servers, then exiting maintenance mode.
Is it safe to do this overwriting of the files while the site is live, without entering maintenance mode? I've heard of people doing this, but they have brochureware sites with not a lot of traffic and not a lot of logged-in user sessions (which we do have). Does doing so become more or less safe if you have multiple load-balanced web servers, use APC, use Varnish in front of the web servers, use nginx, use Memcache (which also stores sessions) between the web servers and the DB, have all pages using SSL, etc?
It would be great to seamlessly roll over to a new version without having to enter maintenance mode, but it feels risky to me. Are there edge cases where if your new files take a couple of minutes to overwrite the old files in the application root, then maybe some users are getting loading one module from the old set of files and one module from the newly-copied set of files, leading to strange and non-reproducible errors?
Answer: As you said there:

but they have brochureware sites with not a lot of traffic and not a lot of logged-in user sessions (which we do have)

If accessibility is very important to your website I would suggest you do NOT take the risk to directly overwrite files for upgrading while the website is still up and serving. It may lead to corrupt data or broken response.
One approach could be take one web server out of the load-balance group, upgrade it while your website is still up and serving. After upgrade and test, put it back then upgrade another one, until all are done. In this way you can seamlessly upgrade without shutting down the service. It may sound complicated and boring, but it could be highly automated by writing some scripts I think.
Comment: This is not actually practical in Drupal, because Drupal does not really support running code without a matching database. Drupal assumes you enter maintenance mode, change code, *run database updates* and then leave maintenance mode. What you're talking about is blue/green deployment and it requires careful planning to ensure code and database are backwards and forwards compatible for any given subsequent releases. This is a devilish problem with a typical Drupal site that would typically use up to several dozen contributed modules.
Answer: It is risky and should generally not be attempted. Drupal code makes assumptions about the database structure and should generally not be run when the accompanying database updates have not been applied.
Currently, the best you can do is:

Make sure your site uses a mechanism that symlinks the PHP code in the correct location.
Copy over all code for the new release to a fresh location
Enter the site into maintenance mode
Switch over the symlink to the new code (this is much quicker than copying or even rsyncing over the new code); you are likely to need to restart your web server for it to pick up the new symlink
Run database updates and hope they do not take a long time
Disable maintenance mode

For lengthy update processes, you can check if they really need to run during maintenance mode. If you are e.g. just updating content and there is no great damage in running the site without the updates applied everywhere, you can consider stopping the actual update short (maybe patch the update hook to just return TRUE), and devising something to run the update script while the site is live. Of course, you will need to take greater care of the load this would cause and if it doesn't interfere with regular site operations. Unfortunately, Drupal does not contain such a mechanism.
When running something like Varnish, there are definitely ways to minimise the number of occasions where users actually see the maintenance page, e.g. have Varnish serve cached content when it finds the backend is not available. It would be rather out of scope here to go into that very deeply, though, I guess.


loop over an object and return lowest number in javascript

Question: So I'm a JS newbie and am trying to figure out how to fix my problem. I am trying to loop over an object and return the lowest number.
in my var shortest = ; if I hardcode a number say var shortest = 455; then the problem returns the correct number 3. although im not sure what to put there to make it blank by default. I have tried object[0], object[key] and '' and none of these work properly
var myObj = {first: 45, second: 23, third: 3, fourth: 222, fifth: 2343};

var myFunc = function (object) {
    var shortest = ;
    for (var key in object) {
      if (object[key] < shortest) {
        shortest = object[key];
      }
    };
    return shortest;
};

Comment: How about putting a really big number? How about `Infinity`? This question sure looks a lot like your previous one. Are these homework questions?
Comment: They are, just problems im creating trying to learn this lovely language :) I could hardcode the number, but that doesn't work in the real world, so trying to understand what the proper way to do it is.
Comment: Why doesn't it work in the real world?
Answer: set initial value of shortest to Number.MAX_VALUE is all you need
var myObj = {first: 45, second: 23, third: 3, fourth: 222, fifth: 2343};

var myFunc = function (object) {
    var shortest = Number.MAX_VALUE;
    for (var key in object) {
      if (object[key] < shortest) {
        shortest = object[key];
      }
    };
    return shortest;
};

Number.MAX_VALUE
The largest positive representable number.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number
Comment: +1 for actually answering the question. A bit more help would be to point out that when *x* is undefined, the result of `x < anyNumber` is always false (see [The Abstract Relational Comparison Algorithm](http://ecma-international.org/ecma-262/5.1/#sec-11.8.5)) since *undefined* will be converted to `NaN`.
Comment: thanks for your feedback. forget to handle undefined is a common source of bug :)
Comment: Thanks this helped a lot. I read the MDN doc and what does `MIN_value` mean as it said `Number.MIN_VALUEThe smallest positive representable number - that is, the positive number closest to zero (without actually being zero).` and I don't really get it. I ran it against my code and it gave back `5e-324` in the console.
Comment: @jstone 5e-324 is a float number: 5 multiply 0.1 324 times like: 0.000000005  you can read the detail here  https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Values,_variables,_and_literals#Floating-point_literalsyou
Answer: Try this:
var myObj = {first: 45, second: 23, third: 3, fourth: 222, fifth: 2343};

    var myFunc = function (object) {
        var shortest = object.first;
        for (var key in object) {
          if (object[key] < shortest) {
            shortest = object[key];
          }
        };
        return shortest;
    };

Comment: Given the use-case, it isn't safe to assume there is a key called `first`.
Comment: You'd really not want to hardcode a property. To take this approach, you'd need to initialize the variable in the first iteration of the loop, either using a flag, or by checking `shortest` for `undefined`.
Comment: You should not rely on setting *shortest* to some random value. What if `object.first === NaN` or `undefined`? Also, please explain answers rather than simply posting code.
Comment: Sorry for my English! But I just follow OP question. I think first key must be valid in this case. It's not random key, right?
Answer: The reason it fails is in here:
var myFunc = function (object) {
    var shortest = ;
    for (var key in object) {
      if (object[key] < shortest) {

Since the value of shortest is undefined, the < operator causes it to be converted to NaN for the test, and according to the rules for The Abstract Relational Comparison Algorithm, comaring anything to NaN returns undefined, which is equivalent to false here.
The fix is to initialise shortest to some value, e.g. as qiu-deqing suggested Number.MAX_VALUE, or you can use something like:
function getShortest(object) {
    var shortest, value;

    for (var key in object) {
      value = object[key];

      if (typeof value == 'number' && !isNaN(value)) {

        if (typeof shortest != 'number') {
          shortest = value;
        } else {
          if (value < shortest) {
            shortest = value;
          }
        }
      }
    }
    return shortest;
}

The above will ensure that you only compare numbers and that shortest will only be a number or undefined. There should probably be a hasOwnProperty test too to avoid inherited properties.
Answer: See if this helps:
var lowest = function(ns) {
  return Math.min.apply(0, ns);
};

var values = function(obj) {
  var result = [];
  for (var i in obj) {
    result.push(obj[i]);
  }
  return result;
};

var result = lowest(values(myObj));

console.log(result); //=> 3


Using Json Variable In Powershell

Question: I have some code that returns some data from a database in the following json format:
{
    "dateTime":  "2021-01-27T10:26:19.595198+11:00",
    "sessionId":  "apples",
    "userId":  "exampleUser"
}

For an operation I wish to perform I need to take only the "userId" from this response, how would I do this in Powershell?
Answer: Use ConvertFrom-Json and the Member access operator . (dot):
$data = @'
{
    "dateTime":  "2021-01-27T10:26:19.595198+11:00",
    "sessionId":  "apples",
    "userId":  "exampleUser"
}
'@

($data | ConvertFrom-Json).userId

Using Json Variable In Powershell


How use flask route with class based view?

Question: Django style Class Based Views cool and powerful feature. But Flask style routers more suitable to the free style of app structure.
How can I do something like this:
@app.route("/")
class MyView(MethodView):
    def get(self):
        return "Hello word"

Answer: from flask documentation(https://flask.palletsprojects.com/en/1.1.x/views/):
from flask.views import View

class ShowUsers(View):
    def dispatch_request(self):
        users = User.query.all()
        return render_template('users.html', objects=users)

app.add_url_rule('/users/', view_func=ShowUsers.as_view('show_users'))

the last string converts to the function and does registration(@app.route(...)) to the app
Answer: I could not find such feature in the official flask documentation. And also I did not find any solution on the internet or a similar question at Stack Overflow, so I prepared a snippet for this case.
import types

from flask import Blueprint
from flask.views import MethodView

# decorator code
def class_route(self, rule, endpoint, **options):
    """
    This decorator allow add routed to class view.
    :param self: any flask object that have `add_url_rule` method.
    :param rule: flask url rule.
    :param endpoint: endpoint name
    """

    def decorator(cls):
        self.add_url_rule(rule, view_func=cls.as_view(endpoint), **options)
        return cls

    return decorator

    # Usage
    # I use `Blueprint` and `MethodView`, but it should work correct with `App` and `View` to.

bp = Blueprint("bp", __name__, template_folder="templates")

@class_route(bp, "/", "my_view")
class MyView(MethodView):
    def get(self):
        return "Hello world"

# Advanced usage
# Add decorator as class method
bp.class_route = types.MethodType(class_route, bp)

# And use is as bultin decorator
@bp.class_route("/advanced", "advanced_my_view")
class AdvancedMyView(MethodView):
    def get(self):
        return "Hello world!"

Comment: This is unnecessary and a better-quality search on your part would've shown you the [`Flask-Classful`](http://flask-classful.teracy.org/) extension.
Answer: I fancy D.I. and prefer the approach described below:
class MyBlueprint:
    def __init__(self, ...some resources...):
        self.resources = ...
        self.blueprint = Blueprint('youdomus_blueprint', __name__)

        self.blueprint.add_url_rule('/my-route', view_func=self.my_method)

    def my_method(self):
        ...

app = Flask(__name__)
app.register_blueprint(MyBlueprint(...).blueprint)

Below a running example. A sample module bp_example.py contains some application logic class:
from flask import Blueprint, jsonify, request

class Greeter:
    def __init__(self, greetings: str, default_name: str):
        self.blueprint = Blueprint('flask_example', __name__)
        self.blueprint.add_url_rule('/a-method', view_func=self.a_method)
        self.greetings = greetings
        self.default_name = default_name

    def a_method(self):
        return jsonify(f'{self.greetings}, {request.args.get("name") or self.default_name}')

The main module use it like this:
def main():
    import sys
    from bp_example import Greeter

    greeter = Greeter(
        greetings=sys.argv[1] if len(sys.argv) > 1 else 'Hello',
        default_name=sys.argv[2] if len(sys.argv) > 2 else 'World',
    )

    from flask import Flask

    app = Flask(__name__)
    app.register_blueprint(greeter.blueprint)

    app.run(port=5000)

if __name__ == '__main__':
    main()

What's important here is that Blueprint routes definitions need an instance, not a class, otherwise you end with some globals around and unit testing becomes a mess.
Comment: How this works? can you give a more concrete example?
Comment: I don't think this works. There are no routes defined
Comment: If you look at Flask route annotation code, you'll find it just invokes add_url_rule. See flask/blueprints.py, class Blueprint, method route. I don't like flask style using annotations at all because it mixes configuration, which is dynamic, with code definition which is static. The code I posted works, I usually test it before postsing.


make a mailbox available for viewing as a website

Question: The goal: make an exchange mailbox (or IMAP) available for (anonymous) viewing as a website.
Has anybody used any existing tools for this? I could use a web-based email client and try to strip out the sending abilities and hard code the account information, but I was wondering if there is a better way.
Answer: If you have to make it viewable to anonymous users, a web application using Exchange EWS services is the best method.  EWS has a full capabilities and is what apps like Outlook for Mac and Blackberry Enterprise server use to access mailboxes.  That way, you're using an API which you can limit calls to and restrict functionality at the web services layer.  You can also skin it so you're just looking at content you need and not entire folder views and other unneeded client UX.
For more information:  https://msdn.microsoft.com/en-us/library/office/jj900168(v=exchg.150).aspx
It's absolutely the way to go for client application access to Exchange.