Visualização padrão do eclipse com o fundo preto

Question: Estou usando o ubuntu 19.04 com a interface gnome, também estou usando o tema flat remix e resolvi instalar o eclipse (versão mais recente) e quando abro ele, me deparo com o seguinte problema:

Já tentei de tudo, procurei diversos foruns mas nenhum resolveu o problema. Alguém poderia me ajudar a encontrar a resolução?
Answer: Ola,
Voce já tentou alterar o tema em Window > Preferences > Appearence ?

Comment: Infelizmente sim, já mexi em tudo nessa aba. Tentei configurar os elementos de background e foreground e nada. Mexi nos css do tema gtk2 e gtk3 mas nada também. Até testei versões diferentes do eclipse..
Comment: qualquer tema fica escuro ou apenas este?
Comment: Qualquer tema :(
Comment: já tentou este plugin ? http://www.eclipsecolorthemes.org/?view=plugin


Two-way authentication for SSL communication

Question: I am trying to send information (in the form of an mime file) to a third party host server that uses two way authentication. After much coaxing I got enough information from their non technical help desk staff to figure out that it is most likely a type of TLS/SSL communication. They use client and server handshakes. I found the following example:
sslstream example. But am having problems using it (TcpClient refuses to see the host adddress).
Before I get too far I was hoping some one could point me in the direction of some good examples or more information on this process. I'm feeling pretty lost.
Answer: By two way authentication, probably they mean that they require a client certificate. This means that during the handshake, the client side has to present a certificate to the server as well. The most common SSL behavior is that only the server part presents a certificate, such as when you go to a normal site that is using HTTPS.
As for SslStream, it is quite straightforward to use. To be able to present a client certificate, you need to have a certificate in the certificate store or a pfx file that you can load into memory during runtime.
I found this sample which seems good enough. Here is another one. The second one  doesn't use client certs, but you can add them as a parameter to the the AuthenticateAsClient call.
If the TcpClient is refusing to see the host address, then this is most likely some kind of connectivity issue and not related to the actual SSL implementation.
Comment: Thanks for the response Can. The examples helped me understand a little more of what is going on. It appears that none of the .Net tools handle the different 'Handshakes' required by TLS http://en.wikipedia.org/wiki/Transport_Layer_Security. I probably could but really don't want to write the code needed for this. Can anyone suggest a .Net friendly third party tool?
Comment: I think SslStream didn't support AES if I remember correctly. That could be the issue if the server is requiring it.
Comment: The links are broken and without the links the answer isn't very useful.


Integral inequality : for $f\in C^{4}[0,1]$ with $f(0)=f(1)=f^\prime(0)=f^\prime(1)=0$, show that $\int_0^1|\frac{f^{(4)}(x)}{f(x)}|dx\geq 192$

Question: I was interested in the problem stated below:
Problem 0. $f\in C^{4}[0,1]$ with $f(0)=f(1)=f^\prime(0)=f^\prime(1)=0$, show that $\int_0^1|\frac{f^{(4)}(x)}{f(x)}|dx\geq 192$
This problem is assigned as supplementary problems based on the easier one :
Problem 1: $f\in C^{2}[0,1]$ with $f(0)=f(1)=0$, show that $\int_0^1|\frac{f^{\prime\prime}(x)}{f(x)}|dx\geq 4$
I proved the easier one in this way:
Proof of Problem 1: $$\int_{[0,1]}|f''(x)|dx\geq \int_{[\theta_1,\theta_2]}|f''(x)|dx\geq \left|\int_{[\theta_1,\theta_2]}f''(x)dx\right|=|f^\prime(\theta_2)-f^\prime(\theta_1)|$$
As $f$ is continuous on a compact set, we can find $x_0$ such that $f(x_0)>f(x)$ for any $x\in [0,1]$. By the mean value theorem, assign $\theta_1$ and $\theta_2$ above to be:
$$\frac{f(x_0)-f(0)}{x_0-0}=f^\prime(\theta_1);\quad \frac{f(x_0)-f(1)}{x_0-1}=f^\prime(\theta_2)$$
Then we have:
$$|f^\prime(\theta_2)-f^\prime(\theta_1)|=\left|\frac{f(x_0)}{x_0(1-x_0)}\right|\geq 4|f(x_0)|$$
In sum, we have:
$$\int_{[0,1]}\left|\frac{f^{\prime\prime}(x)}{f(x)}\right|\geq \int_{[0,1]}\left|\frac{f^{\prime\prime}(x)}{f(x_0)}\right|\geq 4$$
However for Problem 0, I tried MVT and Taylor expansions on $0$ and $1$ but find no clues to continue. Any reasonable thoughts are welcome! Thank you!
Comment: where did you got this question from ?
Answer: For the Problem 0 here I provide one solution inspired by Hermite interpolation (https://sites.math.rutgers.edu/~falk/math373/lecture7.pdf).
Step 1
Let $$\phi(t)=f(t)-\frac{f(x)}{x^2(x-1)^2}t^2(t-1)^2$$ which is fourth differentiable for $t\neq x$ and $t\in(0,1)$ with
$$\phi^{(4)}(t)=f^{(4)}(t)-\frac{12f(x)}{x^2(x-1)^2}$$
One may observe $\phi(0)=\phi(1)=\phi(x)=0$, hence by Rolle's theorem, there exists $\theta_1\in(0,x)$ and $\theta_2\in(x,1)$ such that $$\phi'(0)=\phi'(1)=\phi'(\theta_1)=\phi'(\theta_2)=0$$ Again applying Rolle's theorem one may find $\{\psi_1,\psi_2,\psi_3\}$ and $\{\eta_1,\eta_2\}$ such that $$\phi''(\psi_1)=\phi''(\psi_2)=\phi''(\psi_3)=0$$ and $$\phi'''(\eta_1)=\phi'''(\eta_2)=0$$ Finally, there exists at least one $x_0$ such that $\phi^{(4)}(x_0)=f^{(4)}(x_0)-\frac{12f(x)}{x^2(x-1)^2}=0$ given $x\in [0,1]$.
Step 2:
As $f$ is continuous on a compact set, let $\bar{x}$ to be the global maxima of $f$ on $[0,1]$, then plug in $x=\bar{x}$ to the $\phi(t)$ constructed in Step 1. As there exists $\{\eta_1,\eta_2\}$ such that $\phi'''(\eta_1)=\phi'''(\eta_2)=0$, hence:
$$\int_0^1 |f^{(4)}(x)|dx\geq \int_{\eta_1}^{\eta_2} |f^{(4)}(x)|dx\geq|\int_{\eta_1}^{\eta_2} f^{(4)}(x)dx|=|f^{(3)}(\eta_2)-f^{(3)}(\eta_1)|=\left|\frac{f(\bar{x})}{{\bar{x}}^2(\bar{x}-1)^2}12(\eta_2-\eta_1)\right|\geq \left|\frac{12f(\bar{x})}{{\bar{x}}^2(\bar{x}-1)^2}\right| \geq 192|f(\bar{x})| $$
Then easily to check that :
$$\int_0^1 \left|\frac{f^{(4)}(x)}{f(x)}\right|dx\geq \int_0^1 \left|\frac{f^{(4)}(x)}{f(\bar{x})}\right|dx \geq 192$$
Comment: In this way we can also find interesting results that $$\max\limits_{x\in[0,1]}|f^{(4)}(x)|\geq 192 \max\limits_{x\in[0,1]}|f(x)|$$


Como baixar TODOS os arquivos de uma pasta com requests?

Question: Achei vários artigos na internet sobre como baixar um único arquivo, mas eu sempre preciso especificar o nome e diretório do arquivo.
O programa que eu gostaria de fazer precisa baixar todos os arquivos neste diretório (ex: 22.214.171.124/pasta) e salvá-los no diretório padrão onde se encontra o app.
Fiz algo assim, mas não consegui concluir:
def get_arqchives(url):
    res = requests.get(url)
    if res.status_code == requests.codes.OK:
       for u in res.content:
           with (endereco, 'wb') as target:
               pass
    else:
       res.raise_for_status()

Answer: Numa pasta HTTP apenas recebemos o HTML com a lista dos ficheiros. Temos que usar o BeautifulSoup para obter os links.
from bs4 import BeautifulSoup
import requests
from pathlib import Path

url = '188.8.131.52/pasta/'

def listFD(url):
    page = requests.get(url).text
    soup = BeautifulSoup(page, 'html.parser')
    return [url + '/' + node.get('href') for node in soup.find_all('a') if node.get('href')]

def downloadFile(file):
    r = requests.get(file)
    path = Path(file)
    with open(path.name, 'wb') as f:
        f.write(r.content)

for file in listFD(url):
    downloadFile(file)

Comment: Obtive este erro:

`Traceback (most recent call last):
  File "C:/Users/dannyou/PycharmProjects/autoupdater/main.py", line 34, in
    downloadFile(x)
  File "C:/Users/dannyou/PycharmProjects/autoupdater/main.py", line 29, in downloadFile
    with open(path.name, 'wb') as f:
OSError: [Errno 22] Invalid argument: '?C=N;O=D'`


Verify a statement on a random variable

Question: Given a random variable $x$ with finite expected value $E(x)$, i need to verify whether the following holds:
if $E(x) < 0$ and $\theta \neq 0$, such that $E(e^{\theta x}) = 1$, then $\theta > 0$
I proceeded by noting that
$$E(e^{\theta x}) > E(x) \implies e^{\theta x} > x $$
Then taking logs on both sides and solving for $\theta$ i get
$$\theta > \frac{\ln(x)}{x}$$
Which however seems a really strange result to me given the nature of x. Any ideas of what I am missing here?
Answer: By Jensen's inequality,
$$ E\left[\exp\left\{\theta X\right\}\right] > \exp\left\{\theta E[X]\right\}$$
for any $\theta \neq 0$. Moreover, as $E[X] < 0$,
$$ \exp\left\{\theta E[X]\right\} \begin{cases}
> 1 & \text{if } \theta < 0 \\
< 1 & \text{if } \theta > 0
\end{cases} $$
So when $\theta < 0$, we have
$$ E\left[\exp\left\{\theta X\right\}\right] > \exp\left\{\theta E[X]\right\} > 1$$
which contradict to $E\left[\exp\left\{\theta X\right\}\right] = 1$
Therefore, when $E\left[\exp\left\{\theta X\right\}\right] = 1$, we have $\theta > 0$
Comment: Given that $e^{\theta x}$ is a convex function, now i see it.. would you mind highlighting the mistake in my approach?
Comment: Actually I do not quite follow your first statement already. $X > Y$ almost surely implies $E[X] > E[Y]$, but the converse does not hold in general.
Comment: Thank you for the clarification!

Verify a statement on a random variable


Inequality. $\sum{(a+b)(b+c)\sqrt{a-b+c}} \geq 4(a+b+c)\sqrt{(-a+b+c)(a-b+c)(a+b-c)}.$

Question: Let $a,b,c$ be the side-lengths of a triangle. Prove that:
I.
$$\sum_{cyc}{(a+b)(b+c)\sqrt{a-b+c}} \geq 4(a+b+c)\sqrt{(-a+b+c)(a-b+c)(a+b-c)}.$$
What I have tried:
\begin{eqnarray}
a-b+c&=&x\\
b-c+a&=&y\\
c-a+b&=&z.
\end{eqnarray}
So $a+b+c=x+y+z$ and $2a=x+y$, $2b=y+z$, $2c=x+z$ and our inequality become:
$$\sum_{cyc}{\frac{\sqrt{x}\cdot(x+2y+z)\cdot(x+y+2)}{4}} \geq 4\cdot(x+y+z)\cdot\sqrt{xyz}. $$ Or if we make one more notation : $S=x+y+z$ we obtain that:
$$\sum_{cyc}{\sqrt{x}(S+y)(S+z)} \geq 16S\cdot \sqrt{xyz} \Leftrightarrow$$
$$S^2(\sqrt{x}+\sqrt{y}+\sqrt{z})+S(y\sqrt{x}+z\sqrt{x}+x\sqrt{y}+z\sqrt{y}+x\sqrt{z}+y\sqrt{z})+xy\sqrt{z}+yz\sqrt{x}+xz\sqrt{y} \geq 16S\sqrt{xyz}.$$ To complete the proof we have to prove that:
$$y\sqrt{x}+z\sqrt{x}+x\sqrt{y}+z\sqrt{y}+x\sqrt{z}+y\sqrt{z} \geq 16\sqrt{xyz}. $$
Is this last inequality true ?
II.
Knowing that: $$p=\frac{a+b+c}{2}$$ we can rewrite the inequality:
$$\sum_{cyc}{(2p-c)(2p-a)\sqrt{2(p-b)}} \geq 8p \sqrt{2^3 \cdot (p-a)(p-b)(p-c)} \Leftrightarrow$$
$$\sum_{cyc}{(2p-c)(2p-a)\sqrt{(p-b)}} \geq 16p \sqrt{(p-a)(p-b)(p-c)}$$
This help me ?
Thanks :)
Comment: Re the proposed inequality $y \sqrt{x} + \cdots + y \sqrt{z} \geq 16 \sqrt{xyz}$: This is false when $x=y=z$. You have an algebra error going from $S^2 (\sqrt{x}+\sqrt{y}+\sqrt{z}) + \cdots \geq 16 S \sqrt{xyz}$ to $y \sqrt{x} + z \sqrt{x} + \cdots \geq 16 \sqrt{xyz}$.
Answer: Notice that the inequality proposed is proved once we estabilish

$$\frac{(a+b)(b+c)}{\sqrt{a+b-c}\sqrt{-a+b+c}}+\frac{(b+c)(c+a)}{\sqrt{a-b+c}\sqrt{-a+b+c}}+\frac{(c+a)(a+b)}{\sqrt{a-b+c}\sqrt{a+b-c}}\geq 4(a+b+c).$$

Using AM-GM on the denominators in the LHS, we estabilish that

$\sqrt{a+b-c}\sqrt{-a+b+c}\leq b$,
$\sqrt{a-b+c}\sqrt{-a+b+c}\leq c$,
$\sqrt{a-b+c}\sqrt{a+b-c}\leq a$.

Therefore

$$\operatorname{LHS}\geq \frac{(a+b)(b+c)}{b}+\frac{(b+c)(c+a)}{c}+\frac{(c+a)(a+b)}{a}=3(a+b+c)+\frac{ca}{b}+\frac{ab}{c}+\frac{bc}{a}$$

To finish with the proof it suffices then to prove

$$\frac{ca}{b}+\frac{ab}{c}+\frac{bc}{a}\geq a+b+c.$$

This follows from AM-GM, indeed

$$\frac{\frac{ac}{b}+\frac{ab}{c}}{2}\geq a,$$
$$\frac{\frac{bc}{a}+\frac{ab}{c}}{2}\geq b,$$
$$\frac{\frac{ac}{b}+\frac{bc}{a}}{2}\geq c;$$

summing up these last inequalities, we get the desired result, hence finishing the proof. Notice that the condition of $a,b,c$ being the sides of a triangle is essential in the first usage of AM-GM.
Comment: @Iuli.. did you check this answer? Does it seem correct to you?
Answer: I couldn't solve this with elementary means.
Take $\sum_{cyc}{\sqrt{x}(S+y)(S+z)} \geq 16S\cdot \sqrt{xyz} $ and note that it is enough to prove it for $S=1$ because it is homogeneous. Substituting $x\to x^2$, etc. consider the function $f(x,y,z)=(x^2+1) (y^2+1) z+(x^2+1) y (z^2+1)+x (y^2+1)   (z^2+1)-16 x y z$. It is enough to prove it is non-negative if $\sum_{cyc}{x^2}=1$.
Let's denote $p[i]=x^i+y^i+z^i$.
Now notice that the following decomposition is valid: $$12f(x,y,z)=12 p[1] - 32 p[1]^3 + p[1]^5 + 108 p[1] p[2] - 4 p[1]^3 p[2] +  3 p[1] p[2]^2 - 76 p[3] + 2 p[1]^2 p[3] - 2 p[2] p[3]=$$
Using our assumption $p[2]=1$ this simplifies to:$f(x,y,z)=123 p[1] - 36 p[1]^3 + p[1]^5 - 78 p[3] + 2 p[1]^2 p[3]$.
Lets put $x=p[1]$ and $a=p[3]$.
Because $p[2]=1$ we ca deduce the ranges for $a$ and $x$ as $1 \ge p[3] \ge 1/\sqrt{3}$ and $ \sqrt{3}\ge p[1] \ge 1$. Also we need to keep in mind that from the power means inequality $p[1]/3 \le \sqrt[3]{p[3]/3}$.
We need to prove that the function:$g(x)=123 x - 36 x^3 + x^5 - 78 a + 2 a x^2 $ is non-negative in our domain. It turns out that this problem is numerically tractable, and this function is decreasing within our domain and becomes zero only when $a=\sqrt{3}/3$, and $x=\sqrt{3}$. The calculations however are quite tedious.
I am sure that a better way to solve this exists.


Which first: comping or timing correction?

Question: I have a number of takes (usually 5-8 are usable) of the whole band, all recorded to click that I would like to comp (merge together into one performance). It is no-brainer what to pick if some part is significantly better than in other takes. However, I have problems deciding when some take is slightly better musically, but it has worse timing, while the some other take is the other way around.
Normally, I would say that one should rely on their taste. The issue I have is this: lack of good synchronization might cause inferior choices, on the other hand timing correction affects how we perceive the performance, in particular different parts might require different corrections.
Ideally, I would have time to time-correct every take to match any other given take, but for 8 takes 4 parts each it creates over 200 different tracks to edit for one song (although in reality that would be more like 80-100).
My question is, what is the best approach:

comp first and synchronize later,
synchronize first (to one of the takes? to grid?) and then comp?

The music is something between jazz and funk, so even slightly bad timing would instantly kill the groove. Fortunately the musicians were good, so timing within-one-take is great. Unfortunately, I cannot use just one good take (each has some flaws), cannot re-record individual parts and neither can I invest time to do all the 200+ edits per song (lots of edits in those recordings would be rather hard to do seamlessly).
I suspect there is no easy answer here, but I would appreciate any suggestions.
Comment: If you comp second, then you have to correct all of every take, right? If you comp first, then you only correct the comp take.
Comment: @ToddWilcox Yes, but if one comps first, then it's easy to make bad decisions because timing isn't right and kills the groove.
Comment: I think you should comp first before time correction, time correction might not be perfect but do the best you can as it is also good to humanize your song.
Answer: If I were in this situation, I would comp first.
You aren't really in a position to fully appreciate timing issues (or lack thereof) until you hear the performance in context. A musician never plays in perfect time and this is often desirable - otherwise, what would be the use of the "humanize" function?
After the initial comp, listen to the whole track without the click and see how it grooves. As long as there are no major slips at the moment you transition between takes (which you will have some control over in choosing your comp points), any timing issues within the individual takes will simply be the human element of the performance.
The transition points will be the trouble spots, but your correction workload will be reduced dramatically - you only have to make sure the groove transitions smoothly between the takes you have chosen, as opposed to syncing all the takes (which should probably be done to the click track, in order to keep things consistent).
Moreover, the corrective work you need to do will inform your choices as to which parts of which takes to pick. The goal, at the end of the day, is to have a complete track that sounds the best it can, given what you have to work with. Perhaps this will mean having to discard elements that are in some ways superior, but cannot be made to work with the rest of the material. Them's the breaks.
If you're worried about committing to a bad decision, hold off the final choice for as long as possible. Do a number of rough comps, experimenting with different transition points and try to determine what is going to sound best and require the least amount of work. Only after you've tried out a number of alternatives will you have a good idea of what parts are worth fighting for and where you should just let it go.
Given that you have said correcting everything isn't feasible anyway, comping and then correcting only that which really needs correcting seems the only way to go.


Is this a memory leak?

Question: I have a ListActivity containing an object I've defined called a MessageItem.  I want to pass the data in this MessageItem off to a Service to do some stuff, but I don't want the Activity to be data bound to the Service such that Android can't reclaim the Activity if it needs to (ergo memory leak).
What I'm doing is passing the MessageItem object to a method in a singleton class along with the application Context.  The singleton method uses the application Context to start my Service.  I pass to this Service an Intent.  In this Intent, I put items from the MessageItem object like so:
<code>    intent.putExtra("subject", msg.getSubject());
    intent.putExtra("summary", msg.getSummary());
    intent.putExtra("created_on", msg.getCreatedDate());
    intent.putExtra("read", msg.getIsRead());
</code>
Will this data bind my Activity to the Service the Intent gets passed into and cause a memory leak?
Would this be a better implementation?:
<code>    intent.putExtra("subject", new String(msg.getSubject()));
    intent.putExtra("summary", new String(msg.getSummary()));
    intent.putExtra("created_on", new Integer(msg.getCreatedDate()));
    intent.putExtra("read", new Boolean(msg.getIsRead()));
</code>
Answer: You don't need to new String or Integer. When the data is transfered by intent,
It will be parceled and unparceled.
Comment: Is parceled what Android calls it, rather than just calling it boxed?
Answer:
Will this data bind my Activity to the Service

No, the code above will the references in the activity to the intent. The string and boolean values have no pointer back to the instance.

Would this be a better implementation?

No! That would be much worse. A lot of data would be copied and a lot of objects would be created for naught.

Is this a memory leak?


Django validating a (newsletter) form included as part of the base template

Question: I have a simple newsletter sign form which I want to include on every page of the site.
Here is the form (subscribers/forms.py)
from django import forms

class SubscriberForm(forms.Form):

  email = forms.EmailField()
  first_name = forms.CharField(max_length=20)
  last_name = forms.CharField(max_length=30)

I have set up a context processor, so I can render the form in the base template eg
def subscriber_form(request):
  return {
    'subscriber_form':SubscriberForm(),
  }

And in the base template I have
{% include "subscribers/index.html" with form=subscriber_form %}

All good.
However, the question is how do I validate the form without taking the user to a different url (and view). I obviously don't want to take the user to (eg) /subscriber/index (hence the action would be "'subscriber/index") and the associated view where I validate the form, because I want the validation errors (if any) to be shown on the (base) template. I would also want the success message to be shown on the base template, rather than taking the user off to a "success" url. It's also not a problem to do the validation using JavaScript but I want to have a fallback in case JS is disabled.
This is all because I want the form to be displayed on every single page - and hence why I need to include it within the base template.
Comment: I'd rather use a custom template tag, inside the function you can access the request object with `take_context=True`
Comment: Sorry - could you expand a bit. Not a huge fan of using template tags unless absolutely necessary, which could well be the case here!
Answer: With the assistance of Putting a django login form on every page, I solved it by writing a middleware class:
from subscribers.forms import SubscriberForm

class SubscriberFormMiddleware(object):

  def __init__(self, get_response):
    self.get_response = get_response

  def __call__(self, request):
    return self.get_response(request)

  def process_view(self, request, view_func, view_args, view_kwargs):
    if request.method == 'POST':
      form = SubscriberForm(request.POST, prefix='subscriber')
        if form.is_valid():
          // do your thing
        request.method = 'GET'
    else:
        form = SubscriberForm(prefix='subscriber')
    request.subscriber_form = form

And then in the base template
{% include "subscribers/index.html" with form=request.subscriber_form %}

The action in the form is set to "." so I can use it on any page.


Determining the Weight of Categorical Variable's Coefficient

Question: Lately, I have been studying about Logistic Regression, and I came across a question on how to handle categorical variable (as opposed to numerical ones).
Let's suppose I have a data table with two independent variables, and one dependent variable (the classification). Also, let's say one of the independent variables holds a numerical value, and the other one holds a categorical value. So the first one can be something like age, and the second one would be something like education level (high school, undergraduate, masters, phd).
To my knowledge, in order to perform logistic regression on this data set, I have to make the categorical variable into binary variable. So instead of 2 independent variables, I would have 5 independent variables (using the example I gave above, it would turn from [age, education] to [age, highschool, undergraduate, masters, phd] which the latter 4 would hold binary value.
Once logistic regression is done, it would give each variable a coefficient, a weight. Now in this case, I would have coefficient for each [highschool, undergraduate, masters, phd]. And here, I have a question:
In this case, would the 'weight' of the categorical variable (education) be the sum of 4 coefficients from [highschool, undergraduate, masters, phd] ? In other words, how would I measure the 'weight' (importance) of the categorical variable?
Answer: I would take a different approach than @IgorF. I would treat education as categorical.
In practice, in applications I am familiar with, your question is almost never answered. It is almost always an irrelevant question, and why waste time on something irrelevant? So my first suggestion to you is to explicitly formulate why you would want to know that, and why your audience might want to know that. Only once you have convinced yourself that it is worth your time and effort, start investing in it.
Once you have convinces yourself that this is a worthwhile exercise (remember that this is a very niche problem, so in all likelihood you will never reach this stage), then you could look at sheaf coefficients as a potential solution. See: (Heise 1972).

Some minor notes
Everything said here is not unique to logistic regression, it will apply equally to e.g. linear, poisson, probit, ordinal, multilevel regression.
You could argue education is ordinal in the US system. However, the way we treat ordinal variables as explanatory/independent/right-hand-side/x-variables is no different from  categorical ones. So in practice it does not make a difference. Moreover, in more tracked systems the ordinal interpretation of education gets messy pretty quickly: how do you compare a complete lower track with an incomplete higher track?
If you have a four category explanatory variable, then you create three indicator (dummy) variables. One of the categories is treated as the reference category.
As description of the American education system you are missing a hugely important category: less than highschool, and the PhD is usually too small a group to be really worthwhile measuring.
Heise, David R. (1972). Employing nominal variables, induced variables, and block variables in path analysis. Sociological Methods & Research, 1(2): 147--173. https://doi.org/10.1177%2F004912417200100201

Response to comment
There was some interest in my field in the comparison of weights in the 1960's and 1970's, but it is now largely considered (very) outdated. The reason becomes clear when you look more closely what the weights actually mean. In case of logistic regression: if you get a unit more of x then the odds of the outcome increases by a factor $\exp(\beta)$. So taking your example from your comment: if you get a year older then the odds of the outcome changes by a factor $\exp(\beta_1)$, and lets say your nationalities are Belgium, the Netherlands, and Luxembourg, and the Netherlands is your reference category. In that case you would interpret $\exp(\beta_2)$ as the odds of the outcome is  $\exp(\beta_2)$  times bigger/smaller in Belgium than in the Netherlands. The reason it is hard to compare these weights is that the units are completely different: how would you compare the difference between a year and Belgium versus the Netherlands? Attempts have been made to find a common metric, like the sheafcoefficient, but you can imagine that the result is highly abstract. As a consequence you typically loose much more than you gain by these methods: we know what getting a year older means, but what an unitless number might mean is much harder (plus all the assumptions you need to believe in order to justify that these numbers are really comparable). So nowadays we just focus on the actual meaning of the weights and the story we can tell with them, rather than artificially ranking predictors from most to least important.
Comment: Thanks for the answer. If I consider another case, in which variable is a categorical variable like nationality, I may be wondering if a person's age has more weight on the outcome of classification or his/her nationality has more weight. In this case I may wonder if how much the factor of nationality plays into classification.
Comment: (Assuming that this is one of the cases where it is relevant)
Comment: @Joon I have edited my answer to clarify that to answer your question you need to find a way to compare apples and oranges. This is possible (they are both fruit), but in doing so you necessarily also loose something. My rule of thumb would be to assume that this question is *not* relevant, and require some really really really strong arguments to move away from that assumption. If you have that strong argument you can look at the sheafcoeficient, as I mentioned in the answer.
Answer: Your "education" variable is not simply categorical, it is ordinal. High school is more than no school, undergraduate school is more than nothing or high school etc. Ordinal variables can be thought of as discretised, observable effects of some underlying latent variable.
In many cases, you can treat ordinal variable as numeric. E.g. no school = 0, high school = 1, ..., PhD = 4. You can argue that this is not entirely correct, as the "skill difference" between PhD and masters is not as large as between high school and no school. That's true, but, you wouldn't be better off if you had the access to the latent variabel, but the dependency between it and the outcome having some unknown non-linearity. In other words, the error you make by treating an ordinal variable as numeric is not different from assuming linearity when the dependency is non-linear.
In your case, you can even do better. The education level can easily be translated into years of education, which is numeric: High school = 12, undergraduate = 15-16, etc. That simplifies your problem to two numeric predictors.
Comment: That is a very American way of interpreting the value of education. That is fine, as the categories specified by the OP suggest that her/his data refer to American data. Just remember that this does not work for other educational systems. Especially in systems with a strong occupational education track, the number of years in school has little or no relationship with the "level" or "value" of a school level.
Comment: I can see how for the case I gave above, the education level could be translated into numerical values. But if I have a variable such as "Region" or "Nationality", this can't be translated into numerical values. I was wondering how I would handle cases like this.


smart use of PHP str_replace (or something similar)

Question: There are a large numbers of PHP variables I use in my template files and some of them need to be accessible for editors who can only use HTML.  What I want to do exactly is have them identify the variable doing something like [ITEM_NAME_1] when typing/editing content, and PHP finds them because they are wrapped in brackets, and replaces them with the appropriate PHP variable (in that case, $ITEM_NAME_1)
The content of each page is in a variable "$page_content", so right now the only way I know how to accomplish is to manually write lines to replace what I need.
$page_content = str_replace("[ITEM_NAME_1]", "$ITEM_NAME_1", "$page_content");
print $page_content

The issue is there are hundreds of these "ITEM_NAME_X" variables and I don't want to have to create a massive repeat of "str_replace" lines manually for each ITEM_NAME_X.
What I want to accomplish is have PHP find anything inside $page_content that is wrapped in brackets [], take the name from inside the bracket and replace all of it with the variable of that bracketted name. So if it finds [ITEM_5], it replaces it with $ITEM_5. Is this at all possible? Let me know, thanks.
Comment: You could try a regular expression replacing `/\[([^]*)]/$\1/g` but this might be rather dangerous. I think you're better off doing what you are and *explicitly* replacing what you know and understand with variables. Otherwise a malicious user might write `[_POST]` or `[encrKey]` or something. (A dictionary of bracketed expression->variable names would work though, and you can loop through that instead.)
Answer: this what i use:
public static function rewrite_curley($data,$message){

        if(is_array($data)){
            foreach($data as $key => $var){
                $find = '{'.$key.'}';
                $message = str_replace($find,$var,$message);
            }
            $message = preg_replace('/\{(.*)\}/','',$message); //strip any left over vars with out matches
        }
        return $message;

    }

obviously my variables are in {}, hence the function name
Comment: This function runs str_replace multiple times and so a regex. Isn't that faster to replace array_keys with their values in a single str_replace call?
Answer: Give preg_replace with the /e modifier a whirl. Combine that with variable variable name syntax to get the effect you want.
$page_content = preg_replace('/\[(.*?)\]/e', '$$1', $page_content);

This uses a regex to match strings between square brackets. The strings are captured and are accessed with $1 in the replacement string. The second $ looks up the variable named with whatever's in $1.
If you want to do something more complicated with the replacement, you can invoke your own function from the replacement string. For example:
function substitute_tag($tag_name)
{
    $replacement_values = array('foo' => 'bar', 'baz' => '42', ...);
    return $replacement_values[$tag_name];
}

$page_content = preg_replace('/\[(.*?)\]/e', 'substitute_tag("$1")', $page_content);

Comment: Your first example literally does exactly what I needed. Perfect!! Is there anything I should know about this (performance or security-wise) that I should be aware of?
Comment: @ZackTaylor As lc commented, it's not secure. I highly recommend the second approach with a substitution array so user's can't substitute arbitrary variable names.
Comment: Yeah, that makes sense. In the $replacement_values = array line, what would 'foo' => 'bar' (and so on) be in my particular case? I'm still learning PHP and so I'm trying to figure out what exactly that line is doing/accomplishing for me. Thanks in advance!
Comment: @ZackTaylor That's your mapping. `[foo]` is replaced with "bar", `[baz]` is replaced with "42", etc.
Answer: Why not simply use arrays as arguments for str_replace?
str_replace(array('string1', 'string2'), array('replacement1', 'replacement2'), $page_content);

This way you can avoid using regex.
Comment: I don't know who downvoted this. But in case you have same token and replacement count, str_replace with arrays can be handy and smart.
Comment: A regex on a large string may be a big performance problem; whereas the array approach to str_replace may be far more efficient. There is also far less room for error.


About Locus ( Theory)

Question: I'm literally confused about what a locus is. Can anyone explain me ?? I even searched the web and watched videos, but they failed to satisfy. Please explain elaborately !!
Comment: Why did you not understand them? Because, unless you've run into some sources of exceptionally low quality, you are very likely to find very similar answers here.
Answer: Locus is a set of all points on any geometric 2d figure.A set of points equidistant from a specific point which represents a circle.
Answer: A "locus" is just a fancy word for the set of points that satisfy some condition, when that set of points is viewed as a geometric figure.
For example,

An ellipse the locus of points in the plane whose sum of distances to two fixed points (called the foci of the ellipse) is a certain constant.

This means neither more nor less than

An ellipse the geometric figure made up of all the points in the plane whose sum of distances to two fixed points (called the foci of the ellipse) is a certain constant.

About Locus ( Theory)


Hook_form_alter for changing field labels doesn't work of user registration page

Question: Can anyone tell me why this isn't working (in the below code, or other factors preventing the insert by the hook)?   I don't get an error message or page, the field labels are simply not overwritten...
I created my own module with the following hook on Drupal 8.5.7:
function MYMODULE_form_alter(&$form, Drupal\Core\Form\FormStateInterface $form_state, $form_id){

  if ($form_id == 'user_register_form') {

    $form['field_user_first_name']['widget']['0']['#title'] = 'First Name';
    $form['field_user_last_name']['widget']['0']['#title'] = 'Last Name';
    $form['field_user_phone_number']['widget']['0']['#title'] = 'Phone Number';
    $form['field_user_country_of_residence']['widget']['0']['#title'] = 'Country (of residence)';
  }
}

Comment: If you want to change label take a loot at this question it's the same change just the form_id in condition and fields name: [alter the labels used on the login form](https://drupal.stackexchange.com/questions/269563/where-can-i-alter-the-labels-used-on-the-login-form/269564#269564)
Answer:
Simple Solution just change ['0']['#title'] by [0]['value']['#title'].

/**
 * @param $form
 * @param \Drupal\Core\Form\FormStateInterface $form_state
 * @param $form_id
 */
function MYMODULE_form_alter(&$form, Drupal\Core\Form\FormStateInterface $form_state, $form_id){
    if ($form_id == 'user_register_form') {
        $form['field_user_first_name']['widget'][0]['value']['#title'] = 'First Name';
        $form['field_user_last_name']['widget'][0]['value']['#title'] = 'Last Name';
        $form['field_user_phone_number']['widget'][0]['value']['#title'] = 'Phone Number';
        $form['field_user_country_of_residence']['widget'][0]['value']['#title'] = 'Country (of residence)';
    }
}

This solution a little bit complicated.
After i test your code, i did some search, i found this Post say

It is apparent that we modify any form in drupal by implementing hook_form_alter(). But there are cases when even the hook_form_alter() cannot offer a solution in altering the form fields.

I tried to use hook_element_info_alter as it suggested to alter fields.
In your case Here is the code bellow.

/**
* Implements hook_element_info_alter().
*/
function MYMODULE_element_info_alter(&$type) {
  if (isset($type['textfield'])) {
    $type['textfield']['#process'][] = 'MYMODULE_process_textfield';
  }
}
/**
* Process Callback Function
*
* Callback to process the User fields.
*/
function MYMODULE_process_textfield($element) {
  //- get the current route name
  $route_name = \Drupal::routeMatch()->getRouteName();
  if ($route_name == 'user.register' && isset($element['#array_parents'][0])) {
    switch ($element['#array_parents'][0]) {
      case 'field_user_first_name':
        $element['#title'] = 'New first name label';
        break;
      case 'field_user_last_name':
        $element['#title'] = 'New last name label';
        break;
      case 'field_user_phone_number':
        $element['#title'] = 'New phone numbe label';
        break;
      case 'field_user_country_of_residence':
        $element['#title'] = 'New country of residence label';
        break;
    }
  }
  return $element;
}

Note : all the four fields should be of type textfield Text (plain), otherwise you should add another process to other type, see the example in the article for password_confirm type.
Answer: following the link posted by @leymannx I clicked through to another question, which had the solution somewhere in the comments.
I forgot to put ['value'] in the string, so it had to be :
$form['field_user_first_name']['widget']['0']['value']['#title'] = 'First Name';

I can confirm it works with both :

['0'] and [0]
= t('first name') and = 'first name'

I doesn't work, at least for me, with omitting ['widget']['0']['value'], as suggested in alter the labels used on the login form – berramou
Answer: Try it without [0], I don't think you need this.

Edit
Okay let me rephrase my words per @leymannx. I have tested the code on my machine and removing [0] solves the problem and updates the label text. I was providing an answer and was not asking for more information or anything from the author.
Answer: In this approach, the hook is fired for all forms To avoid extra firing of the hook, use this approach (module name and form id)
function MYMODULE_user_register_form_alter(&$form, Drupal\Core\Form\FormStateInterface $form_state, $form_id){
  //do your alteration
}


Using with JSF - HIbernate validation fails (javax.validation.ConstraintViolationException)

Question: I'm using JSF, Spring and Hibernate. Post model has Hibernate annotated attributes:
@Entity
@Table(name = "posts")
public class Post implements Serializable {

    @Id
    @GeneratedValue(strategy = IDENTITY)
    @Column(name = "id")
    private Long id;

    private int version;

    @Column(name = "title")
    @NotEmpty(message = "Title should not be empty")
    private String title;

    ... getters/setters

}

When I try to create a new Post in the corresponding bean(disregard syntax proper à pretty-faces) :
@Component
@ManagedBean
@RequestScoped
@URLMappings(mappings = {
        @URLMapping(id = "posts", pattern = "/posts/", viewId = "/faces/posts/list.xhtml"),
        @URLMapping(id = "new", pattern = "/posts/new", viewId = "/faces/posts/new.xhtml")
})
public class PostBean {

    @Autowired
    private PostService postService;

    private List<Post> posts;

    private Post post = new Post();

    public List<Post> getPosts() {
        return postService.findAll();
    }

    public Post getPost() {
        return post;
    }

    public void setPost(Post post) {
        this.post = post;
    }

    public String create(Post post) {
        this.post = postService.save(post);
        return "pretty:posts";
    }
}

PostRepository:
public interface PostRepository extends CrudRepository<Post, Long> {
    public Post findByTitleIgnoreCase(String title);
}

PostServiceImpl:
@Service("postService")
@Repository
@Transactional
public class PostServiceImpl implements PostService {

    @Autowired
    private PostRepository postRepository;

    @Override
    @Transactional(readOnly = true)
    public List<Post> findAll() {
        return Lists.newArrayList(postRepository.findAll());
    }

    @Override
    @Transactional(readOnly = true)
    public Post findById(Long id) {
        return postRepository.findOne(id);
    }

    @Override
    @Transactional(readOnly = true)
    public Post findByTitleIgnoreCase(String title) {
        return postRepository.findByTitleIgnoreCase(title);
    }

    @Override
    @Transactional
    public Post save(Post post) {
        return postRepository.save(post);
    }

    @Override
    public void destroy(Post post) {
        postRepository.delete(post);
    }
}

I get the javax.validation.ConstraintViolationException. Strange is that if remove Hibernate annotation and put required="true" directly into the JSF page aside to the title textfield, it works.
<h:inputText id="title" value="#{postBean.post.title}" required="true"/>

Any idea ? You can find the project code source at my github repo
Thank you.
@NotNull is a JSR303 validation, @NotEmpty - is the one by Hibernate, that is the only difference. Even after changing for @NotNull I still get the same error.
[update] By the way, I removed @ManagedBean annotation, it is not needed anymore.
[update-2] @AVolpe: It will change nothing, just move the message to be displayed aside of the title textfield. The error happens when calling:
public String create(Post post) {
        this.post = postService.save(post);
        return "pretty:posts";
    }

Comment: Try adding the annotation `@NotNull` to your property, for `Bean-Validation` a property `null` without the `@NotNull` annotation is allways valid.
Comment: Try add a `` after the `inputText`.
Comment: Adding h:message for title will just display the error for title attribute.Error happens when calling postService.save(post).
Comment: I download your project and test it, I have many errors, but the original problemn don't occur (the validation works fine), I tested it with a jboss 7.1 (see http://postimg.org/image/pf31hehd1/), btw I have so many problem with the URL creation.
Comment: Right, I kept the working version. If you remove required="true" from posts/new page, and add @NotNull to the title attribute in the domain/Post.java, you will get the error. Just run mvm clean install to get all the dependencies and run the project on your server (I used Tomcat).
Comment: You can checkout the branch that raises the error from https://github.com/Javix/blog-jsf/tree/bean_validation
Comment: I deploy the requested version and the validation work's, see http://postimg.org/image/4sfiw61cf/. It's works with `@NotNull`, `@NotEmpty`, and `required = "false"`. Btw, I use a Jboss.
Comment: Not for me: http://postimg.org/image/kkuucqrct/. Be sure to redeploy the project from the bean_validation branch, please.
Comment: see http://stackoverflow.com/questions/23780474/primefaces-client-bean-validation-not-working it's maybe a problem with your JSF version, I change the scope in my machine to `provided` (because the jboss have the dependencies) and it's works fine. See this error report https://java.net/jira/browse/JAVASERVERFACES-3183
It's seems that if you downgrade the version to 2.2.4 (or upgrade to 2.27) its works fine.
Comment: Bravo! Fixed after upgrading com.sun.faces to 2.2.7. THANKS A LOT! I'll merge the fixed branch into master.
Comment: Please mark my answers as the correct one!, cheers, and thanks for make your project openSource, please add a licence.
Answer: Because this error the version 2.2.6 of JSF don't work well with BeanValidation, update to the version 2.2.7 or downgrade to 2.2.4.
See:
This answer
Answer: Fixed by upgrading jsf version up 2.2.7 as suggested by AVolpe.


Javascript global string replace with different elements from array?

Question: I'm a Javascript noob using regex in javascript to globally replace text on web page. Easy enough.
v = v.replace(/\Simon\b/g, "JS Noob");

I know I can replace with functions, but I can't get this to work:
v = v.replace(/\bSimon\b/g, function(replaceLoop) {
    var myStringArray = ["herp","derp","clueless","hurrrrr"];
    var arrayLength = myStringArray.length;
    for (var i = 0; i < arrayLength; i++){
        replaceLoop = myStringArray;
        return replaceLoop;
    }
}

I have a feeling I'm thinking about this all wrong.
Comment: and the question is.....?
Comment: What exactly are you trying to do? Also provide your input and expected output?
Comment: What does `replaceLoop` return exactly?
Answer: Step 1, make a function which returns the next item from an Array each time
function iterGen(arr, i) {
    i || (i = 0);
    return function () {
        i %= arr.length;
        return arr[i++];
    };
}

Step 2, pass this into your replace
v = v.replace(/\bSimon\b/g, iterGen(["herp","derp","clueless","hurrrrr"]));

Comment: Interesting, I took it as OP wanting a random index instead of iterating through with each replacement.
Comment: Starting form JS 1.7 you can simply do `var arr = [1, 2, 3], it = arr.iterator(), next = it.next.bind(it);`
Comment: @plalx I really like some things in 1.7, and many are re-designed and included in _ES 6_, but you can't rely on browser support for 1.7 - it's basically gecko only
Comment: I was unclear in my question... I was actually looking for a random index that, not really stepping through, since that would reach the end of the array. However, this is helpful and answers another question that I know I'll run into. Thank you.
Answer: A quick syntax error is causing issues, you are missing the closing ); to .replace().  Also, you are setting replaceLoop = myStringArray instead of a specific string.  Assuming you want a random index, you'll need Math.random().
v = v.replace(/\bSimon\b/g, function(replaceLoop) {
    var myStringArray = ["herp","derp","clueless","hurrrrr"];
    var arrayLength = myStringArray.length;
    var index = Math.floor(Math.random() * arrayLength);

    return myStringArray[index];
});

Comment: That's exactly it! I had a syntax error AND a conceptual mistake. Your answer solves both... thank you!


Email not sending from background in android?

Question: I am sending email in background in my app using code mention in this post: Sending Email in Android using JavaMail API without using the default/built-in app. I put a debug option in properties to check and verify email sending process like this:
props.put("mail.debug", "true");

and when i send mail from my app it shows following message like this "Please log-in to your account from you browser" i checked my password and email they are correct, please help me to figure out the actual problem.
Thanks!
Answer: First you Authenticate as sender's and then send email in your code like this using javax.mail
props.put("mail.smtp.user", "firstname.lastname@example.com");
       props.put("mail.smtp.host", d_host);
       props.put("mail.smtp.port", d_port);
       props.put("mail.smtp.starttls.enable", "true");
       props.put("mail.smtp.auth", "true");
       //props.put("mail.smtp.debug", "true");
       props.put("mail.smtp.socketFactory.port", d_port);
       props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
       props.put("mail.smtp.socketFactory.fallback", "false");

       try {
           Authenticator auth = new SMTPAuthenticator();
           Session session = Session.getInstance(props, auth);
           MimeMessage msg = new MimeMessage(session);

           msg.setSubject(m_subject);
           msg.setFrom(new InternetAddress("firstname.lastname@example.com"));
           msg.addRecipient(Message.RecipientType.TO, new InternetAddress("email@example.com"));

           Multipart multipart = new MimeMultipart();

           String data=" Hello There.";

           //attach Image
           BodyPart messageBodyPart = new MimeBodyPart();
        DataSource source = new FileDataSource(pathUserImg);
        messageBodyPart.setDataHandler(new DataHandler(source));
        messageBodyPart.setFileName("IMG_NAME.png");

        //attach String Data

MimeBodyPart messageBodyPart1 = new MimeBodyPart();
  messageBodyPart1.setText("data:  "+data);
        multipart.addBodyPart(messageBodyPart);
        multipart.addBodyPart(messageBodyPart1);

           msg.setContent(multipart );

          Transport.send(msg);

       } catch (Exception mex)
       {
           mex.printStackTrace();
           Log.v("TAG", " Email Not Sent "+mex.getMessage());
       }

   private class SMTPAuthenticator extends javax.mail.Authenticator
   {
       public PasswordAuthentication getPasswordAuthentication() {
           return new PasswordAuthentication(firstname.lastname@example.com@gmail.com", "YourPASSWORD");
       }
   }

Comment: Thanks for you comment,i am following exact procedure for sending mail as i mention in my post it is not working as well.
Comment: can put your code here? then i can try to find out what is wrong
Comment: also check for permissions
Comment: Hi am adding all necessary permission
 and code is exact same as this post:http://stackoverflow.com/questions/2020088/sending-email-in-android-using-javamail-api-without-using-the-default-built-in-a/2033124#2033124
Comment: do you get any exceptions in your logcat ? if you are getting NetWorkOnMainThread then you should do email sending process in AsyncTask. I would like to see your logcat if any exception occurs.


delete a certain comment in comment-reply system in php

Question: I have created a comment-reply system in php. It is similar to wall in facebook. User writes a comment and then post it in "wall". I use the following tables in my database to hold comments: comments(comments_id, comment, comment_date, user, comment_hash, flash) and table users that hold user's details: users(user_id, name, surname). Everything works perfect, the only problem is that I cannot delete a certain comment. Deleting a comment means to set flag=1 for this comment in my database.
On each comment there is a link named "delete". When user press delete, a light box starts in javascript and user by pressing delete, the function "deletepost" is executed. My only problem is that this function sets flag=1 to all comments in my databe and not for the certain comment that I press delete. Any idea how to improve my code?
I use the following function in order to display comments:
<?php
function getComments(){
  $session_user_id = $_SESSION['user_id'];
  $comments = "";
  $sql = mysql_query("SELECT * FROM comments WHERE (`flag`=0) ORDER BY comment_date DESC LIMIT 40") or die (mysql_error());

  if(mysql_num_rows($sql) == 0){
    $comments = "
  Write your first posts ...
 ";
  }
  else{

    while ($row= mysql_fetch_assoc($sql)) {
  $comment_id = $row['comments_id'];
      $hash = $row['comment_hash'];

      $personal_1 = mysql_query("SELECT `user_id`, `name`, `surname`, `email`, `profile` FROM `users` WHERE `user_id`='{$row['user']}' ");

        while ($run_personal_1= mysql_fetch_assoc($personal_1)) {
          $comment_user_id = $run_personal_1['user_id'];
          $comment_user_name = $run_personal_1['name'];
          $comment_user_surname = $run_personal_1['surname'];
        }

    // displays comment that includes user's name and surname and hash
    $comments .= " $comment_user_surname   $comment_user_name   $hash";
    $comments .= ".$row['comment'].";

//---- at this point I insert a delete link , that when user presses it a javascript light box ask user if wants to delete the comment. If user press the delete button it is called the function named "deletepost".

//---- first checks if the comment is from the user that is logged in ($session_user_id) in order to have the right to delete post

  if($comment_user_id == $session_user_id){
      if(isset($_POST['submit_2'])) {
        deletepost($session_user_id, $comment_id);
        header('Location: wall.php');
      }

  $comments .= <<<EOD
   Delete

    <form action="$_SERVER[PHP_SELF]" method="post">
    <input type="submit" name="submit_2" value="Delete Post ">
    </form>
    <button>Cancel</button>

  EOD;
  }

  }
    return $comments;
}
?>

I use the following function in order to post comments:
<?php
function postComments($comment){
    $comment = mysql_real_escape_string(strip_tags($comment));
        $session_user_id = $_SESSION['user_id'];
        $random_num = rand(0, 99999999999);
        $sql = mysql_query(" INSERT INTO `comments` (comment, comment_date, user, comment_hash) VALUES ('".$comment."', now(), '$session_user_id', '$random_num') ");
    return getComments();
}
?>

I use the following function in order to delete comments. Deleting comments means that I set flag=1, and in my function that displays the comments (function getComments), if flag is equal to 1 I do not display this comment:
<?php
function deletepost($comment_user_id, $comment_id){
$get_hash = mysql_query("SELECT `comment_hash` from `comments` WHERE (`user`='$comment_user_id' AND `comments_id` = '$comment_id')  ");
        while ($run_hash= mysql_fetch_assoc($get_hash)) {
            $hash = $run_hash['comment_hash'];
        }
    $sql="UPDATE `comments` SET `flag`=1 WHERE (`user`='$comment_user_id' AND `comment_hash`='$hash')";
$result=mysql_query($sql) or die("Error when trying to delete...");
}
?>

Comment: [Please, don't use `mysql_*` functions in new code](http://stackoverflow.com/q/12859942). They are no longer maintained [and are officially deprecated](http://php.net/mysql_connect). Learn about [prepared statements](http://en.wikipedia.org/wiki/Prepared_statement) instead, and use [PDO](http://php.net/pdo) or [MySQLi](http://php.net/mysqli) - [this article](http://php.net/manual/en/mysqlinfo.api.choosing.php) will help you decide which. [Here is a good PDO tutorial](http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers).
Comment: What does your database schema look like?
Comment: if you mean the tables, I have write them at the top
Comment: But what are the data types, what are the indexes, are you sure you set the primary key properly, etc.? Can you post the sql command you used to create the tables?
Comment: comments_id is the P.K and user is the user_id
Answer: My first instinct is to guess that comment_hash isn't working quite right, for whatever reason. Try simplifying your delete function:
function deletepost($comment_user_id, $comment_id){
    $sql="UPDATE `comments` SET `flag`=1 WHERE (`user`='$comment_user_id' AND `comments_id`='$comment_id')";
    $result=mysql_query($sql) or die("Error when trying to delete...");
}

I'm not sure why your current delete function is querying your database to grab a hash from a table and then using the hash to find the same row from the same table. It seems pointless and inefficient, and introduces more things that can break.
Incidentally, Vascowhite is correct that you shouldn't be using the old mysql library, but I don't think changing that would fix your problem here.
Comment: I have try it, but still set flag=1 to all comments in my table. I cannot see where is the mistake, that makes it apply to all and not for the certain comment
Comment: Hmm... Are you sure `comment_id` is being initialized properly? Something like this could happen if you forgot to set it to `AUTO_INCREMENT`.
Comment: Yes I have it AUTO_INCREMENT. I see my table in my database, and I see comments_id getting different values for each post.
Comment: is there any possibility the problem comes from within javascript?
Comment: Javascript? Only if it's somehow sending a separate delete request for each comment, which I suppose is not inconceivable. Take a look at the network requests your page is sending.
Comment: I think that the main problem comes from the while statement into which is called the deletepost.
Comment: It's being called inside a `while` loop? Why? That's definitely something to check out.
Comment: when I call deletepost at the end of function getComments(), before return $comments; it deletes only the last comment each time I press delete. But still not the selected comment
Comment: Okay, it seems like `deletepost()` is fine, and the problem is elsewhere. Since the problematic code is not in the question, there's not much I can do.
Comment: finaly the problem was in EOD I used. For some reason cannot allow me to pass all comments_id and passes only the 1st
Answer: In deletepost why did you run while loop to get the hash , if you are deleting one comment one time . Another thing is that flag=1 happens in all your comment because hash may be common for that users all comment . You need to make hash unique for every comment of a particular user .
Comment: any idea what to write to improve this?
Comment: Whenever you are inserting comment with respect to a particular user insert the comment in database with a unique hash code (Like make the hash code as a random number ) and while deleteing a comment for a particular user pass that users id and the random number in the function parameter and respect to the user id and number update the flag .


Why would I use static methods for database access

Question: So I came across this issues today and I couldn't find some meaningful explanation is there some non-subjective reason to use static methods when it comes to database interactions.
Right now I'm working on a project where everything is made through stored procedures and for example I have some regular methods like :
public void Delete(int clientID)
    {
      //calling store procedure
    }

or
public void Save(int clientID)
    {
      //calling store procedure
    }

but I also have :
public static Client GetByID(int id)
    {
        //calling stored procedure
    }

or
public static int AddNew(string firstName, string lastName...)
    {
      //calling store procedure
    }

and since I'm working with .NET for about 9 months and I've been using only Entity Framework and Repository Pattern I can't recall anywhere or any code where static methods were used. Not for standard CRUD operations, neither for more specific tasks related to the database.
So is this something related to the particular way that the database is accessed, is it some practice that can give (even a very small) performance boost, or it's just the developers approach and I shouldn't give it much of a thought when and when to not use static methods in my database related methods?
Comment: @Anon Yes, it is ASP.NET Web Forms application
Comment: More reading: http://stackoverflow.com/questions/241339/when-to-use-static-classes-in-c-sharp http://stackoverflow.com/questions/4963920/appropriate-use-of-static-method
Answer: In the particular case of a data access layer I'd avoid static methods for one simple reason... coupling.
Static methods can't implement an interface, instance methods can.  By using static methods one is essentially insisting against coding to an interface and instead coding to an implementation.  Thus, everything which uses this data access layer is required to this this specific data access layer at all times.
No alternate implementations, no test stubs, no dependency inversion at all.  The business logic has a dependency arrow pointing to an infrastructure concern (the data access layer), whereas that should be the other way around.

Additionally, it seems like this at least carries a greater risk of having problems with the disposal of resources.  That might not be the case here, but it's really easy for it to become the case.  What if a developer somewhere down the road has the bright idea to extract common lines of code into a class-level static method and property?  Something like the Connection or DBContext object?  That'll create some very interesting and very difficult-to-debug run-time errors.
On the other hand, if repositories were instances then they can simply implement IDisposable and make sure any class-level objects are correctly disposed.

Continuing (I guess I had more objections to the design than I thought), this feels very counter-intuitive to me from an object-oriented sense.  Perhaps this one is just personal preference, but this is turning what would otherwise be a "repository object" into a "dumping ground of DB helper methods."
In a system like this I would expect the number of random one-off methods to grow significantly over time as developers make quick solutions to meet requirements without thinking about the overall architecture.  Instead of a consistent and well-managed series of objects, you could very likely end up with a bloated and difficult-to-follow codebase.
Comment: Lol, as if you've described this exact project. I'm impressed how easy and even unnoticeable one thing can lead to another and end up, as you wrote, in a `"bloated and difficult-to-follow codebase"`. I'm gonna read your answer several times, it's a really good one. Thanks.
Comment: Awesome answer, and pretty perfectly describes my exact pains when trying to add in unit testing to an existing web app project I took over. I will definitely make use of this answer going forward!
Answer: Static methods are used when there is either no state, or shared state.  If you have code that is merely calling stored procedures, then it may have no state other than a shared database connection string.  This would be a valid use of static methods.
Comment: Well, for sure, there's no problem those methods to be static, but yet I wonder is there some more significant reason than the ability to make it static. It's working fine and all, but from what I've seen it's the first time I see someone making this kind of methods static, which from my experience is not the common practice. But of course I might be wrong as well, so I ask..
Comment: +1 for mentioning that calling stored procedures could result in the only shared data being the connection string. We use this in our software to maintain data consistency and security.
Answer: I think your last statement is correct; its just the previous developers approach.
I will say, though, that having those methods static is going to make your life a nightmare to create a testable product; if you have the power to change them to be instance based and create a set of unit tests that can test the app via mocks without needing a database it'll make your life easier in the long run.
Comment: We can't be sure from the posted example, but if these methods are merely calling stored procedures, then there may be nothing here to test or nothing to mock.
Answer: We very rarely use them here in our company, although they can serve a purpose in utility classes or things of the sort that are simply calling functions. Depending on how many instances you would expect of a non-static class, they can also affect performance., but that would need to be a notable instance difference.
source - MSDN


How to use a subquery instead of a joined query to get correct count with hibernate

Question: assuming I have following two tables (Cats with Kittens):
==== Cat.java ====
@Id @GeneratedValue( strategy = GenerationType.IDENTITY )
private long id;

@Column( unique = true, nullable = false )
private String name;

@OneToMany @JoinColumn( name = "cat_id" )
private List<Kitten> kitten;

==== Kitten.java ====
@Id @GeneratedValue( strategy = GenerationType.IDENTITY )
private long id;

@Column( unique = true, nullable = false )
private String name;

with the following data
Cat(id, name)
Cat(1, "Cat 1")
Cat(2, "Cat 2")

Kitten(id, cat_id, name)
Kitten(1, 1, "Kitten 1")
Kitten(2, 1, "Kitten 2")
Kitten(3, 2, "Kitten 3")
Kitten(3, 2, "Bad Kit")

Now I would like to see all cats which have a kitten whose name contains "kitten".
list = sess().createCriteria( Cat.class ).createAlias( "kitten", "kitten" )
.add( Restrictions.like( "kitten.name", "%kitten%" ) ).list();

The previous command is not very nice because of the join I will get duplicate entries and for example count and maxresult are not working. This is a well documented problem and it is mentioned to use subqueries instead.
I'm thinking of something like this (but with Criteria-Api):
from Cat where id in
(select cat_id from Kitten where name like '%kitten%')

This doesn't work because hibernate doesn't give me access to "cat_id" and I don't want to make it bidirectional just for this query.
Answer: Your query, if you just add a projection to get the cat ID, is the subquery you'd like to use. So you just need the following:
DetachedCriteria acceptedCatIds = DetachedCriteria.forClass(Cat.class);
acceptedCatIds.createAlias("kitten", "kitten")
              .add(Restrictions.like("kitten.name", "%kitten%" ))
              .setProjection(Projections.id());

Criteria acceptedCats = session.createCriteria(Cat.class)
acceptedCats.add(Subqueries.propertyIn("id", acceptedCatIds));

Answer: I would strongly recommend you to have Kitten containing reference to Cat too.  Though there is a bit more attention needed to keep the relationship consistent from both Kitten and Cat side, but it worth.
class Cat {

    @Id @GeneratedValue( strategy = GenerationType.IDENTITY )
    private long id;

    @OneToMany(mappedBy="parent")
    private List<Kitten> kitten;
}

class Kitten {

    @Id @GeneratedValue( strategy = GenerationType.IDENTITY )
    private long id;

    @Column( unique = true, nullable = false )
    private String name;

    @ManyToOne
    @JoinColumn( name = "cat_id" )
    private Cat parent;
}

The HQL should become as simple as what you want:
from Cat c where c in
(select parent from Kitten where name like '%kitten%')

or even
select distinct parent from Kitten where name like '%kitten%'


Make content in DataGrid columns which is populated by an sql table clickable, like a link

Question: How do I make it so that in the fields containing links in the image below, I can click on the link and that navigate me to the link I clicked on?
I have populated this using the SqlDataSource tool which come with asp.net; connecting it via a connection string to the DB.
Any advice would be helpful!
Thanks,
Callum
UPDATE
I have now solved the error. I have now custom data bound the datagrid with data; therefore I can have control over what goes into the gridview.
Thanks for all help!
Comment: which asp.net control you are using for links??
Answer: You can use Template Field in second columns instead and add Hyperlink control in that column. then Bind or Eval the NavigateUrl and Text to your column value.
Comment: Ah ok, could you please show me an example of how it would look?
Answer: if you are using Simple Lable then you can't use for Navigation
  <asp:HyperLink id="hyperlink1"
                  ImageUrl="images/pict.jpg"
                  NavigateUrl="http://www.microsoft.com"
                  Text="Microsoft Official Site"
                  Target="_blank"
                  runat="server"/>

Source Link


Is there an optimal bandwidth for a kernel density estimator of derivatives?

Question: I need to estimate the density function based on a set of observations using the kernel density estimator. Based on the same set of observations, I also need to estimate the first and second derivatives of the density using the derivatives of the kernel density estimator. The bandwidth will certainly have a great effect of the final result.
First, I know there are a couple of R functions that give the KDE bandwidth. I am not sure which one is more preferred. Can anyone recommend one out of these R functions for KDE bandwidth?
Secondly, for the derivative of KDE, should I choose the same bandwidth?
Comment: For a density the choice of bandwidth is always somewhat subjective.  It is a question of what is too narrow and therefore causes variation in the curve that is essentially following the noise vs too wide where the curve is too smooth and misses some real features in the curve.  But you estimate the density to find out the shape.  So how smooth the estimate should be is not easy to know.  For derivatives I would think it depends on what feature of the derivative you want to know about.
Answer: The optimal bandwidth for derivative estimation will be different from the bandwidth for density estimation. In general, every feature of a density has its own optimal bandwidth selector.
If your objective is to minimize mean integrated squared error (which is the usual criterion) there is nothing subjective about it. It is a matter of deriving the value that minimizes the criterion. The equations are given in Section 2.10 of Hansen (2009).
The tricky part is that the optimal bandwidth is a function of the density itself, so this solution is not directly useful. There are a number of methods around to try to deal with that problem. These usually approximate some functionals of the density using normal approximations. (Note, there is no assumption that the density itself is normal. The assumption is that some functionals of the density can be obtained assuming normality.)
Where the approximations are imposed determines how good the bandwidth selector is. The crudest approach is called the "normal reference rule" which imposes the approximation at a high level. The end of Section 2.10 in Hansen (2009) gives the formula using this approach. This approach is implemented in the hns() function from the ks package on CRAN. That's probably the best you will get if you don't want to write your own code. So you can estimate the derivative of a density as follows (using ks):
library(ks)
h <- hns(x,deriv.order=1)
den <- kdde(x, h=h, deriv.order=1)

A better approach, usually known as a "direct plug in" selector, imposes the approximation at a lower level. For straight density estimation, this is the Sheather-Jones method, implemented in R using density(x,bw="SJ"). However, I don't think there is a similar facility available in any R package for derivative estimation.
Rather than use straight kernel estimation, you may be better off with a local polynomial estimator. This can be done using the locpoly() function from the ks package in R. Again, there is no optimal bandwidth selection implemented, but the bias will be smaller than for kernel estimators. e.g.,
den2 <- locpoly(x, bandwidth=?, drv=1) # Need to guess a sensible bandwidth

Comment: Thanks a million, Rob. I will likely use SJ bandwidth for density estimation.
Comment: For derivative estimation, if I use h <- hns(x); den <- kdde(x, h=h, deriv.order=1), is h the optimal bandwidth used for the estimation. I am asking this because h <- hns(x) is chosen without specifying the derivative order. Thanks.
Comment: I checked the formula given at the end of Section 2.10 in Hansen (2009). It looks like the bandwidth depends on the order the derivative, say rth derivative.  h <- hns(x) does not seem to depend on the r.
Comment: (1) No. They are not using cross-validation. See the Hansen article.
(2) Use approx().


Indexing the term of unpublished entities

Question: I have a views of unpublished contents of content-type X, which has the Term Y.
It works fine with published content but a thing that I noticed is that if I unpublished a content that has a taxonomy term, in Views it loses the term associated with it, therefore I cannot filter my list based on taxonomy term anymore.
I also found Taxonomy Entity Index module but it doesn't work at all.
Also a related issue on drupal.org
Is there any workaround for this?
Answer: "Lookup published nodes with this taxonomy term" is such a common use-case that the Taxonomy module keeps a taxonomy_index table in the database to optimize for it.  This is what the Content: has taxonomy term ID views argument queries.  Unfortunately, it is only for published content.
In Drupal 8, there is a workaround. Taxonomy term fields are just a special case of Entity Reference fields, which have their own views argument handler, and do not partake of this special index.  So, if Content-type X has a 'Tags' field, you can build a view based around Content: Tags (field_tags), and that will include unpublished content as you'd expect.
Comment: This is what helped me - to filter by a field in my content type that uses taxonomy term as entity reference.  Thanks!
Answer: For anyone who might encounter the same issue:
It looks like that it's a common issue in D7 and unfortunately going to be in D8, but hopefully the fix will be in core for D9.
Right now we have to use TEI module as a workaround for D7 and D8.
If you are installing this module into an existing site, visit admin/config/system/taxonomy-entity-index to rebuild the Taxonomy Entity Index.
Also note that in Views there will be some new fields/filters to work with, for instance instead of Content: Has taxonomy terms in filters section of views, you should use Taxonomy Entity Index: Has taxonomy terms on Nodes and for exposing the taxonomy terms also you should use Taxonomy Entity Index: Has taxonomy terms on Nodes not the default Content: Has taxonomy terms.
Comment: Sohail wrote "Right now we have to use TEI module as a workaround for D7 and D8." But here: [TEI module](https://www.drupal.org/project/taxonomy_entity_index); I see that there is only drupal 7 and not drupal 8.
Comment: For D8, the TEI module isn't ready to use in prod.But @SeanC tips work.
Answer: On Drupal 8 :

Apply the patch from this issue
Clear cache : drush cr
Updade database : drush updb

It works for me.


How to take url output(JSON) as Java Variable

Question: I am trying to use the value of rate in the below JSON object as my variable.
URL is : http://rate-exchange-1.appspot.com/currency?from=USD&to=INR
Output of above URL is like " {"to": "INR", "rate": 64.806700000000006, "from": "USD"}  ". I am assuming it as JSON object. how to get the value of 64, shall i get it by parsing?
Comment: Possible duplicate of [How to parse JSON in Java](http://stackoverflow.com/questions/2591098/how-to-parse-json-in-java)
Comment: http://stackoverflow.com/questions/4308554/simplest-way-to-read-json-from-a-url-in-java
Answer: You can use JSONObject to convert strings into objects.
String responseString = "{'to': 'INR', 'rate': 64.806700000000006, 'from': 'USD'}";
JSONObject responseObject = new JSONObject(responseString);
Log.d("Response",responseObject.getString("rate")); //64.806700000000006

Comment: This requires that you download a JSON library (like Jackson, JSON, etc).  In this case, the library is [JSON]: https://mvnrepository.com/artifact/org.json/json
Comment: The OP only says they are using Java not Android studio. JSONObject is not part of the standard Java libraries.
Comment: You have the wrong language here. The OP is using Java not JavaScript
Comment: I'm using JSONObject without downloading any library in Android Studio 2.3 .
Answer: There're many options to deserialize JSON as mentioned in other answers, most of the time it would be better to define a corresponding Java class and then do serialization/deserialization. One example implementation with Gson would be:
public class Main {
    public static void main(String[] args) {
        Gson gson = new Gson();
        String jsonString = "{\"to\": \"INR\", \"rate\": 64.806700000000006, \"from\": \"USD\"}";
        CurrencyRate currencyRate = gson.fromJson(jsonString, CurrencyRate.class);
    }

    class CurrencyRate {
        private String from;
        private String to;
        private BigDecimal rate;

        public String getFrom() {
            return from;
        }

        public void setFrom(String from) {
            this.from = from;
        }

        public String getTo() {
            return to;
        }

        public void setTo(String to) {
            this.to = to;
        }

        public BigDecimal getRate() {
            return rate;
        }

        public void setRate(BigDecimal rate) {
            this.rate = rate;
        }
    }
}

And Gson is Thread Safe, so it's OK to init only one Gson instance and share it among all threads.
Answer: Q: how to get the value of 64, shall i get it by parsing?
A: Yes.
SUGGESTION:
You can also deserialize it into a Java object.
There are many libraries that support this, including:

JSONOjbect (Android)
GSon
Jackson


Why does laravel IoC does not provisioning my class with my method?

Question: I can't get why laravel tries to create my class itself, without using my method. I can see that IoC binding is executed (POINT 1 is shown). But singleton method is being never executed. Why?
In my service provider (not deferred):
/**
 * Register the service provider.
 *
 * @return void
 */
public function register()
{
    echo "POINT 1"; // I can see this one
    $this->app->singleton(\App\Services\FooBar::class, function($app)
    {
        echo "POINT 2\n"; // Does not comes here
        return new FooBar($params);
    });
}

I try to use typehinting to resolve dependencies when creating a class:
class Test
{
    public function __construct(FooBar $fooBar)
    {

    }
}

I see that laravel tries to create FooBar to inject it, but can't resolve FooBar's dependencies. They could be resolved, if laravel would call service provider callback, but it does not. Why? How to make laravel use that callback for that class?
Comment: How does the FooBar class looks like ? What are their dependencies. Laravel will not be able to resolve dependencies if they are not type hinted ie ``__construct($dep)`` will not work as you require ``$dep`` but dont pass the type of it. So you have to either ``__construct(SomeClass $dep)`` or ``__construct($dep=null)``.
Comment: So if your class looks like this then you should be able to just call ``app('Test')``. Do you get any specific error ? By the way this way you dont need to call ``$this->app->singleton`` unless you want to manually resolve the dependencies.
Answer: It is because when you are binding a class to IoC container you are not immediately calling the closure. Instead when you need to actually do some action on your class from container you call App::make('class') which would fire the closure and give you the value that was returned from it. So for example
/**
 * Register the service provider.
 *
 * @return void
 */
public function register()
{
    echo "POINT 1"; // I can see this one
    $this->app->singleton(\App\Services\FooBar::class, function($app)
    {
        echo "POINT 2\n"; // Does not comes here
        return new FooBar($params);
    });

    $this->app->make(\App\Services\FooBar::class); //here POINT 2 will be called first.
}

Comment: i understand this, but i can't call App::make for DI - it should be done automatically. How it is possible to achieve that?
Comment: I don't understand what you are trying to achieve. Can you provide some example of what you want to do ?
Comment: I want to make dependency injection working. Laravel allows to specify, for example parameters in constructors/etc with typehinting, and if it is possible it tries to resolve dependencies automatically. But it seems that laravel allows to do that only for contracts, not for class names.
Comment: Of course it does not. It will almost always be able to resolve dependencies from constructor if needed. It just depends on what you are trying to achieve. But mostly thing like ``$app->make(\App\Services\FooBar::class)`` will work unless in constructor you are passing some interfaces that were not binded to concrete implementations. In that case you will get ``BindingResolutionException``. Update your question and show what exacly does not work so I can help.
Answer: Instead of closure (that will not work), use boot() method to initiate your service.
/**
 * @param \App\Services\FooBar $foobar
 */
public function boot(\App\Services\FooBar $foobar)
{
    $foobar->setOptions(['option' => 'value']);
}

It will launch right after service will be instantiated.


Laravel Route Post not allowed

Question: I'm trying to create a route post in laravel, i use "get" and it works fine but when i use "post", "delete" etc not working it's returning error 500 (Internal Server Error).
There is my route code
    Route::post('Register' ,function(){
    return "Hello World";
});

I'm using extension for google chrome "Advanced REST client" to execute one "post", and that gives me that information
Request headers
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.80 Safari/537.36
Origin: chrome-extension://hgmloofddffdnphfgcellkdfbfbjeloo
Content-Type: application/json
Accept: */*
Accept-Encoding: gzip, deflate
Accept-Language: pt-PT,pt;q=0.8,en-US;q=0.6,en;q=0.4
Cookie: XSRF-TOKEN=

Response headers
Host: localhost:60967
Connection: close
X-Powered-By: PHP/5.5.12
Cache-Control: no-cache, private
date: Wed, 23 Dec 2015 01:51:29 GMT
Content-type: text/html

I'm searching for hours and i can't find a solution.
Comment: You need to check the log file. Maybe you got the problem with http://laravel.com/docs/5.1/routing#csrf-protection
Comment: Questions seeking debugging help ("why isn't this code working?") must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it in the question itself. Questions without a clear problem statement are not useful to other readers. See: How to create a Minimal, Complete, and Verifiable example.http://stackoverflow.com/help/mcve
Answer: Your XSRF token is missing. By default, all routes in a fresh Laravel application have CSRF protection turned on.
You will either need to add a valid token to your POST request header, or to the POST data itself by setting _token.
If you simply need to test the POST route itself, you can temporarily disable the CSRF middleware, or apply it on a case-by-case basis.
To Disable
app/Http/Kernel.php
protected $middlewareGroups = [
    'web' => [
        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        //\App\Http\Middleware\VerifyCsrfToken::class, //Comment this out
    ],
    'api' => [
        'throttle:60,1',
    ],
];
/**
 * The application's route middleware.
 *
 * These middleware may be assigned to groups or used individually.
 *
 * @var array
 */
protected $routeMiddleware = [
    'auth' => \App\Http\Middleware\Authenticate::class,
    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
    'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
    'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
];

To Enable as Route Middleware
app/Http/Kernel.php
protected $middlewareGroups = [
    'web' => [
        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
    ],
    'api' => [
        'throttle:60,1',
    ],
];
/**
 * The application's route middleware.
 *
 * These middleware may be assigned to groups or used individually.
 *
 * @var array
 */
protected $routeMiddleware = [
    'auth' => \App\Http\Middleware\Authenticate::class,
    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
    'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
    'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
    'csrf' => \App\Http\Middleware\VerifyCsrfToken::class, //Move it here
];

Comment: Anytime. Just remember: CSRF protection is *highly* recommended. If you disable it temporarily for testing purposes, that's fine. But I would highly recommend reenabling it globally, or at least applying it manually on any routes that are accepting user input.
Comment: I'm new with php and laravel, i didn't know that, i'm going to search about, and try to implement.
Comment: No worries. [Here's the latest documentation on CSRF Protection](http://laravel.com/docs/5.2/routing#csrf-protection). If you're not on 5.2, there's a dropdown in the upper-right hand corner to help you get to the right documentation. Good luck.
Answer:
have you tried to dump-autoload
composer dump-autoload

have you checked if the route is listed?
php artisan route:list

are you actually using a post (using a form or an app like POSTman)

Laravel Route Post not allowed


Criar uma tabela com datas

Question: Estou criando uma tabela e preciso que as colunas sejam criadas da seguinte maneira:
Seg, 23 Nov | Ter,24 Nov | Qua,25 Nov | Qui,26 Nov | Sex,27 Nov | Sab,28 Nov | Dom, 29 Nov
Para criar a Tabela eu passo por parâmetro uma data(que é selecionada através de um calendário)
Estou fazendo assim para criar a Tabela:
    DateTime diaAgenda = 'Data que foi selecionada no calendario';

    public DataTable gerarAgenda(DateTime dia)
    {
        DataTable tabela = new DataTable();

        string diahoje = String.Format("{0:ddd, MMM d, yyyy}", dia);

        tabela.Columns.Add("" + diahoje);

        for (int data = 1; data < 7; data++)
        {
            dia = dia.AddDays(1);
            diahoje = String.Format("{0:ddd, MMM d, yyyy}", dia);
            tabela.Columns.Add("" + diahoje);
        }
        return tabela;
    }

Fazendo dessa forma a tabela que eu gero fica com as seguintes colunas:
Qui,26 Nov | Sex,27 Nov | Sab,28 Nov | Dom, 29 Nov | Seg, 30 Nov | Ter,01 Dez | Qua,02 Dez |
Como eu poderia fazer para criar as colunas assim:
Seg, 23 Nov | Ter,24 Nov | Qua,25 Nov | Qui,26 Nov | Sex,27 Nov | Sab,28 Nov | Dom, 29 Nov
Comment: Sua pergunta está bem confusa. Por que não consegues fazer que a primeira coluna seja segunda?
Comment: Pra que serve o parâmetro `dia`? Você está gerando uma tabela com base nele?
Comment: Pergunta ruim gera respostas ruins :)
Comment: Realmente @bigown. Você viu aquele `switch-case` na segunda resposta? Será que é o caso de votar para fechar como **não está clara o suficiente**?
Comment: porque eu não sei como definir que a semana sempre inicie na segunda..
Comment: @jbueno o parâmetro eu passo o dia..
Comment: Isso eu percebi pelo nome do mesmo. A questão é: pra que serve o parâmetro?
Comment: Editei a pergunta. Ficou mais claro?
Answer: Se eu entendi o seu problema então diria que é simplesmente o parâmetro dia que você esta passando. Você não esta passando ele marcando uma Segunda-feira, por isso ocorre o "erro" de não começar na segunda como você deseja.
public DataTable gerarAgenda(DateTime dia)
{
    switch(dia.DayOfWeek)
    {
        case DayOfWeek.Tuesday: dia.AddDays(-1); break;
        case DayOfWeek.Wednesday: dia.AddDays(-2); break;
        case DayOfWeek.Thursday: dia.AddDays(-3); break;
        case DayOfWeek.Friday: dia.AddDays(-4); break;
        case DayOfWeek.Saturday: dia.AddDays(-5); break;
        case DayOfWeek.Sunday: dia.AddDays(-6); break;
    }

    DataTable tabela = new DataTable();

    string diahoje = String.Format("{0:ddd, MMM d, yyyy}", dia);

    tabela.Columns.Add("" + diahoje);

    for (int data = 1; data < 7; data++)
    {
        dia = dia.AddDays(1);
        diahoje = String.Format("{0:ddd, MMM d, yyyy}", dia);
        tabela.Columns.Add("" + diahoje);
    }
    return tabela;
}

Comment: Como eu marco para o dia = Segunda feira?
Answer: Você pode verificar se é segunda feira dessa forma..
if(dia == DayOfWeek.Saturday)

Comment: `Saturday`? '-'
Comment: Mas em fim, fui o primeiro a dar a dica o resto foi copia
Comment: @jbueno ...maldito... Nem vou editar ficar com seus dois pontos uteis shuahs ....Monday .... `if(dia == DayOfWeek.Monday )`
Answer: Ah! Vc quer que a primeira coluna seja a SEGUNDA FEIRA, é isso?
Testa aí:
var diaDaSemana = (int) dia.DayOfWeek;
var inicioDaSemana = dia.AddDays(diaDaSemana-1);
for (int dias = 1; dias < 7; dias++)
{
    data = inicioDaSemana.AddDays(dias);
    dataFormatada = String.Format("{0:ddd, MMM d, yyyy}", data);
    tabela.Columns.Add("" + dataFormatada);
}

Mas aproveitando a deixa, parece muito anti produtivo - ou até mesmo inadequado - o que vc está tentando fazer.
Recomendo dar uma refatorada nesse código. Está muito estranho o resultado final dele.

Criar uma tabela com datas


Particle's acceleration when it achieves maximum displacement in the +x direction

Question: I'm not sure if this goes in the physics section or the mathematics section, but this question seems pretty math oriented, so I'll ask it here.
$t\ge0$ and $v_x=24-3t^3$
I have to find the particle's acceleration when it achieves maximum displacement in the $+x$ direction. I'm not sure how to know exactly when the particle hits maximum displacement.
Answer: HINT:
Maximum displacement occurs at the time when the velocity reaches zero.  (Why?  You can think either from a physical perspective or a mathematical one.)
And acceleration is the derivative of the velocity with respect to time.
Can you proceed now?
Comment: Do I do $0=24-3t^3$ to find t first, and then plug it into the derivative of the velocity equation?
Comment: Yes!  It sounds as if you have it.  Well done.
Comment: The question right before this one asked what the acceleration is when the velocity first reaches zero... is this the same exact thing?
Comment: Yes.  It is the same thing.


add/remove socket descriptors from poll()

Question: I have a TCP server application in which on receiving an incoming connection, I accept the connection and add the socket descriptor to a list. The server needs the list so it can iterate through the list and send data to all the connected clients periodically.
If any of the clients closes the connection, the corresponding socket descriptor needs to be deleted from the list.
I have tried adding the descriptors to poll() so I can detect any closed connection with may be POLLHUP, but I can't figure out how to interrupt poll to dynamically add descriptors to its set on every incoming new connection.
The server just needs the list of descriptors of all open connections whenever it wants to send data.
How do I go about this? Any suggestions?
EDIT: Here's what I did: I created a thread for each client and added its fd to poll.
Pseudo-code on server:
sockfd = accept the conn.
pthread_create

// Inside the thread, add sockfd to poll
struct pollfd fds[1];
fds[0].fd = sockfd;
poll(fds, 1, 500000);
Check for POLLHUP returned event and see which client(fd) closed the connection.

This seems to poll all the descriptors, but my problem now is that when I tested closing the connections with two clients..only one of the descriptors returns POLLHUP.
Comment: After testing with multiple clients I have observed that POLLHUP is triggered by closing of any of the sockets except for the first client that connected to the server.
Answer:
I can't figure out how to interrupt poll to dynamically add
  descriptors to its set on every incoming new connection

You should be monitoring the listening socket for activity. Once poll unblocks the first thing you check is "has my listening socket become interesting?". If so, accept and add to poll and your own list.


Erro ao inserir dados nas tabelas do MySQL

Question: Quando eu insiro os dados nas tabelas aparece o seguinte erro:
ERROR CODE: 1265, data truncate for column 'genero' at row 13
Como resolve esse erro?
create database sf;
use sf;

create table time1(
    id_time1 int primary key not null,
    nome varchar(50),
    arte_marcial varchar(50),
    pais_origem varchar(50),
    genero enum('M','F'),
    data_nascimento date,
    altura decimal (3,2),
    peso decimal (5,2)
);

insert into time1 (id_time1, nome, arte_marcial, pais_origem, genero, data_nascimento, altura, peso)
values
(1,'Ryu','Ansatsuken','Japão','M','1964-07-21',1.75,84.00),
(2,'Ken','Ansatsuken','USA','M','1965-02-14',1.80,72.00),
(3,'Chun-Li','Wushu','China','F','1968-01-03',1.78,63.00),
(4,'Akuma','Ansatsuken','Japão','M','1945-06-21',1.82,90.00),
(5,'Guile','Técnicas Militares','USA','M','1960-12-23',1.65,96.00),
(6,'Cammy White','Delta Red','Inglaterra','F','1974-01-06',1.52,60.00),
(7,'Honda','Sumô','Japão','M','1960-11-03',1.85,137.00),
(8,'Fei Long','Kung Fu','China','M','1969-04-23',1.72,60.00),
(9,'Blanka','Capoeira','Brasil','M','1966-02-12',1.92,96.00),
(10,'Vega','Ninjitsu Espanhol','Espanha','M','1967-01-27',1.86,72.00),
(11,'Dhalsim','Kabbadi','Índia','M','1952-11-22',1.76,48.00),
(12,'Balrog','Boxe','USA','M','1968-09-04',1.98,102.00),
(13,'Mr. Bison','Psycho Power','Tailândia','M','1945-04-17',1.77,112.00),
(14,'Sagat','Muay Thai','Tailândia','M','1955-07-02',2.26,109.00),
(15,'Zangief','Sambo','Rússia','M','1956-06-01',2.13,180.00)

create table time2(
    id_time2 int primary key not null,
    nome varchar(50),
    arte_marcial varchar(50),
    pais_origem varchar(50),
    genero enum('M','F'),
    data_nascimento date,
    altura decimal (3,2),
    peso decimal (5,2)
);

insert into time2 (id_time2, nome, arte_marcial, pais_origem, genero, data_nascimento, altura, peso)
values
(1,'T.Hawk','Luta Indígena','USA','M','1959-07-21',2.30,162.00),
(2,'Dee Jay','Kickboxing','USA','M','1965-10-31',1.84,92.00),
(3,'Rainbow Mika','Wrestling','Japão','F','1969-05-27',1.68,69.00),
(4,'Sakura','Ansatsuken','Japão','F','1973-03-15',1.57,42.00),
(5,'Karin','Kanzukiryu Kakutoujutsu','Japão','F','1973-09-15',1.62,48.00),
(6,'Juri','Tae Kwon Do','Coréia do Sul','F','1970-01-01',1.65,46.00),
(7,'Nash','Técnicas Militares','USA','M','1962-11-01',1.86,93.00),
(8,'Ibuki','Ninjitsu','Japão','F','1979-12-06',1.62,55.00),
(9,'Elena','Capoeira','Quênia','F','1981-09-18',1.83,54.00),
(10,'Laura','Jiu-Jitsu','Brasil','F','1986-07-30',1.75,72.00),
(11,'Rose','Soul Power','Itália','F','1957-07-03',1.78,54.00),
(12,'Hugo Andore','Whestling','Alemanha','M','1964-05-19',2.40,260.00),
(13,'Poison','Luta Acrobática Autodidata','USA','T','1978-12-07',1.75,52.00),
(14,'Alex','Whestling','USA','M','1970-05-15',1.95,111.000),
(15,'Adon','Muay Thai','Tailândia','M','1967-06-28',1.82,73.00)

create table cenario(
    id_cenario int primary key not null,
    nome_cenario varchar (50),
    pais_cenario varchar (50),
    id_time1 int,
    id_time2 int,
    foreign key (id_time1) references time1 (id_time1),
    foreign key (id_time2) references time2 (id_time2)
);

insert into cenario (id_cenario, nome_cenario, pais_cenario, id_time1, id_time2)
values
(1,'Matsue Castle','Japão',1,1),
(2,'Wan Chai','China',2,2),
(3,'Thrissur Pooram Festival','Índia',3,3),
(4,'Ayutthaya','Tailândia',4,4),
(5,'Hakone Kowakien Yunessun','Japão',5,5),
(6,'Parque Museo La Venta','México',6,6),
(7,'Lichtenstein Castle','Alemanha',7,7),
(8,'Manaus','Brasil',8,8),
(9,'Edradour Distillery','Escócia',9,9),
(10,'The Golden Nugget Hotel and Casino','USA',10,10),
(11,'Vulcão Kilawea','USA',11,11),
(12,'Mykonos','Grécia',12,12),
(13,'San Francisco','USA',13,13),
(14,'Todaiji Temple','Japão',14,14),
(15,'Novosibirsk','Rússia',15,15)

Comment: (13,'Poison','Luta Acrobática Autodidata','USA','T','1978-12-07',1.75,52.00). O gênero "**T**" por um acaso está correto?
Comment: É mesmo, por causa que **Poison** na franquia ela é **transsexual**. Realmente não tinha percebido isso, vou alterar aqui.
Comment: @CaiodePaulaSilva muito obrigado, o problema era esse mesmo e agora tudo está resolvido.
Answer: Com base no que @CaiodePaulaSilva disse ficaria assim:
create database sf;
use sf;

create table time1(
    id_time1 int primary key not null,
    nome varchar(50),
    arte_marcial varchar(50),
    pais_origem varchar(50),
    genero enum('M','F','T'), # Linha alterada
    data_nascimento date,
    altura decimal (3,2),
    peso decimal (5,2)
);

insert into time1 (id_time1, nome, arte_marcial, pais_origem, genero, data_nascimento, altura, peso)
values
(1,'Ryu','Ansatsuken','Japão','M','1964-07-21',1.75,84.00),
(2,'Ken','Ansatsuken','USA','M','1965-02-14',1.80,72.00),
(3,'Chun-Li','Wushu','China','F','1968-01-03',1.78,63.00),
(4,'Akuma','Ansatsuken','Japão','M','1945-06-21',1.82,90.00),
(5,'Guile','Técnicas Militares','USA','M','1960-12-23',1.65,96.00),
(6,'Cammy White','Delta Red','Inglaterra','F','1974-01-06',1.52,60.00),
(7,'Honda','Sumô','Japão','M','1960-11-03',1.85,137.00),
(8,'Fei Long','Kung Fu','China','M','1969-04-23',1.72,60.00),
(9,'Blanka','Capoeira','Brasil','M','1966-02-12',1.92,96.00),
(10,'Vega','Ninjitsu Espanhol','Espanha','M','1967-01-27',1.86,72.00),
(11,'Dhalsim','Kabbadi','Índia','M','1952-11-22',1.76,48.00),
(12,'Balrog','Boxe','USA','M','1968-09-04',1.98,102.00),
(13,'Mr. Bison','Psycho Power','Tailândia','M','1945-04-17',1.77,112.00),
(14,'Sagat','Muay Thai','Tailândia','M','1955-07-02',2.26,109.00),
(15,'Zangief','Sambo','Rússia','M','1956-06-01',2.13,180.00)

create table time2(
    id_time1 int primary key not null,
    nome varchar(50),
    arte_marcial varchar(50),
    pais_origem varchar(50),
    genero enum('M','F','T'), # Linha alterada
    data_nascimento date,
    altura decimal (3,2),
    peso decimal (5,2)
);

insert into time2 (id_time2, nome, arte_marcial, pais_origem, genero, data_nascimento, altura, peso)
values
(1,'T.Hawk','Luta Indígena','USA','M','1959-07-21',2.30,162.00),
(2,'Dee Jay','Kickboxing','USA','M','1965-10-31',1.84,92.00),
(3,'Rainbow Mika','Wrestling','Japão','F','1969-05-27',1.68,69.00),
(4,'Sakura','Ansatsuken','Japão','F','1973-03-15',1.57,42.00),
(5,'Karin','Kanzukiryu Kakutoujutsu','Japão','F','1973-09-15',1.62,48.00),
(6,'Juri','Tae Kwon Do','Coréia do Sul','F','1970-01-01',1.65,46.00),
(7,'Nash','Técnicas Militares','USA','M','1962-11-01',1.86,93.00),
(8,'Ibuki','Ninjitsu','Japão','F','1979-12-06',1.62,55.00),
(9,'Elena','Capoeira','Quênia','F','1981-09-18',1.83,54.00),
(10,'Laura','Jiu-Jitsu','Brasil','F','1986-07-30',1.75,72.00),
(11,'Rose','Soul Power','Itália','F','1957-07-03',1.78,54.00),
(12,'Hugo Andore','Whestling','Alemanha','M','1964-05-19',2.40,260.00),
(13,'Poison','Luta Acrobática Autodidata','USA','T','1978-12-07',1.75,52.00),
(14,'Alex','Whestling','USA','M','1970-05-15',1.95,111.00),
(15,'Adon','Muay Thai','Tailândia','M','1967-06-28',1.82,73.00)

insert into cenario (id_cenario, nome_cenario, pais_cenario, id_time1, id_time2)
values
(1,'Matsue Castle','Japão',1,1),
(2,'Wan Chai','China',2,2),
(3,'Thrissur Pooram Festival','Índia',3,3),
(4,'Ayutthaya','Tailândia',4,4),
(5,'Hakone Kowakien Yunessun','Japão',5,5),
(6,'Parque Museo La Venta','México',6,6),
(7,'Lichtenstein Castle','Alemanha',7,7),
(8,'Manaus','Brasil',8,8),
(9,'Edradour Distillery','Escócia',9,9),
(10,'The Golden Nugget Hotel and Casino','USA',10,10),
(11,'Vulcão Kilawea','USA',11,11),
(12,'Mykonos','Grécia',12,12),
(13,'San Francisco','USA',13,13),
(14,'Todaiji Temple','Japão',14,14),
(15,'Novosibirsk','Rússia',15,15)