How to fill the contents of a dynamic array with a constant data

Question: protected String[] getImages(int max, String imageId) {
    String[] images = new String[max];
    for (int i = 0; i < max; i++) {
        images[i] = imageId;
    }

    return images;
}

Is there a simpler way to fill the contents of a dynamic array based on a constant data a single call. I remember a utility method from commons-lang, but I am unable to re-collect what that call was?
Answer: Try using the Arrays utility class:
Arrays.fill(images, imageId);

(That is fill(Object[] objects, Object val).  As you can see from the Javadoc there are many other overloads of fill().)


Find the sum of the roots of the equation.

Question: What is the sum of the roots of the equation
$$(x − 1) + (x − 2)^2 + (x − 3)^3 + \dots + (x − 10)^{10} = 0\, ?$$
When I expand this equation, it become in the power of $10$ and it gets complicated. Now what I am thinking is the sum of roots will be equal to the sum of coefficents of $x^9$. So I just need to evaluate coefficent of $x^9$ in the term $$(x-10)x^{10}.$$
Am I right in thinking?
But is there is any other easier way by which i can calculate?
Thanks in advance.
Comment: Yes, you are right. Take a look at: http://en.wikipedia.org/wiki/Vieta's_formulas
Comment: I would think you'd be after the coeff of $x^9$ in $(x-9)^9+(x-10)^{10}$.
Comment: Ya,I dint mention it as the coefficent of x^9 in (x-9)^9 will be 1 for sure.
Answer: Coefficient of $x^9$ is
$$1+ {10 \choose 1} (-10) = 1 - 100 = -99$$
The sum of the roots is therefore $99$  Do you know why?
I am adding this explanation on request:
Although, I would recommend you have to read more on Vieta's formula.
If $\alpha$ and $\beta$ are roots of a quadratic equation, then $(x-\alpha)(x-\beta) = x^2-(\alpha+\beta)x+\alpha \beta$  and the absolute value of the coefficient of $x$ is the sum of of the roots. (In this case $\alpha+\beta$.
Similarly a tenth degree polynomial, say has roots $\alpha_1, \alpha_2, \dots \alpha_{10}$ , then the polynomial
$$(x-\alpha_1)(x-\alpha_2)\dots(x-\alpha_{10}) = x^{10}-(\sum_{i=1}^{10} \alpha_i)x^9 +\dots +\prod_{i=1}^{10} \alpha_i$$
Comment: Its right but Can you please explain?
Comment: @vikiiii I added explanation as you requested.
Comment: Raman But here we dont know the roots of equation. So how to find their sum.
Comment: @vikiii the sum of the roots is the absolute value of the coefficient of $x^9$ which is the absolute value of $1+ {10 \choose 1} (-10) = 1 - 100 = -99$ and that absolute value is $99$. For instance what is the sum of the roots of $(x-2)^2+(x-4)^2=0$? which is $2x^2-12x+20=2(x^2-6x+10)=0$. The sum of the roots is the absolute value of the coefficient of $x$ and that is 6.
Answer: Hint $\: $ Shift $\rm\: x = y+10,\:$ so $\rm\:y^{10} + (y+1)^9 +\cdots\: = y^{10} + y^9 + \cdots\:$ has root sum $\:\!-1,\:$ so $\rm\:x_1+\cdots + x_{10} =\: (y_1\!+\!10)+\cdots+(y_{10}\!+\!10) =\: y_1+\cdots+y_{10}+100 = -1 + 100 = 99.$
Comment: Can you explain a little bit more?
Comment: @vikiiii What is proving problematic?
Comment: niiiiiiccceeeeeeeeeeee


AJAX data being sent to the wrong Django view

Question: I'm new to django and ajax so I've been working on a project to learn it. I have two buttons, one that adds a marker and one that deletes a marker.
Here is the views.py
@csrf_exempt
def save(request):
    searchVar = request.POST.getlist('search[]')
    waypoint = Waypoint()
    waypoint.name = searchVar[0]
    waypoint.geometry = ('POINT(' + searchVar[2] + " " + searchVar[1] + ')')
    waypoint.save()
    return HttpResponse(json.dumps(dict(isOk=1)), content_type='application/json')

@csrf_exempt
def remove(request):
    objectID = request.POST.get('id')
    point = get_object_or_404(Point, pk = objectID)
    point.delete()

Here is the urls.py
from django.conf.urls import patterns, url, include

urlpatterns = patterns('googlemaps.waypoints.views',
    url(r'^$', 'index', name='waypoints-index'),
    url(r'', 'save', name='waypoints-save'),
    url(r'', 'remove', name='waypoints-remove'),
)

and here is the ajax from the js file
    $('#saveWaypoints').click(function () {
    var searchList = [search.name, search.geometry.location.lat(), search.geometry.location.lng()]
    $.ajax({
      url : "waypoints-save",
      type : "POST",
      data : { search : searchList }
    }, function (data) {
        if (data.isOk) {
            $('#saveWaypoints');
        } else {
            alert(data.message);
        }
    });
});
$('#removeWaypoints').click(function () {
  console.log(markerID);
    $.ajax({
      url : "waypoints-remove",
      type : "POST",
      data : { id : markerID }
    }, function (data) {
        if (data.isOk) {
            $('#removeWaypoints');
        } else {
            alert(data.message);
        }
    });
});

The save button works fine, but when I click on the remove button I get this error in my console log
POST http://127.0.0.1:8000/waypoints-remove 500 (Internal Server Error)

IndexError at /waypoints-remove
list index out of range

Request Method: POST
Request URL: http://127.0.0.1:8000/waypoints-remove

and this error in my server cmd
Internal Server Error: /waypoints-remove
Traceback (most recent call last):
  File "C:\Users\rnvitter\virtualenv4\myvenv\lib\site-packages\django\core\handlers\base.py", line 149, in get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\Users\rnvitter\virtualenv4\myvenv\lib\site-packages\django\core\handlers\base.py", line 147, in get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\rnvitter\virtualenv4\myvenv\lib\site-packages\django\views\decorators\csrf.py", line 58, in wrapped_view
    return view_func(*args, **kwargs)
  File "C:\Users\rnvitter\virtualenv4\googlemaps\googlemaps\waypoints\views.py", line 23, in save
    waypoint.name = searchVar[0]
IndexError: list index out of range
2017-01-09 22:40:11,781 - ERROR - Internal Server Error: /waypoints-remove
Traceback (most recent call last):
  File "C:\Users\rnvitter\virtualenv4\myvenv\lib\site-packages\django\core\handlers\base.py", line 149, in get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\Users\rnvitter\virtualenv4\myvenv\lib\site-packages\django\core\handlers\base.py", line 147, in get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\rnvitter\virtualenv4\myvenv\lib\site-packages\django\views\decorators\csrf.py", line 58, in wrapped_view
    return view_func(*args, **kwargs)
  File "C:\Users\rnvitter\virtualenv4\googlemaps\googlemaps\waypoints\views.py", line 23, in save
    waypoint.name = searchVar[0]
IndexError: list index out of range

Which leads me to believe that the data from the remove button ajax call is being sent to my save view, does anyone know one?
Comment: In js file that you define urls will not work. You have to define ajax in html page with syntax of URL in ajax like :    url : "{% url 'waypoints-save' %}" that automatic create URL and your ajax will go in correct method and also use django latest way to define url in urls.py file without pattern https://docs.djangoproject.com/en/1.10/topics/http/urls/#example
Answer: You have your urls.py file set up wrong. The first parameter is a regular expression to match a URL, so ^$ will match the root path. The name parameter is for getting the URL for a specific view, e.g. when you use the reverse function.
^ indicates the beginning of a line and $ indicates the end of a line. Together, with nothing in between, it will match an empty line.
To match another URL, such as /waypoints-save/, you would need to write another regex: ^/waypoints-save/$. This will match the beginning of the line, followed by the characters /waypoints-save/, followed by the end of the line. To get your entire urls.py set up correctly, it should look like this:
from django.conf.urls import patterns, url, include

urlpatterns = patterns('googlemaps.waypoints.views',
    url(r'^$', 'index', name='waypoints-index'),
    url(r'^/waypoints-save/$', 'save', name='waypoints-save'),
    url(r'^/waypoints-remove/$', 'remove', name='waypoints-remove'),
)

Comment: that did the trick, I was pretty confused on how urls worked in django but this helped a lot thank you!
Answer: You have defined two URL entries that have the same regex.
url(r'', 'save', name='waypoints-save'),
url(r'', 'remove', name='waypoints-remove'),

Since /waypoints-remove would match r'' (a regex with nothing in it, therefore it will match anything), the first match wins, and the save method is executed. So the method you expected to run, remove, is not being run.


What lemma for product of derivatives equals the n-derivative?

Question: Why must one require regularity in order for Fisher information to be $E\bigg( \frac{\partial^2 l(\theta, X)}{\partial \theta^2} \bigg)$?
Rather than
$E\bigg( \frac{\partial l(\theta, X)}{\partial \theta}\frac{\partial l(\theta, X)}{\partial \theta}^T \bigg)$
Since my notes say that "under sufficient regularity conditions", then:
$I(\theta)=E\bigg( \frac{\partial^2 l(\theta, X)}{\partial \theta^2} \bigg)$
However, what's the lemma that says that the product equals 2nd derivative?
Answer: My impression is that you got something wrong here. Note that $$\frac{\partial^2 l(\theta, X)}{\partial \theta^2} $$ is a second derivative, while $$\frac{\partial l(\theta, X)}{\partial \theta}\frac{\partial l(\theta, X)}{\partial \theta}^T$$ is a product of two first-order derivatives. As such, they are surely not equal in general: consider for example the function $$l(\theta,X) = \theta \cdot X.$$
Try reading the wikipedia page on the Fisher information and compare it with your notes.
Comment: Then what's a lemma that says that they can be equal?
Comment: @mavavilj I wouldn't look for such a lemma (it would mean that $l$ has to satisfy a certain differential equation for all $X$, which is a very strict limitation), I'd rather try to understand what was meant in your notes. What is the definition of $l$?
Comment: The wikipedia says same as my notes: "If log f(x; θ) is twice differentiable with respect to θ, and under certain regularity conditions,[4] then the Fisher information may also be written as". But I want to know what the lemma is that allows for that equality.
Comment: Cramer-Rao bound? http://www.stat.tamu.edu/~suhasini/teaching613/inference.pdf (Theorem 1.1)


Populating a div that was generated in an earlier ajax request

Question: I'm having a few problems with jQuery/AJAX and was wondering if anyone could point me in the right direction!
I have an AJAX request on my page that populates a div (call it with div 1) with a select box. Also contained is another DIV (call it div 2). After selecting an option from the select box and clicking a button, I then want to populate div 2 with some extra information. However, when I try to do this, it appears that jQuery is trying to load div 1 with the new information. When I use chrome to inspect the element, I can see that when the button is clicked that div 2 is removed for some reason. Can anyone advise?
Comment: Nice description of the problem, could you post the code along with it? :D
Comment: @user2748228 Is this question still open? If not, please close the question (by choosing a best answer) and upvoting any answers that were helpful to you.
Answer: Not really possible to answer this question without seeing your code, but here is another SO question that discusses how to populate <select> control B, based on the contents of <select> control A.
Three Ajax examples (look at the last one)


NodeJS Google Drive API how to update file

Question: Hi I'm trying to update a Google Doc with NodeJS using the Google Drive API and I'm getting this error:
{
 "error": {
  "code": 500,
  "message": null
 }
}

Here's the relevant code :
var j = new google.auth.JWT(
    creds.client_email,
    null,
    creds.private_key,
    [
        "https://www.googleapis.com/auth/drive"
    ]
);
async function refreshTokens() {
    startedWaiting = true;
    return j.authorize((r,t) => {
        startedWaiting = false;
        timeTillNeedRefresh = t["expiry_date"] - Date.now();
        setTimeout(function() {
            refreshTokens();
        //    console.log("doing Q", Q);

        }, timeTillNeedRefresh);

        tokens = t;
        console.log("GOT A TOKEN", tokens);
        Q.forEach(x=>x());
        Q = [];

    });
}

async function start() {
    await refreshTokens();
}
start();
function myFetch(opts) {
    if(!opts) opts = {};
    var cb = opts.cb || empty;
    var headers =  {
        'Accept-Encoding': 'gzip',
        'User-Agent': 'google-api-nodejs-client/0.7.2 (gzip)',
        Authorization:tokens.token_type +" "+ tokens.access_token,
        Accept:"application/json"
    };
    if(opts.headers) {
        for(k in opts.headers) {
            headers[k] = opts.headers[k];
        }
    }
    fetch(
        opts.url
        || "",
    {
        method:opts.method || "GET",
        headers: headers
    })
        .then(res => res.text())
        .then(body => {
            cb(body);

        });
}

updateFile({
    id: "1vebqOamZ9QB4HqfUaQN-U9Zt4y33eij-I21glMvaPVQ",
    content: "hi there"
});

async function allFuncs(tmp) {
    if(tokens === null) {
        console.log("DOING it later")
        Q.push(tmp);
        await refreshTokens();
    } else if(startedWaiting || timeTillNeedRefresh <= 0) {
        console.log("NOT for a while");
        Q.push(tmp);
    } else {
        console.log("THIS is what should happen");
        start = Date.now();
        tmp();
    }
}

async function updateFile(opts) {
    var id = opts.id,
        content = opts.content || "";
    if(id) {
        allFuncs(() => {
            myFetch({
                url:`https://www.googleapis.com/upload/drive/v3/files/${id}?uploadType=media`,
                method:"PATCH",
                headers: {
                    body: opts.content,
                    "Content-Type": "application/vnd.google-apps.document"
                },
                cb(b) {
                    console.log(b, "DID I DO IT?!");
                }
            });
        });
    }
}

I tried looking up what this error means but I couldn't find anything related to nodejs...
Does anyone know if its a header issue or is there any way to fix it?
I don't know if its possible to do wih a service key, or if you HAVE to verify the user in order to do so??
SEEMINGLY if the service key email has edit permissions for the file, it should just be able to edit it at will.
Comment: In order to correctly your situation, can I ask you about your question? 1. Do you want to overwrite Google Document by a text of ``hi there``? 2. Is the Google Document shared with the Service Account? 3. Can you use googleapis of Node.js? 4. Are you required to use only Drive API? For example, how about using Google Docs API?
Comment: @Tanaike Yes, Yes, Yes, and I'm currently just using the drive API I didn't know there was a difference between the doc and drive API nowadays, I could use anything I need
Comment: Thank you for replying. I could understand about your question. I proposed a sample script as an answer. Could you please confirm it? If this was not the result you want, I apologize.
Comment: Did my answer show you the result what you want? Would you please tell me about it? That is also useful for me to study. If this works, other people who have the same issue with you can also base your question as a question which can be solved. If you have issues for my answer yet, I apologize. At that time, can I ask you about your current situation? I would like to study to solve your issues.
Comment: @Tanaike Yes, although I did say that I can use the googleAPI, but I neglected to mentioned that I would be interested in doing it without it; just by using GET requests, do you know how to do that?
Comment: Thank you for replying. I'm sorry for the inconvenience. And I'm really sorry that my answer was not useful for you. Unfortunately, the file cannot be directly overwritten using GET method. This is the specification. I apologize for this situation. If Web Apps using Google Apps Script is used, the script for overwritten the file is run by requesting to Web Apps with GET method. At that time, Web Apps is required to be created by Google Apps Script and deploy it. How about this?
Comment: @Tanaike I think it said somewhere in the documentiation about using PUT instead of get, do you know if thats possible?
Comment: Is that the method for using Web Apps?
Comment: @Tanaike No it was for a server-side script, I prefer NOT to use web apps
Comment: I could understand that you don't want to use Web Apps with Google Apps Script. Can I ask you about the server-side script?
Comment: @Tanaike NodeJS
Comment: In the case that Drive API is used from the script of node.js, PATCH method is required to be used for overwriting the file. You can see the sample script at my answer. drive.files.update of Drive API v3 is https://developers.google.com/drive/api/v3/reference/files/update
Comment: @Tanaike and without using files.update?
Comment: Do you want to overwrite the file without using files.update method?
Comment: @Tanaike kir-ekct
Comment: I'm sorry. I cannot understand about ``kir-ekct``. Can I ask you about the detail information of it? I apologize for my language skill.
Comment: @Tanaike I just mean "correct" lol "kir-ekct" sound it out..
Comment: I could understand about it. Although I had looked for the method for directly overwriting the file without PUT, PATCH and POST method, unfortunately, I couldn't find it. At Drive API, PUT and PATCH methods are used for it. At batchUpdate of Google Docs API, POST method is used for it. I apologize for this situation.
Comment: @Tanaike No I have no problem using patch and put, just as long as it works, hwo can I do it? When I tried it just didnt wokr
Comment: When you can use PATCH method, you can use the script in my answer. I heard that you can use googleapis of node.js. So I used it. How about this?
Comment: @Tanaike Yes but do you know how I can use it without using the googleapis script? Ultimately its just a request, seemingly I shouldn't need an entire library for that
Comment: If googleapis is not used, you cannot also use ``new google.auth.JWT()``. In this case, you want to retrieve the access token without ``new google.auth.JWT()``. Is my understanding correct?
Answer:
You want to overwrite the existing Google Document by a text of hi there with Drive API using Service Account.
The Google Document is shared with the Service Account.
You can use googleapis.

I could understand like above. If my understanding is correct, how about this sample script? In this sample script, I used the files.update method of Drive API.
Sample script:
Before you run the script, please set the json file path downloaded when the Service Account is created. And please confirm the file ID of Google Document, again.
const stream = require('stream');
const {google} = require('googleapis');
const creds = require('###'); // Please set the json file path downloaded when the Service Account is created.
const jwtClient = new google.auth.JWT(
    creds.client_email,
    null,
    creds.private_key,
    ['https://www.googleapis.com/auth/drive'],
    null
);

const id = "1vebqOamZ9QB4HqfUaQN-U9Zt4y33eij-I21glMvaPVQ"; // Please set the file ID of Google Document
const content = "hi there"; // Please set the text.

const drive = google.drive({version: 'v3', auth: jwtClient});
const buf = Buffer.from(content, 'binary');
const buffer = Uint8Array.from(buf);
var bufferStream = new stream.PassThrough();
bufferStream.end(buffer);
const media = {
    mimeType: 'application/vnd.google-apps.document',
    body: bufferStream,
};
drive.files.update({
    fileId: id,
    media: media,
}, (err, res) => {
    if (err) {
        console.log(err);
        return;
    }
    console.log(res.data);
});

Note:

When you run the script, the existing Google Document is overwritten. So please be careful this. I recommend to use a sample Document for testing.
If this script didn't work, please confirm the following points.

Drive API is enabled at API console.
The Service Account can be used.
The Google Document is shared with the Service Account.
The version of googleapis is the latest one.

Reference:

Files: update

Edit:

You don't want to use googleapis.
You want to overwrite Google Document with a text value without using googleapis.

From your comments, I understood like above. If my understanding is correct, how about this sample script? When you run this script, please confirm the following points.

About the script,

Please set privateKey and clientEmail from JSON file of Service Account.
Please set the file ID of the existing Google Document you want to overwrite.

Drive API is enabled at API console.
The Service Account can be used.
The Google Document is shared with the Service Account.
The version of googleapis is the latest one.

Sample script:
const cryptor = require('crypto');
const request = require('request');

// Get access token using Service Account
function getAccessToken(serviceAccount) {
    const scopes = ["https://www.googleapis.com/auth/drive"];
    const url = "https://www.googleapis.com/oauth2/v4/token";
    const header = {
        alg: "RS256",
        typ: "JWT",
    };
    const now = Math.floor(Date.now() / 1000);
    const claim = {
        iss: serviceAccount.clientEmail,
        scope: scopes.join(" "),
        aud: url,
        exp: (now + 3600).toString(),
        iat: now.toString(),
    };
    const signature = Buffer.from(JSON.stringify(header)).toString('base64') + "." + Buffer.from(JSON.stringify(claim)).toString('base64');
    var sign = cryptor.createSign('RSA-SHA256');
    sign.update(signature);
    const jwt = signature + "." + sign.sign(serviceAccount.privateKey, 'base64');
    return new Promise(function(resolve, reject) {
        request({
            method: "post",
            url: url,
            body: JSON.stringify({
                assertion: jwt,
                grant_type: "urn:ietf:params:oauth:grant-type:jwt-bearer",
            }),
        }, (err, res, body) => {
            if (err) {
                console.log(err);
                return;
            }
            const obj = JSON.parse(body);
            resolve(obj.access_token);
        });
    });
}

// Overwrite file in Google Drive
function overWriting(object) {
    const metadata = {
        mimeType: "application/vnd.google-apps.document",
    };
    const url = "https://www.googleapis.com/upload/drive/v3/files/" + object.googleDocumentFileId + "?uploadType=multipart";
    const boundary = "xxxxxxxxxxx";
    var data = "--" + boundary + "\r\n";
    data += "Content-Disposition: form-data; name=\"metadata\"\r\n";
    data += "Content-Type: application/json; charset=UTF-8\r\n\r\n";
    data += JSON.stringify(metadata) + "\r\n";
    data += "--" + boundary + "\r\n";
    data += "Content-Disposition: form-data; name=\"file\"; filename=\"sample.txt\"\r\n";
    data += "Content-Type: text/plain" + "\r\n\r\n";
    const payload = Buffer.concat([
        Buffer.from(data, "utf8"),
        new Buffer(object.textData, 'binary'),
        Buffer.from("\r\n--" + boundary + "--", "utf8"),
    ]);
    const options = {
        method: 'patch',
        url: url,
        headers: {
            "Content-Type": "multipart/related; boundary=" + boundary,
            'Authorization': 'Bearer ' + object.accessToken,
        },
        body: payload,
    };
    request(options, (error, response, body) => {
        console.log(body);
    });

}

async function main() {
    const serviceAccount = {
        privateKey: "###", // private_key of JSON file retrieved by creating Service Account
        clientEmail: "###", // client_email of JSON file retrieved by creating Service Account
    };
    var object = {
        googleDocumentFileId: "###", // Set the file ID of the existing Google Document
        textData: "hi there",
    };
    const accessToken = await getAccessToken(serviceAccount);
    if (accessToken) {
        object.accessToken = accessToken;
        overWriting(object);
    }
}

main();

Comment: @BartusZak Thank you for your comment. I updated my answer. Could you please confirm it?
Comment: @bluejayke I understood that you want to overwrite Google Document with a text value without using googleapis. For this situation, I added a sample script. Could you please confirm it? If this was not what you want, I apologize.
Comment: @bluejayke Did my additional sample script show you the result what you want? Would you please tell me about it? That is also useful for me to study. If you have issues for my answer yet, I apologize. At that time, can I ask you about your current situation? I would like to study to solve your issues.
Comment: @bluejayke Is there anything that I can do for your question? If my answer was not useful for your situation. I have to apologize and modify it. If you can cooperate to resolve your issue, I'm glad. I would like to think of about the solution.
Comment: `(node:3136) [DEP0005] DeprecationWarning: Buffer() is deprecated due to security and usability issues. Please use the Buffer.alloc(), Buffer.allocUnsafe(), or Buffer.from() methods instead.`


Prove that there exists a subsequence $\{f_{n_k}\}$ such that $f_{n_k} \to 0$

Question: Suppose that $\{f_n\}_{n=1}^{\infty}\in L^2(R)$ is a sequence that converges to 0 in $L^2$ norm; in other words,
$$
\left(\int_{-\infty}^{\infty}|f_n|^2dx\right)^{1/2} \to 0.
$$
Prove that there exists a subsequence ${f_{n_k}}\to 0$ almost everywhere.
I feel I am stuck for a long time, can someone tell me how to prove it? I am thinking about how to construct the subsequence, but still have no idea how to find the subsequence.
Comment: Can you prove convergence in $L^p$ implies convergence in probability? Then, [use this](http://math.stackexchange.com/questions/222264/another-question-on-almost-sure-and-convergence-in-probability).
Comment: But this is not a consequence of the completeness theorem for Lebesgue spaces?
Answer: $L^2$ convergence implies convergence in measure. Thus $\mu(|f_n|>\epsilon)\to0$ as $n\to\infty$.
So taking a sequence $\epsilon_n$ to be $\dfrac{1}{n}$, you have there exists $N_n$ (where $N_n$ can be taken such that $N_1<N_2<N_3<...)$ for which $\mu(|f_{N_n}|>\dfrac{1}{n})<\dfrac{1}{2^n}$. Now use Borel Cantelli to show that this subsequence $\{f_{N_n}\}$ is the one you desire.
EDIT: Please do fill in the details. It's important.
Answer: This is a consequence of the completeness theorem for the Lebsgue spaces, i.e. $L^p(\Omega)$ is a Banach space.
$Theorem$. If $\lbrace f_n \rbrace \subset L^p(\Omega)$ is a Cauchy sequence, then there is $f \in L^p(\Omega)$ such that $||f_n - f||_p \rightarrow 0$. More precisely there is $\lbrace f_{n_k} \rbrace$ and a function $F \in L^p(\Omega)$ $F(x) \geq 0$ such that
$(1)$ $|f_{n_k}(x)| \leq F(x)$ a.e in $\Omega$
$(2)$ $f_{n_k}(x) \rightarrow f(x)$ a.e. in $\Omega$.
In the proof of this theorem you built this subsequence.
Comment: But isn't that basically invoking a stronger theorem than necessary to solve a standard question?
Comment: I do not understand your comment. This theorem in functional analysis should be well known to all.
Comment: It should, **after** taking the course. But *while* taking the course, it's not the first result shown -- at least when I took it, we proved that "convergence in $L^p$ implies convergence in probability implies convergence a.e. of a subsequence" quite *before* proving completeness of $L^p$ spaces. And given the question, which asks to prove this very standard result, I would wager the OP is not done with the course yet...
Comment: This depends on how they are structured the various functional analysis courses. For me it was one of the first things that we have shown.
Comment: (In addition, it's a consequence of the proof of the completeness rather than of the completeness itself -- not really the same point I'm making above, but just knowing that "$L^p$ spaces are complete" does not trivially lead to the answer to the OP's question)
Comment: In fact, I specified the statement, and that in the proof of this theorem we build this subsequence.
Comment: I know, I have seen. I believe there is some communication barrier here: all I'm saying is that the statement that the OP asks to prove is strictly weaker than the one you use to prove it, and that arguably the OP may not have seen it yet. Now, that last part is just a guess based on my own experience, and that is for the OP herself to clarify.
Comment: This we can not know, in any case the questioner can go to study the proof of this theorem. My answer may also be considered as a suggestion.
Answer: Since $(f_n)$ is a Cauchy sequence, consider a subsequence $(f_{n_k} )$ denoted by $(f_k)$ such that
$$\|f_{k+1}-f_k\|_2 \leq \frac{1}{2^k}$$
Let $$g_n(x)=\sum_{k=1}^n|f_{k+1}(x)-f_k(x)|$$ so that $\|g_n\|_2 \leq 1$, by  the monotone convergence theorem, $g_n(x)$ tends to a finite limit, say $g(x)$, a.e. $R$, with $g \in L^2$. On the other hand, for $m \geq  n \geq  2$ we have that
$$|f_m(x)−f_n(x)| \leq  |f_m(x)−f_{m−1}(x)|+· · ·+|f_{n+1}(x)−f_n(x)| \leq g(x)−g_{n−1}(x).$$
It follows that a.e. on $R$, $f_n(x)$ is Cauchy and converges to a finite limit, say $f(x).$ We have a.e. on $R$,
$$ |f (x) − f_k(x)| ≤ g(x), \quad k \geq 2$$
and in particular $f \in L^2$. Note that by dominated convergence we know that $f_k \rightarrow f$  in $L^2$ and thus $f = 0$  a.e.
Answer: Another solution (Suitable for all $p\geq 1$):
$f_n \xrightarrow{L^p} 0$ hence we can extract a subsequence such that $ \| f_{n_k} \| < 2^{-k}$
We then define $g=\sum_{k=1}^\infty |f_{n_k}|$ and notice that $\|g\| \leq 1$. This implies that $g$ is finite almost everywhere, or in other words: the sum $\sum_{k=1}^\infty f_{n_k}$ converge absolutely a.e., which in turn implies $f_{n_k}(x)\xrightarrow{\text{a.e.}} 0$.


What is meaning of parameter in URL Google Maps

Question: I'm doing with Webkit Browser on Android. I want get a sign red "A" in URL following:

https://maps.google.com/maps?f=q&source=s_q&hl=vi&geocode=&q=7+Nguy%E1%BB%85n+Ch%C3%AD+Thanh,+T%C3%A2n+Th%E1%BA%A1nh,+Tam+K%E1%BB%B3,+Qu%E1%BA%A3ng+Nam,+Vi%E1%BB%87t+Nam&aq=0&oq=7+Nguy%E1%BB%85n+Ch%C3%AD+Thanh,+T%C3%A2n+Th%E1%BA%A1nh,+Tam+K%E1%BB%B3&sll=15.579176,108.470603&sspn=0.001573,0.002411&vpsrc=6&ie=UTF8&hq=&hnear=7+Nguy%E1%BB%85n+Ch%C3%AD+Thanh,+Tam+K%E1%BB%B3,+Qu%E1%BA%A3ng+Nam,+Vi%E1%BB%87t+Nam&ll=15.578003,108.471826&spn=0.006294,0.009645&t=m&z=17&ei=mwSGUKXwOK2tiQeHlYH4Ag&pw=2

How to i get a sign red "A" and a set in file HTML:
Show picture: https://i.stack.imgur.com/STyUG.jpg
And what is meaning of parameter in URL Google Maps ???
Example :

f=q; source=s_q; hl=vi; geocode; aq=0;
  oq=7+Nguy%E1%BB%85n+Ch%C3%AD+Thanh,+T%C3%A2n+Th%E1%BA%A1nh,+Tam+K%E1%BB%B3;
  sll=15.579176,108.470603; sspn=0.001573,0.002411;
  vpsrc=6; ie=UTF8;
  hnear=7+Nguy%E1%BB%85n+Ch%C3%AD+Thanh,+Tam+K%E1%BB%B3,+Qu%E1%BA%A3ng+Nam,+Vi%E1%BB%87t+Nam;
  ll=15.578003,108.471826; spn=0.006294,0.009645; t=m;
  z=17; ei=mwSGUKXwOK2tiQeHlYH4Ag; pw=2

My english is not good, and expect people to sympathize..
Answer: Parameter             Description
f=q                   The f parameter, which controls the display of the Google Maps form, can                       be d (for the directions form or l for the local form). Without the f                       parameter, the default search form is displayed.
hl=en           Google Maps supports a limited number of host languages, including en for                       English and fr for French.
q=1600+Pennsylvania+Ave,+Washington,+DC
                      The value of the q parameter is treated as though it were entered via the                       query box at http://maps.google.com.
sll=36.60585,-121.858956
                      sll contains the latitude and longitude for the center point around which                       a business search is performed.
spn=0.006313,0.01133  spn is the approximate latitude/longitude span for the map.
ie=UTF8             ie is the character encoding for the map.
om=1            om determines whether to include an overview map. With om=0 the overview                       map is closed.
iwloc=addr          iwloc controls display options for the info window.
A good way to get a feel for how these parameters function is to change a parameter, add new ones, or drop ones in the sample URL and take a look at the resulting map. For instance, if you have only the q parameter, you would still get a map with some default behavior:
http://maps.google.com/maps?q=1600+Pennsylvania+Ave,+Washington,+DC

That is, the other parameters are not mandatory. Let's play with the z parameter to adjust the zoom factor:
http://maps.google.com/maps?q=1600+Pennsylvania+Ave,+Washington,+DC&z=0

versus the following:
http://maps.google.com/maps?q=1600+Pennsylvania+Ave,+Washington,+DC&z=17

There is a comprehensive list of Google Maps parameters

mrad lets you specify an additional destination address.
output=kml gets a KML file to send to Google Earth.
layer=t adds the traffic layer.
mrt=kmlkmz shows "user-created content." For example, the following shows user-generated information about hotels around the White House:
http://maps.google.com/maps?f=q&hl=en&q=hotel&near=1600+Pennsylvania+Ave,+Washington,+DC&sll=36.60585,-121.858956&sspn=0.006313,0.01133&ie=UTF8&z=16&om=1&iwloc=addr&mrt=kmlkmz
Comment: thanks Jay!
Now, I understand is this! :D
I wish you have a nice day ;)
Answer:


Canonical Mapping in Linear Algebra

Question: I'm just really really wondering....is there such a thing?
I mean, in my lecture notes, it's defined as, for a vector space $V$, and it's subspace or submodule $U$, to be the mapping $f:V \to V/U$, sending $v$ to $v+U$.
The thing is, I can find ZERO resource or reference on this massive massive web of information called the internet.
Nothing hits with "canonical mapping". All that his is canonical "basis" or canonical "Jordan Form" which is not what I want.
Does it have a different name, that most people are familiar with? Is it my uni being weird and using a very very obscure name to it?
I am asked to find a matrix to represent a canonical map but I have no idea how to tackle it. Is this "canonical" mappping thing a linear transformation?? It seems like it but I'm not sure....And I don't know how to find this representation matrix for the mapping.
Any advice? Or source, recommended information I can refer to?
Comment: It's not limited to vector spaces, which is why you may be having a difficult time searching for it. This is an instance of a more general map called the "natural projection" (sometimes also called the "canonical projection") which sends an element to it's equivalence class.
Answer: Suppose $U$ is a subspace of a finite-dimensional vector-space $V$. There is an equivalence relation $\sim$ on $V$ defined by $\vec v\sim\vec w$ if and only if $\vec v-\vec w\in W$. Let $V/U$ be the set of equivalence classes of $V$ under $\sim$ and define addition and scalar-multiplication in $V/U$ by the formulas
\begin{align*}
[\vec v]+[\vec w]&=[\vec v+\vec w] & \lambda\cdot[\vec v]=[\lambda\cdot\vec v]
\end{align*}
One checks that this operation is well-defined and endows $V/U$ with the structure of a vector-space called the quotient space. In fact, if we extend a basis $\{\vec u_1,\dotsc,\vec u_k\}$ of $U$ to a basis $\{\vec u_1,\dotsc,\vec u_k,\vec v_1,\dotsc,\vec v_n\}$ of $V$ one checks that $\{[\vec v_1],\dotsc,[\vec v_n]\}$ is a basis for $V/U$. That is,
$$
\dim V/U=\dim V-\dim U
$$
Now, the map you are interested in is the so-called quotient-map
$$
\pi:V\to V/U
$$
defined by $\pi(\vec v)=[\vec v]$. One checks that this map is a well-defined linear map. One also checks that $\pi$ is surjective with kernel described by
$$
\ker\pi=\DeclareMathOperator{Span}{Span}\Span\{\vec u_1,\dotsc,\vec u_k\}
$$
This map is considered canonical because it is exactly the quotient map one defines in set-theory.
For a concrete example, let $V=\Bbb R^4$ and $U$ be the line through the origin of $V$ and the point $(1,1,1,1)$. Then
$$
\vec u_1=\begin{bmatrix}1\\1\\1\\1\end{bmatrix}
$$
is a basis for $U$ and putting
\begin{align*}
\vec v_1&=\begin{bmatrix}1\\0\\0\\0\end{bmatrix} &
\vec v_2&=\begin{bmatrix}0\\1\\0\\0\end{bmatrix} &
\vec v_3&=\begin{bmatrix}0\\0\\1\\0\end{bmatrix}
\end{align*}
gives a basis $\{\vec u_1,\vec v_1,\vec v_2,\vec v_3\}$ for $V$. In particular, note that $\dim V=4$, that $\dim U=1$, and that $\dim V/U=3$. Can you give a description of the quotient map $\pi:V\to V/U$?
Comment: Hey Brian, Thanks a lot for answering :) Along with Neal's idea, I think I've got a better understanding of this what-seemed-obscure quotient mapping now. For the example...It goes through the origin so $U$ is a subspace of $V$ and so the map takes an element $v \in V$ and takes it to some $w+U \in V/U$ which can be expressed as a linear combination of $v_1, v_2, v_3$?
Answer: When "canonical" is used like this, it usually means "obvious."[*] There are potentially many maps $f:V \to V/U$, but the obvious one, the one you think of first, takes $v$ to the equivalence class that contains it. (Note that your professor actually included the definition of the map, $v\mapsto v+U$.)
If you're not sure whether it's a linear transformation, check it! You know the definitions, so you can apply them. Then find the matrix of the map.
Remember that if you have a linear mapping $M:V\to W$ of vector spaces $V$ and $W$, to assign it a matrix you must first choose bases $\{v_1,\ldots,v_n\}$ of $V$ and $\{w_1,\ldots,w_m\}$ of $W$. Writing vectors as column vectors, the matrix of $M$ is defined so that

the $i^{th}$ column comprises the coordinates of $Mv_i$ with respect to the $\{w_1,\ldots,w_m\}$.

So in this case, you have chosen a basis $\{b_1,b_2,b_3,b_4\}$ of $V$ and a basis of $\{q_1,q_2\}$ of $V/U$. Can you see what the images of the $b_i$ are under the projection, in terms of the $q_j$?

More specifically, here's how I'd recommend approaching the problem. In linear algebra (and everything that depends on linear algebra, which is basically everything else), cleverly choosing a basis is 75% of the problem. So instead of going with the standard basis of $\mathbb{R}^4$, let's use a basis $\{c_1, c_2, c_3, c_4\}$ where $U = \operatorname{span}(c_1,c_2)$.
The projection map is a surjection (you should verify this) so the image of a basis is a spanning set. In fact, this is how we can choose a nice basis for $V/U$: let's push the $c_i$s through the projection and whittle that set down to a basis.
Ah-hah! Our earlier cleverness paid off. The vectors $c_1,c_2$ span $U$, hence span the kernel of the projection map. Thus the images of $c_3,c_4$ span $V/U$, and so we have a useful basis of $V/U$: $\{ c_3 + U, c_4 + U\}$.
Now let's find a matrix for the projection in terms of these vectors. Where does $c_1$ go? Zero. So the first column of the matrix is all zeros. Same for $c_2$. What about $c_3$? It goes to $c_3 + U$, so its column in the matrix is $\begin{bmatrix} 1 \\ 0 \end{bmatrix}$. Likewise for $c_4$.
So the matrix with respect to these bases is
$$ \begin{bmatrix} 0 & 0 & 1 & 0 \\ 0 & 0 & 0 & 1 \end{bmatrix}. $$
If you insist on using the standard basis for $\Bbb R ^4$, the numbers will be more complicated, but you should be fine as long as you hold onto the general principle that coordinates of the matrix are coordinates of the image of each basis vector.

[*] In different contexts, there are many "canonical X"s, but I don't know if the word "canonical" itself has a commonly accepted precise definition. That seems like a question for the category theorists.
Comment: Hi Neal, Thanks for taking your time to answer! I've checked the axioms and it does seem like a linear transformation...But I still can't apply it to solve specific problems :/. Say I have $V=R^4$ and $U$, its subspace. And I picked a basis $b_1=(1 1 0 0)^T,b_2=(0 0  1 1)^T$ for U. I've further extended this basis to a basis of V by adding $b_3=(1 -1 0 0)^T,b_4=(0 0 1 -1)^T$ to my set. Then $b_3+U,b_4+U$ is a basis for $V/U$(I think). However I can't find the method to finding "Matrix for the canonical mapping wrp to the standard basis and $b_3+U,b_4+U$. It's apparently a 2x4 matrix...
Comment: @Melba1993 No problem. It's always fun to review this stuff. I've edited my answer --- does this help?
Comment: I really appreciate your help Neal. So, given the hint, I thought I should add some more context to the question; I am actually given $U={v \in R^4 : v_1=v_2 , v_3=v_4}$ as a subspace of $V=R^4$.  So the bases are as stated above, $b_1,b_2,b_3,b_4$. Now, I've worked out that for some $v \in V$, $v= \frac{1}{2}(v_1+v_2)b_1+\frac{1}{2}(v_1-v_2)b_3+\frac{1}{2}(v_3+v_4)b_2+\frac{1}{2}(v_2-v_4)b_4$. And the mapping sends this to $v+U$ i.e. to $\frac{1}{2}(v_1-v_2)b_3+\frac{1}{2}(v_3+v_4)b_4+U$. But I can't figure out how to construct a matrix from here....
Comment: I mean, on my LHS I have $v$ in terms of for basis so that gives me a 4 by 4 matrix i.e the columns in $b_1,b_2,b_3,b_4$ but the RHS is...a matrix with $U$ in it..? Like, $(b_3+U, b_4+U)(\frac{1}{2}(v_1-v_2) ; \frac{1}{2}(v_3+v_4)$? Even if so,  $(b_3+U, b_4+U)$ isn't a square matrix so, how can I find its inverse, to multiply it along with the LHS to find my final matrix?? I am sorry to ask much but it would be more than great if you could guide me further....thanks
Comment: @Melba1993 I think you're thinking too hard. I edited my answer. A minor point - the elements of $V/U$ are cosets which can be represented as $v + U$, so when you write out an expression for vectors in $V/U$ using this representation, it will have lots of "$+U$"s in it.
Comment: Thanks so much again for replying back! Yes, the edited post cleared it up...I've been fiddling with it on my own too and arrive at the same matrix as yours. I tried another similar one and got the correct answer, I've probably got the hang of the idea now, thanks a lot!!
Answer: Let $X$ be the solution space of the ODE $\ddot x+ x=0$, and let $Y$ be the solution space of the ODE $\ddot y-y=0$. Then both $X$ and $Y$ are two-dimensional vector spaces (over ${\mathbb R}$, say). Therefore $X$ and $Y$ are isomorphic. But there is no "canonical" bijective linear map $f: \>X\to Y$ that is the prime candidate for such an isomorphism. In order to define any particular isomorphism you have to choose a basis $(e_1,e_2)$ in $X$ and to declare what the images $\bar e_i:=f(e_i)\in Y$ shall be.
Contrasting this, a canonical map between spaces $X$ and $Y$ arises if it can be defined from the present situation without introducing new data chosen in some  arbitrary way.
In your case the "situation" consists of a vector space $V$ and a subspace $U$, and nothing else. (Of course there are certain data necessary to define this subspace $U$ precisely.) Given $V$ and $U$ there is a completely abstract construction that defines a new vector space $V/U$. Unlike the vectors $u\in U$ the elements of $V/U$ are not certain special vectors of $V$, but are entities $\hat v$ which are addressed in the form $v+U$, whereby the $v\in V$ is not uniquely determined by $\hat v$. It is then shown that the map
$$f:\quad v\to V/U,\qquad v\mapsto v+U$$
is (a) well defined, and is (b) a linear map from  the vector space $V$ the vector space $V/U$. Note that in order to define this $f$ we did neither have to choose a basis in $V$, nor the images of the chosen basis vectors.
But if you want to do computations with this $f$ you need a basis of the abstract space $V/U$. The way to go is to replace $V/U$ by an isomorphic copy living as a bona fide subspace in $V$. Any complement of $U$ in $V$ will do for this purpose. I won't go into this here.

Canonical Mapping in Linear Algebra


Where to define SSL config for multiple nginx server blocks

Question: I want to redirect http to https, and naked to www.
So my config:
<code># http naked -> https www
# http www -> https www
server {
  listen 80;
  server_name example.com www.example.com;
  return 301 https://www.example.com$request-uri;
}

# https naked -> https www
server {
  listen 443 ssl http2;
  server_name example.com;
  #ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem     # <--- ??
  #ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem   # <--- ??
  return 301 https://www.$host$request-uri;
}

# https www
server {
  listen 443 ssl http2;
  server_name www.example.com;
  ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem
  ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem
}
</code>
Do I need to repeat the SSL stuff shown as <code>??</code> in the middle block?
Answer: Every ssl virtualhost must define key/cert. So in your case if you wrote "listen ... ssl", you have to write ssl_certificate lines. It is not important, if that key/cert pair will be used for anything else.
You can have aliases. I.e. if your key/cert pair in /etc/letsencrypt/live/example.com is valid for both example.com and www.example.com (i.e. that is SAN certificate), and you want to serve same content from www.example.com and example.com without redirect, you can have only one ssl vhost in nginx: server_name example.com www.example.com;
You can do redirect even in this case, but I think it is easier to understand and maintain a config if those are distinct vhosts.
Comment: Yes, it does a redirect ony /after/ initialising a TLS session. Absolutely any HTTP activity in HTTPS is only possible after TLS session setup. Session setup is initiated by Client Hello message, to which TLS server answers with its certificate. Then, after some cryptographic math, they both securely create a secret shared session key. That math requires server to also have a key corresponding to its certificate. This is actually the way to achieve a provably secure communication. If redirect was made possible without TLS, then MitM would be able hijack your visitors to MitM-crafted site.
Comment: Thanks! So every ssl server block must have certs, *even if all it does is redirect?*
Comment: Thanks! Also, I don't understand your second point - I thought I need three blocks: one from naked to www, one for http to https and a last "real" one... Are you saying I only need two?
Comment: You may create a single Nginx virtual host that supports multiple hostnames. For HTTPS case, all these hostnames have to be valid in its certificate, and such certificate would be called a SAN cert (ordinary cert has a name in required common name = "CN" field, and alternative domain names are specified in optional subjectAltName = "SAN" field). "www.example.com" and "example.com" are distinct names, and you can either have different certs, one for each name, or have a single SAN cert that is valid for both. In the latter case you may set up a single ssl virtual host if you wish.


subbase for compact open topology is not base?

Question: I am trying to understand whether a subbase for compact-open topology is a base for the topology?
So, let $X,Y$ be topological space, and $C(X,Y)$ the space of continuous functions from $X$ to $Y$.
For a compact $K\subset X$ and open $V\subset Y$, let $M(K,V)$ denote the collection of all those continuous function $f:X\rightarrow Y$ with $f(K)\subset V$.
The compact open topology on $C(X,Y)$ has subbase $\{M(K,V)\}_{K,V}$ with $K\subset X$ compact and $V\subset Y$ open.
For compact sets $K_1, K_2$ in $X$ and open $V_1,V_2$ in $Y$, I do not understand whether $M(K_1,V_1)\cap M(K_2,V_2)$ is always $M(K,V)$ for some compact $K$ in $X$ and open $V$ in $Y$. Any example for truth/failure of this fact?
Comment: Try $X=\{a,b\}$ discrete, $K_1=\{a\}$, $K_2=\{b\}$.
Answer: Expanding upon the comment by Lord Shark, we construct a counterexample. Take any space $Y$ which contains two disjoint open sets $V_1$ and $V_2$. Now $M(K_i,V_i)$ is the set of functions which map $a$/$b$ into $V_1$/$V_2$. The intersection $F = M(K_1,V_1)\cap M(K_2,V_2)$ is the set of all functions which map $a$ into $V_1$ and $b$ into $V_2$.
I claim, however, that this is not $M(K,V)$ for any sets $K$ and $V$. To see this, note that $f\in F$ is equivalent to both a restriction both on $f(a)$ and $f(b)$. Thus if $F = M(K,V)$ we must have $K=X$. Also, since $F$ contains all functions mapping $a$ into $V_1$ and $b$ into $V_2$, we must have $V_1\cup V_2\subset V$ (since the image of $K=X$ can be any two-point subset with one point in $V_1$ and one point in $V_2$). But then $M(K,V)$ contains some function $g$ mapping both $a$ and $b$ into $V_1$, and since $V_1$ and $V_2$ are disjoint we can not have $g\in F$.
Comment: Maybe I'm not fully understanding what you mean, but you could word your argument differently in claiming that $K=X$; Every subset of $X$ is compact, as there are only finitely many open sets. But clearly, for example, the choice $K=\{a\}$ is not valid as there are some functions such that $f(a)\in V_1$ while $f(b)$ can be anything. Same for $\{b\}$. So we are left with $X$
Comment: Yes, the argument is that the set "$K$" in this notation is the only one on whose image we place an explicit condition. But when $X$ has only two points, and the image of each is restricted, this set on which we place the restriction must be all of $X$.
Answer:
Let $X=Y=\mathbb R$ with the usual topology. Then, there exist no $K\subseteq \mathbb R$ and $V\subseteq\mathbb R$ such that

$K$ is compact,
$V$ is open, and
$M(\{0,1\},(0,1))\cap M(\{1,2\},(0,2))=M(K,V)$.

To see this, suppose, for the sake of contradiction, that such $K$ and $V$ exist. For brevity, let
\begin{align*}
M_1\equiv&\;M(\{0,1\},(0,1)),\\
M_2\equiv&\;M(\{1,2\},(0,2))
\end{align*}
in what follows.
Claim 1$\phantom{--}$ $V\neq \mathbb R$.
Proof$\phantom{--}$ If $V=\mathbb R$, then $M(K,V)$ contains all real-to-real continuous functions, but $M_1\cap M_2$ clearly does not contain all real-to-real continuous functions. $\phantom{--}\blacksquare$
Claim 2$\phantom{--}$ $V\neq \varnothing$.
Proof$\phantom{--}$ If $V=\varnothing$, then the only way that $M(K,V)$ can be non-empty (which it must be, given that $M_1\cap M_2$ is obviously non-empty) is by having $K=\varnothing$. But then $M(K,V)$ contains all real-to-real continuous functions, which is, again, impossible. $\phantom{--}\blacksquare$
Claim 3$\phantom{--}$ $K=\{0,1,2\}$.
Proof$\phantom{--}$ If $x\in K$ but $x\notin\{0,1,2\}$, then construct a continuous function (through, say, linear interpolation) $f:\mathbb R\to\mathbb R$ such that $f(0)=f(1)=f(2)=1/2$ and $f(x)=v$ for some arbitrary $v\in\mathbb R\setminus V$ (see Claim 1). Then, $f\in M_1\cap M_2$, but $f\notin M(K,V)$. Therefore, one must have $K\subseteq\{0,1,2\}$. Conversely, if $x\in\{0,1,2\}$ but $x\notin K$, then pick any $v\in V$ (which is possible by Claim 2) and construct a continuous function $f:\mathbb R\to\mathbb R$ such that $f(x)=3$ and $f(y)=v$ for $y\in\{0,1,2\}\setminus\{x\}$. It is easy to check that $f\in M(K,V)$ (remember it has been already proven that $K\subseteq\{0,1,2\}$) but $f\notin M_1\cap M_2$. Therefore, one must have $\{0,1,2\}\subseteq K$. $\phantom{--}\blacksquare$
Claim 4$\phantom{--}$ $(0,2)\subseteq V$.
Proof$\phantom{--}$ If not, then take any $v\in(0,2)$ such that $v\notin V$. Construct a continuous function $f:\mathbb R\to\mathbb R$ such that $f(0)=f(1)=1/2$ and $f(2)=v$. But then $f\in M_1\cap M_2$, yet $f\notin M(K,V)$, given also that $K=\{0,1,2\}$ by Claim 3. $\phantom{--}\blacksquare$
To obtain a final contradiction, consider the constant function $f\equiv 1$. By Claim 4, $f\in M(K,V)$, but $f\notin M_1\cap M_2$.


Does this prove that two lines are parallel?

Question: I was recently given this problem:
Suppose we have a triangle $ABC$ and let there be a cevian $AD$. Let the foot of the perpendicular from $B$ to $AD$ be $P$ and let the intersection of the extension of $BP$ to $AC$ be $Q$. Prove that $DQ$ and $AB$ are parallel.
So I extended a line from $D$ parallel to $AC$ and let it intersect $AB$ at $R$. By rules of parallel lines, this means that $\widehat{BAD}=\widehat{BDQ}$ which also means that $AB$ and $DQ$ are parallel. However, this seems too simple. Does this approach work?
Comment: "this means that"... what?
Answer: Your statement does not seem to be true. Here is a diagram fitting your requirements, and we clearly see that $\overline{DQ}$ is not parallel to $\overline{AB}$. We also see that your approach with point $R$ does not seem to work.

Did you intend a particular cevian with point $D$, or just any $D$ on $\overline{BC}$?


How do I debug Powershell Desired State Configuration not generating MOF files?

Question: I'm following the most basic example on MSDN and I'm failing to get it to work. I've got my configuration defined as follows:
Configuration MyWebConfig
{
   Param($ComputerName)

   Node $ComputerName {
      WindowsFeature MyRoleExample
      {
          Ensure = "Present"
          Name = "Web-Server"
      }
    }
}

I'm trying to generate MOF with C:\Scripts> .\IisWithCompressionConfig.ps1 -ComputerName "localhost" -Outputpath C:\Scripts\localhost (and couple other command line variants). I'm not getting any file output and no errors are reported (exit status code is also 0). I've tried a version without the $ComputerName variable (and instead "localhost" hardcoded), still nothing. Yes, I'm running this in an elevated prompt.
I've made sure that I'm running PowerShell 4.0:
C:\Scripts> $PSVersionTable

Name                           Value
----                           -----
PSVersion                      4.0
WSManStackVersion              3.0
SerializationVersion           22.214.171.124
CLRVersion                     4.0.30319.34003
BuildVersion                   6.3.9600.16394
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0}
PSRemotingProtocolVersion      2.2

Any ideas what am I missing?
Answer: With DSC, I dot source the configuration definition into the current session, then call it.
# dot source will load PS1 into current session
. .\IisWithCompressionConfig.ps1
# Then call the config
MyWebConfig -ComputerName "localhost"

Configurations are quite similar to functions, that is you'd want to call MyWebConfig (config) not IisWithCompressionConfig (file).  In fact, defined DSCs will be in the Function: PSDrive. Try running the following both before, and after, you dot source your PS1.  Before, you should see no results, after, you should see MyWebConfig in the Function: PSDrive.
Get-ChildItem Function:* | Where-Object { $_.CommandType -eq 'Configuration' }

In the provided TechNet example, they're using the ISE.  In step 4 they're defining (instead of sourcing) the MyWebConfig config right in the current PS session.  This is functionally equivalent to dot sourcing the PS1 file.  Right after step 6, they call MyWebConfig, which generated the MOF.
Comment: D'oh. You're right! In my defense, that article is not very clear on that detail.


Setting local variable containing data from database to global format

Question: I have this variable containing data from database in if statement. How to set it to global or is there any way to access those data outside of that if statement?
if(condition){
   $data = G_Employee::find()->single('id', 'some value');
}

Comment: Outside of that `if`? If the line runs, it's already available outside the `if`. https://3v4l.org/2VY2f
Comment: It says that I am using an undefined variable when I access its data. I did it like this: $data->id; And btw, I put that code inside another if statement. Does doing that cause me to get this error?
Comment: Perhaps your `condition` is returning `false`? If the body of the `if` doesn't run, then `$data` won't be set in which case you should set a default value outside of the condition.
Answer: Use this one to access data outside of that if statement
$GLOBALS['data'];
     if(condition){
       $data = G_Employee::find()->single('id', 'some value');
    }

Answer: You can define a variable for your class and use/access it with $this
Example:
class MY_CLASS extends CI_Controller {

   protected $data;

   public function MY_FUNCTION {
      if(condition){
         $this->data = G_Employee::find()->single('id', 'some value');
      }

      var_dump($this->data); //$this->data is accessible from anywhere in your class.
                            //You can check if it has the value you want
   }

}

Comment: I am coding in view. Will it be applicable in view, the "$this->data"?


Rename sources.list

Question: In

/etc/apt/

a have this:
<code>apt.conf.d  preferences.d  sources.list  sources.list_bak  sources.list.d  sources.list.save  trusted.gpg  trusted.gpg.d
</code>
I need to remove sources.list and rename sources.list_bak to sources.list
Thank you!
Comment: Stack Overflow is a site for programming and development questions. This question appears to be off-topic because it is not about programming or development. See [What topics can I ask about here](http://stackoverflow.com/help/on-topic) in the Help Center. Perhaps [Super User](http://superuser.com/) or [Unix & Linux Stack Exchange](http://unix.stackexchange.com/) would be a better place to ask.
Answer: <code>$ sudo rm sources.list
$ sudo mv sources.list_bak sources.list
</code>
Anyway, I would recommend to backup source.list instead of remove it. So, replace the first command with this one:
<code>$ sudo mv sources.list sources.list.bak
</code>

Rename sources.list


Help with identifying scales from track

Question: I've been studying basic drumming, and found this track on YouTube, Prog Metal - Drumless Track For Drummers - "Reckoning".
The tempo is 175 BPM, so to be able to listen to the notes, I slow the video down to 0.75, 0.5.
Firstly, there are 2 different though similar scales being played, and they remind me of the sound of God Chords or Space Chords, but there is also a certain Middle Eastern sound (notes, natural 3 progression) that make both scales sound not quite Major, resulting in a somewhat mystical sound.
Secondly, the 2nd scale being played either has a delay or is actually being played in such a way as to sound as though it is delayed (if that makes sense).
Can someone please help identify both scales?
Answer: Only two scales and chord types are used: Maj7 and min7.
<code>1st section: B♭maj7 | B♭maj7 | A♭maj7 | Cmin7
2nd section: B♭maj7 | A♭maj7 | G♭maj7 | A♭maj7
</code>
It is possible that the aumented fourth could be used for the major chords (lydian scale), especially for the G♭, and the augmented sixth (dorian scale) for the C minor, but it doesn't seem that those notes are being played by the guitar.

Help with identifying scales from track


Competition using Kentico API - editing comments in workflow

Question: I would like to add content to Kentico CMS Tree using Kentico 7 API in ASP.NET web forms. Main idea: users send the application to the competition via form on my site and I would like to save this application on CMS tree. It will be a competition with hierarhical tree structure of document types:

Competition -> Competition Application -> Application Comment

I would like content editor to clean unappropriate comments.
I have three servers: development environment, staging and production. Content editors have permissions to edit data only on staging. But if I save user application to CMS tree they couldn't do it in staging environment (you can see in only on production). I will be using workflows so it is necessary to use Kentico API. I also cannot give permissions to content editors to edit data on the production environment directly.
So how can I make a competition using API, access workflows and allow content editors edit bad comments on staging? Do you have any idea how can I solve this problem? I would like to avoid making separate website with backoffice.
Answer: Take some time to read Kentico's documentation on working with documents and the workflow using their API.
In particular, read how to create documents and how to control workflow
You can control whether or not a document is published by manipulating what step it's in in the workflow.
You can also manually synchronize documents using the staging module's API.  Its documentation can be found here
Comment: I don't have a problem with implementing this - I have already done it and it works, but I feel that my conception for the competition were wrong - we have problems with editing comments because of lack of opportunity to edit them on staging. On the other hand I don't want to make separate website for content editor to edit things on the cms tree. Any idea how to change the mechanics of my system to allow easier edit things?
Comment: I would just use a simple workflow where a document has to be approved before it's published. User submits comment, comment document is created as an unpublished doc, synch the unpublished doc to staging, your moderators review, if they approve it it becomes published and you synch it back to production. You'll have to create some custom controls and methods to make all this happen at the right time and in the right order, but it should be pretty straightforward.
Comment: Thanks! I didn't think about synch comment back to staging!


Entrada no if() mas as instruções não são executadas

Question: Estou a tentar fazer um chat usando pipes(chat entre servidor e cliente). Fiz uma condição de saída, caso o server queira sair/desligar o chat escreve "quit", no cliente da mesma forma. Fazer "quit" a partir do servidor está a funcionar, no entanto apartir do cliente não. O meu código é este:
client.c
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <ctype.h>
#include <pthread.h>
#include <string.h>
#include <fcntl.h>
#include "fifo.h"

int main()
{
    int readfd, writefd;
    umask(0);
    if((writefd=open(FIFO1, 1))<0)
        printf("client: Erro a abrir write fifo\n");
    if((readfd=open(FIFO2, 0))<0)
        printf("client: Erro ao abrir read fifo\n");

    char name[20], mensagem[200], OtherName[20];
    printf("Bem-vindo ao chat!\n");
    printf("Introduza o seu nome: ");
    fgets(name, 20, stdin);
    printf("Introduza quit caso deseja fechar o chat\n");

    if(fork()==0)
    {
        while(1)
        {
            fgets(mensagem, 200, stdin);
            printf("\n");
            if(strncmp(mensagem, "quit", 4) == 0)
                exit(0);
            write(writefd, name, 20);
            write(writefd, mensagem, 200);
        }
    }

    else
    {
        while(1)
        {
            read(readfd, OtherName, 20);
            read(readfd, mensagem, 200);
            printf("\n%s -->%s\n", OtherName, mensagem);
        }
    }

    close(readfd);
    close(writefd);
    if(unlink(FIFO1)<0)
        printf("client: não foi possível fazer unlink\n");
    if(unlink(FIFO2)<0)
        printf("client: não foi possível fazer unlink\n");
    return 0;
}

server.c
#include <sys/stat.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <ctype.h>
#include <pthread.h>
#include <string.h>
#include <fcntl.h>
#include "fifo.h"

int main()
{
    int readfd, writefd;
    umask(0);
    unlink(FIFO1);
    unlink(FIFO2);//unlink dos fifos anteriores
    if((mknod(FIFO1, S_IFIFO | PERMS, 0))<0)
        printf("Erro a criar o fifo\n");
    if((mknod(FIFO2, S_IFIFO | PERMS, 0))<0)//criação de fifos
        printf("Erro a criar o fifo\n");
    if((readfd=open(FIFO1, 0))<0)//abrir o fifo em modo de leitura
        printf("Erro ao abrir read fifo\n");
    if((writefd=open(FIFO2, 1))<0)//abrir o fifo em modo de escrita
        printf("Erro ao abrir write fifo\n");

    char name[20], mensagem[200], OtherName[20];
    printf("Bem-vindo ao chat!\n");
    printf("Introduza o seu nome: ");
    fgets(name, 20, stdin);//nome do user no chat
    printf("Introduza quit caso deseja fechar o chat\n");

    if(fork()==0)//se fork()==0, então o server vai receber uma mensagem
    {
        while(1)
        {
            read(readfd, OtherName, 20);//lê o nome do outro user
            read(readfd, mensagem, 200);//lê a mensagem do outro user
            printf("\n%s -->%s\n", OtherName, mensagem);//escreve a mensagem
        }
    }

    else//se o servidor vai enviar uma mensagem
    {
        while(1)
        {
            fgets(mensagem, 200, stdin);//user introduz a mensagem
            printf("\n");
            if(strncmp(mensagem, "quit", 4) == 0)
                exit(0);
            write(writefd, name, 20);//escrever o nome para o pipe de escrita
            write(writefd, mensagem, 200);//escrever a mensagem
        }
    }

    close(readfd);
    close(writefd);
    return 0;
}

No client.c, no seguinte if:
if(strncmp(mensagem, "quit", 4) == 0)
 exit(0);

O programa entra no if mas não executa instrução. Porque é que isto acontece?
Obrigado!
Comment: sera' que n~ao tem '\n' no final de mensagem? Desculpe, estou sem acentuacao no meu Linux.
Comment: como assim? não entendi @lemoce
Comment: Tem certeza que entra no if, tenta colocar um pause dentro do if... Acho que o lemoce quis dizer é que se a mensagem não esta " quit \n" esta indo com uma quebra de linha.. dai ele não esta entrando no if, pq a mensagem é maior.
Comment: já testei o if, ele realmente entra no if por isso não penso que o erro esteja aí @MatheusFrancisco
Comment: @Gazelle, o lance 'e que voc^e tem dois processos. O pai e o filho. O processo pai vai esperar at'e o filho terminar, s'o que o filho est'a dentro de um loop infinito. N~ao tenho certeza, mas voc^e tem que mandar uma mensagem de fim para o processo filho. Vou fazer uns testes.
Answer: Eu fiz um exemplo mínimo:
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>

int main()
{
  pid_t myPid = 0;

  if ((myPid = fork()) == 0)
    {
      printf ("processo pai %d\n", myPid);
      if (1)
        {
          exit(0);
        }
    }
  else
    {
      printf ("processo filho %d\n", myPid);
      while(1)
        {
          sleep(1);
          printf("mensagem do filho: dentro do while\n");
        }
    }

  return 0;
}

Esse exemplo tem a saída:
macbook% ./a.out
processo filho 2439
processo pai 0
mensagem do filho: dentro do while
mensagem do filho: dentro do while
mensagem do filho: dentro do while
^C
macbook%

Achei uma resposta no SO. Segue o exemplo mínimo baseado na resposta:
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/prctl.h>
#include <signal.h>

int main()
{

  // para testar o pid do pai apos o termino do pai
  pid_t ppid_before_fork = getpid();
  pid_t pid = fork();

  if (pid == -1)
    {
      perror(0);
      exit(1);
    }

  if (pid)
    {
      printf ("processo pai %d\n", pid);
      sleep(10);
      if (1)
        {
          exit(0);
        }
    }
  else
    {
      // do comando $ man prctl
      // Return  the current value of the parent process death signal, in
      //   the location pointed to by (int *) arg2.
      int r = prctl (PR_SET_PDEATHSIG, SIGTERM);
      printf ("processo filho %d\n", pid);
      while(1)
        {
          sleep(1);
          printf("mensagem do filho: dentro do while\n");
          // if que testa se o pid do pai esta diferente
          // ocorre apos o exit
          if (getppid() != ppid_before_fork)
            exit(1);
        }
    }

  return 0;
}

Basicamente, o exemplo do colega se baseia na especificacão posix:

The parent process ID of all of the existing child processes and zombie processes of the calling process shall be set to the process ID of an implementation-defined system process. That is, these processes shall be inherited by a special system process.

Com uma citacão do autor da resposta:

Traditionally, the system process adopting all orphans is PID 1, i.e. init - which is the ancestor of all processes.

Resumidamente, todo o processo orfão tradicionalmente recebe pid 1, pois ele é o ancestral de todos os processos.
Mais uma citacão do autor:

Note that storing the parent process id before the fork and testing it in the child after prctl() eliminates a race condition between prctl() and the exit of the process that called the child.

Armazenando o processo pai antes do fork e testá-lo apos o prctl() elimina o race condition entre o prctl() e a saída do processo que chama o filho.
ps1: info do $ man prctl

This call is Linux-specific.  IRIX has  a  prctl()  system  call  (also introduced  in  Linux  2.1.44  as irix_prctl on the MIPS architecture), with prototype

Pode não funcionar nos Unix


Graphing a P-P plot given a set of data from a Poisson distribution?

Question: I'm attempting to complete an assignment for a class and reading the book isn't particularly helpful as it's extremely wordy and unclear.  I'm mainly confused on exactly what the x and y values are supposed to be within a P-P plot.  The problem I'm given is as follows:

If the following data are hypothesized to be drawn from a Poisson
distribution:
3, 0, 7, 2, 6, 4, 3, 4, 3, 4, 5, 0, 0, 3, 2, 1, 0, 3, 4, 4, 7, 2, 3, 6,
2, 1, 2, 2, 1, 1, 3, 0, 3, 4, 3, 5
Draw a P-P plot for the distribution.

The book states something along the lines of:

A probability–probability (P–P) plot is a graph of the model
probability $\hat F(X_{(i)})$ versus the sample probability
$\tilde F_{n}(X_{(i)}) = q_i,$ for i = 1,2,...,n

Based on earlier assignments, it's my understanding that $\tilde F_{n}(X_{(i)}) = \frac{i-0.5}{n}$, but what is the formula for $\hat F(X_{(i)})$? And which belongs on which axis?
Comment: You might find this answer [here](http://stats.stackexchange.com/questions/92141/pp-plots-vs-qq-plots) informative.
Answer: It doesn't matter which values go with which axes, provided you clearly label them.  (Both forms are in common use.)
The "sample probability" is badly named, because it is a relative frequency; namely, the relative frequency of any possible value $k$ in a sample $(x_1, x_2, \ldots, x_n)$ is $1/n$ times the number of $x_i$ equal to $k.$  The sample frequencies in the example in the question can be computed in R with a formula like table(x) / length(x). Let's call these relative frequencies $\hat f(k).$
The "model probability" is not well named either.  It is an estimate of the chance of $x,$ assuming the sample is a sequence of $n$ independent realizations of a random variable.  But in this case there at least is a probability model in evidence: the Poisson family of distributions.  A good (but not the only) estimate of the Poisson parameter is the mean of the data, $\bar x.$  The Poisson family is defined so that when the parameter equals $\bar x,$ the probability of $k$ when $k$ is among the natural numbers $0, 1, 2, \ldots$ is given by
$$\Pr(k) = e^{-\bar x} \frac{\bar x^k}{k!}.$$
This gives two distribution functions.  The value of the empirical distribution function $\hat F$ for any number $k$ (whether a natural number or not) is the chance a randomly chosen data value will not exceed $k.$  Evidently
$$\hat F(k) = \sum_{x\mid x \le k} \hat f(x).$$
It is the proportion of data values less than or equal to $k.$
The second distribution is that of the estimated Poisson distribution,
$$\tilde F(k) = \sum_{x=0}^k \Pr(k)$$

The PP plot consists of all the distinct ordered pairs $(\tilde F(k), \hat F(k))$ as $k$ ranges over all the values of the data.

When the data frequencies are similar to the frequencies of this estimated distribution, these pairs will thereby all come close to the line $y=x.$  Deviations from that line indicate deviations between the data distribution and the fitted ("model") distribution.  With a little practice, at a glance you can tell whether the fit is good or not.

Here is a full R implementation and its output.
lambda.hat <- mean(x)
F.hat <- cumsum(table(x) / length(x))
p.hat <- ppois(as.numeric(names(F.hat)), lambda.hat)
plot(F.hat, p.hat, xlim = 0:1, ylim = 0:1, asp = 1)

The set of ordered pairs is implicit in the two arrays F.hat and p.hat.  Here they are stacked to show the pairs in the columns:
          0    1    2    3    4    5    6    7
F.hat 0.140 0.25 0.42 0.67 0.83 0.89 0.94 1.00
p.hat 0.057 0.22 0.46 0.68 0.84 0.93 0.97 0.99

To appreciate what a PP plot can do, here is the output for a dataset of the same size and a similar mean generated with a geometric distribution rather than a Poisson distribution:

It is immediately obvious the points do not come close to the reference line.  Comparing the point heights to the reference line shows that $\hat F$ (the empirical distribution describing the data) is too small for small values (at the left) and too large for large values (at the right).  In other words, the data have too many extremely large values for their average.


C++ interacting with a dynamic webpage?

Question: I was thinking recently about what projects I could start that would be of use to me and this came up.  I post on various forums a daily updated journal entry that is the same for each forum.  I also keep a log of the journal entries as individual docx files on my hard drive.  I figured it would be great if I could create a program that would be given an input docx file and then post its contents as a new reply to all the daily journal threads on the forums that I have.
I am well versed in c++ for college like programming (algorithms, programming competitions, science based assignments and such), but not at all experienced with practical applications.  My first question to get me started with this new idea of mine is if there are any libraries for c++ that allow for an interaction to a dynamic webpage like I described.
Thanks Much,
Michael
Answer: That problem can be approached as simply as using cURL (or a similar library) to GET pages and POST form data, or it could be as complicated as writing a Firefox XPCOM extension.
Answer: Any interaction with web page (posting a reply or tweeting or searching) is typically either POST or GET http request. As meantioned by greyfade - to construct such requests - you whouls use cURL or smth like asio from Boost library.

C++ interacting with a dynamic webpage?


React-codemirror 2 linting feature not working

Question: I have created a react-codemirror 2 component in my react app but the linting feature of the package is not working. I tried browsing other stack overflow questions but since the questions are at least 2 years old it looks like the file structure for the original library i.e. codemirror has been changed and none of the solution seem to work. I also opened an issue in their Github repo but no response on that. Hope you can help, here's the code for my component.
import React from "react";
import { UnControlled as CodeMirror } from "react-codemirror2";

import 'codemirror/lib/codemirror.css';
import 'codemirror/theme/material.css';
import 'codemirror/addon/lint/lint.css';
import 'codemirror/addon/hint/show-hint.css';

import 'codemirror/mode/javascript/javascript.js';
import 'codemirror/addon/lint/javascript-lint';
import 'codemirror/addon/lint/lint.js';
import 'codemirror/addon/hint/javascript-hint';

const JsEditor = ({code}) => {
  return (

 JavaScript

      <CodeMirror
        value={code}
        options={{
          gutters: ["CodeMirror-lint-markers"],
          mode: "javascript",
          theme: "material",
          lineNumbers: true,
          lineWrapping: true,
          lint: true,

        }}

      />

  );
};

export default JsEditor;

Answer: The lint addon from CodeMirror requires jshint library. If you add it (npm i jshint), the following code should work:
import React from 'react';
import { UnControlled as CodeMirror } from "react-codemirror2";
import 'codemirror/lib/codemirror.css';
import 'codemirror/theme/material.css';
import 'codemirror/addon/lint/lint.css';
import 'codemirror/addon/hint/show-hint.css';
import 'codemirror/mode/javascript/javascript.js';
import 'codemirror/addon/lint/javascript-lint';
import 'codemirror/addon/lint/lint.js';
import 'codemirror/addon/hint/javascript-hint';
import { JSHINT } from 'jshint';
window.JSHINT = JSHINT;

const JsEditor = ({ code }) => {
  return (

 JavaScript

      <CodeMirror
        value={code}
        options={{
          gutters: ["CodeMirror-lint-markers"],
          mode: "javascript",
          theme: "material",
          lineNumbers: true,
          lineWrapping: true,
          lint: true,
        }}
      />

  );
};

function App() {
  return (

      <JsEditor code={'var widgets =[]; debugger'} />

  );
}

export default App;


Adding second Windows Server to domain

Question: I have a Windows Server 2008 R2 Server (Server A) running as a domain controller with Active Directory, Group Policy, and DNS services.
I set up a second Windows Server 2008 R2 server (Server B), added it to the domain, and installed the Active Directory, Group Policy, and DNS Roles.
If I take Server A offline, then Active Directory and Group policy services are no longer available on Server B.
What would I need to do in order keep AD & GPO services operating while one server or the other is offline?
[edit]: Would I possibly need to do something involving dcpromo.exe on Server B? If so, what might that be?
Comment: Did you enable the Global Catalog on the new server? http://technet.microsoft.com/en-us/library/cc758330%28v=ws.10%29.aspx
Comment: RE: your edit: Did you run DCPROMO on the new DC or did you just install the Roles? If you didn't run DCPROMO then you need to. Installing the Roles only installs the "bits".
Comment: There are several ways to launch DCPROMO. Open an elevated command prompt and type DCPROMO then press the Enter key. Then follow the wizard.
Comment: I did not do so manually, however, when I looked, the "Global Catalog" option was checked for both servers.
Comment: Make sure that all domain clients are configured to use both DC/DNS servers for DNS.
Comment: I did not run DCPROMO. I just installed the roles individually/manually.
Comment: Should I simply run `dcpromo.exe` from the command line, or do I need to use one of its switches (ie, `dcpromo /forestprep`)?
Comment: whenever I have run dcpromo it brings up a gui so you can select any options you need
Comment: If time is not an issue I would be tempted to start from scratch with server B. Reinstall and then run dcpromo which should automatically set server B into the dc OU
Comment: Running DCPROMO from an elevated command prompt seems to have done the trick. Thanks! The first time around, I didn't run it from an elevated prompt, and it didn't really do much of anything.
Answer: You need to run dcpromo on the second server to make it a domain controller and install the other roles.
You need to make sure it is a global catalog so that these services will continue to run if either server is offline. The AD content should replicate between the two servers by AD DS replication
Comment: Yeah, if you didn't actually run dcpromo, you don't have a second domain controller.
Comment: After running DCPROMO from an elevated command prompt, each server was able to continue AD and GPO operations while the other was offline.
Answer: DNS, DNS, DNS.
Ensure that each DC is a DNS server for the AD's DNS zone, and ensure that the DNS settings on each server's NIC points to itself and the other DNS server.
The order of which each should point to is a bit of a bone of contention, you can find people arguing both sides - but without both, when one is down, the other will be sunk.
Thus, also ensure that your client machines are configured to use both for DNS servers as well.
Comment: I've recently come to the conclusion (for my implementations) that each DC should point to another DC first for DNS and then to itself.
Comment: Each server is configured as @joeqwerty describes.
Comment: As far as I can tell, there isn't a disruption in DNS resolution when one of the servers goes offline.
Comment: I like Joe's approach and it is the one that I use myself, but I've read both sides and wasn't going to try to be authoritative or exhaustive.

Adding second Windows Server to domain


How to restore private file structure after major version update?

Question: After a Drupal 6 to 7 update we are unable to use private image download, symptom is we cannot access private files via system/files, while public files can be loaded.
Trying to download private file results in a 404 -- Not found error, sent from the web-server directly, not drupal. After some changes to the configuration this results instead in a Drupal Error page. The server log says
File does not exist: /home/licebase/drupal/system/files/genefinding_diagram_1_2.png, referer: https://myhost/node/761470/edit?render=overlay
The system file exists and has the correct permissions.
Centos 6 on virtualization host, PHP 5.3.3, Postgres 8.4 on dedicated DB server, Apache 2.2.15 (centos) + a lot of active modules + fields+cck
Comment: There never has been a good upgrade path till D8. Can you give a better description of your setup?
Comment: This is an update from a running d6 instance including tripal (see: http://tripal.info that should have no relevance here). Running on a cloned vm under centos, using postgres 8.4 db host, php5.3.3, apache, drush 6.7, using CCK, views and a bunch of other models. Core update was done following the standard update procedure. Please let me know, if you need any specific information.
Comment: Please be aware that bug reports are off topic here.
Comment: Well, I am not even sure it is a bug, I am in the process of finding out, it might still be a misconfiguration. Is there any relevant input you could give me on topic? I appreciate any constructive hint. Also, who says they are off topic? Would also the disparate question of how to debug a real error  be off topic here? Then this site wouldn't be very useful overall.
Comment: @Michael It's Q+A, so ask a specific, objectively answerable question, get a specific, objective answer. That's the only thing this site is useful for (intentionally so). General hints on where to start, how to debug a site, and other broadly natured requests don't fit the format very well so don't be too surprised if people don't engage here. There are forums out there if you need a back-and-forth/support style request. BTW it's the [help] that lists bug reports/workarounds as off-topic - discussions about such things happen in the module issue queue, not here, for a variety of reasons
Comment: I hope to convince you that my question is specific and objectively answerable in case anyone has observed something similar, further I hope we convinced you that we already have tried a lot. From my own experience as administrator of a QA site I know that this format is not good for back-and forth or debugging. However, you will also find that we haven't had any significant input on any our questions so far except our own findings to a problem (where there has been no other sufficient solutions out there). So there is not much back-and forth to complain about.
Comment: @Michael I do appreciate that, I hope by the same token you appreciate that we can't, and don't, concern ourselves with users' deadlines/other pressures - we're only interested in the **quality** of the content that's provided, and its suitability to our mission. That's why the experts keep coming back here, because we insist questions follow a tried and tested format. It's great that you're contributing elsewhere in the ecosystem, but that wouldn't entitle you to ask off-topic questions (nor anyone else, the rules are the same for everyone) _here_. The effort you've put in to asking the...
Comment: ...question, and solving the problem yourself, is great, keep that up! But you have to admit that you've thrown a "what might be wrong?" question out there, and are hoping to incrementally update your question based on responses,eventually working your way to the root cause of the problem. I'm just saying Q+A doesn't support that, so I wouldn't personally be surprised if it gets closed (there are 2 "Too broad" close votes on it already), or if people give up engaging after a couple of increments. This site was never intended for the sort of engagement and support I think you'll need here
Comment: Please feel free to close the question then, hope you are not deleting it. Comparing it to other questions here, I would think that it is of rather high quality though (the analysis backing it I mean). If not feel free to propose any improvement. I am sure other users have similar problems and once we solve this, we will put the answer here and clean up the question. Also, if you want to or know anyone who could take this on as a paid task, please contact me at email@example.com
Comment: You misunderstand me - I'm just trying to help you understand why this might end up closed, I'm not commenting on its quality, I'm not closing it myself (or deleting it), I'm just responding to your initial confusion about bug reports being off topic, and providing a bit of commentary around how the site works at the same time. I _wish_ that every question here was as detailed and well thought out as yours, kudos for that, but I've seen it all before dozens of times. When there could be multiple, equally valid, answers to a question, it's difficult to see it staying in Q+A. Can't chat, no time
Comment: Not sure why on hold now, as I predicted the question has a definite answer, given by us. Honestly, this QA is not really working out for us.
Answer: Edit: We have a workaround, I hope this question can serve as a good practice guide of good to debug complex software like Drupal showing unexplainable errors or WSOD. Wish we had followed our own advice to not waste time on our futile attempts time.
tl;dr It was the core module Database logging 7.42    Logs and records system events to the database. which is interfering with private files in our specific setting. We disabled most modules including core, and brought them back one-by one. Database logging is reproducibly inducing the error on activation.

Don't panic and make a debugging plan, listing options of what could be checked, and then stick to it until everything has been checked. If out of options, try to shake things up
Compare your system to a vanilla system and note down what is does differently
Modules might interfere with each other in unexpected ways or with your specific configuration. That doesn't mean there is a bug in any of those modules. Boil down your system to the least complex configuration possible, remove any unneeded entry in your configuration file, disable any module that can be disabled including core modules, suspect everyone.
Check if error still present, if not re-enable all modules one-by-one, and note down which configuration change causes the error. Otherwise, start debugging going to 1.

Cheers
Comment: Hold your horses, dude. Have you really tried everything? Nope, follow your plan and everything will work out ....


Drupal Commerce | Hide or set an alias to the order number in the checkout path

Question: Is there any DC module or configuration that would allow me to set an alias for the order number that is shown on the checkout path.
i.e.
Instead of example.com/checkout/10
Something like example.com/checkout/order or just plain example.com/checkout
An alias module would have similar functionalities as the me module.
Comment: Ah, now I understand more, I missed the "me" module and it's description before. That's very different from an alias though, which is what confused me. Can a user only have one order in your system? Otherwise I don't see how this makes sense?
Comment: Couldn't path-auto solve this? I haven't investigated, but the functionality you are requesting looks just like the normal node aliases provided by path aliases.
Comment: @Letharion Path auto does not allow place-holders I am afraid.
For instance, it does not accept checkout/%
Comment: Of course it does, what else would be "auto" about it? "Everyone" uses it for node/%.
Comment: @Letharion Yes but the node/10 gets converted to blog/my-title-1 and node/11 to blog/my-title-2 and so on.

It wont work converting all the checkout/% to checkout/order.

It does not have the option, as node, taxonomy and user do, for setting checkout/[customer-name] or something.
Comment: You can never have an alias on checkout/% to checkout/order, as the system couldn't separate the different % from each other then.
There's a [path-auto fork](http://drupal.org/sandbox/damz/1332096) that seemingly makes path-auto entity agnostic, meaning you could use it on any entity, including orders. The sandbox also has a link the relevant feature request.
Comment: To be honest I didn't think it through when it comes to an unique user having more than one order. What bothered me was the fact that people can see how many orders I got in the system.
Answer: I to went that road, did not want customers to see an on each order incrementing ID in URL's. In hook_url_outbound_alter() any path can be encrypted by altering the regular expression.
/**
 * Implements hook_url_inbound_alter().
 */
function mymodule_url_inbound_alter(&$path, $original_path, $path_language) {
  // Decrypt paths that are encrypted by our hook_url_outbound_alter() to hide possible id's in paths.
  if (preg_match('#^ENC:(.+)#', $path, $m)) {
    $path = _mymodule_mcrypt('decrypt', $m[1]);
  }
}

/**
 * Implements hook_url_outbound_alter().
 */
function mymodule_url_outbound_alter(&$path, &$options, $original_path) {
  // To hide id's in paths, we encrypt them.
  if (preg_match('#^checkout/.*#', $path, $m)) {
    $path = 'ENC:' . _mymodule_mcrypt('encrypt', $path);
  }
}

/**
 * Helper function to encrypt and decrypt strings, ie. paths to hide containing id's.
 * NB: We replace forward slashes for exclamation marks, otherwise trailing
 *     slashes in the URL will be ignored by Drupal.
 */
function _mymodule_mcrypt($action, $string, $key = null) {
  if (!$key) {
    $key = $GLOBALS['drupal_hash_salt'];
  }

  $mcrypt_method = MCRYPT_RIJNDAEL_128;
  $iv_size = mcrypt_get_iv_size($mcrypt_method, MCRYPT_MODE_CBC);

  // Make key exactly as long as long as $iv_size.
  $key = substr(str_repeat($key, CEIL($iv_size / strlen($key))), 0, $iv_size);

  if ($action == 'encrypt') {
    $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
    $encrypted_string = base64_encode($iv . mcrypt_encrypt($mcrypt_method, $key, $string, MCRYPT_MODE_CBC, $iv));
    return preg_replace('#/#', '!', $encrypted_string);
  }
  elseif ($action == 'decrypt') {
    $decrypted_string = base64_decode(preg_replace('#!#', '/', $string));
    $iv = substr($decrypted_string, 0, $iv_size);
    $decrypted_string = substr($decrypted_string, $iv_size);

    return rtrim(mcrypt_decrypt($mcrypt_method, $key, $decrypted_string, MCRYPT_MODE_CBC, $iv));
  }

  return false;
}

Answer: I just realized that my goal is not feasible because the system could not distinguish orders of an unique user who has more than one order in the system.
I will encrypt the order number bit by implementing hook_url_outbound_alter() and hook_url_inbound_alter().
Answer: Hopefully there is a new Drupal module for that named Commerce_Checkout_Paths.
Comment: Cool. I will definitely try it out. Cheers.


Custom "Basic" Authentication for my WCF services. REST and RIA. Possible?

Question: My server side contains WCF4 REST services and I'm going to add RIA services for my future SL4 application.  Currently I'm doing Basic authentication like this:
var auth = HttpContext.Current.Request.Headers.GetValues("Authorization");

And so on.. You get the idea.. I call this on every request. If header not present or I can't validate UN/Password - I do this:
outgoingResponse.Headers.Add("WWW-Authenticate: Basic realm=\"Secure Area\"");

That got me by so far but I'm refactoring my server side. Implementing IoC for linked services. Created custom ServiceHost, ServiceHostFactory, InstanceProvider and all is well.
Now I need to figure how to properly handle authentication and authorization with WCF so I don't have to manually inspect headers. I do have my custom MembershipProvider so there have to be some method that get's UN/PW to process.
Any pointers? I looked at http://www.codeproject.com/KB/WCF/BasicAuthWCFRest.aspx but it uses RequestInterceptor and it is not available in WCF4. I found ServiceAuthenticationManager and ServiceAuthorizationManager but there is no samples available on how to code and wire those..
Can anybody suggest which way I should go?
Answer: Try to use this custom HTTP module. It will add new authentication mode to IIS and it will allow you using custom credentials validation.
Answer: I had all types of issues using the built-in annotations for WCF in a recent SOAP/C# project. I know this isn't the best solution, but for my purposes, I enabled basic authentication in IIS7 for my application, disabled anonymous authentication and created Active Directory users for the external clients that would call the web service endpoints. I then changed the application's permissions in IIS7 (it uses file system permissions) to allow a group containing those users.
This moves authentication outside your application, which may not be what you want, but does allow you to easily add users via the IIS7 console and deployment tools that can copy those permissions. The advantage is that you don't have to redeploy your application for permission changes. The disadvantage is you can't do fine grained permission control per function.


Advantage of using WebAPI in asp.Net MVC

Question: Advantage of using WebAPI as ProjectType over InterNet Application in asp.Net MVC?
Is any other use of WebAPI and why it's introduce in MVC4?
Answer: To name a few :

ASP.NET web api can be selfhosted outside IIS
ASP.NET web api is not specifically geared towards browsers...
ASP.NET Web api makes making a (level 2/3) RESTful webservice easier
Answer: I think that the biggest advantage WebAPI has over other solutions is the built in support for different formats such as XML , JSON, and the relative ease when adding your custom formats. Another advantage worth mentioning is the ability to support extensive OData without coding as much (can be as simple as returning IQueryable), and the support of objects.
That said, WebAPI still have scores of issues that need to be resolved, I keep getting questions from developers that find WebAPI can't resolve their methods, parameters that always result with NULL etc... so I wouldn't swear by it yet, we are all hoping to see a better version sooner rather than later.


simple python list modification

Question: thanks for taking time to answer the question. I am confused here as to why the outputs do not match.
Operation 1:
x = [[0, 0], [0, 0]]
print(type(x)) # <class 'list'>
print(x) # [[0, 0], [0, 0]]

x[0][0] = 1
print(x) # [[1, 0], [0, 0]]

Operation 2:
y = [[0] * 2] * 2
print(type(y)) # <class 'list'>
print(y) # [[0, 0], [0, 0]]

y[0][0] = 1
print(y) # [[1, 0], [1, 0]]

My understanding was that both x and y should be the same. But looks like they are not. What am I missing here?
Answer: What you're missing is that when you do this:
y = [[0] * 2] * 2

You have created a single list [0] then [0, 0].  Call this list X.  Then you created [X, X] where both X's point to the same underlying list.  So when you modify the first list the second one is modified too.
Why doesn't modifying the first element of the first list also modify the second element of each list?  Well, that's because [0] * 2 really is a list of two numbers, because a reference to 0 cannot be modified (imagine the horrors if your program's 0 meant something else!).
Comment: In the future, please consider marking the question as a duplicate, as such duplicates often contain much better, more complete answers than one poster can possibly provide in four minutes.

simple python list modification


Inequality about conditional expectation

Question: I am trying to prove the following property about conditional expectation:
Let ($\Omega, \ F,\mathbb{P} )  $ be a probability space, let  $X$ and $Y$ be two integrable random variables and let $G$ be a sub $\sigma$$- algebra$ of $\ F$. Show that if $\mathbb{E}(X \mathbb{1}_{A}) \leq \mathbb{E}(Y \mathbb{1}_{A})$ for any $\ A \in \ G$, then $\mathbb{E}(X| \ G) \leq \mathbb{E}(Y | \ G)$ a.s.
I know that I should use $\ A=\{\mathbb{E}(X| \ G)<0\}\in G $ but I don't really know how to use this.
Could someone give me a hint about how to prove this? Thanks a lot
Answer: First, in order to simplify the things, we can only consider the case where $X=0$ a.s. Indeed, if we manage to show that for each integrable random variable $Y$,  $\mathbb E\left[Y\mathbf{1}_A\right]\geqslant 0$ for all $A\in\mathcal G$ implies that $\mathbb E\left[Y\mid\mathcal G\right]\geqslant 0$ a.s., then we can apply this to $Y-X$ can conclude by linearity of the conditional expectation.
So, let $Y$ be an integrable random variable such that $\mathbb E\left[Y\mathbf{1}_A\right]\geqslant 0$ for all $A\in\mathcal G$. Let $A_n=\{\mathbb E\left[Y\mid\mathcal G\right]\leqslant -1/n\}$ where $n$ is a positive integer. We now by assumption and the fact that $A_n\in\mathcal G$ that $\mathbb E\left[Y\mathbf{1}_{A_n}\right]\geqslant 0$. Moreover, by definition of the conditional expectation, $$0\leqslant\mathbb E\left[Y\mathbf{1}_{A_n}\right]=\mathbb E\left[\mathbb E\left[Y\mid \mathcal G\right]\mathbf{1}_{A_n}\right]\leqslant -n^{-1}\mathbb P(A_n).$$ This forces $A_n$ to have probability $0$. This show that $\bigcup_{n\geqslant 1}A_n$ has probability $0$, and this set is $\{\mathbb E\left[Y\mid\mathcal G\right]\lt 0\}$.


Converter campo do banco de dados divido em vírgulas em variáveis separadas com PHP

Question: Como posso converter resultados do banco de dados que estão dentro de um campo dividido por vírgulas, em varáveis separadas independente do número de resultados contidos no campo.
Exemplo:
Tenho:
<code>$row['campo'] = 333,444,555,6666
</code>
Preciso:
<code>$var1='333';
$var2='444';

.
.
</code>
Answer: Usando a função explode();
Ex:
<code>$row['campo'] = 333,444,555,6666

$aux = explode(",", $row['campo']);

foreach($aux as $v){
  echo $v;
}
</code>
Comment: Obrigado, perfeito Fernando.