I am working on spring MVC and need help setting flag

Question: This is the source code i have
<code>public Customer add(UI uI)
    {

        String url = "https://localhost:8080/api;
        System.out.println("url is "+url);
        RestTemplate restTemplate = new RestTemplate();
        Customer customer = restTemplate.getForObject(url, Customer.class);
        System.out.println(customer);
        customerDao.save(customer);
        return customer;

    }
</code>
I receive this JSON data from localhost api as response
<code>{"id":"12","datetime":"08:39:02","status":good,"first_name":"ABC","last_name":"xyz"}
</code>
for status i have two values good and bad and my question is how can i raise a flag if the status is bad.
Comment: what do you meant by raise a flag?
Comment: if it is bad then set value of the variable as somthing and call a different function
Comment: why didn't you use `boolean` instead of `String`?
Comment: Again. You should be clear on what you want. Set value  of which variable of which class and call which function
Comment: if it is bad i want to call inspectCustomer function
Comment: you can the status of your response if 200 then it is success else 400 or 500 means error and exicute your function respectively
Comment: If you are keen about the JSON response, then receive it as a JSONObject and iterate it to the required field to check. In your case, the status is inside the Json, so you have to deal it as a json and validate
Answer: <code>    JSOnObject resp = `{"id":"12","datetime":"08:39:02","status":good,"first_name":"ABC","last_name":"xyz"}`;
String status = resp.getAsString("status");
if(status.equalsIgnoreCase("good")){
  //set Flag
}

if(status.equalsIgnoreCase("bad")){
  //call function
}
</code>


Lower bound on $||a-b|-|a+b||.$

Question: Let $a,b\in\mathbb{C}$ be complex numbers. I am looking for some lower bound on
$$||a-b|-|a+b||.$$ I've found an upper bound ( $2|b|$ ), but this is not quite what I need. I think there should be some lower bound as a function of $a,b$ (or their real/imaginary parts). Indeed, my intuition comes from the fact that if $a=a_1+\mathrm ia_2$ and $b=b_1+\mathrm i b_2,$ then
$$|a-b|=|a+b|\Leftrightarrow(a_1+b_1)^2+(a_2+b_2)^2=(a_1-b_1)^2+(a_2-b_2)^2,$$
and this is equivalent to
$$a_1b_1=-a_2b_2,$$
which is a tight condition, so that in most cases,
$||a-b|-|a+b||>0.$
Comment: do you want to know lower bound when $a_{1} b_{1}\neq -a_{2} b_{2}$
Comment: Yes, this would do the trick.
Comment: for $\epsilon >0$, let $a=(1+\epsilon, 1)$ and $b=(1,-1)$ then $||a-b|-|a+b||=|\sqrt{\epsilon ^2+4}-2+\epsilon | \to 0 $ as $\epsilon \to 0$. So I think lower bound should be zero even if $a_1b_1\neq a_2b_2$.
Answer: Does this help? If $a, b$ are not both zero then
$$
  \bigl \lvert \lvert a-b \rvert -  \lvert a+b \rvert \bigr \rvert =
 \frac{\bigl\lvert \lvert a-b \rvert^2 -  \lvert a+b \rvert^2 \bigr \rvert}{\bigl\lvert \lvert a-b \rvert + \lvert a+b \rvert \bigr \rvert} \\
 = \frac{4 \lvert \operatorname{Re} (a \overline b) \rvert}{\bigl\lvert \lvert a-b \rvert + \lvert a+b \rvert \bigr \rvert}
\ge \frac{2 \lvert \operatorname{Re} (a \overline b) \rvert}{\lvert a \rvert + \lvert b \rvert}
= \frac{2 \lvert a_1 b_1 + a_2 b_2\rvert}{\lvert a \rvert + \lvert b \rvert}
$$
Comment: Yes! I think this can help! Thank you!

Lower bound on $||a-b|-|a+b||.$


ssh, authorized_keys and group write grant

Question: I am managing one machine that hosts an OTRS webserver. It has a normal user, 'otrs', which runs several periodic tasks and keeps (in 'otrs' home) the needed files for the service to work. And then there is the Apache user, which runs the webserver that makes the app work. The 'otrs' user is in the 'apache' group, so I can give write grants to 'apache' in some folders.
To add some functionality, I need to give 'apache' write grants in the 'otrs' home directory. But, if I do it, ssh won't connect with authorized keys, because it's a security risk.
I've tried using ACL's to give 'apache' write grants on 'otrs' home but not in home/.ssh, but it won't work.
So, what can I do? I've thought of removing the 'otrs' user and doing everything as 'apache', or run the webserver daemon as 'otrs' user, but I don't know how to do any of these, or if they may carry some problems...
Do you have any option that I haven't thought of?
Answer: The problem is that even without write permission to .ssh, someone with write permissions to the home directory could move or unlink .ssh, then introduce their own .ssh with authorized keys in order to log in as otrs.
One solution would be to limit write permissions to some subdirectory of ~otrs. Another one would be to give ~otrs permissions of 1775 (the t-bit will prevent other users from unlinking or renaming .ssh), then set StrictModes to no in /etc/ssh/sshd_config. This may open up other accounts (with incorrect permissions) to attacks, but I assume that this is a dedicated machine, so that should not be a problem.
Comment: thank you for your quick answer. I really didn't know about this sticky-bit, thanks
Answer: The 'otrs' account is basically a service or system account. The best way to fix this issue is in my opinion to not use the account for access over SSH. Create an account for yourself, 'juanma' or so, and configure sudo suaccess to the 'otrs' account. Now you can change user to the otrs account if needed.


Não consigo enviar esse formulário via Ajax!

Question: Olá tenho esse código de formulário caso a pessoa queira ajudar o meu projeto:
    <form id="my-form" action="envia.php" method="POST">
                 Nome
                <input type="text" id="fname" name="firstname" placeholder="seu nome e sobrenome">
                 Email
                <input type="text" id="email" name="email" placeholder="firstname.lastname@example.com">
                 Address
                <input type="text" id="adr" name="address" placeholder="542 W. 15th Street">
                 City
                <input type="text" id="city" name="city" placeholder="New York">
                Name on Card
                <input type="text" id="cname" name="cardname" placeholder="John More Doe">
                Numero do Cartão:
                <input type="number" id="ccnum" name="cardnumber" placeholder="1111-2222-3333-4444">
                Mês de Expiração:
                <input type="number" id="expmonth" name="expmonth" placeholder="Setembro">
                Exp Year
                <input type="number" id="expyear" name="expyear" placeholder="2018" pattern="[0-9]+$">
                CVV
                <input type="number" id="cvv" name="cvv" placeholder="352">
                <button id="my-form-button" type="submit">Submit</button>

            </form>

até ai tudo bem pois ele envia certinho o formulário no banco de dados,mais eu queria que ele fizesse isso só que sem refresh por isso eu decidi usar ajax então criei esse código:
          window.addEventListener("DOMContentLoaded", function() {
var form = document.getElementById("my-form");
            var button = document.getElementById("my-form-button");
            var status = document.getElementById("my-form-status");

            // Success and Error functions for after the form is submitted

            function success() {
              form.reset();
              button.style = "display: none ";
              status.innerHTML = "Obrigado!!";
            }

            function error() {
              status.innerHTML = "Oops! Temos problemas , tente novamente mais tarde";
            }

            // handle the form submission event

            form.addEventListener("submit", function(ev) {
              ev.preventDefault();
              var data = new FormData(form);
              ajax(form.method, form.action, data, success, error);
            });
          });

          // helper function for sending an AJAX request

          function ajax(method, url, data, success, error) {
            var xhr = new XMLHttpRequest();
            xhr.open(method, url);
            xhr.setRequestHeader("Accept", "application/json");
            xhr.onreadystatechange = function() {
              if (xhr.readyState !== XMLHttpRequest.DONE) return;
              if (xhr.status === 200) {
                success(xhr.response, xhr.responseType);
              } else {
                error(xhr.status, xhr.response, xhr.responseType);
              }
            };
            xhr.send(data);
          }

só que ele só da erro estou fazendo do jeito certo?
Answer: Um exemplo que você pode usar neste caso e serializar o formulário, segue um exemplo que você pode usar como base:
$("#eviarAjax").click(function (e) {
    e.preventDefault();

    var urlCompleto = "/AdicionarDetalhe/";
    var formulario = $("#SeuFormulario");

    $.ajax({
        method: "POST",
        url: urlCompleto,
        data: formulario.serialize(),
        success: function (resultado) {
              console.log(resultado);
        }
    });

});


Django model function implementation to auto initialize a particular field's value

Question: I need to write a Django model function to calculate the value of an existing field.
my models.py:
class questionNumeric(models.Model):
    question = models.TextField()
    marks = models.IntegerField()
    correctAns = models.FloatField()

class questionTureFalse(models.Model):
    question = models.TextField()
    marks = models.IntegerField()
    correctAns = models.BooleanField()

class questionSet(models.Model):
    examName = models.CharField(max_length=200)
    questionNumeric = models.ManyToManyField(questionNumeric)
    questionTureFalse = models.ManyToManyField(questionTureFalse)
    totalMarks = models.IntegerField(default=0)

As you can see here, each questionNumeric or questionTureFalse object has specific marks. Now I want to set my questionSet object's totalMarks field with- the summation of marks carried by all questionNumeric or questionTureFalse under this questionSet object.
How can I write a Django Model function under questionSet to auto initialize totalMarks?
Answer: You can declare a function in questionSet and return count of relations. For example sth like:
class QuestionSet(models.Model):
    ...
    def get_question_numeric_count(self):
        return self.questionNumeric.count()


Android: Error while trying to access a .Net Web Service

Question: I have created a small app to access a .Net Web Service
But I get this error from Android
SoapFault - faultcode: 'soap:Client' faultstring: 'System.Web.Services.Protocols.SoapException: Server did not recognize the value of HTTP Header SOAPAction: http://webservice.pollsdb.com/Msgs.
   at System.Web.Services.Protocols.Soap11ServerProtocolHelper.RouteRequest()
   at System.Web.Services.Protocols.SoapServerProtocol.RouteRequest(SoapServerMessage message)
   at System.Web.Services.Protocols.SoapServerProtocol.Initialize()
   at System.Web.Services.Protocols.ServerProtocolFactory.Create(Type type, HttpContext context, HttpRequest request, HttpResponse response, Boolean& abortProcessing)' faultactor: 'null' detail: org.kxml2.kdom.Node@b1ebfe80

does anyone know how to call this service from android?
This is my code
SOAP_ACTION = namespace + MethodName;

request = new SoapObject(namespace, MethodName);

//Adding String value to request object
request.addProperty("Lg", Lg);
request.addProperty("Lt", Lt);
request.addProperty("Cnt", Cnt);

//request.addProperty("ToUnit", "" + toUnit);

SetEnvelope();

//SOAP calling webservice
androidHttpTransport.call(SOAP_ACTION, envelope);

//Got Webservice response
String result = envelope.getResponse().toString();

return result;

Comment: did u already checkd this topic? hope it helps > http://stackoverflow.com/q/352174/3640637
Comment: yes i saw this, but did not know how to will help in my case, i am very new to android and java
Answer: I found the problem
It was in the .Net not in the Android
Just changed the Namespace from .Net default to the website where the service is
[WebService(Namespace = "http://webservice.pollsdb.com/")]


Microsoft Emotions API, RecognizeInVideoAsync c#

Question: Im trying to use Microsft Emotions Api by using recognize in video, so i downloaded the client library and tried to use it, but when im debugging, it just step out without any exceptions, i thing it might be a thread prbolem - it happens in the method: "recognizeInVideoAsync".
my code:
public static async void testEmotionApi()
{
    var emotionServiceClient = new EmotionServiceClient("c580db97556e405980212f3ff31ac762");

    VideoEmotionRecognitionOperation videoOperation;
    using (var fs = new FileStream(@"D:\Downloads\testForApp.mp4", FileMode.Open))
    {
        videoOperation = await emotionServiceClient.RecognizeInVideoAsync(fs);
    }

    VideoOperationResult operationResult;
    while (true)
    {
        operationResult = await emotionServiceClient.GetOperationResultAsync(videoOperation);
        if (operationResult.Status == VideoOperationStatus.Succeeded || operationResult.Status == VideoOperationStatus.Failed)
        {
            break;
        }

        Task.Delay(30000).Wait();
    }

    var emotionRecognitionJsonString = operationResult.ToString();
}

Comment: What is the purpose of `Task.Delay(30000).Wait();`? You're already `await`ing the async calls...
Comment: Why not adhere to example provided here: https://www.microsoft.com/cognitive-services/en-us/Emotion-api/documentation/GetStarted
Comment: Also not a good practice to include API keys with your sample code.
Answer: This is how the async programming works in C#.  While in source form you appear to have a single method, in practice the method is split in to multiple parts at await boundaries.  In other words, as you've written it, the testEmotionApi method returns after the RecognizeInVideoAsync is called.  The remainder of the method will be executed when the async call completes, but you've no way to wait on that result.  What you could do instead is:
public static async Task<VideoOperationResult> testEmotionApi()
{
    // everything here the same, except...
    return operationResult;
}

public async Task callEmotionTestApi()
{
    VideoOperationResult result = await testEmotionApi();
    ...
}

or, if you don't want the caller to be async,
public void callEmotionTestApi()
{
   VideoOperationResult result = testEmotionApi().GetAwaiter().GetResult();
   ...
}


How to add an extra parameter to be sent to the server while using "formDeleting" in jQgrid?

Question: I need to send an extra parameter while I am trying to delete one or more rows in jQgrid. I have found the following:

jqGrid additional POST data when deleting row
jqGrid (Delete row) - How to send additional POST data?

But those are one/two year old answers and I think jQgrid has changed since then. I am using the formDeleting option from jQgrid defined as follow:
formDeleting: {
    url: '/ajax/forms/delete',
    delicon: [true, "left", "fa-scissors"],
    cancelicon: [true, "left", "fa-times"],
    width: 320,
    caption: 'Delete form',
    msg: 'Are you sure you want to delete this form?',
    beforeShowForm: function ($form) {
        var rowids = $form.find("#DelData>td").data("rowids");

        if (rowids.length > 1) {
            $form.find("td.delmsg").html('Are you sure you want to delete all the selected forms?');
        }
    },
    afterComplete: function (response, postdata, formid) {
        if (response.responseText === "true") {
            alert("The form was deleted successfully.", "Information");
        } else {
            alert("Something went wrong, the form could not be deleted.", "Error");
        }
    }
}

How do I add an extra parameter to the request so I can get it on the backend?
Answer: I'd recommend you to use onclickSubmit callback close to the answer, but to place the code of the onclickSubmit callback inside of formDeleting. The usage of serializeDelData inside of formDeleting inside of formDeleting is possible too, but it's better to use it in case of more deep changing in the posted data, like the usage of JSON.stringify, for example.
Comment: @ReynierPM: Look at https://jsfiddle.net/OlegKi/aw47ytqz/2/ where I added `localReader: { id: "Id" }`, modified the code of `isDisplayButtons` and added the call of `navButtonAdd` at the end of the code.
Comment: @ReynierPM: `localReader: { id: "Id" }` is needed if you fills the data via local `data`, but it could be that in some cases of `loadonce: true` scenario it could be helpful too. In any way your previous demo doesn't used `Id` of the source data.
Comment: `localReader` is because the data is set to by `local` or it's needed if the data is remote as well? This is part of a big grid (see [here](https://stackoverflow.com/questions/48271049/how-to-avoid-jqgrid-initial-ajax-request/48275088#48275088) I just split out my doubts in smaller questions :)
Comment: I am having another issue: as soon as I click on the row and because of `inlineEditing` the row gets selected as well as the checkbox for such row, how do I avoid to edit the row when check|uncheck the select?
Comment: @ReynierPM: I'm not sure that I understand what you *want* to implement. `onSelectRow` starts inline editing depend on the column which is clicked (not on click on `act` column). One can use `beforeSelectRow` to prevent selection on some clicks. On the other side there are many other options, which can change the behavior of selection in general. See https://github.com/free-jqgrid/jqGrid/blob/v4.15.2/ts/free-jqgrid.d.ts#L1152-L1170
Comment: Try this [here](https://jsfiddle.net/OlegKi/aw47ytqz/2/) click on any column `inlineEditing` will happen and the checkbox at the first column gets checked. Try to uncheck the checkbox to stop the `inlineEditing` you can't. You have to click on the `Cancel` button no matter what. I want to avoid this behavior. As soon as you try to uncheck the checkbox `inlineEditing` should stop
Comment: @ReynierPM: What you want to prevent: selection or inline editing?
Comment: And even if you click on the `Cancel` button the checkbox still checked and the line still marked
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/163272/discussion-between-reynierpm-and-oleg).


What's the expected radius of a hypersphere

Question: I would like to compute the expected radius of a hypersphere (dimension $N$) given these conditions:

radius $R\in[R_{min}, R_{max}]$,
radius is acquired by uniformly chosing point from $S_N(R_{max})\backslash{S_N(R_{min})}$, and taking its radius,
$A+B$ number of points $x = (x_1,x_2,...,x_N)$ have been chosen uniformly from the same subspace $S_N(R_{max})\backslash{S_N(R_{min})}$. $A$ points are from the space $S_N(R)\backslash{S_N(R_{min}})$, and $B$ points are from $S_N(R_{max})\backslash{S_N(R)}$,
$E(R)=f(R_{min},R_{max},A,B,N)$.

Done so far:
I have writted distribution function of $R$ as follows:
$$f_R(r)=\binom{A+B}{B}\frac{(r^N-R_{min}^N)^A(R_{max}^N-r^N)^B}{(R_{max}^N-R_{min}^N)^{A+B}}\text{ .}$$
I've got the function by comparing volumes between hyperspheres for given radius. I've had the intention of trying to compute the expected value from this distribution function, but it gets a bit messy if I try to crack it and integrate polynomials that I would get.
Questions:

(of very very minor importance) is general approach alright. I suppose it is.
(of major importance) is there a nice way to compute the $E(R)$?

Probable way:
If I would write $$p(r,N)=\frac{r^N-R_{min}^N}{R_{max}^N-R_{min}^N}\text{ ,}$$ then the density function would be like this
$$f_R(r)=\binom{A+B}{B}p^A (1-p)^B\text{ .}$$
It looks rather similar to binomial distribution to me...
Comment: So given $R_\min$, $R_\max$, $A$ and $B$, and a sample of points $\vec{x}_i \in S_N(R_\max) \backslash S_N(R_\min)$, and define $z_i = |\vec{x}_i|$. We then order $z_i$'s, and consider order statistics $z_{i:A+B}$. You state that $R$ is such that $z_{A:A+B} < R < z_{A+1:A+B}$, but how do you choose $R$ from that interval ?
Comment: That point whose radius is $R$, for which we are computing expected value is also chosen uniformly like other $\vec{x_i}$, and only after all points are chosen $A$ and $B$ are calculated. Does this answers your question?
Comment: The problem statement is quite confusing. Is Sasha's interpretation right?
Comment: Sasha's interpretation is alright...
Answer: Here is my interpretation of your question:

$n=a+b+1$ points are uniformly chosen in $S_d(R_\max)\backslash S_d(R_\min)$, and are sorted by their radius. You are interested in the expectation of $a+1$-th smallest radius.

The radius $R$ of a point, uniformly chosen in $d$-dimensional ball $S_d(R_\max)$, has a known probability density:
$$
   \mathrm{d} F_R(r) = \frac{d \cdot r^{d-1}}{R_\max^d} \mathbf{1}_{0 < r < R_\max} \mathrm{d} r
$$
Truncating the distribution to $(R_\min, R_\max)$, the density becomes
$$
     \mathrm{d} \bar{F}_R(r) = \frac{d \cdot r^{d-1}}{R_\max^d - R_\min^d} \mathbf{1}_{R_\min < r < R_\max} \mathrm{d} r
$$
We are now interested in finding the mean of $a+1$-th out of $a+b+1$ order statistics, whose probability density is well-known:
$$ \begin{eqnarray}
   \mathrm{d} F_{a+b+1}^{(a+1)}(r) &=& (a+b+1) \binom{a+b}{a} f_R(r) F_R(r)^a (1-F_R(r))^b \mathrm{d} r \\
   &=& (a+b+1) \binom{a+b}{a} \cdot d \cdot r^{d-1} \cdot \frac{\left(r^d - R_\min^d\right)^a \cdot\left(R_\max^d - r^d \right)^b }{\left(R_\max^d-R_\min^d\right)^{a+b+1}} \mathrm{d} r \\
   &=& (a+b+1) \binom{a+b}{a} \cdot \frac{\left(r^d - R_\min^d\right)^a \cdot\left(R_\max^d - r^d \right)^b }{\left(R_\max^d-R_\min^d\right)^{a+b+1}} \mathrm{d} r^d \\
   &=& (a+b+1) \binom{a+b}{a} \cdot u^a \cdot\left(1 -u \right)^b \mathrm{d} u \\
   &=& \frac{1}{B(a,b)} u^a \cdot\left(1 -u \right)^b \mathrm{d} u
\end{eqnarray}
$$
where $u = \frac{r^d - R_\min^d}{R_\max^d-R_\min^d} = \bar{F}_R(r)$, meaning that $U = \bar{F}_R(R)$ follows $\mathrm{Beta}(a+1,b+1)$ distribution.
Thus
$$ \begin{eqnarray}
   \mathbb{E}(R) &=& \mathbb{E}\left( \left( R_\min^d + U (R_\max^d-R_\min^d) \right)^{1/d} \right) \\ &=& \int_0^1 \frac{u^a (1-u)^b}{\mathrm{B}(a+1,b+1)} \left( R_\min^d + u (R_\max^d-R_\min^d) \right)^{1/d} \mathrm{d} u \\
   &\stackrel{u\to 1-u}{=}& R_\max \int_0^1 \frac{u^b (1-u)^a}{\mathrm{B}(b+1,a+1)} \left( 1 - u \left( 1 -\frac{R_\min^d}{R_\max^d}\right) \right)^{1/d} \mathrm{d} u \\
   &=& R_\max \cdot {}_2 F_1\left(a+1, -\frac{1}{d} ; a+b+2; 1-\frac{R_\min^d}{R_\max^d}\right)
\end{eqnarray}
$$
where the last equality is direct application of Euler's integral.


Big $\Omega$ question! Prove $(n-1)(n-2)(n-3)$ is $\Omega(n^3)$

Question: Problem
Prove $(n-1)(n-2)(n-3)$ is $\Omega(n^3)$.
Attempt @ Solution

$f(n) = n^3(1-6/n+11/n^2-6/n^3)$
$g(n) = n^3$
Show that there exists a $C > 0$ and $n_0$ such that $f(n) \ge Cg(n)$ for all $n > n_0$.
I tried plugging in different numbers for $n$ that would make $f(n) > n^3$.  I found that setting $n = 7$ makes sure that $f(n)$ is greater than $g(n)$.  So, is that my answer?  Evaluating the expression with $n=7$ to solve for $C$, and setting $n_0$ as $7$?  Is that a sufficient proof?  Also, Does my constant have to be a Natural number, or can it simply be a Rational number?
Comment: Your constant can be any positive real number. But your proof is not sufficient: The definition requires that the inequality holds for all large natural numbers (i.e. every natural number larger than some fixed $n_0$), not just one of them.
Answer: You will not be able to show that $f(n)\gt g(n)$, because it is in fact smaller.
What I would suggest is that if $n\ge 6$, then $n-3\ge \frac{n}{2}$, as are $n-2$ and $n-1$. Thus for $n\ge 6$, we have $f(n)\ge \frac{1}{8}g(n)$.  So we can take $C=\frac{1}{8}$.
And $C$ certainly does not have to be an integer. In our particular problem, we cannot even find a positive  integer $C$ with the desired property.
Remark: Dividing by $n^3$ like you did was a good idea, expanding was not. When we divide by $n^3$ we get
$$\left(1-\frac{1}{n}\right)\left(1-\frac{2}{n}\right)\left(1-\frac{3}{n}\right).$$
Now you can take your favourite $n\ge 4$. Let's pick $6$. Then if $n\ge 6$, the above expression is $\ge \frac{5}{6}\cdot \frac{4}{6}\cdot \frac{3}{6}$. We can pick this for our $C$.
Comment: It is a proof. Let's use the version in the remark, since it seems closer to your approach. We have, if $n\gt 0$, that $f(n)=n^3 \left(1-\frac{1}{n}\right)\left(1-\frac{2}{n}\right)\left(1-\frac{3}{n}\right)$. The fact that if $n\ge 6$ then $1-\frac{3}{6}$ probably doesn't require proof. If you think it does, proof is easy. Same with the other inequalities. So if $n\ge 6$, then $f(n)\ge (5/6)(4/6)(3/6)=5/18$. Therefore if $n\ge 6$ and $C=5/18$, then $f(n)\le Cn^3$. Finished! Unfortunately, other expressions require different estimates. Bounds need not be *sharp* (best possible), just correct.
Comment: Something left out in above, second line. Want "$\dots$ if $n\ge 6$, then $1-\frac{3}{n}\ge 1-\frac{3}{6}$ probably $\dots$".
Answer: $f(n)$ should never be greater than $n^3$, because it's the product of three positive numbers each of which is less than $n$.  But you don't need to prove that it's greater than $n^3$; just that it's greater than some multiple of $n^3$.  Rather than use your approach, I would suggest picking a value of $C$ and then choosing a $n_0$ to match.  The choice of $C=\frac18$ is particularly straightforward here; can you understand the circumstances under which $(n-1)(n-2)(n-3)$ must be greater than $\frac{n}2\cdot\frac{n}2\cdot\frac{n}2$?  (Hint: $n-1\gt n-3$ and $n-2\gt n-3$)  Once you can figure out when that holds, then you have your $n_0$ and your $C$ so you should be all set.
Answer: Your claim is that $n_0=7$ and $C=1$ work: that if $n>7$, then $f(n)\ge g(n)$, but you haven't actually proved it. And you cannot possible prove it, because
$$\frac{f(n)}{g(n)}=\frac{(n-1)(n-2)(n-3)}{n^3}=\frac{n-1}n\cdot\frac{n-2}n\cdot\frac{n-3}n<1^3=1\tag{1}$$
for all $n\ge 1$, and therefore $f(n)<g(n)$ for all $n\ge 1$.
You want to find $n_0$ and $C>0$ such that $f(n)\ge Cg(n)$ whenever $n>n_0$. Since $g(n)\ne 0$ when $n\ge 1$, this amounts to wanting a $C>0$ such that $\frac{f(n)}{g(n)}\ge C$ whenever $n>n_0$. In view of $(1)$, any such $C$ is going to have to be less than $1$, since $\frac{f(n)}{g(n)}$ is always less than $1$.
As you already computed, we do have
$$\frac{f(n)}{g(n)}=\frac{n^3-6n^2+11n-6}{n^3}=1-\frac6n+\frac{11}{n^2}-\frac6{n^3}\;.$$
Let's find something smaller than this that is still positive, at least when $n$ is large enough. I'll do it by progressively increasing the amount that I'm subtracting from $1$ on the righthand side, thereby making the difference smaller, and at the same time making the expression on the righthand side simpler:
$$\begin{align*}
\frac{f(n)}{g(n)}&=1-\frac6n+\frac{11}{n^2}-\frac6{n^3}\\\\
&>1-\frac6n-\frac{11}{n^2}-\frac6{n^3}\\\\
&>1-\frac{11}n-\frac{11}{n^2}-\frac{11}{n^3}\\\\
&=1-11\left(\frac1n+\frac1{n^2}+\frac1{n^3}\right)\\\\
&\ge1-11\left(\frac1n+\frac1n+\frac1n\right)\\\\
&=1-\frac{33}n
\end{align*}$$
whenever $n\ge 1$. And now I see that if $n\ge 34$, then
$$\frac{f(n)}{g(n)}\ge 1-\frac{33}{34}=\frac1{34}\;.$$
In other words, I've proved that if $n\ge 34$, then $f(n)\ge\frac1{34}g(n)$. This shows that $f(n)$ really is $O\big(g(n)\big)$.
(To answer the last question, $C$ can be any positive real number; it need not even be rational, let alone an integer.)


How can I prevent the ::before pseudo element from affecting my flex layout?

Question: I have a header on my website, which uses display: flex. Inside it, there are three elements, a heading, an image (nested inside a div so that I can make use of a certain type of CSS image filtering) and a vertical nav.
The heading and nav have flex: 0, whereas the image has flex: 1, so it gets bigger as my display gets wider, as intended.
The nav items have a ::before pseudo element that appears on hover. When it appears, it takes up space and so my image shrinks varying amounts when I hover over the nav items and it makes my page look glitchy. How can I make it so that the ::before pseudo element does not make the image shrink when it appears? Is this even possible? Or do I need to switch to using an actual element that gets made visible when I hover?
I have tried using absolute positioning on the ::before element but then when I try to move it using the left property, it disappears.
https://codepen.io/pen/?template=BamyEYW

header {
  margin-block-start: 3em;
  padding-bottom: 0.67rem;
  padding-left: 5%;
  padding-right: 5%;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
}

nav {
  margin-left: auto;
}

nav ul {
  list-style: none;
  display: flex;
  flex-direction: column;
  padding-inline-start: 0;
  padding-left: 1em;
}

nav ul li {
  text-align: right;
  font-size: x-large;
}

nav ul li a:hover {
  color: red;
}

nav ul li.internal-nav.selected::before {
  content: '> ';
  color: rgba(0, 0, 0, 0.6);
}

nav ul li.internal-nav:hover::before {
  content: '> ';
  color: red;
}

h1 {
  color: rgba(0, 0, 0, 0.6);
  font-size: 5em;
}

.profile-photo3 {
  position: relative;
  flex: 1;
  min-width: 20rem;
  background-color: blue;
  clip-path: polygon(70% 0%, 100% 50%, 70% 100%, 0% 70%, 20% 15%);
}

.profile-photo3 img {
  width: 100%;
  mix-blend-mode: screen;
}

Page Title

About Me

Experience

Lab

Answer: You can update your pseudo element, like this:
nav ul li.internal-nav.selected a:before,
nav ul li.internal-nav a:hover:before {
  content: '> ';
  position: absolute;
  left: -1rem;
  color: red;
}

nav ul li.internal-nav.selected a:before {
  opacity: .6;
}

Run code snippet and open it on fullpage to see changes.
Also you can check it here (Codepen.io)

header {
  margin-block-start: 3em;
  padding-bottom: 0.67rem;
  padding-left: 5%;
  padding-right: 5%;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
}

nav {
  margin-left: auto;
}

nav ul {
  list-style: none;
  display: flex;
  flex-direction: column;
  padding-inline-start: 0;
  padding-left: 1em;
}

nav ul li {
  text-align: right;
  font-size: x-large;
}

nav ul li a:hover {
  color: red;
}

nav ul li.internal-nav a {
  position: relative;
}

nav ul li.internal-nav.selected a:before,
nav ul li.internal-nav a:hover:before {
  content: '> ';
  position: absolute;
  left: -1rem;
  color: red;
}

nav ul li.internal-nav.selected a:before {
  opacity: .6;
}

h1 {
  color: rgba(0, 0, 0, 0.6);
  font-size: 5em;
}

.profile-photo3 {
  position: relative;
  flex: 1;
  min-width: 20rem;
  background-color: blue;
  clip-path: polygon(70% 0%, 100% 50%, 70% 100%, 0% 70%, 20% 15%);
}

.profile-photo3 img {
  width: 100%;
  mix-blend-mode: screen;
}

Dogs :)

About Dogs

My Fav Dogs

Dog Facts

Comment: I really appreciate your answer, it showed me that I was missing the `position: relative` which is why that attempt did not work for me at all when I tried it. However, this results in the pseudo element appearing at the same horizontal position, such that there is a gap  of varying size between the pseudo element and the text, depending on the length of the different (right-aligned) nav items. I want it to be closer to the text, like a console output.
Comment: @krasi run it again, I've made some updates in snippet, so each '>' appearing close to text
Comment: Thank you, its exactly what I was looking for :)
Comment: You are welcome)
Answer: The core issue here is:

The size of the image depends on the width of the nav
The width of the nav changes

One of those has to go.
I'm assuming you want to keep the first and remove the second.
You can't make a ::before-element take up space when the style that creates it is not enganged, so the remaining (simple) strategies I can think of are:

Reserve space for the marker all the time (as you suggest in your answer)
Make the marker take up space all the time (as you suggest in your question)
Make the marker take up no space all the time (like @yaroslav-trach suggests)

#1 lets you continue to base it on ::before, but is a bit brittle since it involves guesswork/knowledge of font witdth etc.
#2 is very robust, and can still be done in pure css.
#3 is in between: you still need to get the width right, but if you miss it only affects the look of the marker, not the rest of the layout
Answer: Seeing as the nav items are unlikely to change, or if they change they will change to set values, it is fine to set the min-width of the nav to leave enough space for the ::before pseudo element, e.g. min-width: 12em.
Answer: add a max-width: (suggesting 65rem) to profile-photo3 to stop the photo shrinking the max width will never get larger than the appointed size though.
Comment: While this technically works, I do not want to limit the growth of the image. I do not like the gap that appears to the right of the image when the screen gets wider and the image stops growing.


How do I run FlyWay clean with Spring Boot?

Question: I'm using Spring Boot and FlyWay together.  I added the FlyWay dependency to my Gradle build file like this:
dependencies {
    compile("org.springframework.boot:spring-boot-starter-data-jpa")
    compile("org.springframework.boot:spring-boot-starter-web")
    compile("org.postgresql:postgresql:9.4-1202-jdbc42")
    compile("org.flywaydb:flyway-core")
    testCompile("org.springframework.boot:spring-boot-starter-test")
}

I also added a db/migrations folder with an initial migration file.  The migration works as expected.  But now I want to clean by using the gradle flywayClean task.  However, when I run this, I get an error saying the task can't be found.  Is there another way I'm supposed to do this with Spring Boot?
Answer: To run gradle flywayClean, you have to apply the plugin: 'org.flywaydb.flyway'
See http://flywaydb.org/getstarted/firststeps/gradle.html
Comment: Updated link: https://flywaydb.org/documentation/getstarted/firststeps/gradle


Signatures of symmetric $2 \times 2$ matrices.

Question: I've never seen the term signature of a matrix before this exercise I'm given, and understand it simply means the number of positive eigenvalues.
Anyway:
Let $A_1, A_2$ be real invertible symmetric $2 \times 2$ matrices. I need to determine the possible values for their signatures, and also prove that if they're not congruent, they're simultaneously congruent to diagonal matrices.
Pretty helpless here..
Comment: No, the signature is **not** the number of positive eigenvalues.  It is the numbers of positive, negative and zero eigenvalues (for a real symmetric matrix): different authors might put these in different orders.  However, if the matrix is invertible it's determined by the number of positive eigenvalues.
Comment: See [Sylvester's law of inertia](https://en.wikipedia.org/wiki/Sylvester's_law_of_inertia)
Answer: Hint: one of $A$ and $B$, let's say $A$, is similar to (and WLOG may be considered equal to) either $I$ or $-I$. You can explicitly solve the equations
$$(S^T S)_{1,2} = 0,\ (S^T B S)_{1,2} = 0 $$


What happens when a soccer player intentionally catches the ball with their hands in front of the goal?

Question: With the defending player not being but acting like a goalkeeper, and assuming the ball would have clearly gone in otherwise.
Can the referee award a goal in this case, even if the ball didn't go in?
Comment: Appreciating the interest of such situations and the rules involved, please take discussion of them to [a chatroom for this purpose](https://chat.stackexchange.com/rooms/138526/discussion-on-answer-by-shoover-what-happens-when-a-soccer-player-intentionally), rather than using comments on the Q&A here. Thank you all in advance.
Comment: @Nij The chatroom link is to chat about one of the answers, not the chat under this question
Comment: That discussion was not about the answer but in general around the situation, hence the movement to chat, and hence the direction to continue off-point discussion there. @StrangerToKindness
Answer: You can't award a goal without the ball crossing the line. The correct decision would be a penalty and a red card for that player for denying a clear goal opportunity.
Law 12:

Sending-off offences A player, substitute or substituted player who
commits any of the following offences is sent off:
denying the opposing team a goal or an obvious goal-scoring
opportunity by a handball offence (except a goalkeeper within their
penalty area)
Answer: No. A goal is not awarded automatically. The offensive team is awarded a penalty kick.
From the FIFA Laws of the Game:
Law 10 - Determining the Outcome of a Match

A goal is scored when the whole of the ball passes over the goal line, between
the goalposts and under the crossbar, provided that no offence has been
committed by the team scoring the goal.

In your case, the ball has not passed over the goal line, so no goal has been scored.
Laws 14 and 12 determine what should happen.
Law 14 - Penalty Kick

A penalty kick is awarded if a player commits a direct free kick offence inside
their penalty area or off the field as part of play as outlined in Laws 12 and 13.

Law 12 - Fouls and Misconduct

A direct free kick is awarded if a player commits any of the following
offences:
• a handball offence (except for the goalkeeper within their penalty area)

Also in Law 12

Handling the ball
It is an offence if a player:
• deliberately touches the ball with their hand/arm, including moving the
hand/arm towards the ball

Putting these together, if a player who is not the goalkeeper deliberately plays the ball with their hand/arm in their own penalty area, a penalty kick shall be awarded to the other team.
Comment: You forgot that the offending play should be sent off for DOGSO.
Comment: Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackexchange.com/rooms/138526/discussion-on-answer-by-shoover-what-happens-when-a-soccer-player-intentionally).
Answer: No, the referee can not award a goal in this case, and the player must be red-carded.
Maybe the most famous case of this was the action of Luis Suarez from Uruguay Selection, making exactly what you ask in 2010 world cup vs Ghana (if I remember well).
He was expelled, but in the end the penalty was not converted and Uruguay won the game, So Suarez movement was interesting to me. He interchanged a red card for the possibility of the other team fail a goal that, other way, was obvious.
Answer: To quote the rules

Where a player denies the opposing team a goal or an obvious goal-scoring opportunity by a deliberate handball offence the player is sent off wherever the offence occurs.

So, that player would get a red card.  Assuming it happens inside the penalty area, the other team also gets a penalty kick.  It doesn't sound as if this would happen outside the penalty box, but if it did, that would be a free kick (from a dangerous position, since you say the shot from there would surely have gone in before).


What is the population minimizer for Huber loss

Question: Suppose we make predictions for a continuous outcome $Y$ conditional on a vector of covariates $X$.  If we use mean squared error loss (MSE), the population minimizer is $\mathbf{E}[Y \;|\; X]$. If instead we use mean absolute error as our loss function (MAE), the population minimizer is the conditional median.
What is the population minimizer for Huber loss?  For example, if I fit a gradient boosting machine (GBM) with Huber loss, what optimal prediction am I attempting to learn?

See The Elements of Statistical Learning (Second Edition), 2.4 Statistical Decision Theory for the population minimizers under MSE and MAE, and section 10.6 Loss Functions and Robustness for a definition of Huber loss:
$\begin{equation*}L(y, \,f(x)) = \begin{cases}(y -
 f(x))^2 \text{ if } \lvert y - f(x) \rvert \leq \delta  \\ 2\delta \, \lvert y - f(x) \rvert - \delta^2 \text{ otherwise}\end{cases}\end{equation*}$
Comment: It doesn't have closed form -- the estimates are obtained iteratively; however it's *sort* of analogous to a trimmed mean, at least in a particular sense.
Comment: Not really any reference that would state it explicitly (that I can think of). More generally, outside of the classic works by Huber and Hampel et al and some of the papers around that era, which should give you some of the tools you need to see why I said that (like looking at influence functions), I can't think of a reference off the top of my head. I could perhaps write something up about empirical influence functions later.
Comment: Do you have a reference you could point me to? I'd happily accept your comment plus a reference as an answer.
Answer: The sample Huber estimator doesn't have closed form -- the estimates are obtained iteratively. However it's sort of analogous to a trimmed mean, at least in a particular sense.
If it were applied to the whole population it's essentially going to come down to a mean of values between two quantiles ($x_{\alpha_1}=F_X^{-1}(\alpha_1)$ and $x_{1-\alpha_2}$) but which quantiles those are depends on the particulars of the distribution and the specifics of the Huber spread estimation and value of $k$. (In the general case those quantiles won't be symmetric -- i.e. typically $\alpha_1\neq \alpha_2$).
Specifically, consider the influence function. In this case we'll look at something closely related to (and similar in appearance to) the empirical influence function, which in this example is simply the estimate itself but where the sample is taken to be a set of expected normal order statistics (or rather, approximations to them, though it hardly matters), plus an additional observation that's allowed to vary across the real line. I'll call this the influence function, but strictly speaking it would need to be adjusted (by things that won't change the general appearance). The population influence functions will be similar in general appearance.
One advantage of using the empirical function on a sample made to be about as much like we'd expect the population to look (expected quantiles) is that we can give the flavor of what's going on with something that will behave very like the population equivalent while avoiding introducing Gateaux derivatives. For details on those see the references.
With them we see how the two estimates respond to a changing observation:

These are quantitatively very similar - indicating that the two respond very similarly to a small proportion of outliers (below $\alpha$ for the trimmed mean) for a fairly symmetric sample. However, there are differences in how they respond -- if you get more extreme outliers, the Huber will effectively "trim" a greater percentage, e.g. for a very skewed sample it would act more like an asymmetric trim for example, in effect "trimming" little or nothing from the "light-tailed" side but "trimming" heavily on the heavy-tailed side and if both tails got very heavy it would act as if it was trimming more.
Here's some R code, because someone will want it:
<code>library(MASS)

opar = par()
par(mfrow=c(1,2),cex.main=1)

xn=seq(-4,4,l=201)
x=qnorm(ppoints(19,a=3/8))
f=function(xc,x) mean(c(x,xc),trim=0.05)
f2=function(xc,x) huber(c(x,xc),k=1.95)$mu
infl=sapply(xn,f,x=x)
plot(infl~xn,type="l",xlim=c(-4,4),col="blue3",main="Trimmed mean empirical IF")
inflh=sapply(xn,f2,x=x)
plot(inflh~xn,type="l",xlim=c(-4,4),col="blue3",main="Huber empirical IF")

par(opar)
</code>

As for references, the classic ones are the books by Huber [1] and Hampel et al. [2]. There's a little on M-estimation in the first 4 pages here. The wikipedia page is a bit sparse but may help.
A caveat: a number of references claim that the influence for trimmed means redescend. As we see by actually doing it, this is not so (and it's easy to see why -- trimmed means don't completely ignore observations that are trimmed, since we count how many are each side and that continues to pull the resulting estimator no matter how far away the observation may get).
[1] Huber, Peter J. (1981), Robust statistics, New York: John Wiley & Sons, Inc., ISBN 0-471-41805-6, MR 606374.
(Republished in paperback, 2004. 2nd ed., Wiley)
[2] Hampel, Frank R.; Ronchetti, Elvezio M.; Rousseeuw, Peter J.; Stahel, Werner A. (1986), Robust statistics, Wiley
Answer: Brilliant answer by Glen_b, the empirical influence curve (aka sensitivity curve, or SC) is much easier for non-specialists to understand than the true influence curve (IC) based on Gateaux derivatives, as Glen says. May I recommend a more modern book than the two classics Glen cited (both of which I own and have read over-and-over, but now reach for the following instead): "Robust Statistics, Theory and Methods", by Maronna, Martin, & Yohai (Wiley, 2006). There is a proof in the book that the IC is indeed the correct asymptotic form of the SC. You can trust this book -- the authors are very well-respected, accomplished experts in this field. If instead you really want all the rigorous mathematical details, read: http://j-kahn.com/files/influencefunctions.pdf . I know the guidelines say "don't respond to other answers", but I really had to tip-the-hat to Glen_b.


A sitewide solution to protect input fields in PHP

Question: I have recently started work at a company that has a website. The previous programmers have not used any protection whatsoever on the input fields. Now I need to do something. The site consists of hundreds of PHP files included in just two files (index.php and main.php - first one for visiting users, second one-for registered). Is there a way to protect all of the fields in all of the files trough code that is only contained within those two files? Otherwise I'd have to edit every single PHP file which would take like.. a month.
Comment: I'd get started editing those PHP files.
Comment: possible duplicate of [PHP secure user variable](http://stackoverflow.com/questions/3538353/php-secure-user-variable)
Answer: It depends on what you mean by protection.
If the user input is passed directly to unparameterized SQL statements, you will have one set of problems due to SQL injections. If the input is written directly back to HTML output, you will have another set of problems due to XSS, etc.
Any quick global fix such as heximal's suggestion is probably going to result in errors such as double encoded data in your database or web pages. Of course, this could very well be a lesser evil than having your site taken down by hackers. Also note that it takes much more than just escaping the <code>'</code> character.
In the end, the proper solution for these kinds of vulnerabilities is to fix it in the vulnerable component. SQL injections should be fixed by using a proper database abstraction layer with parameterized statements. HTML output should be HTML-encoded when constructing the HTML view, preferably by using a view engine that does this by default. This is not to say that input should not be validated, but that validation cannot stand on its own.


Chamada de função ``

Question: Atualmente estou estudando WebComponents, Polymer, LitElement e afins e me deparei com essa característica da criação do template usando LitElement que eu nunca havia visto:
html`<div>Teste</div>`

O mesmo vale para CSS:
css`div {color: blue}`

O código pode ser conferido aqui e o resultado aqui
Tentando entender melhor como funciona essa declaração js fui no código fonte e descobri que não passa de uma função diferentona:
/**
 * Interprets a template literal as an HTML template that can efficiently
 * render to and update a container.
 */
export const html = (strings: TemplateStringsArray, ...values: unknown[]) =>
  new TemplateResult(strings, values, 'html', defaultTemplateProcessor);

Então tentei implementar algo do tipo pra entender como funciona:

html = (t, i) => {
  console.log(t, i);
  console.log(typeof t, typeof i);
}

html('teste');

html`teste`;

No console aparece:

O que me fez entender menos ainda essa declaração:
<function>`<parameter>`

Onde eu passo uma string e na verdade eu recebo um objeto que parece um array.... afinal, do que se trata essa declaração? E como atingir a segunda variável da função? Quais são os reais benefícios e quando devo usar esse tipo de declaração? Tem alguma coisa a ver com String.raw()?
Answer: Essa notação é chamada de tagged template. Quando a função é invocada com essa notação, a string recebida é transformada num array utilizando os placeholders ${} como delimitadores, e os valores dentro dos delimitadores são passados como os demais parâmetros.
Ou seja:

function log(strings, ...values) {
  console.log(strings, values)
}

log `<ul> <li>${123}</li> <li>${456}</li> </ul>`

Irá gerar uma lista contendo

,

 e

 em strings, e todos os demais valores serão coletados em values por causa do operador ..., gerando uma lista contendo 123 e 456.

Qual a vantagem disso?
Você pode criar uma função "middleware" para ser executada antes do Javascript atribuir os valores dos placeholders na sua string literal.

function toUpper(strings, ...values) {
  var upperValues = values.map(v => v.toUpperCase())
  return String.raw(strings, ...upperValues)
}

var company = "Alfreds Futterkiste"
var contact = "Maria Anders"
var country = "Germany"

var template = toUpper `

    ${company}
    ${contact}
    ${country}

`

console.log(template)

Não é um exemplo terrivelmente útil, você também poderia chamar o método toUpperCase manualmente em cada variável, mas essa é a ideia.

Outro caso de uso clássico é escapar tags HTML prevenindo ataques de XSS, exemplo retirado daqui:

function sanitize(strings, ...values) {
  const dirty = strings.reduce((prev, next, i) => `${prev}${next}${values[i] || ''}`, '');
  console.log(dirty);
  console.log(aboutMe);
  return DOMPurify.sanitize(aboutMe);
}
const name = 'petyr baelish';
const aboutMe = `I love to do evil <img src="http://unsplash.it/100/100?random" onload="alert('I hacked you. Haha');" />`;
const html = sanitize `

${name}

${aboutMe}

  `;

console.log(html);

Chamada de função ``


Link de torrent (magnet) com contador

Question: Oi, tem como fazer download de links magnet via php como se fosse o modo normal?
Preciso contar quantas vezes o arquivo foi baixado. Tentei fopen(), file_get_contents() e header("Location: "), que também e não deu certo:
Warning: fopen() expects at least 2 parameters, 1 given in C:\xampp\htdocs\gamepatch\download2.php on line 4

e também
Warning: file_get_contents(magnet:?xt=urn:btih:ed4fad95b4cb): failed to open stream: No such file or directory in C:\xampp\htdocs\gamepatch\download2.php on line 4

Tentativa:
<?php
   include "bd_connect.php";

   $arquivo = $_GET["arquivo"];
   header("Location: $arquivo");
?>

Answer: A página do link ficaria assim:
<?php
   $link = urlencode( 'magnet:?xt=urn:btih:ed4fad95b4cb' );
   echo 'Clique para baixar'
?>

E a página contador.php, assim:
<?php
   $link=$_GET['link'];
   ... código do seu contador vai aqui ...
   header( "Location: $link" );

?>

Partindo destes modelos, basta acrescentar a lógica desejada, ou base de dados de links nas páginas dos links para download e do contador.
Comment: valew!!!!!!!!!!

Link de torrent (magnet) com contador


How to produce separate scatter plots for each data in python?

Question: I have list of lists where each list represent as a feature vector :
Matrix=[[12,43,65,78,54,43,76,98],
[23,465,90,9,32,75,324,12],
[67,43,21,56,32,7,4,9],
[3,9,0,67,23,12,65,97]]

i also have another feature vector as fvector:
fvector=[54,76,12,55,88,75,32,3]

I want to plot a scatter plot for each list of a matrix with fvector separately but when i tried plotting by iterating over each list then it plots on the same graph:
I tried this:
import matplotlib.pyplot as plt
for i in Matrix:
    plt.scatter(i,fvector)

Output that i got is :

but i want each matrix plot separately ,and is it possible to plot small separate graphs ?
Any reference or resource will be helpful.
Thanks
Comment: Just call `plt.figure()` before `plt.scatter()`
Answer: You can use the subplots to create multiple plots on the same figure.
for i, item in enumerate(Matrix,1):
    plt.subplot(2, 2, i)
    plt.scatter(item, fvector)
plt.show()

If we have more than four lists in the Matrix then we can divide them into groups of four and generate separate figures for each set of 4 lists. Please check below:
for j in range(0, len(Matrix), 4):
    for i, item in enumerate(Matrix[j:j+4],1):
        plt.subplot(2, 2, i)
        plt.scatter(item, fvector)
    plt.show()

Hope this helps!!
Comment: Then you just need to change plt.subpot(2,2,i) to plt.subplot(5,2,i) or plt.subplt(2,5,i). In other words you would need to find two values n and m such that n*m is equal to the length of Matrix list.
Comment: Thanks ,but what if i have 10 lists in Matrix.Its giving ValueError: num must be 1 <= num <= 4, not 5......how can i plot 2 or 3 graphs in each row .?
Comment: but it also reduce the size
Comment: I see. I guess then you should divide the Matrix into groups of 4 lists and keep generating the Plots.
Comment: like how can we do that ?will you please help me out
Answer: for i in Matrix:
    plt.scatter(i,fvector)
    plt.show()

Should do it
Answer: You need to use multiple axes using subplots
fig, ax = plt.subplots(2)

And the plot will look something like:
axs[0].plot(x1, y)
axs[1].plot(x2, y)


Ansible throws an " ERROR! A worker was found in a dead state " error

Question: When I run a playbook that simply copies a directory from one place to another, ansible throws

ERROR! A worker was found in a dead state

Error. After some googling, it looks like this is caused by the oom-killer killing the ansible process (but i'm not exactly sure that this is the case). My Memory is:
              total        used        free      shared  buff/cache   available
Mem:            991         372         448           1         170         467
Swap:           511         365         146

I don't have a clue how to fix it. I should mention I only had the RAM when I first executed the playbook, which couldn't run cause of low memory. After that, I added the swap.Not sure if it's related but note that it's a swap file, not a separate partition.
I've watched the memory while running and I see that the free swap goes down very fast once it runs that task. The error message is thrown when it hits 0.

I'm running the following playbook.
---
- hosts: localhost
  become: true
  become_method: sudo
  become_user: root

  vars:
    portals:
      - mysite
    contentPath: "/var/www/"
    backupPath: "/home/dataFiles/backups/"

  tasks:

    - name: backup content
      copy:
        src: "{{ contentPath }}/{{ item }}"
        dest: "{{backupPath}}/{{ item }}/{{ ansible_date_time.date }}/"
      with_items:
        - "{{ portals }}"
...

The error I've given above is the only info I get out of ansible. Even running the playbook verbosely doesn't give anything additional for that.
Comment: Update: added 2 GB of swap. It still runs out when the command is run.
Comment: You should add the task which throws the error and the complete error message returned by Ansible.
Comment: @HenrikPingel Thanks for the response. Added the info.
Comment: Look on your logs. Read up on [ansible debugging](https://www.google.co.uk/search?q=ansible+debugging). Pfovide more information.
Comment: Yes, you need to run your `ansible-playbook` command with `-vvv`. You should also add your ansible version with `ansible --verison`
Comment: If there are many files under `portals` you might want to check if the [synchronize](http://docs.ansible.com/ansible/synchronize_module.html) module works better for you. Its a wrapper around rsync.
Answer: There is a note in the copy_module documentation:

The "copy" module recursively copy facility does not scale to lots (>hundreds) of files. For alternative, see synchronize module, which is a wrapper around rsync.

Assuming this is the case here one should consider using the synchronize module.
Answer: This solved my issue:
export OBJC_DISABLE_INITIALIZE_FORK_SAFETY=YES

Answer: Something like this works for me:
env no_proxy='*' ansible-playbook collect-facts.yml
You can also add export no_proxy="*" to your .bashrc or .zshrc, so you don't need to type it every time.
More detail on this : https://www.whatan00b.com/posts/debugging-a-segfault-from-ansible/
(Credit: https://github.com/ansible/ansible/issues/32554#issuecomment-572985680)
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).
Comment: The relationship with the question is unclear. A segfault is not an oom-killer event.
Answer: I had the same error, but I was not using the copy module in any task.
In my case the problem was that the machine (on which was running the ansible task when the error appeared) was run out of memory.
I checked it out by launching the playbook and then in another terminal launching htop and monitoring how the RAM and the SWAP were filling up as the execution of the playbook was going on.
I solved it by increasing the RAM of the machine which was failing.
(Increasing the SWAP would not be so effective since it is not a random access memory but disk memory, so the "computational power" given by 1GB of SWAP is way less thant the one given by 1GB of RAM.)

Ansible throws an “ ERROR! A worker was found in a dead state ” error


How can I change array items?

Question: I have an array containing links. I am trying to cut a part of those links. For example:
$array = [
  "https://eksisozluk.com/merve-sanayin-pizzaciya-kapiyi-ciplak-acmasi--5868043?a=popular",
  "https://eksisozluk.com/merve-sanayin-pizzaciya-kapiyi-ciplak-acmasi--5868043?a=popular"
];

I want change these links like below:
array(2) {
  [0]=>
  string(91) "https://eksisozluk.com/merve-sanayin"
  [1]=>
  string(91) "https://eksisozluk.com/merve-sanayin"
  [2]=>
}

Is there any possible way to edit array items?
Comment: `array_map()` will iterate the array, as will a `for()` or a `foreach()` loop.
Comment: Hi Barbie, welcome on Stack overflow. you can use `array_walk` or `array_map` along with `str_replace` or `preg_replace`.
Comment: And then you can handle each entry one by one and reassign whatever value you want.
Comment: @Barbie  a better solution is:- https://3v4l.org/S4VU1
Answer: Given the array:
$array = [
    "https://eksisozluk.com/merve-sanayin-pizzaciya-kapiyi-ciplak-acmasi--5868043?a=popular",
    "https://eksisozluk.com/merve-sanayin-pizzaciya-kapiyi-ciplak-acmasi--5868043?a=popular"
];

Using array_walk() (modifies the array in place).
Using a regular expression this time:
function filter_url(&$item)
{
    preg_match('|(https:\/\/\w+\.\w{2,4}\/\w+-\w+)-.+|', $item, $matches);
    $item = $matches[1];
}

array_walk($array, 'filter_url');

(See it working here).
Note that filter_url passes the first parameter by reference, as explained in the documentation, so changes to each of the array items are performed in place and affect the original array.
Using array_map() (returns a modified array)
Simply using substr, since we know next to nothing about your actual requirements:
function clean_url($item)
{
    return substr($item, 0, 36);
}

$new_array = array_map('clean_url', $array);

Working here.

The specifics of how actually filter the array elements are up to you.
The example shown here seems kinda pointless, since you are setting all elements exactly to the same value. If you know the lenght you can use substr, or you could just could write a more robust regex.
Since all the elements of your input array are the same in the example, I am going to assume this doesn't represent your actual input.
You could also iterate the array using either for, foreach or  while, but either of those options seems less elegant when you have specific array functions to deal with this kind of situation.
Comment: Good demonstration of those methods. You might want to point out that the ampersand `&` is needed for array_walk() to modify the value and explain that it means `$item` is a reference.
Answer: There are multiple ways. One way is to iterate over the items and clip them with substr().
$arr = array("https://eksisozluk.com/merve-sanayin-pizzaciya-kapiyi-ciplak-acmasi--5868043?a=popular",
"https://eksisozluk.com/merve-sanayin-pizzaciya-kapiyi-ciplak-acmasi--5868043?a=popular");

for ($i = 0; $i < count($arr); $i++)
{
    $arr[$i] = substr($arr[$i], 0, 36);
}

Comment: it will not work if count changed from 36 .(no of characters counted before second -) .Check here:- https://3v4l.org/a4GQo

How can I change array items?


Prime Factorization of Large Numbers

Question: Recently, I have been required to compute the Prime Factorization of large numbers.
For instance,
$5^9 -1 $
I know that it ends in a $4$, so can be divided by $2$. Then can be divided by $2$ again, but this creates a factor tree which is what I am looking to avoid.
How would I go about prime factorising this?

By my factor tree method I get to $2\times 2\times 19\times 31\times 829$. But I had to type into the internet whether $829$ was a prime, so I immediately run into a problem.
Any help or ideas would be appreciated!
Comment: It's not that difficult to check whether $829$ is prime by hand. $\sqrt{829}<30$, so you only need to check the primes up to $30$. It seems a lot harder to find the prime factors of $\frac{5^9-1}{2^2}$ by hand
Comment: Unfortunately, the question of "how to factor large numbers" is an incredibly broad and difficult question, although it's quite fast to do with a computer for small numbers. You might want to start [here](https://en.wikipedia.org/wiki/Integer_factorization) or with a book on elementary number theory or cryptography, but I think this question is too broad.
Comment: @VáclavMordvinov This is the problem. This could come up in an exam where I am only equipped with a calculator. I am thinking there must be a simple way to do it and I am overlooking it
Answer: What you are attempting to do is called prime factorization (Yes, that is in the title).
In order to determine if $829$ is a prime number or not, I would use trial division:

If the number $829$ is not divisible by any prime number that is less that $\sqrt{829}$ than the number $829$ is prime.

By using your factor tree method, you have factored it to $2\times 2\times 19\times 31\times 829$.
At this point, if you are doing it right (test the divisibility of $5^9-1$ starting from the smallest prime number, which is $2$), then the number $829$ is not divisible by any prime numbers from $2$ to $31$. Because $31^2=961>829$, that is enough to show that $829$ is a prime number.
Comment: Using a calculator: $(5^9-1)\div 2=976562$ (I would recommend to write those number down in a rough paper); $976562\div 2=488281$, no longer divisible by $2$, check $3$; $488281\div 3$ will not yield an integer result... Continue for $5;7;11;13;17;19$ and you will see that dividing by $19$ now yields an integer result (that number is not too big for a $10$-digit calculator).
Comment: Thanks for explaining the prime number check :) I have a follow up question - The question has been written as $ 5^9 -1 $ for a reason, so what method would you use the solve this question?
Comment: To reduce the number of calculator steps: Note that a natural number is divisible by $2$ if and only if the last digit is even. A number is divisible by $3$ if and only if the sum of all digits is divisible by $3$. A number is divisible by $5$ if and only if the last digit is $0$ or $5$.
Answer: no truly simple way. You have
$$ x^9 - 1 = (x-1)(x^2 + x + 1)(x^6 + x^3 + 1) $$
As the third factor is also of the form $u^2 + u + 1,$ it can only be divisible by primes $p \equiv 1 \pmod 3 \; ,$ more specifically $p \equiv 7 \pmod 6 \; .$ Once you get to $15751$ and find that it is not divisible by $7,13,$ you get a bit of luck with $19.$ The leftover is $829.$ It is not divisible by $19$ or $31,$ and that is it. You have exceeded $\sqrt {829} \approx 28.7$ so $829$ is prime.
In case of interest, this has to do with quadratic residues.
Comment: How did you know that was the factorisation? Did you use the roots of unity?

Prime Factorization of Large Numbers


All shell scripts dropping back to command line

Question: I'm probably doing something remarkably stupid, but I can't figure out what.
Running Ubuntu Server 12.04 on a cloud host (Digital Ocean, if it matters). All shell scripts do absolutely nothing and just return immediately to the prompt, without error, warning or even a wag of the middle finger.

start-stop-daemons scripts will not run from command line with "./script-name", not just cron
execute bit is set
shell is /bin/bash
user is root
tried changing #!/bin/sh to #!/bin/bash
tried not using dash by dpkg-reconfigure dash
scripts are being parsed -- if I edit it to something illegal, I get errors

Running out of ideas...
Is there some reason I just wouldn't be seeing the output?
Comment: Can you execute `strace -f`, its output might be useful.
Answer: Try to debug the shell script, here is how
Put that after the #!/bin/bash line
logfile=/tmp/script.log
exec > $logfile 2>&1

then execute the script with this command from shell prompt.
# bash -x script-name.sh

See what happens next, check to see if the commands written in script are getting executed.
Also double check the path using this commnad.
echo $PATH

Comment: Thank you! That did it. My binaries had somehow migrated from `/usr/local/bin` to `/usr/bin` and all the scripts just happened to be failing without warning.


How to prevent required field validation in validation function?

Question: Issue: When create a node and node publish check box is checked, all validation should work (it's working fine). but when create a node and node publish check box is not checked , then all validation should skip.
function mymodule_form_alter(&$form, &$form_state) {
   array_unshift($form['#validate'], 'mymodule_reqursive_unrequired');
}

function mymodule_reqursive_unrequired(&$form, &$form_state) {
    // print_r($form);die;
    $form['actions_copy']['submit']['#limit_validation_errors'] = array();
    $form['actions']['submit']['#limit_validation_errors'] = array();

    $form['title']['#required'] = FALSE;
    $blog_images = $form['field_image_blog'][LANGUAGE_NONE];
    $form['field_page_title'][LANGUAGE_NONE][0]['#required'] = FALSE;
    foreach($blog_images as $image_k => $blog_image) {
      $form['field_image_blog'][LANGUAGE_NONE][$image_k]['#required'] = FALSE;
    }
    // print_r($form);die;
}

Any suggestion ?
Comment: Is there any reason why you would want to avoid a non published node is validated? It is only when a node is saved that the node is validated. If you want to save a draft, there are modules for that already.
Comment: yes, want to save as draft without any validation for unpublished content.
Comment: Then, there are modules already doing that; there isn't the need to write a module just for that.
Comment: are you sure the node which is not saved yet that will not be validated? i am already using revisioning module  for moderation work. bdw can you mention the module name
Comment: this functionality is not working for saved content also. ..:( Any suggestion please...
Answer: After a lot of debugging and search i get the solution.
function mymodule_reqursive_unrequired(&$form, &$form_state) {
    // print_r($form);die;
   if(!$form_state['values']['status']) {
     drupal_static('form_set_error', NULL, TRUE);
     drupal_get_messages();
   }
    // print_r($form);die;
}

for reference check it


Using Cypher (Neo4j) within a REST API request (Objective C)

Question: I am trying to query my Neo4j database, using the REST API.
I have this working so far without using the Cypher query language to retrieve data,
however, now I need to get nodes which are sorted by 'newest' i.e. unix timestamp DESC.
I have tried to add the query within the HTTP body of the NSMutableURLRequest but I am just getting the HTTP error 405.
Here is my code:
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@node/%i", EventsManagerDataURL, creatorID]];
NSLog(@"Connecting to URL: %@", url);

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];

NSString *jsonMap = @"{'query' : 'start x  = node(4,6,7) return x order by x.datestart,'params' : {}}";
NSData *jsonData = [jsonMap dataUsingEncoding:NSUTF8StringEncoding];

[request setHTTPMethod:@"POST"];

[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:[NSString stringWithFormat:@"%d", jsonData.length] forHTTPHeaderField:@"Content-Length"];

[request setHTTPBody:jsonData];

[NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error){

    if (data){
        NSLog(@"%s. Data: %@", _cmd, [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
    } else {
        NSLog(@"Error: %@", error.localizedDescription);
    }
}];

Answer: You're missing a single quote here:
NSString *jsonMap = @"{'query' : 'start x  = node(4,6,7) return x order by x.datestart***'***,'params' : {}}";

And actually, it needs to have double quotes:
NSString *jsonMap = @"{\"query\" : \"start x  = node(4,6,7) return x order by x.datestart\", \"params\" : {}}";

Test with cURL:
curl -H Accept:application/json -H Content-Type:application/json -X POST -d '{"query" : "start x  = node(4,6,7) return x order by x.datestart", "params" : {}}' localhost:7474/db/data/cypher

Comment: I'm trying to get my coworker to write an Objective-C REST wrapper for Cypher. Hopefully that will make some of this syntax prettier. :)
Comment: Thanks for your reply, the cURL seems to work, however, I still get the 405 error in my `NSLog` :/
Comment: Make sure your URL is right, too. I've had issues with that before.
Comment: Yeah, the URL was pointing to a node, not the `cypher` path. Thanks!
Comment: Yeah! I've made/making a basic Objective-C class, which I am using, but one made by someone with a lot more experience than me would be great! Please link me to it if you ever convince him!
Comment: Thank you for the help with the curl example. In my case I was missing the POST part.


Proof that difference of Martingale Sequence is a Martingale

Question: $\left\{ Z_{n},n\geq1\right\} $ is a martingale, which means that $\forall n$,
it satisfies the below two conditions,
1) This is the uniformly bounded condition.
$$
E\left[\left|Z_{n}\right|\right]<\infty
$$
2) Standard martingalge condition.
$$
E\left[\left.Z_{n+1}\right|Z_{1},\ldots,Z_{n}\right]=Z_{n}
$$
Question:
How do we prove that $\left\{ Z_{m+k}-Z_{m},m\geq1,k=1,\ldots,n\right\} $ is a martingale?
Context:
This is an omitted step in the proof of the Martingale Convergence Theorem from Stochastic Processes, Second Edition, Sheldon Ross, Theorem 6.4.6, Page 315.
Steps Tried:
$$
\text{Let, }Y_{k}=Z_{m+k}-Z_{m}
$$
$$
E\left[\left.Y_{k+1}\right|Y_{k}\ldots Y_{1}\right]=E\left[\left.Z_{m+k+1}-Z_{m}\right|Z_{m+k}-Z_{m},\ldots,Z_{m+1}-Z_{m}\right]
$$
Comment: What have you tried? Also, you need one more condition on measurability in the definition of martingale.
Comment: @SiXUlm Please note, I am using the definition from Stochastic Processes, Second Edition, Sheldon Ross. I am not aware of the measurability condition. Since this book is mostly a non-measure theoretic approach.  Also, I have added the steps tried above. Please feel free to suggest anything I need to include with full details.
Answer: We'll use the tower property of conditional expectation, and first condition on a larger set of random variables. First since $Z_{m+k}-Z_m,\dots, Z_{m+1}-Z_m,Z_m$ and $Z_{m+k},\dots,Z_m$ determine the same events, we have
$$E [Z_{m+k+1} | Z_{m+k}-Z_m,\dots,Z_{m+1}-Z_m,Z_m]=E[Z_{m+k+1} |Z_{m+k},\dots,Z_m]=Z_{m+k}=(*)$$
By the tower property, to get the conditional expectation of $Z_{m+K+1}$ WRT to the smaller set of variables $Z_{m+k}-Z_m,\dots,Z_{m+1}-Z_m$, we take the conditional expectation of $(*)$ with respect to the latter set (tower property):
$$E[Z_{m+k+1} | Z_{m+k}-Z_m,\dots,Z_{m+1}-Z_m]=E [ Z_{m+k} |Z_{m+k}-Z_m,\dots,Z_{m+1}-Z_m],$$
But this gives
$$E[Z_{m+k+1} - Z_m | Z_{m+k}-Z_m,\dots,Z_{m+1}-Z_m ] = E [ Z_{m+k}-Z_m  |Z_{m+k}-Z_m,\dots,Z_{m+1}-Z_m ] = Z_{m+k}-Z_m,$$
which is what we wanted to show.
Comment: Much appreciative of this clear and complete answer. As I read it, the key was adding $Z_m$ into the conditional expectation and then conditioning on a smaller set without it.


Persistência usando Fluent API

Question: Como faço para persistir um endereço sem ter que passar toda a informação do cliente?
Segue abaixo meu mapeamento de cliente endereco:
HasMany(f => f.EnderecoList)
            .WithMany(e => e.ClienteList)
            .Map(me =>
            {
                me.MapLeftKey("ClienteId");
                me.MapRightKey("EnderecoId");
                me.ToTable("EnderecosCliente");
            });

Answer: O ideal é você não usar a Fluent API, e sim uma entidade associativa:
public class Cliente
{
    /* Propriedades do Cliente */

    public virtual EnderecoCliente EnderecoCliente { get; set; }
}

public class Endereco
{
    /* Propriedades do Endereco */

    public virtual EnderecoCliente EnderecoCliente { get; set; }
}

E então:
public class EnderecoCliente
{
    [Key]
    public int EnderecoClienteId { get; set; }
    [Index("IUQ_EnderecoCliente_ClienteId_EnderecoId", IsUnique = true, Order = 1)]
    public int ClienteId { get; set; }
    [Index("IUQ_EnderecoCliente_ClienteId_EnderecoId", IsUnique = true, Order = 2)]
    public int EnderecoId { get; set; }

    public virtual Endereco Endereco { get; set; }
    public virtual Cliente Cliente { get; set; }
}

Definindo:
var endereco = new Endereco
{
    /* Defina aqui outras propriedades */
    EnderecoCliente = new EnderecoCliente {
        Cliente = contexto.Clientes.FirstOrDefault(c => c.ClienteId == 5)
    }
};

[Index], introduzido nesta forma a partir do Entity Framework 6.1.0, garante a unicidade do registro associativo. Validações adicionais podem ser necessárias na aplicação para evitar erros estranhos de duplicidade de chave para o usuário.
Comment: como ficaria minha model no momento da persistência de um novo endereço , eu teria um list de EnderecoCliente, é isso ?
Comment: Uma lista não. Um único registro.
Comment: Coloquei errado o exemplo. Agora está certo.
Comment: mas a questão é a persistencia, suponha que no momento em que estou cadastrando endereços esse cliente possua 3 ou 4 endereços diferentes. Como persisto isso se o model só recebe um registro ?
Comment: Então, veja se agora ficou mais claro. Eu editei a resposta.
Comment: só pra entendimento eu tenho um cadastro que me diz o seguinte, endereço de cobrança, endereço de entrega, endereço residencial, cada um num lugar diferente , como persistir isso ? Obrigado @CiganoMorrisonMendez
Comment: Então, você cria usando aquela sintaxe que eu coloquei ali em cima. O bloco de criar a associação com o cliente é o mesmo para os 4.
Answer: Do jeito que está mapeando é uma relação de muitos-para-muitos...  se você quiser que um cliente tenha vários endereços tente alguma coisa assim:
    public class ClienteEntity
{
    [Key]
    public int Codigo { get; set; }
    public string Nome { get; set; }
    public virtual HashSet<EnderecoEntity> Enderecos { get; set; }
}

public class EnderecoEntity
{
    [Key]
    public int Codigo { get; set; }
    public string Logradouro { get; set; }

    public int? CodigoCliente { get; set; }
    public virtual ClienteEntity Cliente { get; set; }
}

public class ClienteContext:DbContext
{
    public DbSet<ClienteEntity> Clientes { get; set; }
    public DbSet<EnderecoEntity> Enderecos { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder
            .Entity<ClienteEntity>()
            .HasMany(t=>t.Enderecos)
            .WithOptional(c=>c.Cliente)
            .HasForeignKey(c=>c.CodigoCliente);
    }
}

Com isso é possível preencher vários endereços com um cliente e chegar a partir do endereço no cliente correspondente...

Persistência usando Fluent API


trying to use mod_proxy with httpd and tomcat

Question: I been trying to use mod_proxy with httpd and tomcat...
I have on VirtualBox running Scientific Linux which has httpd and tomcat 6 on it.. I made two nodes of tomcat6.
I followed this guide like 10 times and still cant get the 2nd node of tomcat working..
http://www.richardnichols.net/2010/08/5-minute-guide-clustering-apache-tomcat/
Here is the lines from my http.conf file
<Proxy balancer://testcluster stickysession=JSESSIONID>
BalancerMember ajp://127.0.0.1:8009 min=10 max=100 route=node1 loadfactor=1
BalancerMember ajp://127.0.0.1:8109 min=10 max=100 route=node2 loadfactor=1
</Proxy>

ProxyPass /examples balancer://testcluster/examples

<Location /balancer-manager>
SetHandler balancer-manager
AuthType Basic
AuthName "Balancer Manager"
AuthUserFile "/etc/httpd/conf/.htpasswd"
Require valid-user
</Location>

Now here is my server.xml from node1
<?xml version='1.0' encoding='utf-8'?>

<Server port="8005" shutdown="SHUTDOWN">

  <Listener className="org.apache.catalina.core.AprLifecycleListener" SSLEngine="on" />

  <Listener className="org.apache.catalina.core.JasperListener" />

  <Listener className="org.apache.catalina.core.JreMemoryLeakPreventionListener" />

  <Listener className="org.apache.catalina.mbeans.ServerLifecycleListener" />
  <Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener" />

  <GlobalNamingResources>

    <Resource name="UserDatabase" auth="Container"
              type="org.apache.catalina.UserDatabase"
              description="User database that can be updated and saved"
              factory="org.apache.catalina.users.MemoryUserDatabaseFactory"
              pathname="conf/tomcat-users.xml" />
  </GlobalNamingResources>

  <Service name="Catalina">

    <Connector port="8009" protocol="AJP/1.3" redirectPort="8443" />

    <Engine name="Catalina" defaultHost="localhost" jvmRoute="node1">

      <Realm className="org.apache.catalina.realm.UserDatabaseRealm"
             resourceName="UserDatabase"/>

      <Host name="localhost"  appBase="webapps"
            unpackWARs="true" autoDeploy="true"
            xmlValidation="false" xmlNamespaceAware="false">

      </Host>
    </Engine>
  </Service>
</Server>

now here is the server.xml file from node2
<?xml version='1.0' encoding='utf-8'?>

<Server port="8105" shutdown="SHUTDOWN">

  <Listener className="org.apache.catalina.core.AprLifecycleListener" SSLEngine="on" />

  <Listener className="org.apache.catalina.core.JasperListener" />

  <Listener className="org.apache.catalina.core.JreMemoryLeakPreventionListener" />

  <Listener className="org.apache.catalina.mbeans.ServerLifecycleListener" />
  <Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener" />

  <GlobalNamingResources>

    <Resource name="UserDatabase" auth="Container"
              type="org.apache.catalina.UserDatabase"
              description="User database that can be updated and saved"
              factory="org.apache.catalina.users.MemoryUserDatabaseFactory"
              pathname="conf/tomcat-users.xml" />
  </GlobalNamingResources>

  <Service name="Catalina">

    <Connector port="8109" protocol="AJP/1.3" redirectPort="8443" />

    <Engine name="Catalina" defaultHost="localhost" jvmRoute="node2">

      <Realm className="org.apache.catalina.realm.UserDatabaseRealm"
             resourceName="UserDatabase"/>

      <Host name="localhost"  appBase="webapps"
            unpackWARs="true" autoDeploy="true"
            xmlValidation="false" xmlNamespaceAware="false">

      </Host>
    </Engine>
  </Service>
</Server>

I dont know what it is. but I been trying for days
Comment: are you able to access node2:8109 ?, if not, check your firewall. or try to take out node1 config see if it's working or not.
Comment: how should I test that
Comment: just use 1 node first, see if it's working
BalancerMember ajp://127.0.0.1:8109 min=10 max=100 route=node2 loadfactor=1
Comment: I tryed it with one at a time and the first node worked and the 2nd did not...
Comment: check if node2 listen to the port 8109 (netstat -an|grep 8109), if it's listened, try to (telnet localhost 8109), if it's not connected, check your firewall setting
Comment: I did try to telnet to it and I could not.. so I changed it to 8209 and it i can now telnet to it but it still dont work :(
Comment: if you are able to telnet node2:8209, you should able to access using   BalancerMember ajp://127.0.0.1:8209 min=10 max=100 route=node2 loadfactor=1
Comment: I am starting to think I am going crazy... I did this on 4 VMs and all have the same issue... maybe I should remove stickysession to see if it frees something up?
Comment: I deleted the dir with node2 and copy node1 over and started it... everything worked great until I stop it and changed the port from 8009 to 8109 or 8209 once I change the port it stops working.. I can telnet to the new port but it done work from httd. and once I change it back to 8009 it works???
Comment: it works if I do "setenforce 0" I am using Scientific Linux release 6.2. Can someone please tell me why it works and how to get around doing the serenforce 0..
Answer: Your second server.xml has its redirectPort connector bound to the same port as the first tomcat instance 8443. Check your second tomcat's: ...logs/catalina.out to see if this has prevented it from starting, if it has you alter the port in the second instance to a different value and restart the instance. You might also wish to consider temporarily enabling a HTTP, port 8080 connector in the second instance, to provide a quick mechanism to test the app is running as expected.
Comment: I enabled http and I can get to it from 8080. found it be something with the session is locked on a node?
Comment: if I try to use wget 127.0.0.1:8080/examples it works if I do a wget 127.0.0.1/examples I get a 503
Comment: I deleted the dir with node2 and copy node1 over and started it... everything worked great until I stop it and changed the port from 8009 to 8109 or 8209 once I change the port it stops working.. I can telnet to the new port but it done work from httd.
Comment: Are there any errors in the catalina.out? Are you running on a hardened box e.g. have SElinux enabled?  Can you [ping](http://www.joedog.org/2012/06/ajp-functional-test/) the ajp port?
Comment: nothing in catalina.out, I did not ping it but I telnet to the port and its ok... its on SElinux 32bit and 64bit...
Comment: Can you check the SE logs for any rejections e.g. _ausearch -ts today_
Comment: If SElinux is blocking you will nedd a: _semanage port -a -t http_port_t -p tcp 8109_
Comment: it works if I do "setenforce 0" I am using Scientific Linux release 6.2. Can someone please tell me why it works and how to get around doing the serenforce 0..
Comment: SELinux adds an extra level of security, at the kernel level, and will only permit files / sockets to be accessed by a process if explicitly granted access beforehand, I'm not an expert but the following should explain some of the basics: http://www.laliluna.de/articles/2008/09/14/apache_tomcat_mod_jk_selinux.html
Answer: no it was a issue with SELinux... I had to do a setenforce 0.


React Native search bar dispatch API call

Question: I have multiple tabs where in three of those there is a FlatList component where I need to be able to search for items. Now in my Header I want to make a SearchBar and be able to make an API call to get what the user searched for and to display the result(s) in the FlatList. I am using react-navigation/native ^5.7.1.
Answer: You can render a custom component in the options props. More details here
function SearchBar() {
      const [value, onChangeText] = React.useState('Useless Placeholder');
      return (
       <TextInput
        style={{ height: 40, borderColor: 'gray', borderWidth: 1 }}
        onChangeText={text => onChangeText(text)}
        value={value}
       />
      );
    }

function StackScreen() {
  return (
    <Stack.Navigator>
      <Stack.Screen
        name="Home"
        component={HomeScreen}
        options={{ headerTitle: props => <SearchBar {...props} /> }}
      />
    </Stack.Navigator>
  );
}

Comment: @stefan0905 If this answers your question. Please accept it as an answer so that it will be helpful for others!


MS-SQL: Changing the FileGrowth parameters of a database generically

Question: In our software the user can create databases as well as connect to databases that were not created by our software. The DBMS is Microsoft SQL-Server.
Now I need to update the databases that we use and set the FileGrowth parameter of all the files of all the databases to a certain value.
I know how to get the logical file names of the files of the current database from a query:
SELECT file_id, name as [logical_file_name], physical_name FROM sys.database_files

And I know how to set the desired FileGrowth value, once I know the logical file name:
ALTER DATABASE MyDB MODIFY FILE (Name='<logical file name>', FileGrowth=10%)

But I don't know how to combine these to steps into one script.
Since there are various databases I can't hard code the logical file names into the script.
And for the update process (right now) we only have the possibility to get the connection of a database and execute sql scripts on this connection, so a "pure" script solution would be best, if that's possible.
Answer: The following script receives a database name as parameter and uses 2 dynamic SQL: one for a cursor to cycle database files of chosen database and another to apply the proper ALTER TABLE command, since you can't use a variable for the file name on MODIFY FILE.
The EXEC is commented on both occasions and there's a PRINT instead, so you can review before executing. I've just tested it on my sandbox and it's working as expected.
DECLARE @DatabaseName VARCHAR(100) = 'DBName'

DECLARE @DynamicSQLCursor VARCHAR(MAX) = '

    USE ' + @DatabaseName + ';

    DECLARE @FileName VARCHAR(100)

    DECLARE FileCursor CURSOR FOR
        SELECT S.name FROM sys.database_files AS S

    OPEN FileCursor
    FETCH NEXT FROM FileCursor INTO @FileName

    WHILE @@FETCH_STATUS = 0
    BEGIN

        DECLARE @DynamicSQLAlterDatabase VARCHAR(MAX) = ''
            ALTER DATABASE ' + @DatabaseName + ' MODIFY FILE (Name = '''''' + @FileName + '''''', FileGrowth = 10%)''

        -- EXEC (@DynamicSQLAlterDatabase)
        PRINT (@DynamicSQLAlterDatabase)

        FETCH NEXT FROM FileCursor INTO @FileName

    END

    CLOSE FileCursor
    DEALLOCATE FileCursor '

-- EXEC (@DynamicSQLCursor)
PRINT (@DynamicSQLCursor)

You might want to check for the usual dynamic SQL caveats like making sure the values being concatenated won't break the SQL and also add error handling.
As for how to apply this to several databases, you can create an SP and execute it several times, or wrap a database name cursor / while loop over this.
Comment: Thank you! Can you tell me, if that should work in every MS SQL Server from 2008 R2 up to 2019? Or is there anything used that's too new for 2008 R2 or too old for 2019?
Comment: `sys.database_files` was incorporated from 2008 onwards and the `ALTER DATABASE` to modify files was already available since 2005 so it should be OK.


Python Array: Continuous Field

Question: I am trying to group objects in an array where positive values above, below, left and right would indicate a common group but diagonal would not. See example below.
input = [
 [0,1,1,1,0,0,0],
 [0,1,1,1,0,0,0],
 [0,0,1,1,0,0,0],
 [0,0,0,0,1,1,0],
 [0,1,1,0,0,0,0],
 [0,0,1,1,0,0,1],
]

output = [
 [0,a,a,a,0,0,0],
 [0,a,a,a,0,0,0],
 [0,0,a,a,0,0,0],
 [0,0,0,0,b,b,0],
 [0,c,c,0,0,0,0],
 [0,0,c,c,0,0,d],
]

At the moment my solution is to loop through the array testing each value against the values alongside. Owing to the size of the arrays ~2500x~1400, the solution is running very slowly.
Does anyone know of any libraries that are optimised for this or any ideas on the best way to accomplish this, please?
Thanks for your time.
Comment: definitely `numpy` for that task, how to group by idk...
Comment: If you run a lot of loops, it may be worth looking into numba. It can help speed up your loops by just-in-time compiling your code into machine-code.
Comment: thank you, @sunnytown - I will look into it.
Comment: Looks like a task for `skimage.measure.label` https://scikit-image.org/docs/stable/api/skimage.measure.html#skimage.measure.label with `1-connectivity`.
Answer: Thank you, @Max111. That was exactly what I was after.
from skimage.measure import label

input = np.array([
 [0,1,1,1,0,0,0],
 [0,1,1,1,0,0,0],
 [0,0,1,1,0,0,0],
 [0,0,0,0,1,1,0],
 [0,1,1,0,0,0,0],
 [0,0,1,1,0,0,1],
])

output = label(input, connectivity=1)

Python Array: Continuous Field


How to hide few details of GrandTotal in Tableau

Question: In my report, I am showing both the shape(tickmark) and text as content.
Now I want only the tickmark in the rows,columns and only the text in grandtotal.
But the grandtotal automatically applies the tickmark to the final value also.
Can i show only the value in grandtotal?
Answer: You may append dome dummy data here.
Tableau may not have direct options to change mark types for grand total.  As a workaround it id suggested that a calculated field may be used instead of using totals so that different marks in both fields may be used.
I created a calc field (in Tableau sample superstore data) named Gtotal as
<code>{FIXED [sub category] : COUNT([People])}
</code>
and got this view


MAIL FROM:<>, Exchange server 2010

Question: In the process of troubleshooting another issue, I have turned on protocol logging on my Exchange 2010 server.  I noticed that there are numerous instances of MAIL FROM:<> in the logs.  Many of the messages show information like MAIL FROM:<email@example.com> SIZE=11209, so I'm a bit worried that perhaps something is amiss.
This is even more suspicious because most instances of this appear to correspond to failed attempts as message relay.
Here's an example
2013-06-17T15:06:12.167Z,Send Connector - Internet,08D038810B434725,1,184.108.40.206:23428,126.96.36.199:25,+,,
2013-06-17T15:06:13.540Z,Send Connector - Internet,08D038810B434725,2,18.104.22.168:23428,22.214.171.124:25,<,220 mail4.canteke.com ESMTP,
2013-06-17T15:06:13.540Z,Send Connector - Internet,08D038810B434725,3,188.8.131.52:23428,184.108.40.206:25,>,EHLO mail.mydomain.com,
2013-06-17T15:06:13.587Z,Send Connector - Internet,08D038810B434725,4,18.104.22.168:23428,220.127.116.11:25,<,250 mail4.canteke.com,
2013-06-17T15:06:13.587Z,Send Connector - Internet,08D038810B434725,5,18.104.22.168:23428,126.96.36.199:25,*,85673,sending message
2013-06-17T15:06:13.587Z,Send Connector - Internet,08D038810B434725,6,18.104.22.168:23428,126.96.36.199:25,>,MAIL FROM:<>,
2013-06-17T15:06:13.634Z,Send Connector - Internet,08D038810B434725,7,126.96.36.199:23428,126.96.36.199:25,<,250 Ok,
2013-06-17T15:06:13.634Z,Send Connector - Internet,08D038810B434725,8,18.104.22.168:23428,22.214.171.124:25,>,RCPT TO:<firstname.lastname@example.com>,
2013-06-17T15:06:13.696Z,Send Connector - Internet,08D038810B434725,9,126.96.36.199:23428,22.214.171.124:25,<,"553 sorry, that domain isn't in my list of allowed rcpthosts (#5.7.1)",
2013-06-17T15:06:13.696Z,Send Connector - Internet,08D038810B434725,10,184.108.40.206:23428,188.8.131.52:25,>,QUIT,
2013-06-17T15:06:13.743Z,Send Connector - Internet,08D038810B434725,11,220.127.116.11:23428,18.104.22.168:25,<,221 Bye,
2013-06-17T15:06:13.743Z,Send Connector - Internet,08D038810B434725,12,126.96.36.199:23428,22.214.171.124:25,-,,Local

I'd like to discover how and why these mail attempts are being generated.
Comment: when you check the message tracking logs for this recipient does it show an internal mailbox or client IP as the source?
Answer: This is normal. Many MTAs will use a null sender address for bounces and other types of status messages, so as to avoid mail loops. This practice is referenced in section 4.5.5 of RFC 5321.

MAIL FROM:<>, Exchange server 2010


Why use virtual function instead of regular?

Question: In c++, the virtual function in base class can be overridden in derived class.
and a member function where the specific implementation will depend on the type of the object it is called upon, at run-time.
Since virtual function has to be implemented(except for pure virtual)
Can I use regular function in base class and redefine it in derived class?
if yes.
What's the point of using virtual function?
Thanks
Comment: You can *hide* a non-virtual function. That's generally a bad thing.
Comment: Are you sure its not given in your book ?
Answer: You can redefine it but it won't work in a polymorphic way.
so if I have a
class base
{
   int foo(){ return 3; }
};

class Der : public base
{
  int foo() {return 5;}
};

and then have a function that takes a base
void dostuff(base &b)
{
   b.foo(); // This will call base.foo and return 3 no matter what
}

and I call it like this
Der D;
dostuff(D);

Now if I change the base to
class base
{
   virtual int foo(){ return 3; }
};

void dostuff(base &b)
{
   b.foo(); // This will call the most derived version of foo
            //which in this case will return 5
}

so the real answer is if you want to write common code that will call the correct function from the base it needs to be virtual.
Answer: Actually, Virtual function is base of object oriented language.
In java, all functions are virtual function.
But in c++, virtual function is slower than regular function.
So if there is no need to function override, you should use regular function instead of virtual function.


Filter only EQUAL values into columns with dplyr::filter_if

Question: I have following data:
df <- data.frame(
  x = c(1, 4, 3, 4, 4, 3),
  y = c(2, 3, 4, 4, 2, 3)
)

I try use this code:
library(tidyverse)

df %>%
  filter_if(~ is.numeric(.), all_vars(. %in% c('3', '4')))

  x y
1 4 3
2 3 4
3 4 4
4 3 3

But, the expected result is:
  x y
1 3 3
2 4 4

How do this?
Comment: You can just do `df %>%
 filter(x == y)`.
Comment: How apply in the `filter_if` (only numeric columns)? I try this `df %>%
  filter_if(~ is.numeric(.), all_vars(. == .))`. But, doesn't work.  I can't use variables names (`x` and `y`), only your classes.
Answer: A different approach:
require(tidyverse)

df <- data.frame(
  x = c(1, 4, 3, 4, 4, 3),
  y = c(2, 3, 4, 4, 2, 3),
  z = letters[1:6]
)

df %>%
  filter(apply(.,1,function(x) length(unique(x[grepl('[0-9]',x)]))==1))

gives:
  x y z
1 4 4 d
2 3 3 f

I have added a non-numeric column to the example data, to illustrate this solution.
Comment: Thanks @Wietze314. But, I need a solution with `filter_if`.
Comment: I think `filter_if` evaluates each value per row separately, so you are not able to evaluate the context of these values (i.e. compare values within its row). That is why I don't think you can do this with `filter_if` and why I used `filter` and `apply`.
Answer: Not a filter_if() possibility, but essentially following that logic:
df %>%
 filter(rowMeans(select_if(., is.numeric) == pmax(!!!select_if(., is.numeric))) == 1)

  x y z
1 4 4 d
2 3 3 f

Sample data:
df <- data.frame(x = c(1, 4, 3, 4, 4, 3),
                 y = c(2, 3, 4, 4, 2, 3),
                 z = letters[1:6],
                 stringsAsFactors = FALSE)


How to learn to exchange hands' roles on keyboard

Question: I'm used to using my left hand to play rhythmic parts and my right hand to play melodic lines (like, I assume, many other players).
What kind of approaches would you recommend to learn to swap these roles (i.e., play rhythmic parts with the right hand while playing melodic lines with the left one)? If that's unclear, here's a segment I can play if I cross hands, but that I'm unable to play the way it's shown (from 2:15 to 2:27):

(I'm right-handed, but I'm not sure it matters)
Comment: Start with simpler songs, played slowly, and work your way up.
Comment: There is no "magic formula", just lots of practice.  Start with each hand separately, then put them together. There are lots of exercises for left hand independence, e.g. http://imslp.org/wiki/24_Piano_Studies_for_the_Left_Hand,_Op.718_(Czerny,_Carl) - use google and/or youtube for more.
Answer: A few tips:

Practice sight-reading left-hand parts with the right hand (resting the left)
Practice sight-reading right-hand parts with the left (resting the right)
It's generally more difficult for the left hand to do the right hand's job than the other way around, so practice accordingly.
Learn about stride piano and related genres. If you like what you hear and learn some of it, it'll do wonders for your left-right skills ( http://en.wikipedia.org/wiki/Art_Tatum#cite_ref-43 :)


Hibernate session and garbage collector

Question: An object with hibernate session data member when garbage collected, is session's jdbc connection closed? In other words is leaving closing session to garbage collector bad idea?
Answer: You should always explicitly close resources, and not rely on GC/finalisation.
Answer: If your entities are garbage-collected, there is no reason to GC the session too. The session will be GCed then or later.

For example, if I store a reference to a session in a static list, I can run my application for hours, entities will get collected but not the sessions...

Session should be closed explicitely.

If you dislike the explicit closing in your code, I totally agree with you, and many other people also. :-)
A common solution is to make the closing happen in framework code, that is code that is written once, and applies to all your transactions. It could happen in a superclass, for example if all your transactions are implemented via the command pattern.
However, the most common implementation pattern is to use AOP for such a global concern. Our projects use Spring, which provide out-of-the-box support for closing all hibernate sessions (and the associated transaction), with an additional feature for commit/rollback:

if an exception is thrown, rollback is called on the transaction before closing it
otherwise, commit is called.
Answer: completely agree with @Robert. It cannot be stressed enough, hibernate session objects should be treated with the same care as a JDBC connection, you should be aware of when and where it is opened and when and where it is closed in all cases.
This is of course one of the reasons people find spring very useful, it provides a very complete framework for managing the life cycle of resources like jdbc connections and hibernate sessions.

Hibernate session and garbage collector