Factoring a polynomial modulo prime

Question: How would I go about factoring a polynomial $x^{5}-4$ over a finite field $\mathbb{F}_{29}=\mathbb{Z}/29\mathbb{Z}$? I know that $29$ is prime, so that will be relevant at the very least. Moreover, if we solve the equation $x^{5}\equiv 4 \mod 29$, we would get the solution $x=6$ unique up to modulo $29$. Is there a way to factor this over $\mathbb{Z}/29\mathbb{Z}$ by using the solution obtained from the equation?
Comment: You are correct, there is a unique solution. Try to divide your polynomial by $x-6$
Comment: Then one has to worry about whether the remaining quartic factor is a product of two quadratic factors.
Answer: In finite fields, you have the advantage that given any $n \in \Bbb N$, there are only finitely many polynomials of degree $\le n$. In particular, there are only finitely many irreducible ones.
Now, in your example, you have already found a root of the polynomial. So, you can do the usual polynomial division to get $$x^5 - 4 = (x - 6)(x^4 + 6x^3 + 7x^2 + 13x + 20).$$
Now, you could check if $6$ is again a root of the quartic. This will not be the case. Since you already observed that the original polynomial has no root apart from $6$, you can conclude that the quartic has no root.
Thus, you have two cases now:

The quartic is irreducible. (Meaning it has no proper factors.)
The quartic is a product of two irreducible quadratics.

You could now try to list all (monic) irreducible quadratics over $\Bbb F_{29}$. These will be precisely those quadratics that have no root. Due to this, our life will be simpler.
(Note that this trick only works for quadratics and cubics. For higher degree polynomials, it may very well be the case that it is reducible but has no root.)
Of course, this is much easier to do by hand for the case of $\Bbb F_p$ with $p$ much smaller than $29$. In your case, there are $29^2 = 841$ monic quadratics. You would have to figure out which ones are irreducible. (You can note that $841 - 435  = 406$ would be irreducible.) It would probably be best to use some sort of program for this.

Factoring a polynomial modulo prime


Como obter o número de telefone via facebook API

Question: Estou implementando login via facebook em meu site e parece que não é mais possível obter o número de telefone do usuário, mesmo com a sua autorização.
https://developers.facebook.com/blog/post/2011/01/14/platform-updates--new-user-object-fields--edge-remove-event-and-more/
Esse post é de 2011. Pelo que entendi, é uma funcionalidade que existia e foi removida para que fosse aperfeiçoada a maneira pela qual o usuário é informado que o aplicativo vai extrair essa informação e que nas próximas semanas isso seria reabilitado.
Não encontrei mais nada a respeito. Pergunto: não é mesmo possível obter o celular do usuário que autorize isso?
Answer: Felizmente/Infelizmente não é mais possível pegar o telefone do usuário via API.
Ano passado fiz esta pergunta para a Luz Caballero, Facebook Developer Advocate, na PHP Conference Argentina 2013 e ela disse "não há nenhuma maneira de recuperar o número de telefone do usuário através da API. Este foi um breve recurso, mas foi retirado pouco depois".
Comment: @LuizVieira procurarei o cartão dela e ver se ela me responde por e-mail com algum link ou mais alguma informação e posto aqui.
Comment: Pelo aviso (2011!) parece que a remoção era pra ser algo temporário: "We'll be working to launch these updates as soon as possible, and will be *temporarily disabling* this feature [...] We look forward to re-enabling this [...]." Você consegue com o seu contato ao menos um link para alguma informação mais recente e, principalmente, definitiva?


Series of ln(x) for x>=1

Question: I need to develop $\mathrm{ln}(x)$ into series, where $x \geq 1$, and I don`t know how? In literature I only found series of $\mathrm{ln}(x)$, where:

$|x-1| \leq 1 \land x \neq 0$, $ \,\,\,\,\, \mathrm{ln}(x) = x - 1 - \dfrac{(x-1)^2}{2} + ...$

$|x| \leq 1 \land x \neq -1$, $ \,\,\,\,\, \mathrm{ln}(x+1) = x - \dfrac{x^2}{2}+ ...$

My problem is problem in area of fluid dynamics, and $x$ is non-dimensional coordinate and it signifies radial coordinate of annular tube (it starts in the center of the tube). At the wall of inner tube $x=1$, and at the wall of outer tube it only can be larger (and values are not limited), because of that I need to fulfill a condition $x \geq 1$, for developing $\mathrm{ln}(x)$ into series.
===================================================================
Additional explanation:
I am looking for series of $\mathrm{ln}(x)$, where $x \geq 1$, because I have two integrals that I can't solve. That is, I can solve it in Wolfram Mathematica (I don't know how to solve it analyticaly), but in obtained solution appear Gamma and ExpIntegralEi function. These functions are formulated  over an imaginary number $z=x+iy$, and the solutions of my integrals represents the mass flow and the pressure field in the pipe. So, in my solution I got Gamma function, formulated over $z=x+iy$, on the other side I am sure that solution of mass flow does not contain any imaginary number. Maybe the right question is: what is the behavior of Gamma and ExpIntegralEi function? Could I look at these functions as black boxes? And if input is real number ($0i$) will the output be a real number?
Integrals:
$$\int \dfrac{ r^3 + r \mathrm{ln}r}{\mathrm{ln}r}\mathrm{d}r$$
$$\int \dfrac{r}{(\mathrm{ln}r)^{0.5} }\mathrm{d}r$$
Comment: There is no power series which only converges for $x \ge 1$. A power series which converges for arbitrarily large positive $x$ must also converge for arbitrarily large negative $x$ - and there is no such series for $\ln$. What do you need the series for? We may be able to help solve your real problem.
Comment: I concur with preferred_anon here. The domain of $\ln$ is $\{x\in\mathbb{R}\,:\,x\gt0\}$. Due to the natural boundary at 0, any series expansion of $\ln$ can only have a finite radius of convergence. If the center of expansion is $p$, then the radius of convergence is also $p$, meaning that the series converges for $0\lt{x}\leq2p$. But as such, it is not possible to give an expansion for $\ln$ that converges for every $x\geq1$. There is also no non-trivial asymptotic expansion for $\ln$. So you will need to provide more context here.
Comment: Are you restricting yourself to Laurent series?
Comment: I added explanation why I am looking for series of ln(x), shortly: because I have two integrals with ln(x) that I cannot solve.
Answer: If I understand correctly, I am allowed to assume that for all $y$ such that $1 \leq y < 2$, you are able to satisfactorily express $\ln(y)$ as a series.
Given $x$ such that $2 \leq x$, let $r$ denote the largest positive integer such that $2^r \leq x$.
Define $\displaystyle y = \frac{x}{2^r} \implies 1 \leq y < 2.$
Further, $\ln(y) = \ln(x) - r\ln(2)$.
Therefore, since $\ln(2)$ is a constant, as long as it is acceptable to be able to assume that $r$ may be computed in terms of $x$, then you are done.
One approach that you may or may not consider acceptable is to define $r$ as $\displaystyle \left\lfloor \frac{\ln(x)}{\ln(2)}\right\rfloor,$ where $\lfloor a\rfloor$ denotes the largest integer $\leq a.$
Answer: Render $y=(x-1)/(x+1), \therefore x=(1+y)/(1-y)$. With the aid of the familiar Maclaurin series render
$\ln x =\ln(1+y)-\ln(1-y)=[y-\dfrac{y^2}2+\dfrac{y^3}3-...]-[-y-\dfrac{y^2}2-\dfrac{y^3}3-...]$
$=2y+\dfrac{2y^3}3+\dfrac{2y^5}5+...$
$=\dfrac{2(x-1)}{x+1}+\dfrac{2(x-1)^3}{3(x+1)^3}+\dfrac{2(x-1)^5}{5(x+1)^5}+...$
which by the ratio test converges for all positive $x$. Also for all positive $\Re(x)$ in the complex domain.
Comment: +1 : Clearly better than my answer.

Series of ln(x) for x>=1


BizTalk configuration troubleshooting

Question: I am trying to configure BTS 2016 3.12.774.0 against SQL Server v 17.9.1.  They are running on separate servers running Windows server 2016 64 bit OS.
The Enterprise Single Sign On database (SSODB) and the Business Rules Engine DB (BizTalkRuleEngineDB) get created but only to BRE is configured when I go into Biztalk Config.
I have had the servers rebooted but no change.
The Ent SSO Service does not exist in Services
User doing the install is in groups Biztalk Server Admin, Application Users, Server Operators and SSO Admin, Affiliate Admin all at the domain level.
Names of both servers are 13 characters.
Not sure what to look for in the configuration logs.  I have searched for the words Error, Fail, Exception but there are none.
A new attempt to configure gave the following error:

Microsoft BizTalk Server Configuration Wizard ------------------------------ Failed to create the SQL database 'SSODB' on SQL Server 'servername10' (with SSO Administrator account 'SSO Administrators'). (SSO) For help, click: go.microsoft.com/fwlink/… ------------------------------ ADDITIONAL INFORMATION: (0xC0002A21) An error occurred while attempting to access the SSO database. (SSO) For help, click: go.microsoft.com/fwlink/… ------------------------------ An error occurred while attempting to access the SSO database. See the event log (on computer 'servername10') for more details. (SSO)
Comment: "See the event log (on computer 'servername10') for more details" What does the Event Log say?
Comment: @Johns-305 Basically the same.  Here is what is strange.  It says it is trying to create the SSODB on the BTS Server NOT the SQL Server.  But I specified the SQL Server in the definition

[7:24:46 PM Info SSOServerCfg] (ssoconfigobj2.cpp:5164) Returning error description:
Answer: There is no SQL Server v 17.9.1.  That version number is one for SSMS.
BizTalk Server 2016 does not support SQL Server 2017.  Hardware and Software Requirements for BizTalk Server 2016
Please post the error text, either from the little red X or the error log.  There will always be an error.  BT Config will never silently fail.

BizTalk configuration troubleshooting


Fake proof regarding continuity.

Question:
So to my understanding the fallacy in this argument is that it's circular. Since he didn't declare an ϵ at the beginning of the proof, his choice of ϵ is dependant on δ, which in turn is dependant on ϵ. We were taught to always begin our proofs with "Let ϵ>0 ... ", or "We choose ϵ=[blank/fill in later]>0 ... " and the fact that he doesn't raised my suspicion. But I can't TRULY point out his mistake, and my thought regarding the fallacy is purely intuitive, and the fact that everything else looks fine really makes me wonder if there is something that I am missing..
Comment: The "proof" is sly in that it doesn't say what $\epsilon_0$ is when it is first brought up, making it seem like we have an implicit "for all $\epsilon_0$...". But we haven't fixed such an $\epsilon_0$ yet, and if we had, it certainly doesn't necessarily need to be the number called "$\epsilon_0$" which is introduced after $\delta_1$ has already been defined (in terms of $\epsilon_0$, as you noticed). So the issue really comes down to omitting details to make the following conflation of (potentially different) $\epsilon_0$'s less noticeable.
Comment: As much as I want to go into this rabbit hole of inequality systems, I'm certain they wouldn't give us a problem that is that detail oriented, I might be wrong, but I'm pretty sure that the whole point of this question is to make us more aware of the structure of our proofs.. Also he has been dropping hints all weeks about circular arguments and proof structure so I guess it's his way of helping us..
Comment: hey again :)  I'm also trying to figure out what is the problem. I actually think that the choice of epsilon is ok, but take a look at student A definition of $\delta_{1}$. before "(surly, there exists such a delta)". note that there is an option which n+$\delta_{1}$ in smaller then $x_{1}+\delta$.
Comment: I think it is used to throw us off, since such a delta truly must exist haha. :)
Comment: I edited the comment, so read it again:)
Answer: The catch is that when it states that "there exists an $ \epsilon_0 > 0 $", this $ \epsilon_0 $ depends on $ x_1 $, it is $ \epsilon_0(x_1) $. But $ x_1 $ was chosen based on $ \delta_1 $ which in turn was defined based on the choice of $ \epsilon_0 $. So the first $ \epsilon_0 $ and the second are not the same positive number!
The second $ \epsilon_0 $ is equal to $ \epsilon_0 = \epsilon_0 (x_1(\delta_1(\epsilon_0))) $
Comment: That is basically the difference between "for all" and "there exists". There exists $ \epsilon $ implies that this number is specific.
Comment: i don't see how $\epsilon_0$ is dependent. there is no statement "there exists an ϵ0>0" so $\epsilon_0$ can be replaced with any positive number

Fake proof regarding continuity.


My centOS 7 minimal font screwed up when trying to tail modsecurity audit log

Question: My font display was completely normal. But right after i cat or tail /var/log/modsec_audit.log, my font becomes like this. Any solution?
Image link:
https://i.stack.imgur.com/XkIyj.png
Answer: execute the command reset in your console.
if this doesn't do the trick:

press: CTRL+J
type: reset
press CTRL+J again
Comment: Problem solved :D ty sir


What is the difference between declaring data attributes inside or outside __init__

Question:
Possible Duplicate:
Python: Difference between class and instance attributes

I'm trying to get my head around OOP in Python and I'm a bit confused when it comes to declare variables within a class. Should I declare them inside of the __init__ procedure or outside it? What's the difference?
The following code works just fine:
# Declaring variables within __init__
class MyClass:
    def __init__(self):
        country = ""
        city = ""
    def information(self):
        print "Hi! I'm from %s, (%s)"%(self.city,self.country)

me = MyClass()
me.country = "Spain"
me.city = "Barcelona"
me.information()

But declaring the variables outside of the __init__ procedure also works:
# Declaring variables outside of __init__
class MyClass:
    country = ""
    city = ""
    def information(self):
        print "Hi! I'm from %s, (%s)"%(self.city,self.country)

me = MyClass()
me.country = "Spain"
me.city = "Barcelona"
me.information()

Comment: **There is no such thing as a *variable declaration* in python!**
Variables are only assigned to/initialized(*binded* is the correct term).
There is no distinction between declaration and initialization.
Comment: This question appears to also be confusing instance attributes and method local variables.
Answer: In your first example you are defining instance attributes. In the second, class attributes.
Class attributes are shared between all instances of that class, where as instance attributes are "owned" by that particular instance.
Difference by example
To understand the differences let's use an example.
We'll define a class with instance attributes:
class MyClassOne:
    def __init__(self):
        self.country = "Spain"
        self.city = "Barcelona"
        self.things = []

And one with class attributes:
class MyClassTwo:
    country = "Spain"
    city = "Barcelona"
    things = []

And a function that prints out information about one of these objects:
def information(obj):
    print "I'm from {0}, ({1}). I own: {2}".format(
                obj.city, obj.country, ','.join(obj.things))

Let's create 2 MyClassOne objects and change one to be Milan, and give Milan "something":
foo1 = MyClassOne()
bar1 = MyClassOne()

foo1.city = "Milan"
foo1.country = "Italy"
foo1.things.append("Something")

When we call information() on the foo1 and bar1 we get the values you'd expect:
>>> information(foo1)
I'm from Milan, (Italy). I own: Something

>>> information(bar1)
I'm from Barcelona, (Spain). I own:

However, if we were to do exactly the same thing, but using instances of MyClassTwo you'll see that the class attributes are shared between instances.
foo2 = MyClassTwo()
bar2 = MyClassTwo()

foo2.city = "Milan"
foo2.country = "Italy"
foo2.things.append("Something")

And then call information()...
>>> information(foo2)
I'm from Milan, (Italy). I own: Something
>>> information(bar2)
I'm from Barcelona, (Spain). I own: Something

So as you can see - things is being shared between the instances. things is a reference to a list that each instance has access to. So if you append to things from any instance that same list will be seen by all other instances.
The reason you don't see this behaviour in the string variables is because you are actually assigning a new variable to an instance. In this case that reference is "owned" by the instance and not shared at the class level. To illustrate let's assign a new list to things for bar2:
bar2.things = []

This results in:
>>> information(foo2)
I'm from Milan, (Italy). I own: Something
>>> information(bar2)
I'm from Barcelona, (Spain). I own:

Comment: Thanks a lot! It makes perfect sense now. I suppose that I got confused because I was using an immutable type.
Answer: You're two versions of the code are very different.  In python, you have 2 distinct entities:  classes and class instances.  An instance is what is created when you do:
new_instance = my_class()

You can bind attributes to an instance within __init__ via self (self is the new instance).
class MyClass(object):
    def __init__(self):
        self.country = ""  #every instance will have a `country` attribute initialized to ""

There's nothing terribly special about self and __init__.  self is the customary name that is used to represent the instance that gets passed to every method (by default).
a.method()  #-> Inside the class where `method` is defined, `a` gets passed in as `self`

The only thing special here is that __init__ gets called when the class is constructed:
a = MyClass()  #implicitly calls `__init__`

You can also bind attributes to the class (putting it outside __init__):
class MyClass(object):
    country = ""  #This attribute is a class attribute.

At any point, you can bind a new attribute to an instance simply by:
my_instance = MyClass()
my_instance.attribute = something

Or a new attribute to a class via:
MyClass.attribute = something

Now it gets interesting.  If an instance doesn't have a requested attribute, then python looks at the class for the attribute and returns it (if it is there).  So, class attributes are a way for all instances of a class to share a piece of data.
Consider:
def MyClass(object):
    cls_attr = []
    def __init__(self):
        self.inst_attr = []

a = MyClass()
a.inst_attr.append('a added this')
a.cls_attr.append('a added this to class')
b = MyClass()
print (b.inst_attr) # []  <- empty list, changes to `a` don't affect this.
print (b.cls_attr) # ['a added this to class'] <- Stuff added by `a`!
print (a.inst_attr) #['a added this']

Comment: Might be useful to underline that `__init__` has absolutely nothing special. You can add instance attributes in every method, or even outside the class code(as the Op is doing even if I don't know if he knows that).
Comment: @Bakuriu -- Updated.  Maybe that will be more clear now?
Comment: Nice, but I thing should also make more clear that class attributes are shared across instances and that may cause problems for someone that doesn't understand this.
Answer: When you define a variable in class scope (outside any method), it becomes a class attribute.  When you define a value in method scope, it becomes a method local variable.  If you assign a value to an attribute of self (or any other label referencing an object), it becomes (or modifies) an instance attribute.


$\det (A^{-1})$ from eigenvalues of $A$

Question: Suppose I have invertible square matrix $A$ in the complex field and I know all of its eigenvalues and they may be assumed to be non zero. Is there a way to write $\det(A)$ and $\det (A^{-1})$?
PS. This is related to my previous question Eigenvalues of $(A+B)^{-1}$ and is not homework. Thank you.
Answer: If $A$ is diagonalizable, it's easy. You can write $A=PDP^{-1}$ where $D$ is the diagonal matrix with the eigenvalues of $A$ in the diagonal. Therefore $\det(A)=\det(P)\det(D)\det(P)^{-1}=\det(D)=\lambda_1\cdots\lambda_n$, where $\lambda_i$ are the eigenvalues of $D$. Also $\det(A^{-1})=\det(A)^{-1}=1/(\lambda_1\cdots\lambda_n)$.
In general, we have that the characteristic polynomial of $A$ is of the form $p(t)=(t-\lambda_1)\cdots(t-\lambda_n)$. Evaluating in 0, we get that $p(0)=(-1)^n\lambda_1\cdots\lambda_n$. Now, $p(t)=\det(tI-A)$, and so by evaluating in 0, we get that $(-1)^n\lambda_1\cdots\lambda_n=\det(-A)=(-1)^n\det A$.  The determinant of $A^{-1}$ is just the inverse of the determinant of $A$.
Comment: $A$ could be non diagonalizable, though.
Comment: Sorry, thought it was diagonalizable. I'll edit my post.
Comment: @RobertAuffarth Thank you very much. Could you also please tell me if it is possible to calculate eigenvalues of $(AB^{-1})$ from eigenvalues of $A$ and $B$? It is related to another question http://math.stackexchange.com/questions/489386/monotonicity-of-log-det-rd-i-d-j
Comment: Mmm... I'm not sure if the eigenvalues of the product are determined by the eigenvalues of each one. I doubt there is any relation in general, but maybe for specific examples...
Answer: The so-called Jordan form of a complex matrix $A$ has the eigenvalues of $A$ in the main diagonal and maybe some more stuff above the main diagonal. Now it is an elementary property of determinants that the determinant of an upper triangular matrix is the product of its diagonal elements. Furthermore the determinant of $A^{-1}$ is the reciprocal of the determinant of $A$. It follows that
$$\det(A)=\lambda_1\cdot\lambda_2\cdot\ldots\cdot\lambda_n\>,\qquad
\det(A^{-1})={1\over\lambda_1\cdot\lambda_2\cdot\ldots\cdot\lambda_n}\ .$$

$\det (A^{-1})$ from eigenvalues of $A$


Belief propagation using pgmpy lib - algorithm understanding

Question: I am now starting to use pgmpy lib for probabailistic graphical model implementation. The probability that I get using this lib differs from the one I get manually (e.g. using SamIam). Here is a screenshot of the very small graphical model made in SamIam to check the concept idea:

The code I have using pgmpy.
from pgmpy.models import BayesianModel
from pgmpy.factors import TabularCPD
from pgmpy.inference import BeliefPropagation

student_model = BayesianModel([('D', 'G'), ('I', 'G')])

difficulty_cpd = TabularCPD(variable='D', variable_card=2, values=[[0.6, 0.4]])
intel_cpd = TabularCPD(variable='I', variable_card=2, values=[[0.7, 0.3]])
grade_cpd = TabularCPD(variable='G',variable_card=3, values=[[0.3, 0.05, 0.9, 0.5], [0.4, 0.25, 0.08, 0.3], [0.3, 0.7, 0.02, 0.2]], evidence=['I', 'D'], evidence_card=[2, 2])

student_model.add_cpds(grade_cpd, difficulty_cpd, intel_cpd)

print (student_model.nodes())
print (student_model.get_cpds('D'))
print (student_model.get_cpds('I'))
print (student_model.get_cpds('G'))

belief_propagation = BeliefPropagation(student_model)
res = belief_propagation.query(variables=["G"])
print (res['G'])

I get following results

The values of phi(G) are not the same as in Samiam.
According the algorithm used in Samiam we should get for G_0:
P(G_0) = P(G_0|I_0,D_0) + P(G_0|I_0,D_1) + P(G_0|I_1,D_0) + P(G_0|I_1,D_1)
P(G_0) = 0.3*0.7*0.6 + 0.05*0.7*0.4 + 0.9*0.3*0.6 + 0.5*0.3*0.4 = 0.3620

Could someone please give me a tip on how these phi(G) values have been counted (which algorithm is really used), and how I could get the same values as in SamIam.
Answer: actually, I get the same answer as SamIam when running the nearly the exact same code using the most recent version of pgmpy. The only change I needed to make was that TabularCPD has been refactored so that you now need to declare this import statement:
from pgmpy.factors.discrete import TabularCPD

instead of
from pgmpy.factors import TabularCPD

['I', 'G', 'D']
╒═════╤═════╕
│ D_0 │ 0.6 │
├─────┼─────┤
│ D_1 │ 0.4 │
╘═════╧═════╛
╒═════╤═════╕
│ I_0 │ 0.7 │
├─────┼─────┤
│ I_1 │ 0.3 │
╘═════╧═════╛
╒═════╤═════╤══════╤══════╤═════╕
│ I   │ I_0 │ I_0  │ I_1  │ I_1 │
├─────┼─────┼──────┼──────┼─────┤
│ D   │ D_0 │ D_1  │ D_0  │ D_1 │
├─────┼─────┼──────┼──────┼─────┤
│ G_0 │ 0.3 │ 0.05 │ 0.9  │ 0.5 │
├─────┼─────┼──────┼──────┼─────┤
│ G_1 │ 0.4 │ 0.25 │ 0.08 │ 0.3 │
├─────┼─────┼──────┼──────┼─────┤
│ G_2 │ 0.3 │ 0.7  │ 0.02 │ 0.2 │
╘═════╧═════╧══════╧══════╧═════╛
╒═════╤══════════╕
│ G   │   phi(G) │
╞═════╪══════════╡
│ G_0 │   0.3620 │
├─────┼──────────┤
│ G_1 │   0.2884 │
├─────┼──────────┤
│ G_2 │   0.3496 │
╘═════╧══════════╛

Comment: Thank you for your help. I have installed the version of the lib from GitHub and looks like the calculations are right now
Comment: When I installed pgmpy using pip, I got the same incorrect result as you. It was only when I installed from https://github.com/pgmpy/pgmpy  that I got the same answer as samIam.
Comment: Also, I got the same answer as SamIam whether using python2 or python3 as long as I used the github.com/pgmpy/pgmpy version


Binary cross entropy vs mse loss function when asymmetric payoffs

Question: I'm building a binary classifyer that has an unequal payoff given the following cass:

$Y_{pred}=Y_{actual}= True$: payoff is +x*100
$Y_{pred}$$\ne$$Y_{actual}= True$: payoff is -x*100
$Y_{pred}$$\ne$$Y_{actual}= False$: payoff is -1
$Y_{pred}=Y_{actual}= False$: payoff is +1

In other words, there are two possible courses of action: True for action 1 and False for action 2.
I'm looking at two approaches to implement it:

I could mse as loss function with two output neurons, assign the payoffs directly to $Y_{actual}$, with the neural network predicting the payoffs for each of the actions.

I assume I would then just look for which of the two neurons predicts a higher payoff and use liner function in the last activation layer. Correct?

I could create a custom loss function that will calculate the respective payoffs as described above and then use binary cross entropy on that?

Which of those two approaches would be preferred? Should they lead to the same result, giving a recommendation for each sample which action is preferable?
Answer: You cannot use your "payoff" function as a loss for your network because it is not differentiable. Instead, you can use a differentiable function which has outputs close to your evaluation metric (payoff).
As you are predicting a binary variable, the way to go is the binomial cross-entropy. The loss function would look like:
$$\mathcal{L}(\mathbf y, \mathbf c, \mathbf t)=-\frac {1}{N}\sum_n 100c_n t_n\log y_n + (1-t_n)\log (1-y_n),$$
where $\mathbf y$ are the predictions, $\mathbf t$ are the targets and $\mathbf c$ are the individual costs for each sample. You can see it is giving the false negative predictions $100c_n$-times higher penalty than false positives.
It is possible that you will have to implement this loss yourself, but it should be quite easy.
Using MSE for classification does not make much sense.
Comment: I guess not, but you can use the tensorflow `sigmoid_cross_entropy_with_logits` [source code](https://github.com/tensorflow/tensorflow/blob/3d52b444a36c76ead0b129f215a9670cc6f4a1c6/tensorflow/python/ops/nn_impl.py#L104) and modify it for your purpose.
Comment: In my case each sample would need to have an individual weight. Also, cross entropy with weights only seems to offer a coefficient for positive cases - unclear to me what that means as I have basically 4 different payoffs that need to be weighted.
Comment: What is "x" in your "payoff"? The weight coefficient for each sample?
Comment: Yes that's correct. So I would need the samples weighted but also dependent on the outcome (if correctly matched or not).
Comment: Check the updated answer. Hope it solves your problem.
Comment: Ok that's great if this really works. In Keras binary cross entropy is calling tensorflow via `K.mean(K.binary_crossentropy(y_pred, y_true), axis=-1)`. Any way I can rewrite this so I can make use of tensorflow's `sigmoid_cross_entropy_with_logits`?
Comment: Ok so you suggest the term  `max(x, 0) - x * z + log(1 + exp(-abs(x)))` needs to be changed to `100*c*t*log(y) + (1-t)*log(1-y)`?
Comment: Yeah. Now that I am looking at the TF implementation, it is quite confusing why they require logit inputs and compute sigmoid over them... But the second formula should be just what you need.
Comment: I understand now how your function weights the false negatives and false positives. But what about the true positive and true negatives? Is there any way to weight them too in relation to each other? Any suggestions how I can handle that? Thanks for your great help so far!
Comment: These are correct predictions, therefore they don't belong into the loss expression: If they are predicted correctly, there will be no penalty. Also, note that this information is already inherently encoded: It is 100 times worse to mis-classify a negative sample than a positive one, that means it is 100 better to discover a true negative than a true positive.
Comment: I see what you mean, but in my case I don't really want to achieve the maximum accuracy in classification, but rather I want to maximize a payoff that is caused by a binary decision. That's why I think even the true decisions need additional weighting.
Comment: Have you considered using reinforcement learning? It might be the way to go for you.
Comment: I have thought about it but then rejected it as in my case each decision is not dependent on a previous state but is taken independently. I.e. the state is reset after each action. Not sure if my rejection is correct based on that reasoning.


Porque devo manter arquivos de áudio e vídeo dentro da pasta raw?

Question: No Android tem-se dentro do diretório res vários subdiretórios, separados, aparentemente, para melhor organização. As vezes quando se quer colocar um novo áudio, por exemplo para toque, diferente dos padrões do dispositivo, é aconselhado colocar numa pasta chamada raw.
Porque devo manter arquivos de áudio e vídeo dentro da pasta raw? Existe alguma tratamento especial para que tenhamos que mante-los dentro deste diretório? Existe alguma consequência ou perda de performance ao colocar um arquivo de áudio dentro do diretório drawable?
Answer: As ferramentas do SDK do Android compilam os recursos(resources) juntamente com o binário da aplicação(1). Durante esse processo são gerados símbolos(classe R) para cada um, afim de poderem ser acedidos no código.
A classe R contém código para todos os recursos na pasta res/. Para cada tipo de recurso, há uma subclasse R (R.drawable, R.layout, etc.) e, para cada recurso daquele tipo, um número inteiro (id) que o identifica.
O id é usado, no código, para referenciá-lo, quando se pretende utilizar o recurso.
Para permitir esse mecanismo o Android tem uma estrutura de pastas pré definida e obriga a que cada tipo de recurso seja colocada na pasta respectiva dessa estrutura.
Assim, não é uma questão de "devo" ou "performance" mas sim a forma como o Android trata os recursos da aplicação que obriga a que cada tipo de recurso seja colocado na pasta respectiva.
(1)
- Os arquivos colocados na pasta res/raw não são compilados, são apenas geradas entradas na classe R.
- Os arquivos colocados na pasta java/assets não são compilados e não será gerada qualquer entrada na classe R.
Referências:

Acesso aos recursos.
Fornecimento de recursos.
Resources.
Resource Types.
Comment: O gradle não permitirá a existência de um arquivo áudio na pasta *layout*. Experimente e veja o que acontece.
Comment: Considerando a frase "Os arquivos colocados na pasta res/raw não são compilados[...]", então se eu colocar um arquivo de áudio no diretório, por exemplo layout, esse arquivo será compilado? Ou arquivos de mídia não são compilados de forma alguma?


Multiple submit buttons for post in Javascript/Node/EJS

Question: So I'm learning Javascript and one of the things I'm practicing is a model view controller of sorts. Right now I have a form with multiple ejs templates, but only the first one pertains to this question.
The first is Home.ejs

<DOCTYPE html>

            <title> HomeTitle </title>

 Welcome Home

                 <form id ="redirect" method="POST">
                      <input type="submit"value="SignIn" >
                      <input type="submit" value="Exit" >
                    </form>

I also have a router.js that handles as the router file.

// Importing the module
const express=require("express")
var bodyParser=require('body-parser')

// Creating express Router
const router=express.Router()
var jsonParser= bodyParser.json()
var urlencodedParser =bodyParser.urlencoded({extended: false});
// Handling login request
router.get("/",(req,res,next)=>{
  res.render('home.ejs')
})

router.post("/", urlencodedParser, function (req,res){
  return res.redirect("/login");
})

router.get("/login",(req,res,next)=>{
  res.render("profile.ejs")
})

router.post("/login", urlencodedParser, function (req,res){

  console.log(req.body)
  //res.send(req.body.first)
  return res.redirect('/');

})
module.exports=router

In my Home.ejs I have two submit buttons, one for signing in, and one for exiting. At present, pressing either button takes me to the sign in page (profile.ejs) I am rendering (b/c there's only one render destination). Is there a way for me to differentiate which button was pressed in the javscript section so that I can chose which page I want to render. For example pressing the Sign In button would render one ejs template, whereas Exit would go to another template that I would render.
The first router.post is the post function where ideally the solution for differentiating would be since that is where I handle rendering the new page based on the post data.
Answer: You can assign a name to your inputs:
<input type="submit" value="SignIn" name="submit">
<input type="submit" value="Exit" name="submit">

Then check the value of submitted input and render/redirect based on that value:
const submit = req.body.submit;
if(submit === "SignIn"){
  //Do something
} else if(submit === "Exit"){
  //Do Something
} else {
}


Auto update: Is this secure?

Question: Dot Net Auto Update
I felt like .net was lacking a simple secure automatic update library so I've implemented something and put it up here. Before anyone considers using the library I was keen for the update process to get a bit a peer review.
Here are the steps:

The client software is populated with a public key and URI to poll.
Client polls a URI for a manifest file.
Manifest is downloaded and signature (in a separate ".signature") is used to check that the manifest is valid.
A list of pending updates is parsed out of the manifest (to show to the user).
The installer file is downloaded and again is verified with a corresponding ".signature" file. (the downloaded file will be protected with ACLs)
The installer is run.

Mitigated threats:

The manifest signature should prevent any malicious downloads ("carpet bombing")
The installer signature should prevent any MITM attacks from sending malicious installers
Protecting the downloaded installer with ACLs should prevent any local escalation attacks.

Unmitigated threats:

A MITM attack where the attacker always reports "no updates available". (Could keep a client at a vulnerable version)

References:

Secure Software Updates: Disappointments and New Challenges
Black Ops 2008: It's The End Of The Cache As We Know It
Evilgrade Will Destroy Us All

What have I missed?
Comment: What about just using SSL, it'd solve the whole problem without any complexity. Nowadays it costs about 50$
Comment: Out of interest, what was wrong with ClickOnce for this scenario?
Comment: @Robert ClickOnce only installs with limited access to the system. For example there is no access to system's scanners. I may be wrong but I think ClickOnce apps always need to check for updates before starting?
Comment: @Luke : You can choose the behaviour you want with clickonce (ie there's a "application is available offline" checkbox than you can tick)
Comment: @Robert : clickonce doesn't support all proxy schemes, clickonce sometimes fail with erratic "corrupted store" messages, clickonce doesn't support encryption ... just to name a few clickonce caveats
Answer: Dan Kaminsky has a good set of guidelines for an updater:
To succeed, your update package must be:

Signed.
Signed by you.
Signed by you, using the right EKU
(Extended Key Usage)
Signed from an unrevoked signature
Be the same product
Be a new version

From your description in this question, it appears that you have the first 3.
Comment: I was thinking that points #5 and #6 should be enforced by the user of the library. Any thoughts on that?
Comment: The user of the library should be able to pass the name of the application and the current version, and the library could read the metadata from the installer to check the last two points.
Answer: Having build my own deployer in a corporate environment, here are a few use case I needed to address :

support for digital signature
support for all kind of proxy. Some big corps have complex proxy configurations (through the use of proxy configuration scripts for example). You should support all of those.
encryption support. Your customers will probably want to have the deployed binaries available on a web-server, and they won't want to manage some sort of authentication or access control ; but they won't want unauthorized users to download the binaries either. An easy solution is to encrypt the binaries and have your tool deploy it
support for pluggable additional steps. Corporate clients are usually not very comfortable using automatically deployed tools. They will want more control. Typically, allowing them to run customizable steps (like anti-virus checks, etc) will help
support for different versions of the software based on the consumer identity. This is often needed in corporate environments, when you want to update the copies of a specific consumer (to fix a bug or add an extra-feature) very fast without running all your Q&A process (in this situation, you want to limit the update to this specific consumer)
support limited privilege situations. Aside from the fact that your users may lack Administrator access to their computer, big corporations often use specific tools to limit what you can do. Be ready to deploy in a user-owned folder (or even a temporary folder) rather than the classic "program files".
your tool should be signed by a strong certification authority.

Regarding the MITM attack you mentionned, it's easily solved through the use of public cryptography (as noted by unknown)
Comment: +1 for proxy as well. I am someone who sits behind these complex proxies  and it can wreck havok
Comment: Proxy support is a useful feature but it isn't really a security concern for the update process.
Comment: @Luke : depends on your standpoint. I can assure you a lot of *security* departments will refuse any direct connection to the www for *security* reasons.
Answer: Well, you can try to prevent MITM by having the "no version update" response also include a timestamp (& be signed).  Then if a month goes by (or whatever your policy is) with no version change and no timestamp update, then you refuse to run the software or pop-up a warning dialog informing the user there might be a MITM attack.
Doesn't solve the problem of what to do if your server goes down - presumably you treat it the same as a no timestamp change.
Comment: +1, Good Idea.  Also, you should register your account so you don't lose your rep.
Comment: Wasn't I registered? Do I have to do something other than loggin w/ my OpenID?
Answer: Don't mean to be troll in here, but you are trying to solve an already solved problem. Using SSL would be a much better choice. That would solve all problems listed in your question.
I understand that this system can be useful for people who can't afford an SSL certificate but anyone who can get one, should get one to solve this problem.
Don't forget, "Complexity is the enemy of security".
Answer: Just as an addition, add a MD5 CheckSum to the downloaded file as well, otherwise, looking good :) - Fair comment below.
Added:
The only additional thing I can see here is delving into things like obfuscating the code, or archiving the setup file and locking the archive, then once downloaded, unlocking it. That type of thing. However I think what you have currently done should be 100%.
The only time more is needed is when the application is very security complex. Right now you prevent DLL tampering and proof of origin, which for an auto updater, should be plenty.
Comment: SHA1 is dead, do not use it. Use SHA256.
Comment: The code uses RSA/SHA1 to calculate the file signatures so I think that's covered.
Comment: Thanks @silky, I'll switch it over to SHA256.
Answer: So I'm not clear on something; the downloader verifies that the manifest is the one it expects, via a signature, does it do the same for the actual patches it installs?
Comment: Yes, it also verifies the install file once it is downloaded.
Comment: Okay. Okay then. So is it possible to somehow update the public key it validates with? (And the url)?
Comment: Its up to the application. The way I'm planning on using it is to only update the key/url by installing a new version (i.e. hard coded in the app). Though you could use the crypto API to store the key so it could be changed.
Comment: I guess what I am suggesting is that you may need a facility to securely update that, incase, for whatever reason, you decide you need to change your private key, or you foresee that a domain is going down/changing.
Answer: There is some very nice comment and solution in this post. But I am strongly agree with dr. evil. You should use SSL connection for update and the certificate must be saved (built on) in the client. So, you can make sure the client is not going to accept fake certificate.
I think it will effectively immune the client from the MiTM attack.
NOTE: If client can accept unauthorized certificate then MiTM attack can be successful, so do not give this option to the client.
Edit: I think SSL certificate can be self signed in this case.
Comment: I would like to know if MiTM attack can be possible in this scenario. As far as I know it is not.

Auto update: Is this secure?


Firefox intermittently tries to download/open a PHP page rather than it execute on the server

Question: I found this similar question here on serverfault, but the answers there don't cover my case (that I can tell).
On some [apparently] random basis, Firefox (only browser I've tried) will try to download a PHP page rather than 'load' it.
Often, closing the download/open dialog and re-clicking the link will make it work properly. Sometimes, I need to bounce Apache.
This is annoying not only to myself, but to others who use my server. Any idea as to what could be causing this?
Output of top:
(mysqld runs anywhere from 1% to 190% on this server, but I have not noticed a correlation between its spikes and Apache flaking out on whether to offer a PHP page for "opening" and just running it like it should.)
top - 15:37:38 up 44 days, 10:17,  1 user,  load average: 0.11, 0.37, 0.43
Tasks:  39 total,   2 running,  37 sleeping,   0 stopped,   0 zombie
Cpu0  : 94.6% us,  5.4% sy,  0.0% ni,  0.0% id,  0.0% wa,  0.0% hi,  0.0% si
Cpu1  : 94.9% us,  5.1% sy,  0.0% ni,  0.0% id,  0.0% wa,  0.0% hi,  0.0% si
Mem:   1474560k total,  1464856k used,     9704k free,        0k buffers
Swap:        0k total,        0k used,        0k free,        0k cached

  PID USER      PR  NI  VIRT  RES  SHR S %CPU %MEM    TIME+  COMMAND
 3698 mysql     15   0  124m  28m 4348 S 187.0  1.9   5:26.25 mysqld
11286 root      15   0  3552  880  656 S  1.6  0.1  83:31.36 dovecot
    1 root      15   0  1652  608  520 S  0.0  0.0   3:19.89 init
 3622 root      15   0 21220 8992 5524 S  0.0  0.6   0:00.17 httpd
 3651 root      19   0  2124 1040  888 S  0.0  0.1   0:00.00 mysqld_safe
 3709 apache    15   0 41464  27m 4104 S  0.0  1.9   0:03.21 httpd
 3728 apache    16   0 44008  29m 4276 S  0.0  2.1   0:07.59 httpd
 3853 apache    16   0 44568  30m 4244 S  0.0  2.1   0:08.38 httpd
 3869 apache    15   0 35084  20m 3040 S  0.0  1.4   0:01.82 httpd
 9580 root      23   0  1548  576  492 S  0.0  0.0   0:00.00 udevd
 9811 apache    15   0 32736  17m 2808 S  0.0  1.2   0:00.22 httpd
10042 root      15   0  1552  528  440 S  0.0  0.0   0:28.87 syslogd
10047 root      22   0  1492  372  308 S  0.0  0.0   0:00.00 klogd
10065 named     18   0 47508 2876 1920 S  0.0  0.2   0:37.05 named
10123 root      15   0  4068 1144  840 S  0.0  0.1   0:08.00 sshd
10137 root      18   0  2112  756  632 S  0.0  0.1   0:00.00 xinetd
11350 root      15   0  2632 1052  532 S  0.0  0.1   0:20.59 crond
11362 root      15   0  6404 2140 1072 S  0.0  0.1   3:11.85 dovecot-auth
11383 xfs       18   0  3172 1476  768 S  0.0  0.1   0:01.21 xfs
11401 root      16   0  1720  452  344 S  0.0  0.0   0:03.66 atd
11411 root      18   0  4092  804  576 S  0.0  0.1   0:00.00 saslauthd
11412 root      18   0  4092  468  240 S  0.0  0.0   0:00.00 saslauthd
11435 root      18   0  7344 5388 1628 S  0.0  0.4   1:41.01 miniserv.pl
11935 root      15   0  6944 2240 1804 S  0.0  0.2   0:00.01 sshd
11938 datente   15   0  7092 1520 1068 R  0.0  0.1   0:00.00 sshd
11939 datente   15   0  2176 1312 1052 S  0.0  0.1   0:00.00 bash
12005 datente   15   0  1912  992  788 R  0.0  0.1   0:00.00 top
12161 root      15   0 11164  480  336 S  0.0  0.0   0:00.00 vzctl
12162 root      17   0  2184 1292 1068 S  0.0  0.1   0:00.01 bash
13574 root      15   0  7380 2016  992 S  0.0  0.1   0:01.88 sendmail
13583 smmsp     18   0  6528 1640  828 S  0.0  0.1   0:00.00 sendmail
20230 datente   18   0  2748 1224  712 S  0.0  0.1   0:00.07 screen
20231 datente   15   0  2316 1344 1060 S  0.0  0.1   0:00.00 bash
20264 datente   26  10 1132m 2884  844 S  0.0  0.2  13:50.31 fah6
23843 dovecot   15   0  3556 1532 1268 S  0.0  0.1   4:06.58 imap-login
23845 dovecot   15   0  3552 1528 1268 S  0.0  0.1   4:07.76 imap-login
23847 dovecot   15   0  3556 1536 1272 S  0.0  0.1   4:09.06 imap-login
23899 dovecot   15   0  3556 1532 1268 S  0.0  0.1   4:07.39 imap-login
23963 dovecot   15   0  3556 1532 1268 S  0.0  0.1   4:06.99 imap-login

Comment: Have you let firefox download to see what it retrieved?  I have seen this type of behavior when discovering some really obscure bugs in php.  It is important to determine if you get blank page or if you get the php/html source.
Comment: that's the thing - it's either the raw page, or it's blank - no rhyme or reason I've yet seen :-|  ..also - re-clicking the link seconds later works fine
Comment: @unhillbilly - I'm seeing this on both "normal" (ie, home-written simple PHP pages) and "supplied" pages (such as those with wordpress)
Comment: Raw page, meaning the PHP code?  If so, the question is why isn't it consistently parsing as PHP..
Comment: @Warner - yes the raw code sometimes, blank pages others, and then it works properly (most of the time)
Comment: What is in the error log?  Any segfaults or indication of failure?  How do you have PHP configured?
Comment: the only indications of failure I'm seeing are on a page I'm not loading when the error occurs (a wordpress plugin that occasionally has an error contacting a pingback location)
Answer: If PHP is configured properly in Apache and the client is functioning properly, the PHP script may not be specifying the proper MIME type for the content output.  The Content-type often has to be printed for the browser to understand how to handle the data.
What is the content of the file that Firefox is attempting to download?
Comment: Agree. This is a **server side** problem.  Firefox is doing the best it can with bad data.  The server is not setting the correct header or not executing the PHP and returning it to the client instead.  looking at the contents of the file downloaded will tell you which. If it's HTML then the problem is the former if PHP then the later.
Comment: the issue has cleared-up over the last week, but this being a server-side issue is most reasonable
Answer: You might try loading your server (if its not production or if you have a test copy) with Apache Jarkarta Jmeter
http://jakarta.apache.org/jmeter/index.html
It takes a half hour or so to figure it out if you have never used it, but it's fairly straight forward to use. You can make hundreds of requests and see the returned information from your server, and even render the pages if you desire. This may enable you to determine correlations, be it load, random, or incorrect headers\mime issues.
It's a wonderful tool that can be used for under load time diagnostics.
Answer: Are you precompressing your page and then allowing mod_deflate to recompress?  The issue you're running into is that Firefox has not received Content-length: bytes from the server, and therefore treats it as a partial download.  Using live-http-headers, you'll see that it does indeed have text/html as the content type and saving the file does have the proper rendered content less a few bytes.  Chunked encoding can also cause an issue if the content is just the right number of bytes.
The issue happens when Firefox encounters a short download, either via a timeout or connection closed issue (through sigkill, etc).
Warner's novice assumption that the content type is set incorrectly just shows that he's not dealt in high volume web traffic.  I've noticed this behavior more frequently on 2.2.14/2.2.15 to the point that we backported a few patches to 2.2.12
Comment: Easy with the "novice assumption." Your assuming he's using mod_deflate. Your sounding a little adversarial.
Comment: If warren's results were consistently blank or had incomplete parsed results, your theory would be a good starting point.  It seems that he sometimes receives raw PHP code according to his comments.  It will be interesting to see what additional information he can provide.
Comment: Seems like you're the one making the assumption.  I'm recommending troubleshooting.
Comment: As it is a serverside issue that occurs in high volume hosting, the common problem with firefox is that the content-length doesn't match what it has received from apache.  This can happen for a number of reasons, one is using ob_start to compress, then mod_deflate running on top.  Another is if the apache processes time out or the connection is closed before Firefox gets the last bytes of the transaction.  It is not an improperly configured server as evidenced by the fact that sometimes requests work.  The novice assumption is expecting different behavior from apache on each pageload.
Comment: Why someone would assume that reloading a page repeatedly and having it work one time, and not the next, and assuming that the content-type is being set incorrectly by the server.  I don't need to troubleshoot it, the issue is common, is documented in several bugs on firefox's bugtracker, and is documented in apache's bugtracker.  2.2.12 with the security patches backported fixes it.  Insanity is repeating the same action over and over again, expecting different results.  But, thanks again to the SF boys club for the downvotes.  Do correct answers scare you guys that much?
Comment: PHP could be segfaulting and then Apache is serving the request as plaintext.  There's still not enough information to be sure though.  One thing is certain however, mod_deflate does not impact whether or not PHP code is parsed on the server side.
Comment: This is a well documented issue.  Apache doesn't need to segfault for this to occur.  The issue is that code in 2.2.14/2.2.15 changed the way connection closes are handled which Firefox doesn't like.  When Firefox receives a partial download due to a number of non-tcp stack related issues, this behavior occurs.  It happens in high traffic situations much more frequently.  The common issues that show up are listed above.  I can reiterate the points if you cannot comprehend the previous post.  And you are right, mod_deflate does not interpret PHP code, kudos for getting one fact correct.


Unexpected OptimisticLockingException on MongoTemplate.save

Question: Using MongoTemplate I'm trying to store an entity called Person. Since I want to use optimistic locking, the entity is versioned using the @Version annotation.
When I try to store a new Person entity into an empty collection using MongoTemplate.save, I get OptimisticLockingException. I didn't expect this, since I'm creating a new object rather than updating an existing one. (And no other thread is accessing the collection.)
Is this expected behavior, or am I doing something wrong?
(If I use MongoOperations.insert instead, everything works. (I want to use save though, since CrudRepository only has save, not update.) If I remove the @Version annotation, it works as well.)
Thanks,
Daniel
My entity class:
import org.bson.types.ObjectId;
import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.Version;
import org.springframework.data.mongodb.core.mapping.Document;

@Document
public class Person {

    @Version
    private long versionId;

    @Id
    private ObjectId id;

    private final String name;

    public Person(String name) {
        this.name = name;
    }

    public long getVersionId() {
        return versionId;
    }

    public ObjectId getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Person person = (Person) o;

        if (id != null ? !id.equals(person.id) : person.id != null) return false;

        return true;
    }

    @Override
    public int hashCode() {
        return id != null ? id.hashCode() : 0;
    }
}

My test setup (which is using EmbedMongo to set up a MongoDb instance):
import com.mongodb.Mongo;
import de.flapdoodle.embed.mongo.MongodExecutable;
import de.flapdoodle.embed.mongo.MongodProcess;
import de.flapdoodle.embed.mongo.MongodStarter;
import de.flapdoodle.embed.mongo.config.MongodConfig;
import de.flapdoodle.embed.mongo.distribution.Version;
import de.flapdoodle.embed.process.runtime.Network;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.data.mapping.context.MappingContext;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;
import org.springframework.data.mongodb.core.convert.MappingMongoConverter;
import org.springframework.data.mongodb.core.mapping.MongoMappingContext;

public class MongoDbTest {

    private MongodExecutable mongodExe;
    private MongodProcess mongod;
    private Mongo mongo;
    private MongoOperations mongoOperations;

    @Before
    public void setUp() throws Exception {
        MongodStarter runtime = MongodStarter.getDefaultInstance();

        mongodExe = runtime.prepare(new MongodConfig(Version.Main.V2_0, 12345, Network.localhostIsIPv6()));
        mongod = mongodExe.start();
        mongo = new Mongo("localhost", 12345);

        MongoDbFactory mongoDbFactory = new SimpleMongoDbFactory(mongo, "database");

        MappingContext mappingContext = new MongoMappingContext();
        MappingMongoConverter mappingMongoConverter = new MappingMongoConverter(mongoDbFactory, mappingContext);

        mongoOperations = new MongoTemplate(mongoDbFactory, mappingMongoConverter);
    }

    @After
    public void tearDown() {
       mongod.stop();
       mongodExe.stop();
    }

    @Test
    public void testSave() {
        Person person = new Person("Joe");
        mongoOperations.save(person);  // This call throws OptimisticLockingException.
    }
}

Answer: When version property has type long it has 0 value by default which seems to be not acceptable by Spring Data MongoDB.
Change type of versionId in Person class into Long/Integer.
@Version
private Long versionId;

Comment: Thanks Maciej, this confirms my understanding after looking at the code Spring Data MongoDb. My tests also show that Long failed in some case (don't remember exactly which at the moment), but Integer seems to work well.


How to toggle bool while in a while loop using a key press

Question: Ive been trying to toggle bool while in a while loop. Im struggling at finding a way to only toggle it once (as when I check if a key has been pressed in the loop it registers it many times). Im somewhat new so I apologize if this is a bad question. Thanks!
<code>//Loop

while (true)
{
    //*active* is the bool that I want to toggle
    if (active)
    {

        if (*CRITERIA*)
        {
            *CODE*
        }
    }
    Sleep(1);
}
</code>
Answer: The negation of the current state is the new state you want:
<code>active = !active;
</code>
Comment: Yeah I understand that, but Im wondering how I can make it so that when I release a certain key it will change the bool.
Comment: Put the line to where you check for key release events? `if (key_released) toggle_bool;`?
Comment: Yeah, but I dont know how to check for key release events :/
Comment: Then you should ask about a specific problem you encountered while trying to implement that. And add what library you're using.


how to handle mysql update error using ajax

Question: I am  having some issue that is facing me with running the following dismiss functions,
So page with an alert bootstrap that I have named as notifications-success.php goes as follows:
<?php
$root = realpath(str_replace('\\', '/', $_SERVER['DOCUMENT_ROOT']) );
include ($root . '/insights/ss/onix.php');

$result = mysqli_query($mysqli,"select * from notifications where seen = 0");
    if ($result)
    {
    if($result->num_rows) {
        while($row = mysqli_fetch_assoc($result))
        {?>

 <button type="button" class="close" onClick="updateId('<?php echo $row['id'];?>')" data-dismiss="alert" aria-label="Close" style="float:left!important; border:0; background:none;">×</button>

       File has been moved successfully
To confirm reading this message please press x button

<?php       }
    }

}
                  ?>

Action file which is dismisssuccess.php goes as follows:
<?php
if(isset($_GET['id']) && !empty($_GET['id']))
{
    $id = $_GET['id'];
    $ip = getenv('REMOTE_ADDR');
$root = realpath(str_replace('\\', '/', $_SERVER['DOCUMENT_ROOT']) );
include ($root . '/insights/ss/onix.php');

    $update = "UPDATE notifications SET seen = 1 , seenby = '$ip' WHERE id = '".$id."'";

    if (mysqli_query($mysqli, $update))
    {
              echo "success";

    }
    else
    {
        echo "There is some error";
    }
    die;
}
?>

Now when I press x , the update statement doesn't actually run, meanwhile, when i open dismisssuccess file by http with relevant id it works fine with no error and does the update required, also works fine only when I change the table to be update.
Does anyone have clue what could be possible reason behind this issue?
Thank you in advance
Comment: What have you tried to resolve the problem? Where are you stuck? Also, be warned that your `UPDATE` query is widely open for SQL injection
Comment: Your generated HTML markup is incorrectly nested .. one portion begins `To confirm reading this message please press x button `
Comment: Also - you ajax function does nothing with any returned content so why bother generating any in php?
Comment: **Warning:** You are wide open to [SQL Injections](https://php.net/manual/en/security.database.sql-injection.php) and should use parameterized **prepared statements** instead of manually building your queries. They are provided by [PDO](https://php.net/manual/pdo.prepared-statements.php) or by [MySQLi](https://php.net/manual/mysqli.quickstart.prepared-statements.php). Never trust any kind of input! Even when your queries are executed only by trusted users, [you are still in risk of corrupting your data](http://bobby-tables.com/). [Escaping is not enough!](https://stackoverflow.com/q/5741187)
Comment: @NicoHaase what i have tried are 1. running action file using http and target id and update stmt have worked only seperately from notification file 2. changing target table to be updated also have made my code to be fully working
Comment: my database is protected by another service so my aim is not to work on securing sql injection as this is already handled by another service, and so I only write down simply in that way as in above
Answer: Tweak the PHP & HTML so that the nesting is correct and assign a new dataset attribute to the button rather than the inline event handler.
<?php

    $root = realpath(str_replace('\\', '/', $_SERVER['DOCUMENT_ROOT']) );
    include ($root . '/insights/ss/onix.php');

    $result = mysqli_query($mysqli,"select * from notifications where seen = 0");
        if ($result){
            if($result->num_rows) {
                while($row = mysqli_fetch_assoc($result)){
?>

    <button type="button" class="close" data-id="<?=$row['id'];?>" data-dismiss="alert" aria-label="Close" style="float:left!important; border:0; background:none;">
        ×
    </button>

               File has been moved successfully

    To confirm reading this message please press X button

<?php
           }
        }
    }
?>

Use an externally registered event handler and why not use the fetch api ~ appears slightly shorter and is a better api moving forwards.

Within the PHP you really, really should use a prepared statement when dealing with user supplied data - otherwise all your hard work could be undone by one malicious user!
<?php

    if( !empty( $_GET['id'] ) ){

        $id = $_GET['id'];
        $ip = getenv('REMOTE_ADDR');

        $root = realpath(str_replace('\\', '/', $_SERVER['DOCUMENT_ROOT']) );
        include ($root . '/insights/ss/onix.php');

        $sql='UPDATE `notifications` SET `seen`=1, `seenby`=? where `id`=?';

        $stmt=$mysqli->prepare($sql);
        $stmt->bind_param('ss',$ip,$id);
        $stmt->execute();
        $rows=$stmt->affected_rows;
        $stmt->close();

        exit( $rows ? 'Success' : 'There is some error' );
    }
?>

Comment: Same thing, unexpectedly not updating thru the notifications dot php file
Comment: do you see any errors in the developer console? Can you confirm that the AJAX request is reaching the designated endpoint and also that it is sending the ID as expected?!
Comment: OK - just ran a little test and it is the `span` element within the `button` that mainly propagates the event so a little tweak to the Javascript function is required. My fault -sorry dude.
Comment: yea it is now working after truncating the span tag! thank u for saving me that time


Closed form expression for the sum of a product of binomials

Question: I'm wondering if a closed form expression, not involving the hypergeometric function, exists for the following sum
$$
\sum_{k=0}^{n}\binom{n}{k}\binom{q-k}{r}
$$
where $q \geq n$, and $n,k,q,r$ are all non-negative integers, and $\binom{0}{r}=1$ if $r$ is $0$, and $0$ otherwise. It's not amenable to a Vandermonde convolution due to $k$ appearing in both the upper and lower indices, and upper negation has not proved useful. I could not find any related identities in Concrete Mathematics or in Henry W. Gould's collected identities involving binomial coefficients. If no closed form exists this information will also be valuable to me. Any hints or suggestions are greatly appreciated.
Comment: According to Mathematica: $$\sum_{k=0}^{n}{n \choose k}{q-k \choose r} = {q \choose r}\,_{2}F_{1}\left(\left.-n, r-q \atop -q\right|-1\right)$$
Comment: @Shaktal: "not involving the hypergeometric function".
Comment: @Gugg well, Shaktal comments practically answers the question -  in the negative.
Comment: @leonbloy That's probably a fair point, but you'd need to know either something about (the inner workings and typical output of) Mathematica or a lot about the hypergeometric function. Which, for example, I do not. The same more or less applies to the current answer. I knew nothing about either Maxima or Gosper's algorithm, although I assume that the answer is useful to the OP.
Comment: It's worth noting that there is a closed form for the alternate version of this sum. Indeed :
$\sum_{k=0}^n(-1)^k\binom{n}{k}\binom{q-k}{r}=\binom{q-n}{r-n}$
Comment: @ThomasRussell Dear Russell, Could you please send me the Mathematica cods of it? Thanks
Answer: According to Maxima's implementation of the Gosper algorithm, this sum has no simple closed form.


Prove problem reduces to 0-1 knapsack problem

Question: http://community.topcoder.com/stat?c=problem_statement&pm=12329
I was practicing on TopCoder and found this problem. I solved it by noticing that it looks a little like the 0-1 knapsack, but I do not have even the smallest clue why this assumption was correct.
I will simplify the problem statement here:

Given a ordered list of cards, each with a level and a damage, you can make the following steps in order to maximize your damage (assuming the first card has level Li and damage Di):

play the first card and add Di to the total damage made and then discard it and the next Li - 1 cards
move the first card to the end of the list (so the second card becomes the first, the third becomes second, etc)

My question is: can you always play any cards you want as long as you don't have to discard more cards than they actually are? Can you reduce this to the 0-1 knapsack problem where you can choose any items to put in the backpack as long as you do not exceed the maximum weight?
Answer: We can use induction to show that any set of cards can be picked as long as their levels do not add up to more than the number of cards. This is clearly true when we pick only $1$ card. Suppose this is true for $m-1$ cards. Now, let the indices of the $m$ cards to be picked be $i_1, i_2, \ldots , i_m$. As the levels add up to less than total number of cards, there must exist an $i_r$ such that $i_r + L_r \leq i_{r+1}$ (treat $i_{m+1}$ as $i_1 + n$, where $n$ is the total number of cards). Then place all cards above $i_r$ at the end of the list and discard $i_r$ first (note that this operation doesn't remove any other $i_k$ from the list). And by induction assumption, it follows that the remaining $m-1$ cards can be discarded too.
So, as you pointed out, this problem reduces to the knapsack problem.


error with ownership

Question: "The specified file temporary://filelo2Fkx could not be copied, because the destination directory is not properly configured. This may be caused by a problem with file or directory permissions. More information is available in the system log."
ANYWAY what I am getting is everything minus theme and all images but strangely my multi site folders in root drupal sites folder are all working fine.
In the end I solved it by putting the root subfolder in sites along with other multi-sites. No amount of changing permissions or ownership or clean install or dropping and recreating database worked until then...which is very odd because it used to before I took the site down.
Answer: You can try and change the permission of the folder 'sites/all/files' to give it 777 permission in your drupal installation and see if this works.
Comment: Thanks I have already done that but still get same error because now I have no clue what ownership should be on all the folders.
Comment: I think giving the owner 777 permission and others only read permissions should work. Did you already try this?
Comment: I have tried 777 root:apache and tried apache:apache and root:root on files folder but still get the error.
Comment: weirdly my multi-sites listed in sites folder are all fine.
Answer: you have a problem with temporary directory (/tmp is the default).
Read this: https://stackoverflow.com/questions/5040718/file-system-permission-error-while-installing-drupal-modules
M.
Comment: Nothing is working
Comment: Ok. Have you opened an assistance/help ticket with your ISP ? M.
Comment: it is an unmanaged VPS
Comment: I think what I will try doing is do vanilla install and then just bring sql for those one's not working.

error with ownership


installing php gd on ubuntu on a vps server

Question: I was working on localhost with resizing images and everything was great. Then I uploaded to my server and things got interesting. After searching around, looks like I have to enable php-gd on my server.
I tried running the line sudo apt-get install php5-gd using putty, and it didn't work. Any ideas why?
Also, after the install, I assume I will need to run the function sudo reboot right? Clearly I'm not an expert in this area. :P
Comment: What do you mean by "it didn't work"? What message did you get? If it installed successfuly and GD still doesn't work, you have to reboot Apache by executing `sudo /etc/init.d/apache2 restart` or `sudo service apache2 restart`. You shouldn't reboot the whole machine for that, just a particular service which is Apache in this case.
Answer: Try restarting your Apache daemon by executing sudo /etc/init.d/apache2 restart or sudo service apache2 restart if the installation of php5-gd went well. If it didn't, then execute sudo apt-get update and finally sudo apt-get install php5-gd again.


Change the title of date_popup filed in custom form

Question: I'm building a custom form in Drupal 7 and i need to use the date_popup widget in it. It all works as expected, except the title of the field.
My code is:
  $form['filter']['start_date'] = array(
    '#type' => 'date_popup',
    '#date_format' => 'd-m-Y',
    '#title' => t('Start date'),
  );

  $form['filter']['end_date'] = array(
    '#type' => 'date_popup',
    '#date_format' => 'd-m-Y',
    '#title' => t('End date'),
  );

But it keeps showing the default label "Date" for the field, as you can see on in the picture below.
Can you please let me know how can i put Start date and End date as field labels instead of just Date, or correct me if i'm doing something wrong
Answer: Just use the following code:
'#date_label_position' => 'none',

your code :
$form['filter']['start_date'] = array(
    '#type' => 'date_popup',
    '#date_format' => 'd-m-Y',
    '#title' => t('Start date'),
    '#date_label_position' => 'none',
  );

  $form['filter']['end_date'] = array(
    '#type' => 'date_popup',
    '#date_format' => 'd-m-Y',
    '#title' => t('End date'),
    '#date_label_position' => 'none',
  );

Answer: You can unset the labels like below:
function <module_name>_date_popup_process_alter(&$element, &$form_state, $context) {
  if ($element['#name'] == '<fieldname>') {
    unset($element['date']['#title']);
  }
}

Comment: I don't want to unset the title, i just want to use titles i need, not default one.
Comment: The above code should unset the default
Comment: This is the best place to update the title, simply don't use the `unset` part.
Answer: Solution i came up with is following:
  $form['filter']['start_date'] = array(
    '#type' => 'date_popup',
    '#date_format' => 'd-m-Y',
    '#title' => t('Start date'), //set desired title
    '#title_display' => 'invisible', //but hide it from showing
  );

Next, implement hook_element_info_alter():
function my_module_element_info_alter(&$type) {
  if (isset($type['date_popup'])) {
    $type['date_popup']['#process'][] = 'my_module_date_popup_process'; //name of the process function, can be anything
  }
}

and then set default title equals the title from form element:
//process function called from hook_element_info_alter
function my_module_date_popup_process($element, $form_state, $complete_form) {
  if ($complete_form['form_id']['#id'] == 'edit-my-form-id') {
    $element['date']['#title'] = $element['#title'];
  }
  return $element;
}

Result is like this:
Comment: Although this works, you can do it in one function by implementing `hook_date_popup_process_alter()` and set the title there.
Answer: I only got this to work in Drupal 7.43 by hacking the date_popup module.
I added the following code in line 336 to the file date_popup.module found in sites/all/modules/contrib/date/date_popup/date_popup.module (your installation might omit the contrib folder)
// Fixes bug where title wasn't getting updated in hook
if (isset($element['#title'])) {
  $element['date']['#title'] = $element['#title'];
  $element['#title_display']  =  'invisible';
}

Hope this helps someone, I took a long time to figure it out.


Interest Modeling Problem Mistake?

Question:
Adriana opens a savings account with an initial deposit of $\$1000$. The annual rate is $6\%$, compounded continuously. Adriana pledges that each year, her annual deposit (deposited continuously) will exceed that of the previous year by $\$500$. How much will be in the account at the end of the tenth year?

First I calculated the annual deposit $D$, via $D' = D + 500, D(0) = 1000$, to find that $D = 1500e^t - 500$.
Then I calculated $P(10)$, where $P$ is the balance at time $t$, via $P' = .06P + 1500e^t - 500, P(0) = 1000$.  However, this yields ~$\$35\ million$, which seems very high.  I checked the ODE solutions on Wolfram, so my mistake must be in the modeling.  What am I doing wrong?
Answer: Edit:
$D = 1000+500t$
$P' = 0.06P+1000+500t$
Solving this would give
https://www.wolframalpha.com/input/?i=p%27(t)+%3D+0.06p%2B1000%2B500t
$p(t) = c_1e^{0.06t} - 8333.33t -155556$
$p(0) = c_1 - 155556 = 1000$
$c_1 = 156556$
Now
$p(t) = 156556e^{0.06t} - 8333.33t - 155556$
Now $p(10) = 46374$
Comment: I believe this approach would be for discrete compounding and depositing, not for continuous?
Comment: when you say deposited continuously, what do you mean by it. I have never come across this.  The approach what i have given is good for continuous compounding but for the so called discrete depositing.
Comment: I am doing Exercise 10 on page 127 at https://www.academia.edu/32329978/_John_Polking_Differential_Equations_with_Boundary  Note that recurrence relations aren't introduced until just after Exercise 10, which has led me to believe that Exercises 1-10 implicitly assume deposits/withdrawals/payments are somehow made continuously (i.e., the deposit/withdrawal/payment is non zero between any times $t$ and $\Delta t$).
Comment: Also, I am confused about how your solution represent continuous compounding.  If the time between $n$ and $n + 1$ is a year, isn't that annual compounding?
Comment: Can you check if this is the answer?
Comment: Ahhh yes, I managed to find a full solution manual (https://www.scribd.com/doc/133899961/Instructor-Solutions-Manual-differential-Equations-With-Boundary-Value-Problems-2e-polking book page 88, PDF page 97) and it seems your edited answer is correct.  My only question is, why do we solve $S' = .01S$ to find the salary in Exercise 9 (linked in above comment, solution linked in this comment), but $D' = D + 500$ to find the deposit in Exercise 10 doesn't work?
Comment: Answer to my previous comment:  "annual deposit will exceed that of the previous year by \$500" translates to $D' = 500$, not $D' = D + 500$.
Comment: I think the problem is missing information. We have an "initial" deposit which is deposited instantaneously in a lump sum at the beginning--this is correctly modeled as $P(0)=1000$ here and in the answer key. Then we have an "annual" deposit "deposited continuously" that increases by $500$ each year. But what is it in the first year? And does "deposited continuously" imply "increases continuously"? I don't think so. And if it does increase continuously, is the "annual deposit" for the first year one year times the rate at the start of the year, at the end of the year, or halfway through?
Comment: Frankly I think Adriana would satisfy the conditions of the problem if she deposited $0.01$ (one cent) per day throughout the first year, $1.38$ per day ($500$ more per year) throughout the second year, and so forth. How that would qualify as "continuous" I don't know, but the whole "continuous deposit" notion is absurd to begin with.

Interest Modeling Problem Mistake?


Number of observation differs per group. How to deal with that?

Question: I have a question regarding a mixed model analyses in SPSS.
I have 2 groups (shift workers and non shift workers), each individual has different number of observations (depending on the frequency of the onset of a disease). But it is clear that shift workers have higher frequency of the disease than non-shift workers. Depending on the onset of a disease, absenteeism was measured.
I know that mixed model can deal with missing data. But does it also takes into account that shift workers has more observations than non-shift workers?
Because depending on that, my interpretation of the results would be different.
Answer: In general, mixed models provide valid inferences under the missing at random assumption provided that the mean and variance-covariance structures are appropriately specified. This protective effect also carries over to the visiting process, namely the mechanism that describes when subjects provide measurements. In particular, in mixed models will provide valid results when the visiting process is a random process, i.e., in a longitudinal study when the decision that a subject needs to come earlier than originally planned is based on the previously observed measurements of that subject.
Comment: Mixed models can handle unbalanced data, and therefore deferences between the number of measurements in the two groups. However, as I mentioned in my answer, the important consideration is why these differences exist, and whether it is an informative process.
Comment: Hi Dimitris. Thank you for your reply. I don't understand it fully yet. Becasue do you know ifmixed models takes into account the differences in number of observations between the 2 groups? Is mixed models 'smart' enough for that?
Comment: For example. My outcome is that shift workers and non-shift workers do not differences much in absenteeism. However, shift workers have higher disease episodes. So if mixed model does not take the number of disease episodes into account, and the absenteeism rate is similar, then your interpetation would be differ a lot if it takes the number of disease episodes into account. :)


hook form alter with hidden field, throw an error

Question: I try to alter taxonomy edit form.
This is my hook:
function MYMODULE_form_taxonomy_form_term_alter(&$form, &$form_state, $form_id) {
    // hide the desciption field and relations group field
    $form['description']['#type'] = 'hidden';
    $form['relations']['#type'] = 'hidden';

    // set the default value
    $form['description']['#value'] = ' ';
    $form['relations']['weight']['#value'] = 0;
    $form['relations']['parent']['#value'] = array('value' => '13');

}

But When I submit, It throw me an error:
Warning: Illegal string offset 'value' in taxonomy_form_term_submit_build_taxonomy_term() (line 862 in /Users/tangmonk/MyGit/Drupal/daxuebao/modules/taxonomy/taxonomy.admin.inc).

Answer: The problem causing the error is that you are setting your hidden description field value is a string, but the taxonomy module is expecting a text area type array with a 'value' and a 'format', which you cannot replicate with a hidden field.
Unfortunately the term description field is a special property of the term, not a proper field, so you can't remove the field (the taxonomy module relies on it being there).
If you don't want people to see it and you always want it to have an empty value a good option is to restrict it from the user like this:
$form['description']['#access'] = FALSE;

but that doesn't allow you to change the value if you want to.
Another option is to use 'value' instead of 'hidden' as the type, like this:
/**
 * Implements hook_form_FORM_ID_alter().
 */
function MYMODULE_form_taxonomy_form_term_alter(&$form, &$form_state, $form_id) {
  // Hide the desciption field and relations group field
  $form['description'] = array(
    '#type' => 'value',
    '#value' => array(
      'value' => '',
      'format' => 'filtered_html',
    ),
  );
  // Unset the existing relations fieldset.
  unset($form['relations']);
  // Set hidden values for all the sub-fields of the relations fieldset.
  $form['weight'] = array(
    '#type' => 'value',
    '#value' => 0,
  );
  $form['parent'] = array(
    '#type' => 'value',
    '#value' => 13,
  );
}

Note the changes to the relations fieldset too:
Since you only want to pass hidden values from the children of the fieldset just remove the fieldset altogether and then set the hidden values (be careful if using other add on modules that add fields to the 'relations' fieldset).
Because the fieldset wasn't using #tree the values passed through in $form_state will just be ['weight'] and ['parent'], not ['relations']['weight'] and ['relations']['parent'] so you can leave the ['relations'] part out when adding the values back in.
Comment: thanks for your reply, '#access' and '#hidden' are the same effect(hide field for user), what's the deep different of '#access' and '#hidden'?
Comment: Hidden created a html input field of type hidden, which changes the way the value is passed through when the form is submitted (description is normally an array of value & format, which hidden fields can't replicate). Using #access means the field is not added to the form at all.
Comment: See https://developer.mozilla.org/en-US/docs/Web/HTML/Element/Input#Attributes - hidden is a type of field, which is how the drupal hidden type works.


Alinhamento de span com css

Question: Preciso alinhar o icone da estrela ('material-icons') com o texto ('span') e o ícone de menu ('overflow-menu'), tudo na horizontal.
Alguém pode me ajudar? Tenho que fazer isso sem alterar a estrutura do html.

.container {
  left: 0;
  right: 0;
  margin: 10px auto 10px auto;
  width: 95%;
  border-radius: 4px;
  background: #FFFFFF;
}
.container table {
  width: 100%;
  margin: 0 auto;
}
.container .linha {
  border-top: 1px solid #D7D7D7;
}
.container-head {
  display: table;
  width: 100%;
  color: #FFFFFF;
  border-radius: 4px 4px 0 0;
  height: 65px;
  background: #000;
}
.container-head span {
  background: #000;
}
.container-head .material-icons {
  padding: 20px 0 20px 20px;
  width: 24px;
}
.container-head button {
  margin-top: 12px;
  margin-right: 20px;
  border: 0;
  width: 100px;
  height: 42px;
  cursor: pointer;
  border-radius: 4px;
  color: #FFFFFF;
  float: right;
}
.container-head button .material-icons {
  padding: 0;
  position: absolute;
  margin-top: -12px;
  margin-left: 32px;
}
.container-body {
  padding: 20px;
}
.container-body .notification {
  margin-left: -20px;
  margin-right: -20px;
}
.container-body .tab-content {
  margin-left: -15px;
  margin-right: -15px;
}
.container-body-scroll {
  overflow: auto;
  height: 319px;
  text-align: left;
}
.container-footer {
  border-top: 1px solid #D7D7D7;
  height: 45px;
  padding-left: 10px;
  padding-right: 10px;
}
.container-footer button .material-icons {
  font-size: 16px;
}
.container-footer button {
  margin-top: 7px;
  border: 0;
  padding: 7px;
  cursor: pointer;
  border-radius: 4px;
  color: #FFFFFF;
  float: right;
}
.container-footer .txt {
  float: left;
  margin-top: 12px;
}

<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

    grade
    TÍTULO CONTAINER

      more_vert

    TEXTO

      RODAPÉ

Comment: Já testaste `.container-head > * {
  display: inline-block;
}`? ou `float: left;`?
Answer:

.container {
  left: 0;
  right: 0;
  margin: 10px auto 10px auto;
  width: 95%;
  border-radius: 4px;
  background: #FFFFFF;
}
.container table {
  width: 100%;
  margin: 0 auto;
}
.container .linha {
  border-top: 1px solid #D7D7D7;
}
.container-head {
  display: table;
  width: 100%;
  color: #FFFFFF;
  border-radius: 4px 4px 0 0;
  height: 65px;
  background: #000;
  line-height: 65px;
}
.container-head span {
  display: inline-block;
  vertical-align: middle;
  padding: 0px 20px 0px 20px;
}
.container-head .material-icons {
  width: 24px;
  display: inline-block;
  vertical-align: middle;
  padding: 0px 0px 0px 20px;
}
.container-head .overflow-menu {
  float: right;
  vertical-align: middle;
}
.container-head .overflow-menu .material-icons {
  padding-right: 20px;
}
.container-head button {
  margin-top: 12px;
  margin-right: 20px;
  border: 0;
  width: 100px;
  height: 42px;
  cursor: pointer;
  border-radius: 4px;
  color: #FFFFFF;
  float: right;
}
.container-head button .material-icons {
  padding: 0;
  position: absolute;
  margin-top: -12px;
  margin-left: 32px;
}
.container-body {
  padding: 20px;
}
.container-body .notification {
  margin-left: -20px;
  margin-right: -20px;
}
.container-body .tab-content {
  margin-left: -15px;
  margin-right: -15px;
}
.container-body-scroll {
  overflow: auto;
  height: 319px;
  text-align: left;
}
.container-footer {
  border-top: 1px solid #D7D7D7;
  height: 45px;
  padding-left: 10px;
  padding-right: 10px;
}
.container-footer button .material-icons {
  font-size: 16px;
}
.container-footer button {
  margin-top: 7px;
  border: 0;
  padding: 7px;
  cursor: pointer;
  border-radius: 4px;
  color: #FFFFFF;
  float: right;
}
.container-footer .txt {
  float: left;
  margin-top: 12px;
}

<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

    grade
    TÍTULO CONTAINER

      more_vert

    TEXTO

      RODAPÉ

Comment: Corrigido. Veja agora.
Comment: o 'overflow-menu' tem que ficar no fim, a direita, tem como?
Comment: Ok so tem mais uma coisa, tem alguns 'container' que não vão possuir o ícone da estrela, nesse caso o texto esta ficando desalinhado, tem como vc verificar?
Comment: Se te ajudou marque como correta a resposta, por favor. Haja visto que respondi mais do que você disse na pergunta.
Comment: sim claro, que irei marcar, só estava aguardando vc me responder e me ajudar com a última questão. Poderia me ajudar?
Comment: Já fiz. Faz 27 minutos.
Comment: ok, muito obrigado, não tinha visto

Alinhamento de span com css


Incrementar valor no nome de uma função

Question: Boa tarde, galera!
Seguinte, tenho três campos de arquivo em uma tabela do meu banco, são eles:
File1, File2 e File3.
Tenho também um get e um set para cada um deles.
A Questão é, queria rodar um for() e em cada loop incrementar o get.
    <?php if(isset($pedido) && $pedido->getFile1() != null): ?>
     <?php for($i=0;$i<$count;$i++): ?>

                <a target="_blank" href="<?php echo '/files/'.$pedido->getFile[$i](); ?>">

                    Arquivo <?php echo $i; ?>

                    <?php echo $pedido->getFile[i](); ?>

     <?php endfor; ?>
 <?php else: ?>

ou seja, em cada incremento ficaria getFile1(), getFile2, getFile3.
Teria alguma forma de fazer isso?
Sei que aquela sintaxe [$i] ali não funciona, foi mais para exemplificar.
Comment: É tão grande a diferença desses `gets`? baseado pelo nome uso bastaria.
Comment: Não, são todos iguais, sou novo em php desculpa se a pergunta é muito ridícula.Como assim "pelo nome uso bastaria"?
Comment: Mas você tem várias funções de `getFile` todas numeradas ? E são todas iguais/similares ? Então significa que não tem as coisas estruturadas corretamente e precisa de refatorar o seu código. Crie uma função `getFile` que receba o numero como parametro e aplique somente as diferenças lá dentro
Answer: Conheço as seguintes maneiras de fazer isso:
<?php for($i=0;$i<$count;$i++): ?>
    $nomeMetodo = 'getFile' . $i;

    // 1
    $this->{$nomeMetodo}($arg1, $arg2, $arg3);
    // 2
    $this->$nomeMetodo($arg1, $arg2, $arg3);
    // 3
    call_user_func_array(array('namespaceComNomeDaClasse', $nomeMetodo), array($arg1, $arg2, $arg3));

<?php endfor; ?>

Incrementar valor no nome de uma função


Pegar a ultima posição de explode

Question: Galera preciso pegar a ultima posição depois de dar um explode. Como faço?
 $geturl = explode('/', $_SERVER['REQUEST_URI']);

 self::$modulo = isset($geturl[2]) ? $geturl[2] : '';
 self::$funcao = isset($geturl[3]) ? $geturl[3] : '';
 self::$chave = isset($geturl[4]) ? $geturl[4] : '';

Obs.: Pode acontecer de $chave ser nulo
Answer: Use a função end() para deixar o ponteiro do array na última posição e obter seu valor.
$ultimo = end($geturl);

Pegar a ultima posição de explode


Struct com ponteiro e alocação

Question: Não consigo usar o fscanf numa estrutura, eu já aloquei  as estruturas.
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

struct Cliente
{
    int numero;
    char *nome;
};
struct Filme
{
    int numero;
    char * nome;
};
struct Data
{
    int dia;
    int mes;
    int ano;
};
struct Emprestimo
{
    int numero;
    int ativo;
    Cliente *cliente;
    Filme *filme;
    Data *emprestimo;
    Data *devolucao;
};

void verifica_erro(FILE *arquivo)  //verifica se deu erro ao abrir o arquivo
{
    if(arquivo==NULL)
    {
        printf("Erro ao abrir o arquivo!");
        exit(0);
    }
}
void carrega_empre(Emprestimo *video) //carrega na memoria os dados do cliente
{
    FILE *arquivo;
    arquivo=fopen("emprestimos.txt","rt");
    verifica_erro(arquivo);
    int cont=0;
    while(!feof(arquivo))
    {
        fscanf(arquivo,"%d %d %d" ,&video[cont].numero,&video[cont].cliente->numero,&video[cont].filme->numero);
        fscanf(arquivo,"%d %d %d %d " ,&video[cont].emprestimo->dia,&video[cont].emprestimo->mes,&video[cont].emprestimo->ano,&video[cont].ativo);
        fscanf(arquivo,"%d %d %d",&video[cont].devolucao->dia,&video[cont].devolucao->mes,&video[cont].devolucao->ano);
        cont++;
        cont++;
    }
    fclose(arquivo);
}
int conta_registros(char *caminho) //conta quatos registros tem no txt para alocar na         strutura
{
    FILE *arquivo;
    char caracter;
    int linhas=0;
    arquivo=fopen(caminho,"rt");
    while((caracter = fgetc(arquivo)) != EOF)
    {
        if(caracter == '\n')  //cada linha eh um registro
        {
            linhas++;
        }
    }
    fclose(arquivo);
   return linhas;
}
int main()
{
    int regE;
    Emprestimo *video;
    regE=conta_registros("emprestimos.txt");
    video=(Emprestimo*)malloc(regE+20*sizeof(Emprestimo));

    carrega_empre(video);
    printf("acabo\n");
    scanf("%*c");
    return 0;
}

Comment: Poste um modelo/exemplo do arquivo que você está tentando ler.
Answer: Depois de alocar memoria para video, tens que alocar para video->cliente, para video->filme, video->emprestimo, e video->devolucao.
int main()
{
    Emprestimo *video;
    video = malloc(regE * sizeof *video); /* falta validacao de erro */
    for (int k = 0; k < regE; k++) {
        video->cliente = malloc(sizeof *video->cliente); /* falta validacao de erro */
        video->filme = malloc(sizeof *video->filme); /* falta validacao de erro */
        // etc ...
    }

Comment: entao mesmoa assim nao vai cara! pode tentar com o codigo ai
Answer: Existe um erro na linha:

video=(Emprestimo*)malloc(regE+20*sizeof(Emprestimo));

Se regE contém a quantidade de registros, então falta um par de () para fazer com que a multiplicação dê o resultado esperado, alocando a quantidade de memória necessária:
video=(Emprestimo*)malloc((regE+20)*sizeof(Emprestimo));

Struct com ponteiro e alocação


Algorithm issues with newer version of [ms-identity-java-webapp] token?

Question: https://github.com/Azure-Samples/ms-identity-java-webapp/tree/master/msal-java-webapp-sample
when I am using the latest (latest version)downloaded application [ms-identity-java-webapp], it gives me a token that is not getting parsed it gives below exception
"com.nimbusds.jose.JOSEException: Unsupported JWS algorithm RS256, must be HS256, HS384 or HS512".
But when I am using the old downloaded project [ms-identity-java-webapp] ( which was downloaded by me in sept 2021), the token by this project is getting parsed. Why the token doesn't work for the newer version of the app?
ms-identity-java-webapp not parsing the token
Comment: Please provide enough code so others can better understand or reproduce the problem.
Answer: The error you are getting could be due to version compatibility issues.
I cloned GitHub project to my environment to run and check if it works, I didn't face any such issues.
Steps followed:

Registered a new application in Azure Active Directory.
Replaced the client_id, client_secret and Tenant_id values in the application.properties code with the values of the newly created application.

application.properties:

#AAD configuration
aad.clientId=097dXX-XXX-XXXX-XXXX-556XXXXX
aad.authority=https://login.microsoftonline.com/<Tenant_ID/
aad.secretKey=<Client_secret_value>
aad.redirectUriSignin=https://jwt.ms
aad.redirectUriGraph=https://localhost:8443/msal4jsample/graph/me
aad.msGraphEndpointHost=https://graph.microsoft.com/

Registered the redirectURI in Registered application in Azure Active directory=>Authentication:

Open Terminal, navigate to the root directory of the application and run the command mvn clean install :

Run mvn spring-boot:run:

Response:

Code got generated as shown below:


String comparison in 2 adjacent rows of a data frame in R

Question: I have a data-frame with 627 observations and 16 variables are present. I am considering one column named "ZoneDivison" which has factors: North Eastern, Eastern and South Eastern.
So, I want to compare the adjacent row values and create a new column which has 1, if two adjacent rows have same zones, else 0, if the adjacent rows are different.
I referred to the following links to find a way out:
[here] Matching two Columns in R
[here] compare row values over multiple rows (R)
library(dplyr)
a <- c(rep("Eastern",3),rep ("North Eastern", 6),rep("South Eastern", 3))
a=data.frame(a)
colnames(a)="ZoneDivision"

#comparing the zones
library(plyr)
ddply(n, .(ZoneDivision),summarize,ZoneMatching=Position(isTRUE,ZoneDivision))

Expected Result

   ZoneDivision ZoneMatching
 1      Eastern       NA
 2      Eastern       1
 3       Eastern      1
 4 North Eastern      0
 5 North Eastern      1
 6 North Eastern      1
 7 North Eastern      1
 8 North Eastern      1
 9 North Eastern      1
 10 South Eastern     0
 11 South Eastern     1
 12 South Eastern     1

Actual Result
    ZoneDivision ZoneMatching
1       Eastern           NA
2 North Eastern           NA
3 South Eastern           NA

How should I proceed? Please help!!
Answer: Using base R, we can do
as.numeric(c(NA, a$ZoneDivision[-1] == a$ZoneDivision[-nrow(a)]))
#[1] NA  1  1  0  1  1  1  1  1  0  1  1

Comment: Thanks Ronak, that helped.
Answer: The data.table way:
a <- c(rep("Eastern",3),rep ("North Eastern", 6),rep("South Eastern", 3))
dt <- as.data.table(a)

dt[,'ZoneMatching' := as.numeric(.SD[,a] == shift(.SD[,a],1))]

Where you add a new ZoneMatching column as the numeric values of the logical comparison between the a column and the lagged values, generated by the shift() function.
Answer: You can use lag to get that:
library(dplyr)
a %>%
  mutate(ZoneMatching = as.numeric((ZoneDivision == lag(ZoneDivision, 1))))
    ZoneDivision ZoneMatching
1        Eastern           NA
2        Eastern            1
3        Eastern            1
4  North Eastern            0
5  North Eastern            1
6  North Eastern            1
7  North Eastern            1
8  North Eastern            1
9  North Eastern            1
10 South Eastern            0
11 South Eastern            1
12 South Eastern            1

Answer: We can use base R
with(a, c(NA, +(head(ZoneDivision, -1) == tail(ZoneDivision, -1))))
#[1] NA  1  1  0  1  1  1  1  1  0  1  1


trying to use pipe(2) with the sort unix tool but not working

Question: I have been struggling to find what I'm doing wrong and I can't seem to find the issue. When I compile the code below, I get an I/O error.

e.g: /usr/bin/sort: read failed: -: Input/output error

<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

int main(int argc, char **argv, char **envp)
{
        int fd[2];
        pid_t pid;

        pipe(fd);

        pid = fork();
        if (pid == -1) {
                exit(EXIT_FAILURE);
        }

        if (pid == 0) { /* child */
                char *exe[]= { "/usr/bin/sort", NULL };
                close(fd[0]);
                execve("/usr/bin/sort", exe, envp);

        }
        else {
                char *a[] = { "zilda", "andrew", "bartholomeu", NULL };
                int i;

                close(fd[1]);

                for (i = 0; a[i]; i++)
                        printf("%s\n", a[i]);
        }

        return 0;
}
</code>
Answer: dup2(fd[0], 0) in the child.
dup2(fd[1], 1) in the parent.
close the other fd.
Comment: close fd[1] in the child and fd[0] in the parent. This is not strictly necessary, but better, since you don't leave open unused descriptors.
Comment: Which "other" fd? and also, where does dup2 get called? before or after the close(fd[x]) in both child/parent?