Load contents of alexa php results with parameters into html page - Maybe using jquery or ajax

Question: I'm trying to load the alexa rank of a website as a piece of text into a standard html file.  I want to avoid setting up the whole page as php so I've created a php file called rank.php which works
<?php
$url=$_GET["url"];
$xml = simplexml_load_file('http://data.alexa.com/data?cli=10&dat=snbamz&url='.$url);
$rank=isset($xml->SD[1]->POPULARITY)?$xml->SD[1]->POPULARITY->attributes()->TEXT:0;
echo $rank;
?>

I can load this to my server and call it with something like rank.php?url=google.com
This returns a number on the screen (in this case 1). So how do I get that number into a normal
 tag in a html document.
Ie
Alex rank:

I'm looking into jquery and using the get method but I'm getting lost.
eg putting this in the  tags

Then in my html page adding

Alex rank:

doesn't work for me.
I've also tried adding the following script within the

 tag.

I just want a simple solution to pull that number across.
Any help greatly appreciated.
Answer:  jQuery.ajax({
    url: 'code/rank.php?url=google.com',
    type: 'get',
    dataType: 'text/html',
    success:function(data)
    {
        alert(data);
        document.write(data);
        }
 });

I made some tests - and it seems that this is a culprit:
dataType: 'text/html'
Why:
in documentation of jQuery - at http://api.jquery.com/jQuery.ajax/
dataType allowed values:

"xml"
"html"
"json"
"jsonp"
"text"
multiple, space-separated values

I tried
dataType: 'text'
Worked for me.
Be sure to put your script tag after  if you are executing it inline of your page

Alexa rank:

But cleaner way to do it:

Alexa rank:

In this last code I am using cache: false because I feel it is good for this case. I am using dataType: 'text' because you are expecting just a number - so why not? It just fells more KISS for me. Perhaps it will work with 'html'.
By the way - there can be another place where another mistake can be hidden:
code/rank.php?url=google.com
If you current URL is
www.example.com/somefolder/
then it will be interpreted as
www.example.com**/somefolder/**code/rank.php?url=google.com
If your current URL is www.example.com/somefolder/another/
then it will be interpreted as
www.example.com**/somefolder/another/**code/rank.php?url=google.com
My advise - you can always use Firefox or Google Chrome Developer Tools > Network to see what is returning your ajax request - a '1' or 'PAGE 404 NOT FOUND' ^_^
     jQuery.ajax({
        url: 'code/rank.php?url=google.com',
        type: 'get',
        dataType: 'text/html',
        success:function(data)
        {
            alert(data);
            document.write(data);
            }
     });
I made some tests - and it seems that this is a culprit:
dataType: 'text/html'
Why:
in documentation of jQuery - at http://api.jquery.com/jQuery.ajax/
dataType allowed values:

"xml"
"html"
"json"
"jsonp"
"text"
multiple, space-separated values

I tried
dataType: 'text'
Worked for me.
Be sure to put your script tag after  if you are executing it inline of your page

Alexa rank:

But cleaner way to do it:

Alexa rank:

In this last code I am using cache: false because I feel it is good for this case. I am using dataType: 'text' because you are expecting just a number - so why not? It just fells more KISS for me. Perhaps it will work with 'html'.
By the way - there can be another place where another mistake can be hidden:
code/rank.php?url=google.com
If you current URL is
www.example.com/somefolder/
then it will be interpreted as
www.example.com**/somefolder/**code/rank.php?url=google.com
If your current URL is www.example.com/somefolder/another/
then it will be interpreted as
www.example.com**/somefolder/another/**code/rank.php?url=google.com
My advise - you can always use Firefox or Google Chrome Developer Tools > Network to see what is returning your ajax request - a '1' or 'PAGE 404 NOT FOUND' ^_^
Answering comment:
Yes, you've got the gist of it right.
Here is one way how you could implement it
(it would be comfortable for my way of thinking and organizing code):

Alexa rank for google.com:

Alexa rank for yandex.com:

        Alexa rank for stackoverflow.com (press button to get rank):

    Press this button to update rank

Comment: Brilliant thanks.  I may have had a few errors in there but the Developer Tools > Network put me on the right track.  I'm doing a redesign of my live site and don't want to load anything to the server yet but I had to to get the php aspect working.  I had a local copy of jQuery and like an idiot I hadn't loaded it to the server.  All working now thanks.
Comment: I have a follow up question. Is there a way to extend to to any url by passing a value to the function.   Something like.                                                               ``
Comment: I added "Answering comment:" to the answer.


Signal processing: How to patch over dip in signal using R?

Question:
I am a biologist starting to use R to analyze my data.

Could anybody please help me solve my problem I encountered when working in signal processing in R?
Problem
I have a recording of a signal in a form of 2 columns (x=row number, y=intensity) with some well defined drops in the signal.

I would like to bridge these drops using a simple line anchored at the manually selected endpoints as shown below.

I can manually get coordinations of the end points (X,Y).
Example data: exampleData
My idea of solution:
I go through the acquisition files, manually collect the start (X1,Y1) and end (X2,Y2) points coordinates for each acquisition, save as .csv file
Have a script which calculates line segments connecting these endpoints in form of two columns ranging from X1toX2 in row numbers, Y1toY2 in intensity.
Have a script replaces that the dip in the original data with the line segment.
What I do not know:
How to make a function which based on start ( X1, Y1)and end point (X2, Y2) coordinates generates X2-X1 rows with values from Y1 to Y2.
Notes:
I have some 50 files to go through.
There can be more dips in the signal in given acquisition file.
Example data here:
<code>dput(dataInput[1:2500,])
structure(list(X = 0:2499, Y = c(87, 87.3333, 86.3333, 85.6667,
85.3333, 86, 85, 84.6667, 85, 84, 83.6667, 83, 82, 82, 82.3333,
81.6667, 82.3333, 81.3333, 80.6667, 79.6667, 80.3333, 79.3333,
79, 79, 78.3333, 78.6667, 77.6667, 78, 77.3333, 78, 76.6667,
77, 76.3333, 75.6667, 75.3333, 74.6667, 75.6667, 74.3333, 73.6667,
74.3333, 74, 73.6667, 74.3333, 72.6667, 72.6667, 72.3333, 73,
72, 72.6667, 71.6667, 71, 71.3333, 71.6667, 70.6667, 70, 70.6667,
70.6667, 69.6667, 69.6667, 69, 68.6667, 68, 69, 68.6667, 68,
68, 66.6667, 67, 67.3333, 66.3333, 67, 66.3333, 66.3333, 66.6667,
66, 65.6667, 66, 65.3333, 65.6667, 64.6667, 65, 64.6667, 64.3333,
63.6667, 63.6667, 64, 64, 63.3333, 63, 63.3333, 62.6667, 62.6667,
62.3333, 62, 62.6667, 62, 61.3333, 61.3333, 61.3333, 61, 61,
61.6667, 61.3333, 61.6667, 60.6667, 60.6667, 60, 59.6667, 59.6667,
59.3333, 59.6667, 59.3333, 60, 58.3333, 58.6667, 58.3333, 59.3333,
59, 58, 58, 58, 57, 58.3333, 58.3333, 58, 57.3333, 57.3333, 57.3333,
58, 56.6667, 57, 56.6667, 56, 56.6667, 56, 56.6667, 56.6667,
56, 55.6667, 56, 55.6667, 54.3333, 55.3333, 55, 54.6667, 55.3333,
54.6667, 55, 54, 54.6667, 54.3333, 54.3333, 54.6667, 54, 54.3333,
53.6667, 54, 54, 52.6667, 53.6667, 53.3333, 53, 53.3333, 52.6667,
53, 53, 52.6667, 52, 52.3333, 52.3333, 52, 52.3333, 52, 52, 51.6667,
51.6667, 52, 51.3333, 50.3333, 50.3333, 52, 51.3333, 51.3333,
51, 50.6667, 51.3333, 51, 50, 51, 50.6667, 51, 50.6667, 50.6667,
50.6667, 50.6667, 50.3333, 50.3333, 51, 49.6667, 50.6667, 49.6667,
49.3333, 49.6667, 49.3333, 49, 49.6667, 49.3333, 49.3333, 48.6667,
48.6667, 48.6667, 48.6667, 48.6667, 48, 48, 48.3333, 49, 48.3333,
49, 48.3333, 48, 47.3333, 48, 48.3333, 47.6667, 47.6667, 47.6667,
48, 47.6667, 47.3333, 47.6667, 48, 47.6667, 47.3333, 46.3333,
47.3333, 47, 46.6667, 46.6667, 46.3333, 47, 46.6667, 46, 46,
46.6667, 47, 46.6667, 46.3333, 45.6667, 46.3333, 45.6667, 45.3333,
46, 46, 45.6667, 46.3333, 45.6667, 45.6667, 46.3333, 45, 45.6667,
45.6667, 45, 45.3333, 45.6667, 45.3333, 45.3333, 45, 44.6667,
45.6667, 44.6667, 45.3333, 44.3333, 45, 45, 45.3333, 45.3333,
44.6667, 44.6667, 44.6667, 45.3333, 44.6667, 44.3333, 43.6667,
44.3333, 44, 44.3333, 45, 43.6667, 44, 43.6667, 44, 44, 43, 43.6667,
43.3333, 44, 44.3333, 43.6667, 43.3333, 43.6667, 43.3333, 44.3333,
43.3333, 43.3333, 43, 43.3333, 44, 42.6667, 43.3333, 43.6667,
43, 43, 44, 42.6667, 43.6667, 43.3333, 42.6667, 43, 42, 41.6667,
42.6667, 42.6667, 42.6667, 42, 43, 41.6667, 42.3333, 42, 41.6667,
41.6667, 41.6667, 41.3333, 42, 41.6667, 42, 42, 41.6667, 42,
42, 42, 41.3333, 41.6667, 42, 42, 41.3333, 41.6667, 41.6667,
41.3333, 40.6667, 41, 40.6667, 41, 41.3333, 41.6667, 41, 41.6667,
40.3333, 40.3333, 41.3333, 40, 41.3333, 40.3333, 41.3333, 40,
41.6667, 41.3333, 40.6667, 40.6667, 41, 40, 40, 40.6667, 40.3333,
41, 40.3333, 40.6667, 40.3333, 40.3333, 40, 40.6667, 40, 40.6667,
40, 40, 40.3333, 40, 40, 40, 40.3333, 39.6667, 39.6667, 39.6667,
40, 40, 40.6667, 40.3333, 40.6667, 39.6667, 40.3333, 39, 40,
40, 39.6667, 39.6667, 39.3333, 39.3333, 39.6667, 39.6667, 39.6667,
39.6667, 39, 39.6667, 39.6667, 39.3333, 39.3333, 40, 39.6667,
39.6667, 38.6667, 39.3333, 39.6667, 39, 38.6667, 39, 39, 39,
39, 39.3333, 39.3333, 39, 37.6667, 38.6667, 39, 39.3333, 39.3333,
39, 38.6667, 38.6667, 38.6667, 39, 38.3333, 39, 38.3333, 37.6667,
38, 39, 38.3333, 39, 38.3333, 38, 38, 38.6667, 38.3333, 39, 38,
38.3333, 38.3333, 38, 38.3333, 38, 38, 37.6667, 39.3333, 38.3333,
38.3333, 37.6667, 37.6667, 38, 37.3333, 37.6667, 37.6667, 37.6667,
38, 38, 38, 37.6667, 38, 38, 37.6667, 38, 37.3333, 37.3333, 37.3333,
37.3333, 37.3333, 37, 37, 37.6667, 37, 37.3333, 37.3333, 37.6667,
37, 37.6667, 37.6667, 37, 37, 37.3333, 37, 37.3333, 37, 36.6667,
37, 37, 37, 37.6667, 37.3333, 36.3333, 37.3333, 36.3333, 36.6667,
37, 37, 36.6667, 36.6667, 37, 36.6667, 37.3333, 36.3333, 36,
36.6667, 37, 36.3333, 36.3333, 37, 36.6667, 36.3333, 36.6667,
36.6667, 37, 37, 37, 36.6667, 36, 36.3333, 36.6667, 36.3333,
36.6667, 36.3333, 36.6667, 36.6667, 36, 36.3333, 36.3333, 36.6667,
36, 36.3333, 36, 36, 36.3333, 36, 36, 37, 36.6667, 36.3333, 36,
36, 36, 35.3333, 35.6667, 35.6667, 35.6667, 35.6667, 36.3333,
36.3333, 36, 35.6667, 35.6667, 36, 35.6667, 36, 35.6667, 36,
35.3333, 35.3333, 36, 35.3333, 35.6667, 36, 35.6667, 35.6667,
35.3333, 36, 36, 35.3333, 35, 36, 35.6667, 35.3333, 35.3333,
35, 35.6667, 35.3333, 35, 36, 36, 35.6667, 35.6667, 35.3333,
36.3333, 35.6667, 35.6667, 35.3333, 35.3333, 35, 35.6667, 35,
35.3333, 35.3333, 34.6667, 35, 35.3333, 35.6667, 35, 35.6667,
35.3333, 35, 35, 35, 35.3333, 34.3333, 35, 35, 35.3333, 35, 35.3333,
35, 35.6667, 35, 35, 34.6667, 35, 35.3333, 35, 35, 35, 34.3333,
34.6667, 35, 35, 35.3333, 35, 35.3333, 34.3333, 34.3333, 35,
35, 34.6667, 34.6667, 34.6667, 35.3333, 34.3333, 34.3333, 34.6667,
34.6667, 34, 28.3333, 28, 28.6667, 28, 28, 28, 27.6667, 28, 27.6667,
28.3333, 27.6667, 26.6667, 26, 25.3333, 25.3333, 25.6667, 25,
25.3333, 25, 25, 25.3333, 25, 24.6667, 25.6667, 25, 25, 25.3333,
24.6667, 24.6667, 24.3333, 25, 25, 25, 25, 24.6667, 25.6667,
25, 25, 25, 25.6667, 25, 24, 24.6667, 25, 24.6667, 25, 24.6667,
25.3333, 25.6667, 25, 25.3333, 24, 25, 24.3333, 25, 25, 25, 24.3333,
24.6667, 24.6667, 25, 24.3333, 24.6667, 24.6667, 24, 24.3333,
24.3333, 24.6667, 24, 24.3333, 24, 24.6667, 25, 25, 24.6667,
24, 27.6667, 30.3333, 30.3333, 30, 30.3333, 30.3333, 30.6667,
31.3333, 31.3333, 31, 31, 30.6667, 30.6667, 31, 31, 30.3333,
30, 31.6667, 30.3333, 31.6667, 31.3333, 30.6667, 31.3333, 31.3333,
30.6667, 31.3333, 30.6667, 31.3333, 31.6667, 32.3333, 32.3333,
31.6667, 31.6667, 32.3333, 31.6667, 32.3333, 32, 31.6667, 31.6667,
32, 31.6667, 32, 31.6667, 31.6667, 32, 32, 32, 31.6667, 31.6667,
31.6667, 32.3333, 31.3333, 31.6667, 32, 32, 32.3333, 32, 32.6667,
31.6667, 31.6667, 31.6667, 31.6667, 31.6667, 32, 32.3333, 31.6667,
31.6667, 32, 32, 31.6667, 31.6667, 31.3333, 31.6667, 31.3333,
32, 32.3333, 32.3333, 31.3333, 32.6667, 31.6667, 32.6667, 32.3333,
32.3333, 32.3333, 32.6667, 32, 32.6667, 32, 32, 32.6667, 33,
32, 32, 33, 32.6667, 32.3333, 32.6667, 32.6667, 32, 32.3333,
32.3333, 32.6667, 32.6667, 32.3333, 32.6667, 32, 32.6667, 32.3333,
32.3333, 31.6667, 32.3333, 32.3333, 33.3333, 32.3333, 32, 32.6667,
31.6667, 31.6667, 32.3333, 32, 32.6667, 32, 32, 32, 32.3333,
32, 32.6667, 32.6667, 32.3333, 33, 32, 32, 32.6667, 32.3333,
32, 32.3333, 32, 32.3333, 32, 32.3333, 32.3333, 32.3333, 32.3333,
32.3333, 32.3333, 31.6667, 32.3333, 32, 32.3333, 32.3333, 31.3333,
32.3333, 32.6667, 32.3333, 32.3333, 31.6667, 31.6667, 32, 31.6667,
32.3333, 32, 31.6667, 31.6667, 31.6667, 32.3333, 32, 31.6667,
31.3333, 32, 32.6667, 32.3333, 32, 32.3333, 32, 32.3333, 32.6667,
32, 31.6667, 32, 32.3333, 32, 32, 32.3333, 32.3333, 32, 32.3333,
31.6667, 31.6667, 32.3333, 32.3333, 32, 31.6667, 32.3333, 32.6667,
31.6667, 32, 31.6667, 32, 32, 32.3333, 32.6667, 31.6667, 31.6667,
32, 32, 32.6667, 31.6667, 32, 32.3333, 32.3333, 31.3333, 33.3333,
32.3333, 31.6667, 31.6667, 32.3333, 32, 32, 32, 32, 32, 32.3333,
32.3333, 32.6667, 32.3333, 32, 33, 32, 32.3333, 32.3333, 31.6667,
32, 32.3333, 31.6667, 32.6667, 32.3333, 31.3333, 32.3333, 32,
32.3333, 31.6667, 31.6667, 32, 32, 32.6667, 32, 31.6667, 31.6667,
32.3333, 32, 32.3333, 32.3333, 33, 32, 32.3333, 32, 32.6667,
31.6667, 32, 32, 32, 31.6667, 31.6667, 32.3333, 32.3333, 32,
32.3333, 32.3333, 32.6667, 31.6667, 32, 32, 32.3333, 32.6667,
32.3333, 32, 33, 32, 32.6667, 32.6667, 32.3333, 32.6667, 32.3333,
32, 32.3333, 32.6667, 32.3333, 32.3333, 32, 32.6667, 32, 32.3333,
32, 32.3333, 32, 32.3333, 32, 32.3333, 32, 32.6667, 32, 32.6667,
32.3333, 32.3333, 32.3333, 32, 32.6667, 32.6667, 32, 31.6667,
32.6667, 31.6667, 32.3333, 32.3333, 31.6667, 31.6667, 32, 32.3333,
32.3333, 32, 32, 32, 32.3333, 32, 32.3333, 31.6667, 32, 31.6667,
31.6667, 32.3333, 32, 32.6667, 32.3333, 33, 32.6667, 32.6667,
32.3333, 32, 32.3333, 32, 31.6667, 32, 32.3333, 32, 32, 32.3333,
32.6667, 32, 32, 32, 32, 32, 32.6667, 33, 32.3333, 32.3333, 31.6667,
31.6667, 32.3333, 31.3333, 32.3333, 32, 32, 31.3333, 31.6667,
32.3333, 32, 32, 31.3333, 32.3333, 32.3333, 32, 32, 32, 31.6667,
31.6667, 32, 32.3333, 31.6667, 32.3333, 32.3333, 31.6667, 32,
32.3333, 32.3333, 31.6667, 31.6667, 32, 33, 31.3333, 31.6667,
31.6667, 32, 32.3333, 31.3333, 32, 31.6667, 32.3333, 32, 32,
32, 31.6667, 32, 32, 31.6667, 32, 31.6667, 32, 31.6667, 32, 32,
31.6667, 32, 31.6667, 32, 31.6667, 32, 32, 32, 32.3333, 31.6667,
31.6667, 32, 32, 32.3333, 32.3333, 31.6667, 32, 32.3333, 32,
31.6667, 32.3333, 31.6667, 32, 32.3333, 32, 32, 32, 31.6667,
32.6667, 32.3333, 32.6667, 32, 32, 32.6667, 32.3333, 32.3333,
32, 32.3333, 32, 32, 32.6667, 32.3333, 32, 33, 32.3333, 32, 32.3333,
31.6667, 32.3333, 32, 32.6667, 31.6667, 32, 32, 31.6667, 32.3333,
32, 32.3333, 31.6667, 32.3333, 32, 32.3333, 32, 32, 32.6667,
32, 31.6667, 32, 32, 32, 32.3333, 31.6667, 32, 32.3333, 32, 31.6667,
32.3333, 32.6667, 32.3333, 32.3333, 32.3333, 32.3333, 31.6667,
32.6667, 31.6667, 33.3333, 32, 32, 32.3333, 32.6667, 32.3333,
31.6667, 32, 32, 31.6667, 32, 33, 31.6667, 32.3333, 33, 32.3333,
32.3333, 32.3333, 32.3333, 32.3333, 32.3333, 32.6667, 31.6667,
32.3333, 32, 32, 32, 31.3333, 32.3333, 31.6667, 32.3333, 31.6667,
32.3333, 32.3333, 32.3333, 32, 32, 31.6667, 31.6667, 32, 32.3333,
32.3333, 32, 31.6667, 32.6667, 32, 32, 32.6667, 32.6667, 32.3333,
31.6667, 31.6667, 32, 32, 32, 31.3333, 32.6667, 32.6667, 32.3333,
32, 32.6667, 32.3333, 32, 31.6667, 32, 32.3333, 32, 32.6667,
32, 31.6667, 32, 31.6667, 32, 32.3333, 32, 31.6667, 32, 32.6667,
32.3333, 32.3333, 31.6667, 32, 31.6667, 32, 32, 32.3333, 32.3333,
32, 32.3333, 32.6667, 32, 32.3333, 32, 32.3333, 32.6667, 32.6667,
32, 32.3333, 32.3333, 32, 32.3333, 32, 32, 32.6667, 32, 32, 32,
32, 31.6667, 32.6667, 32.3333, 32.6667, 32, 32, 32, 33, 32, 32.3333,
32.3333, 32, 32.3333, 32.3333, 32.6667, 32.3333, 31.6667, 32.3333,
31.6667, 32.6667, 32.6667, 33, 32.3333, 32.3333, 32.3333, 32.6667,
32.6667, 32.3333, 32, 32, 32, 32, 32, 32, 32.3333, 31.6667, 32,
32.3333, 32.3333, 32.3333, 33, 31.6667, 32, 32, 32, 32.3333,
31.6667, 32.6667, 32.6667, 32, 32, 32, 32, 32.6667, 32.6667,
32.3333, 32.3333, 32.3333, 32, 32.3333, 32.3333, 32, 32, 32.3333,
31.6667, 31.6667, 32.3333, 32.6667, 32, 33, 32.3333, 31.6667,
27.6667, 27.3333, 26.6667, 26, 26.3333, 26.3333, 26, 26.3333,
26.3333, 26, 26.3333, 25.3333, 24.6667, 24, 23.6667, 23.6667,
24, 23.6667, 24, 24, 24, 23.6667, 23.6667, 23.6667, 23.6667,
24, 24, 24, 24, 24, 24.3333, 24, 24, 23.6667, 23.6667, 23.6667,
24, 23.3333, 24, 24, 24.3333, 23.6667, 23.3333, 23.6667, 23.6667,
23.6667, 24, 24.3333, 24, 23.6667, 23.3333, 24, 23.6667, 24,
24, 24, 23.3333, 23.3333, 23.3333, 23.3333, 23.6667, 24, 23.6667,
24, 23.6667, 24, 24, 23.6667, 24, 24, 24, 24, 24, 23.6667, 23.6667,
24, 25, 29, 29.3333, 29, 29, 29, 29.6667, 29.6667, 30, 30, 29.6667,
29.6667, 30, 29.6667, 29.6667, 30, 30.3333, 30, 29.6667, 29.6667,
29.6667, 30, 30, 30, 30, 30.3333, 29.6667, 29.6667, 30, 31, 31,
31.3333, 30.6667, 31.3333, 31.3333, 31, 31.3333, 29.6667, 31,
30.6667, 31.6667, 30.6667, 31, 31, 31.3333, 30.3333, 30.6667,
31.3333, 31, 31.6667, 30.6667, 31.3333, 31.3333, 31.3333, 31.6667,
30.6667, 31.6667, 31.3333, 31.3333, 31.3333, 31.3333, 31.3333,
31, 31, 31.6667, 31.6667, 31.6667, 31.3333, 31, 30.6667, 31.3333,
30.6667, 31.3333, 31.3333, 31.6667, 31.6667, 30.6667, 31, 31.6667,
31.3333, 32, 32.3333, 31.6667, 32, 31.6667, 31.6667, 31.6667,
31.3333, 31.3333, 32.3333, 31.6667, 31.6667, 32, 31.6667, 31.6667,
32, 31.6667, 32.3333, 31.6667, 32.3333, 32, 32.3333, 31.3333,
31.6667, 32, 31.3333, 32.3333, 32.3333, 32, 32.6667, 32, 32.3333,
32, 32.3333, 32.3333, 32.6667, 32, 31.6667, 32, 32, 32.6667,
32, 32.3333, 32.3333, 32, 31.6667, 32.3333, 32, 31.6667, 31.3333,
31.6667, 32.3333, 32, 32.3333, 32, 32.3333, 32.3333, 32.3333,
32.6667, 32, 32, 32, 32, 31.6667, 32.3333, 32.3333, 32.3333,
31.6667, 33, 32.3333, 32, 32, 32.3333, 31.3333, 33, 33, 32.6667,
32.3333, 32, 33, 32.3333, 32.6667, 32.6667, 32.6667, 33, 32.6667,
33.6667, 32.6667, 33, 32.6667, 32.6667, 33.3333, 33, 33.3333,
33.6667, 33, 32.6667, 33, 33.3333, 33, 33.3333, 33.6667, 33.3333,
33, 33, 34.3333, 33.3333, 33.6667, 33.6667, 33, 33.6667, 33.6667,
33.6667, 33.6667, 34.3333, 34, 34, 34.3333, 33.6667, 33.6667,
34.3333, 34, 34, 34.3333, 34.3333, 35, 34, 33.6667, 35, 34.3333,
34.3333, 34.6667, 34.6667, 35.6667, 34.6667, 35, 35.3333, 35,
35.6667, 34.6667, 35.6667, 35.6667, 36, 35.6667, 36.6667, 36,
36, 37, 37.6667, 39, 40.3333, 43.3333, 47.6667, 52, 53.3333,
55.6667, 57.6667, 58, 58.6667, 60.6667, 61, 61.6667, 62, 61.6667,
62.6667, 62.6667, 63.3333, 63, 64, 64.6667, 64.3333, 64.3333,
65, 65.3333, 65, 66, 66.6667, 66, 67, 67, 67.3333, 68.3333, 67.3333,
67.6667, 68.3333, 67.6667, 68.3333, 68.3333, 68.3333, 69, 68.6667,
68.6667, 69.6667, 69.3333, 70, 69.6667, 70.3333, 71, 71.3333,
70.6667, 72, 72, 72.3333, 71.6667, 71.3333, 72, 72.3333, 72.6667,
72, 72.6667, 74, 74.3333, 74, 74, 74.3333, 74.3333, 74.3333,
74, 74.6667, 74, 75.3333, 74.3333, 75.6667, 74.6667, 75.3333,
75, 75.6667, 76, 75.6667, 75.3333, 76.6667, 76.6667, 77.3333,
76.3333, 76.3333, 77, 77.6667, 77.6667, 76.6667, 78, 77.6667,
78.6667, 78.3333, 77.3333, 78.3333, 77.6667, 78.6667, 79, 78.3333,
79, 79, 79.3333, 79, 79.3333, 78.6667, 79.3333, 79.6667, 79.3333,
80, 80, 80, 80, 81, 80.3333, 80, 80.3333, 80.6667, 79.6667, 80,
80.6667, 81.6667, 81, 80.3333, 81, 81.6667, 82, 81.3333, 82,
82.3333, 81.3333, 81.3333, 82, 81.6667, 82, 81.6667, 83.3333,
83, 82, 82.3333, 83.3333, 83.3333, 83.3333, 83.3333, 83, 83,
84.3333, 83.3333, 83.6667, 83.3333, 83, 83.6667, 84, 84.3333,
84.3333, 84, 84, 84, 82.6667, 84.6667, 84.6667, 85, 85, 84.6667,
84.3333, 84.6667, 85.3333, 84.3333, 85.3333, 85.3333, 85.3333,
85, 84.6667, 85.6667, 86.3333, 85.3333, 86.3333, 86, 85.3333,
85.3333, 86, 85.3333, 86, 87, 86.6667, 85.3333, 86.6667, 87,
86, 86.6667, 87.3333, 87, 87.6667, 86.6667, 86.3333, 86.3333,
87.3333, 87, 88, 86.6667, 87.6667, 87.3333, 87.6667, 88, 87.3333,
87.3333, 87.3333, 87.6667, 88, 88, 87.6667, 88.3333, 87.6667,
87.6667, 87, 88, 87.6667, 87.3333, 88, 87.3333, 87.6667, 88.3333,
88.3333, 88, 88, 87.3333, 88.3333, 88.6667, 88.3333, 88.3333,
88, 89.3333, 89.3333, 89, 88.6667, 88.6667, 88, 89, 88.6667,
89.6667, 89.3333, 89, 89.3333, 89.6667, 88.6667, 88.3333, 89,
89, 89.3333, 89.6667, 89.6667, 89.3333, 89.3333, 88.6667, 89,
88.3333, 90, 88.3333, 90.3333, 89, 89.6667, 90, 89.3333, 89,
89.6667, 88.6667, 89, 88.6667, 89.6667, 89.3333, 88.6667, 88.6667,
88.6667, 88, 88, 87, 87.6667, 87, 86.6667, 86.6667, 86.3333,
86, 85.6667, 85.3333, 84.3333, 83.6667, 84, 83, 82.6667, 82.6667,
82.6667, 82, 82.3333, 81.6667, 80.6667, 80, 80.3333, 80, 79.3333,
78.6667, 79, 78, 78, 78, 77, 77, 76.3333, 75.6667, 77, 75.6667,
74.6667, 75.3333, 75, 74.3333, 73.3333, 73.6667, 73, 72.3333,
72.3333, 72.6667, 72.3333, 71.6667, 71, 70.3333, 71.3333, 71,
69.6667, 70, 69.3333, 69.3333, 69, 68.3333, 68.6667, 68.3333,
68, 67.6667, 67.3333, 67.6667, 67, 66.6667, 67, 67, 66, 65.6667,
66, 65.3333, 65.3333, 64.6667, 64.6667, 64.6667, 63.3333, 64,
64.6667, 64, 64, 63.3333, 62, 63, 63, 62, 61.6667, 61.6667, 62,
61.6667, 60.3333, 61, 61.3333, 60, 60.6667, 59.3333, 59.6667,
60, 59.6667, 59.6667, 59.3333, 59.3333, 59.3333, 58.6667, 58,
58.3333, 57.6667, 58, 58, 57.3333, 57, 57.3333, 57, 57, 56.3333,
56.3333, 56.6667, 56, 57, 57, 55.3333, 55, 56.3333, 55.3333,
55.6667, 55.3333, 55.3333, 55.3333, 55, 54, 54.6667, 54, 54,
54.6667, 53.6667, 54, 54, 54, 53, 53, 53, 53, 52.3333, 53, 52.3333,
52.3333, 52, 52.6667, 52.3333, 51, 51.6667, 51.6667, 52, 51.3333,
51.3333, 51, 51, 50.6667, 50.6667, 50.6667, 50.6667, 50.3333,
50.6667, 50.6667, 50, 50.3333, 50, 50.6667, 50, 50, 49.3333,
49, 49.3333, 49.3333, 49, 48.6667, 49, 49.3333, 48.6667, 48.3333,
48.3333, 49, 49, 49, 48.6667, 48.3333, 48.3333, 48, 48, 47.3333,
48, 48, 47, 47, 48, 47.6667, 46.6667, 46.6667, 47.6667, 47.3333,
47, 46.6667, 47.3333, 47, 46.3333, 46, 46, 46, 46.3333, 46.3333,
46, 46, 45.6667, 46, 46.3333, 46, 45.3333, 45.6667, 45.6667,
45.6667, 44.6667, 45.3333, 45.6667, 45.3333, 45.3333, 44.6667,
45, 45, 44.6667, 44.6667, 45, 44.6667, 44.3333, 44, 44.3333,
44.3333, 43.3333, 44.3333, 44, 43.6667, 44, 44, 43.6667, 43.6667,
44, 43.3333, 43.6667, 43.6667, 43.6667, 43.3333, 43, 42.6667,
43.3333, 43.3333, 43.3333, 43, 43.3333, 42.3333, 43, 42.6667,
42.3333, 43, 42.6667, 43, 42.3333, 42.3333, 42.3333, 42.3333,
42.6667, 42.6667, 42.3333, 42.3333, 42.3333, 41.6667, 41.6667,
42, 41.6667, 41.6667, 42.6667, 41.6667, 41, 41.3333, 42, 41.6667,
42, 42, 41.6667, 41.3333, 41.6667, 41.3333, 41, 35.6667, 33.6667,
33.6667, 32.6667, 33.3333, 32.3333, 32.6667, 32.6667, 32.3333,
32, 32.6667, 31.6667, 30, 29.6667, 30, 29.3333, 29.6667, 29.6667,
29.3333, 28.3333, 28.6667, 29.6667, 29.6667, 28.6667, 29, 28.6667,
29.3333, 29, 28.3333, 29, 28.6667, 29, 28.3333, 29.3333, 28.6667,
28.3333, 29, 28, 28.3333, 29, 28.3333, 28, 28.6667, 28.3333,
28.3333, 28.6667, 28, 28, 28, 27.6667, 28, 28, 28, 28.3333, 28.3333,
28, 28, 28.3333, 28, 27.6667, 28, 27.6667, 27.6667, 27.6667,
27.6667, 27.3333, 28, 27.3333, 27.6667, 27.6667, 27.3333, 27.6667,
27.3333, 28, 27.6667, 27.6667, 32.3333, 33.6667, 33.6667, 34.3333,
33.6667, 33.3333, 34.3333, 34.3333, 34.6667, 34, 34.6667, 34.3333,
34.3333, 34.3333, 34, 34.6667, 34.6667, 34.3333, 34.3333, 34,
34.3333, 34, 34.6667, 34.3333, 34.3333, 34.3333, 34.6667, 34.3333,
35, 35.3333, 35.3333, 36, 35.6667, 35.6667, 35.6667, 35.3333,
35.6667, 35.3333, 35, 35, 35.6667, 35.6667, 35, 35, 35.6667,
35.3333, 35, 35, 35.3333, 34.6667, 35.3333, 35, 35.6667, 35.3333,
34.6667, 35, 34.3333, 35.3333, 35, 34.6667, 34.6667, 35.6667,
35.3333, 34.3333, 35, 34.6667, 35, 34.3333, 34.6667, 34.3333,
34.3333, 34.6667, 34.3333, 34.6667, 34.3333, 34.6667, 35, 35,
34.6667, 34.6667, 34.3333, 34.3333, 35, 34.6667, 35, 34.6667,
34, 35, 34.6667, 34, 34.6667, 34.6667, 34, 34.6667, 34.6667,
35, 34, 34.3333, 34.3333, 34, 34.3333, 35, 34.3333, 34.6667,
34.3333, 34, 34.6667, 33.6667, 34, 34.3333, 34, 35, 35, 34.6667,
34, 33.6667, 35, 34.3333, 34.3333, 34.3333, 34, 34.3333, 34.3333,
34, 34, 33.6667, 34.3333, 34.3333, 33.3333, 34.3333, 34, 34.3333,
34.3333, 34, 34, 34, 34, 33.6667, 34.6667, 34, 34, 33.6667, 34.6667,
34, 33.6667)), row.names = c(NA, 2500L), class = "data.frame")
</code>
Comment: Dear whuber while it would be nice to have the detection automated, it is not what I am after. I would be sufficiently happy with detecting and recording the start and end points of the dropouts manually and just patch over the dips automatically based on them. thanks
Comment: Your solution of "bridging the line" does not appear to be well-defined. For instance, applying it to your data (the first 2500 points) would cause you to extend a horizontal line from (655, 34.6667) all the way to (1697, 34.6667), thereby obliterating an extended portion of your signal that spans *two* drop outs. Is that really what you want? Although many solutions are possible that will work for the example data, it would be better to develop them based on some understanding of what this signal means and what causes the drop-outs: that would assure their applicability in the other 49 cases.
Comment: Hello,
thank you for your comment.
I need to bridge over these gaps in order to feed it into another peak detecting programme (clampfit) which I use to define width of the peak, its height, and some more parameters. However these dips in the signal does not allow the following programme to process it. The dips in the signal were caused by malfunctioning mirror in our microscope, which was later fixed,but I would still like to squeeze results even from these imperfect data.
Comment: Hello,
Thank you for your attention, I guess I did not describe it clearly.
I need to span each drop out with a line, not necessarily horizontal line, so in the case of the first arrow would go from 1400 to cca 1600 in X axis, would be horizontal in this case, but not in each, the endpoints would be selected manually. Hope it makes it clearer.
Comment: Since the selection is manual, would it be fair to say your question concerns only *detecting* the signal dropouts?
Answer: Although it is difficult to determine general behavior from one dataset, it looks like these data would be amenable to a simple, robust analysis that looks for sudden drops followed a little later by a sudden rise.  (I adopt the language of time series analysis in which row numbers are viewed as succeeding points in time.)
To find a drop, predict the data in a robust way.  A moving (windowed) median will do nicely, perhaps of width 5 through 50.  Sufficiently large negative discrepancies between actual and predicted values (the "residuals") will indicate drops.  The rises can be discovered by reversing the series and looking for its drops, obviating any need to code two algorithms.
The main challenge to automating this lies in estimating how large a "sufficiently large" drop must be.  In this case, because the signal is discrete (all values are multiplies of 1/3), a tabulation of the residuals reveals a few extreme values that appear only a few times: those are the candidates for further examination.
These candidates must be post-processed to combine quick successions of drops into the first drop in each sequence and to eliminate the "false" drops and rises created by rapid decreases or increases (respectively) in the valid part of the signal.
Here is a plot of the data with the drops marked in red, the rises in blue, and the data in between each such pair (corresponding to the invalid signal) in gray.  No tuning or manual intervention was performed.  The window width was 41 rows, but any window larger than 4 yet smaller than the durations of the bad signals will work fine with this dataset.  Whether this approach works with your other datasets will depend on whether I have guessed correctly at the nature of the signal dropouts.

For further details, consult this <code>R</code> code used to produce the figure.  It references the data as a data frame <code>X</code> having fields <code>X</code> and <code>Y</code>.  It adds a third field <code>Y.hat</code> equal to the good data and otherwise containing <code>NA</code> (missing) values for the signal dropouts it detected.
<code>#
# Plot the data.
#
with(X, plot(X, Y, type="l", ylim=c(0,100), bty="n", col="#00000040", xlab="X", ylab="Y",
             main="Data and Gaps"))
#
# Find the sudden drops in both directions.
#
drops <- function(x, w=1) {
  require(zoo)
  #
  # Smooth the differences.
  #
  dx <- c(0, diff(x))
  r <- rollapply(dx, 2*w+1, median, align="right", fill=NA)
  #
  # Identify the extreme differences.
  #
  counts <- table(r <- round(r - dx, ceiling(-log10(range(x)))+2))
  i <- as.numeric(names(table(counts)))
  u <- min(which(diff(i) > 1))
  thresholds <- as.numeric(names(counts)[counts < u])
  upper <- min(thresholds[thresholds > 0])
  #
  # Return the indexes where those extreme drops occur.
  #
  which(r >= upper)
}

w <- 20 # Specify the half-window size.
i <- drops(X$Y, w)
j <- rev(nrow(X)+1 - drops(rev(X$Y), w))
#
# Look for drop/rise pairs.
#
if (min(j) < min(i)) i <- c(1,i)
if (max(i) > max(j)) j <- c(j, nrow(X))
ij <- sort(c(i,j))

inds <- c(rep(0, length(i)), rep(1, length(j)))[order(c(i,j))]
i.drops <- ij[which(c(inds,1)==0 & c(1,inds)==1)] # First 0-->1
i.rises <- ij[which(c(inds,1)==1 & c(1,inds)==0)] # Last 0-->1

abline(v=X$X[i.drops], col="Red")
abline(v=X$X[i.rises], col="Blue")
#
# Remove the intervals between drop/rise pairs from the data and plot them in gray.
#
X$Y.hat <- X$Y
for (k in seq_along(i.drops))
  X$Y.hat[i.drops[k]:i.rises[k]] <- NA

lines(X$X, X$Y.hat)
</code>
Comment: Hello and thank you whuber, looks very useful. I will try to apply to my dataset and see how it works. Thanks very much:)


Couldn't get the reason for the fault in the code

Question: This is a program to print the smallest value and its position in an array (defined by user).
#include <stdio.h>
int position_smallest(int a[],int n)
{
    int smallest = a[0];
    int i,k;
    for(i=0; i<=n-1; i=i+1)
    {
        if(a[i]<a[0])
        {
            smallest = a[i];
            k = i;
        }
    }
    printf("The smallest value is %d\n", smallest);
    printf("It's position is %d\n", k);
    return 0;
 }

int main()
{
    int n,j;
    int a[n];
    printf("Enter the size of the array: ");
    scanf("%d", &n);
    for(j=0; j<=n; j=j+1)
    {
         printf("a[%d] = ", j);
         scanf("%d", &a[j]);
    }
    position_smallest(a,n);
}

But upon running it, it shows following error:
Segmentation fault (core dumped)

What can be the possible reason(s) for it?
Comment: For a start you create an array of size n but n is uninitialised at the time.
Comment: First of all, Your array `a`'s size is `n` and `n` has no value until u get input.
Comment: You can't go from 0 to `n` inclusive but exclusive so try `j < n`. Let me know if this helped you.
Comment: And that's why my compiler can't compile it when there array `a`'s size is n.
Answer: First error, as stated in one of the comments, is declaring an array of size n before even knowing how much n is.
Second mistake is for loop in your main function that goes from 0 to n, i.e. index of an array is out of bounds.
Try this:
int main() {
    int n = 0, j = 0;
    printf("Enter the size of the array: ");
    scanf("%d", &n);

    int a[n];

    for (j = 0; j < n; j++) {
        printf("a[%d] = ", j + 1);
        scanf("%d", &a[j]);
    }
    position_smallest(a,n);
}

If this solved your problem, please mark it.
Comment: The second error does not exist. The OP's condition i <=n-1 is equivalent to your i<n. EDIT: whoops,  I was looking at the testing loop, while the error is in the filling loop.
Answer: First of all:
int n, j;

both uninitialized. Initialize them otherwise you will get garbage values.
int n = 0, j = 0;

What happens if n by chance (very likely) is 0 in following line?
int a[n];

You allocate 0 bytes for array a[]. You then enter 10 in following line
scanf("%d", &n);

You will get segmentation fault in for() loop below because your loop is trying to put 10 elements where you allocated no memory at all.
What happens if uninitialized n by chance (very likely) is 2^32 * 4 bytes (ints max)?
int a[n];

You allocate 2^32 bytes for array a[]. You then enter 10 in following line
scanf("%d", &n);

You will not get segmentation fault but you will allocate 2^32 * 4 bytes of memory for your program and you will use only 10
Second if that is not enough:
for (j = 0; j <= n; ++j)
    scanf("%d", arr[n];

will access 11th element of array which is undefined behavior, and you might even get segmentation fault there. As you know arrays in C arrays are indexed from 0 to n - 1 (if n is size of array).
Third your loop inside function:
for(i=0; i<=n-1; i=i+1)

is the same as:
for(i=0; i < n; ++i)

And finally, you have a bug in your code, I believe:
if(a[i]<a[0])

should be:
if (a[i] < smallest)

because it is most likely that you would like compare other number to already smallest element not to a[0]. Here is my code
#include <stdio.h>

int position_smallest(int a[],int n) {
    int smallest = a[0];
    int i = 0, k=0;
    for(i=0; i<n; ++i) {
        if(a[i]<smallest) {
            smallest = a[i];
            k = i;
        }
    }
    printf("The smallest value is %d\n", smallest);
    printf("It's position is %d\n", k);
    return 0;
}

int main() {
    int n=0, j=0;
    printf("Enter the size of the array: ");
    scanf("%d", &n);
    int a[n];

    for(j=0; j<n; ++j) {
        printf("a[%d] = ", j);
        scanf("%d", &a[j]);
    }
    position_smallest(a,n);

    return 0;
}

The version above is legit for C99 and up standards. If you are using C89 and earlier compilers you are stack with fixed size as mentioned in @Saurabh's answer or preferably use malloc().
Here is malloc() version:
#include <stdio.h>
#include <stdlib.h>

int position_smallest(int a[],int n) {
    int smallest = a[0];
    int i=0,k=0;
    for(i=0; i<=n-1; i=i+1) {
        if(a[i]<smallest) {
            smallest = a[i];
            k = i;
        }
    }
    printf("The smallest value is %d\n", smallest);
    printf("It's position is %d\n", k);
    return 0;
}

int main() {
    int n=0, j=0;
    printf("Enter the size of the array: ");
    scanf("%d", &n);
    int *a = malloc(sizeof(int) * n);

    for(j=0; j<n; j=j+1) {
        printf("a[%d] = ", j);
        scanf("%d", &a[j]);
    }
    position_smallest(a,n);

    return 0;
}

Comment: Thanks @Gox for giving knowledge to me about a new function `malloc()`. I didn't knew it before your answer.
Answer: Use this one:
#include <stdio.h>

int position_smallest(int a[],int n)
{
    int smallest = a[0];
    int i,k;
    for(i=0; i<=n-1; i=i+1)
    {
        if(a[i]<a[0])
        {
            smallest = a[i];
            k = i;
        }
    }
    printf("The smallest value is %d\n", smallest);
    printf("It's position is %d\n", k);
    return 0;
}

int main()
{
    int n,j;
    int a[100];
    printf("Enter the size of the array: ");
    scanf("%d", &n);
    for(j=0; j<n; j=j+1)
    {
        printf("a[%d] = ", j);
        scanf("%d", &a[j]);
    }
    position_smallest(a,n);
}

Specify the size of the array anything but run the loop according to user's input.
And there is some problems in your function position_smallest. So if you want correct it then take a look at @Gox's answer.


jedis usage in servlet

Question: <code>import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import redis.clients.jedis.*;
public class Welcome extends HttpServlet
{
Jedis jedis;

public void init(ServletConfig sc) throws ServletException
{

        Jedis jedis = new Jedis("localhost");
}
public void doGet(HttpServletRequest request,HttpServletResponse response)throws IOException,ServletException
{
int count=0;
PrintWriter out=response.getWriter();
jedis.set("k1","123");//This statement is not working
}
public void destroy(){}
}
</code>
I have been trying to access keys and it's values in redis using jedis. It works fine with normal java code. but when it comes to servlets it's not working. I can't able to find the reasons. Pls answer me in detail that how can i use jedis.set() in servlets.
Comment: You aren't setting the instance variable `jedis`. The `init` callback is instantiating `Jedis` and assigning it to a local variable, not the instance variable. Change `Jedis jedis = new Jedis("localhost");` to `jedis = new Jedis("localhost");` or `this.jedis = new Jedis("localhost");` to be clearer
Answer: Even so, We should not use Jedis object as an instance variable, because of thread safety. Instead of this, We use connection object in ServletContext by implementing ContextListener or resource injection. I think that we always consider thread safety when using Servlet instance. A single Jedis instance is not threadsafe! or; use JedisPool. it is thread safe.
JedisPool pool = new JedisPool(new JedisPoolConfig(), "localhost");

jedis usage in servlet


Adding a border/outline to buttons in android studio

Question: I would like to add a border to a button.
I have tried the usual stuff i.e creating a drawable file and referencing that in the xml file. But this does not seem to be working. Anyone know why?
Here is my XML code for the button:
<Button
        android:id="@+id/logoutButton"
        android:layout_width="357dp"
        android:layout_height="51dp"
        android:background="@drawable/round_btn"
        android:fontFamily="@font/work_sans"
        android:text="Log Out"
        android:textAllCaps="false"
        android:textSize="16sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.46"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.992"
         />

Here is my code for the drawable file 'round_btn':
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="#6200EE"/>
    <stroke
        android:width="20px"
        android:color="#000000"
        />
    <corners
        android:radius="50dp"
        />
</shape>

No border is added but the corners are modified (curved).
Comment: could you please share how it looks now?
Answer: Adding this line:
app:backgroundTint="@null"

solves the problem.
So, your final code (for the button) becomes:
<Button
        android:id="@+id/logoutButton"
        android:layout_width="357dp"
        android:layout_height="51dp"
        android:background="@drawable/round_btn"
        android:fontFamily="@font/work_sans"
        android:text="Log Out"
        android:textAllCaps="false"
        android:textSize="16sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.46"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.992"
        app:backgroundTint="@null"
        />

You may look into this question: Android Background Drawable Not Working in Button Since Android Studio 4.1 for more information (Credit to question asker & some answerers, part(s) of this answer may have been inspired/taken from them)


Indicator and simple functions verify Fubini's Theorem (Lebesgue-Integral)

Question: I'm working on a proof of Fubini's Theorem. The theorem says:

Given $A\times B\in \mathcal{L}\times\mathcal{L}$ a Lebesgue
  measurable set in $\mathbb{R^2}$, and $f:A\times
> B\rightarrow\overline{\mathbb{R}}$ a Lebesgue integrable function,
  then: $$\iint_{A\times B}f(x,y)dxdy=\int_A(\int_Bf(x,y)dy)dx=\int_B(\int_Af(x,y)dx)dy.$$

My proof consists in four steps:

Prove it for indicator functions $\chi_E$, being $E\in\mathcal{L}\times\mathcal{L}.$
Prove it for simple functions $S$.
Prove it for Lebesgue measurable positive functions $f$.
Extend it to real measurable functions $f$, using the decomposition $f=f^+-f^-$.

I've already proven points 3 and 4 assuming the first two. My questions is about proving it for cases 1 and 2. I will thank any help.
Answer: You should include "step $0$", which is to prove it for indicator functions of the form $\chi_{A\times B}$, where $A, B\in \mathcal{L}$. Then use the fact that these kind of sets, generate your $\sigma$-algebra


Get the count of most occurring element in a list at every iteration

Question: I need to fetch the most occurring ID in a list at every iteration I process the list. Its a huge list that contains positive/negative IDs. If ID is positive, increase the count for that ID; if negative, reduce the count for that ID.
Consider input list as below:
input_list = [6,6,6,2,2,-6,-6,-6,-2,-2]

input_list[0] = 6 -> Count of ID 6:1 ->max count at this iteration is 1
input_list[1] = 6 -> Count of ID 6:2 ->max count at this iteration is 2
input_list[2] = 6 -> Count of ID 6:3 ->max count at this iteration is 3
input_list[3] = 2 -> Count of ID 6:3, Count of ID 2:1 ->max count at this iteration is 3
input_list[4] = 2 -> Count of ID 6:3, Count of ID 2:2 ->max count at this iteration is 3
input_list[5] = -6 -> Count of ID 6:2, Count of ID 2:2 ->max count at this iteration is 2
input_list[6] = -6 -> Count of ID 6:1, Count of ID 2:2 ->max count at this iteration is 1
and so on..

Expected output:
[1,2,3,3,3,2,2,2,1,0]

Note: -6 means the count of ID 6 getting reduced by 1.
def getMAxIDAfterEachUpdate(input_list):
    res = []
    dic = {}
    for i in range(len(input_list)):
        tmp = abs(input_list[i])
        if tmp not in dic:
            tmp = 1
        else:
            # ID is negative, we decrement its count
            if input_list[i] < 0:
                dic[tmp] -= 1
            else: #its positive, increment its count
                dic[tmp] += 1
        res.append(max(dic.values())
    return res

Finding max value in dictionary at every iteration is expensive. Is there a better way to find the result?
Comment: @krishna The OP's current approach is *O(n x m)* where *n* is the size of the input and *m* is the number of unique IDs. Note the use of the `max` function inside a loop. With a better algorithm it is possible to improve the time complexity to *O(n)* where the number of unique IDs no longer matters.
Comment: Please further elaborate your question with examples or sample code and what error you are facing.
Comment: Why you think the current approach is time expensive ? You are only using single loop, so the complexity is O(n), which is good. Since need max count per iteration and  you are handling negative values also as deletion, I don't think you can reduce the complexity to O(logn) or O(1). The code you pasted look good for this problem.
Comment: @blhsing is there a better approach?
Comment: Yes, there is. It seems that this question has not been able to garner enough reopen votes even though I believev it is now clarified enough after the edits. Try reposting this as a new question so I can answer you there.
Comment: @blhsing The question is now open again.
Answer: The main issue with your approach using a simple dict to store counts of IDs is that dict values are unordered, so in each iteration a full scan of dict values must be performed in order to obtain the maximum value/ID count, resulting in a time complexity of O(n x m), where n is the size of the input list and m is the number of unique IDs.
Since we know that the count of a given ID can only incremenet or decrement by 1 in each iteration, one way to optimize the algorithm is to store the ID count, along with the number of IDs sharing that count, in a node of a doubly linked list instead, and keep the counts stored in the nodes in ascending order in each iteration by either creating a new node with the new count or merging with the next/previous node if it shares the new count, while updating the node with the new number of IDs sharing the count, both operations of which takes O(1) time complextiy. Since the nodes are kept in ascending order of the counts, obtaining the maximum count is simply a matter of getting the count in the last node in O(1) time complexity, resulting in an improved overall time complexity of O(n).
With nodes being the dict that maps ID to node, and counts being the doubly linked list where each node stores a pair of count and number of IDs sharing the count, using your sample input list of [6, 6, 6, 2, 2, -6, -6, -6, -2, -2] to illustrate the result at the end of each iteration:
Iteration 1, ID = 6:
    nodes = {6: node1}
    counts = [node1(count=1, number=1)] => max count = 1
Iteration 2, ID = 6:
    nodes = {6: node1}
    counts = [node1(count=2, number=1)] => max count = 2
Iteration 3, ID = 6:
    nodes = {6: node1}
    counts = [node1(count=3, number=1)] => max count = 3
Iteration 4, ID = 2:
    nodes = {6: node1, 2: node2}
    counts = [node2(count=1, number=1), node1(count=3, number=1)] => max count = 3
Iteration 5, ID = 2:
    nodes = {6: node1, 2: node2}
    counts = [node2(count=2, number=1), node1(count=3, number=1)] => max count = 3
Iteration 6, ID = -6:
    nodes = {6: node2, 2: node2}
    counts = [node2(count=2, number=2)] => max count = 2
Iteration 7, ID = -6:
    nodes = {6: node1, 2: node2}
    counts = [node1(count=1, number=1), node2(count=2, number=1)] => max count = 2
Iteration 8, ID = -6:
    nodes = {6: node1, 2: node2}
    counts = [node1(count=0, number=1), node2(count=2, number=1)] => max count = 1
Iteration 9, ID = -2:
    nodes = {6: node1, 2: node2}
    counts = [node1(count=0, number=1), node2(count=1, number=1)] => max count = 1
Iteration 10, ID = -2:
    nodes = {6: node1, 2: node1}
    counts = [node1(count=0, number=2)] => max count = 0

Here's an implementation of the algorithm using the dllist class in the llist module for an efficient implementation of a doubly linked list:
from llist import dllist
from collections import namedtuple

count_number = namedtuple('count_number', ('count', 'number'))

def max_count_per_update(ids):
    nodes = {}
    counts = dllist()
    for id in ids:
        if not (node := nodes.get(key := abs(id))):
            if counts and (first := counts.first).value.count == 0:
                node = first
            else:
                node = counts.appendleft(count_number(0, 1))
        new_count = (current_node := node).value.count + (-1 if id < 0 else 1)
        next_node = node.prev if id < 0 else node.next
        if next_node and (next_value := next_node.value).count == new_count:
            (node := next_node).value = count_number(new_count, next_value.number + 1)
        else:
            insert = counts.insertbefore if id < 0 else counts.insertafter
            node = insert(count_number(new_count, 1), node)
        if new_number := (current_value := current_node.value).number - 1:
            current_node.value = count_number(current_value.count, new_number)
        else:
            counts.remove(current_node)
        nodes[key] = node
        yield counts.last.value.count

so that:
input_list = [6, 6, 6, 2, 2, -6, -6, -6, -2, -2]
print(list(max_count_per_update(input_list)))

outputs:
[1, 2, 3, 3, 3, 2, 2, 2, 1, 0]

Demo on replit: https://replit.com/@blhsing1/InfantileSandybrownNanotechnology#main.py
Note that llist requires a C compiler, which isn't available in replit's Python environment so I have to use the bash envrionment instead and write a shell script to install pip and llist on the fly, which sometimes requires a rerun after installation to work for some reason.
Comment: You get the "sorted dllist by current count" part right, but you're missing the part where I store the count together with the number of IDs sharing the count, so any increment or decrement to an ID count always needs just one move to the right or left, either by merging with an existing node (if it shares the same count) or by creating a new node (if an existing node with the new count doesn't exist). Please see how iteration 5 evolves to iteration 6 and then to iteration 7 in my illustration above.
Comment: Makes sense, thank you.
Comment: If understand correctly "counts" is sorted dllist by current count. How this works if there are multiple nodes (id-s) having same count? That is, how is list updated when one of such nodes is to be updated, and need to skip by multiple nodes on left/right ?
Answer: It seems that what you need is bidirectional mapping of dict(key, counter) <-> ordered_dict(counter,set(key)).
You can implement this ony your own, or you can use exiting library.
https://grantjenks.com/docs/sortedcontainers/sorteddict.html
Where main gist is using : https://grantjenks.com/docs/sortedcontainers/sorteddict.html#sorteditemsview
sd = SortedDict()
siv = sd.items()
for i in input_list:
   k = abs(i)
   diff = 1 if i > 0 else -1
   if i in sd:
     sd[i] += diff
   else:
     sd[i] = diff
   k,c = siv[-1]
   print(k,c) # largest item and count

Comment: Note that an assignment to a key in a `SortedDict` requires a time complexity of [*O(log n)*](https://grantjenks.com/docs/sortedcontainers/sorteddict.html#sortedcontainers.SortedDict.__setitem__), so doing it in a loop as your code is would result in a time complexity of *O(n log m)*.


Notice: Undefined variable

Question: Estou com esse problema, o código mostra este erro:

Notice: Undefined variable: row in C:\www\crud-master\formulario.php on line 33

MODELS:
<?php

try {

    $pdo = new PDO('mysql:host=localhost;dbname=CRUD_DATA', 'root', 'root');
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (Exception $e) {
    print "LOG de Erro {$e}";
}

/*
    === Aqui temos uma conexao tipo SINGLETON, que garente que teremos apenas uma conexao durante todo o processo.
 *      Isso evita que muitas conexoes sejam abertas ocassionando lentidao no sistema
 */

formulario.php
<?php
require('./conn/conexao_PDO.php');

if ($_GET) {

    $sql = $pdo->query("SELECT * FROM pessoas WHERE id = {$_GET['id']}");

    if ($sql !== false) {
        //imprima
        foreach ($sql as $row) {

        }
    }
} elseif ($_POST) {
    $sql = "UPDATE pessoas set nome = '{$_POST['nome']}', email = '{$_POST['email']}', telefone = '{$_POST['telefone']}', endereco = '{$_POST['endereco']}'";
    $query = $pdo->query($sql);

    $sql = "SELECT * FROM pessoas where id = {$_POST['id']}";

    $query = $pdo->prepare($sql);
    $query->execute();
    $data = $query->fetch_assoc();
}
?>
<!DOCTYPE html>

        <?php require ('./header.php'); ?>

ID:<?php echo $row['id']?>

            <form class="form-horizontal" method="post" action="formulario.php">

                    Nome:

                        <input type="hidden" id="id" value="<?php echo $row['id']?>">

                        <input type="text" class="form-control" id="nome" placeholder="Como te lhamas ??" value="<?php echo $row['nome']?>">

                    Email:

                        <input type="text" class="form-control" id="email" placeholder="Qual é o email pra enviar nudes ?" value="<?php echo $row['email']?>">

                    Telefone:

                        <input type="phone" class="form-control" id="telefone" placeholder="Numero do zap zap ?" value="<?php echo $row['telefone'];?>">

                    Endereço:

                        <input type="text" class="form-control" id="endereco" placeholder="Endereço para os Presentes" value="<?php echo $row['endereco']?>">

                        <button type="submit" class="btn btn-warning">SALVAR ALTERAÇÃO</button>
                        <button type="button" class="btn btn-info">Voltar</button>

            </form>

Comment: Variável indefinida $row. Você atribui os valores do fetch() a **$data e não $row**.Você tem que mudar o nome da sua variável.
Answer: Você está com uma variável indefinida chamada $row.
O que acontece é que você atribui os valores do fetch() a variável $data e depois chama por uma variável que não foi criada, $row. Você tem que mudar o nome da sua variável, ou na hora do fetch():
$data = $query->fetch_assoc();

para isso:
$row = $query->fetch_assoc();

Ou mudar todos os:
<?php echo $row['campo']?>

para isso:
<?php echo $data['campo']?>

Comment: Eu mudei para $row = $query->fetch_assoc();, mais o erro continua.
Comment: Queria perguntar, qual a lógica do if($_GET), if($_POST)? Porque você verifica se eles são verdadeiros, então nem dá para saber em qual vai entrar. Você sabe em qual dos ifs vai entrar? @MichelSpirlandeli
Comment: Dependendo, pode ser que entre no $_GET e nesse if não está programado $row = $query->fetch_assoc();. Perto de  if ($sql !== false) {
        //imprima
        foreach ($sql as $row) {
Comment: Então não consegui resolver isso acabei mudando td meu codigo,mas obrigado pela ajuda.
Answer: Tente tirar o ['id'] do $row porque no
foreach($sql as $row)

$row irá receber a última propriedade da array. Então $row ficará uma string
Comment: Reveja sua resposta. Não condiz nada com a pergunta.

Notice: Undefined variable


What's the reason for the value of the maximum security groups per VPC in AWS?

Question: I can understand imposing a limit. That's not the question.
The question is: is there a reason for the value of 500 or is it just some arbitrary number plucked out of the air?
Answer:
The multiple of the number of VPCs in the region and the number of
  security groups per VPC cannot exceed 5000. Which is the hard limit even after requesting service increase from AWS.

The real reason is not stated in any documentation but it shouldn't be an arbitrary number. It makes sense for AWS to have Security Group soft limits to internally provision resources efficiently with predictable boundaries. Similarly hard limits also allows them to have predictable functionality for their platform.
In addition these limits direct users to make design choices accordingly so that people are following best practices.
In this scenario even having 500 security groups in a single VPC would be extremely difficult to manage.


How to translate front but keep admin in FR

Question: I have a website with translation by domain, ex :

monsite.fr
fr.monsite.ca
en.moniste.ca
...

But in admin i'd like to stay on monsite.fr/admin whatever content that i translate, is it possible ?
Regards
Answer: You need to make sure you have the following core multilingual modules enable

Interface Translation (locale)
Language (language)

I'll assume you have also added your desired languages on /admin/config/regional/language
On the /admin/config/regional/language/detection page you can set the language preference used by your site.
You will want to enable:

Account administration pages [X]
User [X]

Then under the admin account edit page, you can find LANGUAGE SETTINGS | Administration pages language. You will want to set this to your preference.
Answer: @tyler36 :
thanks for your answer, i've done all this config but when i' m on admin content page when i click on translate i'm redirected to an other domain.
Below my config detection url by domain (/admin/config/regional/language/detection/url) :

FR : site.fr
IT : site.it
CA-EN : en.site.ca
CA-FR : fr.site.ca....
when i want to translate a french page to italian when i click on the language i'm redirected to this edit page on dedicated domain BUT i want to stay on french admin BO whatever translation, is it clear ? :)
is it possible ?

Regards


Use Composer to manage sub-theme Bootstrap LESS dependencies when using LESS starterkit

Question: In Drupal 8 let's say I want to use a Bootstrap subtheme and the LESS starterkit described here:
http://drupal-bootstrap.org/api/bootstrap/starterkits!less!README.md/group/subtheme_less/8
The Instruction there is to:

Download and extract the latest 3.x.x version of Bootstrap Framework Source Files into your new sub-theme. After it has been extracted, the folder should read ./subtheme/bootstrap.

Unfortunately this puts the Bootstrap source outside the ambit of my composer.json where I am managing my site dependecies and upgrade etc... more on why I want to do this here:
https://bojanz.wordpress.com/2015/09/18/d8-composer-definitive-intro/
So how can I include the bootstrap source required by my subtheme in the composer.json?
Comment: This [Q/A](http://drupal.stackexchange.com/q/184666/55237) is slightly related. No idea about sub-themes tough.
Answer: composer require twbs/bootstrap ^3.3.6 --prefer-dist -vvv
Drupal Bootstrap requires 3.x.x the caret will stop us tripping into v4.
We don't want to include any git files so we do --prefer-dist.
This downloads the latest bootstrap source to vendor/twbs.
I can expose this dir to my subtheme by editing:
/themes/custom/MYSUBTHEME/less/bootstrap.less
Now when I run composer update I will get the latest bootstrap less in my subtheme.


Desmos.com simulating spinning orbital object

Question: https://www.youtube.com/watch?v=U_VsPV1WJbg
As shown in the video, the face with the eyes and mouth are orbiting an unplotted circle with radius = 4, but also spinning (rotating) in a circular motion simulateneously.
How would one graph this, using preferably cosines/sines/tangents and possibly vectors, on desmos.com?
update:
How would I plot the parametric circles if I define the variables s and t with sliders?
Answer: You need to create a rotation around a rotation. Here's an example. The purple dot rotates around the green dot while the green dot rotates around the origin
https://www.desmos.com/calculator/cq05gca4tw
Play s & t at the same time. Make s go faster to make it more obvious.
Here is a more interesting example
https://www.desmos.com/calculator/8ptjoisdr2
All I did was apply the rotation linear transformation to obtain these formulas, along with a little geometry to start. Try changing the radii to see some interesting effects
Edit again: Another example with more objects
https://www.desmos.com/calculator/63rhaynifa
Comment: So how would I plot the parametric circles if I define s and t with sliders?
Comment: @GHQentertainment check out the edit
Answer: Here is a point that revolves: $$(r \sin ( \frac{1}{p} 2 \pi t)+h,r \cos ( \frac{1}{p} 2 \pi t)+k)$$
$t$: time
$(h,k)$: center of circle point is revolving on
$r$: radius of circle
$p$: revolution period in units of $t$
$ $
So, the parts that calculate the point's position in its rotation are $r \sin ( \frac{1}{p} 2 \pi t)$ and $r \cos ( \frac{1}{p} 2 \pi t)$. The $h$ and $k$ determine the center the point is orbiting. But what if the center of the point's orbit is orbiting something? Then $h$ and $k$ get replaced by the same expressions that move the first point around. So you'd end up with this, m variables for the "moon" point and p variables for the "planet point:$$(r_m \sin ( \frac{1}{p_m} 2 \pi t_m)+r_p \sin ( \frac{1}{p_p} 2 \pi t_p)+h,r_m \cos ( \frac{1}{p_m} 2 \pi t_m)+r_p \cos ( \frac{1}{p_p} 2 \pi t_p)+k)$$
If you want to see* this in action, I have a desmos solar system with moons.
*With extensive use of your scroll wheel.


Adicionando itens/subitens em massa no ListView

Question: Boa tarde,
Estou tentando adicionar itens em massa em um ListView.
Preciso colocar o texto de um Memo separado por ponto e vírgulas (;) como itens e subitens nesse ListView.
Exemplo:

Texto digitado no Memo:
  João da Silva;Curitiba - PR
  Maria Oliveira;São Paulo - SP
  Roberto Silva
  Pedro Miranda;Porto Alegre - RS

Na 1a coluna do ListView ficarão os nomes.
Na 2a coluna as cidades (algumas vezes a cidade não será mencionada).
Como eu poderia fazer isso?
Parece algo simples, porém ao pesquisar na internet só encontrei exemplos muito complicados.
Desde já agradeço.
Answer: <code>    procedure TForm3.Button1Click(Sender: TObject);
    Var Item: TListItem;
        Conta, Posicao : Integer;
    begin

      // pega o memo e adiciona no listview
      ListView1.Items.Clear;

      for Conta := 0 to Memo1.Lines.Count-1 do
      begin
        Item := ListView1.Items.Add;
        Posicao := Pos('-', Memo1.Lines[Conta]);

        if (Posicao = 0) then
          Item.Caption := Memo1.Lines[Conta]
        else
        begin
          Item.Caption := Copy(Memo1.Lines[Conta],0,Posicao-1);
          Item.SubItems.Add(Copy(Memo1.Lines[Conta],Posicao+1, Length(Memo1.Lines[Conta])));
        end;
      end;
    end;

    procedure TForm3.FormCreate(Sender: TObject);
    var
      Col : TListColumn;
    begin
      ListView1.ViewStyle := TViewStyle.vsReport;

      // Criando titulo das colunas
      Col := ListView1.Columns.Add;
      Col.Caption := 'Cidade';
      Col.Alignment := taLeftJustify;
      Col.Width := 200;

      Col := ListView1.Columns.Add;
      Col.Caption := 'Estado';
      Col.Alignment := taLeftJustify;
      Col.Width := 100;
      // Fim criando titulos das colunas

      // Preenchendo o memo
      Memo1.Lines.Clear;
      Memo1.Lines.Add('João da Silva;Curitiba - PR');
      Memo1.Lines.Add('Maria Oliveira;São Paulo - SP');
      Memo1.Lines.Add('Roberto Silva');
      Memo1.Lines.Add('Pedro Miranda;Porto Alegre - RS');
      // Fim Preenchendo o memo
    end;
</code>
Comment: Funcionou 100%. Muito obrigado.


Chord progression in Phrygian mode

Question: I'm working with a C scale in Phrygian mode. I can create some interesting melody with some character, but I miserably fail in creating pads with this scale. My chord progression has no 'soul', does not transfer any emotion, and is not able to fill the melody.
Is there any rule for creating progression in Phrygian mode? Are there any rules to apply to make a chord progression that should always be used?
Answer: A thing I noticed in 16th century music in phrygian is the heavy use of major VI harmonization -- in your case, that would be A-flat major.
I have mixed feelings about this.  On one hand, to the modern ear, it can very readily collapse the tonality of the piece into the relative major, losing all the nifty modality.  On the other hand, it is awfully attractive.  It sets up a nice contrast between the moody, darker phrygian and the brighter major.
So while I'm not sure what the complete answer is for your desired chord progression, you might find a judicious use of major VI chords in it gets you the soulful quality you are hunting.
Comment: @Codeswitcher, FelicePollano it's both true - you're not at home, but they do have the tendency to return to the tonic. esp. II - it's tonic (minor 2nd degree) acts as a descending leading tone. A similar thing happens to the root of VI - that acts as a descending leading tone for the 5th degree. You can use this in a VI - i progression, letting the root of VI flow down into the fifth of the i triad.
Comment: In phrygian, the VI acts as a dominant. The chord on II also acts as dominant in phrygian.

Chord progression in Phrygian mode


How to know from which country people are accessing my website?

Question: I am using Drupal7. I have a Chinese version of my site and I want to know whether they are using it or not. So I want to know which countries are using my website.
I tried to find that out like this -> if I go to the Reports>>Recent Hits then I find the hostname for the anonymous users.
I found some website that tells the country name taking the host IP address as input.
Is there any module that shows country from which the website got accessed?
Comment: Do you want to *know* that (then @4life answered already, or be able to use that in your scripts, like displaying "free pizza near %yourarea"?
Comment: Actually I have a Chinese version of my site and I want to know whether they are using it or not.
Answer: You do not need a module for that. Simply make use of any web analytics system such as
 Google analytics, Piwik analytics and such like.
Comment: Just to make sure... can I include this in my website? Maybe a page which shows a pie chart of % usage in countries ?
Comment: @Dan - I asked in comment under your question do you want to **know** the data or to **use** it in your site. There you said you wanna know. Please decide. But to answer your concern - yes, you can import GA data to Drupal. Not the easiest thing, but it can be done. "How" is a matter for separate question.
Comment: ya i just want to know the stats. so 4life's answer is what i need.


Chamada de método dentro da JSP

Question: Bom dia pessoal!
Estava com problemas para formatar datas na jsp, porém com a ajuda dos amigos daqui, consegui resolver.
O problema é que acho que acho que meu código ficou longe das boas práticas no JSP, tive que programar dentro da página, mas amigos me falaram que eu podia chamar o método getInicioFormatado() direto que resolveria, porém não consegui... estou deixando as classes aqui embaixo, retirei a maior parte que achei desnecessária, porém se alguém precisar de algo é só falar.
Obs.: para persistência estou usando hibernate.
Obrigado pela ajuda pessoal!
Classe do Fornecedor.
/* imports e anotations desnecessários para o exemplo, foram omitidos.

public class Fornecedor extends Pessoa{

@Column
private Integer codigo;
@Column
private String pessoaContato;
@Column
private String cnpj;
@Column
private Date inicioAtividades;

    /* construtores, get and seters desnecessários para o exemplo, foram omitidos.

public  Date getInicioAtividades()  {

    return inicioAtividades;
}
public void setInicioAtividades( java.util.Date inicioAtividades) {
    this.inicioAtividades = (Date) inicioAtividades;
}

public String getInicioFormatado() {
    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
    String data = sdf.format(inicioAtividades);
    return  data;
    }

Servlet Controle Fornecedor
protected void buscar(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

try{
List<Fornecedor> listaFornecedores = new FornecedorDao().listarFornecedores();

    request.setAttribute("listaFornecedores", listaFornecedores);
    request.getRequestDispatcher("cadFornecedores.jsp").forward(request, response);

}catch(Exception e){
    e.printStackTrace();
}

Fornecedor Dao
public List<Fornecedor> listarFornecedores() {
    session = HibernateUtil.getSessionFactory().openSession();
    List<Fornecedor> listaFornecedores = new ArrayList<Fornecedor>();
    query = session.createQuery("FROM Fornecedor");

    listaFornecedores = query.list();
    session.close();
    return listaFornecedores;
    }

Cadastro de fornecedores JSP (onde dei muita volta)
<c:if test="${fn:length(listaFornecedores) > 0 }">

            Nome
            Código
            Telefone
            Endereço
            Nº
            Cep
            Bairro
            Cidade
            Estado
            E-mail
            Nome do Contato
            CNPJ
            Início das Atividades

        <% List<Fornecedor> listaFornecedores = new FornecedorDao().listarFornecedores();
            Integer i = 0;
            Fornecedor f = new Fornecedor();
            SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
        %>

        <c:forEach items="${listaFornecedores }" var="forn">

                ${forn.nome }
                ${forn.codigo }
                ${forn.telefone }
                ${forn.endereco }
                ${forn.numeroDoEndereco }
                ${forn.cep }
                ${forn.bairro }
                ${forn.cidade }
                ${forn.estado }
                ${forn.email }
                ${forn.pessoaContato }
                ${forn.cnpj }

                <%
                f.setid(listaFornecedores.get(i).getid());
                f.setInicioAtividades(listaFornecedores.get(i).getInicioAtividades());
                    String data =  sdf.format(f.getInicioAtividades());
                out.print(data);
                    //System.out.println(f.getInicioFormatado());
                    i=i+1;

                %>

                                Alterar Remover

                        </c:forEach>

                </c:if>

Answer: Algumas observações:
Como você está adicionando sua lista de fornecedores como um àttribute a sua request nesse trecho:
request.setAttribute("listaFornecedores", listaFornecedores);

O seguinte trecho de código no seu JSP se torna desnecessário:
<% List<Fornecedor> listaFornecedores = new FornecedorDao().listarFornecedores();
        Integer i = 0;
        Fornecedor f = new Fornecedor();
        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
%>

Caso você tivesse mencionado no outro tópico que o objetivo de ter uma Date formatada era para exibi-la no seu JSP, nós podíamos ter te instruído a utilizar a taglib fmt e formatá-la dentro do próprio JSP. Dessa forma. Exemplo:
<fmt:formatDate value="${fornecedor.inicioAtividades}" pattern="dd/MM/yyyy" />

Seu código ficaria assim:
Seu Servlet:
protected void buscar(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    try{
        List<Fornecedor> listaFornecedores = new FornecedorDao().listarFornecedores();

        request.setAttribute("listaFornecedores", listaFornecedores);
        request.getRequestDispatcher("cadFornecedores.jsp").forward(request, response);

    } catch(Exception e){
        e.printStackTrace();
    }
}

Seu JSP:
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>

    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>Lista de Fornecedores</title>

                Nome
                Código
                Telefone
                Endereço
                Nº
                Cep
                Bairro
                Cidade
                Estado
                E-mail
                Nome do Contato
                CNPJ
                Início das Atividades

            <c:forEach var="fornecedor" items="${listaFornecedores}">

                    ${fornecedor.nome}
                    ${fornecedor.codigo}
                    ${fornecedor.telefone}
                    ${fornecedor.endereco}
                    ${fornecedor.numeroDoEndereco }
                    ${fornecedor.cep}
                    ${fornecedor.bairro}
                    ${fornecedor.cidade}
                    ${fornecedor.estado}
                    ${fornecedor.email}
                    ${fornecedor.pessoaContato}
                    ${fornecedor.cnpj}

                        <fmt:formatDate value="${fornecedor.inicioAtividades}" pattern="dd/MM/yyyy" />

            </c:forEach>
            <c:if test="${empty listaFornecedores}">

Nenhum fornecedor cadastrado

            </c:if>

Comment: Kra, obrigado, de verdade! Respondeu até mais do que eu precisava. Funcionou perfeitamente, e ainda me deu a ideia caso não tenha fornecedor cadastrado, mostrar a mensagem com o c:if. :)

Chamada de método dentro da JSP


How array works internally in Java?

Question: This query is posted to basically understand points like

An object is class instance or an array;
An array is a subclass of Object class;
Everything that is instantiated other than primitive is an object in Java.

Here is my understanding of working with arrays in Java.
Considering the below program,
/* dummy.java */
class C {
    private int i;
    public C() {
        i = 1;
        System.out.println("Am in constructor");
    }
}
public class dummy {
    public static void main(String[] args) {
        C[] c = new C[2]; // Line 11
        c[0] = new C();
        System.out.println(c);
    }
}

An object of type class [LC is created in run-time after running,
C[] c = new C[2]; //Line 11

In the above code. class [LC is an immediate subclass of Object class. Reference variable c points to this object (shown in red boundary below) after running Line 12 in the above code. Reference variables sit in stack and an object of type class C will go in heap.

For a below change of line 11 & 12 in the above code
C[][] c = new C[2][2];
c[0][0] = new C();

will make the representation as shown below.

Is my understanding correct? If yes, Can you please explain more on usage of class [LC in run time to instantiate an object?
Note: C[].class gives the actual type in run-time, which is class [LC.
Comment: Almost correct.  However, the instance of C is not part of the array (counter to what your red boundary implies).
Comment: Both the array and the C instance are objects, so they're both on the heap (at least, conceptually).  But they're *separate* objects.
Comment: What are you hoping to learn from this? Why do you want to know. That can help someone provide a better answer for you.
Comment: There's also the details that the memory for the array will hold the array's size, type, and it might not be contiguous.
Comment: @OliverCharlesworth I did not get you when you say, instance of C is not part of the array. Instance of C sits in heap, unlike reference variables, correct?
Comment: @DavidEhrmann *"and it might not be contiguous"* - Do you mean that the references of the elements in the array are not stored contiguously in memory (IMO they are, but I'd like to be corrected if I'm wrong)? Or were you referring to the fact that the elements of the array are objects from the heap that could be anywhere?
Comment: @BillR Hope i addressed your point by modifying the query.
Comment: http://stackoverflow.com/questions/20646022/how-does-arrays-work-in-the-bytecode-of-java nitty gritty detail in the answer here
Comment: @OliverCharlesworth you mean object1 `[1234, null]` is of type `class [LC` and  object2(instance of C) is of type `class C` and both are different objects. Both objects sit in heap. reference variable c[0] of object1 points to object2 with reference at address(say 1234). Is that correct?
Comment: "The instance of C is not part of the array": one way to understand this is that it's possible for the array to get garbage-collected while the instance may still have references pointing to it so it can't be garbage-collected.
Comment: @ajb Ok. But when we say: 'they're separate objects', Does that mean, object1 `[1234, null]` is of type `class [LC` and object2 is of type `class C` . Both objects sit in heap. reference variable `c[0]`( of object1) points to object2 with referring to address(say 1234). Is that correct?
Comment: @overexchange I think that's generally correct.
Comment: By not contiguous, he means that the different instances of objects C that will be created (for example c[0] and c[1]) might not be stored contiguously in the memory.  Only the array of pointers c[] itself is.  Also, in Java, all pointers are double pointers in order to allow for the compaction of memory when the garbage collection is done (for most but not all versions of Java).  Therefore, c doesn't point directly toward the array c[] but first to another pointer and this pointer toward c[].  Same thing for all pointers of c[] toward the objects C.  This is why Java is slower than C++.
Comment: @SylvainL Do you think the second diagram in the query will make understand the idea of 'contiguous'? Here instance of C is created in some random space.
Comment: @SylvainL "This is why Java is slower than C++" http://stackoverflow.com/questions/145110/c-performance-vs-java-c
Comment: A lot of people have worked on both C/C++ on one side and C#/Java on the other side and I don't remember anyone of those telling that C#/Java was faster or even just to be of comparable speed to C/C++.  In fact, many of us have begun coding with C/C++ before starting with Java and the first comment usually was often "How sluggish it is to work with Java!".  There is a reason why there are a lot of people willing to mix C++ with Java for those "need to be really fast" routines.
Comment: On the other hand, given a good JIT compiler and time for it to settle in and optimize the code, Java isn't necessarily significantly slower than most compiled languages. If it was, you wouldn't have companies like IBM using Java to write major applications.
Comment: Speed is only one of many factors to consider when choosing a language or a mix of languages to perform a task.
Comment: @SylvainL I did not get your point: `Also, in Java, all pointers are double pointers in order to allow for the compaction of memory when the garbage collection is done (for most but not all versions of Java).`
Comment: First, technically, in Java, you don't have pointers; only references but a lot of people still call them pointers by habit.  These references are represented internally by double pointers (a pointer to a pointer); which give the runtime the possibility of compacting most of the memory when the garbage collection is done.  However, it's not all the versions of Java who perform this.  For example, with Java for the first versions of Android, there is no compaction of memory (but I'm not sure if this is still the case for the latest versions as I didn't check).
Comment: @OliverCharlesworth In the above query, if i say `class C implements I{}` where `interface I{}` is an interface, then Does `class [LC` becomes a subclass of `class [LI`? i know that `class [LI` is subclass of `class Object`.
Comment: @SylvainL i did not get your answer about double pointers.
Comment: You should read about the garbage collection process of Java; this is explained in full details.  These little comments are definitely not the place to try explaining these concepts.
Answer: To answer your question: yes, in Java (and C#), nearly everything is split into multiple discrete chunks of memory accessed by pointers.  This not only include your bidimensional array but also any embedded object inside your object C.  In C++, if you have an array (single dimensional or not) of 10 objects and each of these object contains 10 embedded objects, you can allocate all this with a single piece of memory.  In C# and Java, you will have a minimum of 101 memory allocations for storing all this (if all of the embedded objects are simple objects) in the case of a mono-dimensional array and more in the case of a multi-dimensional array.
However, this explosion of pieces of memory shouldn't be seen a something very bad because it's free you of the difficulty of managing yourself the allocation of memory as you can have with C/C++ and in most cases, the power of any modern CPU is generally sufficient to pull it forward at a sufficient speed.
Comment: Does `class [LC` implement any interface?if yes, let me know the name  or definition of that interface
Comment: Not to my knowledge.  You cannot create an object that will emulate an array natively.
Comment: When we say that reference variable `c` points to an instance of `class [LC` after executing `C[] c = new C[2]`. Does the constructor of `class [LC` get called to instantiate?
Comment: Internally, the memory for the object c is initialised to the correct values by the runtime.  However, you don't have access to this behavior: you cannot call it directly or change it from your Java coding.  Therefore, weither you call this initialisation a constructor or whatever else, it's up to you.  For what I remember, C++ give you access to some part of this process but Java not.
Comment: The class `[LC;` is a subclass of `Object`, and inherits all of the methods in the `Object` API.  However, obviously, `Object` is a class not an interface.  However, the class `[LC;` exists in a conceptual sense only.  It has no code, no methods *of its own* and cannot be instantiated l*ike a normal class*, either in Java source code, bytecodes, or reflectively.

How array works internally in Java?


Interpreting tweedie-location-scale result from R mgcv package

Question: I came across the Tweedie-location-scale family function in R (twlss function from mgcv). It looks appealing to model my data. I understand the general concepts is that "twlss" family allows modelling scale and power parameter to the Tweedie distribution. However, after I tried it on data, I am puzzled by the returned values. For example, if I fit data with the command:
gam(list(y ~ s(x), ~1, ~1), family = twlss(), ...)
I expected the fitted power parameter and scale to be a constant "~1". My understanding is that the power must be between [1, 2] as required by Tweedie distribution. But sometimes, I get result saying fitted intercept.1 field to be a negative number. The documentation didn't mention whether intercept.1 is indeed the power parameter, but I guess they are related (for example, some kind of transformation, perhaps?)
I wonder if anyone ha used this package and knows how to interpret the fitted parameters. In particular, how to extract the fitted power and scale parameters from the fitted model.
Many thanks.
Answer: These location-scale-shape models are often tricky to work with in {mgcv} because the parameterisations chosen by Simon Wood, while numerically stable (as possible), don't often fit into the standard link/inverse link framework common to other GLMs. This coupled with the fact that the documentation for these general families often is terse or just lacking detail makes them difficult to work with unless you are an expert.
Doing a bit of digging (because I am not an expert), it seems that what is returned in the second column of fitted() or predict() for a model fitted using twlss() is not the power parameter itself but rather $\theta$ (which is on an unbounded scale) which needs to have an unstated inverse function applied to it to transform it to the bounded [a,b] scale.
I've written a few functions to help you convert from what is returned with the model fit to the parameters of the Tweedie distribution, $\mu$, $\text{p}$, and $\phi$, but for generality, it works on the fitted values of the model (or the predicted values if given some new data).
The first function just recovers the bounds on the power parameter $\text{a}$ and $\text{b}$ that were used when the model was fitted:
get_tw_ab <- function(model) {
    fam <- family(model)
    if (fam$family != "twlss") {
        stop("'model' wasn't fitted with 'twlss()' family.",
             call. = FALSE)
    }
    rfun <- fam$residuals
    a <- get(".a", envir = environment(rfun))
    b <- get(".b", envir = environment(rfun))
    c(a, b)
}

Next we have a helper function that does the conversion from the $\theta$ scale to the $\text{p}$ (power) scale, given values for $\text{a}$ and $\text{b}$:
theta_2_power <- function(p, a, b) {
    i <- p > 0
    exp_theta_pos <- exp(-p[i])
    exp_theta_neg <- exp(p[!i])
    p[i] <- (b + a * exp_theta_pos) / (1 + exp_theta_pos)
    p[!i] <- (b * exp_theta_neg + a) / (1 + exp_theta_neg)
    p
}

These are used internally in the final function which, returns the parameters of the fitted Tweedie distribution for each observation or new data combination on their real scales
tw_params <- function(model, data = NULL) {
    require("gratia")
    data <- if (is.null(data)) {
        predict(model, type = "link")
    } else {
        predict(model, newdata = data, type = "link")
    }
    mu_ilink <- gratia::inv_link(model, parameter = "mu")
    ab <- get_tw_ab(model)
    data[, 1] <- mu_ilink(data[,1])
    data[, 2] <- theta_2_power(data[, 2], a = ab[1], b = ab[2])
    data[, 3] <- exp(data[, 3])
    colnames(data) <- c("mu", "power", "scale")
    data
}

Here's an example building on the one in ?twlss
library('mgcv')
library('gratia') # for inv_link()
set.seed(3)
n <- 400
## Simulate data...
dat <- gamSim(1, n = n, dist = "poisson", scale = .2)
dat$y <- rTweedie(exp(dat$f), p = 1.3, phi = 0.5) ## Tweedie response

## Fit a fixed p Tweedie, with wrong link ...
b <- gam(list(y ~ s(x0) + s(x1) + s(x2) + s(x3), ~1, ~1),
         family=twlss(), data=dat)

What you get back for the intercepts for the power and scale parameters in the summary() output are the second and third columns of the matrix returned by fitted() or predict()
head(predict(b, type = "link"))

 head(predict(b, type = "link"))
       [,1]       [,2]       [,3]
1 0.3770615 -0.4588997 -0.9378858
2 1.8091046 -0.4588997 -0.9378858
3 1.1973448 -0.4588997 -0.9378858
4 2.5295548 -0.4588997 -0.9378858
5 2.1003765 -0.4588997 -0.9378858
6 0.6554773 -0.4588997 -0.9378858

here the first column is on the link scale for the linear predictor of $\mu$, which by default is the log scale. If you asked for fitted(b) you'd get it on the natural non-log scale.
Notice that columns 2 and 3 of this matrix are constants in this case because we fitted a LSS model with constants in the linear predictors for the power and scale parameters.
The full suite of parameters on their natural/true scales are given  y tw_params():
head(tw_params(b))

> head(tw_params(b))
         mu    power     scale
1  1.457994 1.389502 0.3914546
2  6.104979 1.389502 0.3914546
3  3.311313 1.389502 0.3914546
4 12.547918 1.389502 0.3914546
5  8.169245 1.389502 0.3914546
6  1.926062 1.389502 0.3914546

These are pretty close to the values used to simulate the data (power = 1.3, and phi = 0.5)
Comment: That's awesome! These link functions really recovers p and phi. Thank you! The documentation said the link for p and phi are `identity` link when constructing twlss family function, which I think is very confusing.


How to store date_popup fileld in mysql

Question: For some reason I cannot save the value of my date_popup field (comment_date) to mysql database.
I need to use default value from existing field (field_due_date6) and store the new value to this field.
So I do the following:
function custom_form_alter(&$form, $form_state, $form_id) {
  $form['comment_date'] = array(
      '#date_format' => 'Y-m-d',
      '#date_year_range' => '0:+1',
      '#type' => 'date_popup',
      '#weight'=>1,
      '#datepicker_options' => array('minDate' => 0),
      '#default_value' => $form['#node']->field_due_date6['und'][0]['value']
    );
}

Then I'm trying to submit it to database:
function custom_support_comment_submit($form, &$form_state) {
  $node = node_load($form_state['values']['nid']);
  $node_wrapper = entity_metadata_wrapper('node', $node);

  if($form_state['values']['comment_date']) {
    $node_wrapper->field_due_date6->set($form_state['values']['comment_date']);
  }
  $node_wrapper->save();
}

But when I click Submit button I got the error -
EntityMetadataWrapperException: Invalid data value given. Be sure it matches the required data type and format. в функции EntityMetadataWrapper->set() (строка 122 в файле Z:\home\dd1\www\sites\all\modules\entity\includes\entity.wrapper.inc).

Could you please specify what I'm doing wrong?
Answer: Node Field must be expecting date field value in unixtimestamp format while the custom form will return the value in the format mention as '#date_format' => 'Y-m-d'. View of your form submit values will look like.

You should run the submit date value through strtotime() to get the unxtimestamp value for it before assigning it to node field.
$node_wrapper->field_due_date6->set(strtotime($form_state['values']['comment_date']));

How to store date_popup fileld in mysql


Test and minimum sample size to conclude that 2 ECDFs are different

Question: Let's say I have samples $X$ from one distribution and I am now collecting new samples $Y$ from another unknown distribution. What would be the best test to check whether the samples $Y$ come from the same distribution of $X$? Should I use the Kolmogorov-Smirnov test? And how do I check that I have enough samples (as in my case the sampling step is expensive)?
As illustration: In this next scenario I can visually see after 10 samples that the distributions are very likely to be different.

However, in the following scenario, more samples are required to make the same conclusion.
Comment: How do you have just $X$ and $Y$ in your question yet three distinct CDFs in your plots?
Comment: @Dave the green CDF uses 10 random points from the 100 points that make up the orange CDF, so they are both constructed from $Y$
Comment: Okay, so you aim to compare just two distributions, right, not three?
Answer: As with any power and sample size determination,
the sample size to achieve given power depends on
the 'distance' between the two models being
compared.
The test statistic $D$ of the Kolmogorov-Smirnov
test is the maximum vertical distance between
the two ECDFs (plotted as step functions).
If you are using a pooled two-sample t test to
compare means of two normal distributions (having
equal variances), then there is an exact analytic
formula, using a noncentral t distribution, to
find the power for given $n$'s, significance level,
common variance $\sigma^2$ and distance $\Delta$
between means to be detected.
I know of no such formula for the K-S test, but
it is possible to use simulation to approximate the power for given sample size and significance level.
For example, suppose you want to detect the difference
between samples of size $n=10$ from distributions
$\mathsf{Gamma}(\mathrm{shape}=4, \mathrm{rate}=2)$
and $\mathsf{Gamma}(6, 3).$ Then CDFs are much
the same and ten observations from each will probably
not give good power at the 5% level.

A simulation using data from 10,000 samples
of size 10 shows the power to be uselessly small.
set.seed(1217)
pv = replicate(10^4,ks.test(
        rgamma(10,4,2),
        rgamma(10,6,3))$p.val)
mean(pv <= .05)
[1] 0.0144  # aprx power

You would need sample sizes something like 1000 in
order to have reasonable power (say 90%) to detect the difference
between these two distributions.
set.seed(1218)
pv = replicate(10^4, ks.test(
      rgamma(1000,4,2),
      rgamma(1000,6,3))$p.val)
mean(pv <= .05)
[1] 0.9027 # aprx power

By contrast, if you are trying to distinguish between
the distributions $\mathsf{Exp}(\mathrm{rate}=2)$ and $\mathsf{Norm}(1,1),$ then samples of size 20 might
be good enough.

A test at the 5% level with samples of size twenty has almost 80% power.
set.seed(2021)
pv = replicate(10^4, ks.test(rexp(20,2),
                 rnorm(20,0, 1))$p.val)
mean(pv <= .05)
[1] 0.7882

Unfortunately, the K-S test is not known for good
power. If the differences between your distributions
of interest are due only to different parameter values (e.g, distinguishing between two normal distributions or two exponential distributions),
then you might find a parametric test using key parameters that
gives better results.


What is the expected value of the division of a random variable by a sum of random variables?

Question: With $X_1$, $X_2$ and $X_3$ being independent random variables, how can I compute $\mathbb{E}\left[ \frac{X_1}{X_1+X_2+X_3}\right]$?
Is $\mathbb{E}\left[ \frac{X_1}{X_1+X_2+X_3}\right] = \frac{\mathbb{E}\left[X_1\right]}{\mathbb{E}\left[X_1\right]+\mathbb{E}\left[X_2\right]+\mathbb{E}\left[X_3\right]}$? If not, how is it  calculated?
Thank you in advance for any clarification.
Comment: Are you also assuming the variables all have the same distribution?
Answer: There is a famous "folk theorem" residual to my undergrad classes, namely that
$$\mathbb E[X/Y] = \mathbb E[X] \big/ \mathbb E[Y]$$
and it is often permeates during exams, as it makes computing much easier. Sadly, the equality does not hold in general, even when $X$ and $Y$ are independent (due to Jensen's inequality).
In the case of $\mathbb E[X_1/X_1+X_2+X_3]$, numerator and denominator are dependent, which usually makes the computation more difficult. However, in the very special case when the three $X_i$'s are iid, $X_i/X_1+X_2+X_3$ has the same distribution for all three $i$'s and this leads to an obvious conclusion concerning the expectation of any of them. Assuming this expectation exists, of course. A counterexample is provided by a triplet of Normal variables (see Marsaglia's paper in connection).
As a special case where the identity works, take the Dirichlet $\mathcal D(\alpha_1,\ldots,\alpha_d)$ distribution, whose expectation is
$$\mathbb E[Y_i]=\alpha_i\Big/\sum_{j=1}^d \alpha_j$$
One representation of a Dirichlet random vector $(Y_1,\ldots,Y_d)$ is
$$Y_i=\frac{X_i}{X_1+\ldots+X_d}\qquad X_i\sim\mathcal G(\alpha_i,1)$$
where the $X_i$'s are independent. In that case,
$$\mathbb E[Y_i]=\mathbb E[X_i\big/X_1+\ldots+X_d]=
\mathbb E[X_i]\big/\mathbb E[X_1+\ldots+X_d]$$
Comment: The identity will work whenever the $X_i$ are *iid* with nonzero expectation, as you basically pointed out in an earlier version of this answer.
Comment: Good question: I don't think so. For instance, let the distribution be uniform on the values $\{-1,1,3\}.$ $|X_1/(X_1+X_2)|$ equals one divided by zero with a chance of $2/9.$ Continuous approximations to this will have comparable problems. Notice that these random variables are (a) bounded and (b) have zero probability to be zero.
Comment: The expression like $X_1/(X_1 + X_2)$ also occured in this question https://stats.stackexchange.com/a/399952/ . There is an expression from Hinkley for the case that the $X_i$ are Gaussian distributed (and the expectation will be infinite). In this question https://stats.stackexchange.com/a/438402 an intuitive view is given for the ratio distribution (and you could do the same for the correlated case). You could also express the distribution of the *angle*. And the expectation of the ratio is the expectation of the tangens of the angle, which becomes infinite when 90 deg has non-zero density.
Comment: When the $X_i$ are continuous and non-negative then the division by 0 occurs only in the point $(X_1,X_2) = (0,0)$ (which has zero probability) and for the other values of $X_1,X_2$ the value of the ratio $X_1/(X_1+X_2)$ is between 0 and 1, such that the ratio won't have infinite or undefined expectation.
Comment: @whuber: Is this enough to ensure that $X_1/(X_1+X_2)$ has a well-defined expectation?
Comment: Correct!, the expectation is defined since $X_1/(X_1+\cdots)\le 1$ with probability one.


CCEventListener.cpp - Assertion failed when trying to implement touch functionality

Question: I'm fiddling around with Cocos2D-X and trying to implement touch functionality as per this wiki entry. However, when I try to run my code, it launches and pops up a dialog saying "Assertion failed!" giving a reason "CCEventListenerTouch.cpp, Line:89, Expression: false".
Here's my code related to this:
bool MainLayer::init()
{
    Sprite* tile = Sprite::create("tile.png");
    this->addChild(tile);
    auto listener = EventListenerTouchOneByOne::create();
    listener->setSwallowTouches(true);

    listener->onTouchMoved = [](Touch* touch, Event* event)
    {
        tile->setPosition(tile->getPosition() + touch->getDelta());
    };

    _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, tile);

    return true;
}

If I uncomment the line before the returnstatement, it works without crashing, but the touches are not working.
Answer: It seems that you actually have to implement all the onTouch* callbacks. I added these two and it started working.
listener->onTouchBegan = [&](Touch* touch, Event* event)
{
    return true;
};

listener->onTouchEnded = [=](Touch* touch, Event* event)
{

};

Comment: Yes and it is also common to check to make sure your sprite contains the touch location, just to be sure.


Is there a simple sequence with bi-alternating parity?

Question: Any polynomial $p$ over $\mathbf Z$ has either alternating or constant parity, i.e., either
$p(n)$ is even for all $n$, $p(n)$ is odd for all $n$, or $p(n)$ alternates; odd, even, odd, even etc.
This follows just by noting that any polynomial $a_dn^d + \cdots + a_1n+a_0$ equals
$$n(a_dn^{d-1}+\cdots+a_1)+a_0,$$
so for even $n$, the parity of $p(n)$ is fixed (it is the same as that of $a_0$), and for odd $n$, the parity is also fixed (it is the same as that of $a_0+a_1+\cdots+a_d$).
I would like a simple expression which has bi-alternating parity, i.e., some expression $f(n)$ whose parity for successive $n$ looks like:
$$\text{even, even, odd, odd, even, even, odd, odd},\dots$$
What is the "simplest" kind of expression I can create which has this property? It cannot be polynomial by the reasoning above, but maybe something algebraic (involving radicals)? I would like to avoid floors/ceilings and have something nicely differentiable.
Comment: $\big \lfloor \frac n2\big \rfloor$.
Comment: $\dfrac12+\dfrac{\sin((2n+1)\pi/4)}{\sqrt 2}$ goes $1,1,0,0,1,1,0,0,\ldots$
Answer: Probably one of the simplest such sequences is the sequence of triangular numbers, $T_n =  \frac{n(n+1)}{2}$. For nonnegative integers it starts as
$$0, 1, 3, 6, 10, 15, 21, \ldots$$
It is odd when $n = 1, 2 \pmod 4$ and even when $n = 3, 0 \pmod 4$. Note that it can be given as a polynomial expression with coefficients over $\mathbb{Q}$ (but not over $\mathbb{Z}$, as your question shows).


Importing table from Postgres to MS Access and losing records

Question: I have a postgres table containing nearly 700,000 records, I import that table into MS access (via an ODBC data source) and end up with only 250,000 records.
I start with an empty MS access database (520 kbytes). Select (external data)/(New data source)/(from other sources)/(ODBC database)/(Import the source data)/(Machine data source) I pick my ODBC postgres database, and select the table I want, wait for 30 seconds, then I get a message box saying all objects have been successfully imported followed by being asked if I want to save the import steps.
There are no error messages, but the number of rows in my MS access version of the table is around 250,000.
Other info...

I'm using MS office 365 version 1710
I'm using postgres 9.5.7
I'm using the PostgrSQL ANSI ODBC driver (not sure which version)
There are no signs of any error messages (or warnings).
After the import the Access database is still only 375 Mbytes, well short of the 2 Gbyte limit.
I've checked the 'ODBC data sources' app to check how the postgres ODBC link is configured, there's no obvious problem with it.
The final message that MS access gives me after the import includes 'all objects imported without errors'
There is no obvious difference between the records that are getting through and those that aren't.

Why am I losing records, and what can I do to cure it?
Thanks
Comment: You should ask your question on [DBA Exchange](https://dba.stackexchange.com/help/on-topic).
Answer: If you attempt to "slurp" all records from the database at one time, the ODBC driver will stop fetching at some point and just return what it has without warning.  It's annoying.  As far as I know this has nothing to do with the 32-bit limit.
The way to solve this is to not fetch all records at once, but use the declare/fetch option on the driver.  You can do this permanently on the ODBC settings by going to your ODBC properties, selecting "Datasource" and then on "Page 2" checking the "Use Declare/Fetch" and setting your cache (# of rows) size.  I recommend a number somewhere between 5,000 and 50,000.  Each batch represents a hit to the database, so you want it to be reasonably large to begin with.
From all practical purposes, the use of declare/fetch will be totally transparent to your application.  You won't even notice.  You will on the database admin side, but if your fetch size is sufficiently large, it won't be an issue.

You can also do one-time edits to your connection string from your particular query.  You would add the following to make this work:
<code>UseDeclareFetch=1;Fetch=25000;
</code>