app.receivedEvent is not a function

Question: I am building a phonegap application and I get the following error message when debugging.

Uncaught TypeError: app.receivedEvent is not a function(…)** on line 18 of my JS code (I point it out below).

To be honest I have read many guides on the deviceready but I just can't figure out how to properly use it for my phonegap build code.
Here is my HTML:
<!DOCTYPE html>

        <meta charset="utf-8" />
        <meta name="format-detection" content="telephone=no" />
        <meta name="msapplication-tap-highlight" content="no" />

  <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" type="text/css" href="css/index.css" />

  <link rel="stylesheet" href="css/jquery.mobile-1.4.5.min.css">
  <link href='https://fonts.googleapis.com/css?family=Lobster|Anton|Patua+One' rel='stylesheet' type='text/css'>
  <link rel="stylesheet" href="css/fact_page.css">
  <title>One Direction Facts</title>

One Direction - Fact of the Day

 Today's One Direction Fact:

 Welcome to
One Direction Facts.

You will get a random fact each day.

    View Fact

1

New Features Coming Soon!

Here is my JS:
    var app = {

    // Application Constructor
    initialize: function() {
        this.bindEvents();
    },
    // Bind Event Listeners
    //
    // Bind any events that are required on startup. Common events are:
    // 'load', 'deviceready', 'offline', and 'online'.
    bindEvents: function() {
        document.addEventListener('deviceready', this.onDeviceReady, false);
    },
    // deviceready Event Handler
    //
    // The scope of 'this' is the event. In order to call the 'receivedEvent'
    // function, we must explicitly call 'app.receivedEvent(...);'
    onDeviceReady: function() {

/*--error is here-->*/     app.receivedEvent('deviceready');

    },
    // Update DOM on a Received Event
    receivedEvent:
            $("#nextQ").click(function(){

        var tempd = new Date(); //Get today's date
        //Checks if localstorage had 'DateOpened' already stored

     // Note that by adding strings in there, we end up with a string instead of adding.
        // Note the order: Year first, then month, then day.
        // Also, since we display it, we put separators in and add 1 to month (since Jan = 0).
        var str = tempd.getFullYear() + "-" + (tempd.getMonth() + 1) + "-" + tempd.getDate();
        console.log("Today's date: " + str);

        var localVal = localStorage.getItem('DateOpened');
        console.log("Previous localVal: " + localVal);

        if(localVal != null){
            var difference = localVal.localeCompare(str);
        }
            console.log("localeCompare: " + difference);
        //If stored date is older than this date do something:
        if(localVal  == null || difference < 0){
                        // If the localstorage doesn't exist, nothing happens
                        console.log("App will now run once for today.")

        //Run the JS for the app (give new quote since it is a new day)

                                var Quotes = [];
                                var ID = [];
                                var Tag = [];
                                        //Get quotes from JSON file
                                        $.ajax({
                                                            url: './json/facts.json',
                                                            dataType: 'json',
                                                            type: 'get',
                                                            success: function(data){
                                                                    console.log(data);
                                                                    console.log("successfully imported the JSON file");
                                                                    console.log(data.length); //Returns 64
                                                                    totalQ = data.length;
                                                                    for (i = 0; i < totalQ; i++){
                                                                                ID[i] = data[i][0];
                                                                                Tag[i] = data[i][1];
                                                                                Quotes[i] = data[i][2];
                                                                    }
                                                                console.log(Quotes.length);
                                                    }
                                        })
                                        .done(function(data){ //This waits for AJAX to be done before running

                                                var Quote = new String;
                                                var qnumber = 0;
                                                var totalQ //The total number of available quotes to choose from
                                                var CurrentImage = String;

                                                totalQ = Quotes.length - 1;
                                                console.log("TotalQ = " + totalQ);

                                                //Get list of which facts have already been seen
                                                var seen = JSON.parse(localStorage.getItem('seen'));
                                             console.log("var seen = " + seen);
                                                    if (seen == null){
                                                            var seen = new Array(totalQ);
                                                         for (var i = 0; i < seen.length; ++i) {
                                                                    seen[i] = false;
                                                            }
                                                         console.log("var seen = " + seen);
                                                    }

                                             //Get a Quote
                                                ChooseQuote(0,totalQ);

                                                //Change the image depending on the quote

                                                //replace the quote with a new one
                                                $("#qotd:visible").hide();
                                                $("#ShineDiv").addClass("shine");
                                                $(".facebox").css("background-image",CurrentImage);
                                                $(".facebox").css("opacity","1.0");
                                                $("#qotd").html(Quote);
                                                console.log("Image Changed");

                                                increaseXP();
                                                //================
                                            function ChooseQuote(min,max){
                                                 //Choose 2 random numbers, one for quotes one for image
                                                    var RandomNum = Math.floor(Math.random()*(max-min+1)+min);
                                                    var ImageNum = Math.floor(Math.random()*(5-1+1)+1);

                                                    Quote = Quotes[RandomNum];
                                                    CurrentImage = "url(./images/FaceBoxes/" + Tag[RandomNum] + "/" + Tag[RandomNum] + ImageNum + ".png)";
                                                    if (seen[RandomNum] == true ) {
                                                        //Choose new quote
                                                        ChooseQuote(0,totalQ);
                                                        console.log("Has this fact been seen before? Answer: " + seen[RandomNum] );
                                                        var numOfTrue = 0;
                                                                        for(var i=0; i<=totalQ; i++){
                                                                                if(seen[i] === "true")
                                                                                numOfTrue++;
                                                                        }
                                                            if (numOfTrue = totalQ) {
                                                                             localStorage.setItem('All_Facts_Seen:', true);
                                                                             console.log("All the Facts have been seen. Resetting Facts.");
                                                                             seen = new Array(totalQ); //Empty the seen Array
                                                                             localStorage.setItem('seen', JSON.stringify(seen)); //Save the empty Array
                                                                        }
                                                            }
                                                 else {
                                                        seen[RandomNum] = "true";
                                                        console.log("This fact has never been seen.")
                                                    }
                                                    console.log(Quote);
                                                    console.log(CurrentImage);

                                                 //Remeber which fact is displayed
                                                 localStorage.setItem('Curr_Fact', Quote);
                                                 localStorage.setItem('Curr_ImgUrl', CurrentImage);
                                                 localStorage.setItem('seen', JSON.stringify(seen));
                                                    }
                                    //==================
                                //Save the current date in local storage
        localStorage.setItem('DateOpened',str);
                             console.log("The App Ran, you can get a new fact tomorrow");
                                console.log("Current LocalStorage Date: " + str);
                                });
        }
     else {
            //If it is still the same day, show the last fact & image
             var Quote = localStorage.getItem('Curr_Fact');
             var CurrentImage = localStorage.getItem('Curr_ImgUrl');

               $("#qotd:visible").hide(); //Hide main quote
               $("#ShineDiv2").addClass("shine");
                        if ($('h2').hasClass("invisible")){ //if heading is invisble show it, remove that class
                            $('h2').css('visibility','visible').hide().fadeIn('slow').removeClass("invisible");
                        }
                        $(".facebox").css("background-image",CurrentImage);
               setTimeout( function() { //This is so that the first image and new image don't crossfade/stretch
                                $(".facebox").css("opacity","1.0");
                                }, 100);

                        $("#qotd").html(Quote); //Replace the main message with the actual quote

                        console.log("Showing the same fact as before. Wait until tomorrow to get a new fact.");
        }
    },
};

$(window).load(function() {
var headerh;
var footerh;
var pageh;
var hbtn_nextq;

headerh = $("div[data-role='header']").outerHeight();
footerh = $("div[data-role='footer']").outerHeight();
pageh = $(window).height();

console.log(headerh + " " + footerh + " " + pageh);

var difference = pageh - headerh - footerh;

$(".ui-content").css("height", difference);

var h1, h2, h3, h4 , h5;

h1 = $(".ui-content").outerHeight();
h2 = $(".ui-content>h2").outerHeight();
h3 = $("#quotebox").outerHeight(true);
h4 = $("#nextQ").outerHeight();

h5 = ((h1 - h2 - h3 - h4) /2) - 50;
    console.log(h1);
 console.log(h2);
 console.log(h3);
    console.log(h4);
 console.log(h5);

 var h5s = h5 + "px";

//$("#quotebox").css("margin-top",h5s);
$(".ui-content>h2").css("margin-top",h5s);
//$("#nextQ").css("margin-bottom",h5s);

//ShowXP();
//Make the quotebox flip over on click
$(".facebox, #ShineDiv").click(function(){
    $("#quotebox").removeClass("PulseEffect")
    $("#ShineDiv").removeClass("shine");
    $(".facebox").css("opacity","0");
    $("#qotd").fadeIn("slow", function(){});
});

ShowXP();

});

function increaseXP(){
    //Get the lvl and xp from storage
    var lvl = localStorage.getItem("lvl", lvl);
    var XP = localStorage.getItem("XP", XP);
    console.log("Old XP = " + XP + " Old Level = " + lvl);

    lvl = parseInt(lvl);
    XP = parseInt(XP);

    //Increase XP
    XP = XP + 25;

    //Increase lvl
    if (XP >= 100){
      lvl = lvl + 1;
      localStorage.setItem('XP',XP);
      localStorage.setItem('lvl',lvl);

      UpdateXP(XP);
        setTimeout(function() {
      ShowUP(lvl);
        }, 200);
      XP = XP - 100;
                     console.log("Current XP = " + XP + " Current Level = " + lvl);
      UpdateXP(XP);
    }

    localStorage.setItem('XP',XP);
    localStorage.setItem('lvl',lvl);
    UpdateXP(XP);

}

function ShowXP(){
    var XP = localStorage.getItem("XP");
    var lvl = localStorage.getItem("lvl");

    if (XP == null){
        XP = 0;
        localStorage.setItem("XP", XP);
    }
    if (lvl == null){
        lvl = 1;
        localStorage.setItem("lvl",lvl);
    }

    lvl = parseInt(lvl);
    XP = parseInt(XP);

    $("#lvl").text(lvl);

    $(".XPmeter > span#bar").each(function() {
      $(this)
        .data("origWidth", XP)
        .width(0)
        .animate({
          width: $(this).data("origWidth") + "%" // or + "%" if fluid
        }, 1200);
    });

}

function UpdateXP(XP){
    $(".XPmeter > span#bar").each(function() {
      $(this)
        .animate({
          width: XP + "%" // or + "%" if fluid
        }, 1200);
    });
}

function ShowUP(new_level){
    $("#medal").animate({height: "100px" },600, function(){
        $("#lvl").text(new_level);
        $("#medal").animate({height: "50px" },600);
    });

    $(".XPmeter > span#bar").width("0");
}

//-------------------------------------------------------------//
//                                                             //
// This is the scirpt that will get the facts and display them //
//                                                             //
//-------------------------------------------------------------//

Comment: The return value of `$("#nextQ").click(function(){...})` is not a function
Comment: why does it have to return a function?
Comment: You will have to answer this, but from the code you act like it is a function: `app.receivedEvent('deviceready');`
Comment: doesn't that just say run the code for that event? I got that from the startup guide for making a phonegap app so I'm not really sure how  `app.receivedEvent('deviceready');` works. I've read many guides on it but none seem to be relevant to what I am doing.
Comment: [JavaScript | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript)
Comment: That's not helpful.
Answer: That's because your receivedEvent is not defined as a functions but as a property of the app object so it can't be called as a function.
You to change it from:
// Update DOM on a Received Event
receivedEvent:

to:
// Update DOM on a Received Event
receivedEvent: function(id) {

app.receivedEvent is not a function


Calling Azure storage account REST APIs using Azure Data Factory Managed Identity

Question: We are hoping to make a call to the "Blob Containers - Create" api endpoint i.e. https://learn.microsoft.com/en-us/rest/api/storagerp/blob-containers/create?view=rest-storagerp-2023-01-01&tabs=HTTP from the Azure data factory pipeline web activity.
While this typically works seamlessly with a dedicated Azure AD application registered with a secret, our aim is to execute the call using the Managed Identity of the Data Factory. The ADF's Managed Identity already holds the storage blob data contributor role assigned on the storage account.
Given that the REST endpoint necessitates the mandatory authorization header requiring a bearer token issued by Azure AD, we are currently encountering an issue in obtaining it for ADF's managed identity.
Any assistance on this will be appreciated.
Answer:
Note that, there is no need to generate access token separately while
using managed identity authentication.

Initially, I added Storage Blob Data Contributor role to ADF managed identity under storage account like this:

In your Azure data factory pipeline web activity, use below parameter values in Settings tab:
URL : https://management.azure.com/subscriptions/subId/resourceGroups/rg_name/providers/Microsoft.Storage/storageAccounts/storacc/blobServices/default/containers/sricontainer01?api-version=2023-01-01
Method:  PUT
Body: {"null": "null"}
Authentication:  System Assigned Managed Identity
Resource: https://management.azure.com
Headers: Content-Type : application/json

When I ran the pipeline, I got the response with Succeeded status as below:

To confirm that, I checked the same in Portal where container created successfully in storage account like this:


Como fazer a pagina esperar um pop-up?

Question: Criei um método para chamar uma pop-up para validar um evento, mas esse evento acontece junto com a validação.
A pop-up aparece e o evento dispara. como faço para o evento esperar a pop-up?
if(self.Cookie("my_coocke") == undefined){
    self.OpenConfigurationDialog();
    event();

Comment: [`setTimeout`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout) não soluciona o teu problema?
Answer: Cara, tem duas formas de resolver isso, ou você usa a função timeout do Javascript ou você usa o Sleep do PHP, fora o usleep() que Atrasa a execução em milionésimos de segundo.
Ex Javascript:
setTimeout(function() { console.log("setTimeout: Ja passou 1 segundo!"); }, 1000);
setInterval(function() { console.log("setInterval: Ja passou 1 segundo!"); }, 1000);

O que o código imprime na tela:
setTimeout: Ja passou 1 segundo!
setInterval: Ja passou 1 segundo!
setInterval: Ja passou 1 segundo!
setInterval: Ja passou 1 segundo!
setInterval: Ja passou 1 segundo!
...

Aprofundando:
var recursiva = function () {
    console.log("Se passaram 1 segundo!");
    setTimeout(recursiva,1000);
}
recursiva();

Ex Sleep PHP
int sleep ( int $seconds )
Visão próxima de codificação
<?php
// Hora atual
echo date('h:i:s') . "\n";

// Dorme por 10 segundos
sleep(10);

// Acorde!
echo date('h:i:s') . "\n";
?>

Como fazer a pagina esperar um pop-up?


How to hide overflowed element but only on the top?

Question: I only want to hide elements thats overflowing on the top. In my document blue is the background img and the child is skewed div.
fiddle

.parent {
  margin: 50px;
  height: 200px;
  width: 200px;
  background: red;
}
.child {
  height: 200px;
  width: 200px;
  background: blue;
      transform: skewY(20deg);
    -webkit-transform: skewY(20deg);
    -moz-transform: skewY(20deg);
    -o-transform: skewY(20deg);
}

Answer: Need to add another parent with overflow: hidden:

.ovh-parent {
  overflow: hidden;
}
.parent {
  margin: 50px;
  height: 200px;
  width: 200px;
  background: red;
  margin-top: 0;
}
.child {
  height: 200px;
  width: 200px;
  background: blue;
  transform: skewY(20deg);
  -webkit-transform: skewY(20deg);
  -moz-transform: skewY(20deg);
  -o-transform: skewY(20deg);
}

Does this work out for you? See the preview below...
Preview
Comment: 1+ Nice answer! And it's simpler than mine.
Answer: You would need to add another div outside of the parent that would help with hiding the overflow.

.overflow{
  margin: 20px;
  overflow: hidden;
  height: 300px;
  width: 200px;
  position: relative;
}
.parent {
  height: 200px;
  width: 200px;
  background: red;
  position: absolute;
  top: 0;
}
.child {
  height: 200px;
  width: 200px;
  background: blue;
  transform: skewY(20deg);
  -webkit-transform: skewY(20deg);
  -moz-transform: skewY(20deg);
  -o-transform: skewY(20deg);
}

Answer: You don't need to add another ancestor if you use this trick:

Add overflow: hidden to hide overflow
Increase the height to avoid clipping the overflow at the bottom
Add a negative margin to prevent the previous step from affecting following contents
Use a background image instead of a background color. For example, use a gradient.
Use background-size to set the size of that background image. Do not repeat the background.

.parent {
  overflow: hidden;
  margin: 50px;
  height: 300px;
  margin-bottom: -100px;
  width: 200px;
  background: linear-gradient(red, red) no-repeat;
  background-size: auto 200px;
  margin-top: 0;
}
.child {
  height: 200px;
  width: 200px;
  background: blue;
  transform: skewY(20deg);
  -webkit-transform: skewY(20deg);
  -moz-transform: skewY(20deg);
  -o-transform: skewY(20deg);
}

Lorem ipsum


Changing CBAdvertisementDataManufacturerDataKey from peripheral

Question: Is there any way to modify CBAdvertisementDataManufacturerDataKey from CBPeripheralManager? I understand I can get the CBAdvertisementDataManufacturerDataKey from CBCentralManager.
The reason I want to do this is because I want the peripheral to advertise a 10-byte value without resorting to having the central connect to it, discover services, and then reading a characteristic which would contain the 10-byte value.
Answer: No, this is currently not possible as of iOS 7. The Manufacturer Data is reserved by Apple and is unmodifiable (at least on non-jailbroken devices). If you were writing the firmware for your own peripheral, this would not be a problem. But since the CoreBluetooth api is a layer above Apple's actual implementation of the iOS ble firmware, we face the limitations of what they actually expose. You may consider advertising you own custom service and displaying the same value you would have put in the manufacturer data, however.
Comment: Yes, it would be in the advertisement data seen when a device is discovered. However, there are limitations on advertising in the background vs. foreground. Check out the peripheralManager docs for more details https://developer.apple.com/library/ios/documentation/CoreBluetooth/Reference/CBPeripheralManager_Class/Reference/CBPeripheralManager.html
Comment: would I be able to retrieve this custom service from the peripheral (iOS device) without having to connect to it?
Comment: OH - the local name. yes im aware of this but I require peripherals to advertise in the background as well... feeling very limited with the current iOS SDK


Sampling distribution of the mean of a Beta

Question: Say we have $X \sim \text{Beta}(\alpha, \beta)$. What's the sampling distribution of its sample mean?
In other words, what distribution does the sample mean $\bar{X}$ of a Beta follow?
Comment: The asymptotic distribution of a sample average of a random sample will be governed by the CLT whenever the variance exists, which does not require that $\alpha,\beta>1$.
Comment: Wow - tough question.  Might be hard to characterize over all values of alpha and beta given the strange shapes that occur for some parameter choices, but when they're both greater than 1, it looks like it will tend asymptotically to Gaussian per CLT, but I can't say for sure.
Answer: I thought this was an interesting question so here's a quick visual exploration. For $X\sim Beta(\alpha_1,\alpha_2)$, I first selected 4 separate Beta distributions (PDFs shown below).

Then I collected sample means, $\bar X = \frac{1}{n}\sum_{i=1}^n x_i$ and plotted the corresponding histograms as shown below. The results look Normal and I'm inclined to believe @ChristophHanck's assertion that the Central Limit Theorem (CLT) is at work here.

MATLAB code
<code>% Parameters
n = 5000;
K = 5000;
% Define Beta distributions
pd1 = makedist('Beta',0.25,0.45);
pd2 = makedist('Beta',0.25,2.5);
pd3 = makedist('Beta',4,0.15);
pd4 = makedist('Beta',3.5,5);
% Collect Sample Means
X1bar = zeros(K,1);
X2bar = zeros(K,1);
X3bar = zeros(K,1);
X4bar = zeros(K,1);
for k = 1:K                           % get K sample means
    X1bar(k) = mean(random(pd1,n,1)); % take mean of n samples
    X2bar(k) = mean(random(pd2,n,1));
    X3bar(k) = mean(random(pd3,n,1));
    X4bar(k) = mean(random(pd4,n,1));
end
% Plot Beta distribution PDFs
Xsupport = 0:.01:1;

figure, hold on, box on
title('Beta(\alpha_1,\alpha_2) PDFs')
plot(Xsupport,pdf(pd1,Xsupport),'r-','LineWidth',2.2)
plot(Xsupport,pdf(pd2,Xsupport),'b-','LineWidth',2.2)
plot(Xsupport,pdf(pd3,Xsupport),'k-','LineWidth',2.2)
plot(Xsupport,pdf(pd4,Xsupport),'g-','LineWidth',2.2)
legend('(0.25,0.45)','(0.25,2.5)','(4,0.15)','(3.5,5)')

figure
s(1) = subplot(2,2,1), hold on, box on
    histogram(X1bar,'FaceColor','r')
s(2) = subplot(2,2,2), hold on, box on
    histogram(X2bar,'FaceColor','b')
s(3) = subplot(2,2,3), hold on, box on
    histogram(X3bar,'FaceColor','k')
s(4) = subplot(2,2,4), hold on, box on
    histogram(X4bar,'FaceColor','g')
title(s(1),'(0.25,0.45)')
title(s(2),'(0.25,2.5)')
title(s(3),'(4,0.15)')
title(s(4),'(3.5,5)')
</code>

Edit: This post was a quick attempt to provide the OP something. As pointed out, we know the Central Limit Theorem (CLT) implies these results will hold for any distribution with a finite variance.
Comment: You have run a bunch of examples demonstrating the CLT.  As noted in comments, there's nothing special about Beta distributions in these examples: you may start with literally *any* finite-variance distribution and obtain identical results.
Comment: You are correct.  I upvoted that comment but provided an answer because there was none.  Of course CLT holds for a finite-variance distribution.  I even mentioned the commenter in the answer.  Should I delete this answer?  Or make it community?
Answer: Note: see also for the same question: Sum of n i.i.d Beta-distributed variables.
For the case of a uniform distribution, $\text{Beta}(1,1)$, the distribution of the sum of a number of independent variables (and the mean is related) has been described as the Irwin-Hall distribution.
If $$X_n = \sum_{i=1}^n Y_i \quad \text{ with } \quad U_i \sim \text{Beta}(1,1)$$
then you have a spline of degree $n-1$
$$f_X(x;n) = \frac{1}{(n-1)!}  \sum_{j=0}^{n-1} a_j(k,n)x^j \quad \text{ for } \quad k \leq x \leq k+1$$
where the $a_j(k,n)$ can be described by a recurrence relation:
$$a_j(k,n) = \begin{cases} 1 & \quad k=0,j=n-1  \\
                      0 & \quad k=0,j< n-1 \\
           a_j(k-1,n) + (-1)^{n+k-j-1} {{n}\choose{k}} {{n-1}\choose{j}} k^{n-j-1}  & \quad k>1
     \end{cases}$$

You could see the above formula as being constructed by a repeated convolution of $X_{n-1}$ with $Y_n$ where the integral is solved piecewice. Can we possibly generalize this for Beta distributed variables with any $\alpha$ and $\beta$?
Let $$X_n(\alpha,\beta) = \sum_{i=1}^n Y_i \quad \text{ with } \quad U_i \sim \text{Beta}(\alpha,\beta)$$
We expect the function $f_X(x;n,\alpha,\beta)$ to be split up in $n$ pieces (though possibly not a spline anymore). The convolution to compute the distribution of $X_{n}(\alpha,\beta) = X_{n-1}(\alpha,\beta)+U_n$ will be something like:
$$f_X(x;n,\alpha,\beta) = \int^{\text{min}(1,x)}_{1-\text{min}(1,n-x)} f_X(x-y;n-1,\alpha,\beta) y^{\alpha-1}(1-y)^{\beta-1}  dy$$

For $n=2$:

$$f_X(x;n,\alpha,\beta) = \begin{cases}  \int_{0\phantom{-x}}^{x} ((x-y)y)^{\alpha-1}((1-x+y)(1-y))^{\beta-1}   dy & \quad \text{if $0 \leq x \leq 1$} \\
\int_{x-1}^{1} ((x-y)y)^{\alpha-1}((1-x+y)(1-y))^{\beta-1}   dy & \quad \text{if $1 \leq x \leq 2$}
\end{cases}$$

For integer $\alpha$ and $\beta$: the terms like $((x-y)y)^{\alpha-1}$ and $((1-x+y)(1-y))^{\beta-1}$  can be expanded for integer values of $\alpha$ and $\beta$, such that the integral is straightforward to solve.
For example:
$$\begin{array}{} f_X(x;2,2,2) &=& \begin{cases}  \frac{1}{30} x^3(x^2-5x+5) & \quad \text{if $x \leq 1$} \\
\frac{1}{30}(2-x)^3(x^2+x-1) & \quad \text{if $x \geq 1$}
\end{cases}\\
\\
f_X(x;2,3,3) &=& \begin{cases}  \frac{1}{630} x^5(x^4-9x^3+30x^2-42x+21) & \quad \text{if $x \leq 1$} \\
\frac{1}{630}(2-x)^5(x^4+x^3-2x+1) & \quad \text{if $x \geq 1$}
\end{cases} \end{array}$$

The solution for integer values of $\alpha$ and $\beta$ will be a spline as well. Possibly this could be cast in some nice (or more likely not so nice) formula for more general situations (not just $n=2$ and $\alpha=\beta=2$ or $\alpha=\beta=3$). But at this point one needs quite a few cups of coffee, or better an infuse, to tackle this stuff.


$0=1$, or I have done something wrong.

Question: $$\int \frac{1}{x}dx=\int1dx \frac{1}{x}-\int \left(\frac{d}{dx}\frac{1}{x}\int1dx\right)dx=1+\int\frac{1}{x}dx \Leftrightarrow 0=1$$
Comment: Remember, indefinite integrals are only defined up to an additive constant.
Comment: $+C{}{}{}{}{}{}{}$
Comment: 1 *does* equal 0 .... plus a constant.
Answer: yes! This is one of the integrals you should always remember! Recall that $$\frac{d}{dt}\left(\ln(x)\right)=\frac{1}{x}$$
hence $$\int \frac{1}{x} dx = \ln(|x|) + Constant$$
Comment: @ZacharySelk, my lecturer would kill me for that, thanks ahah
Answer: When $f$ is continuous the "$=$" sign in $g(x)=\int f(x)dx$  is not literally "equals". It means that $g$ is an anti-derivative of $f.$ But $g+C$ is also an anti-derivative of $f$ for any constant $C.$

$0=1$, or I have done something wrong.


What's the protocol-level difference between IPSec and "Cisco IPSec"?

Question: Most VPN clients distinguish between IPSec and "Cisco IPSec." For example, (Apple's) iOS treats them as essentially separate things.
But I can't find any explanation of what the protocol-level differences are. They may be minor, but there definitely appear to be differences.
Can someone shed light on this? Even just a pointer to a detailed explanation would help a great deal. Thanks!
Comment: @MadHatter I've clarified in the question by adding the word "(Apple's)" in front of iOS. I did definitely mean Apple's iOS.
Comment: @petrus "L2TP" on Apple's iOS is actually L2TP+IPSec, and is the default non-cisco IPSec implementation. "IPSec" on Apple's iOS is actually Cisco IPSec. This is confusing, yes.
Comment: @Dave: ooops, my bad, thanks for clarifying.  Also Apple's bad, but hey, what can you do?
Comment: (My best guess right now is that there's no real protocol difference, but that Cisco IPSec typically uses PSK and xauth in isakmp. But I don't really know -- looking to the experts for this one. Thanks. ;-)
Comment: My iPhone doesn't have two different IPSec. It has L2TP, PPTP and IPSec, which client code seems to be provided by Cisco. Could you please share a screenshot showing both clients ?
Comment: Wrong IOS, I suspect.  IOS (Internetwork Operating System) is the OS used by better-than-consumer-grade CISCO routers, and was for years before Apple came along, borrowed yet another thing that was already in use, and claimed it was theirs ;-)
Answer: From my understanding, "Cisco IPSec" is just marketing speak for IPSec with some pre-defined settings for AH/ESP, tunnel/transport mode, etc. pp.
When you read the RFCs, you see that they deliberately leave room for implementations...you, as the network admin setting up the IPSec connection have quite a lot of options to choose from for the protocol (and you need to). Cisco simplified this a great deal by saying "Both participiants do ESP, they have encryption modes X, Y, Z at their disposal, (...)".
Comment: This is my belief, too. I'm wondering what specific settings we're looking at as well. My best guess is that the StrongSwan wiki pages about Apple iOS hold at least some of the answer: http://wiki.strongswan.org/projects/strongswan/wiki/IOS_(Apple)
Comment: Tell me about it, I searched for those quite a while as well, but no dice. If you ever find out about them, make sure to drop me a note! :)
Comment: I've decided to accept this as the answer. I suspect it's the only good one we're gonna get. Thanks, @Roman!
Answer: I understand from your comment that you are wondering the differences between L2TP+IPSec and IPSec only.

L2TP is a tunneling protocol. No encryption.
IPSec is a security protocol (encryption + authentication)

When IPSec is used "alone", it can oper in two modes :

"tunnel": The tunnel is in fact a GRE tunnel (IP in IP), but the payload is encrypted.
"transport": IP payload is encrypted, without any encapsulation.

Tunnel mode is mostly used to connect two networks, from router to router, while transport mode will be used for road-warriors, devices (laptop, iPhone), connecting to corporate network.
L2TP over IPSec is similar to transport mode, connecting a remote device to a concentrator. The remote device can be however a router.
Comment: Thanks, @petrus, but: alas, that is not what I am asking about at all. Please re-read the initial question.


How to implement an (iOS) action sheet but with multiple buttons in one line?

Question: I am wondering that how to implement the action sheet like the iPhone built-in photo edit app.
Go to the Photos app, then select one photo, then click crop button. There is a button called Constrain. Clicking that, an action sheet ( or a popover view?) Will show up. It has 3 buttons on one line. But seems action sheet can only have one button in a line.
So how do I do that?
Comment: Private subclass. Don't even dream about it.
Answer: Write your own view and viewController. Design the view to look as you want, when you want to show the 'action sheet' have your controller animate the view in from the bottom just as the system does. Its not all that hard to do a custom sheet like this. Do yourself a favor, don't add the code to your existing VC, but create a new class with a delegate and a simple protocol, so that it acts a bit like the action sheet. when the user finally taps the button the protocol returns the result using a protocol callback. You can then reuse this class elsewhere (or post it on github for fame and fortune!)
Comment: David, finally I followed your advice and have some code to get the action sheet I wanted. The code is here: https://github.com/russj/MBActionSheet
Comment: Great! Glad this worked out for you. Will look at your code soon. You could accept my answer as the solution, we both get points if you do so.


Cookie is Null in Other Class

Question: Method to set user cookie, in UserRest class
@Component
@Path("/user")
public class UserRest{
    .............

    @POST
    @Path("/login")
    @Produces(MediaType.APPLICATION_JSON)
    public Response login(@FormParam("username") String username,
    @FormParam("password") String password){
        return Response.ok(messageDto)
           cookie(new NewCookie("tokenId", "12345", "/medinetra/rest_service/", "192.168.1.2", "", 1800, true))
           .build();
   }

It successful when i try to get cookie in UserRest class
@GET
@Path("getcookie")
@Produces(MediaType.APPLICATION_JSON)
public Response getCookie(@CookieParam("token") String token){
    System.out.println(token); //=> write 123456
    return Response.status(200).entity("ok").build();
}

But it will return null when i put getCookie method in CustomerRest.
It also not working when i try the other manner to set cookie.
Response.ok(messageDto)
    .header("Set-Cookie", "token="+token+";Domain=192.168.1.2;Path=appname/rest_service;")
   .build();

How can i handle this, how to get cookie from the other class.
Answer: In the first example you aren't specifying a path.  With HTTP cookies if you don't specify a path then it defaults to the path of the resource that returned the cookie.  You should use one of the NewCookie constructors that takes more arguments and supply the path.
In the second example you are naming your cookie tokenId and not token as in the first example.  If your CustomerRest code looks like your UserRest code then you are asking for the cookie named token and not tokenId.
Comment: Sorry, actually it is still not work. I have updated my code above.
Comment: This is my url example http://192.168.1.2:8080/appname/rest_service/patient/getdoctorpatient

Cookie is Null in Other Class


Diferenças entre declarações de variáveis em C#

Question: Qual a diferença entre essas declarações:
Classex xx = new Classex();
var xx = new Classex();
Classex xx;

Se no final consigo usar tudo da mesma forma (métodos, propriedades...)
Ex.:
Eu crio uma lista: List<Classex> lstx = new List<Classex>();
Adiciono alguns valores: lstx.Add(...)
Depois quero pegar alguns valores dessa lista e inserir em outra, qual a melhor maneira de se fazer:
var lstx_filtrada = new List<Classex>;,
List<Classex> lstx_filtrada= new List<Classex>;
List<Classex> lstx_filtrada;

Answer: Sobre o uso do var ou o tipo explicitamente já foi em respondi em Quando usar var em C#?, por este motivo acho desnecessário postar aqui os dois primeiros exemplos.
A terceira opção você não consegue usar da mesma forma, se tentar usar o objeto uma exceção NullReferenceException será lançada porque não há um objeto instanciado para a variável. Só poderá ser usado se mais pra frente inicializar o objeto de alguma forma. Sem um objeto formado qualquer acesso a um membro da instância falhará porque não tem nada para acessar. Note que o acesso aos membros da classe (portanto os estáticos) é possível porque não depende de instância.
Em C# 8 passa ser proibida essa forma de declaração, a não ser que mantenha desligado a verificação de objeto nulo, ou declare assim:
Classex? xx;

Coloquei no GitHub para referência futura.
Answer: A diferença é:
1º Caso

Classex xx = new Classex();

Você criou uma variável xx do tipo Classex que já foi inicializada com uma nova instância de Classex.
2º Caso

var xx = new Classex();

A mesma coisa do anterior, só que quando você declarou var você atribuiu ao compilador a responsabilidade de 'descobrir' qual é o tipo de xx, como já esclarecido na pergunta e resposta referenciada.
Tecnicamente as duas declarações são iguais, mas uma delas (a que usa o var) é uma forma simplificada de codificar. Se a variável está sendo criada naquele momento e já recebendo o seu valor o compilador infere que o tipo dela será o mesmo tipo do objeto que ela está recebendo.
3º Caso

Classex xx;

Como no primeiro, você especificou explicitamente o tipo da variável. Mas, em qualquer tentativa de uso sem uma inicialização resultará em erro (em alguns casos de compilação inclusive), como já explicado na resposta do Maniero.


Chef / Vagrant - Kitchen cant connect to Update Jenkins

Question: Iam getting crazy with Chef, Vagrant and Test-Kitchen.
We have an customized Jenkins Cookbook, it works on "normal" Clients without Cooperate Network Proxys, but fails behind with the following error.
 - create new file /tmp/kitchen/cache/jenkins-cli.jar
             - update content in file /tmp/kitchen/cache/jenkins-cli.jar from none to 0b49c2
             (new content is binary, diff output suppressed)

           * remote_file[/tmp/kitchen/cache/update-center.json] action create_if_missing
       [2015-05-11T16:28:32+00:00] ERROR: Error connecting to http://mirrors.jenkins-ci.org/updates/update-center.json, retry 1/5
       [2015-05-11T16:30:43+00:00] ERROR: Error connecting to http://mirrors.jenkins-ci.org/updates/update-center.json, retry 2/5
       [2015-05-11T16:32:54+00:00] ERROR: Error connecting to http://mirrors.jenkins-ci.org/updates/update-center.json, retry 3/5
       [2015-05-11T16:35:06+00:00] ERROR: Error connecting to http://mirrors.jenkins-ci.org/updates/update-center.json, retry 4/5
       [2015-05-11T16:37:17+00:00] ERROR: Error connecting to http://mirrors.jenkins-ci.org/updates/update-center.json, retry 5/5

All other ressources are downloaded without any problems (using vagrant proxy plugin). The Host is based on Windows 7, the guest is CentOS 6.6
Problem identfied: jenkins-cli.jar is not using system proxy, iam not able to download plugin when logged in to the VM. But no solution found so far (;
Comment: Configuring the proxy in test-kitchen should help you (see https://gist.github.com/fnichol/7551540 for the `driver.http_proxy` variables).
Comment: No changes (-: still fails at the update-center.json .. i have no idea why everything else works.. the only "interessting" is, that it is an redirect.. ?
Answer: As a quick workaround, simply set the attribute:
default['jenkins']['master']['mirror'] = 'http://example.lan'

to point to a local HTTP server, where the http://example.lan/updates/update-center.json is an empty JSON file (or, generally, the server returns 200 for the request GET /updates/update-center.json).
Also, please have a look at this line of code.


Fix given in the dependency jar did not reflect even after mvn clean install

Question: I have a dependency jar in which there was a bug. Developer gave a fix.
Artifact version was not changed. So I just did a mvn clean install on my project. But It did not download the changes done for the artifact.
So, not sure where it is going wrong.
Comment: use the option -U to force the dependency update. also see here: http://stackoverflow.com/questions/4701532/force-maven-update
Comment: "Artifact version was not changed" - if it is a fix version, it should have a new version number (unless it is a -SNAPSHOT version, where the -U fix applies)
Comment: It is SNAPSHOT version
Answer: Try doing this from Console, then do a mvn clean.
<code>find ~/.m2  -name "*.lastUpdated" -print -exec rm {} \;
</code>
Else, download the jar, and install it manually using maven, then clean it


Find all of the prime ideals of $\mathbb{Z}_3 \times \mathbb{Z}_4$

Question: My assignment was to find all of the prime ideals of $\mathbb{Z}_3 \times \mathbb{Z}_4$ so I first found all of the ideals which are:
$\mathbb{Z}_3 \times {0}$, ${0} \times \mathbb{Z}_4$,  $\mathbb{Z}_3 \times \mathbb{Z}_2$,${0} \times \mathbb{Z}_2$
I then just modded the whole group by each of the ideals (ignoring the trivial cases). Which told me that
${0} \times \mathbb{Z}_4$, and $\mathbb{Z}_3 \times \mathbb{Z}_2$ where both maximal and prime.
Is there an easier way to do this by just looking at the structure of the ring? It feels like the way I approached this question was much slower than it should have been.
Comment: Use the Chinese remainder theorem and look for the prime ideals $I$ of the (principal) ring $A=\mathbb Z/ 12\mathbb Z.$ ($|A/I|$ must be a prime factor of $12$.)
Comment: You may find this interesting : [Find all prime ideals and maximal ideals of  Z/12Z](https://math.stackexchange.com/questions/1625743) and [Describe all prime and maximal ideals of  Zn](https://math.stackexchange.com/questions/2569986).
Answer: First of all,  when you're talking about ideals,  you've got rings, not groups.
Second, in $\Bbb Z_3×\Bbb Z_4\cong \Bbb Z_{12}$, the prime ideals are the prime ideals in $\Bbb Z$ containing $(12)$, by the correspondence theorem.
So we get just $(12)\subset(2),(3)\subset \Bbb Z$, which correspond to $(\bar2),(\bar3)\subset \Bbb Z_{12}$.  These are $\{(2,2),(1,0),(0,2),(2,0),(1,2),(0,0)\}, 0×\Bbb Z_4$ (after isomorphism).
So, note:  $\Bbb Z_3×\Bbb Z_2$ is wrong.   It contains $(1,1)$, so any ideal containing it is the whole ring.
You can also tell because the respective quotients, $\Bbb Z_2,\Bbb Z_3$ are integral domains.
Comment: The whole ring is a trivial ideal of any ring.
Comment: @DougM yes, but by a prime ideal is meant a proper ideal.  Also there was a typo.   I meant $\Bbb Z_3×\Bbb Z_2$, as the OP wrote.


Solve for $\mu$ in $\epsilon^\frac32=\mu^\frac32+\frac{(\pi k_B T)^2}{8}\frac1{\sqrt\mu}$

Question: $$\epsilon^\frac32=\mu^\frac32+\frac{\left(\pi k_B T\right)^2}{8}\frac1{\mu^\frac12}$$
I am given that $\epsilon\approx\mu$ and $(1+x)^\alpha\approx1+\alpha x$ when $x\to0$.
I have tried manipulating this to
$$1-\frac{8}{(\pi k_B T)^2}\mu^\frac12(\epsilon^\frac32-\mu^\frac32)=0\Leftrightarrow\left[1+\mu^\frac12(\epsilon^\frac32-\mu^\frac32)\right]^{-\frac{8}{(\pi k_B T)^2}}=0$$
but this doesn't seem to lead anywhere.
any hints please?
the solution is one of these $T_f=\epsilon/k_B$:
Comment: In principle, you can write $x=\sqrt{\mu}$, rearrange to get $x^4-\epsilon^{3/2} x+(\pi k_B T)^2/8=0$, and solve using the quartic formula. But this is almost certainly not what you're expected to do; rather, you presumably should find $\mu$ as some kind of series expansion (in powers of $k_B T$, perhaps, since $\epsilon\to \mu$ as $k_B T\to 0$.)
Comment: Are you looking for a closed form solution?
Comment: yes! please read the post again, i have attached a picture. @PedroIgnacioMartinezBruera
Comment: The simplest solution is probably to plug in each of those answers in turn and see which one works. (In the sense of being correct to the desired order in $T/T_f$.) Also, should it be $\epsilon_f$ in your equation?
Comment: I think it would end up being the root of a quartic equation, which isn't very neat.
Comment: @Luyw You are probably expected to write $\mu = \epsilon (1+x)$ where $x$ is small because $\epsilon \approx \mu$ then use the binomial approximation and solve for $x$.
Comment: P vs NP. See which one satisfies the equation and pick that one
Comment: You can solve for μ by solving $μ^{3/2}+Βμ^{-1/2}-C=0$ where B and C are constants in your title which are constants with respect to μ. Fraction MathJax makes this looks worse.
Comment: @Semiclassical yes.
Comment: To simplify the "checking": One of the possible solutions has inconsistent units and can be ignored. The others are of the form $\mu=\epsilon_f(1+\alpha (T/T_f)^2)$ for various $\alpha$. So plug that in as your ansatz and use the binomial approximation to get rid of irrelevant terms.
Comment: @Semiclassical https://www.physicsforums.com/threads/solving-for-a-variable-in-an-equation-with-fractional-powers.1002586/post-6486816
Answer: $$\epsilon^\frac32=\mu^\frac32+\frac{\left(\pi k_B T\right)^2}{8}\frac1{\mu^\frac12}$$
Let $b=\frac{\left(\pi k_B T\right)^2}{8}$ and croos mulitiply to make
$$f(\mu)=\epsilon ^{3/2}\sqrt{\mu }-\mu ^2-b=0$$  Now, since you are told that $\epsilon\approx\mu$, expand $f(\mu)$ as a series around $\mu=\epsilon$. This gives
$$f(\mu)=-b-\frac{3}{2} \epsilon  (\mu -\epsilon )+O\left((\mu -\epsilon )^2\right)$$ Neglecting the higher order terms
$$\mu=\epsilon -\frac{2 b}{3 \epsilon }=\epsilon  \left(1-\frac{2 b}{3 \epsilon ^2}\right)$$ Just continue and introduce $T_f$.


Does a partial derivative existing at a point imply it exists in a neighbourhood of that same point?

Question: One sufficient condition for a function to be differentiable at a point $a$ is for it to have partial derivatives in $B_{\epsilon}(a)$ and they be continuous.
My question is if having partial derivatives at $a$, implies the existence of an $\epsilon$ where partial derivatives exist everywhere in $B_{\epsilon}(a)$.
Answer: Consider the function
$$f(x):=\left\{\eqalign{x^2\qquad&(x\in{\mathbb Q})\cr 0\ \qquad&(x\notin{\mathbb Q})\ .\cr}\right.$$
Then $f'(0)=0$, but $f$ is not  differentiable at any point $x\ne0$.
Comment: Christian thanks for your answer. I still have some doubts, though. If the existence of partial derivatives would imply continuity, then I would understand the importance of f not being continuous. However,  since they do not, why is it important to see f is not continuous for the existence of partial derivatives?
Answer: From the Wiki page
$\;\;\;\;\;\;\,$https://calculus.subwiki.org/wiki/Existence_of_partial_derivatives_not_implies_differentiable

we get the following counterexample . . .

If $f:\mathbb{R^2}\to\mathbb{R}$ is given by $f(x,y)=(xy)^{\large{{\frac{1}{3}}}}$, then

$f$ is continuous.$\\[4pt]$
$f_x(0,0)=0$ and $f_y(0,0)=0$.$\\[4pt]$
$f_x(0,t)$ does not exist if $t\ne 0$.$\\[4pt]$
$f_y(t,0)$ does not exist if $t\ne 0$.
Comment: Quasi, thanks. By the way, how would one go about to prove the existence of the partial derivatives in a neighbourhood? Is there a simpler way than just using the limit definition?
Comment: It depends on the form by which the function is defined.


Determining whether a string has a substring (word)

Question: I try to use a conditional to verify if a string contain a certain word, for example:
I want to use a method (regex?) to find if a string has the text "&SWE>clickable".
var text1 = "layer_legs";
var text2 = "layer_head&SWE>clickable";

if (....)
   document.write ("the layer is clickable")
else
   document.write ("the layer is not clickable")

How can I do that?
Answer: You can use String.indexOf. It returns -1 if the string is not found, otherwise it returns the index where the string was found. You can use it like this:
if (s.indexOf("&SWE>clickable") !== -1) { ... }

Answer:  if (text2.indexOf("&SWE>clickable") > -1) {
    ....

Answer: if (/&SWE>clickable/g.test(text2)) {
    // exists
}

EDIT: Using indexOf like others have posted might be better, since it's more readable and you don't need to escape characters. And arguably faster :/
Comment: Your regexp should be in parentheses, do u think so ?
Answer: try this :
if (text1.indexOf('&SWE>clickable')>=0){ ... }

or regex way :
var re = new RegExp('\&SWE\>clickable')
if (re.test(text1)){ ... }

Answer:  if(text1.indexOf(text2))
    document.write ("the layer is clickable")
 else
    document.write ("the layer is not clickable")


Guitar tutoring software that listens to your playing?

Question: I'm looking into learning classical guitar. I know most people will suggest getting lessons, and I'm looking into that.
But I was also wondering if there are any software tutors out there that can actually listen to and critique your playing through a standard computer microphone?
Comment: That sounds awesome, but I don't think that there's something like this currently available. I think the best way for you would be to get an teacher at least for like 5-10 hours to learn the basics like proper holding your guitar, hands and so on for classical playing. from that point you might use some good books and learn some things on your own and take 1 or 2 hours with a teacher once in awhile to keep on track. Do you have friends who play the classical guitar? They might help you out, too. sry, that's all I can tell you for now. (that's why I didn't choose to write this as an answer)
Answer: Rocksmith
Rocksmith is a guitar game from Ubisoft - it is meant to teach you to play songs on the guitar - a real guitar.
http://www.fakeplasticrock.com/2011/09/rocksmith-hands-on-preview/
It is compatible with any guitar with a standard instrument-out jack. It doesn't have the size of library that Rock Band 3 has, but the following points in its favor have resuscitated my interest in the music game genre:

It is intended as practice / training from the ground up. The 'game' portion is built around improving your guitar skills, not scoring points, making money, touring, getting groupies,  etc..
It is supposed to be able to detect your level of ability and scale the difficulty of songs accordingly. This will allow me (advanced beginner) to play at my own level and my son (rank beginner) to play at his. The jump between medium and hard on RB was significant.
It will allow me to use the guitars I've already got. I won't need to go out and buy a guitar just for Rocksmith, I'll be able to use an axe I love. And I won't be practicing on an instrument that I don't want to play in other circumstances.

Update: I have now owned this game for a while and it certainly is entertaining and educational. I have enjoyed playing it and it has been good at motivating me to play more. I will say that the between-songs interface seems clunky and needlessly slow on the Xbox 360. But the songs, mini-games, skill drills, etc., are all valuable in a way that Rock Band, etc., never were.
Additional Update: I have moved onto PC platform for Rocksmith. Rocksmith 2014 is much better, more focused and usable than the original. And I don't know if it's having a mostly modern PC or the difference in versions, but it's much faster and better in terms of just simple navigation which could be frustrating on the original 360 version. My original cable worked just fine with my Steam-purchased Rocksmith and if you hunt for sales, finding a good deal on the original (for importing the song catalog) shouldn't present much expense.
Comment: @eric I have actually played this game, and I can confirm it not only exists, but it really works. I took the liberty of adding my hands-on preview link to the post.
Comment: Oh if this ever comes out I will get it just for practicing chord voicings
Comment: Looks like this is the closest thing to what I'm looking for but unfortunately wont work for me as I'm learning classical guitar that does not have a pickup.
Comment: @Eric Anastas - Well - that's not impossible, either. You can get a [soundhole pickup](http://backstage.musiciansfriend.com/accessories/ghs-original-acoustic-soundhole-microphone/301011000000000) for practically any guitar. If you're doing classical, that means nylon strings, and that means no magnetic pickups.
Comment: Unfortunately the up-to-date Rocksmith 2014 does not work (for many people if not all) on Windows 10 -- you may end up needing to run an Windows 7 VM.  I've contact Ubisoft about this and will update when they get back to me.
Answer: There is only one I know of that does anything similar - and don't laugh - Rock Band 3 with the Fender Rock Band 3 Squier.

(rest of series, part 2 and part 3)
This lets you use a real guitar to play real notes, and it scores you on accuracy, timing etc. It doesn't use a mic to listen, it is plugged in to your games console. Please note the Fender Squier has since been sort of discontinued, though there may be residual stock in the retail pipeline. The wireless Fender Mustang pro guitar controller available also works, but it is just that, a controller -- not a true guitar like the Squier.
Of course you are limited to the 250+ odd songs in the Rock Band catalog that have "Pro Guitar" support, and it isn't the cheapest way to go but I am pretty certain that is the closest to the solution you have asked for.
Comment: I recently bought the RB3 guitar - cost, including the required MIDA adapter, was $300.  The guitar came setup to spec and is decent.  One thing I don't like is the notched frets which make bends annoying.  The notches divide the frets into zones and that's how the game picks up where your fingers are.  The game is a decent way to learn songs visually. The built in tutorials are pretty good so far.  I've worked on a couple of songs in expert pro mode - it really does feel like playing.  I don't like that you have to engage a string damper to get the most accurate strum detection.
Comment: I thought of it too, but I don't think that's what he is looking for. Also, I heard that the guitar is some kind of a Squier Bullet Strat for about 200 bucks, but I may be wrong. Also, there's a similiar solution from Fretlight guitar wich works with the newest version of the commonly used Guitar Pro Software: http://www.fretlight.com/
Comment: @Phelios - it will not make you a pro musician, no, but where the earlier versions may help you develop as a gamer (I managed to win my current PS3 in a large Guitar Hero tournament:-) entirely unrelated to musical ability), the latest version does actually teach you how to play the whole song - including all the notes and chords. A distinct step change in implementation.
Comment: @Markus - wow, you are right. $200! For that I actually might buy one. Wonder where I got the 2k figure from.... I agree it doesn't look like what the OP wants but figured it was worth popping up as it is a partial solution
Comment: I laughed !! sorry.. I had an argument with my friend about it (he is a pro Rock Band 2 gamer), because I doubt that the game will actually make you a pro musician rather than a pro gamer. But I'm not sure because I've never play before.
Comment: @Phelios - The original game could be played with the sound off - fun party challenge: have another song on the stereo while playing Through the Fire and Flames on Rock Band muted. Heh.
Comment: I dropped my daughter's Disney Sing-It microphone for the Wii into the hole of an acoustic and play the singing parts while she plays the drums or guitar in Beatles Rock Band...
Answer: eMedia Guitar Method
This question piqued my interest, and I kept looking for answers. It turns out that eMedia can do this now, too, at least to some extent. Look down the linked page for New Instant Feedback on Your Playing! You'll still need a microphone, but this software is out now, and possibly more applicable to your desired genre than Rocksmith is.
Comment: @skystar - Right. The software can only tell you if you missed a note, not if you've got soul. But "you missed that note" is a form of critique, which is what the question asks for. Obviously no program that listens through a mic can deal with an out of tune guitar - but your tutor won't put up with that either!
Comment: Well, that's not really anything new. Any program can detect what note you are playing. To get technical, it just compares it with a pre-defined midi note. If your guitar's out of tune, or what if it's a slide/HO or PO, how will it fare against that? It also doesn't provide you with "how" good your technique is in reality. Guitar tutors are still the best for this.
Comment: I'm not concerned with how "well" I'm playing now. Right now I'm just learning how to read notes and how to figure out what fret/string they correspond to. Guitar Method looks like what I'm looking for. Although, how well would it work for classical guitar which is not as focused on chords as acoustic?
Comment: @Eric Anastas - I have no idea how well it works at all, I've never used this one. But I can tell you that any software is going to have an easier time discerning single notes than chords anyhow!
Answer: There is some software called Yousician that gives you songs/tunes to play and it critiques how well you do. It starts off with really simple tunes and progressively gets more difficult.
I've used Yousician for the piano and liked it. It's also compatible with the Ukulele and, as you're asking, the guitar. I found it missed some of my ukulele playing, but it could just have been me playing poorly.
Answer: Check out the Rock Prodigy app for iOS devices.
The app listens to you play and then scores how accurately you played the track. Sort of like Guitar Hero with a real guitar. Multiple levels of difficulty for each song/lesson. The app is free (with some functionality disabled) and then you pay for each song you want to learn. Works with the iPad and the onboard mic.
I just downloaded it and played with it. The free version is OK but as a beginner I wanted some of the disabled features so I took out a loan and spent $5 for the full version (which also has a built-in tuner). The $5 also gets you more free songs and lessons. Other songs and lessons run from .99 to 1.99. There appears to be more than a dozen lessons and more than 50 songs (classic, country and rock). For the cost of one private guitar lesson it looks like you can have a lot of fun with this app. If you just go for the free version, be sure to register and go online as there will be more free content that you need to download. There are versions for the iPhone/iTouch as well as the iPad. Per a comment on another reply, I should mention there are three hammer on/pull off lessons as well as an acoustic tapping and legato lesson from Nuno Bettencourt. The three Steves (Vai, Morse and Howe) also have some advanced lessons available.
Answer: First off all software pretty much sucks when it comes to learning guitar.
My suggestion would be to get the book "First Book for Guitar" by Frederick Noad. It's an excellent book for those that are serious about learning the instrument. It teaches you the from the beginning and by the end you could be an intermediate player.
Also, software that seems to go well with guitar is the "Guitar pro" software. There are loads of sites that offer lots of pieces compatible with this software and guess what just type the name of the song and it finds it and also its free..... :-) It also plays the notes on the screen so you get a chance to here how it should sound. Lovely Jubbly
Comment: Disagree. Rocksmith does not suck. Here is the blog of one guy who was a total noob when he started to play Rocksmith one year ago: http://myrocksmithjourney.blogspot.com/ Now he has >7 guitars and can kick an ass.
Answer: FretLight
is an integrated system for learning guitar that relies on a custom electric guitar that can interface with a computer.
Answer: WildChords is an iPad app that uses the microphone to listen to your guitar. I haven't tried it, but I saw an enthusiastic endorsement.
http://www.wildchords.com/
Answer: The problem with using software to critique your playing, especially with classical guitar, is that playing the correct notes is only a small part of the whole. For the beginner classical guitarist, learning a good technique (right and left hand positions and motions, correct sitting position, etc.) is much more important in the long term.
Having said that, it is certainly possible to use software to rate your ability to play the correct notes in the correct time. In the long run, though, you will likely find that the scoring that software will give you can be misleading because it does not take tone or timbre into account, only pitch.
For example, you can play A - 440 Hz on 4 different strings. In each case, the pitch is the same, but the note will sound very different if you play it on the 1st string, 5th fret as compared to the 4th string, 19th fret.
I am not aware of any software that can make that distinction. What can make the distinction, though, is the human ear. With a little bit of practice and deliberate listening, issues such as sudden shifts in timbre, or nail clicks (a common problem with classical guitar) will practically jump out at you.
In addition, part of the beauty of classical guitar is in the interpretation of the performer. Guitarists do not play the same piece the same way. If they did, there would be little point to having many guitarists.  An important part of an artists interpretation is the rhythmic aspect. I am not familiar with all the software out there, but I have not heard of any software that gives the performer rhythmic flexibility while still accurately rating pitch throughout the piece.
Based on all of this, I would say the best judge of your playing at any level (outside of a professional teacher) is yourself. Record your practice sessions and listen to what you did. Try to keep specific goals in mind and focus on them so you do not get too side-tracked with any other issues you may hear, although keeping a note of them can be useful as well.  Once you are comfortable with your recording, let a more experienced guitarist listen and critique it as well. This may help you notice things you otherwise would not have.
Answer: You Rock Guitar
Or any Guitar-shaped MIDI Controller and tablature software.
Answer: Check Out String Wars in iTunes Store
String Wars is exactly the application you are looking for. Currently, it is available only on iPad for just $5. It has many good features, which lets the user:
a. use locally available guitar-pro tab files to practice songs
b. challenge other players to compete on a particular riff
c. record and share the played music over social networking websites
And much more. You can get more information on: http://www.stringwars.co
It does not replace the initial lessons by a guitar teacher, but is a great practicing tool, which makes guitar practicing more enjoyable.
Disclaimer: I am one of the co-founders of the company aynur labs, which has released the product in the market.
cheers!


How to make Voting api not cache

Question: For my application with several different voters, I want the caching table (votingapi_cache) to never be populated. Is there a hook or a configuration I can implement so that no caching happens at all?
Answer: The function votingapi_add_results() is responsible for writing records to the votingapi_cache table. Immediately afterwards, it invokes hook_votingapi_results() which any module can use to wipe out the table.
For example:
/**
 * Implements hook_votingapi_results().
 */
function MYMODULE_votingapi_results() {
  db_truncate('votingapi_cache')->execute();
}

How to make Voting api not cache


What windows software to use to get nice instruments when I connected Casio Keyboard via USB?

Question: How can someone who just connected a MIDI keyboard via USB to a Windows 8 PC take advantage of some nice instruments?
I installed MuseScore and can enter notes by playing on the USB-connected CASIO keyboard (CTK 2080), but what I would like is to just play on the keyboard and the have computer render the sounds (not record sheet input), using for example xylophone sounds?
Comment: I would rather have the sounds come out directly out of PC speakers rather then record sheet notes and then configure the notes to be xylophone and play them with delay.
Comment: Take a look at this post: https://music.stackexchange.com/questions/16304/midi-how-do-i-refer-to-and-search-for-software-that-will-play-audio-from-a-mi
Answer: What you're looking for is a software instrument. It takes midi input from your keyboard, and generates audio data, either using pre-recorded sounds (in which case it would be a sampler) or generating sound on-the spot (a synthesizer).
There is a very vast repository of virtual instruments available for windows - some free, some commercial. Most of them are focused on specific instruments or categories. There are also packs of many different instruments, such as NI's Kontakt.
If you're looking for free software, a good alternative might be using soundfounts. There are dozens of free soundfonts available, only a google search away.
It's worth noticing that, although some software instruments provide stand-alone programs, many are only available as VST plugins. In order to use VST plugins and soundfonts, you should learn how to use a digital audio workstation.
A popular "free" DAW is Reaper. A truly free one is LMMS.
Answer: I'll call this a "partial answer" that might help you get started in researching your problem.
Googling "windows 8 musescore midi input" reveals a number of posts.  Try this one for starters: http://musescore.org/node/12098 .  If you can't find something that helps you, then try posting on musescore.org.


MySQL - recreate default mysql database

Question: For whatever reason, the "mysql" database on my windows mysql installation has been deleted. I now have a mysql install that cannot start because the system database is missing, but I cannot find any documentation on recreating this database.
How do I recreate the mysql database (with users) on Windows?
Comment: Hehe..."whatever reason". Good way to cover your tracks there, wouldn't want to admit you accidentally the whole database.
Answer: On Unix, you would move your existing database data directory out of the way and run mysql_install_db. Unfortunately, according to the MySQL documentation, you don't have this command on Windows. It claims it is unnecessary because Windows distributions include preinitialized mysql and test databases. This would seem to suggest that you do need to reinstall MySQL.
Comment: If you are on Windows 7 don't forget to delete the folder C:\ProgramData\MySQL after deinstallation - usually it contains the database. If you don't delete it, the database will not be recreated upon installation! Instead you will end up with the old database.
Comment: I have this command on my rather customized version of CentOS and mysql and it says `Installing MySQL system tables...
OK
Filling help tables...
OK
` but doesn't really recreate dropped `mysql` database (also your link is broken, [this one](http://dev.mysql.com/doc/refman/5.7/en/mysql-install-db.html) is ok)
Answer: Reinstall MySQL.
Here's an sql dump from my mysql table: http://www.box.net/shared/js92gum4gh.
Answer: I dropped my mysql deafult system database accidentally.
Reinstallation (as accepted answer suggest) is not always possible, so I tried mysql_install_db first from second answer.
Now it's a part of mysqld and you can try mysqld --initialize but not on my version of OS and mysql.
Anyway it didn't help me too. So I've read docs carefully and found

If the data directory does already exist, you are performing an upgrade operation (not an install operation) and should run mysql_upgrade, not mysql_install_db

That did the trick. With mysql_upgrade I've restored all system tables.
ps I have to mention, that it was fresh install of mysql server, so I didn't care about other databases, settings or users. Be carefull!!! You can lose important data.

MySQL - recreate default mysql database


Why is sample standard deviation a biased estimator of $\sigma$?

Question: According to the Wikipedia article on unbiased estimation of standard deviation the sample SD
$$s = \sqrt{\frac{1}{n-1} \sum_{i=1}^n (x_i - \overline{x})^2}$$
is a biased estimator of the SD of the population. It states that $E(\sqrt{s^2}) \neq \sqrt{E(s^2)}$.
NB. Random variables are independent and each $x_{i} \sim N(\mu,\sigma^{2})$
My question is two-fold:

What is the proof of the biasedness?
How does one compute the expectation of the sample standard deviation

My knowledge of maths/stats is only intermediate.
Comment: You will find both questions are answered in the Wikipedia article on the [Chi distribution](http://en.wikipedia.org/wiki/Chi_distribution).
Comment: You might also be interested in reading about [Bessel's correction](https://en.wikipedia.org/wiki/Bessel%27s_correction).
Answer: @NRH's answer to this question gives a nice, simple proof of the biasedness of the sample standard deviation. Here I will explicitly calculate the expectation of the sample standard deviation (the original poster's second question) from a normally distributed sample, at which point the bias is clear.
The unbiased sample variance of a set of points $x_1, ..., x_n$ is
$$ s^{2} = \frac{1}{n-1} \sum_{i=1}^{n} (x_i - \overline{x})^2 $$
If the $x_i$'s are normally distributed, it is a fact that
$$ \frac{(n-1)s^2}{\sigma^2} \sim \chi^{2}_{n-1} $$
where $\sigma^2$ is the true variance. The $\chi^2_{k}$ distribution has probability density
$$ p(x) = \frac{(1/2)^{k/2}}{\Gamma(k/2)} x^{k/2 - 1}e^{-x/2} $$
using this we can derive the expected value of $s$;
$$ \begin{align} E(s) &= \sqrt{\frac{\sigma^2}{n-1}} E \left( \sqrt{\frac{s^2(n-1)}{\sigma^2}} \right) \\
&= \sqrt{\frac{\sigma^2}{n-1}}
\int_{0}^{\infty}
\sqrt{x} \frac{(1/2)^{(n-1)/2}}{\Gamma((n-1)/2)} x^{((n-1)/2) - 1}e^{-x/2}  \ dx \end{align} $$
which follows from the definition of expected value and  fact that $ \sqrt{\frac{s^2(n-1)}{\sigma^2}}$ is the square root of a $\chi^2$ distributed variable. The trick now is to rearrange terms so that the integrand becomes another $\chi^2$ density:
$$ \begin{align} E(s) &= \sqrt{\frac{\sigma^2}{n-1}}
\int_{0}^{\infty}
\frac{(1/2)^{(n-1)/2}}{\Gamma(\frac{n-1}{2})} x^{(n/2) - 1}e^{-x/2}  \ dx \\
&= \sqrt{\frac{\sigma^2}{n-1}} \cdot
\frac{ \Gamma(n/2) }{ \Gamma( \frac{n-1}{2} ) }
\int_{0}^{\infty}
\frac{(1/2)^{(n-1)/2}}{\Gamma(n/2)} x^{(n/2) - 1}e^{-x/2} \ dx \\
&= \sqrt{\frac{\sigma^2}{n-1}} \cdot
\frac{ \Gamma(n/2) }{ \Gamma( \frac{n-1}{2} ) } \cdot
\frac{ (1/2)^{(n-1)/2} }{ (1/2)^{n/2} }
\underbrace{
\int_{0}^{\infty}
\frac{(1/2)^{n/2}}{\Gamma(n/2)} x^{(n/2) - 1}e^{-x/2} \ dx}_{\chi^2_n \ {\rm density} }
\end{align}
$$
now we know the integrand the last line is equal to 1, since it is a $\chi^2_{n}$ density. Simplifying constants a bit gives
$$ E(s)
= \sigma \cdot \sqrt{ \frac{2}{n-1} }  \cdot \frac{ \Gamma(n/2) }{ \Gamma( \frac{n-1}{2} ) } $$
Therefore the bias of $s$ is
$$ \sigma - E(s) = \sigma \bigg(1 - \sqrt{ \frac{2}{n-1} }  \cdot \frac{ \Gamma(n/2) }{ \Gamma( \frac{n-1}{2} ) } \bigg) \sim \frac{\sigma}{4 n} \>$$
as $n \to \infty$.
It's not hard to see that this bias is not 0 for any finite $n$, thus proving the sample standard deviation is biased. Below the bias is plot as a function of $n$ for $\sigma=1$ in red along with $1/4n$ in blue:
Comment: (+1) Nice answer. I hope you don't mind, I tweaked a couple of very minor things and added an asymptotic result regarding the bias. I suppose you could superimpose the curve $(4n)^{-1}$ onto your plot, but it's probably unnecessary. Cheers. :)
Comment: of course this is a round-a-bout way to show that the standard deviation is biased - I was mainly answering the original poster's second question: "How does one compute the expectation of the standard deviation?".
Comment: Another point perhaps worth mentioning is that this calculation allows one to read off immediately what the UMVU estimator of the standard deviation is in the Gaussian case: One simply multiplies $s$ by the reciprocal of the scale factor that appears in the proof. This generalizes to UMVU estimators of $\sigma^k$ fairly readily.
Comment: Sorry, Macro. The same basic integral approach you've used will work, you'll just end up with a different scaling factor of $s^k$, with the gamma arguments you get being functions of $k$. That's what I meant, but it came out a bit too terse. :)
Comment: You really went to a lot of pains to do this Macro.  When I first saw the post about a minute ago I was thinking of showing the bias using Jensen's rule but someone already did it.
Comment: @cardinal I can see that $$\frac{s}{\sqrt{ \frac{2}{n-1} }  \cdot \frac{ \Gamma(n/2) }{ \Gamma( \frac{n-1}{2} )}}$$ is the UMVU for $\sigma$, but I'm missing how this can be generalized to give the UMVU for $\sigma^k$.
Answer: You don't need normality. All you need is that
$$s^2 = \frac{1}{n-1} \sum_{i=1}^n(x_i - \bar{x})^2$$
is an unbiased estimator of the variance $\sigma^2$. Then use that the square root function is strictly concave such that (by a strong form of Jensen's inequality)
$$E(\sqrt{s^2}) < \sqrt{E(s^2)} = \sigma$$
unless the distribution of $s^2$ is degenerate at $\sigma^2$.
Comment: Does this assume that $s^2 \neq 0$ and therefore $s^2 > 0$? The strong form of Jensen's inequality would only hold if square root was strictly convex but we lose the strictness if $s^2 = 0$. I assume that's an adequate assumption since $s^2 = 0$ only if we're dealing with a constant, in which case it is obvious that $s = \sigma$?
Comment: @David you are right that we need $\sigma > 0$. I believe I avoided $\sigma = 0$ by stating that $s^2$ should not have a degenerate distribution. If $\sigma = 0$, the distribution of $s^2$ is degenerate in 0. I guess that with independent variables, this is the only case where $s^2$ is degenerate. It's not really a problem if $s^2 = 0$ occurs with positive probability.
Answer: Complementing NRH's answer, if someone is teaching this to a group of students who haven't studied Jensen's inequality yet, one way to go is to define the sample standard deviation
$$
  S_n = \sqrt{\sum_{i=1}^n\frac{(X_i-\bar{X}_n)^2}{n-1}} ,
$$
suppose that $S_n$ is non degenerate (therefore, $\mathrm{Var}[S_n]\ne0$), and notice the equivalences
$$
  0 < \mathrm{Var}[S_n] = \mathrm{E}[S_n^2] - \mathrm{E}^2[S_n]
    \;\;\Leftrightarrow\;\; \mathrm{E}^2[S_n] < \mathrm{E}[S_n^2]
    \;\;\Leftrightarrow\;\; \mathrm{E}[S_n] < \sqrt{\mathrm{E}[S_n^2]} =\sigma.
$$
Answer: This is a more general result without assuming of Normal distribution. The proof goes along the lines of this paper by David E. Giles.
First, we consider Taylor's expanding $g(x) = \sqrt{x}$ about $x=\sigma^2$,
we have
$$
g(x) = \sigma + \frac{1}{2 \sigma}(x-\sigma^2) -  \frac{1}{8 \sigma^3}(x-\sigma^2)^2 + R(x),
$$
where $R(x) =- \left(\frac{1}{8 \tilde \sigma^3} - \frac{1}{8 \sigma^3}\right)(x-\sigma^2)^2$ for some  $\tilde \sigma$ between $\sqrt{x}$ and $\sigma$.
Let $\kappa = E(X - \mu)^4 / \sigma^4$ be the kurtosis.
It could be shown that $E\left[\sqrt{n}(S_n^2 - \sigma^2)\right]^2 \rightarrow \sigma^4(\kappa-1)$ and $n ER(S_n^2) \rightarrow 0$ (and the proofs are beyond the discussion of this thread. See for example  CLT that states that $\sqrt{n}(S_n^2 - \sigma^2)$  converges to $N(0, \sigma^4(\kappa-1))$).
Thus,
$$
E(S_n) = Eg(S_n^2) =\sigma + \frac{1}{2 \sigma} E(S_n^2 - \sigma^2) - \frac{1}{8\sigma^3} E(S_n^2 - \sigma^2)^2 + o(n^{-1}).
$$
$$
 = \sigma - \frac{\sigma}{8}\left[ \frac{\kappa - 1}{n}\right] + o(n^{-1}).
$$
For normal distribution, setting $\kappa = 3$ gives the first order bias $-\frac{\sigma}{4n}$ as shown above.


Conflicting intuition with binomial distribution formula

Question: There are two political candidates, A and B. Each voter has a 51% chance of voting for A, and a 49% chance of voting for B (say they flip a slightly biased coin to choose). Out of a population of 100 voters, what's the chance that A wins if a majority of votes is necessary for a win?
My intuition immediately tells me that A has a 51% chance of winning because of the probabilities mentioned above.
But the true answer from the binomial distribution formula is (100 choose 51) * (0.51)^51 * (0.49)^49, which is around 8%.
What gives?
Comment: You need to compute the cumulative probability for $X \geq 51$
Comment: @littleO: Around 54%
Comment: "My intuition immediately tells me that A has a 51% chance of winning because of the probabilities mentioned above" This intuition is wrong! You'd expect that 51% of the population, approximately, will vote for candidate A. If the population is large, then the fraction that votes for candidate A is unlikely to deviate much from 51%. So, if the population is large, we're very confident that candidate A will win.
Comment: @trueblueanil what would that number come out to?
Comment: @littleO Does me saying A has a 51% chance of winning mean the same thing as 51% of the population is expected to vote for A? Also, could you explain: "if the population is large, then the fraction that votes for candidate A is unlikely to deviate much from 51%"
Comment: @trueblueanil Do you mean 54% if the population is 100 people? When I said "If the population is large" I was thinking like 100 million people in my mind. Just explaining the intuition, not doing a precise calculation. If the population is enormous we will be nearly certain that A wins.
Comment: @littleO: You had *specified* a total population of $100$ people. Of course, it will change upwards for a larger population. Even for $1000$, it shoots up to 70%
Answer: As said by true blue anil you have to calculate $P(X\geq 51)=1-P(X\leq 50)$. Since the population is $n=100>30$ you can apply the central limit theorem. In this context $\Phi(z)$ denotes the cdf of the standard normal distribution. The mean and the standard deviation of the binomial distribution are $n\cdot p=100\cdot 0.51$ and $\sqrt{n\cdot p\cdot (1-p)}=\sqrt{100\cdot 0.51\cdot 0.49}$, respectively Then we have
$$P(X\geq 51)\approx 1-\Phi\left(\frac{50\color{blue}{+0.5}-100\cdot 0.51}{\sqrt{100\cdot 0.51\cdot 0.49}}\right)=1-\Phi(-0.1)$$
$\color{blue}{+0.5}$ is the continuity correction factor. The value of $\Phi(-0.1)$ can be looked up at wiki, for instance. Thus $P(X\geq 51)\approx 53.983\%\approx 54\%$
Answer: Both intuitions are wrong.

My intuition immediately tells me that A has a 51% chance of winning because of the probabilities mentioned above.

No, that's the chance of winning if only one person votes. When many persons vote, the average tends to concentrate around the mean (law of large numbers) and hence we should expect that the chances of A increase.

But the true answer from the binomial distribution formula is (100 choose 51) * (0.51)^51 * (0.49)^49, which is around 8%.

No, that's the probability that A receives exactly 51 votes. But A wins not only when he receives 51 votes, also when he receives 52, or 53, or...
Hence, you need to sum over all those probabilities.
The result is $\approx 0.54$ (google sheet).
As mentioned by @callculus42, you can also resort to the CLT approximation.


How to redirect in a Generic View

Question: I am using a generic view to render my blog post item:
class PostUpdateView(UpdateView, LoginRequiredMixin):
    model = Post
    # etc

I have a model method on the Post model that results in a boolean True or False:
@property
def can_edit(self):
    return self.displays_set.count() == 0

If can_edit is False for the Post object, how can I refactor the view to redirect from my UpdateView to a different DetailView?
Comment: Note that the mixin should come first, i.e. `class PostUpdateView(LoginRequiredMixin, UpdateView):`
Comment: Look at [this](http://ccbv.co.uk/projects/Django/2.2/django.views.generic.edit/UpdateView/) to understand how the `UpdateView` works and where you'd want to redirect. The method to override depends a bit on your flow. E.g. does this happen on GET or POST? You can see the `object` of the view (your `Post`) gets fetched in the first line of `get()` and `post()`, so after that you can check your condition and redirect if necessary. If you need it for both, then override `dispatch()`.
Answer: Override the dispatch method, and check obj.can_edit there. That way the object will be checked for get and post requests.
class PostUpdateView(LoginRequiredMixin, UpdateView):
    model = Post

    def dispatch(self, *args, **kwargs):
        obj = self.get_object()
        if not obj.can_edit:
            return redirect('/readonly-view/')

        return super().dispatch(*args, **kwargs)

With this solution, get_object() is called twice so there is a duplicate SQL query. However this is probably worth it to keep the code simple.
Comment: Nice solution, however, I would rather redirect in `get` and `post` separately to avoid extra database hit.
Answer: I would say that override dispatch method is best solution,
but if you want to avoid extra database hit, then you need to override get and post methods
def get(self, request, *args, **kwargs):
    self.object = self.get_object()
    if not obj.can_edit:
        return redirect('/readonly-view/')

    return self.render_to_response(self.get_context_data())

def post(self, request, *args, **kwargs):
    self.object = self.get_object()
    if not obj.can_edit:
        return redirect('/readonly-view/')

    form = self.get_form()
    if form.is_valid():
        return self.form_valid(form)
    else:
        return self.form_invalid(form)

How to redirect in a Generic View


jquery passing $(this) to other functions

Question: High!
What i want to do is the following: i have a table with a onclick attached to a link that resides in the table of an even row. every odd row is hidden. on a click on that link, the odd row is shown and data is loaded into that row. Works fine
Now what i want to do is that whenever that process is done, i want to attach a new click function to that link that makes the row hidden again. Kind of like toggle, but then with some more then just show/hide functionality. I tried to do that with the following code, but cant get it to work.
I surely miss something very basic or just do not know jquery well enough (which is very well possible, because i just got started for a few weeks ago).
$(document).ready(function(){

    // The version icons
    $("a.version").click(function () {
        var sLink = $(this).attr("href");
        var nexttr = $(this).parent().parent().next("tr.version");
        var nexttrtd = nexttr.find("td:first");
        $.get(sLink, function(sData){
            nexttrtd.html(sData);
            nexttr.show();
        });

        $(this).click(function(){
            attachHideMyChildren();
        });

        return false;
    });
});

function attachShowMyChildren()
{
    var sLink = $(this).attr("href");
    var nexttr = $(this).parent().parent().next("tr.version");
    var nexttrtd = nexttr.find("td:first");
    $.get(sLink, function(sData){
        nexttrtd.html(sData);
        nexttr.show();
    });
    $(this).click(function(){
        attachHideMyChildren();
    });
    return false;
}

function attachHideMyChildren()
{
    $(this).parent().parent().next("tr.version").hide();
    $(this).click(function(){
        attachShowMyChildren();
    });
}

It opens the table row, inserts the data but then doesn't attach the function to close the row again. How can i get this to happen?
Any ideas?
Answer: The problem is this:
$(this).click(function(){
  attachHideMyChildren();
});

When you call a function that way this becomes window. Instead do this:
$(this).click(attachHideMyChildren);

Also, you're adding click() handlers without removing the old ones.
That being said, there is an easier way of doing this.
$("a.version").click(function() {
  var next = $(this).closest("tr").next();
  if (next.is(":hidden")) {
    $.get($(this).attr("href"), function(sData) {
      next.find("td:first").html(sData);
      next.show();
    });
  } else {
    next.hide();
  }
  return false;
});

should about do it.
Comment: holy crap! that did it. Thanks cletus.


Finding asymptote of specific function with parameter

Question: How can I find the asymptotes and points of rising and falling in the function:
$$\dfrac{\sqrt{a^2-x^2}}{x}$$
Comment: What are  your thoughts?
Answer: Assume that $a>0$. This function is defined on $[-a,0)\cup(0,a]$. Since the domain is bounded, it can only have vertical asymptotes. The vertical asymptote is $x=0$. For $x>0$, as $x$ increase, the denominator increases, while the numerator decreases, so the function is decreasing. Since this is an odd function, it is increasing for $x<0$.


Query on $X_n\rightarrow 1 \ \text{in probability}$

Question:
Consider a sample of $n$ points randomly placed on a circle of radius $1$. It
  can be shown that $X_n$ , the distance from the centre of the circle of the
  farthest point, has density function
  $$f_{X_n}(x)=2nx^{2n-1} \ \ \ \ \ \ 0<x<1$$
  Show that $$X_n\rightarrow 1 \ \text{in probability}$$

My attempt:
I first calculated that $$F_{X_n}(x)=1 \ \ \ \ \ 0<x<1$$
Now, I want to show that $$\forall\epsilon>0, \ \ \ \lim_{n\to\infty} \mathbb{P}(\left|X_n-1\right|>\epsilon)=0$$
My question is, how do I deal with the absolute value $\left|X_n-1\right|$?
For instance, if I assumed it was positive, then
$$\lim_{n\to\infty} \mathbb{P}(\left|X_n-1\right|>\epsilon)=\lim_{n\to\infty} \mathbb{P}(X_n>\epsilon+1)=0$$
As $$\mathbb{P}\left(X_n>\frac{1}{2}\right)=1-F_{X_n}\left(\frac{1}{2}\right)=1-1=0$$
But why is it okay to make this assumption?
Comment: On a **disk** (instead of circle) you probably mean.
Comment: Perhaps, I'm not sure. The question is literally copied and pasted from a final exam paper.
Answer: Note that $X_n \leq 1$ almost surely. (Because the density is $0$ for $x>1$). Hence $|X_n-1|>\epsilon $ iff $X_n <1-\epsilon $. Thus $P\{|X_n-1|>\epsilon\} =\int_0^{1-\epsilon } 2nx^{2n-1} \, dx =(1-\epsilon )^{2n} \to 0$ as $n \to \infty $.
Comment: I don't see how as $n\rightarrow\infty, \ \ (1-\epsilon)^{2n}\rightarrow 0$.
Comment: For any number $x \in (0,1)$ we have $x^{n} \to 0$ as $n \to \infty $. Take $x=1-\epsilon $.


why pip is not working after removing the metadata and can't be reinstalled by python

Question: No module named 'pip._internal.metadata
I have removed meta data from my pc manually and now I got this message:
ModuleNotFoundError: No module named 'pip._internal.metadata'
pip is not functioning now!!
I tried to upgrade through python command:
python -m pip install --upgrade pip --user
however the same error message appear
:
(ModuleNotFoundError: No module named 'pip._internal.metadata')
Comment: _I have removed meta data from my pc manually_ And why did you do that?
Comment: if `pip` has problem to work then using `pip` to reinstall `pip` makes no sense. You should rather reinstall `Python` or search script `get_pip.py` which downloads and installs module again without using `pip`. See [https://pip.pypa.io/en/stable/installation/#get-pip-py](https://pip.pypa.io/en/stable/installation/#get-pip-py)
Answer: Check if you have the ensurepip module available:
$ python -m ensurepip --version

Now remove the dist info of the broken pip installation. Locate the directory via e.g.
$ python -c "import importlib.metadata as m; print(next(f for f in m.files('pip') if f.name == 'METADATA').locate().parent)"
/private/tmp/tst/lib/python3.10/site-packages/pip-22.0.4.dist-info

You can also invoke the deletion of the dist info directory with a variant of the above command
$ python -c "import importlib.metadata as m; import shutil; shutil.rmtree(next(f for f in m.files('pip') if f.name == 'METADATA').locate().parent)"

Now reinstall pip:
$ python -m ensurepip --upgrade


Guitar is not tuning right

Question: I have a guitar and I love it, and then I broke a string. I fixed it and I am positive I used the right string, I triple checked! But now about a month and a half later, I was tuning my guitar, and doesn't reach the G. I tried my best, I tried tuning it myself, but it doesn't sound like other G strings on records and apps. I have tried to start as low as it would go without breaking and working my way up. But I can not get it back to being a G without snapping a string! How can I fix this? I am new, so be ear is really hard and it doesn't work any ways. I got my guitar at a guitar center, can they help me there? Or give me advice for free if I take it in?
When you answer please use simpler terms, because I am new, I might not get it, I really only have started practice chords and strumming and a little tabs.
Comment: Update: it has steel strings! And it is acoustic! Also I can't find any apps with good tuners that are reading the right string!
Comment: Could you please edit your question and prove read? Some typos make it hard to read. Do I understand correctly that the G-string was broken? How often you've tuned the guitar since replacing the string? Do you tune by pitchfork/ear or are you using a tuning device (or an other way)?
Comment: Are you using the "5-5-5-5-4" method? The fifth fret on the D is the exact note for open G. Also, is it snapping up at the tuning machine, or somewhere else?
Answer: Does the new string look the same thickness as the old string ? They vary quite a lot on steel-strung acoustic guitars: The G string can be wound (usually copper colour) or not (just a straight bit of wire) depending on the 'weight' (actuall: thickness) of the string.
If you can't get it tight enough to get to G, it could be that the tuning pegs need some attention, or the part where you attach it over the bridge (other end to tuning pegs) might be at fault.
If there's any flex, for example the tuning peg can move about, or the bridge has movement, or the guitar body itself is flexing (unlikely) then the string will be very difficult to tune.
Whatever the issue, your guitar centre will be able to help, probably for free. It'd be good for you to take it in and ask them to show you how it's fixed, so you learn a bit abbout maintenance too.
Enjoy - and welcome to the hugely cool family :-)
Answer: Is it wrapped in the correct direction?  There is a method for wrapping the string around the tuning peg and a correct direction (above/below) with respect to the direction of the peg.  Check out this blog.
https://www.sweetwater.com/insync/how-to-change-electric-guitar-strings/
Even if it doesn't match your guitar exactly the principle is discussed.  You can look for more examples.  If the string is not wrapped around the peg properly it will slip very easily out of tune.
Answer: If the string is breaking at the same place in the length of the string as you try to bring it up to tuning,(most often  the bridge) you may have a point where the string is being bent over a relatively sharp edge or pinched in such  a way that it is unduly stressed  at that point. Also the string should be able to move freely in  the string slots in the bridge and the nut when tuning. A little nut grease will usually help make that possible.

Guitar is not tuning right