What's the purpose of AsyncContext.start(...) in Servlet 3.0?

Question: Servlet API says about "AsyncContext.start":

void start(java.lang.Runnable run)
Causes the container to dispatch a thread, possibly from a managed thread pool, to run the specified Runnable. The container may propagate appropriate contextual information to the Runnable.

From this description it's not clear how does it relate to task of optimizing thread usage when job requires waiting.
In "Servlet & JSP", Budi Kurniawan gives example of Servlet 3.0 async features, where he uses AsyncContext.start, I'll show simplified version of the example:
public void doGet(...) {
    final AsyncContext asyncContext = request.startAsync();

    asyncContext.start(new Runnable() {
        @ Override
        public void run() {
            // do some work here which involves waiting
            ...
            asyncContext.complete();
        }
    });
}

In most other examples I've met, the service method just stores the AsyncContext somewhere and it's processed somewhere else (eg. by a background thread). In this example it looks like the job is just passed to another thread, which completes the request. As I understand, now it's simply the worker thread, which wastes time on waiting.
Do you actually gain something by passing the job (which involves waiting) from one thread to another? If not, then what's the purpose of AsyncContext.start(...)?
Comment: I was wondering the same thing!
Answer: You found a poor example, IMHO. In fact I wasn't even aware of AsyncContext.start() existence.
I had a quick look at how Jetty and Tomcat implement this. In fact, they seem to have some thread pool that handles asynchronous invocations independently.
Such usage of the API gives you nothing or very little. Instead of blocking the HTTP thread you are blocking some other thread pool. So I can imagine the application still accepts new connections, but the problem remains - the container can't handle them all because that extra thread pool is still limited.
The whole points of AsyncContext is the ability to handle more than one request by a single thread. Often you need only a single thread to handle thousands of asynchronous connections - e.g. when exactly one thread waits for data that is suppose to be broadcasted to several clients. Also see The Limited Usefulness of AsyncContext.start()
Comment: That's what I suspected. Thanks!
Comment: Have you learned of any change in this implementation since you answered?
Answer: I had the same reaction at first -- if you're just passing the work to another thread, what do you gain?  The spec is not much help in explaining why this is a good idea.  But this post does an excellent job.  Basically, it's to let the server degrade gracefully under heavy load rather than just fail by running out of threads.  The actual work is done in a fixed-size pool of threads, so the server can accept any number of requests without having to keep a thread around for each one until it completes.  Of course, you may have to tweak your O/S settings to be able to keep open thousands of sockets at a time.
Once you have this ability, you can more easily take advantage of the Comet (server push) architecture, where the client Javascript keeps an AJAX request open so that the server can notify it as soon as some event occurs, rather than having to poll the server to find out if something happened.
Comment: post url broken, finding this one, and maybe it's what you mean:https://www.infoworld.com/article/2077995/java-concurrency-asynchronous-processing-support-in-servlet-3-0.html
Comment: @puppylpg Thanks, I fixed the link. The article you found is different, but also looks useful.
Answer: One reason this can be useful is when you want to release the incoming web thread, do some other work, and after done - get back to the web thread (might be another thread, but still from the web server pool) to complete the original operation and send response to the client.
For example:
1. ac = request.startAsync();
2. forward("some data", "another system"); // async outbound HTTP request
3. (at this point, incoming servlet thread is released to handle other requests)
4. (in some other, non-servlet thread, upon "forward" response arrival)
   ac.start(new Runnable() { /* send response to the client */ });

You could, of course, send response in the non-servlet thread, but this has one  disadvantage - you use non-servlet thread to do servlet-typical operations, which means you're implicitly changing the balance between amount of thread power reserved for servlet work vs. other work.
In other words - it gives you the ability to post Runnable into servlet thread pool. Obviously these are rare needs, but still - it gives some reasoning for AsyncContext.start() method.
Answer: Tomcat ThreadPoolExecutor based on java.util.concurrent.ThreadPoolExecutor and configured in Apache Tomcat 8 Configuration Reference. It handles all Tomcat request, so, if you have long running task its better to handle them in own small-size Fixed/Cached thread pool and submit task like described here.


Python distributed application architecture on constrained corporate environment

Question: This is my scenario: I developed a Python desktop application which I use to probe the status of services/DBs on the very same machine it is running on.
My need is to monitor, using my application, two "brother" Window Server 2003 hosts (Python version is 2.5 for both). One of the hosts lies in my own LAN, the other one lies in another LAN which is reachable via VPN.
The application is composed by:

A Graphical User Interface (gui.py), which provides widgets to collect user inputs and launches the...
...business-logic script (console.py), which in turn invokes slave Python scripts that check the system's services and DB usage/accounts status/ecc. The textual output of those checks is then returned back to the GUI.

I used to execute the application directly on each the two machines, but it would be great to turn it into a client/server application, so that:

users will just be supposed to run the gui.py locally
the gui.py will be supposed to communicate parameters to some server remakes of console.py which will be running on both of the Windows hosts
the servers will then execute system checks and report back the results to the client GUIs which will display them.

I thought about two possible solutions:

Create a Windows service on each of the Windows hosts, basically executing  console.py's code and waiting for incoming requests from the clients
Open SSH connections from any LAN host to the eliged Windows host and directly run console.py on it.

I am working on a corporate environment, which has some network and host constraints: many network protocols (like SSH) are filtered by our corporate firewall. Furthermore, I don't have Administration privileges onto the Windows hosts, so I can't install system services on them...this is frustrating!
I just wanted to ask if there is any other way to make gui.py and console.py communicate over the network and which I did not take into account. Does anyone have any suggestion? Please note that - if possible - I'm not going to ask ICT department to give me Administration privileges on the Windows hosts!
Thanks in advance!
Answer: Answer to myself: I found one possible solution..
I'm lucky because the console.py script is actually invoking many slave python scripts, each of them performing one single system check via standard third-party command-line tools which can be fired to check features on remote hosts.
Then, what I did was to modify the gui.py and console.py so that users can parametrically specify on which Windows host the checks must be carried out.
In this way, I can obtain a ditributed application...but I've been lucky, what if one or more of the third-party CL tools did not support remote host features checking?


Background com imagem transparente

Question: Como deixo a imagem de fundo transparente e responsiva, responsiva eu consegui com o código abaixo, mais agora preciso colocar transparecia na imagem.

CSS

body{
  background: url(../img/bg.jpg) no-repeat center center fixed;
  background-size: cover; /*Css padrão*/
  -webkit-background-size: cover; /*Css safari e chrome*/
  -moz-background-size: cover; /*Css firefox*/
  -ms-background-size: cover; /*Css IE não use mer#^@%#*/
  -o-background-size: cover; /*Css Opera*/
}

HTML

    <title>ControlHall - Telve Tecnologia</title>
    <link href="css/style.css" rel="stylesheet">

Answer: Você pode usar o filtro de opacidade no CSS:
opacity: 0.5;
filter: alpha(opacity=50); /* PARA IE8 ou superiores */

Leia mais sobre opacidade e transparência no site do W3SCHOOLS - CSS Opacity / Transparency

Background com imagem transparente


Prove polynomial map between two affine curves is bijection except origin

Question: I wanna to solve this problem dealing with a polynomial map between two affine curves.
First curve is $A \subset \mathbb{C}^2$ defined by equation $s(1+t^2)-1=0$
and the second curve is $B \subset \mathbb{C}^2$ defined by equation $(x^2+y^2)^2+3x^2y-y^3 = 0$
I have a polynomial map $f: A \rightarrow B$ defined as $f(s,t)= ( s^2t(1-3t^2), s^2(1-3t^2) )$
The problem is to prove that $f$ is surjective and also one-to-one (except the point $(0,0)$
I have no idea how to approach this. Can someone give me a little nudge what to look for? I only see that in the image of $f$ this holds $x=yt$, but I dont see how it can help. Maybe looking for inverse might be the way?
Thanks in advance
Answer: We can approach this by solving the polynomial system
$$
\left\{\begin{matrix}
x = ts^2(1-3t^2)\\
y = s^2(1-3t^2)
\end{matrix} \right.
$$
with $(x,y) \neq (0,0)$ satisfying $(x^2+y^2)^2+3x^2y-y^3=0$ and $(s,t)$ satisfying $s(1+t^2)=1$. First assume that $y\neq 0$, then $t = \frac{x}{y}$. From the equation of $A$ we see that $s= \frac{y^2}{y^2+x^2}$ (Note that the equation of $B$ implies that $x^2+y^2 \neq 0$) and you can verify that they solve the system above. Hence for each $(x,y)$ with $y\neq 0$ we have a unique point
$$
(s,t) = \left(\frac{y^2}{y^2+x^2},\frac{x}{y} \right)
$$
such that $f(s,t)=(x,y)$.
Now we turn to the case $y=0$. The equation of $B$ becomes $x^4 =0$ whence $x=0$ (we are at the origin). In this case our system becomes
$$
\left\{\begin{matrix}
0 = ts^2(1-3t^2)\\
0 = s^2(1-3t^2)
\end{matrix} \right. .
$$
The equation of $A$ says that $s \neq 0$ hence $1-3t^2 =0$. Therefore $ t = \pm \sqrt{\frac{1}{3}}$ and $s = \frac{3}{4}$ give the two possible solutions. This means that the inverse image of the origin by $f$ is composed by two points.
Comment: Thank you so much for this great write up.


Using let! inside match statements causes compilation error

Question: Is there some restriction on using let! inside match statements? I'm not sure why this won't compile.
module Foo =
  let Bar =
    async {
      let result =
        match 1 with
        | 1 ->
          let! num = async.Return 12345 // Doesn't compile
          1
        | _ -> 2

      return result
    }

Compilation fails with "This construct may only be used within computation expressions"
Answer: As already explained, the problem is that asynchronous workflows only allow certain kinds of nestings - you cannot use let! inside an ordinary expression, but only inside computation expression. The problem in your example is not really the match but the let (which contains match). To better see what's going on, the specification looks (roughly) as follows:

cexpr := let! x = expr in cexpr
             |  let x = expr in cexpr
             |  return! expr
             |  (...)

The key thing is that the argument is just an ordinary expression expr and the body following let or let! is another computation expression that can contain more asynchronous operations.
So, if you have let x = e1 in e2 then you can only have let! in e2 but not in e1.
In practice, you can do what Daniel suggests and use nested asynchronous workflow, or you can rewrite your code so that the code that needs to be asynchronous does not use waiting inside expressions where this is not possible - it is hard to say how to do this in general, but in your specific example, you can just write:
let bar = async {
  match 1 with
  | 1 ->
      let! num = async.Return 12345
      return 1
  | _ ->
      return 2 }

Answer: Calls to Bind (via let!) must appear at the top level of the computation expression. You can fix it by creating a nested async { } block:
module Foo =
  let Bar =
    async {
      let result = async {
        match 1 with
        | 1 ->
          let! num = async.Return 12345
          return 1
        | _ -> return 2
      }
      return result
    }

Comment: Probably. I was just showing the OP the minimal changes required to make it compile. I don't necessarily think it's idiomatic.
Comment: Shouldn't that be `let! result` or `return! result`?
Answer: This is tricky, because async in F# is only sort-of like async in c#. In F#, it is not a keyword, it is an instance of a Computation Expression. The bang(!) operators[let!;do!;etc!] only work in blocks of computation expressions. That is, they only work for code immediately under the curly braces. When you do a match, as you have done, you have effectively created an anonymous method which does not know anything about the computation expression.
Like c#'s await keyword, the let! operator separates code before the operator from code after the operator into separate methods. I suspect that code before the let! operator has to be able to completely unwind from the stack and that is your problem here. The "let result =" expression needs to be able to be resolved and cannot if we have a "let!" in the middle of it.
I hope that this helps.


Computing Variances by Conditioning

Question: I have trouble with the first part of this problem (Please take a look at the image below). This is an example problem from my old textbook years ago and I have had trouble understanding:

How Y is useful in solving the total variance?
Why E[X|Y] is a random variable, and how its values are obtained.
Why in calculating var(E[X|Y]), mean of E[X|Y] is used, instead of var(E[X|Y)) = E[(square of X)|Y] - (square of (E[X|Y]))?
Comment: $E(X\mid Y)=g(Y)$ (say) is a random variable whose distribution is given. Then they calculate its variance $V(E(X\mid Y))=V(g(Y))=E[g(Y)-E(g(Y))]^2$.
Answer: This problem is from Bertsekas by the way; and to be precise since the limits are not shown in the image:
$$f_X(x)=\begin{cases}1/2, & 0\leq x < 1 \\ 1/4, & 1\leq x < 3 \\ 0, & \text{o/w}\end{cases}$$
First of all if you're OK with the statement in the solution that $E[X|Y]$ takes values $2$ and $1/2$ with probability $1/2$, then you're left with a new random variable, $Z=E[X|Y]$, where you're asked the variance of it, $\operatorname{var}(Z)$, in which you can execute the standard way of calculating the variance, as also pointed out by @StubbornAtom in the comments.
Let's derive $E[X|Y]$. First of all, it is a function of $Y$, and there are two cases at most because we have only two $Y$ values. So, we'll calculate $E[X|Y=1]$ and $E[X|Y=2]$. We can analytically find $f_{X|Y=1}(x)$ and find the expectation, but a simpler approach would be using the given plot. If $Y$ is $1$, then $X$ is uniform in $[0,1]$, which gives $E[X|Y=1]=1/2$. If $Y=2$, $X$ is uniform in $[1,3]$, which gives $E[X|Y=2]=2$.
Edit: After you added your bullet points:
1) PDF of $X$ is not in any standard form, e.g. uniform, exponential, normal etc. But, when we condition on $Y$, it's partitioned into two simpler (i.e. uniform PDFs) pieces: $f_{X|Y=1}(x)$ and $f_{X|Y=2}(x)$. We can directly use uniform PDF's pre-calculated statistics. You first need to understand that these two PDFs are uniform as a checkpoint.
2) $E[X|Y]$ is a random variable because it depends on $Y$. It doesn't depend on $X$, because $x$ is integrated out: $$E[X|Y]=\int_{\mathcal{X}} xf_{X|Y}(x)dx$$
Similarly, $E[X]$ is constant, $E[X|Y,Z,T]$ depends on $Y,Z,T$ etc.
3) Typical definition of variance is $\operatorname{var}(Z)=E[(Z-E[Z])^2]$; and here $Z=E[X|Y]$. Also, in your definition, you're confusing $\operatorname{var}(E[X|Y])$ with $\operatorname{var}(X|Y)$:
$$\operatorname{var}(E[X|Y])\neq E[X^2|Y]-E[X|Y]^2 = \operatorname{var}(X|Y)$$
Comment: Thank you for clarifying further. So, the value of E[Z] is the sum of[ (probability of each interval) X ( the value of Z in each interval)] . Is my understanding correct?
Comment: Yes, because `probability of each interval` is the `probability of Z in that interval`, e.g. $P(X\in [0,1])=P(Z=1/2)$. For another view, $E[Z]=E[E[X|Y]]=E[X]=5/4$, from the law of iterated expectations.
Comment: Thanks a lot for clarifying the details! I got everything now.
Comment: In general, $E[X^2|Y]$ is the expected value of $X^2$ when we know $Y$. And, $var(X|Y)$ is the variance of $X$ when we know $Y$.
Comment: I am first time asking question. Please explain how to accept/upvote the answer. Thanks. (I logged in using Facebook login but I got a message saying I cannot vote for my own question...)
Comment: Click on the tick below the answer to accept it. But, I think you won't be able to upvote it till you're 15 rep.
Comment: I kind of understand why E[X|Y=1]=1/2. That is the value of fx(X) in [0,1], but please explain this part in more detail: "If =2,  is uniform in [1,3], which gives [|=2]=2.". This is one of the place I get stuck. How do you get that '2' while fx(x) is 1/4?
Comment: $E[X|Y=1]$ is not the value of $f(x)$ in $[0,1]$. It's actually $(0+1)/2=1/2$, because $X$ is uniform in the interval $[0,1]$. Similarly, when $Y=2$, $X$ is uniform in $[1,3]$, which means an expectation of $(1+3)/2=2$.
Comment: Thank you for your points 1 and 2, and now I understand better.
Comment: Ok, I also understand that I have been confused between the definitions of var(E[X|Y]) and var(X|Y)。Then, my remaining question is why var(Z) was obtained using the mean of E[X|Y] (or mean of Z) instead the definition you pointed out? Where is that formula author used coming from? It is obviously different
Comment: It's using the standard formula of variance, which I also quoted: $\operatorname{var}(Z)=E[(Z-E[Z])^2]$. This means we subtract the mean from each value, square and average them.

Computing Variances by Conditioning


AngularJS directive scope variable doesnt update after reopening the window

Question: This question might seem as if it was asked before but I can't find solution anywhere.
I have directive to which i pass array
<code>    <div modal-panel
     array="ctrl.array" >
    </div>
</code>
and i get it in scope
<code>       scope: {
            array: '=',
        },
</code>
It works all good, updates, etc until I close the form and open it once again.
It just doesn't update.
I tried logging the contents of an array to console and it is just the old array from the time i first opened the form containing that directive. I tired doing things like
<code> $scope.$on('$destroy', () => {
    $scope.array = null
 });
</code>
but it just doesnt work. Any ideas appreciated
edit
I found that the problem exists only in callback that i have to check all checkboxes in ng-table containing that array.
Is there a way to update data in a callback when this happens?
Answer: I found the problem.
The directive was'nt rebuilt cause of my spa app and list of callbacks wasn't updated so there was one callback with old reference. I just deleted old callback and added new with actual reference.


File gets downloaded from app_data folder, but in the corrupted format

Question: My web application stores files (.png, .bmp, .jpg, .jpeg, .jpe, .jfif, .gif, .tif, .tiff, .doc, .docx, .pdf, .xls, .xlsx) in the app_data/upload folder. It gets stored on live server as it is on the local system. But when trying to download, it gets downloaded with the same file size but in the corrupted format.
Here is the code that downloads the file from the live server.
<code>string strURL = "~/App_Data/Upload/" + fileRepository.FileName;
WebClient req = new WebClient();
HttpResponse response = HttpContext.Current.Response;
response.Clear();
response.ClearContent();
response.ClearHeaders();
response.Buffer = true;
response.ContentType = "application/octet-stream";
response.AppendHeader("Content-Disposition", "attachment;filename=\"" + fileRepository.FileName + "\"");
byte[] data = req.DownloadData(Server.MapPath(strURL));
response.BinaryWrite(data);
response.TransmitFile(Server.MapPath(strURL));
FileRespository.DownloadCount(Convert.ToString(_fileID));
response.End();
</code>
Kindly find an image attached when word file is downloaded.
Please help me out.
Answer: Read the file as a blocks/buffers instead of transmit file.


Election: probability of A is in the lead from the first vote on

Question: I was trying to solve the following problem:
In an election, candidate A receives n votes and candidate B receives m votes, where n > m. Assume that in the count of the votes all possible orderings of the n + m votes are equally likely. Let $P_{n, m}$ denote the probability that from the first vote on A is always in the lead. Find
(a - i) $P_{2, 1}$, $P_{3, 1}$, $P_{n, 1}$, $P_{3, 2}$, $P_{4, 2}$, $P_{n, 2}$, $P_{4, 3}$, $P_{5, 3}$, $P_{5, 4}$
(j) Make a conjecture as to the value of $P_{n, m}$.
I solved all parts and my conjecture was that $P_{n, m} = \frac{n - m}{n + m}$ which I sort of verified with a small app I wrote to check my solutions (JavaScript: https://repl.it/EWNM/35).
While I was working on the exercises (a - i) I kept coming up with the formula $P_{n, m} = x * \frac{n!m!}{(n+m)!}$. The $\frac{n!m!}{(n + m)!}$ part is the probability of any one of the outcomes happening. The $x$ would be the number of outcomes where A leads from the first vote on. I was trying to come up with the formula for $x$ even before reaching part (j) but I could not. After figuring out the probability $P_{n, m} = \frac{n - m}{n + m}$, I could solve for $x$ and got $x = \frac{(n - m)(n + m - 1)!}{n!m!}$.
How could I have come up with $x$ without knowing $P_{n, m} = \frac{n - m}{n + m}$?
So, instead of thinking about probabilities, how many different orderings of A and B is possible where the number of A's at any position is more then the number of B's?
Is there some kind of general formula or way of thinking about this kind of problems? What would be the solution for A always leading by 2, 3, ..., i?
Thanks,
Norbert
Comment: https://en.wikipedia.org/wiki/Bertrand%27s_ballot_theorem
Comment: Thanks Micah! I don't have the solutions for this problem and it's nice to have a proof. I looked at Bertrand's proof but I don't understand it. I don't understand how he proved that there are equal number of sequences that end in a tie and begin with A or B and I also don't understand how he converts the unfavourable orders into favourable ones. Could you explain this in a bit more details?
Answer: Here's a more detailed account of the reflection argument than the one in the Wikipedia article. Let me know if there's any part of it that you still want me to expand on.
Let's consider all possible sequences of ballots. The idea of the proof is to divide them into three categories:

Sequences where $A$ is always ahead
Sequences where $A$ starts out ahead (i.e., gets the first vote), but $B$ catches up at some point
Sequences where $B$ starts out ahead

For concreteness, let's say $n=3$, $m=2$.  Then the categories split up like this:

AABAB, AAABB
AABBA (B catches up after ballot #4), ABAAB (B catches up after ballot #2), ABABA (B catches up after ballot #2), ABBAA (B catches up after ballot #2)
BAAAB, BAABA, BABAA, BBAAA

Notice that category 2 and category 3 are the same size. This is not a coincidence! The "reflection" idea is to pair off sequences from category 2 with sequences from category 3.
To do this, we first comment that for any sequence in either category, the count will be exactly tied at some point. For category 2 sequences, this is by definition; if $B$ has caught up to $A$, then $A$ and $B$ are tied. For category 3 sequences, it's because $B$ starts out ahead, but $A$ must eventually win. So at some point before winning, $A$ must catch up to $B$ and they will both be tied.
For concreteness, let's focus on the last time each of these sequences is tied. In our example set, I'll write a | to indicate this point. So the two categories are:

AABB|A, AB|AAB, ABAB|A, ABBA|A
BA|AAB, BAAB|A, BABA|A, BBAA|A

Next, we'll look at what happens if we flip all the votes before a |. For example, AABB|A would flip into BBAA|A. Notice that:

We can always do this and get another valid ballot sequence — because the | denotes a point where the count is tied, flipping all the votes doesn't change the final total.
This takes sequences from category 2 (which start with an A) to sequences in category 3 (which start with a B), and vice versa.
If you do it twice, you get back to the sequence you started with.

This means it gives a way of pairing off sequences from category 2 with sequences from category 3, just as we wanted. In our specific example, this pairing is:

AABB|A <=> BBAA|A
AB|AAB <=> BA|AAB
ABAB|A <=> BABA|A
ABBA|A <=> BAAB|A

Now, we're almost done. We just need one more observation: category 3 just consists of sequences which start with a B. Since $m$ out of $n+m$ ballots are $B$ ballots, that means the probability that you end up in category 3 is $\frac{m}{n+m}$. But category 2 is the same size as category 3! Since all ballot sequences are equally likely, that means the probability that you end up in category 2 is also $\frac{m}{n+m}$. So the probability that you end up in category 1 is
$$
1-2\frac{m}{n+m}=\frac{n+m-2m}{n+m}=\frac{n-m}{n+m}
$$
just as you conjectured.
Comment: Great, I get the proof after reading this. The article still doesn't make sense as they convert AABBABAA to ABAAAAB which doesn't even have the same length, but using your explanation I get the proof. The part in the article which explains what happens when ties are allowed is what I am looking for because that discusses how to come up with the number of favourable outcomes if A has to lead by k. In that proof, I don't understand two things: if k = 0 (it can tie), then the points start from (-1, 1) but why is it ${p+q \choose q-1}$ and I don't see if all paths are covered either.
Comment: @norbertk the wikipedia article is a bit poorly written in regards to Andre's solution to the problem. The sequence AABBABAA actually corresponds as follows. Find the first B that causes an issue and split on that: AAB B ABAA. Take the B and place it at the start of the sequence: B AAB ABAA. Then Swap the positions of the other two parts: B ABAA AAB. Yielding the sequence BABAAAAB. In the article, for some reason, they leave out the starting B. The proof that this is a 1-to-1 with the sequences that begin with a B is that the process is uniquely invertable.


Possible Flaw in taking derivatives in a limit

Question: I was calculating some limits involving trigonometric functions, but I was stuck in the following limit for a while : $$\lim_{x\to 0} \frac {-\cos^2 x - \cos x + 2 }{x.\sin x} $$
I evaluated it as below:
$$\begin{align} & \lim_{x\to 0} \frac {-\cos^2 x - \cos x + 2 }{x.\sin x}\\
&= \lim_{x\to 0} \frac {\frac {-\cos^2 x - cos x + 2}{x} }{\sin x}\\
&= \lim_{x\to 0} \frac {\frac {\left(-\cos^2 x - \cos x + 2\right) - \left(-\cos^2 0 - \cos 0 + 2\right)}{x - 0} }{\sin x}\\
&= \lim_{x\to 0} \frac {\frac {d}{dx}\left(-\cos^2 x - \cos x + 2\right)  }{\sin x}\\
&= \lim_{x\to 0} \frac {2 \cos x . \sin x + \sin x }{\sin x}\\
&= \lim_{x\to 0} {2 \cos x + 1}\\
&= 3\end {align}$$
But  the correct answer is actually$$\frac 32$$ so I want to know what is the flaw in my work, and is it possible in general to use this trick.. (my exemple may be just an exception).
Comment: Why exactly did you replace $$\lim_{x\to 0} \frac{\frac{f(x)-f(0)}{x-0}}{g(x)}$$ by  $$\lim_{x\to 0} \frac{f'(x)}{g(x)}$$ in the third step? (Why do you think this is correct?)
Comment: In the very first line, I must be missing something: Doesn't the numerator evaluate to $4$ at $x = 0$?
Comment: is $x.\sin x$ supposed to be $x\sin x$?
Comment: @BrianTung You're right, I expect this should be +2.
Comment: There must be a typo. Perhaps you mean the numerator to end with $+2$ instead of $-2$.
Comment: My bad, the function is -cos^2(x) -cos(x)+2
Comment: Yeah we usually use '.' as '×'
Comment: You have done a replacement which is not justified by any rule/theorem. Remember that in mathematics you can replace $A$ by $B$ only when $A = B$ and not otherwise. You are trying to replace a difference quotient by a derivative and these are normally not equal (unless the function is linear).
Answer: In short: you cannot say
$$
\lim_{x\to 0} \frac{\frac{f(x)-f(0)}{x-0}}{g(x)} =
\lim_{x\to 0} \frac{f'(x)}{g(x)}
$$
which is what you used in your third step. This is simply not true in general.

To see this on a simpler example, take e.g. $f$ defined by $f(x)=x^2$ and $g(x)=x$.
Then
$$
\lim_{x\to 0} \frac{\frac{f(x)-f(0)}{x-0}}{g(x)} =
\lim_{x\to 0} \frac{\frac{x^2}{x}}{x}
\lim_{x\to 0} 1 = 1
$$
while
$$
\lim_{x\to 0} \frac{f'(x)}{g(x)} = \lim_{x\to 0} \frac{2x}{x} = 2.
$$
Comment: Well thanks for the answer, this derivative thing doesn't work then at all
Answer: If the limits exist and the denominator is nonzero, then
$$ \lim_{x \to a} \frac{ \frac{f(x) - f(a)}{x-a} }{g(x) }
= \frac{\lim_{x \to a} \frac{f(x) - f(a)}{x-a}}{\lim_{x \to a} g(x)} $$
and so you could conclude
$$ \lim_{x \to a} \frac{ \frac{f(x) - f(a)}{x-a} }{g(x) } = \frac{f'(a)} {\lim_{x \to a} g(x)}$$
But you are not in that situation, and that's not what you tried to conclude either.
Comment: Thanks for the answer, I wanted to use something similar to l'Hoptial's rule but it's clear that it is wrong
Answer: You cannot just replace the tangent formula by the derivative ; doing so would mean that you are actually taking the limit when x -> 0, but in that case, you must also divide by $sin(0)$, which you cannot do obviously.
What you should do here is use equivalent functions, namely the following :
$sin(x) \underset{x \rightarrow 0}{=}x + o(x^2)$
$cos(x) \underset{x \rightarrow 0}{=}1 - \frac{x^2}{2} + o(x^3)$
Where $o(x^n)$ is a term that represents negligeable values. Technically speaking, $o(x^n)$ is a non-zero function $g$ so that $\frac{g(x)}{x^n} \underset{x \rightarrow 0}{\rightarrow} 0$. When replacing functions in products or divisions by their equivalents, you can ignore the $o(x^n)$ term, but not when replacing functions in sums or differences. For example, this is true :
$\frac{sin(x)cos(x)}{x} \underset{x \rightarrow 0}{=} \frac{x \times cos(x)}{x} = cos(x) \underset{x \rightarrow 0}{\rightarrow} 1$
But this is false :
$(1 + \frac{1}{n})^n \underset{n \rightarrow \infty}{=} (1 + 0)^n = 1$
In your case, just don't forget to include the negligeable terms when replacing terms of the sum with equivalent functions, and you should be good - remember than squaring is doing a product.
Comment: Yeah now I get it clearly, thanks  for the  detailed answer


How do I use twig templates with views?

Question: I'm trying to figure out how to use twig templates with views. at the moment I'm just using twig in the view itself but I'm sure I can use twig files to overwrite the styling of the view.
e.g.

        {{ field_category }}
        {{ title }}

I'm using this in the rewrite field of the block view with one field hidden.
How can I translate this to a twig file?

Edit1; I'll try to explain my issue in more detail. I've been working with the page.html.twig file which overwrites the default homepage used by Drupal. I'm wondering if I can do the same with blockviews. Can I overwrite the default layout, meaning html layout, divs, classes, ID's using a Html.twig file for the view?
Answer: You can overwrite views-view-fields.html.twig or create your personal views-view-fields--YourViewName.html.twig and apply the div or any wrapper you want.
I advise you to activate the twig debug to follow the suggestions
Comment: Does it automatically detect the template or do you have to apply it to the view?
Comment: I think it's automatically, beacause these are standards, to make sure enable the twig debug
Answer: To create custom template for view create a file called  views-view-fields--view_name--page/block.html.twig. Save this file in your theme's template directory.
In this file define your html structure and specify the fields you want to display in your view like {{ fields.field_name.content }}.
It is mandatory that the fields your specifying in template file must be added to view through admin view, otherwise it will not be displayed in custom view template.
Once your template file is saved clear the cache to take effect the changes.
Answer: https://www.drupal.org/project/drupal/issues/2118743 causes missing file name suggestions when using views as blocks.
To style them, you have to know the pattern, and contrary to what would seem obvious, you don't need to create a template for a block, but for a view.
It is
views-view--<view-name-goes-here>.html.twig in <theme>/templates/views

How do I use twig templates with views?


problemas com fpdf no cakephp

Question: Quando vou criar uma nova classe PDF estendendo-a para o FPDF para reescrever os métodos Header,Footer, etc... Me aparece esse seguinte erro, já pesquisei mas não consegui resolver..
esse é o meu método privado no controller:
http://hastebin.com/eqenexequd.coffee
e o erro que aparece é esse:
Class declarations may not be nested
Comment: O erro quer dizer que tem uma classe dentro do outro. Pode postar seu código de classe? Pode ser que realmente tem um classe dentro do outro, ou pode ser que é simplesmente um erro tipográfica.
Answer: Você está carregando o vendor de forma correta ?.
O  vendor segue as convenções do cakephp ?.
<code>App::import('Vendor', 'SomeName', array('file' => 'some.name.php'));
</code>
Veja a sessão: Loading Vendors em: http://book.cakephp.org/2.0/en/core-utility-libraries/app.html

problemas com fpdf no cakephp


What does the P-value tell me in this case?

Question: I've made a mosaic plot in R - I know that the colors suggest the deviance from the expected value. But how do I explain the P-value? That the deviance is not due to chance?
Comment: I'm voting to close this question because of mixed reasons. Basically it seems to ask for interpretation of the 'p-value' (which many resources already explain, also on this website, so it is a bit **duplicate**), and it has a lot of vague introduction/context about mosaic which is not very well explained (**unclear**). also it is a bit about a software implementation of statistics rather than statistics itself (**of-topic**).
Comment: The documentation should explain which statistical test is used.
Comment: Are you talking about the documentation of the mosaic plot function? Because that still does not get me anywhere...
Comment: I don't know what it means to close a question, but this question seems to ask about the connection between visual display and p-value...a question I receive from my students in many different, but related, forms.
Answer: The plot is providing a graphical representation of the chi-square test for independence. (In the 2x2 context, the same test as asking if two groups have the same proportion.) The null hypothesis is that $H_0$: $\pi_1=\pi_2$. Thus, the $P$-value you found indicates the distance between your observed percentages for the two groups is unlikely due to chance if the population percents are equal.
Comment: Some more information: https://towardsdatascience.com/mosaic-plot-and-chi-square-test-c41b1a527ce4


Organic Groups - Include nodes as part if it on group creation

Question: I'm looking for at way to make some nodes, eg. "About us", part of the Organic Group.
<code>/
/about-us*
/more-general-stuff
</code>
When I create the OG I want the nodes marked with * to be part of the group.
<code>/my-group
/my-group/about-us
/my-group/another-page-for-the-group
</code>
/my-group/about-us is a copy of /about-us, and if you edit /about-us it also updates /my-group/about-us.
/my-group/about-us could contain blocks specific for the group.
So when I tried to use views to create a page on /%/about-us, I'm not able to put blocks on that "page".
Any ideas is welcome.
Comment: I ended up using relations for this, I create on "referral node" that via a relation fetches the data form the main node.
Answer: You can use Rules to generate the nodes upon creation of the group.  If you haven't worked with Rules it is an incredibly powerful module and is well worth the time investment to learn its intricacies.


Nginx: protect directory and files

Question: I wrote this to prevent the directory "download" to be accessed but from the IP 126.96.36.199.
location ~ /folder/download {
    allow 188.8.131.52;
    deny all;
    return 403;
}

However, the directory "folder" is being blocked as well and I did not wanted this.
What am I doing wrong?
UPDATE:
Here it goes all the real config:
server {
    server_name www.domain.com;
    rewrite ^ $scheme://domain.com$request_uri? permanent;
}

server {
    server_name atpc.info;

    access_log /var/log/nginx/atpc.info.access;
    error_log /var/log/nginx/atpc.info.error;

    root /var/www/atpc.info;

    location ^~ folder/download {
            allow 188.8.131.52;
            deny all;
    }

    location ^~ folder/includes {
            allow 22.214.171.124;
            deny all;
    }

    location ^~ folder/mythings {
            allow 126.96.36.199;
            deny all;
    }

    location ^~ folder/functions {
            allow 220.127.116.11;
            deny all;
    }

    location / { index index.htm index.php; }

    location ~ .php$ {
            fastcgi_pass 127.0.0.1:9000;
            fastcgi_index index.php;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            include /etc/nginx/fastcgi_params;
    }

    location = /favicon.ico {
            return 204;
            access_log off;
            log_not_found off;
    }

    location = /robots.txt { allow all; log_not_found off; access_log off; }
    location ~ /\. { deny all; access_log off; log_not_found off; }
}

Thanks.
Comment: Your config looks fine. Is there any other `location` related to `folder`? Could you please post the full config?
Comment: I updated the question.
Answer: You probably want location ^~ instead of location ~, as the former is a prefix match that doesn't allow regex overrides, and the latter is a regex location.  Also, remove the return 403;  The allow and deny directives are sufficient for your application, and the return will always be evaluated, which means everyone will get a 403.
Comment: /f/f is a prefix of /f/form.js, so location ^~ /f/f blocks it.  What about that isn't working?  If all those are supposed to be dirs, then maybe you need to add slashes at the end of each one.  location ^~ /f/f/ { ... }
Comment: Sorry, but it's not working...
Comment: I updated the question.

Nginx: protect directory and files


Getting the current position of a list element

Question: I was wondering if there is a way find out where the list position x is at in a function?
hep list = [if x=="you" then "u" else if x=="are" then "r" else x | x <- list]

Something like:
hep list = [if x=="by" && elemAt(x+1)=="the" && elemAt(x+2)=="way" then "btw" else if x=="are" then "r" else x | x <- list]

Answer: You probably don't want to solve your problem this way (indexing into linked lists being an algorithm smell and all), but if you really need indices you can get them by zipping against a list of indices:
zip [0..] some_list

Then, as you traverse this new list, you will get pairs instead of single elements.  The first element of each pair will be the index that you want, the second element will be the item.
Or perhaps you are asking what function you use to go the other way (to get the element at some index)?  For that you use !!:
some_list !! 5

Comment: Thanks for the reply. I appreciate the suggestion, however, this is not what I was looking for, thanks anyways though.
Comment: @MHZ how is this not what you're looking for?  Details.
Comment: How is it? Explain. You did not really explain how it can be applied to my problem, you just showed me how to use zip, which I already know how to do :D
Comment: @MHZ He told you how to get the index by using `zip`, which is what you asked.
Answer: You can get the index by zipping the given list with [0..], but accessing list items by index is neither an idiomatic nor an efficient way to do what you want to do.
A better solution would be to use recursion and pattern matching to iterate over the list, taking multiple elements at once.
Comment: @MHZ You pattern match to see whether the first elements of the list are any of the word combinations you're looking for and then you recurse on the remaining elements.
Comment: How would recursion be used to take multiple elements at once, in this case?
Answer: To expand on sepp2k's answer, you could try something like this:
hep ("by" : "the" : "way" : rest) = "btw" : hep rest
hep ("are" : rest)                = "r"   : hep rest
hep (yadda : rest)                = yadda : hep rest
hep []                            = []

Comment: Thanks for the reply. I am not familiar with this syntax, can you please explain what it is your code does?
Comment: Everything to the left of the equals signs is [pattern matching](http://learnyouahaskell.com/syntax-in-functions); to the right I build the list using [the cons operator and the empty list](http://learnyouahaskell.com/starting-out#an-intro-to-lists). (Sorry I am not able to link to precisely the parts of the pages I wish to: you will need to read down a little.)


Make a custom block to render a published content

Question: Is there way to make a custom block displays a list of published contents?
I tried...

Create a new block type with just one field of type Reference->content.
Create a new block with recently created type.
Configure visibility -> type of content to a particular type of content on this recently created block.
Place block in block layout.
Publish a new content.

But at the end nothing is rendered on my page.
Drupal 8 question.
Comment: It might make more sense to create that block as a VIew. It'll be more configurable that way
Comment: I agree with Clive. This is what the Views module is made to do.
Comment: Thanks for replay, I'm new in Drupal and getting the "drupal way of thinking " yet. Any advices are welcome.
Answer: The easier way to achieve this problem is by creating a view block. That only show the content that is been published. Then you going to add that view block on any region that you wish.
Here is the code for a export view block that only show content that have been published.
<code>uuid: 36b6dd0f-8a30-4d08-a718-24afe8b4cfc0
langcode: en
status: true
dependencies:
  module:
    - node
    - user
id: content_published
label: 'Content Published'
module: views
description: ''
tag: ''
base_table: node_field_data
base_field: nid
core: 8.x
display:
  default:
    display_plugin: default
    id: default
    display_title: Master
    position: 0
    display_options:
      access:
        type: perm
        options:
          perm: 'access content'
      cache:
        type: tag
        options: {  }
      query:
        type: views_query
        options:
          disable_sql_rewrite: false
          distinct: false
          replica: false
          query_comment: ''
          query_tags: {  }
      exposed_form:
        type: basic
        options:
          submit_button: Apply
          reset_button: false
          reset_button_label: Reset
          exposed_sorts_label: 'Sort by'
          expose_sort_order: true
          sort_asc_label: Asc
          sort_desc_label: Desc
      pager:
        type: some
        options:
          items_per_page: 5
          offset: 0
      style:
        type: default
      row:
        type: fields
      fields:
        title:
          id: title
          table: node_field_data
          field: title
          settings:
            link_to_entity: true
          plugin_id: field
          relationship: none
          group_type: group
          admin_label: ''
          label: ''
          exclude: false
          alter:
            alter_text: false
            text: ''
            make_link: false
            path: ''
            absolute: false
            external: false
            replace_spaces: false
            path_case: none
            trim_whitespace: false
            alt: ''
            rel: ''
            link_class: ''
            prefix: ''
            suffix: ''
            target: ''
            nl2br: false
            max_length: 0
            word_boundary: true
            ellipsis: true
            more_link: false
            more_link_text: ''
            more_link_path: ''
            strip_tags: false
            trim: false
            preserve_tags: ''
            html: false
          element_type: ''
          element_class: ''
          element_label_type: ''
          element_label_class: ''
          element_label_colon: true
          element_wrapper_type: ''
          element_wrapper_class: ''
          element_default_classes: true
          empty: ''
          hide_empty: false
          empty_zero: false
          hide_alter_empty: true
          click_sort_column: value
          type: string
          group_column: value
          group_columns: {  }
          group_rows: true
          delta_limit: 0
          delta_offset: 0
          delta_reversed: false
          delta_first_last: false
          multi_type: separator
          separator: ', '
          field_api_classes: false
      filters:
        status:
          value: true
          table: node_field_data
          field: status
          plugin_id: boolean
          entity_type: node
          entity_field: status
          id: status
          expose:
            operator: ''
          group: 1
      sorts:
        created:
          id: created
          table: node_field_data
          field: created
          order: DESC
          entity_type: node
          entity_field: created
          plugin_id: date
          relationship: none
          group_type: group
          admin_label: ''
          exposed: false
          expose:
            label: ''
          granularity: second
      title: 'Content Published'
      header: {  }
      footer: {  }
      empty: {  }
      relationships: {  }
      arguments: {  }
      display_extenders: {  }
    cache_metadata:
      max-age: -1
      contexts:
        - 'languages:language_content'
        - 'languages:language_interface'
        - 'user.node_grants:view'
        - user.permissions
      tags: {  }
  block_1:
    display_plugin: block
    id: block_1
    display_title: Block
    position: 1
    display_options:
      display_extenders: {  }
    cache_metadata:
      max-age: -1
      contexts:
        - 'languages:language_content'
        - 'languages:language_interface'
        - 'user.node_grants:view'
        - user.permissions
      tags: {  }
</code>


Check that Goldbach Conjecture holds for every even number between 900 and 1000

Question: Like in the title, I have to check that Goldbach Conjecture holds for every even number between 900 and 1000.
It's worth to note that I'm not supposed to use computer, so writing e.g. Python code will not do the trick.
Only idea that's coming to my mind is to check every number manually, but it looks very inefficient and like a kind of non-sens.
Is there any better way to do that? (I doubt it to be honest, but hopes I'm wrong)
Comment: I'd go in the opposite direction, try a sieve like method.  Noting that $907$ is prime, you can handle $907+3, 907+5, 907+7, 907+11, \cdots$.    That's a lot of cases!    Likewise, $887$ is prime so you can get $887+13, 887+17,\cdots$.    A couple of things like that and you should be down to a small number of sporadic cases.
Comment: I don't think there's a better way. It's not completely infeasible to do it by hand, but it's a pain. Could take an hour depending on your calculation skills. Start by listing out the primes up to 1000, then find the pairs.
Comment: To save time, you'll want to look either for representations where one prime is quite small or representations where both primes are close to 500. Either way, you'll need either a list of primes near 1000 or a list of primes near 500; if you really must do that by hand, that's almost as much as finding the entire list of primes up to 1000 anyway (sieve of Eratosthenes).
Comment: There are only $50$ numbers to check.  Make a list of them.  If you have a list of primes it will go quickly.  I started down from $900$ and the first prime I came to is $887$.  Given that, we can mark off $900,904,906,910,916$ and so on.  This will get $20$ of the $50$ off your list.
Answer: Let $p_1$ be the largest prime less than $900$.  $p_1 = 887$.  Let $Q_1$ be the list of all the (odd) primes between $900- p_1$ and $1000 - p_1$
$$  13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113  $$
and record which even numbers in $[900,1000]$ are covered by elements of $p_1 + Q_1$.
$$ (p_1 + Q_1)\cap [900,1000] = 900, 904, 906, 910, 916, 918, 924, 928, 930, 934, 940, 946, 948, 954, 958, 960, 966, 970, 976, 984, 988, 990, 994, 996, 1000  \text{.}  $$
That's one quarter of the problem solved.  Now we only need to find representations for a subset of $[902,998]$.
Now let $p_2$ be the largest prime less than $p_1$.  $p_2 = 883$.  Let $Q_2$ be the list of all the (odd) primes between $902 - p_2$ and $998 - p_2$
$$  19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113  $$
and record which even numbers in $[900,1000]$ are covered by elements of $p_2 + Q_2$.
$$ (p_2 + Q_2)\cap [900,1000] = 902^*, 906, 912^*, 914^*, 920^*, 924, 926^*, 930, 936^*, 942^*, 944^*, 950^*, 954, 956^*, 962^*, 966, 972^*, 980^*, 984, 986^*, 990, 992^*, 996  \text{,}  $$
where we mark by asterisks those numbers not previously covered.  This is 16 more, so we are 41% finished.
Continue until you have covered everything, although covering the last few cases can take a while.  You might occasionally switch to directly trying to cover particular unresolved even numbers in the interval.  (Happily, the following process can be stopped and continued easily.)

Let's suppose one of these few remaining numbers is $998$.  Now, search through the pairs $(499-2k, 499+2k)$, iterating $k$, starting at $0$, until you find a pair of primes.  In this case, we stop immediately; $499$ is prime.
Let's suppose one of these few remaining numbers is $908$.  Now search through the pairs $(454-1-2k, 454+1+2k)$, iterating $k$, starting at $0$, until you find a pair of primes.  This process stops at the pair $(421, 487)$.
Answer: I cheated, but you could do this by hand easily enough. Make up $2$ sieve tables, one from $0$ to $79$ and the other from $870$ to $1009$. Going through the first table staring from $3$, replace all of its odd multiples in both tables with the current prime. Then the next odd number in the first table which hasn't been replaced is prime, so replace all of its odd multiples and so on until a pass through the first table has been completed.
At this point you know all the primes in both tables. Then in the second (and optionally also the first) table subtract all primes in the first table from each even number and when the difference is a prime visible in the table, replace the current number with the first prime in the first table for which this was the case.
When you are done you should have $4$ classes of numbers: odd primes, smallest divisors of odd numbers, smallest prime which is the difference between the current number and any odd prime in the tables, and the rest. The !@#\$%^&* number here turns out to be $992$.
$$\begin{array}{cccccccccc}
0&1&2&\color{green}{3}&4&\color{green}{5}&\color{blue}{3}&\color{green}{7}&\color{blue}{3}&\color{red}{3}\\
\color{blue}{3}&\color{green}{11}&\color{blue}{5}&\color{green}{13}&\color{blue}{3}&\color{red}{3}&\color{blue}{3}&\color{green}{17}&\color{blue}{5}&\color{green}{19}\\
\color{blue}{3}&\color{red}{3}&\color{blue}{3}&\color{green}{23}&\color{blue}{5}&\color{red}{5}&\color{blue}{3}&\color{red}{3}&\color{blue}{5}&\color{green}{29}\\
\color{blue}{7}&\color{green}{31}&\color{blue}{3}&\color{red}{3}&\color{blue}{3}&\color{red}{5}&\color{blue}{5}&\color{green}{37}&\color{blue}{7}&\color{red}{3}\\
\color{blue}{3}&\color{green}{41}&\color{blue}{5}&\color{green}{43}&\color{blue}{3}&\color{red}{3}&\color{blue}{3}&\color{green}{47}&\color{blue}{5}&\color{red}{7}\\
\color{blue}{3}&\color{red}{3}&\color{blue}{5}&\color{green}{53}&\color{blue}{7}&\color{red}{5}&\color{blue}{3}&\color{red}{3}&\color{blue}{5}&\color{green}{59}\\
\color{blue}{7}&\color{green}{61}&\color{blue}{3}&\color{red}{3}&\color{blue}{3}&\color{red}{5}&\color{blue}{5}&\color{green}{67}&\color{blue}{7}&\color{red}{3}\\
\color{blue}{3}&\color{green}{71}&\color{blue}{5}&\color{green}{73}&\color{blue}{3}&\color{red}{3}&\color{blue}{3}&\color{red}{7}&\color{blue}{5}&\color{green}{79}
\end{array}$$
$$\begin{array}{cccccccccc}
870&\color{red}{13}&872&\color{red}{3}&874&\color{red}{5}&876&\color{green}{877}&878&\color{red}{3}\\
\color{blue}{3}&\color{green}{881}&\color{blue}{5}&\color{green}{883}&\color{blue}{3}&\color{red}{3}&\color{blue}{3}&\color{green}{887}&\color{blue}{5}&\color{red}{7}\\
\color{blue}{3}&\color{red}{3}&\color{blue}{5}&\color{red}{19}&\color{blue}{7}&\color{red}{5}&\color{blue}{13}&\color{red}{3}&\color{blue}{11}&\color{red}{29}\\
\color{blue}{13}&\color{red}{17}&\color{blue}{19}&\color{red}{3}&\color{blue}{17}&\color{red}{5}&\color{blue}{19}&\color{green}{907}&\color{blue}{31}&\color{red}{3}\\
\color{blue}{3}&\color{green}{911}&\color{blue}{5}&\color{red}{11}&\color{blue}{3}&\color{red}{3}&\color{blue}{5}&\color{red}{7}&\color{blue}{7}&\color{green}{919}\\
\color{blue}{13}&\color{red}{3}&\color{blue}{3}&\color{red}{13}&\color{blue}{5}&\color{red}{5}&\color{blue}{7}&\color{red}{3}&\color{blue}{17}&\color{green}{929}\\
\color{blue}{11}&\color{red}{7}&\color{blue}{3}&\color{red}{3}&\color{blue}{5}&\color{red}{5}&\color{blue}{7}&\color{green}{937}&\color{blue}{19}&\color{red}{3}\\
\color{blue}{3}&\color{green}{941}&\color{blue}{5}&\color{red}{23}&\color{blue}{3}&\color{red}{3}&\color{blue}{5}&\color{green}{947}&\color{blue}{7}&\color{red}{13}\\
\color{blue}{3}&\color{red}{3}&\color{blue}{5}&\color{green}{953}&\color{blue}{7}&\color{red}{5}&\color{blue}{3}&\color{red}{3}&\color{blue}{5}&\color{red}{7}\\
\color{blue}{7}&\color{red}{31}&\color{blue}{43}&\color{red}{3}&\color{blue}{11}&\color{red}{5}&\color{blue}{13}&\color{green}{967}&\color{blue}{31}&\color{red}{3}\\
\color{blue}{3}&\color{green}{971}&\color{blue}{5}&\color{red}{7}&\color{blue}{3}&\color{red}{3}&\color{blue}{5}&\color{green}{977}&\color{blue}{7}&\color{red}{11}\\
\color{blue}{3}&\color{red}{3}&\color{blue}{5}&\color{green}{983}&\color{blue}{7}&\color{red}{5}&\color{blue}{3}&\color{red}{3}&\color{blue}{5}&\color{red}{23}\\
\color{blue}{7}&\color{green}{991}&\color{blue}{73}&\color{red}{3}&\color{blue}{3}&\color{red}{5}&\color{blue}{5}&\color{green}{997}&\color{blue}{7}&\color{red}{3}\\
\color{blue}{3}&\color{red}{7}&\color{blue}{5}&\color{red}{17}&\color{blue}{7}&\color{red}{3}&\color{blue}{23}&\color{red}{19}&\color{blue}{11}&\color{green}{1009}
\end{array}$$


What functions satisfy one of these equalities: $x \cdot \Phi(x) = (\Phi \ast \Phi)(x)= \int_{- \infty}^{x} \Phi(t) dt$?

Question: When reading about the unit step or Heaviside function and it's derivative, the ramp function I encountered the following characterisations of the Heaviside function $\mathscr{H}$:

$x \cdot \mathscr{H}(x) = \int_{- \infty}^{x} \mathscr{H}(t) dt$
$(\mathscr{H} \ast \mathscr{H})(x) = \int_{- \infty}^{x} \mathscr{H}(t) dt$, where $\ast$ is convolution.

Are there any other functions $\Phi: \mathbb{R} \to \mathbb{R}$ with $\Phi \not \equiv 0$ satisfying either of those conditions on $\mathbb{R}$? I wrote out the definition of convolution but didn't come any further since surely, $\Phi$ could to be defined piece-wisely.
Some ideas:
Plugging $x = 0$ into (1) and (2) yields
$$
\int_{-\infty}^{0} \mathscr{H}(t) dt
= \int_{\mathbb{R}} \mathscr{H}(t) \mathscr{H}(-t) dt
= 0,
$$
meaning that the function and its reflection upon the $y$-axis "cancel out".

Update 1: $f$ is not differentiable in $x = 0$.
Case 1: $f$ is differentiable and fulfils one above requirement
Now we can differentiate
$$
x \cdot f(x) = \int_{-\infty}^{x} f(t) dt
$$
to obtain
$$
x \cdot f'(x) + f(x) = f(x)
\implies x \cdot f'(x) = 0
$$
Since $x \not\equiv 0$ we know that $f'(x)$ is constant, implying that it is constant lets say $f(x) \equiv c \in \mathbb{R}$.
(Since $f$ is differentiable it is continuous and therefore can't be piecewise constant with discontinuous jumps like a step function)
But this is a contraction since $\int_{-\infty}^{x} c dx = \infty$ for all $x,c \in \mathbb{R}$.
Case 2: $f$ has an antiderivative $F$ defined on $\mathbb{R}$
Then, by the FTOC we can write
$$
x \cdot f(x) = F(x) - F(-\infty)
\implies x \cdot f(x) + F(-\infty) = F(x).
$$
Since $f$ fulfils the above condition we deduce $F(-\infty) < \infty$.
We know that $F$ is differentiable with $F' = f$.
Since $F(-\infty)$ is a constant irrelevant to the differentiability of the LHS we conclude that $f(x)$ is differentiable on $\mathbb{R} \setminus \{0\}$.
Because of case 1, $f$ can't be differentiable in zero.
Is this correct and if yes, how can we continue from here?

I also noticed that $x \cdot \Phi(x) = (\Phi \ast \Phi)(x)$ will also hold for the "reverse Heaviside function" $\Phi := \mathbb{1}_{\{x<0\}}$.
Comment: You may find the following interesting: $$\int_{-\infty}^x f(t)\,dt=\int_{-\infty}^\infty f(t)\mathscr{H}(x-t)\,dt=(f\ast \mathscr{H})(x).$$ Thus the first antiderivative of $f(x)$ can itself be expressed as a convolution against the Heaviside step function. (This in particular makes it obvious why $\int_{-\infty}^x \mathscr{H}(t)\,dt=(\mathscr{H}\ast \mathscr{H})(x).$)
Answer: Suppose $\Phi(x)$ is a distribution, then the only solutions, $f(x)$, to equation 1 are multiples of the Heaviside function.  This is because, as you already stated, $x\cdot f'(x)=0$, which has only $\delta (x)$, or multiples, as solutions for$f'(x)$.  Note that $x\cdot \delta'(x)=\delta(x)$ not $0$ and similarly for higher derivatives.  Of course $\int_{-\infty}^{x} \delta(t)dt=\mathscr{H}(x)$.
It is straightforward to show that $f(x)=e^{icx}\mathscr{H}(x)$ solves equation 2 for any $c$.  Invoking the idea of $f(x)$ as a distribution on the space of smooth test functions which fall off rapidly at large $x$, we can Fourier transform equation 2.  I note that distributions do not in general have convolutions with themselves, but assume that the convolution is ok.  Then equation 2 becomes $$-i\tilde{f}'(\omega)=2\pi \tilde{f}^2(\omega),$$ which has solutions $$\tilde{f}(\omega) = \frac{i}{2\pi(\omega+c)},$$ where $\tilde{f}$ denotes the Fourier transform of $f$.  Fourier transforming  back, we get $f(x)=e^{icx}\mathscr{H}(x)$.


how to use cookie to protect other node pages in Drupal

Question: some bots are grabbing my site's content everyday,I confirm if I set cookie protection the bots will not work again.
My question is how to use cookie to protect my content? if someone has no cookie then he can't go to next page.
Answer: Sounds like a case for user authentication?
The problem is the first page request will never have a server-side set cookie as it will be set on the subsequent request and you don't want to deny access on your homepage.
You could set the cookie with javascript, but then you risk blocking users with js disabled.
Requiring user login would be the easiest solution.


localhost:8080 displays type error "code" : "Forbidden" on any servers

Question: localhost:8080 does not works, the only thing I get is
{
"type" : "error",
"code" : "Forbidden"
}
written on page.
last thing what I remember is I used webSocket using javaee-api-7.0.jar package in JBoss 7.1as . Before that it was working fine. But now neither JBoss diplays localhost nor tomcat nor glassfish.
Comment: Have you set any application as Root application (via jboss-web.xml) ?did you alter any configuration parameter in the web (as7) or undertow (wildfly) subsystem ?
Comment: Actually One of my application(RealPlayer) was interfering with port 80, I uninstalled it and now everything is working fine...
Answer: Its sorted!.. I was trying to install XAMPP and it prompt me an error saying one of my application(RealPlayer) is not allowing to access port number(Don't remember exact statement). I removed it from my pc and now my localhost is working fine...


"x509.DecryptPEMBlock" is Deprecated, what is alternative?

Question: As of Go 1.16, x509.Encrypt/DecryptPEMBlock is Deprecated. What is the alternative for this to encrypt private key?
Comment: Duplicate: https://stackoverflow.com/questions/67432235/x509-decryptpemblock-deprecated
Comment: @Peter: the question is indeed a duplicate, but the linked question doesn't even have an answer. It'd be great to expand upon your comment to an answer which could then be marked accepted and used as a canonical link to further deprecated questions
Comment: There are alternatives, but requests for recommendations are off-topic for SO. One common format is encrypted [PKCS8](https://datatracker.ietf.org/doc/html/rfc5208), though Go does not currently support decrypting these with the stand library: https://github.com/golang/go/issues/8860.
Comment: These are deprecated due to the padding oracle attacks so there will be no std lib alternative as the intention is for the user to move away from this approach to another one. Read more here - https://github.com/golang/go/issues/59961 .
Answer: I would use x509.MarshalPKCS1PrivateKey and x509.ParsePKCS1PrivateKey for this purpose.
func ParsePrivateKey(data []byte) (*rsa.PrivateKey, error) {
    return x509.ParsePKCS1PrivateKey(data)
}

func MarshalPrivateKey(key *rsa.PrivateKey) []byte {
    data := x509.MarshalPKCS1PrivateKey(key)
    return data
}


Separar itens de uma string utilizando Regex

Question: Preciso separar os itens de uma string em um array utilizando C# e Regex, poderiam me ajudar?
A string é a seguinte:
required|email|min:2|max:255
Há algumas regras que eu queria adequar:

Separar os itens principais delimitados pela barra |.
Ignorar caso haja uma barra no final da string, exemplo required|email|.
Separar itens que possuam um valor, exemplo min:2 e max:255.
Comment: Os itens separados por "`:`" vão ficar juntos em um mesmo item ou eles serão totalmente separados?
Comment: Juntos em um mesmo item.
Comment: Se os itens de "`:`" tiverem que ficar juntos de alguma maneira, acho que a resposta que eu te dei não vai resolver. Você teria que, por exemplo, criar uma lista de _Array_, sendo que maioria dos _Array_ teriam só uma posição e os que tivessem mais de uma posição seriam dos itens separados por "`:`"... Se precisar disso mesmo só comenta aqui que eu mudo a resposta!
Comment: Exatamente, o que preciso é de algo que gere um array onde os itens que forem separados por `:` sejam inclusos em um outro nível, onde a primeira string é a key e a segunda string é o valor, exemplo: `["required", ["max", 255], ["min": 6], "email"]`.
Comment: Resposta editada para incluir uma solução pra essa situação.
Answer: Recomendo usar o Split normal, normalmente é mais eficiente que Regex.
Se todos os valores tiverem que ser separados, basta dar Split pelos dois caracteres e usar a opção de ignorar divisões vazias: Split(new char[] { ':', '|' }, StringSplitOptions.RemoveEmptyEntries).
Se os valores separados por ":" precisarem ficar juntos, a solução complica um pouco. Um dos problemas é que não existe Array ou List de tipos diferentes no C#, então uma alternativa seria List de Array:
var texto = "required|email|min:2|max:255";

var itensSeparados = texto.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries)
    .Select(x => x.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries))
    .ToList();

foreach (var item in itensSeparados)
{
    if (item.Length == 1)
        ; // Item único
    else
        ; // Itens separados por ":"
}


Finding length of median

Question:
In the given figure ABCD and MNPD are square ,AB=a and NP=b then find QT if AT=TP
IS the above question correct? I tried solving it a lot but could not solve
Comment: Hint: What is $\angle AQP$? (What are the slopes of $\overline{AQ}$ and $\overline{PQ}$?)
Answer: Let $A(0,0)$ and $D(a,0)$. Hence, $P(a+b,0)$, $M(a,b)$, $C(a,a)$, $T\left(\frac{a+b}{2},0\right)$.
Equation of $PQ$ is
$$y-a=-\frac{a}{b}(x-a) \tag{1}$$
therefore
$$y=-\frac{a}{b}x+\frac{a^2+b^2}{b} \tag{2}$$
Also equation of $AQ$ is
$$y=\frac{b}{a}x \tag{3}$$
Solving $(2)$ and $(3)$:
$$Q\left(\frac{a^2(a+b)}{a^2+b^2},\frac{ab(a+b)}{a^2+b^2}\right) \tag{4}$$
Hence,
$$QT=\frac{a+b}{2} \tag{5}$$
Comment: Thanks for correction now I think it is correct.
Answer: In triangle AMD where AD=a and MD=b and let AP represent x axis Hence slop of AM is $m_{AM}=\frac{b}{a}$ and similarly since CD=a and DP=b Hence slope of PC is $m_{PC}=-\frac{a}{b}$
$$. $$
Hence AQP is right angle triangle and T is circumcenter of triangle
Hence AT=PT=QT=$\frac{a+b}{2}$

Finding length of median


The number of a triangle on a rectangular grid

Question: Given a $n \times m$ rectangular grid, the length of each side of the cell is 1
Arbitrarily take three non-collinear grid points on this grid to form a triangle
So what is the number of congruent triangles in this rectangular grid (including itself)?
In fact, we only need to find the length $s$ and width $t$ of the smallest rectangle covering this triangle.
Then the answer is $2(n-s+1)(m-t+1)$
But if we only know the length of the three sides of the triangle $a,b$ and $c$,
how can we fine the $s$ and $t$?
Sometimes, the $s$ and $t$ are not unique, for example, if $a=5$, maybe you can put it horizontally or diagonally
Comment: I personally found this question a bit unclear. Could you give some examples for smaller $n$ and $m$ values?
Answer: It looks like $n \times m$ are the dimensions of rectangle, so the grid of points is $(n+1) \times (m+1)$.  Your answer is not correct.  Take a $1,2,\sqrt 5$ triangle, which gives $s=2,t=1$ for the covering rectangle.  If the $2$ is along the $n$ direction, there are $n-1$ places it can start and $m$ places you can start the other way, so there are $(n-1)m$ triangles.  The triangle has two orientations in the rectangle, so this gives $2(n-1)m$ triangles.  This matches your formula, but you can orient the rectangle the other way and get another $2(m-1)n$ triangles.
I don't have a magic way to find $s,t$.  First see if any of $a,b,c$ are irrational.  Find all the ways to express $a^2,b^2,c^2$ as a sum of two squares.  You need to close the triangle, so need to find a way to add or subtract the values in your expression to do so.  For example, if we have a $5,12,13$ triangle, we have $5^2=5^2+0^2=3^2+4^2, 12^2=12^2+0^2, 13^2=13^2+0^2=5^2+12^2$.  The fact that $12^2$ has no other expression says that the $12$ must be along a grid line.  Then you find $s=5,t=12$.
If you have a triangle with $a=10,b=13$, both of which can be put orthogonally or diagonally, the third side will tell you which.  If your triangle is $10,13,\sqrt{269}$,the fact that $269=10^2+13^2$ says the $10$ and $13$ are orthogonal.  If your triangle is $10,13,\sqrt {333}$, you have $333=18^2+3^2$.  If the $10$ is oriented with the $6$ vertical and $8$ horizontal, the $13$ must be oriented with the $12$ vertical so $12+6=18$ and the $5$ horizontal so $8-5=3$
I don't know if there are triangles that can have more than one orientation on the grid up to rotations and reflections.


Can someone explain the output of this recursive function in python?

Question: This is a function in python3 that prints 1 through 10. There are a few things I don't understand about this, since I'm a programming noob.
This function will subtract 1 from a given number as long as that number is above 1. So if number = 10 it will subtract 1 from 10 to give 9 and then 1 from 9 to give 8 and so on... until it reaches 1, which will be printed to the screen.
I don't understand is why the function subsequently prints 2, 3, 4, 5, 6, 7, 8, 9 and 10. Since these numbers are above one, shouldn't they enter the if-statement and then not be printed? According to my understanding of the code, only numbers that are equal to or below 1 will be printed.
In other words: "Why is the output of this function, not "1" alone?"
def print_numbers(number):
    if number > 1:
        print_numbers(number-1)
    print(number)
print_numbers(10)

You can try out the code in python to see that the output is 1 through 10?
Answer: In this block:
if number > 1:
    print_numbers(number-1)
print(number)

the interpreter enters the print_numbers function under that condition, but will afterwards also print the number. Your expected effect would occur if you put the print in an else branch:
if number > 1:
    print_numbers(number-1)
else:
    print(number)

Answer: What happens is this:

call function: print_numbers(10)
call function: print_numbers(9)

etc. etc.

call function: print_numbers(1)

in print_numbers(1) there's no next function being called so the
if number > 1:
    print_numbers(number-1)

is skipped. Now the print statement is called, your program prints '1'.

print_numbers(1) continues and prints 1
print_numbers(2) continues and prints 2

etc etc.
If you were to put the print statement earlier, like this:
def print_numbers(number):
    print(number)
    if number > 1:
        print_numbers(number-1)
print_numbers(10)

It would first print, and then call the function, returning 10, 9, 8, 7 etc.
Answer: You read the instructions the wrong way…
In the body of the function, the order of the instructions is the following :
if the number is greater than one, the function calls a function and waits for its completion before printing the value. So, if print_numbers(10) is called :

it calls print_numbers(9) and wait
print_numbers(8) calls print_numbers(7) and wait
print_numbers(7) calls print_numbers(6) and wait

…

print_numbers(1) prints 1 and returns
print_numbers(2) resumes, prints 1 and returns
print_numbers(3) resumes, prints 1 and returns

…

print_numbers(9) resumes, prints 1 and returns
print_numbers(10) resumes, prints 1 and returns

Beware, the print statement have the same indentation as the if statement. Si the if block is called and after that, the execution continues with the print statement.
Answer: I have been struggling to visualise what actually goes on in a recursive function myself. However, the sequence of events are:
The function is called and a value passed to it. 10 in your example.
10 is then stored in memory
function checks if 10 > 1
and subtracts 1 if true
9 is passed back to the start of the function and is stored in memory. It is positioned after 10, which is still in memory
function checks if 9 > 1
and subtracts 1 if true
8 is then passed back, stored in memory etc
This continues until the remaining value passed back is not > 1
We now have:
10, 8, 7, 6, 5, 4, 3, 2
stored in sequence in memory
the function then moves on to the print statement and prints out the numbers starting with the last to be stored in memory i.e. 2
it then discards 2 and moves on to process 3 etc. until it finally prints and discards 10, the first entry in memory.
After trying to figure out what a recusive factorial equation was doing, I found a great visualisation tool that can help to understand what is going on in such equations.
The link is here:
Python Tutor by Philip Guo
I used the value 4 for brevity, but you can edit the code if you want to use any value.
Some coding concepts melt my brain, but I keep trying to learn! I hope the tool helps, it certainly did me :0)