Divergence from uniform distribution (continuous): dispersion measure?

Question: I have data of a continuous random variable within the range [-1,1], which sometimes is concentrated around 0, while other times is concentrated toward -1 and 1, while zero is relatively underpopulated.
What measure can I use for both these cases to measure the divergence from a uniform distribution?
In other terms: I am looking for a measure of how evenly spread out the data is within the range, but standard dispersion measures (like variance) don't seem to work, since they favor distributions in which the tails are higher than the 'peak', e.g., when the region around zero is relatively underpopulated.
Comment: you mean like some goodness of fit statistic (such as a Kolmogorov-Smirnov or Cramer-von Mises statistic)?
Answer: Expanding on @Glen_b 's comment:
KS works quite well here. In R, first create distributions like those mentioned
set.seed(123)
library(moments)
library(lattice)

UniDist <- runif(10000,-1,1)
NormDist <- rnorm(10000,0,1)
TruncNormDist <- NormDist[NormDist > -1 & NormDist < 1]
LowDist <- rnorm(5000,-.5,.1)
HighDist <- rnorm(5000,.5,.1)
TruncLowDist <- LowDist[LowDist < 0 & LowDist > -.5]
TruncHighDist <- HighDist[HighDist > 0 & HighDist < .5]
InvDist <- c(TruncLowDist, TruncHighDist)

Then test with ks.test:
ks.test(TruncNormDist, UniDist)
ks.test(InvDist, UniDist)

However, the D values are not intuitive (at least, not to me); ordinarily, I would suggest also using quantile plots:
qqplot(TruncNormDist, UniDist)

But that does not work well here (there is almost no divergence). Nor is a basic scatterplot much help:
xyplot(TruncNormDist~UniDist)

But Tukey mean difference plots are another matter
tmd(xyplot(TruncNormDist~UniDist))

Shows that the difference between the two distributions is near 0 at -1 and 1, but larger in the middle.
Comparing the inverse distribution to the truncated normal is much easier; both qqplot and xyplot show huge differences, and tmdplot is fascinating.
Comment: install.packages("lattice") and library(lattice). If you use `SAS` you can get both of these plots there, as well. Let me know if that's the case and I will provide more details.
Comment: It's been a while since I've used R. How do I get `tmd` and `xyplot`?
Comment: Yes, I just needed to do `library(lattice)`. Not using `SAS`, though.


How do I download/open a pdf file directly by clicking on lable/link

Question: I have created a view that displays in a bulletin format, which works fine. My challenge is when I click on the bulletin which has a pdf attachment, I want it to immediately download/open the attached pdf file. Currently it takes me to  second screen(see attached) which has a pdf attachment. I would like to get pdf attachment downloaded immediately when I click on the bulletin, National Arts Festival Grahamstown 27 June to 7 July 2013 from the first screen(see attached).
I have tried to use file force drupal module but seems not to be doing the trick.
Herewith an attachments.
Answer: If want to Download File, then use DownloadFile module.

a module to direct download files or images.

If want to open PDF, then use PDF Reader module

will render your entity file fields with the selected PDF renderer.

and PDF module.

Use HTML5 to display PDF files if users don't have pdf plugin for
  their browsers.


Adding ajax to text field in node edit form

Question: I have created a content type "Type A" and added three fields to content type. I want to display value in third field equal to (value of first field - value of second field).
I want to implement the same using ajax functionality. I have created a custom module and alter the "node form" and add ajax to field 1 but ajax is not working on change event of textfield.
Code Snippet:
function employee_login_form_alter(&$form, &$form_state, $form_id){

    $form['field_total_value']['#prefix'] = '
';
    $form['field_total_value']['#suffix'] = '
';

    $form['field_value_first']['#ajax'] = array(
        'callback' => 'employee_login_ajax',
        'wrapper' => 'calculate-total-value',
        'method' => 'replace',
        'event' => 'change',
    );

    $form['field_value_first']['und'][0]['#ajax'] = array(
        'callback' => 'employee_login_ajax',
        'wrapper' => 'calculate-total-value',
        'method' => 'replace',
        'event' => 'change',
    );

}

function employee_login_ajax(&$form, &$form_state) { //print_r($form); exit;
  print_r($form_state['values']);
}

Comment: Hello. What form elements keeps your first and second fields?
Comment: field_value_first and field_value_second are first and second fields.
Comment: Did you meant `$form['field_value_first']`? Well, you can `dpr($form)` with devel to be sure. The rest is in my answer.
Comment: yes, $form['field_value_first'] and $form['field_value_second'] are two fields.
Answer: You don't need ajax, you can do this with jQuery or javascript. Something like this might work.
First, create an external js file and set up your change events.
jQuery(document).ready(
    function()
    {
        jQuery("#field2").change(subtract_fields);
        jQuery("#field1").change(subtract_fields);

        function subtract_fields()
        {
            if (jQuery("#field1").value != "" && jQuery("#field2").value != "")
            {
                return jQuery("#field1").value - jQuery("#field2").value;
            }

            return "";
        }
    }
);

Next, load the external js file using drupal_add_js.
Clear your cache and voila.
Comment: Good idea, and faster than ajax, but fails if calculations needs something from database. Upvoted anyway.
Comment: I know that I can do this with jquery or javascript. But, ajax should work which is not working.
Comment: If you're just subtracting two values that exist on the form, I don't see why you would need ajax.
Answer: In ajax callback you are not supposed to print form part you want updated. You are supposed to return form part that needs updating. And you can set field's value using $form_state['input'].
function employee_login_ajax(&$form, &$form_state) {
  $form_state['input']['field_total_value'] = $your_value;
  return $form['field_total_value'];
}

Ah, and don't forget <input> usually does not support change event. You can use one of the following instead:

keyup
blur
maybe input, this one depends on browser

Or don't set ['#ajax']['event'] at all, to let Drupal decide.
Comment: Yes, you are right. But issue is that when I enter any value in field_value_first and leave it, ajax does not work on the same. I have add print_r in the ajax callback only to check ajax is working or not.
Comment: @JayendraKainthola answer updated
Comment: I added comment before I got your update answer.
Comment: @JayendraKainthola yea, your comment made me update my answer :)
Comment: Before, I did not set ['#ajax']['event'] and it was not working for me. Then I tried to set ['#ajax']['event'] and hope that it work. Trying with other option but not working.
Comment: @JayendraKainthola define "not working" please. AJAX request is never sent? or is sent and returns with status 500? or what exactly happens?
Comment: Ajax request is never sent. I checked firebug consule, but it did not display any ajax path.
Comment: @JayendraKainthola `dpr( $form['field_value_first'])` and see if you are adding ajax to something with `'#type' => 'textfield'`. It will not work if you happen to add it to some wrapper.


Truncate given text to specific width, for a specific font

Question: I want to truncate specific text, to specific width. I know the font I'll be using and the font size. I'm trying to figure which is the best approach to tackle this problem. This has to be done serverside.
As far as I'm aware of there's no function in PHP that outputs the width of each character. I could use image* functions, but I don't want to create images, only for the purpose of determining the width of the given text.
An obvious solution that comes to my mind is to create a magic widths table, as: a - 16px, b - 14px, etc. but that sound horrendous (and obviously I won't be able to go through entire scope of characters given text has).
Another solution that comes to my mind is convert TTF to json through Cufón, and then use that reference file to truncate given text, but again this sounds like a roundabout way of doing things. If I remember correctly Cufón (and other converters) use Batik to generate the SVG reference, and using that as a step is out of the question as well.
Do I have to write my own implementation of hmtx table parsing in PHP, or is there some implementation I can use?
Comment: Won't the font be "applied" clientside and so be enlarged, not be used at all, ...?
Comment: The purpose of this is either to output "smartly" truncated results for Google results, or to warn the admin that the SEO title that he's putting in goes outside the width that Google uses (certain width depending upon the client, using Arial 16). While the second one **can** be done clientside, the first one can not.
Comment: Is this in some kind of closed or otherwise carefully controlled system where you can make assumptions about how the font will actually render on the client?
Comment: @djangodude please see the comment above on what is the purpose of this. If I know the font and its size why shouldn't I be able to calculate the width of the bounding box - accessing the glyphs is the problem.
Comment: I'm pretty sure I understand what you're trying to do. That's not what I asked. To help you figure out a solution I want to know whether you are sure that you can rely on the font being rendered the same on the client as it is on the server. In my experience it is not a reliable assumption at all, unless you have very carefully-controlled/known clients.
Comment: @djangodude while I don't know how fonts "work", I assume each glyph has its width set within TTF file. Google specified that what they're outputting in the results is 482px. Let's assume that all the browsers output the text with the same dimensions (as, letter spacing and glyph widths are the same between the browsers) or differences between the browsers don't matter (I don't need to be exact)
Comment: For the most part, your assumption is correct about the width within the TTF file. But the assumption that all browsers output the text with the same dimensions is not: there are differences in the font rendering engines among the various platforms and even among browsers on a single platform which can affect the dimensions (sometimes quite significantly). You didn't mention originally that you don't need to be exact, which is a pretty big detail, but I think there's a way to get close enough to what you need (see my answer, coming shortly).
Comment: @djangodude out of curiosity - how big are the differences? While the differences of few pixels virtually don't matter for me (and that's why I omitted it), differences of "W is twice the size in IE, what are we going to do about it" kind of do.
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/59759/discussion-between-djangodude-and-eithedog).
Answer: If you can make use of ImageMagick in your PHP installation, Imagick::queryFontMetrics (and a few other related font functions) should do the trick for you. The example on the linked page does pretty much exactly what you are after: basically, you set the font & size, then pass a string in to queryFontMetrics. It returns a number of metrics, one of which is textWidth, which you can use to determine whether you're within your specified width or not.
You may need to make a few passes over a given string to get it right. It is important to use a full string, though (as opposed to simply adding up widths of characters) because data inside of the font can cause differences between the width of, say "AV" compared to the summed widths of 'A' and 'V'.
As I mentioned in the comments, there can also be differences between your server versus clients on the various platforms and browsers, so I would recommend incorporating some kind of error tolerance, particularly at smaller font sizes where the differences are likely to be exaggerated.
Comment: I don't think I can - while it's not a big deal (as I can request IM to be installed), I won't close the question just yet (I don't want to install IM on the server, specifically for this functionality). Otherwise - yup, that's exactly the thing I'm searching for.
Answer: Similar to djanodude's answer, but GD library also has the same capabilities, and GD is often installed on PHP servers.
The function you need is imagettfbbox (Image Bounding Box for TTF fonts). http://php.net/manual/en/function.imagettfbbox.php
This gives you the corners of the text from a given TrueType font (in pixels) and from here you can work out the pixels on screen.
Same limitations as mentioned in djanodude's answer regarding slight differences between server and client. Another gotcha is that the True Type fonts may not be the same as you will be reading a TTF you put on the server which may be different from the one one on the client computer.
Another warning: GD library can be memory hungry. You might want to cache your results (to save unnecessary processing) and user ini_set('memory_limit','128M'); if you run itno problems.


Violin strings breaking in fingerboard area

Question: My violin's strings have been breaking every 3 to 4 weeks. I only practice about 10 hours a week.
It is not normal for strings to be breaking constantly and though the problem could be an incorrect setup I've read that something that could be useful in determining the cause is noticing where the string is breaking. I've read people mentioning the bridge, the pegs, the fine tuners, etc. My teacher said the same.
My strings are breaking in the fingerboard  area. The only theory to explain this I found online is something related to sweat and the skin being to acidic, therefore breaking down the metal and eventually causing the string to break. This seems to be supported by the fact that my fingertips get black lines in them (presumably from the strings) after practicing for a while.
Is there any truth to this acidic skin claim or is it just a myth? Has this happened to you or at least have you heard of it? What can be done about it? Is there a type of string I can get that will diminish the issue (because of the material used)? Or one I should avoid? Could it be something else?
UPDATE 1:

Maybe breaking is not the appropriate term. The string's metallic cover is coming undone (they are "unwinding" or something). The metallic cover is coming loose (don't know if I"m explaining this correctly), but the string doesn't really break in two pieces. The internal core filament is there, but the string is useless without the metal cover.
I'm using D'Addario Helicore strings.
The ones that are breaking the most are G and D. I have some Dominant strings (haven't tried with those), but don't know if that will make any difference.
I've kept reading and another theory I found has to do with too much pressure. I think I may use more pressure than necessary, but never thought it would cause this. It's worth looking at though.
Comment: What kind of strings is it you're playing? Which one of them usually breaks first?
Comment: Anecdotally, [this thread](http://www.violinist.com/discussion/response.cfm?ID=13567) supports the idea that sweat/oil has something to do with faster string breakdown.  It seems that 30-40 hours is much less than anyone else is reporting before their strings break, though, so I would suspect something physically wrong with the violin or the strings.  Have you tried a different brand?
Comment: I've updated the question with more information instead of here since I thought it would be easier to follow. Thanks!
Comment: @Lilitu88: it's useful to adress comments to users so they are notified, like this. – If you haven't tried any other string brand, that's the first thing to do. I personally was never happy with any strings by d'Addario when I tried them, but for reasons of sounds rather than longevity; and I'm not a violinist, so this is not really significant here. Still, try it! — I really doubt it has to do with too much playing-pressure, unless you have steel hands... it's more likely to have to do with your violin.
Comment: keep your nails short. biggest influence on string life I've ever experienced, while sweat will have some effect.
Answer: There are only three possible reasons for this to be occuring,

The fingerboard on your violin has been worn out (or it is quite uneven) and this means that when the strings come in contact with the fingerboard on an uneven surface the string gets caught and is slightly damaged each time. Take your violin to a professional luthier and ask him to polish the fingerboard and even it out.
Your nails are simply too long and you're damaging the winding by scratching them constantly when you play.
Check if anything inside of your case is coming in contact with the strings when you close your case as this may also be scratching your strings.
Answer: As well as the things stated above, there's actually a few more things I can think of (although admittedly much rarer) that could be causing the issue:

Cheap strings. Seriously - I once used a knock off no brand string because I'd run out of dominants, and had that lying around somewhere. It lasted all of a week before giving in.
The fingerboard is too long. Again, seriously, and I had this issue too. My violin used to belong to my great grandad, and during the last 100 or so years the fingerboard, which was already a tad long to start with, had actually swollen slightly. Obviously if this is the case, it's time to have it looked at by a qualified professional.
Others have mentioned nails as a causal factor, but this is especially exacerbated if you're shifting positions with your nails in contact with the strings. Not an issue I've had myself, but have seen others who this has been a problem for.
Where do you store your violin? If you're storing it next to a radiator, then shoving it in the car in winter for a cold journey to orchestra practice, then warming it up practicing, then it's in the car for the cold journey back, then put in another warm place for a while - this constant expansion and contraction can really weaken the strings, especially the outer windings.
The strings could be sitting too high over the fingerboard, meaning they come under more stress when you put your finger down. Again, if this is the issue then time to take it to a repair shop.

Due to the fact they're breaking so quickly, I actually wonder whether it's a combination of what's been mentioned already - you'd struggle to break them that quickly with just one thing wrong, unless it really is extreme.
Answer: I play guitar, and there's great anecdotal evidence of killer sweat for guitar strings, but there, the strings go dark and sound dead. Your sweat should not break strings.
Comment: Violin strings are pretty different, though -- they're often not even completely metal.
Comment: I don't know about guitar strings, but violin strings are made of a filament that can be synthetic and then covered (wound) in some metal.
Comment: With the addition of the "strings unwinding", I have an unrelated answer to my previous answer. I used to play acoustic in an otherwise electric band, and I would play hard so I could hear myself, and I would play with a brass pick to sound brighter, so I could hear myself. I got to the point of getting an unwound G string for my acoustic, just so the windings wouldn't break and split.

That is very unusual. It only happened with me when I was playing hard with what amounted to a small brass knife. There is something, and I have no idea what, that's going on with your strings.
Answer: My violin has exactly the same problem. I use Dominant strings and I noticed that the small wires were unwinding from the core of the string and as I tried to play it it sounded terrible.
I think that there is no way of preventing this but perhaps you should try different brands of strings and different types of strings to see which strings are more durable and, most importantly, which sound best. Although Dominant strings are a very popular choice of string, the have a tendency to unwind like yours are. If you have tried different types of strings and different brands you should take your violin to a violin shop and ask for a new string(s). You will need to buy new ones every time this occurs.
Answer: Strings made by Thomastik have this problem.  I've not seen it with other strings.  Next time try Larsens.  They are more expensive, but a set will last a year or more.
Answer: I use Dominant strings, get very black fingers and strings unravel in some 6-8 weeks, especially "e" and "a".
I'm going to try wiping the strings and going for a less acidic diet, drinking more water...don't laugh, its expensive !!
Answer: Try the solutions given above in the previous posts. Brilliant answers guys.
Also check the case my old case was not high enough for some of my cases. Don't panic because this is more likely a badly measured case than a violin. Also check your environmental conditions, trim your nails and check your bridge and compare it with photos online primarily the shape.
Try it with a different set of strings if all of the above does not fix it. Finally take it to a luthier nearby and get the instrument checked. What instrument do you use?(Should have asked this first.)
Also wipe your strings gently with a soft, dry cloth before and after practice and in between if you practice for a long time at once. Do you use the same type of strings(gauge and tension)?


What is the surface area of the plane $x+2y+2z=12$ cutoff by $x=0, y=0$ and $x^2+y^2=16$

Question:
What is the surface area of the plane $x+2y+2z=12$ cutoff by $x=0, y=0$ and $x^2+y^2=16\,?$

I am unable to solve this question since it involves $z$ variable too.
Comment: maybe cut off by x>0 and y>0?
Comment: Please, if you are ok, you can accept the answer and set it as solved. Thanks!
Answer: The cylinder
$$x^2+y^2=16$$
cut off an ellipse from the plane $$x+2y+2z=12$$
The projection of the ellipse in the x-y plane is given by the circle:
$$x^2+y^2\leq16$$
with radius $R=4$ and area $A=\pi R^2=16\pi$.
The ratio between the area of the circle and the area of the ellipse is given by the $\cos \alpha$, $\alpha$ being the angle between the normal to the plane and the $z$ axis.
Thus: normal to the plane: $\vec n(1,2,2) \implies \cos \alpha=\frac{2}{3}$.

The area of a quarter of ellipse is thus:
$$S=\frac32 \cdot 4\pi=6\pi$$
Answer: First, let me know what do you think about given equations?
here, x+2y+2z=12 is a plane cutting X,Y&Z axes at 12,6,6 respectively.
x=0 is a plane i.e. YZ-plane & y=0 is XZ-plane.
x^2+y^2=16 is a circular cylinder with radius 4 and Z-axis as its axis.
Now trace all these and you will get some part of plane x+2y+2z=12 inside the cylinder b/w axes- planes. This is the portion for which to find the surface area and take projection of this portion on xy-plane , you will get 1/4 of circle of radius 4 with centre at origin.( say this circular region R)
Now, write the equation of plane in form of Monge's equation i. e.  z=6-(x/2)-y
and find it's partial derivatives with respect to x and y both.
formula for surface area is,  S=$\iint \ ds $ over R.
here, dS =$ \sqrt( p^2 + q^2 + 1 )\ dx dy $;where p and q are partial derivatives of the Monge's equation with respect to x&y respectively.
p=-1/2  , q = -1 ; so ds=(3/2) dx dy
Now, S =3/2$\iint \ dx dy $ over R
you can see, S= (3/2)area of 1/4 of circle of radius 4 with centre at origin.
therefore S =(1/4)24$\pi$ = 6$\pi$
Comment: Thanks. I understood it clearly.
Comment: So, do you accept it. Any if you face any problem just let me know


JGit how do i get the SHA1 from a RevCommit?

Question: This seems like an idiotic question, but I can't find documentation on it anywhere.
How do I get a the SHA1 of a RevCommit object?
Comment: I've never used Java before but I typed "jgit revcommit" into Google and found http://download.eclipse.org/jgit/docs/jgit-220.127.116.11206130900-r/apidocs/org/eclipse/jgit/revwalk/RevCommit.html then http://download.eclipse.org/jgit/docs/jgit-18.104.22.168206130900-r/apidocs/org/eclipse/jgit/lib/AnyObjectId.html#getName()
Answer: RevCommit inherits from AnyObjectId which has a getName function.

getName
public final String getName()

Returns:
string form of the SHA-1, in lower case hexadecimal.
Comment: For the sake of completeness, there is also an `AnyObjectId::name()` method that returns the same as `getName()`.
Answer: Do note that getName()only works with SHA-1 repositories: JGit does not yet work with SHA-256 repositories.
That is why, for instance, Git 2.30 (Q1 2021) does mark the tests that uses JGit not to run unless we are testing with ShA-1 repositories.
See commit ea699b4 (13 Nov 2020) by SZEDER Gábor (szeder).
(Merged by Junio C Hamano -- gitster -- in commit d302170, 25 Nov 2020)

t5310-pack-bitmaps: skip JGit tests with SHA256
Signed-off-by: SZEDER Gábor
Reviewed-by: Taylor Blau

In 't5310-pack-bitmaps.sh' two tests make sure that our pack bitmaps are compatible with JGit's bitmaps.
Alas, not even the most recent JGit version (22.214.171.124009080501-r) supports SHA256 yet, so when this test script is run with GIT_TEST_DEFAULT_HASH=sha256 on a setup with JGit installed in PATH, then these two tests fail.
Protect these two tests with the SHA1 prereq in order to skip them when testing with SHA256.
Comment: @shabunc Yes, recent commit [shows the skip is still in place](https://github.com/git/git/blame/93eb41e2403788fa9105211956e87b6b2c22c68c/t/t5310-pack-bitmaps.sh#L189).
Comment: does this stay true in 2022?


Knife inside the square

Question: A square of side $n$ is drawn in the sand. A knife of length $k$ is thrown into the square. The tip of the knife lands inside the square, and then the knife falls down to the ground in a random direction.
The location of the tip of the knife is uniformly distributed within the square, and the direction in which the knife falls to the ground is uniformly distributed in $(0,2\pi]$.
What is the probability that the entire length of the knife now lies inside the square? What happens when we replace the square with a circle of diameter $n$?
Comment: It's very close to [Buffon's needle problem](https://en.wikipedia.org/wiki/Buffon's_needle_problem).
Comment: The tip may or may not fall in the square when thrown. If forced to fall into the square, then it is not a probability problem.
Comment: We need information about the probability distribution of the tip inside the square. Equidistribution appears unrealistic. There is no obvious distribution that we could assume that would model someone aiming for the square and being guaranteed to hit it. Equidistribution would become more realistic if you had a large square grid, since then the knife tip could be guaranteed to land in *a* square, and you could use that square for the rest of the consideration.
Comment: The tip is forced to fall into the square and lands on a random point inside the square.
Comment: Perhaps it would be better phrased as something like "*… is thrown onto the **beach. If** the tip of the knife lands inside the square …*", making every point within the square equally likely.  Without that information, the question isn't answerable.
Comment: If $k > n\sqrt{2}$ the probability is zero. If $k < n/2$ and it falls inside the square of side $n-2k$ the probability is one and the chance of this is $(1-2k/n)^2$, so this is a lower bound.
Comment: Thank you all for the edits. The problem reads much better now.
Comment: Oh no. Why is it closed? Would Ray's suggestion make it better?
Answer: We will only cover the first question of throwing a knife to a square in detail.
Choose a coordinate system so that the square is $[0,n]^2$. Let

$p, q$ be the landing positions for knife's tip and end.
$\theta$ be the angle between $x$-axis and knife's body. i.e.
$q - p = k_\theta \stackrel{def}{=} ( k \cos\theta, k \sin\theta )$
For any expression, let $(\cdots)_{+} = \max(\cdots,0)$ be a short hand of its positive part.
Let $\mathcal{E}$ be the event for the whole knife to lie within the square.

Since the square is convex, $\mathcal{E}$ is true if and only if $p , q \in [0,n]^2$.
This is equivalent to $p$ lies within a $(n - k|\cos\theta|)_{+} \times (n - k|\sin\theta|)_{+}$ rectangle. For example, when $\theta \in [0,\frac{\pi}{2}]$,
$$\begin{align}
p, q \in [0,n]^2
& \iff  p \in [0,n]^2 \cap [ -k \cos\theta, n - k\cos\theta] \times [ -k \sin\theta, n - k\sin\theta]\\
& \iff p \in [0,n-k\cos\theta]\times[0,n-k\sin\theta]\end{align}$$
For general $\theta$, the conditional probability for event $\mathcal{E}$ is
$${\bf P}[\mathcal{E} | \theta ] = \left(1 - \frac{k}{n}|\cos\theta|\right)_{+}\left(1 - \frac{k}{n}|\sin\theta|\right)_{+}$$
Let $\alpha = \begin{cases}
0, & k \le n\\
\cos^{-1}\frac{n}{k}, & n < k < \sqrt{2} n\\
\frac{\pi}{4}, &  \sqrt{2} n \le k
\end{cases}$, the desired probability equals to
$$\begin{align}
{\bf P}[\mathcal{E}] = &
\frac{1}{2\pi} \int_0^{2\pi} {\bf P}[\mathcal{E} | \theta ] d\theta\\
= & \frac{1}{2\pi}\int_0^{2\pi}\left(1 - \frac{k}{n}|\cos\theta|\right)_{+}\left(1 - \frac{k}{n}|\sin\theta|\right)_{+} d\theta\\
= & \frac{2}{\pi}\int_0^{\frac{\pi}{2}} \left(1 - \frac{k}{n}\cos\theta\right)_{+}\left(1 - \frac{k}{n}\sin\theta\right)_{+} d\theta\\
= & \frac{2}{\pi}\int_\alpha^{\frac{\pi}{2}-\alpha}
\left(1 - \frac{k}{n}\cos\theta\right)\left(1 - \frac{k}{n}\sin\theta\right) d\theta\\
= & \frac{2}{\pi}\left[
\theta - \frac{k}{n}(\sin\theta - \cos\theta) + \frac{k^2}{2n^2}\sin^2\theta
\right]_{\alpha}^{\frac{\pi}{2}-\alpha}\\
= & \frac{2}{\pi}\left(\frac{\pi}{2} - 2\alpha - \frac{2k}{n}(\cos\alpha - \sin\alpha) + \frac{k^2}{2n^2}\cos(2\alpha)\right)
\end{align}$$
When $k \ge \sqrt{2}n$, this evaluates to $0$ as expected. For the more
interesting case $k \le n$, this simplifies to
$${\bf P}[\mathcal{E}] = 1 - \frac{4k}{\pi n} + \frac{k^2}{\pi n^2}$$
For the remaining case $n < k < \sqrt{2}n$, we have the horrible mess
$${\bf P}[\mathcal{E}] = 1 - \frac{4}{\pi}\cos^{-1}\frac{n}{k}
 - \frac{4}{\pi n}\left(n - \sqrt{k^2-n^2}\right)
+ \frac{2n^2 - k^2}{\pi n^2}
$$
Update
For the second question, choose a coordinate system so that the "circle" is $B(0,\frac{n}{2})$, the disk centered at origin with diameter $n$.
In order for $p, q \in B(0,\frac{n}{2})$, we need $p \in B(0,\frac{n}{2}) \cap B(-k_\theta,\frac{n}{2})$.
For any fixed $\theta$, the conditional probability becomes
$${\bf P}[\mathcal{E}|\theta] =
\frac{\verb/area/(B(0,\frac{n}{2}) \cap B(-k_\theta,\frac{n}{2}))}{\verb/area/(B(0,\frac{n}{2}))}
= \frac{\verb/area/(B(0,\frac{n}{2}) \cap B(-k_0,\frac{n}{2}))}{
\verb/area/(B(0,\frac{n}{2}))}
$$
Since the rightmost expression is independent of $\theta$, this is also
the probability we seek. The end result is
$${\bf P}[\mathcal{E}] =
\begin{cases}
\frac{2}{\pi}\left(\cos^{-1}\frac{k}{n} - \frac{k}{n}\sqrt{1 - \frac{k^2}{n^2}}\right), & k < n\\
0, & k \ge n
\end{cases}$$
Comment: @DmitryKamenetsky you are right, I misread the question and I'll fix that.
Comment: Shouldn't the probability be zero if $k \geq n$? $n$ is the diameter here, not radius.

Knife inside the square


android requestFocusFromTouch brings up menu with first item highlighted

Question: I set the focus and the first selected item on the listview like so:
this._listItems.requestFocusFromTouch();
this._listItems.setSelection(listViewLastPosition);

this causes menu come up with first item selected. How do I change that? I've tried to work with the selector but it does not work. How do I cancel the touch when menu comes up and enable it back if user hides the menu?
EDIT: I noticed that there is an orange background that is always visible under my selected item and here is my menu selector:

menukey_home_focus"  and menukey_home are on transprent background which is why we see orange under. Which brings up two questions:

how to change default orange background to fully transparent background (the stuff with setMenuBackground() all over the internet is NOT working, out code is in the activity base)
how to cancel out focus altogether?

Either of these two will work. Second one is preferable.
Comment: can somebody please tell me how to do this? This is ridiculous! We are 2 days from the app launch and this ugly orange selected state is all over our app!!! UGLY UGLY UGLY!
Answer: android:cacheColorHint="@color/....."

android:divider="@color/...."

android:listSelector="@color/...."

color = #00000000


Diatonic vs chromatic harmonica

Question: The hohner super chromonica has the pattern
<code>Do re    mi fa    sol la    ti do
^     |       ^    |      ^   |      |   ^
 |    v       |    v      |   v     v   |
____         ____       ____     ___
  1             2            3         4    <——Holes
  5            6            7          8
  9           10          11        12
</code>
The hohner marine band harmonica
has this pattern  on holes 4,5,6,7 but due to less holes has different patterns
on holes  1,2,3,4   and on 7,8,9,10
In the lower range there is a duplicate
note on holes 3,4.  (3 draw is sol.)
 Why wasn't it made fa?
Answer: The low 4 blow notes give you the I chord: 1, 3, 5, 1.
The low 4 draw notes give you the V chord: 5, 1, 3, 5.
Putting in the 4 would give you a rootless dominant 7.
Answer: At a guess, the prominence and importance of the 5th in pentatonic scales might have something to do with it; as I'm sure you're aware, diatonic harps are also called 'blues harps', and blues music generally focuses heavily on the dominant (and slightly less on the 4th).  From Wikipedia:

Although there are three octaves between 1 and 10 "blow", there is
  only one full major scale available on the harmonica, between holes 4
  and 7. The lower holes are designed around the tonic (C major) and
  dominant (G major) chords, allowing a player to play these chords
  underneath a melody by blocking or unblocking the lower holes with the
  tongue. The most important notes (the tonic triad C–E–G) are given the
  blow, and the secondary notes (B–D–F–A), the draw.
Comment: They are much used for blues but the tuning predates this use

Diatonic vs chromatic harmonica


What is the sum of digits in the unit place of all numbers

Question: What is the sum of digits in the unit place of all numbers formed using 1,2,3,4,5,6 taken all at a time without repeating any of them?
Answer: Sum of digits in the unit place $$=(6-1)!(1+2+3+4+5+6)$$
$$=5! ~\times~21~=~120~\times~21~=~2520$$

Explanation :  Let us first choose the unit place as $~6~$, then the possible choice for other places are $~5\times 4\times 3\times 2\times 1~=~5!~=~120$.
Now if we choose the unit place as $~5~$, then the possible choice for other places are again  $~5\times 4\times 3\times 2\times 1~=~5!~=~120$.
Similarly, the others.
So the total sum of digits in the unit place of all numbers formed using $~1,~2,~3,~4,~5,~6~$ taken all at a time without repeating any of them $$~=(~6~\times~5!~)+(~5~\times~5!~)+(~4~\times~5!~)+(~3~\times ~5!~)+(~2~\times~5!~)+(~1~\times ~5!~)$$
$$=~5!~\times~(6+5+4+3+2+1)~$$$$=~120~\times~21~$$$$=~2520$$


Practice amp for a flute/piccolo

Question: My wife is a fairly accomplished flautist who has recently taken up the piccolo.  Already practicing the flute is probably affecting her hearing, and the piccolo promises to be an order of magnitude worse.
She's tried earplugs, but she can't adequately hear the tone of the instrument when using those, so it occurred to me to try a microphone, small amplifier, and noise-cancelling earphones to allow her to hear the full tone of the instrument while protecting her hearing from the intense volume.
The problem is, I cannot find a suitable small (preferably battery-powered) amplifier.  Standard mike preamps are both horribly expensive and quite bulky (and most seem to be tube type that wouldn't do too well on battery power), but otherwise about all I can find are "guitar headphone practice amps" and phono preamps.
Close as I can tell, the typical guitar practice amp is designed for an input level about 10x the typical mike input level, while a phono preamp (while it would appear to be sensitive enough) has RIAA compensation which I wouldn't want.  Is there an obvious alternative to either of these, or is there a reason I've overlooked that either would work fairly well (with good tone quality, low distortion, and reasonably low noise)?
I was an electrical engineer in a former life and have considered building something, but I'd prefer to buy something in a nice package.
(It does seem odd that no one has designed a custom box for this use, perhaps with the mike built in.)
Update 2/27
Last night I jury-rigged a test setup (with a crummy, noisy amp) for my wife to try and she indicated that she liked it.  Today I bought the rest of the parts I need to build something.  We'll see if I ever get around to doing it.
Comment: I don't think I'd trust noise cancelling headphones to cancel out a dynamic sound like an instrument being played. They're more for cancelling a constant background noise. Also this solution seems overcomplicated. What kind of earplugs have you tried? Disposable wax/foam plugs will affect her ability to hear the tone, but musicians' earplugs (starting at $25 or so) should attenuate all audible frequencies equally.
Comment: I'll add that it would be nice if the box had only 1/8" inputs/outputs.  I don't see that XLRs are needed here.
Comment: The noise cancelling probably isn't necessary, but earphones that block outside noise well.
Comment: Interesting question.  I'm not sure I understand why you'd want to amplify and feed the sound through headphones. I think that could be worse for her hearing.  Is the idea to get her to play more softly?  Or can she not hear herself when she plays softly unamplified?
Comment: @vjones -- The problem is that the direct sound from the instrument is too loud (and damaging to her ears).
Comment: @slim I don't see why NC headphones wouldn't work. The last time I saw some being demoed, they had a loud music track playing through speakers next to the headphones, and a different track playing through the headphones - worked beautifully.
Comment: @HotLicks _"Update 2/27 Last night I jury-rigged a test setup (with a crummy, noisy amp)"_ - maybe you two will invent a new style, playing flute/piccolo with distortion and effects?!
Answer: This is a seriously overengineered solution.  Like several others stated, you should really invest in actual musician earplugs which are designed for attenuating with a constant frequency response rather than focusing on the most "disturbing" frequencies which also happen to be the most important ones for, well, not being annoying to the audience.
Yes, they are are ridiculously expensive for what they do.  But orders of magnitude more practical than your setup.
Answer: You could try "musicians ear plugs" as commented by @slim. This is not mic/amp, but earplugs that reduce all frequences equally so the sound is not distorted in any way. It just lower the volume received by the ear, and the music still sounds right, just not so loud.
Here is a online store where it seems they have some good alternatives:
http://www.earplugstore.com/nasopl.html
Answer: An in-ear-monitoring headphone preamp would seem the right tool, such as the Fischer Amps bodypack XL. This one has only XLR inputs (two of which won't be needed, that's of course not so nice), but I can't see why you would prefer 1/8". The whole endeavour only has a point if you actually manage to make the sound substantially better than with earplugs, so I'd see to it that a proper condenser mic is used – for which you need phantom power over XLR.
Comment: Unfortunately, most "in-ear-monitoring headphone preamps" don't have mike inputs -- that Fischer unit seems to be about the only one that does.
Answer: So what you need is a way for your wife to hear herself play "naturally", but with a volume control.
The "right" answer is a mic setup (a clip-on, condenser on a stand, omni area mic, or some combo) that goes to a simple 4-channel home studio mixer, which has a monitor/earphones output into which you plug some noise-cancelling studio reference headphones. The "pro audio" department of your local music store can set you up; the cost of it will depend on the quality of the gear. You can get a Mackie 402-VLZ3 mixer for about $100 that will suit your needs quite well, but a good studio-quality mic and good studio-reference noise-cancelling earphones will each be in the $200-$300 range.
To save some money, you can replace the mixer in most cases with a computer (you'd have to have the computer already to save the money, of course). You can either use a USB microphone or buy a converter that will accept an XLR input and feed it into the computer via the mic-in, line-in, SPDIF, or some internal connection (SoundBlaster used to market sound cards with a "LiveDrive" interface that was installed into a 5.25" drive slot and hooked to the sound card directly with a ribbon cable).
The most important part of the whole thing is a good pair of headphones. An NRR of 25 or better would be great if you can get it, the problem is that most studio phones aren't rated like ear protection is.
One last thought that occurred to me; there are specialty earmuffs made for shooting guns. They're basically a very high-NRR earmuff, that also has a microphone with adjustable volume and a compressor circuit. They're designed to detect high-volume transients (gunfire) and compress/suppress them, while allowing the person wearing them to hear people talking normally in between shots. Depending on the exact design, you might find that a pair of these will fit the bill quite nicely in a very portable package; she puts them on and naturally gets an NRR of 30 or better, but using the mic at a reasonable volume she can hear herself. The mic will not be studio-quality by any stretch, though.
Answer: This might not be good enough in terms of sound quality but my thought was you could use a smartphone/tablet, Some phones like the high end Lumias have very good microphones (maybe modern iPhones too) and you can buy a separate microphone for your iPhone for sure - and of course then you can plug headphones in as normal.
It could be a much cheaper way to begin with at least. Although you talked about proper active noise-cancelling earphones which are pretty expensive I think, some noise-reducing headphones can be bought for $50 or less and might do the job.

Practice amp for a flute/piccolo


add classes to wp_list_categories

Question: I am displaying all the categories of custom taxonomy like this:
<?php
    $taxonomy     = 'question';
    $orderby      = 'name';
    $show_count   = false;
    $pad_counts   = false;
    $hierarchical = true;
    $title        = '';

    $args = array(
        'taxonomy'     => $taxonomy,
        'orderby'      => $orderby,
        'show_count'   => $show_count,
        'pad_counts'   => $pad_counts,
        'hierarchical' => $hierarchical,
        'title_li'     => $title
    );
    ?>

            <?php wp_list_categories( $args ); ?>

What i want to do is give different classes to each list item. Like this:

Basics

Mobile

Account

Payments

Privacy

Delivery

how can i do this?
Comment: Instead of using wp_list_categories, use get_categories and loop through each individually to style it the way you want.
Answer: You have two possible solutions - parse the output code through the wp_list_categories filter, which have a full access to the final code outputed by the wp_list_categories function. But in this case you will affect also other calls of the wp_list_categories function.
Other solution is to create own function based on the wp_list_categories code but i.e. modified to add CSS clases based on the category slug.
You can find a full source code of the wp_list_categories function here.
Answer:

  <?php
    $categories = get_categories( [
      'taxonomy'     => 'category',
      'type'         => 'post',
      'child_of'     => 0,
      'parent'       => '',
      'orderby'      => 'name',
      'order'        => 'ASC',
      'hide_empty'   => 1,
      'hierarchical' => 1,
      'exclude'      => '',
      'include'      => '',
      'number'       => 0,
      'pad_counts'   => false,
    ] );

    if( $categories ) {
      foreach( $categories as $cat ) {

    ?>

        <a
          href="<?php echo get_category_link($cat->term_id); ?>"
         >
          <?php echo $cat->name; ?>

  <?php
      }
    }
  ?>

Answer:

<?php
$my_walker= new Walker_Category_Custom();
wp_list_categories(array('walker'=>$my_walker,'orderby'=>'name','title_li' => '','hide_empty'=>0));
?>

Walker class
class Walker_Category_Custom extends Walker_Category {

function start_lvl(&$output, $depth=0, $args=array()) {
$output .= "\n
\n";
}

function end_lvl(&$output, $depth=0, $args=array()) {
$output .= "
\n";
}

function start_el(&$output, $item, $depth=0, $args=array(),$current_object_id = 0) {
$output.= '
ID . '" class="post-archive-categories__item post-archive-categories__item--category">slug).'/" class="post-archive-categories__item-link">

'.esc_attr($item->name);
//slug).'.jpg">
}

function end_el(&$output, $item, $depth=0, $args=array()) {
$output .= "
\n";
}
}

Comment: While this code may solve the question, including an explanation of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please edit your answer to add explanations and give an indication of what limitations and assumptions apply.
Comment: I'm glad I could help but I'm sorry to hear that, don't forget we don't all have enough time to do it, I'll try to explain later in the evening.

add classes to wp_list_categories


How to monitor VOIP packets

Question: We have Asterisk server configured in a Cent OS 5.5. Sometimes my colleague complains
that the quality of the call is not good.

How can I monitor the incoming or outgoing VOIP packets ?
Is there a way to investigate amount of VOIP packets loss ?
Answer: Use Wireshark to capture and analyse the network traffic. This will allows you to look at packet loss on the audio (RTP) stream, and even listen to it (Remember to warn the users that you will be monitoring their communications during your troubleshooting).
If your server does not have a graphical desktop use tshark instead. This will allow you to save a capture file and analyse it later once you have downloaded it to your desktop, where you will need to install Wireshark.
Answer:
How can I monitor the incoming or outgoing VOIP packets ?

For count packages(byte) use iptables rules
For collecting traffic statistic use NetFlow
For runtime monitoring use iptraf

Is there a way to investigate amount of VOIP packets loss ?

I use VoIPmonitor. Many SIP clients have built-in functions.
Answer: tcpdump, specifically looking at port 5060 for sip traffic. You can view captures in Wireshark.

How to monitor VOIP packets


How do I generate C# code from WADL files?

Question: I am looking for a code generator than can generate C# code to access RESTful web services described by WADL files in a way similar to how wadl2java works.
Doing som searching I came across the rest-api-code-gen project on Google Code, but although the latest source does in fact support C#, the REST Describe & Compile demo site does not. (The C# button is there, but it's disabled.)
I realize I could download the source and set up my own server with the latest version, but I would prefer not to, as what I need is a command line tool and not a web application with dependencies to Google Web Toolkit. I guess I could write my own a command line tool based on the same source code, but if it has already been done, or other tools can do the job, I'd rather avoid it.
So, I'm wondering, are there any tools like that out there?
Answer: There is no normal tool for C# and WADL. rest-api-code-gen project seems to be not developing anymore. And may be in future nothing will be changed. There is no definitive opinion about need of WADL for REST and it's non standard like a WSDL
Answer: Another possible answer: http://code.google.com/p/rest-api-code-gen/


How do you fix an attribute error when using "fillpdfs.write_fillable_pdf"?

Question: I am trying to fill out the rest of a partially filled out pdf form, however, when I try to update some of the values in the form using "fillpdfs", I receive a Attribute Error stating: 'NoneType' object has no attribute 'update'. Any help in understanding this issue would be fantastic! I have attached a full screen shot of the error.

I have tried uninstalling and reinstalling the modules however this did not work. I have also tried changing the names of the pdf files themselves.
Comment: Don't make us squint to read code in an image.  Please post all code and errors as plain text.
Answer: There are a few possible causes for this error:
The write_fillable_pdf function might not be defined. Make sure that you have correctly imported the fillpdf library and that you are using the correct function name.
The write_fillable_pdf function might be expecting certain arguments, and you are not providing them. Make sure that you are passing the correct number and type of arguments to the function.
The write_fillable_pdf function might be trying to access an attribute or property that does not exist. Make sure that you are providing the correct data to the function and that the data you are using has the required attributes.
To troubleshoot this error further, you can try the following:
Check the documentation for the fillpdf library to make sure you are using the correct function name and arguments.
Check the stack trace of the error to see which line of code is causing the issue. This can help you identify which part of your code is causing the problem.
Print out the values of the arguments that you are passing to the write_fillable_pdf function to make sure they are correct.
Add some debug statements to your code to print out the value of any attributes that the write_fillable_pdf function is trying to access.
Comment: import fillpdf

# Open the fillable PDF form
with open('form.pdf', 'rb') as f:
  form = f.read()

# Define the data to be written to the form
data = {
  'field_name_1': 'Value 1',
  'field_name_2': 'Value 2'
}

# Write the data to the form and save the resulting PDF
output_pdf = fillpdf.write_fillable_pdf(form, data)
with open('filled_form.pdf', 'wb') as f:
  f.write(output_pdf)
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


Alter taxonomy autocomplete value

Question: I need to alter the element value of a taxonomy autocomplete field before it is processed and can't seem to find a way of doing so.
taxonomy autocomplete fields have an element validator attached, that replaces the String value with an array of terms:
[$form] (array)
  [field_myautocomplete] (array)
    [und] (array)
      [#element_validate] (array)
        [0] => "taxonomy_autocomplete_validate" (string)

I need to alter the String before the validator taxonomy_autocomplete_validate() // taxonomy.module:1747 passes it to drupal_explode_tags() // common.inc:7416. Thus I attach my own element validator via hook_form_alter():
[$form] (array)
  [field_myautocomplete] (array)
    [und] (array)
      [#element_validate] (array)
        [0] => "MYMODULE_validate" (string)
        [1] => "taxonomy_autocomplete_validate" (string)

My validator is executed first and uses form_set_value() to update the value (exactly what taxonomy.module:1782 does in its validator).
However, this only updates the value for $form_state and not $element which is the value used by taxonomy_autocomplete_validate(). Thus, the altered value is completely ignored and gets overwritten by the second validator, based on the original string.
Any suggestions beyond hacking core (make taxonomy_autocomplete_validate use $form_state) are most welcome.
Comment: I guess I could remove the core validator entirely and implement a copy myself that honors $form_state - not very DRY though.
Answer: the simple solution to this issue, is to pass $element by reference to the first element validator:
function MYMODULE_validate(&$element, &$form_state) {
  (...)
  form_set_value($element, $new_value, $form_state);
  $element['#value'] = 'new_value';
}

This way, the $element['#value'] (used by the taxonomy_autocomplete_validate) can be modified and the following validators will.
The form_set_value() is not required, but since the form value has changed, it makes sense to update the state as well.
* many thanks to @ciss for helping troubleshoot the issue on #drupal and suggesting the pass by reference.

Alter taxonomy autocomplete value


Como mostrar uma DIV e ocultar outras com Javascript?

Question: queria ajuda com esse código. Eu fiz  e funciona, mas queria enxugar isso porque está muito verboso e horroroso. Sou iniciante em javascript. As aspas simples são porque o codigo vai dentro de um ECHO do PHP.
OBS: não quero fazer com jQuery.
Agradeço desde já pela ajuda!

function filtro(){
    getValue = document.getElementById('selecao').value;
    if(getValue == ''){
        document.getElementById('ano_grau').style.display = 'none';
        document.getElementById('curso').style.display = 'none';
        document.getElementById('cargo').style.display = 'none';
        document.getElementById('avaliacao').style.display = 'none';
        document.getElementById('disponibilidade').style.display = 'none';
    }
    if(getValue == 'ano_grau'){
        document.getElementById('ano_grau').style.display = 'block';
        document.getElementById('cargo').style.display = 'none';
        document.getElementById('curso').style.display = 'none';
        document.getElementById('avaliacao').style.display = 'none';
        document.getElementById('disponibilidade').style.display = 'none';
    }
    if(getValue == 'curso'){
        document.getElementById('curso').style.display = 'block';
        document.getElementById('cargo').style.display = 'none';
        document.getElementById('ano_grau').style.display = 'none';
        document.getElementById('avaliacao').style.display = 'none';
        document.getElementById('disponibilidade').style.display = 'none';
    }
    if(getValue == 'cargo'){
        document.getElementById('cargo').style.display = 'block';
        document.getElementById('curso').style.display = 'none';
        document.getElementById('ano_grau').style.display = 'none';
        document.getElementById('avaliacao').style.display = 'none';
        document.getElementById('disponibilidade').style.display = 'none';
    }
    if(getValue == 'avaliacao'){
        document.getElementById('ano_grau').style.display = 'none';
        document.getElementById('curso').style.display = 'none';
        document.getElementById('cargo').style.display = 'none';
        document.getElementById('avaliacao').style.display = 'block';
        document.getElementById('disponibilidade').style.display = 'none';
    }
    if(getValue == 'disponibilidade'){
        document.getElementById('ano_grau').style.display = 'none';
        document.getElementById('curso').style.display = 'none';
        document.getElementById('cargo').style.display = 'none';
        document.getElementById('avaliacao').style.display = 'none';
        document.getElementById('disponibilidade').style.display = 'block';
    }

}
    <select id='selecao' onChange='filtro()'>
    <option value='' selected>Selecione uma opção</option>
    <option value='ano_grau'>Ano em que colou grau</option>
    <option value='curso'>Curso realizado depois de formado</option>
    <option value='cargo'>Cargo atual</option>
    <option value='avaliacao'>Avaliação entre a formação e a exigência do cargo</option>
    <option value='disponibilidade'>Disponibilidade de colaboração com a faculdade por meio de entrevistas e palestras</option>
    </select>
Comment: Sempre que postar uma pergunta, é importante explicar a dificuldade encontrada e fornecer sempre um [mcve] do problema. Para entender que tipo de pergunta serve para o site e, consequentemente, evitar fechamentos e negativações vale a pena ler [O que é o Stack Overflow](https://pt.meta.stackoverflow.com/q/7256/70) e o [Guia de sobrevivência (resumido) do Stack Overflow em Português](https://pt.meta.stackoverflow.com/q/8089/70).
Comment: Sem o código completo não vou conseguir te ajudar, senão vou ter que chutar uma resposta.
Comment: Seu código acima parece estar incompleto...
Comment: eu coloquei o HTML só pra mostrar que se trata de um select. Quero mesmo é enxugar o javascript.
Answer: Bom, cada um tem um estilo, eu primeiramente iniciava todos os elementos para display = none e conforme a escolhe na caixa de seleção pego o mesmo valor e manda mostrar com o mesmo nome da div, exemplo:

function init() {
  document.getElementById('ano_grau').style.display = 'none';
  document.getElementById('curso').style.display = 'none';
  document.getElementById('cargo').style.display = 'none';
  document.getElementById('avaliacao').style.display = 'none';
  document.getElementById('disponibilidade').style.display = 'none';
}

function filtro() {
  init();
  const getValue = document.getElementById('selecao').value;
  if (getValue) {
    document.getElementById(getValue).style.display = 'block';
  }
}

(function() {
  filtro();
})();

  <select id='selecao' onChange='filtro()'>
    <option value='' selected>Selecione uma opção</option>
    <option value='ano_grau'>Ano em que colou grau</option>
    <option value='curso'>Curso realizado depois de formado</option>
    <option value='cargo'>Cargo atual</option>
    <option value='avaliacao'>Avaliação entre a formação e a exigência do cargo</option>
    <option value='disponibilidade'>Disponibilidade de colaboração com a faculdade por meio de entrevistas e palestras</option>
  </select>

Ano Grau

Curso

Cargo

Avaliação

Disponibilidade

Se tivesse o HTML, talvez possa diminuir mais o código, mas, acredito que esse ficou bem claro como proceder com otimização, leitura de código e manutenção que posteriormente possam acontecer.


Modify node in hook_node_view() for Drupal 7

Question: I'm trying to modify the array of content, and add an extra link.

I don't want to use the Link module; this link is going to be generated with other fields, it's something like Computed Field module (which is in developing stage for Drupal 7, and I'd rather not use it).
I don't want to just add HTML/PHP to node.tpl.php. I want this to be nice solution.

I've been trying with adding new field to $node->content. I managed to copy another field and display it once again. I was able to change label of that field, but not the link itself.
Does anyone have any idea on how to proceed?
Comment: Give us some code and we tell you where you messed it up. Alternatively, read the documentation on what [drupal_render](http://api.drupal.org/api/drupal/includes--common.inc/function/drupal_render/7) expects.
Comment: Showing the code you are using would help to understand what it is wrong with the code you are using. Differently, who answers could just report what you need to do, which would be what you are already doing.
Answer: You can do this by implementing hook_node_view.
For example:
function my_module_node_view($node, $view_mode, $langcode) {
  switch ($node->type) {
    case 'my_node_type':
      $node->content['extra_link'] = array(
          '#weight' => 10,
          '#theme' => 'link',
          '#path' => 'path_to_content',
          '#text' => t('An extra link'),
          '#options' => array(
              'attributes' => array(),
              'html' => FALSE
          ),
      );
      break;
  }
}

Answer: Whisky's answer will work most of the time, but didn't work if you're trying to add query arguments to the end of the URL. In my case, I'm prepopulating an Entity Reference field which needs a URL that looks like this:
node/add/er-engagement?field_er_cal_entity_reference=19

Whiskey's answer doesn't seem to allow this, whether 'html' is TRUE or FALSE.
The '#markup' attribute will work, however.
function hook_node_view($node, $view_mode, $langcode){
  switch ($node->type) {
      case 'er_event':
        $node->content['links']['extra_link'] = array(
            '#weight' => 100, // place it at the bottom
            '#markup' => l('Add attendee data', 'node/add/er-engagement', array('query' => array('field_er_cal_entity_reference' => $node->nid))),
        );
        break;
}

}
That works great if you need those arguments in there.
The documentation is lacking, but thanks to this post, it helps to check out Drupal 7's blog.module, just search for '#links' to get a clue.
Answer: To add query fragment just put it inside the option array:
$node->content['links']['extra_link'] = array(
    '#weight' => 10,
    '#theme' => 'link',
    '#path' => 'node/add/er-engagement',
    '#text' => t('Add attendee data'),
    '#options' => array(
        'html' => FALSE,
        'query' => array('field_er_cal_entity_reference' => $node->nid)
    ),
);

This will return an URL like this: node/add/er-engagement?field_er_cal_entity_reference=13


SQLite open database from string

Question: Assume I have a string containing an sqlite database.
(I read the entire content of the file containing the Sqlite database into a string)
Now, I want to get a connection to the database  without saving the string to a file first.
Basically, this is an in-memory data base, which is totally possible in sqlite. But according to the sqlite documentation  "[when you open an in memory data base] no disk file is opened. Instead, a new database is created purely in memory".
But I have string representing a data base. i want to use it and not create a new one.
Can this be done?
Comment: You have a database in xml? Please explan or give examples. What have you tried so far?
Comment: Its not a database in xml. I have an xml file that contains a lot of nodes, and each node hold a different kind of data. There is one node that contains the entire text of an sqlite3 file. if i take this text and save it to a file, i can (successfully) connect to it using the sqlite driver. But I want to do it without saving the text to a file.
Answer: In-memory databases do not give you access to the underlying memory.
It is possible to copy databases with the backup API, but that would require another, file-based database.
Just create a temporary file, and open it directly.
Comment: It actually specifically says: "It cannot be used to copy data to or from in-memory databases."  So i guess its not possible to do what i wanted. But thanks for the answer!!

SQLite open database from string


C# - EF Core dúvidas para criar modelo relacional

Question: Estou iniciando em Asp Net Core e tenho a seguinte dúvida:
Possuo um modelo Curso e um modelo Unidade, um curso possui várias unidades e aquela unidade pode pertencer a mais de um curso.
Eu fiz o modelo individual de Curso e Unidade, porém, o meu problema está sendo na hora de criar o modelo de relacionamento, estava pensando em alguma forma que ele recebesse uma lista de cursos e uma unidade, porem sem sucesso.
Abaixo tenho exemplos de código do meu projeto, ao executar estou me deparando com o erro Identity_Insert.
Modelo de curso
public class Curso
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    [Required]
    [Key]
    public long curId { get; set; }

    [Required]
    [StringLength(80)]
    public string curDescricao { get; set; }

    [Required]
    [StringLength(1)]
    public string curStatus { get; set; }

    [StringLength(20)]
    public string curCodExterno { get; set; }

    [StringLength(60)]
    public string curObservacao { get; set; }
}

Modelo de unidade
public class Unidade
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    [Required]
    [Key]
    public long uniId { get; set; }
    [Required]
    [StringLength(80)]
    public string uniDescricao { get; set; }
    [Required]
    [StringLength(1)]
    public string uniStatus { get; set; }
    [StringLength(20)]
    public string uniCodExterno { get; set; }
    public byte[] uniImagem { get; set; }
}

Modelo de CursoUnidade
public class CursoUnidade
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    [Required]
    [Key]
    public long cuuId { get; set; }

    /*[Required]
    public long cuuCurId { get; set; }
    [ForeignKey("cuuCurId")]*/
    public List<Curso> Curso { get; set; }

    /*[Required]
    public long cuuUniId { get; set; }
    [ForeignKey("cuuUniId")]        */
    public Unidade Unidade { get; set; }
}

Serviço de unidade
public void AddTeste(CursoUnidade cursoUnidade)
{
    _contexto.Add(cursoUnidade);
    _contexto.SaveChanges();
}

Comment: Essa é uma relação 1 pra muitos, ou seja 1 unidade pode ter vários cursos. Sendo assim você pode ter na classe unidade uma lista de cursos: `List Cursos` .
Depois você pode adicionar os cursos na Unidade através do método List.Add()
Answer: Provavelmente em algum lugar você deve estar setando explicitamente o valor de alguma coluna de chave primária. Como você definiu as suas chaves primárias como identity, elas serão incrementadas automaticamente, e vai lançar uma exceção caso você tente definir o valor de alguma chave com essa restrição.
Aqui diz que

para inserir valores explícitos em uma coluna IDENTITY do SQL Server, é necessário habilitar IDENTITY_INSERT manualmente antes de chamar SaveChanges();


checkbox states disappear on pagination of kendo grid

Question: Not sure if I am doing this correctly. But I bind a kendo grid with array data of objects, where each object has a Boolean property (i.e. either true or false).
For the user I display it as a checkbox with the checked state showing the true state and vice versa. If you check something in the page 1; go to the page 3; check a few rows; and go back to page 1, the state of the checkbox defaults to how it was at the time it was loaded.
Here is the code snippet I've used.
$(function () {
    var ds = new kendo.data.DataSource({
        transport: {
            read: {
                url: '/echo/json/',
                type: 'POST',
                data: {
                    json: JSON.stringify(students)
                }
            }
        },
        pageSize: 5
    });

    var kgrid = $("#grid").kendoGrid({
        columns: [

        {
            field: 'name',
            title: 'Name'
        }, {
            field: 'age',
            title: 'Age'
        }, {
            field: 'place',
            title: 'Place'
        }, {
            field: 'hasCar',
            title: 'Owns Car',
            template: function (data) {
                return '<input type="checkbox" ' + (data.hasCar ? 'checked' : '') + '/>';
            }
        }],
        height: 240,
        pageable: true
    });

    $('#btnload').click(function () {
        var grid = kgrid.data('kendoGrid');
        grid.setDataSource(ds);
        $('#grid-display').show();
    });

    $('#btnrefresh').click(function(){
       ds.read();
       console.log('refresh');
    });

    $('#btnlist').click(function(){
        var res = $('#result');
        kgrid.find('tr td:last input:checked').each(function(i, e){
           var name = $(e).closest('tr').children().first().text();
           res.append('
' + name + '
');
           console.log('execute');
        });
    });
});

How to persist the state on pagination?
Ps: fiddle to work with: http://jsfiddle.net/deostroll/2SGyV/3/
Answer: That is because the changes you are doing stays there in the grid only - not in kendoDataSource. Here MVVM is not done. So you have to change appropriate value in dataSource each time you click the checkbox.
When you select another page in kendoGrid, it fetches data from dataSource, and then display it the grid. Unless and untill that dataSource is changed, you can't see the changes done in the grid.
PS: Had there is any field for Id in dataSource I would have updated jsfiddle myself
UPDATE
Check this Updated jsfiddle
I have updated template for checkbox
template: function (data) {
    return '<input type="checkbox" ' + (data.hasCar ? 'checked' : '') + ' data-name="'+ data.name + '"' +'/>';
}

Now checkbox will have name of the data. You can change it with id. On change event, update your dataSource accordingly on each checkbox click.
$('#grid-display input').live('change', function(){
    alert($(this).attr('data-name'));
    //update the data source here based on the data-name attribute u're getting
});

Comment: any declarative way of doing this? Like adding `data-bind` syntaxes?
Answer: Use databound event in the kendo Grid.
Not sure below code work will work for you or not. But similar code worked for me
function OnDataBoundEventMethod(e) {
    var view = this.dataSource.view();
    for (var i = 0; i < view.length; i++) {
        if ([view[i].hasCar]) {
            this.tbody.find("tr[data-uid='" + view[i].uid + "']")
                .addClass("k-state-selected")
                .find(".row-check-box")
                .attr("checked", "checked");
        }
    }
}


Must every group with a one-half morphism embed into a ring in which the morphism is division by 2?

Question: Let $\alpha$ be an endomorphism of a group $G$. We say $\alpha$ is a one-half morphism if $\alpha(gg) = g$ for all $g \in G$. The existence of such a morphism in fact implies that $G$ is abelian, hence the name "one-half morphism" rather than "square-root morphism".
A few examples:

Any cyclic group of odd order has a one-half morphism.
More generally, if $G$ is finite, $G$ has a one-half morphism if and only if it is abelian and has no element of order 2, if and only if $G$ is a direct product of cyclic groups of odd order.
If $G$ is the additive group of a ring in which 2 is invertible, then multiplication by $1/2$ in the ring gives a one-half morphism of $G$.
And certainly any direct sum/product of groups with one-half morphisms yields a group with a one-half morphism.

There are groups $G$ with one-half morphisms which are not simply division by 2 in a ring structure on $G$, e.g., the direct sum of all odd prime cyclic groups. But this embeds into the direct product, in which the one-half morphism is again just division by 2.
My question is: is this always true? I.e, is every $G$ with a one-half morphism $\alpha$ simply a subgroup of the additive group of a ring in which $\alpha$ is division by 2?
Comment: A question whether every abelian group is an additivie subgroup of some unital ring is interesting on its own. Note that not every abelian group can be turned into a unital ring. In fact there are abelian groups such that the only valid multiplication on them is the zero multiplication, e.g. $\mathbb{Z}_{p^\infty}$.
Answer: The group $G$ has the structure of a module over $\mathbb{Z}[1/2]$, where we fiat that multiplication by $1/2$ is given by $\alpha$. Then $G$ embeds into the tensor algebra (or the symmetric algebra, if you want a commutative ring) of $G$ over $\mathbb{Z}[1/2]$, and on $G$, $\alpha$ is division by $2$.


Best way to bin continuous data

Question: I have a data frame with 1 vector of integers and 1 as a character factor like so:

I have created a linear model that shows a relationship between age and party affiliation. I now want to determine the best bins of ages (50-59, 60-69, etc..) that can explain party affiliation. Is there an R package/model that can help me do that?
Comment: I would suggest not binning a continuous variable since this is needlessly throwing away information in general.  Can you explain your actual model?  You seem to have a class variable with several levels as the response, so how did you fit a linear model?
Comment: Simply asking for functions / packages is off topic here. You may want to look into [Fisher's Linear Discriminant Analysis](https://en.wikipedia.org/wiki/Linear_discriminant_analysis) ([Quick-R](http://www.statmethods.net/advstats/discriminant.html)), though.
Answer: You might try a regression tree with party as response and age as independent variable.
<code>>temp <- rpart(Party ~ Age)
>plot(temp)
>text(temp)
</code>
The algorithm will find suitable places to split the Age variable, if these exist. If not, the tree won't grow past the root stage, which would tell you something.
Answer: (For the record, I agree with @dsaxton.  But just to give you something, here is a quick demonstration of using LDA to optimally bin a continuous variable based on a factor.)
<code>library(MASS)

Iris  = iris[,c(1,5)]
model = lda(Species~Sepal.Length, Iris)
range(Iris$Sepal.Length)  # [1] 4.3 7.9
cbind(seq(4, 8, .1),
      predict(model, data.frame(Sepal.Length=seq(4, 8, .1)))$class)
#       [,1] [,2]
#  [1,]  4.0    1
#  [2,]  4.1    1
#        ...
# [15,]  5.4    1
# [16,]  5.5    2
# [17,]  5.6    2
#        ...
# [23,]  6.2    2
# [24,]  6.3    3
# [25,]  6.4    3
#        ...
# [41,]  8.0    3
</code>
Comment: Neat idea. I'm not sure if there is a universal equivalence, but making the class predictions via a multinomial model results in the same predictions for your Iris example. [Example here](https://dl.dropbox.com/s/9d3gqanolspkbnr/multinom_effectplot.R?dl=0). That has an example plot to show uncertainty in the predictions as well.
Comment: @AndyW, they are similar but won't be universally equivalent. LDA assumes age is normally distributed; if so, it will work slightly better--especially as the distributions get further apart. MLR can handle categorical variables (sex, race, etc) as well, so can be more generally applicable, but it seems to me a little more advanced to understand & use (although your example was very straightforward, so maybe not). MLR is a viable option; you could add it as an answer, if you wanted.

Best way to bin continuous data


Minimal implementation of gmtime algorithm?

Question: Does anyone know of a simple gmtime or ctime implementation without consideration for timezone, no external dependencies, and a non-copyleft license (BSD/MIT/anything proprietary-safe)?  Preferably in C, but basically anything that gives me the algorithm in its minimal form would work.
I just need seconds since "Jan 1, 1970 00:00:00" broken down into year, day, month, hr, min, sec.  And it's almost time to go home on a Friday so I'm feeling a bit lazy.
Answer: Reverse the algorithm defining "Seconds Since the Epoch" from POSIX:
http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html#tag_04_15
tm_sec + tm_min*60 + tm_hour*3600 + tm_yday*86400 +
    (tm_year-70)*31536000 + ((tm_year-69)/4)*86400 -
    ((tm_year-1)/100)*86400 + ((tm_year+299)/400)*86400

Comment: If you need this direction (not the one in the question), here is a short implementation: https://github.com/pts/minilibc686/blob/master/fyi/c_timegm.c
Answer: Try newlib
http://sourceware.org/newlib/
it is a BSD license.
It is designed for embedded systems, so tends to be quite small and simple.
Look at Docs -> Timefns to see if ctime or gmtime meet your needs.
Comment: I'm already using  functions from newlib, so I dunno why I didn't think to look there.  `mktm_r` (called by `gmtime` via `gmtime_r`) from newlib looks like it will work quite nicely.
Comment: I think you might have answered "...why I didn't think to look there" already: "And it's almost time to go home on a Friday ..." B-) We all get a bit tired (z_z)
Comment: So to anyone else who stumbles upon this post and may question the license of that part of newlib since it's not explicitly declared--mktm_r is derived from tzcode which is public domain.  That doesn't mean the derivation is too, but you can always re-derive if necessary.
Comment: @Brian McFarland - You have panicked me. I am unclear, are you telling me something that I need to carefully consider? I had assumed that the [newlib license](http://sourceware.org/newlib/COPYING.NEWLIB) explicitly applied BSD license terms to all source unless the file carried its own license. So are you saying that, even though that file mktm_r.c does not carry its own license statement, but only identify the authors, that it is not covered by the newlib license? And further, that parts have to be re-derived? This may be bad! I must state, that is not my understanding, by I am not a lawyer.
Comment: Yeah, it looks like you're right.  Anything that doesn't explicitly declare another license is supposed be under the newlib BSD terms.  So I guess I'm safe copying mktm_r.  Sorry to cause panic.  I am also not a lawyer, but like to err on the side of being extra cautious.  Both out of respect for the FSF people and for fear of litigation.
Comment: @Brian McFarland - PHEW!-) Thank you very much for getting back quickly. I agree, be cautious. I became extra careful after a well-known consultant told me many of his larger IT clients spent more on their litigation department than they did on development, and that his company made more money as expert witnesses in litigation, than they did from improving companies software development capability (which was their 'real' business) :-(
Comment: here's a direct link to [`mktm_r.c` (rev. 1.7), to view it online](https://sourceware.org/cgi-bin/cvsweb.cgi/src/newlib/libc/time/mktm_r.c?rev=1.7&content-type=text/x-cvsweb-markup&cvsroot=src&only_with_tag=HEAD)
Comment: Here is an updated link to the source code: https://sourceware.org/git/?p=newlib-cygwin.git;a=blob;f=newlib/libc/time/gmtime_r.c;h=8bf9ee52dd1e54e39d2b1516b0208375104e4415;hb=HEAD
Comment: Please note that the linked Newlib implementation doesn't conform to [POSIX](http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html#tag_04_15) for negative years (i.e. BCE). See my answer for an implementation which does.
Answer: Another short C implementation with MIT license which works with time_t of any size (32 bits, 64 bits etc.): https://github.com/pts/minilibc686/blob/master/fyi/c_gmtime.c
Size-optimized i386 assembly, with 32-bit time_t: https://github.com/pts/minilibc686/blob/master/src/gmtime_r.nasm
Compiled code size comparison (size-optimized for i386, with 32-bit time_t):

Newlib C: 444 bytes. Also this implementation doesn't conform to POSIX for negative years (i.e. BCE).
minilibc686 C: 222 bytes
minilibc686 i386 assembly: 180 bytes


Tangent by scratch

Question: I'm completely new to Erlang and i'm using the Ubuntu command line to run the program and gedit to edit/write the code.
I'm trying to code tangent my scratch rather than using the built in math class.
I get the following errors and unsure what needs to be changed.
ERROR
** exception error: an error occurred when evaluating an arithmetic expression
     in function  math:sqrt/1
        called as math:sqrt(-0.07926409746793839)
        *** argument 1: is outside the domain for this function
     in call from extra:double/1 (extra.erl, line 11)

CODE
-module(extra).

-export([double/1]).

-import(io,[fwrite/1]).

% I am a comment.

double(N) ->
    Num = math:sin(N),
    Dem = math:sqrt(1 - (Num * 2)),
    Tan = Num / Dem,
    io:fwrite("~w",[Tan]).

Comment: `*** argument 1: is outside the domain for this function`... That's coming from `math.sqrt` function application. `sqrt` function requires an argument of `positive` value.
Comment: What was the input you have given which broke this for you?
Comment: I been inputing 0.57 to get this error
Comment: As an aside, you don't actually need the `-import(io, [fwrite/1]).` line in your code. It is usually considered bad style to use `-import` in Erlang - see [this answer](https://stackoverflow.com/a/36092365/113848) for details.
Answer: I think you should be doing a Num * Num instead of Num * 2 when calculating the sqrt for Dem.
double(N) ->
    Num = math:sin(N),
    Dem = math:sqrt(1 - (Num * Num)),
    Tan = Num / Dem,
    io:fwrite("~w~n",[Tan]).

As the error clearly says...

*** argument 1: is outside the domain for this function

While doing math:sqrt(1 - (Num * 2)), clearly the Num * 2 is becoming more than 1 causing a negative argument to be fed into math:sqrt, and hence the breakage.
Illustration: sqrt with negative argument
> math:sqrt(-1).
math:sqrt(-1).
** exception error: an error occurred when evaluating an arithmetic expression
     in function  math:sqrt/1
        called as math:sqrt(-1)
        *** argument 1: is outside the domain for this function

WYSIWYG => WHAT YOU SHOW IS WHAT YOU GET

Tangent by scratch


Convergence in distribution, probability, and 2nd mean

Question:
Let $\mathbb P(X=1) = \mathbb P(X=-1) = 1/2$. Define
$$X_n = \begin {cases} X & \text{with probability } 1- \frac{1}{n}\\

e^n & \text{with probability }  \frac{1}{n} \end {cases}$$
Does $X_n \leadsto X$ (i.e., converge in distribution)? Does $X_n \stackrel{P}{\rightarrow} X$? Does $\mathbb{E}[(X-X_n)^2] \to 0$?

I think $X_n \leadsto X$ because just by picturing the CDF  as n goes to infinity, their CDFs converge. Can I get some confirmation on this?
But for convergence in probability, I'm having trouble with the limits.
To do this, what I'm trying to do is find $\mathbb P(|X_n-X| \leq \epsilon)$ and then just take 1 minus that as shown on this site: http://www.statlect.com/prbcon1.htm
If $X_n = X$, then $|X_n - X|$ is just $0$ so for all $n$, $|X_n -X| < \epsilon$
But if $X_n = e^n$ then I have the two cases for $X$. For $X=1$, $|X_n-X| = |e^n-1| \leq \epsilon$. and For $X=-1$, $|X_n-X| = |e^n +1| = e^n + 1 \leq \epsilon$. This is where I am stuck. I'm trying to find conditions relating $n$ and $\epsilon$ similiar to here the example on the site. But I'm not sure how to get that from $|e^n - 1| \leq \epsilon$ and  $e^n + 1 \leq \epsilon$ .
Am I even on the right track?
Comment: You are interpreting $X$ and $X_n$ as deterministic quantities, not as random variables. So the sentence "If $X_n=X$ then $|X-X_n|=0$ for all $n$'s" does not make sense. Those are random variables, e.g. $|X-X_n|=0$ with probability $1-(1/n)$ and $e^n$ with probability $1/n$. From there, you can conclude about convergence in probability and $L_2$ [lack of] convergence.
Answer: To prove that $X_n \stackrel{P}{\rightarrow} X$ you have to show that, for any given $\epsilon>0$, the sequence of real numbers $\{p_n\}_{n\geq 1}$ defined by
$$
  p_n = P\{\omega:|X_n(\omega)-X(\omega)|\geq \epsilon\}
$$
has limit $0$. What happens at the ``beginning'' of the sequence does not change its limit. For $n\geq \log(1+\epsilon)$, we have
$$
  P\{\omega:|X_n(\omega)-X(\omega)|\geq \epsilon\} = P\{\omega:X_n(\omega)=e^n\}=\frac{1}{n} \, .
$$
Hence, $p_n\to 0$, and therefore $X_n \stackrel{P}{\rightarrow} X$.
Since convergence in probability implies convergence in distribution, we also have $X_n \leadsto X$.
Now, since
$$
\begin{align*}
  \mathbb{E}[(X_n-X)^2]&=0^2\times\left(1-\frac{1}{n}\right) + (e^n+1)^2\times\frac{1}{n}\times\frac{1}{2}+(e^n-1)^2\times\frac{1}{n}\times\frac{1}{2}\\
& = \frac{(e^{2n}+1)}{n}\to\infty \, ,
\end{align*}
$$
we don't have convergence in quadratic mean.
Comment: (+1) Welcome to the site. A couple notes: (**a**) We generally do not give full answers to homework problems on this site, except in exceptional circumstances . Providing hints as answers is *strongly* preferred. ([FAQ](http://stats.stackexchange.com/faq#questions)). (**b**) The last part can be simplified a little by noting that immediately from the definition of $X_n$ we have $\mathbb E((X_n - X)^2) \geq  \frac{1}{n} (e^n-1)^2 \to \infty$.
Comment: Sorry, cardinal! I had not seen the "homework" tag.
Comment: Maybe a $2$ is missing in the denominator? $$\mathbb E((X_n - X)^2) \geq  \frac{1}{2n} (e^n-1)^2 \to \infty$$
Comment: No problem. newer users often aren't aware of some of the finer details of what happens on the site or how. So, I just wanted to point you to a useful resource in case you hadn't seen it. Cheers.
Comment: No, it is not necessary to have a 2 in the denominator. Think of the range of values that $X$ can take on.


Modelagem de Banco de Dados, relação muitos para muitos entre duas tabelas

Question: Tenho 3 websites que irão compartilhar o mesmo banco de dados.
São 3 tabelas: Noticias, Galeria de Fotos, Blog.
Será apenas um sistema de gerenciamento para os 3 websites.
Exemplo: o usuário irá salvar uma notícia que pertencera apenas para 2 websites.
Questão: Qual a melhor forma de modelar o banco de dados?
Criar uma tabela e gravar por exemplo o código do site e da notícia para ser recuperada nos sites que podem exibi-las?
Criar apenas um campo em cada tabela e salvar quais sites essa a notícia pertence? Pensei de ser dessa forma, mas como gravar esses dados que depois possa fazer a busca com SQL de forma eficiente?
Comment: Pergunta baseada em opiniões não fazem parte do escopo do site. Você pode reformular a sua pergunta, por gentileza? Pois se não as respostas serão baseadas em opiniões, e cada um responderá "Eu acho isso ou aquilo"
Answer: Eu faria assim, visto que a mesma noticia pode ser exibida em 2 ou mais sites:
Crie uma tabela Sites com as colunas id (1, 2 e 3) e coluna url (endereço do website, ex: www.meusite.com), aí você insere logo os sites.
Depois criava uma tabela pivot Sites_Noticias visto que a relação é N:N (muitas noticias para muitos websites), esta é a tabela que vai relacionar os Sites com as Noticias. Nesta tabela armazenava somente dois dados, criava uma coluna id_noticia e id_site
Assim desta maneira você já tem a noticia/noticias e o site/sites relecionados.
Agora por ex:
Tabela Sites:
id | url
1 | www.meusite1.com
2 | www.meusite2.com
3 | www.meusite3.com
Tabela Sites_Noticias:
id_site | id_noticia
1 | 3
2 | 1
1 | 2
3 | 1
Neste exemplo podemos ver que a noticia cujo id é 1 vai aparecer no site cujo id é 2 (www.meusite2.com) e no site cujo id é 3 (www.meusite3.com). No site 1 (www.meusite1.com) vão ser publicadas as noticias com os id's 3 e 2.
Pela tabela pivot (Sites_Noticias), consoante o site onde estiver, pode ir buscar as noticias (à tabela Noticias) que devem ser mostradas. Neste exemplo se tivermos no site 1 vamos buscar as noticias cujos id's são id's 3 e 2.
SQL para ir buscar as noticias que fazem parte do site www.meusite1.com:
SELECT Noticias.* FROM Sites JOIN Sites_Noticias ON Sites.id = Sites_Noticias.id_site JOIN Noticias ON Noticias.id = Sites_Noticias.id_noticia WHERE Sites.url="www.meusite1.com";

Peço desculpa pela má formatação da resposta, tentei ser o mais claro possível.


Simplifying a log of a log

Question: I have a summation series that unfortunately involves a log of a log. It looks like the following (assume all $\log$ are log base $2$):
$$
\sum_{i=1}^k \log\log\frac{n}{2^{k-i}}
$$
I'd like to simplify this somehow, such as move the logs or the n value to the outside of the equation, so that I can use the closed form of the geometric series sum to further simplify the equation, but I'm not sure where to start.
Thanks for the help!
Comment: Welcome to MSE! [Here](http://meta.math.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) is a small guide on how to make your math look nicer.
Answer: Well, let's see:
$$\sum_{i=0}^{k-1} \log(\log(n\cdot 2^{-i}))  = \log\left(\prod_{i=0}^{k-1}\log n + \log 2^{-i}\right) = \log\left(\prod_{i=0}^{k-1} \log n - i\right) = \log\Big(k! \binom{\log n}k\Big) = \log((\log n)_k) = \log\Big(\frac{\Gamma(\log n +1)}{\Gamma(\log n - k + 1)}\Big)=\color{maroon}{\log(\Gamma(\log n + 1)) - \log(\Gamma(\log n - k + 1))}$$
Where $(x)_k$ is the Pochhammer symbol
$$(x)_k = x(x-1)\cdots(x-k+1)$$
We used $\log a + \log b = \log(ab)$ and $\log_2 2^k = k$.
Comment: I don't know if that helps in any way, but $\log\left(\prod_{i=0}^{k-1} \log n - i\right) = \log \left( (\log n)^{\underline{k}}\right)$, where $a^{\underline k}$ denotes the falling factorial.
Comment: @hife Good suggestion.
Comment: @AlexR You should say what that notation means in the answer.
Comment: @columbus8myhw Well, it seems obvious but okay.
Comment: Thanks for the quick responses, all. This sort of simplification is fairly foreign to me, so could you lend some insight into the Pochhammer symbol? I'm trying to come up with the simplest closed form possible for this series. For further reference, I will be substituting log(n) for k once I have a closed form of the summation. is @hife right with k as an exponent in the final portion, or is AlexR right with the Pochhammer symbol? Thanks again.
Comment: @drshmoo Well, it's just a compact notation of the product. You can pick some formula for it from the wiki page. For example
$$(x)_n = \frac{\Gamma(x+1)}{\Gamma(x-n+1)}$$
Comment: The Pochhammer symbol is just a notation for the falling factorial. They are the same thing (see the link in AlexR's answer).
Comment: @drshmoo Actually using this formula, you can arrive at a fairly nice "closed form" assuming you permit the $\Gamma$ function (wich has no closed form in elementary functions, but quickly converging series for numerical evaluation)
Comment: @drshmoo: If you wish to substitute log(n) for k, you have to be careful, as the calculations made assumed k to be a positive integer. You would then have to take the integer part of log(n).
Comment: By the way, I've never seen an actual _proof_ that Gamma can't be expressed in terms of elementary functions...
Comment: @columbus8myhw Neither have I but my professor assured me of this some years ago, proof by authority!
Comment: For some more background, this product series results from the recurrence relation T(n) = 4T(n/2) + 5(n^2)*lg(lg(n)). Backwards substitution produces the series. Is all of the above still true if the 2^(k-1) produces a geometric series (2, 4, 8, 16, etc)? I'm guessing that since the lg(lg(...) is present, we aren't able to apply the closed form for a typical geometric series.
Comment: @drshmoo I don't quite understand what you mean by "if [it] produces a geometric series". It doesn't, really. If you're interested in $\lim_{k\to\infty}$ you should ask a follow-up question.
Comment: I suppose I've been led to expect certain behavior from my course. To confirm: n/2 + n/4 + n/8 + n/16...+ n/2^(k-1) is not a geometric series in the context of this problem?
Comment: @drshmoo You're summing $\log\log x$, not $x$. The inner part would be a geometric sum _if_ it were summed on its own.

Simplifying a log of a log


Baroque Performance Tips

Question: What are some recommendations for performing Baroque music?  My studio professor seems to think that I can improvise in the Baroque style as easily as breathing -- which is sadly not true.
The specific piece I'm performing is Marcello's Oboe Concerto in D minor (public domain score at this link at the Petrucci Music Library).
I am looking for help with the second movement.
Comment: Perfectly clear! I've heard that sort of ornamentational improvisation used in Handel's Messiah.  Thanks for the clarification!  If I'm not mistaken, that sort of improvising includes the addition of grace notes, turns and trills.  Best of luck!
Comment: By improvise, do you mean adopt a baroque style or actually deviate from the written notes and improvise music?
Comment: The movement in question has straight 8th notes in a slow quarter = 60 meter.  So hitting all of the notes listed, but adding more in between.  ... is that a clear way to describe it?  I know what I mean, but I'm not sure it's how I want to describe it!
Comment: @user3169 As Kristina mentioned, that would be Ornamentation. And yes, it can be learned. There are a few tips and tricks but it's sort of in the range of improvisation because it is up to your discretion; certain things work in certain passages. Bach's music is a good ground to test this on, by the way.
Answer: Learning to improvise in the style that Baroque musicians used at that time is quite a deep field of study. It's what we call "historically-informed performance practice."
If you have a score that has the originally-published markings for turns, trills and ornaments, then there are specific rules on what notes to play. There is certainly room for a little improvising and using your own phrasing, but if you want to play like a Baroque musician (well, as well as we can tell from scholarship after 300 years) then you need to find a textbook resource for Baroque ornamentation.
The appropriate places in a Baroque score where you can more purely improvise are at cadenzas, which are usually performed at the end of a section where there is a fermata for the accompaniment and the soloist is allowed to "cut loose".
I happen to be friends with a college professor whose specialty is Baroque oboe. I'm going to ask him if he has any specific textbook references for Baroque ornamentation. If he gives me any, I'll post them here.
I would also suggest that you look for recordings that you know to be in Baroque historically-informed performance style, and listen to how the soloist ornaments their playing. If you can listen to a sample of the recording online, you can spot a Baroque performance because it won't be in standard A=440 tuning. Modern musicians who play Baroque instruments tune down one half-step or even a whole step for early Baroque, because that is near the tuning that people used 300 years ago. So although it's written in D minor, a historically-informed recording will be played on instruments that sound like they are playing the piece in D-flat minor or E-minor according to your tuning fork.
Comment: Thank you!  That sounds like good advice.  Also, thanks for the edit of the question.
Answer: Actually, that is a yes-yes. Research notes inegales for more information about the practice of purposefully "un-equalling" equally written note values for expressive effect. Baroque musicians were fond of employing double dotting and playing even figures unevenly.
Jazz is a descendent of Baroque music. Where do you think some of our earliest jazz styles came from? New Orleans. And what was one of the influential styles present in old New Orleans? The French Baroque and its improvisation conventions.
Comment: So you are drawing a comparison between *notes inegales* and jazz swing rhythm? I hadn't thought of that. I see your point! I think it was more of a coincidence rather than a logical evolution, though.
Answer: Improvisation is a skill that has to be learned and practiced, just like any other musical skill.
You can start with rhythmic variations of short phrases. For example, if a phrase contains consecutive sixteenth notes, then play a mix of eighth and sixteenth notes, possibly inserting a few quarter notes at resolution points.
You can also use the same rhythm of the phrase and change the order of notes.
Experimentation is the key. The great thing about music is that whatever we do with it, no-one gets hurt:)
I hope this helps.
Comment: You've evidently never heard of a trombone suicide. :P
Comment: I get the feeling that changing the rhythm of, using your example, straight 16th notes to a mix of 8th and 16th would be a no-no in Baroque, but I could be wrong.  But for jazz improv etc. I think that's excellent advice.  Thank you!

Baroque Performance Tips


NOIP Static IP address resetting with router

Question: I need a static IP address to access a client's website, which has a list of whitelisted IPs but rejects all others. This is great, except I have a Dynamic IP address and a Talk Talk router.
I registered for a free NOIP account, and created a host. I logged into my router, went to the DynDNS section and then entered my NOIP details, they synced with what was on record and I believed I had a static IP (Is this correct?).
Last week, our internet dropped out and our, apparently static, IP address changed. I logged into NOIP and manually reset it to the previous address. After pressing save NOIP showed the old IP that I wanted to use. Googling What's my IP still showed as the recent, new address so I logged into the router, and re-saved the DynDNS options with the NOIP username and password.
When it finished saving, the router showed the new IP address (not the old one that I was trying to re-use). When I refreshed the NOIP admin screen in my browser, it had also flushed the IP saved in NOIP and replaced it with the new one.
Is there anyway I can get it to re-use the old IP address?
Is NOIP behaving incorrectly or is it behaving exactly as expected?
Comment: Is NOIP a dynamic DNS service or a VPN service?
Comment: I am half inclined to just edit your first sentence out, but I'd rather just explain. Most questions come from someone who did something wrong and can't figure out what. You don't need to preface your question with it, and while it is admirable that you realize it, there can be nothing gained from saying it.
Comment: It offers Free Dynamic DNS – is that the correct service to have a static IP?
Comment: @kasperd It's a competitor to Dyn-DNS.
Comment: @Djave A dynamic DNS service cannot do that. What you are thinking of is called a VPN, that's a different thing. There are other options: A VPS, a proxy with a static IP, or a NAT64 with a static IP.
Answer: NOIP does not do what you want.
Some ways you might achieve what you want:

Purchase a VPN connection with a static IP at the other end
Purchase a static IP from your ISP

NOIP and other dynamic DNS services give you a way to dynamically sync your connection to your changing IP.
They in no way actually provide you with a static IP.

Dynamic DNS (DDNS or DynDNS) is a method of automatically updating a name server in the Domain Name System (DNS), often in Not Real Time, with the active DDOS configuration of its configured hostnames, addresses or other information.

So you did nothing wrong with your NOIP settings, you just picked the wrong service for what you want to achieve.
Answer: Best Answer - Call your ISP and get a static IP.
Other Options using a VPS with a static IP:

create a reverse proxy in Apache2 to access their site from the same IP address each time. Also this assumes the application is able to be behind a reverse proxy (trial and error).

This will disable their 'security' of whitelisting IPs by allowing anyone to access their website via the reverse proxy, so you could set your IP address or dynamic-hostname in the allow from field, similar method of what you are trying to do.

Purchase a VP
Install APACHE
Load a standard reverse proxy config (using 10.4.3.2 as VPS IP)

    ProxyRequests Off
    ProxyPreserveHost On
    ProxyPass / http://188.8.131.52/

    <Proxy *>
            Order deny,allow
            Allow from dynamicIP.example.org
    </Proxy>

    <Location />
            ProxyPassReverse /
            RequestHeader unset Accept-Encoding
    </Location>

And then point DNS for the website (example.com) to your new IP 10.4.3.2
either create the specific zone in local dns
www.example.com IN A 10.4.3.2

Or Hosts File
10.4.3.2 www.example.com

Forward Proxy, you can do this with socks5 with putty/ssh easily or install a proxy like squid, this will set your source IP to the same, I use firefox's OS independent proxy settings for this purpose, and then chrome for general web access.

Good Luck!
Comment: Thanks so much for your answer. The simplest choice sounds best and I've just gone with the ISP option!