Log-likelihood gradient and Hessian

Question: Considering a binary classification problem with data $D = \left\{ (x_i, y_i) \right\}_{i=1}^n$, $x_i \in \mathbb{R}^d$ and $y_i \in \{0,1\}$. Given the following definitions,
$$f(x) = x^T \beta$$
$$p(x) = \sigma(f(x)) \quad \text{with}  \quad\sigma(z) = 1/(1 + e^{-z})$$
$$L(\beta) = \sum_{i=1}^n \Bigl[ y_i \log p(x_i) + (1 - y_i) \log [1 - p(x_i)] \Bigr]$$
where $\beta \in \mathbb{R}^d$ is a vector. $p(x)$ is a short-hand for $p(y = 1\ |\ x)$. The task is to compute the derivative $\frac{\partial}{\partial \beta} L(\beta)$. A tip is to use the fact $$\frac{\partial}{\partial z} \sigma(z) = \sigma(z) (1 - \sigma(z))$$

So here is my approach so far:
\begin{align*}
L(\beta) & = \sum_{i=1}^n \Bigl[ y_i \log p(x_i) + (1 - y_i) \log [1 - p(x_i)] \Bigr]\\
\frac{\partial}{\partial \beta} L(\beta) & =  \sum_{i=1}^n \Bigl[ \Bigl( \frac{\partial}{\partial \beta} y_i \log p(x_i) \Bigr) + \Bigl( \frac{\partial}{\partial \beta} (1 - y_i) \log [1 - p(x_i)] \Bigr) \Bigr]\\
\end{align*}
\begin{align*}
\frac{\partial}{\partial \beta} y_i  \log p(x_i) &= (\frac{\partial}{\partial \beta} y_i) \cdot \log p(x_i) + y_i \cdot  (\frac{\partial}{\partial \beta} p(x_i))\\
&= 0 \cdot \log p(x_i) + y_i \cdot (\frac{\partial}{\partial \beta} p(x_i))\\
&= y_i \cdot (p(x_i) \cdot (1 - p(x_i)))
\end{align*}
\begin{align*}
\frac{\partial}{\partial \beta} (1 - y_i) \log [1 - p(x_i)] &= (1 - y_i) \cdot (\frac{\partial}{\partial \beta} \log [1 - p(x_i)])\\
& = (1 - y_i) \cdot \frac{1}{1 - p(x_i)} \cdot p(x_i) \cdot (1 - p(x_i))\\
& = (1 - y_i) \cdot p(x_i)
\end{align*}
$$\frac{\partial}{\partial \beta} L(\beta) = \sum_{i=1}^n \Bigl[ y_i \cdot (p(x_i) \cdot (1 - p(x_i))) + (1 - y_i) \cdot p(x_i)  \Bigr]$$
So basically I used the product and chain rule to compute the derivative. I am afraid, that my solution is wrong, because on page 120 of The Elements of Statistical Learning it says the gradient is
$$\sum_{i = 1}^N x_i(y_i - p(x_i;\beta))$$
I don't know what could have possibly gone wrong. Any advice on this?
Comment: Did you mean $p(x)=\sigma(p(x))$ ? Because I don't see you using $f$ anywhere.
Comment: Also, note your final line can be simplified to: $\sum_{i=1}^n \Bigl[ p(x_i) (y_i - p(x_i))  \Bigr]$.
Comment: Yes, absolutely, thanks for pointing out, it is indeed $p(x) = \sigma(p(x))$. But isn't the simplification term: $\sum_{i=1}^n [p(x_i) ( 1 - y \cdot p(x_i)]$ ?
Comment: Maybe, but I just noticed another mistake: when you compute the derivative of the first term in $L(\beta)$.
Comment: Ah, are you sure about the relation being $p(x)=\sigma(f(x))$? Because if that's the case, then I can see why you don't arrive at the correct result.
Comment: Yes, double checked it, the basis definition is now correct.
Answer: So, if $p(x)=\sigma(f(x))$ and $\frac{d}{dz}\sigma(z)=\sigma(z)(1-\sigma(z))$, then
$$\frac{d}{dz}p(z) = p(z)(1-p(z)) f'(z) \; .$$
This changes everyting and you should arrive at the correct result this time.
In particular,
$$\frac{d}{dz}\log p(z) = (1-p(z)) f'(z)$$
and
$$\frac{d}{dz}\log (1-p(z)) = -p(z) f'(z) \; .$$
Comment: Of course, I ignored the chain rule for that one!
Comment: Also be careful because your $\beta$ is a vector, so is $x$. So you should really compute a gradient when you write $\partial/\partial \beta$.
Answer: The classification problem data can be captured in one matrix and one vector, i.e. $\{X,y\}$.
Then the relevant quantities are the vectors
$$\eqalign{
 f &= X^T\beta \cr
 p &= \sigma(f) \cr
}$$
and their differentials and logarithmic differentials
$$\eqalign{
 df &= X^Td\beta \cr
 dp &= p\circ(1-p)\circ df \cr\cr
 d\log(p) &= \frac{dp}{p} \,=\, (1-p)\circ df \cr
 d\log(1-p) &= \frac{-dp}{1-p} \,=\, -p\circ df \cr
}$$
where $(g\circ h)$ and $\big(\frac{g}{h}\big)$ denote element-wise (aka Hadamard) multiplication and division.
The likelihood function is a scalar which can be written in terms of Frobenius products
$$\eqalign{
 L &= y:\log(p) + (1-y):\log(1-p) \cr
}$$
whose differential is
$$\eqalign{
 dL &= y:d\log(p) + (1-y):d\log(1-p) \cr
 &= y:(1-p)\circ df - (1-y):p\circ df \cr
 &= (y-p):df \cr
 &= \big(y-p\big):X^Td\beta \cr
 &= X\,\big(y-p\big):d\beta \cr
}$$
Yielding the gradient as
$$\eqalign{
\frac{\partial L}{\partial\beta} &= X\,(y-p) \cr
}$$
Comment: This is the matrix form of the gradient, which appears on page 121 of Hastie's book.
Comment: Why did the transpose of X become just X? How did you remove the transpose by moving the order to the front?
Answer: In your third line, while differentiating you missed out $1/p(x_i)$ which is the derivative of $\log(p(x_i))$.
\begin{eqnarray}
d/db(y_i \cdot \log p(x_i)) &=& \log p(x_i) \cdot 0 + y_i \cdot(d/db(\log p(x_i))\\
&=& y_i \cdot 1/p(x_i) \cdot d/db(p(x_i))
\end{eqnarray}
Note that $d/db(p(xi)) = p(x_i)\cdot {\bf x_i} \cdot (1-p(x_i))$ and not just $p(x_i) \cdot(1-p(x_i))$.
Also in 7th line you missed out the $-$ sign which comes with the derivative of $(1-p(x_i))$.

Log-likelihood gradient and Hessian


Creating SNMPD Agent - Writeable objects and more

Question: Apologize for the long post, majority of it are config files that need to be shown.
I've been creating my own SNMP agent.  For creating my MIB and snmpd.conf file I've just searched the web for answers.  For actually implementing the handlers I've used the example.c/.h found at http://www.net-snmp.org/dev/agent/example_8c_source.html
I'm using another PC (all Linux) to test my implementation and so far I've only been able to get snmpwalk/snmpget commands to work.
I've setup the WriteMethod function inside my source file for my setable objects.  Problem is, I do not think this code is getting executed when trying to set the object.
Below is an example of trying to set the object:
root@jt:/usr/share/snmp/mibs# snmpset -v 2c -c communityNameHere -m MIB-NAME-HERE.txt 10.20.30.40 126.96.36.199.4.1.12345.1 s "0"
MIB search path: /root/.snmp/mibs:/usr/share/snmp/mibs:/usr/share/snmp/mibs/iana:/usr/share/snmp/mibs/ietf:/usr/share/mibs/site:/usr/share/snmp/mibs:/usr/share/mibs/iana:/usr/share/mibs/ietf:/usr/share/mibs/netsnmp
Cannot find module (MIB-NAME-HERE.txt): At line 0 in (none)
Error in packet.
Reason: notWritable (That object does not support modification)
Failed object: iso.22.214.171.124.1.12345.1

I've also tried to use snmpset without the -m option.  I've tried using -m +MIB-NAME-HERE.txt as well.
Question - I have snmp.conf commented out.  How can it not find the module when the MIB I specify is in /usr/share/snmp/mibs ?
Below is my MIB :
MIB-NAME-HERE DEFINITIONS ::= BEGIN

IMPORTS
    MODULE-IDENTITY, OBJECT-TYPE, Integer32, enterprises,
    NOTIFICATION-TYPE                       FROM SNMPv2-SMI
    OBJECT-GROUP, NOTIFICATION-GROUP        FROM SNMPv2-CONF
;

testSnmp MODULE-IDENTITY
    LAST-UPDATED "201505200000Z"
    ORGANIZATION "www.example.com"
    CONTACT-INFO
         "email: email@example.com"
    DESCRIPTION
        "MIB Example."
    REVISION     "201505200000Z"
    DESCRIPTION
        "version 1.0"
    ::= { enterprises 12345 }

--
-- top level structure
--
   testSnmpValues       OBJECT IDENTIFIER ::= { testSnmp 1 }

testSnmpValuesGroup OBJECT-GROUP
    OBJECTS { testObject
            }

    STATUS current
    DESCRIPTION
           "Group of all test variables."

    ::= { testSnmp 4 }

--
-- Values
--

testObject OBJECT-TYPE
    SYNTAX      OCTET STRING (SIZE(1..4096))
    MAX-ACCESS  read-write
    STATUS      current
    DESCRIPTION
        "Test Example"
    ::= { testSnmpValues 1 }

Question - What is the purpose of :
   testSnmpValues       OBJECT IDENTIFIER ::= { testSnmp 1 }

testSnmpValuesGroup OBJECT-GROUP
    OBJECTS { testObject
            }

    STATUS current
    DESCRIPTION
           "Group of all test variables."

    ::= { testSnmp 4 }

Now for my snmpd.conf file :
###############################################################################
#
# snmpd.conf:
#   Test snmpd configuration file.  (See EXAMPLE.conf as a reference)
#
###############################################################################
# By default snmp looks here:
# /etc/snmp/snmpd.conf.
# Use '-C -c <configfile>' to override.
#

###############################################################################
# Access Control
###############################################################################

#       sec.name  source          community
com2sec testall    default         communityNameHere
#---- Community 'communityNameHere' uses security name 'testall'. 'source' selects which IPs can connect.

####
# Second, map the security names into group names:
#               sec.model  sec.name
group TestGroup  v1         testall
group TestGroup  v2c        testall
group TestGroup  usm        testall

####
# Third, create a view for us to let the groups have rights to:
#           incl/excl subtree                          mask
#view all    included  .1                               80
view testview included .22.214.171.124.4.1.12345
#---- testview - A view which only allows access to Test OIDs.

####
# Finally, grant the groups access to the 1 view with different
# write permissions:
#                context sec.model sec.level match  read    write   notif
#---- Grant read access to TEST group for all security models.
access  TestGroup ""      any       noauth    exact  testview testview testview

# -----------------------------------------------------------------------------

# load the testsnmp module
dlmod testsnmp /usr/local/testsnmp.so

Question - Is there something I am missing to make an object writeable?  I've seen other snmpd.conf files with different formats but I assume that shouldn't matter?
Comment: I've tried adding `rwcommunity communityNameHere` to the snmpd.conf file and still no luck.
Answer: You generally don't need a MIB for net-snmp to work. It is enough when you have the OID specified in the .c file.
Are you trying the snmpset/get/walk on a remote PC or on the same one.
I had to specifie in my snmpd.conf   the
-> agentAddress  udp:161
Without it i didn't had access.
Comment: It was actually the syntax of the snmpset command that was the problem.  I needed to add a .0 to the end of the element I was attempting to set.  Reason for it, I think it has something to do with the non-supported type of the object but without going through the underlying code, I wouldn't trust what I've read.
Answer: Your MIB file missing "END" at the end, you can validate it here: simpleweb mib validation
I named my community "public" and had to add this in /etc/snmp/snmpd.conf
com2sec ConfigUser     default       public
 com2sec AllUser        default       public
 group   ConfigGroup     v1           ConfigUser
 group   AllGroup        v2c          AllUser
Now you shall be able to do your tests with v1.
I had to do export MIBS="MY-MIB", whereas MY-MIB.txt is my MIB file, which I put info /usr/local/share/snmp/mibs/. I don't remember exactly whether it was required for mib2c tool or if you can skip defining MIBS variable.
Then you could start snmpd with -d switch to see debug output, start your agent and can do testing. I had to enable ports used by snmpd in my firewall, which were blocked by default. I can test read/write on my dummy value with:
snmpget -v1 -c public localhost:10161 MY-MIB::test2.0
MY-MIB::test2.0 = INTEGER: 43 tests
snmpset -v1 -c public localhost:10161 MY-MIB::test2.0 = 123
MY-MIB::test2.0 = INTEGER: 123 tests

As long as you have a working agent, this shall work, you can use also mib2c to create simple sub-agent for your test-MIB and test it with it, just to make sure your config+agent is all right.
Comment: I should have noted - I didn't display the entire MIB which is ultimately my fault.  Come to find out, I needed to add a .0 after the OID I specified to set. +1 for your explanation.


Use comparison test to show that $\sum^{+\infty}_{k=1} \frac{1}{k(k+1)(k+2)}$ converges and find its limit

Question: Use comparison test to show that $\sum^{+\infty}_{k=1} \frac{1}{k(k+1)(k+2)}$ converges and find its limit
I tried expanding out the denominator, and then using the comparison test with $\frac{1}{k^3}$ but I think this is an incorrect use of the comparison test as I get divergence. I know that the limit is $\frac{1}{4}$ but I am not sure how to use the comparison test to then apply the limit.
Comment: To find the limit, see my answer on http://math.stackexchange.com/questions/1000297/calculate-sum-n-1-infty-frac12n-frac1n1-frac12n4/1000306#1000306
Comment: The series is smaller than $\sum 1/k^3$ so converge.
Comment: use partial fraction decomposition, and it will telescope. otherwise integrate 2 times the Taylor series of $-\log(1-z)$
Answer: $$\begin{align}\sum^\infty_{k=1} \frac{1}{k(k+1)(k+2)} & <\sum^\infty_{k=1} \frac{1}{k(k+0)(k+0)}\\ & =\sum^\infty_{k=1} \frac{1}{k^3}\end{align}$$
It converges.
Franko's telescoping sum:
$$\sum^\infty_{k=1} \frac{1}{k(k+1)(k+2)}=\sum^\infty_{k=1}\left(\frac{1/2}{k(k+1)}-\frac{1/2}{(k+1)(k+2)}\right)$$
$$=\frac14$$
Answer: Observe that
$$\frac{1}{k(k+1)(k+2)}<\frac1{k^3}$$
Then
$$\sum_{k\ge 1} \frac{1}{k(k+1)(k+2)}<\sum_{k\ge 1}\frac1{k^3}$$
I dont know an easy way to calculate it limit. But if you know something about finite calculus we can rewrite your summation as
$$\sum_{k\ge 1} \frac{1}{k(k+1)(k+2)}=\sum_{k\ge 0}k^{\underline {-3}}=\frac{k^{\underline {-2}}}{-2}\Bigg|^{\infty}_{0}=\frac{1}{4}$$
Comment: you are allowed to write it as a telescoping series..
Comment: @user1952009 yeah... Im allowed to be millonaire too but is not the case xD. I mean: this is the easier thing that comes to my mind.
Comment: It isn't, see simpleArt's answer (and think on this: is $\int_a^b f'(t) dt = f(b)-f(a)$ a telescoping sum afterall ?)
Answer: Given that the rising and falling factorials are defined  as
$$
\begin{array}{l}
 n^{\,\overline {\,m\,} }  = n\left( {n + 1} \right)\, \cdots \;\left( {n + m - 1} \right) \\
 n^{\,\underline {\,m\,} }  = n\left( {n - 1} \right)\, \cdots \;\left( {n - \left( {m + 1} \right)} \right) \\
 n^{\,\underline {\, - \,m\,} }  = \frac{1}{{\left( {n + m} \right)^{\,\underline {\,m\,} } }} = \frac{1}{{\left( {n + 1} \right)^{\,\overline {\,m\,} } }} \\
 \end{array}
$$
where here we consider $n$ and $m$ integers,
and that it is not difficult to demonstrate that
$$
\begin{gathered}
  \Delta _{\,n} \,n^{\,\underline {\,m\,} }  = \left( {n + 1} \right)^{\,\underline {\,m\,} }  - n^{\,\underline {\,m\,} }  = m\,n^{\,\underline {\,m - 1\,} }  \hfill \\
  \sum\limits_{k = a}^{b - 1} {k^{\,\underline {\,m\,} } } \quad \left| {\;a < b} \right.\quad  = \frac{1}
{{m + 1}}\left( {b^{\,\underline {\,m + 1\,} }  - a^{\,\underline {\,m + 1\,} } } \right) \hfill \\
\end{gathered}
$$
Then
$$
\begin{gathered}
  \sum\limits_{k = 1}^\infty  {\frac{1}
{{k\left( {k + 1} \right)\left( {k + 2} \right)}}}  = \sum\limits_{k = 0}^\infty  {\frac{1}
{{\left( {k + 1} \right)\left( {k + 2} \right)\left( {k + 3} \right)}}}  = \sum\limits_{k = 0}^\infty  {k^{\,\underline {\, - 3\,} } }  = \mathop {\lim }\limits_{n\; \to \;\infty } \sum\limits_{k = 0}^{n - 1} {k^{\,\underline {\, - 3\,} } }  = \mathop {\lim }\limits_{n\; \to \;\infty } \left( { - \frac{1}
{2}\left( {n^{\,\underline {\, - 2\,} }  - 0^{\,\underline {\, - 2\,} } } \right)} \right) =  \hfill \\
   = \mathop {\lim }\limits_{n\; \to \;\infty } \left( { - \frac{1}
{2}\left( {\frac{1}
{{\left( {n + 1} \right)\left( {n + 2} \right)}} - \frac{1}
{{1 \cdot 2}}} \right)} \right) = \frac{1}
{4} \hfill \\
\end{gathered}
$$
Answer: Yes you compare with $\frac{1}{k^3}$, as follows,
$$\frac{k^3}{k(k+1)(k+2)}\rightarrow 1$$ so the series converges, because $\sum \frac{1}{k^3}$ converges.


angularjs: using $watch in directive to call serivce

Question: I am creating a directive that does a two day binding with an input box.
a $watch is placed inside link function(which i don't know if this is a good idea) to watch the value in the input box.
it looks like the scope.$watch is not doing anything at all.
I can't figure out what the problem is as i have tried to replace
from
scope.$watch('var',srv.doStuff(),true);

to
scope.$watch('location',srv.doStuff(),true);

No luck still.
Thanks all
http://plnkr.co/edit/4XUqPsCLFOoJD0BPlk14
index.html

<form novalidate class="simple-form">
    Input: <input type="text" ng-model="location" required>

</form>

app.js
var app = angular.module('plunker', []);

app.controller('formCtrl', function($scope) {
  $scope.location="empty";
});

// a service
app.service('srv', function() {
  //a function does stuff
  this.doStuff=function (){
     console.log('i am done');
  };
});

//a diretive calls serivce
app.directive('ngMydir', function (srv) {
  return {
    restrict: 'A',
    scope: {
        var:'='
    },
    link: function(scope,elem,attrs,ctrl){
    console.log(scope.var);
    scope.$watch('var',srv.doStuff(),true);
    }
  };
});

Answer: You passed in srv.doStuff(), which is a function call rather than an actually function, you can use one of the following solutions:
Warp the function call srv.doStuff() in a function like this
link: function (scope, elem, attrs, ctrl) {
    scope.$watch('var', function () {
        srv.doStuff();
    }, true);
}

Or simply
link: function (scope, elem, attrs, ctrl) {
    scope.$watch('var', srv.doStuff, true);
}

Comment: thanks, it works, but i don't understand as srv.soStuff() is a function already, why do i have to wrap it inside a function?
Comment: @user2213606 updated. you did `srv.doStuff()`, this is function call rather than a function reference.


The easiest way to solve $\int\arcsin(\sin x)\;\mathrm{d}x$?

Question: Here's the integral:
$$\int\arcsin(\sin x)\;\mathrm{d}x$$
What is the best way to solve it? I was thinking of integration by parts, but it seems to be the most hard way to deal with it. Are there easier ways to proceed?
Comment: In which interval  ? you want to integrate  ?
Comment: If you are careful about the interval of integration, the expression will simplify substantially.
Answer: $$f(x)=\arcsin(\sin x)$$ is a periodic function with $T=2\pi$
$$f(x)=\arcsin(\sin x)=\begin{cases}x & -\dfrac{\pi}{2}\leq x \leq\dfrac{\pi}{2} \\ \pi-x & \dfrac{\pi}{2} \leq x\leq \dfrac{3\pi}{2}\end{cases}$$
Comment: @Salahamam_Fatima: $$f(\dfrac{\pi}{2})=\arcsin(sin \dfrac{\pi}{2})=\arcsin(1)=\dfrac{\pi}{2}\\f(\dfrac{5\pi}{2})=\arcsin(sin \dfrac{\pi}{2})=\arcsin(1)=\dfrac{\pi}{2} \\ \to \\f(\dfrac{\pi}{2})=f(5\dfrac{\pi}{2})$$
Comment: soory it is Ramadan.thanks .
Answer: hint
In the interval $[-\frac {\pi}{2}+2k\pi,\frac {\pi}{2}+2k\pi] $
$$\arcsin (\sin (x))=x-2k\pi $$
and in $[\frac {\pi}{2}+2k\pi,\frac {3\pi}{2}+2k\pi ] $
$$\arcsin (\sin (x))=x-(2k+1)\pi $$
for example
$$\int_0^\pi\arcsin (\sin (x))dx=$$
$$\Bigl [\frac {x^2}{2}\Bigr]_0^\frac {\pi}{2}+\Bigl [\frac {x^2}{2}-\pi x\Bigr]_\frac {\pi}{2}^\pi $$
Answer: Let's have $f(x)=\arcsin(\sin(x))$ and calculate $\displaystyle F(x)=\int_0^x f(t)dt$
Since $f$ is $2\pi-$periodic and $F(2\pi)=0$ by symetry, we have that $F$ is $2\pi-$periodic too.

The idea by kingW3 to introduce $s(x)=\operatorname{sgn}(\cos(x))$ will be useful to find a closed form.
$F(x)=x\arcsin(\sin(x))-\frac{s(x)}2x^2+C(x)$
In fact his formula is correct on $1$ period interval under the condition that we assign a constant value for $C(x)$ in each of the $3$ intervals described below.

But I'll propose a slightly different form : $F(x)=s(x)(\frac 12f(x)^2)+B(x)$ where $B(x)$ is piecewise constant too, but zero on two of the intervals.
Under this form the periodicity of $F$ is more obvious knowing that $f$ is periodic.

$\displaystyle x\in[0,\frac{\pi}{2}];\quad F(x)=\int_0^x tdt=\frac {x^2}2$
$\displaystyle x\in[\frac{\pi}{2},\frac{3\pi}{2}];\quad F(x)=F(\frac{\pi}2)+\int_{\frac\pi2}^x (\pi-t)dt=\frac {\pi^2}8+\bigg[\pi t-\frac{t^2}2\bigg]_{\frac{\pi}2}^x=\pi x-\frac{x^2}2-\frac{\pi^2}4$
$\displaystyle x\in[\frac{3\pi}{2},2\pi];\quad F(x)=F(\frac{3\pi}2)+\int_{\frac{3\pi}2}^x (t-2\pi)dt=\frac {\pi^2}8+\bigg[\frac{t^2}2-2\pi t\bigg]_{\frac{3\pi}2}^x=\frac{x^2}2-2\pi x+2\pi^2$

$\begin{cases}
x\in[0,\frac{\pi}{2}] & f(x)=x & s(x)=+1 & \frac 12s(x)f(x)^2=\frac {x^2}2 & B(x)=0\\
x\in[\frac{\pi}{2},\frac{3\pi}{2}] & f(x)=\pi-x & s(x)=-1 & \frac 12s(x)f(x)^2=-\frac{\pi^2}2+\pi x-\frac {x^2}2 & B(x)=\frac{\pi^2}4\\
x\in[\frac{3\pi}{2},2\pi] & f(t)=x-2\pi & s(x)=+1 & \frac 12s(x)f(x)^2=\frac{x^2}2-2\pi x+2\pi^2 & B(x)=0\\
\end{cases}$
Now if we consider $\displaystyle \frac{1-s(x)}2=\chi_{[\frac{\pi}{2},\frac{3\pi}{2}]+2k\pi}$ then $B(x)=\big(\frac{1-s(x)}2\big)\frac{\pi^2}4$
Finally a simplified closed form for $F(x)$ can be given by :

$\displaystyle \int_0^x \arcsin(\sin(t))dt=\frac{\pi^2}8+\operatorname{sgn}(\cos(x))\bigg(\frac{\arcsin(\sin(x))^2}2-\frac{\pi^2}8\bigg)$


Prove that $\lim_{z \to i} |1-z|^2=2$

Question:
Prove that $\lim_{z \to i} |1-z|^2=2$.

I let $\epsilon>0$ and $\delta$ = (blank, since I don't know what to choose yet)
When $|z - i| < \delta$, $||1 - z|^2 - 2| ≤ |(1 - z)^2 - 2| = |z^2 - 2z - 1|.$
And then I'm stuck. I'm not sure how I can extract out a $|z - i| < \delta$ in order to further the proof.
Comment: It isn't true that $\;|1-z|^2=(1-z)^2\;$ in $\;\Bbb C\;$ . For example, the left side is always real, whereas the right one is always complex non-real if $\;\text{Im}(z)\neq0\;$
Comment: I do know that $|1 - z|^2$ is not always equal to $(1-z)^2$, but I was thinking of using the reverse triangle inequality, which states that |a - b| ≥ ||a| - |b||. So I took a = $|1 - z|^2 = |(1-z)^2|$ and b = 2 = |2|. Was that a wrong assumption to make?
Answer: You could use the identification $\;\Bbb C\sim\Bbb R^2\;$ and then
$$\lim_{z\to i}|1-z|^2=\lim_{(x,y)\to(0,1)}||(1,0)-(x,y)||^2=\lim_{(x,y)\to (0,1)}\left[(1-x)^2+y^2\right]=1^2+1^2=2$$
Comment: And this is still not a $\varepsilon$-$\delta$ proof.
Comment: and isn't this proof based on the assumption that we approach x and y from the left and right side? Whereas with a $\epsilon-\delta$ proof (and the fact that it is on the complex plane), we would have to approach from every direction.
Comment: @GitGud Yes, it is not. I didn't read that was a condition, although the poster tried it.
Comment: @Cici What left and right sides? We're on the plane: there are infinite number of direction, and in the proof there is nothing that restricts them.
Comment: @Joanpemo To be honest it's not necessary. Your proof is as useful as saying $\lim \limits_{z\to i}\left(|1-z|^2\right)=2$. You use polynomials in $\mathbb R^2$, I use them in $\mathbb C$. But a proof that at least one of them works is required.
Comment: @Joanpemo, when I said "left and right side", I meant the idea that is used in single variable calculus on the reals, where one would observe the limit of $x \to 1^+$ and $x \to 1^-$. And to me your proof doesn't look like it is using the idea that we're approaching i from all directions.

Perhaps I'm just misunderstanding something, but would it be possible to do a $\epsilon-\delta$ proof? (out of curiosity)
Comment: @GitGud I used the idea that a polynomial in any number of variables is always contunuous anywhere and thus its limit is just substituting, and I guess it is possible to do it the same over the rationals or over the complex.
Comment: @Cici If you see any restriction on any direction in my proof please do tell me. I just can't see any. About an $\;\epsilon-\delta\;$ proof: I'll post something if I come up with some idea.
Comment: @Joanpemo I suppose it's because I don't see any restrictions, hence why I'm hesitant. And your proof just seemed to be too simple and too elegant. (I'm not very good with $\epsilon-\delta$ proofs, hence why I'm often unsure of what I can and can't claim in them).
Answer: You will have hard time bounding the distance this way. $\varepsilon-\delta$ tricks work well if you use more "homogenous" inequalities or you should decompose it to an atomic level (But thats just my two cents)...
Write $z=x+iy$, then:
$$||1-z|^2-2| =|(1-x)^2 +y^2 -2|=|-2x+x^2+y^2-1| \tag1 $$
Recall we have $\delta^2 > |z-i|^2 =x^2+(y-1)^2 $, so obviously enough: $|x|<\delta$ and $|y-1| < \delta$
Returning to $(1)$ we have: $$|-2x+x^2+y^2-1|\leq|x||-2+x| + |y-1||y+1| $$
Which can be bounded in terms of delta (I leave it to you).
Comment: Oh thank you! A quick question though, when you said:
$||1 - z|^2 - 2| = |(1 + x)^2 + y^2 - 2|$
Shouldn't it be $|(1 - x)^2 + y^2 - 2|$?
Comment: @Cici, you are right!
Comment: @Ranc Alrighty! Thank you for your help!
Comment: @Cici Yes, you are right. But it's worth mentioning that the reason i could still bound it is because we can define $z=-x+iy$... (Thats why there wasn't any "crucial" mistake in the next steps...)

Prove that $\lim_{z \to i} |1-z|^2=2$


Merge [rest] into [rest-api]

Question:
rest-api: 1,078 tagged questions

Magento REST API defines a set of functions that a developer can use to perform requests and receive responses. These interactions are performed using the HTTP protocol.

rest: 813 tagged questions

Denotes questions related to the REST API on Magento

These tags are both about the Magento REST API. I think they should be merged and rest should be a synonym of rest-api.
Answer: Done!. Thanks for the suggestion

Merge [rest] into [rest-api]


Por que HATEOAS é importante?

Question: Estou estudando REST e desenvolvimento de Web API's e ouvi falar sobre HATEOAS (Hypertext as the engine of application state). Eu entendi a ideia: ao responder uma requisição, além do que normalmente retornamos, a ideia é também retornar dados sobre o que pode ser feito em seguida. Um exemplo que vi na internet foi esse:
GET /account/12345 HTTP/1.1 HTTP/1.1 200 OK
<?xml version="1.0"?>
<account>
    <account_number>12345</account_number>
    <balance currency="usd">100.00</balance>
    <link rel="deposit" href="/account/12345/deposit" />
    <link rel="withdraw" href="/account/12345/withdraw" />
    <link rel="transfer" href="/account/12345/transfer" />
    <link rel="close" href="/account/12345/close" />
</account>

Além disso, já li várias vezes que fazer isso é muito importante pra várias coisas, entre elas pra permitir que a API consiga evoluir facilmente sem quebrar clients antigos.
Acontece que eu não consigo entender quais são os reais benefícios de fazer isso. Basicamente o client não vai decidir por si só quais chamadas fazer baseado nesses links, de qualquer forma temos que colocar "hardcoded" lá o que pode ser feito em seguida.
Assim, qual a real importância de usar HATEOAS e quais benefícios temos a partir do seu uso?
Comment: No momento não posso dar uma resposta abrangente, mas pense numa simples página web: o client (browser) pode não decidir por si só quais chamadas fazer, mas o usuário pode - é só clicar nos links! O fato das páginas web usarem HATEOAS permite que tanto os servidores (i.e. o que implementa a lógica da aplicação, e que serve páginas web segundo esse princípio) podem variar (não importa se é Java, .NET, PHP, Python...) quanto os clientes que consomem as mesmas também podem (não importa se é Firefox, Chrome, IE...), *de forma independente um do outro*. A ideia geral é essa.
Answer: A característica HATEOAS é, nas palavras do seu autor, "design na escala de décadas" e "muitas das suas restrições são diretamente opostas à eficiência em curto prazo". Ou seja, é algo aplicável a softwares/plataformas de propósito mais geral, destinados a sobreviver por um longo período de tempo, apesar das evoluções da tecnologia.
O melhor exemplo de aplicação prática do HATEOAS é o protocolo HTTP, no qual uma variedade de servidores podem se comunicar com uma variedade de clientes, e ambos podem evoluir de forma independente uns dos outros. Numa aplicação web, por exemplo, não apenas as estruturas das páginas são informadas pelo servidor (e renderizadas no browser) como também vem a indicação de quais ações são possíveis a partir daquela página - representadas por meio de URLs a serem consultadas (sejam hiperlinks, destinos de formulários, ou outra coisa). Uma mudança no servidor (digamos, a inclusão de um novo campo na página) não demanda uma mudança no cliente, pois quaisquer ações relacionadas a ela estarão representadas na forma de hipermídia, e o browser sabe como invocá-las via o próprio protocolo HTTP.
Você está certo quando diz que os links devem representar o que pode ser feito em seguida. O significado disso, entretanto, é que é o ponto chave: essa combinação dados + link representam o estado do sistema, ou do recurso dentro do sistema. Usando o mesmo exemplo citado, se a conta bancária está no negativo, então não se pode retirar dela ou transferir a partir dela, somente depositar mais dinheiro nela:
<?xml version="1.0"?>
<account>
    <account_number>12345</account_number>
    <balance currency="usd">-25.00</balance>
    <link rel="deposit" href="/account/12345/deposit" />
</account>

Isso tem pelo menos dois significados práticos:

O servidor não precisa manter registro de quem é o cliente que está acessando, nem em que estado ele está: o próprio cliente sabe que as únicas transições possíveis são aquelas para as quais existe um link disponível;
O cliente não precisa implementar nenhuma lógica customizada para descobrir quais ações são possíveis baseadas no estado atual do recurso (ex.: verificar se o saldo é ou não positivo, e com base nisso determinar se os links para retirar ou transferir devem ou não ser exibidos/habilitados). Os próprios links já dizem - pela sua presença ou ausência - o que pode ou não ser feito.

Quanto à sua alegação de que "o client não vai decidir por si só quais chamadas fazer baseado nesses links", de fato, não vai, pelo menos não sem que alguma ação seja feita por parte do usuário. Mas não é essa a única razão pela qual o servidor se comunicou com o cliente, para permitir que o usuário fizesse alguma coisa? Se a próxima chamada já pudesse ser determinada segundo alguma lógica automatizada, não precisava do controle vir pro cliente e ele fazer uma nova requisição depois disso, bastaria o próprio servidor decidir e fazer isso lá mesmo...
hardcoding
Essa questão do que colocar hardcoded e do que deixar genérico é justamente o que diferencia um design para longo prazo de um para curto. Se você está desenvolvendo um único servidor para se comunicar com um único [tipo de] cliente, então não faz sentido a princípio usar REST, muito menos usar HATEOAS! Apenas se você prevê que múltiplos clientes serão desenvolvidos com o tempo, e todos têm de ser compatíveis com o seu servidor, é que essa metodologia se aplica.
A questão toda é de evolução: se na especificação do seu client você determina que "deve haver uma tela para representar uma conta bancária, com um campo pro número e outro pro saldo, e botões para as ações 'depositar', 'retirar', 'transferir' e 'fechar'", nada impede que múltiplas implementações do seu client sejam feitas. Entretanto, se no futuro você decide incluir um campo "agência", ou você terá que torná-lo opcional (para não quebrar os clients existentes) ou terá que atualizar a especificação do client (automaticamente tornando todos os existentes incompatíveis com sua versão do server). A evolução do servidor fica atrelada à evolução dos clientes...
No caso de um campo, como no exemplo acima, não existe solução fácil: afinal, a semântica por trás dos dados representados ainda precisa ser acordada entre clientes e servidores, e isso tem de ser feito "out-of-band" (como exemplo, cada tag HTML possui uma semântica precisa, e espera-se tanto que os browsers renderizem/implementem ela corretamente quando que os servidores as enviem com uma expectativa correta do que será apresentado ao usuário).
Mas no caso das ações, no sentido de "coisas que podem ser requeridas posteriormente do servidor", é mais simples estabelecê-las de uma forma genérica do que colocá-las também hardcoded na especificação. É claro, isso presume alguma forma de comunicar ao usuário qual é a semântica da mesma (apareceu um link novo, mas o que exatamente ele faz?). Isso pode ser feito ou de forma genérica (um texto, ícone ou tooltip acompanha o link) ou também demandar uma mudança no client (se é uma ferramenta automatizada que está consumindo sua API REST, não há saída a não ser adaptá-la para se beneficiar da possibilidade nova que surgiu).
Importância e Benefícios
Infelizmente, não tenho conhecimento nem experiência suficiente para opinar sobre isso. A grande maioria dos softwares que fazemos busca eficiência em curto prazo, e a forma mais comum de evolução é "jogar fora e começar do zero"... Não apenas é raro termos prazo e orçamento para projetar para o longo prazo, como também é relativamente raro haver o interesse na interoperabilidade com sistemas de terceiros (o servidor da minha empresa tem de ser acessado pelo client da minha empresa!). E quanto surge a necessidade de uma API, ela normalmente é destinada a alimentar um processo automatizado, que precisa tomar uma decisão em relação ao próximo passo a executar, e portanto um "conhecimento" da semântica por trás das ações disponíveis.
Por essas razões, eu pessoalmente não vejo muito benefício em se seguir os princípios REST e HATEOAS à risca; talvez com mais experiência em projetos maiores, minha opinião mude, e eu possa dar uma resposta mais completa e embasada. No momento, só posso responder com uma outra pergunta: você está preparado para o momento em que seu serviço evoluir? Como pretende evitar que todos os clients do mesmo quebrem quando isso acontecer?
Answer: Não é um padrão que me agrada, pode ter certeza que implementar isso vai deixar seu desenvolvimento no mínimo 20% mais lento, também mais poluido, veja uma implementação em Spring onde você retornaria a entidade pura, você retorna um "Resource" da entidade ou seja, tem trabalho de criar uma classe secundaria, na hora de receber o dado também recebe com uma camada a mais, ia demorar mais pra fazer e deixar o codigo mais poluído, e não me agrada a idéia de misturar a documentação da API com os dados que estão sendo trafegados, a documentação é algo que na minha opnião é melhor estar separada em um documento, gera uma poluição amais nos seus dados, imagine uma lista com 30 dados por exemplo cada um com 5 links, seria um problema indentificar um erro nesse JSON ou XML, já o que mas me faz ir contra esse padrão são os beneficios dele, não vejo nenhum quase, exemplo:
<link rel="close" href="/account/12345/close" />

Aqui o front iria trabalhar com o parametro que esta dentro do HREF, um beneficio seria ficar desacoplado desse conteudo, se ele fosse alterado não teria nenhuma modificação no client, porém e se estamos pensando em alterar as rotas da aplicação teriamos que pensar que os atributos podem ser alterados também como por exemplo ao invés de "close", poderia virar "exit" por exemplo, e isso estaria hardcoded no client também, causaria problema da mesma forma, e complicaria ainda mais a correção do problema, a documentação teria que existir de qualquer forma, trabalhar substituindo a documentação por esse padrão, daria muito mais problema do que solução, e se a documentação vai ter que existir de qualquer forma sinceramente não vejo beneficio nenhum nisso.
Existem coisas parecidas como por exemplo pra quem ja trabalhou com Web Service deve conhecer WSDL, onde é uma especie de documentação do webservice, só que a utilidade é extrema, o java tem recursos que ja converte isso em classes, além disso é um arquivo só para documentação, não mistura dado com documento. Assim então hoje é algo que eu jamais usaria em nenhum projeto meu nem a curto e muito menos a longo prazo, acho que iria prejudicar muito o projeto com pouco beneficio, mas se por exemplo desenvolverem uma hora ai uma solução que le um rest hateoas e ja faz um client automaticamente, ai a coisa pode começar a mudar, e a produtividade começar a vir com esse modelo ai, mas hoje eu não usaria realmente, ha quem fale muito bem desse padrão mas eu realmente não consigo.
Answer: O que temos hoje na maioria dos serviços são implementações erradas do conceito de REST, tanto que tem uma vertente que tenta corrigir isso chamando as API's que realmente buscar ser REST de Hypermedia API.
O erro está ai

de qualquer forma temos que colocar "hardcoded" lá o que pode ser feito em seguida.

O servidor deve ter a liberdade de gerenciar seus recursos da forma mais apropriada, instruindo o cliente como montar as URL para acessar determinado recurso (que se for "hardcoded" pode ser considerado como um RPC).
Em uma tradução livre das palavras do Roy Fielding:

Uma API REST deve ser usada sem nenhum conhecimento além da URI inicial e um conjunto de tipos de mídia padronizados. A partir desse ponto toda transição de estado deve ser guiado pelo cliente pelas escolhas providas pelo servidor que estão presentes nas representações recebidas ou implícitas pela manipulação do usuário dessas representações. As transições podem ser determinadas (ou limitadas) pelo conhecimento do cliente dos tipos de mídia e mecanismos de comunicação de recursos, ambos podendo ser melhorados on-the-fly.

É um assunto complexo, mas você pode extrair mais informações no blog do Roy Fielding: http://roy.gbiv.com/untangled/2008/rest-apis-must-be-hypertext-driven
--
Recomendo essa apresentações:

https://vimeo.com/20781278
http://symfony.com/video/26/designing-http-interfaces-and-restful-web-services/English

E esse artigo "Ninguém entende REST" http://blog.steveklabnik.com/posts/2011-07-03-nobody-understands-rest-or-http
Comment: Concordo! Quando as pessoas pensam em "API REST" elas pensam numa API estável, que pode ser usada por processos automatizados para realizar tarefas sem intervenção humana (e que portanto seriam "quebrados" caso a API mudasse sem aviso), quando originalmente esse conceito descrevia algo bem diferente...
Answer: Eu acho sem sentido essa idea de HATEOAS.
Se eu adicionar/alterar/remover um método/url da API, o implementador precisa conhecer o que foi alterado, e como chamá-lo, a "API CLiente" não saberá simplesmente navegar na estrutura descrita. O que vai ler isso será um sistema, e não um usuário com inteligência de ler um link e saber o que fazer com ele.
A GRANDE promessa é a de pseudo-documentar a API, porém, existem alternativas muito melhores para tal finalidade.

Por que HATEOAS é importante?


How do I create menu link icons?

Question: I noticed that when I added a new menu link, an icon is now show like groups, events, etc. How do I add an icon for that menu link item?
Answer: You can use menu icons module to generate icon for the menu item.

This module allows you to upload an image in the menu-item's
  configuration form.
After uploading the image, the icon data will be added to the menu
  link's options array.
When a menu link is goes through the theme layer, it will receive an
  extra class which by default is used to attach the images as a
  background image to the corresponding menu item.
Answer: I've recently run into a similar issue. I have a bootstrap based theme that comes with FontAwesome icons, so I was hoping to be able to directly use these icons in my menu title without installing a separate module.
For example fa-homeHome as the menu title would display the home icon before the title "Home", or fa-user would  only show the user icon without any text.
For that I wrote the following theming function:
function MY_THEME_menu_link($variables) {
  $element = &$variables['element'];
  $pattern = '/(^)([a-z\-]+)(<\/i>)([\w\s]*)/i';
  if (preg_match($pattern, $element['#title'], $matches) > 0) {
    $element['#title'] = preg_replace($pattern, ' ' . $matches[4], $element['#title']);
    $element['#localized_options']['html'] = TRUE;
  }
  return theme_menu_link($variables);
}

If you want to do the same with superfish menus, you need to add a different theming function, since superfish menus do not call theme_menu_link:
function scholarly_lite_superfish_menu_item_link(array $variables) {
  $menu_title = $variables['menu_item']['link']['title'];
  $menu_path = $variables['menu_item']['link']['link_path'];
  $link_options = $variables['link_options'];

  $pattern = '/(^)([a-z\-]+)(<\/i>)([\w\s]*)/i';
  if (preg_match($pattern, $menu_title, $matches) > 0) {
    $menu_title = preg_replace($pattern, ' ' . $matches[4], $menu_title);
    $link_options = $variables['link_options'] + array('html' => TRUE);
    // need to pass title without markup to page
  }
  return l($menu_title, $menu_path, $link_options);
}

Hope this helps someone else stumbling upon similar configuration.
Answer: In your template.php file place this
<?php
function phptemplate_menu_item($mid, $children = '', $leaf = TRUE) {
  $link = menu_item_link($mid);
  $css_id = strtolower(str_replace(' ', '_', strip_tags($link)));
  return '
'. $link . $children ."
\n";
}
?>

It'll assign a unique id to each of your menu items, allowing you to attach css to individual menu items. Very handy!
Answer: You can use these module to add icon in menu
Menuimage

When editing a menu link, this module provides a file field to upload
  an image to associate with a menu item. In the array returned by
  menu_link_load, the fid of the image file is contained in
  [options][content][image]. This may may be passed as a parameter to
  file_load to obtain its public:// uri, and further used with either
  file_build_uri or image_style_url to populate the src= attribute of an
  .

Menu_icon

This module allows you to upload an image in the menu-item's
  configuration form.
After uploading the image, the icon data will be added to the menu
  link's options array.

How do I create menu link icons?


"Uncaught TypeError: Cannot read properties of undefined (reading FetchApi.js:23 'data')" when refresh the page

Question: When the code runs for the first time, it's mappings data as I wanted. But when I refresh the page it shows an error.
Does anyone know how can I fix this error and what causes it?

The code

import React, { useEffect, useState } from 'react';
import axios from 'axios';

const FetchApi = () => {

const [items, setItems] = useState();

useEffect(() => {
    getUser();
}, [])

async function getUser() {
    try {
        const response = await axios.get('https://datausa.io/api/data?drilldowns=Nation&measures=Population');
        setItems(response.data.data)
        return items;
    } catch (error) {
        console.error(error);
    }
}

return (

        {
            items.map(item => (

                    {item.Nation}

            ))
        }

  )
}

export default FetchApi

Output when runs for the first time

Error when refresh the page
Comment: Please try changing: `setItems(response.data.data)` to `if (response && response.data && response.data.data) setItems(response.data.data);`. It should avoid trying to access `data` if the object is undefined.
Comment: It didn't work.
Answer: I found the problem.
The problem was, "items" is undefined in its default state.
It should be
const [items, setItems] = useState([]);

And I think the reason this error shows only when refresh the page was,
when I change the code and save, it changes the html view automatically but the browser only reads the changed JavaScript codes so the const [items, setItems] = useState(); line never reads at first.
But when I refresh the page the code runs from the beginning and it catches that "items" is undefined and shows the error.


Vertically scrolling. Horizontal movement

Question: I'm trying to find the code that is moving the page vertically and then moves horizontally while still scrolling vertically. I'm positive it's not Canvas, but I could be wrong.
Here is the example.
http://enso.readymag.com/architects-own-houses/10/
Comment: "Scrolljacking" is one of the worst UX tricks to ever grace the web, and you really, really shouldn't try to imitate it.
Comment: why would it block the scroll events ?..he just needs to listen to scroll events on window and decide wether user is scrolling up or down.
Comment: It probably just blocks all your scroll events, and manually override them. Don't do this. This is terrible UX.
Comment: It is hard to say by looking via web inspector, but you must provide us with your JS files, at least any code related to `.content-bounds` and `animation-container force3d` which are the `div` elements that are being translated horizontally/vertically simultaneously. Look into your JS plugins to identify who is modifying these elements
Comment: Are you looking for something like http://joelb.me/scrollpath/?
Comment: THanks for the quick reply. No actually I'm thinking about ways to present a 15000 word thesis as a design public so I'm looking at way to show it. This really helps though.
Comment: @Blazemonger...that sounds so dogmatic
Comment: As others suggested it might be a bad idea...but if you know what you are dooing, take a look at this : http://codepen.io/nishants/pen/jWVomQ
Answer: Okay your approach seems terrible, but I get what you want to achieve.
You need to fix a container on the viewport, and animate it as scroll happens.
Like this :
<code>var $target  = $(".slider").first(),
    currentPosition = 0,
    moveBy = function(scrolledBy){
        currentPosition += scrolledBy;
        $target.css("transform", "translateX(" + (currentPosition) + "px)")
    },
    lastScrollTop = 0 ;

$(window).bind("scroll",function(e){
    var scrolledBy = $(window).scrollTop() - lastScrollTop;
    moveBy(-scrolledBy);
    lastScrollTop = $(window).scrollTop();
});
</code>
find a demo here : http://codepen.io/nishants/pen/qbqLjw
Do not even think of doing this with canvas
Comment: ha...BTW tried the demo http://joelb.me/scrollpath/, doesn't even work on chrome (mac-os)
Comment: Dawn, Chuckle...At this very moment I am thinking about using html5 canvas to create this [Meezio](https://github.com/JoelBesada/scrollpath) effect. Upvote.


binding lost in jquery using on

Question: $(document).on('submit', 'form[method="POST"]', function(event) {
alert();
});

Above code worked when I submit the form but it lost the binding after I do few pjax navigation.
I have no idea why it stop firing, it's placed the core script and I never refresh the page.
update:
I did an experiment binding click instead of submit
$(document).on('click','.test',function(){
      alert('click')
    })

It worked, but why it doesn't with submit?
Comment: Does `pjax` submit form ? Can include `pjax` portions of `js` at Question ?
Comment: @guest271314 it doesn't matter with pjax
Comment: Something is unbinding your submit event or stopping submit event to propagate through document
Comment: @A.Wolff that must be pjax? have do I bind it back?
Comment: @NicholeA.Miler _"it doesn't matter with pjax "_ ? Not certain what "doesn't matter" ? Is form submitted using `$.ajax()` via `pjax` ?
Comment: @NicholeA.Miler Ya try to rebind it or investigate further the why event isn't fired as expected. Now i don't know pjax plugin, i've no idea what's going on. Other way would be instead of delegating event, try to capture it: `document.addEventListener(
    'submit',
    function(event){
        if( $(event.target).is('form[method="POST"]')){
            alert('form submit called!');
        }
    },
    true /*Capture event*/
);`
Comment: @A.Wolff what does capture event do? It has no different I put an alert within my submit event
Comment: @NicholeA.Miler Capturing event is to avoid any propagation event issue. Now do you have any error in console? Any online link we can check it?
Comment: @A.Wolff can u tell which line of the code unbind my stuff? https://github.com/defunkt/jquery-pjax/blob/master/jquery.pjax.js
Comment: @NicholeA.Miler I'm not sure your event is unbound... I'm not sure what you are doing. Provide a MCVE. And just in doc, they use their own custom method for `submit`, isn't it what you are looking for? `$(document).on('submit', 'form[data-pjax]', function(event) {
  $.pjax.submit(event, '#pjax-container')
})`
Answer: Try using ajaxComplete event
$(document).ajaxComplete(function(event, xhr, settings) {
  // do stuff
})

Comment: If can reproduce issue at jsfiddle or plnkr , would probably be helpful in determining a solution
Comment: Where I should use this? please explain more.
Comment: @NicholeA.Miler If `form` is submitted using `$.ajax()` an `ajaxComplete` event should be called at each `form` submission. Try substituting `ajaxComplete` event for `submit` event for handler to be called when `form` is submitted; see http://api.jquery.com/ajaxComplete/
Comment: Where does this ajaxComplete be placed? the submit event happen before the ajax fire. Does ajaxComplete make sense here?
Comment: @NicholeA.Miler _"Where does this ajaxComplete be placed?"_ Same place where `$(document).on('submit'` is, after removing `$(document).on('submit'` . _"the submit event happen before the ajax fire."_ ? Why asked at comments above if `$.ajax()` submits `form` : _"Is form submitted using $.ajax() via pjax ?"_ : _"$.ajax"_ . Could alternatively use `ajaxStart` event or both `ajaxStart` and `ajaxComplete` events
Comment: you put $.ajax inside a submit event, not the other round.
Comment: @NicholeA.Miler _"you put $.ajax inside a submit event, not the other round."_ ? How is `form` submitted ? Is `form` submitted using `$.ajax()` ? Can you create a jsfiddle http://jsfiddle.net or plnkr http://plnkr.co to demonstrate issue described at original Question ?
Comment: It can be nothing to do with ajax at all, the bind simply gone after I navigate the site which used pjax. http://pastebin.com/hjadYAFM
Comment: Where in `js` does site navigate to a different `url` ?
Comment: `$(document).pjax('a', {
            container: "#content",
            timeout: 12000
        });` With this one line code all links which originally were a native post/get, it use pjax.
Comment: Can this be reproduced at jsfiddle ? Note, not tried `pjax` before here
Comment: the problem is simple, pjax unbind my submit handler. https://github.com/defunkt/jquery-pjax/blob/master/jquery.pjax.js but I have no idea which line does that.
Comment: I've found the problem. A clash of name. Sigh because I'm using on() globally, I have to refactor my classes name on its child. will requirejs solve helps to avoid such clashes?

binding lost in jquery using on


Cannot override FOSOAuthServerBundle tokenAction

Question: I am using the following packages:
    "friendsofsymfony/oauth-server-bundle": "^1.6",
    "friendsofsymfony/rest-bundle": "^2.5",
    "friendsofsymfony/user-bundle": "^2.1",
    "symfony/framework-bundle": "4.2.*",
    "symfony/http-foundation": "4.2.*",
    "symfony/http-kernel": "4.2.*"

I am attempting to override the tokenAction method of the FOSOAuthServerBundle package, but I am getting stuck on the error:
"Cannot autowire service App\Controller\TokenController argument $server of method FOS\OAuthServerBundle\Controller\TokenController::__construct() references class OAuth2\OAuth2; but no such service exists. You should maybe alias this class to the existing fos_oauth_server.server service"

I have tried several different approaches (autowire, auto-injection), but I keep coming full circle back to the error described above. It seems that the "use OAuth2\OAuth2;" reference is properly namespaced in the bundle's TokenController, but when I try to override it cannot parse the OAuth2 class locations properly, and I am not sure what pattern to use either in the class or in the services.yaml to point it to the right location.
Here is my services.yaml
services:

    ...

    App\Controller\TokenController\:
        resource: '../src/Controller/TokenController.php'
        arguments: ['@fos_oauth_server.server']

And my custom TokenController class
?php

namespace App\Controller;

use FOS\OAuthServerBundle\Controller\TokenController as BaseController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

class TokenController extends BaseController
{

    /**
     * @param Request $request
     *
     * @return Response
     */
    public function tokenAction(Request $request)
    {
        $token = parent::tokenAction($request);

        // my custom code here

        return $token;
    }

}

And if I try to do the obvious and add the line
use OAuth2\OAuth2;

to my custom TokenController I get the same error.
Answer: Turns out the answer was to use decorators
In my services.yaml
    App\Controller\OAuth\OAuthTokenController:
        decorates: FOS\OAuthServerBundle\Controller\TokenController
        arguments: ['@fos_oauth_server.server']

Any my custom class to override the TokenController
namespace App\Controller\OAuth;

use FOS\OAuthServerBundle\Controller\TokenController as BaseController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

class OAuthTokenController extends BaseController
{

    /**
     * @param Request $request
     *
     * @return Response
     */
    public function tokenAction(Request $request)
    {
        try {
            $token = $this->server->grantAccessToken($request);

            // custom code here

            return $token;
        } catch (OAuth2ServerException $e) {
            return $e->getHttpResponse();
        }
    }

}


Redirecionar todas as requisições de mídia(css,js e imagens) com htaccess

Question: Estou construindo uma aplicação MVC e estava tendo alguns problemas com o caminho dos arquivos css,js e imagens no html... foi me dada uma solução de usar a tag <base> para definir o caminho que todos os arquivos do html seguiriam, ex: <base href="http://localhost/mvc/>, só que de lá pra cá tive alguns problemas para instalar plugins javascript, uma vez que quando eu colocava, por exemplo, href="#" que ao clicar em vez de não fazer ação nenhuma, esse link me levava pra a url que foi definida com a tag <base> que seria http://localhost/mvc/#, gostaria de saber como posso redirecionar todos os "requests" desses arquivos à uma subpasta, ex:
<link rel="stylesheet" href="main.css">

Todas as requisições levariam para uma subpasta, por exemplo, PUBLIC, ai só precisaria definir no html as pastas dentro dessa public...
Arquivo HTACCESS:
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . index.php [L]

Answer: Testou algo assim? Acredito que solucione seu problema.
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{DOCUMENT_ROOT}/public/$0 -f
    RewriteRule ^.+\.(jpg|jpeg|gif|png|ico|css|js|swf)$ /public/$0 [L]

Comment: Ainda não testei, mas gostaria também de preservar a estrutura do htaccess que eu postei antes, esse vai fazer isso? Obrigado!


Solve for $x$ with exponents

Question: I am trying to solve an equation to find a value of $x$ like this:
$(1.08107)^{98/252}=(1.08804+x)^{23/252}(1.08804+2x)^{37/252}(1.08804+3x)^{38/252}$
That is pretty straightforward using Excel Solver, but I am not quite grasping how to do it by hand.
The result is $-0.00323$.
Thanks in advance.
Comment: Welcome to MSE.  Please type your questions instead of posting images.  Images can't be browsed and are not accessible to those using screen readers.  If you need help formatting math on this site, here's a [tutorial](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference)
Comment: There may be a solution more simply rendered than MS Excel's -0.00323.
Comment: What do you mean Oscar? Thanks for the reply
Comment: A whole number maybe?
Comment: I am sorry. 1.08 is rounded, I wanted to make the post clearer because I am interested in the resolution and not the result itself. I'll edit it to make it more clear.
Comment: Moo, I edited the question before to put the decimals because I didn't realize that would be 0.
Answer: We can use a root finding algorithm, like Newton's Method.
Our function is given by
$$f(x) =  1.03078 -(x+1.08804)^{23/252} (2 x+1.08804)^{37/252} (3 x+1.08804)^{19/126}$$
The Newton iteration is given by
$x_{n+1} = x_n - \frac{f(x_n)}{f'(x_n)} = x_n - \dfrac{
  1.03078 -(x+1.08804)^{23/252} (2 x+1.08804)^{37/252} (3 x+1.08804)^{19/126} }{\left(-\dfrac{23 (2 x+1.08804)^{37/252} (3 x+1.08804)^{19/126}}{252 (x+1.08804)^{229/252}}-\dfrac{37 (x+1.08804)^{23/252} (3 x+1.08804)^{19/126}}{126 (2 x+1.08804)^{215/252}}-\dfrac{19 (x+1.08804)^{23/252} (2 x+1.08804)^{37/252}}{42 (3 x+1.08804)^{107/126}}\right)}$
Starting at $x_0 = 1$, we arrive at
$$x \approx -0.003235904357553754$$
Comment: Thanks Moo. I put that into Python and the answer matches my work in Excel.
Comment: Excellent to hear that! Great job.
Answer: The first step is to ignore the $252$, converting the equation to
$$(1.08107)^{98}=(1.08804+x)^{23}(1.08804+2x)^{37}(1.08804+3x)^{38}$$
(that is, raise both sides to the $252$th power). Now, since $98=23+37+38$, we can move the left hand side to the right, giving
$$1=\left(1.08804+x\over1.08107\right)^{23}\left(1.08804+2x\over1.08107\right)^{37}\left(1.08804+3x\over1.08107\right)^{38}$$
Noting $1.08804=1.08107+0.00697$ and taking logs, we have
$$\begin{align}
0&=23\ln\left(1+{x+0.00697\over1.08107}\right)+37\ln\left(1+{2x+0.00697\over1.08107}\right)+38\ln\left(1+{2x+0.00697\over1.08107}\right)\\
&\approx23\cdot{x+0.00697\over1.08107}+37\cdot{2x+0.00697\over1.08107}+38\cdot{3x+0.00697\over1.08107}\\
&={(23+74+114)x+98\cdot0.00697\over1.08107}\\
&={211x+0.68306\over1.08107}\\
&\implies x\approx-0.68306/211=0.00323725\ldots
\end{align}$$
This gets us in the ballpark of the asserted result. In fact, the true answer is somewhere between $0-.00323$ and $-0.003237$: The right hand side of the first equation is larger than $(1.081076)^{98}$ for $x=-0.00323$ and smaller for $x=-0.003237$.
The key here is the approximation $\ln(1+u)\approx u$ if $|u|$ is small, which turns out to be the case. One could get a better approximation using $\ln(1+u)\approx u-{1\over2}u^2$, but that would lead to a messy quadratic equation to solve for $x$.
Comment: Nice approach + 1

Solve for $x$ with exponents


Remove javascript console sentences from source using gsub

Question: Im noob in ruby and i coding a simple rakefile ...
one of my task remove from javascript files the "console" lines, what do you thing about the current snippet?
def self.remove_debug()
  FileList[File.join(DIST_DIR, '**/console-nodebug.js')].each do |file_name|
    puts "file: #{file_name}"
    content = File.read(file_name).gsub(/console\..*?;/m, "// console removed")
    File.open(file_name, 'wb') { |file| file.write(content) }
  end
end

its fine?? i need to change something?
i test the code and all goes fine, but ... im looking for good practices ...
thks!
Comment: yup, i looking for opinions, good practices, ideas ...
Answer: I would recommend having a debug variable and have ruby initialize that variable (I really don't know much about ruby, I leave this to you, I guess something like injecting it in the html file). And then in you js file you may do like this:
if (debug) {
  console.log("I'm debugging! Yay!! XD");
}

In my humble opinion this is better than modifying the file.
Hope it helped, good luck!
==EDIT==
If it's a minified file that you need to shrink I would suggest replacing your regex bu "/* console removed */" instead of "// console removed", just in case that there is some more code after that line.
Other than that I think you will be ok. Is it working?
Comment: yup, im in that way ... but im working for a lazy javascript minified file to my productive environment ... debug traces === kb ... cos' im removing lines in the productive build phase ... thks !
Comment: only one thing ... if u forget in "console" statement the final ";", gsub destroy all code until found ";" character. But in my case i had a pre-task to perform jlint check over the code xD
Comment: Then maybe you should check for the closed ')' that is not quoted and matches the oppening ')' of the console... hehehe, maybe is too much work if you already check it with jslint ^.^, I'm glad it's working!


Workaround jarring menu-in-toolbar style in WPF

Question: I've troubles getting to play a <Menu/> within a <Toolbar/> to play nice. My Example, as follows is placed in an empty window in a default WpfApplication project template from VS2010:
<DockPanel>
    <ToolBar DockPanel.Dock="Top">
        <Button Content="Button 1"/>
        <Button Content="Button 2"/>
        <Separator/>
        <CheckBox Content="CheckBox 1"/>
        <CheckBox Content="CheckBox 2"/>
        <Separator/>
        <Menu>
            <MenuItem Header="Menu">
                <MenuItem Header="File">
                    <MenuItem Header="Copy"/>
                    <MenuItem Header="Paste"/>
                </MenuItem>
            </MenuItem>
        </Menu>
    </ToolBar>
    <Menu DockPanel.Dock="Top">
        <MenuItem Header="Menu">
            <MenuItem Header="File">
                <MenuItem Header="Copy"/>
                <MenuItem Header="Paste"/>
            </MenuItem>
        </MenuItem>
    </Menu>
    <Grid>

    </Grid>
</DockPanel>

The default style mis-aligns both the label and the hover-indicator:

I'm no designer, nor a WPF-guru, so my simple attempts at getting the menu's style closer to the buttons have failed catastrophically.
Has anybody a simple (ideally based on Toolbar.MenuStyleKey) Style to get the Menu back in line?
Answer: Here is a quick thing that seemed to work in KaXaml:
    <ToolBar DockPanel.Dock="Top">
        <Button Content="Button 1"/>
        <Button Content="Button 2"/>
        <Separator/>
        <CheckBox Content="CheckBox 1"/>
        <CheckBox Content="CheckBox 2"/>
        <Separator/>
        <Menu Margin="0, -1, 0, 0" Style="{x:Null}">
            <MenuItem Header="Menu">
                <MenuItem Header="File">
                    <MenuItem Header="Copy"/>
                    <MenuItem Header="Paste"/>
                </MenuItem>
            </MenuItem>
        </Menu>
    </ToolBar>

Comment: P.S: This approach doesn't work when the Menu is applied as DataTemplate. I've now set a different margin and a transparent background which is still not perfect, but still looks better than the default.


Key of a Song in Modes

Question: If I'm playing a song in Dorian D would I say that the song is in the key of C?
Or is the song in the key of D, cause that my true tonic?
I guess the question can be boiled down to, is the tonic the same as the key?
So if Dorian D is in the Key of D, would I say, this song is in the Key of D in Dorian? Or just, this song is in the Key of D(if I say this i suspect they will assume I'm saying major)?
Comment: I've just been looking at the same issue. The Dorian tune I'm looking at is written in key of Dm, which seems strange because all the Bb's are turned into B naturals. So why bother with a Bb in the key signature at all, just have the same key signature as as C major. But as explained above that's just not the way it's done.
Answer: You'd say it's in D Dorian, rather than Dorian D.Like you say C major rather than major C. But be careful, as there are two ways to describe it. The Dorian of D is different from D Dorian. The former has 2 sharps, because it's the mode of D that centres around E, whereas the latter uses C major notes, but is centred around D. I've heard both used, and it can get confusing at a jam session, believe me!
Also, I think you'd write the key signature of the parent key, otherwise if you write a D key sig. with its two sharps, to show a kind of D-ness, there'll be a lot of accidentals on the way! You could write it out with a D minor key sig., as it's a minor mode, and then you'd only have the B/Bb to change.
Comment: I don't want to cause a little bit of conflict. However, I'm already confused so I need to address it. Your answer and Dom's answer seem to say contrary things. Or am I just really really confused? (BTW re: D Dorian vs Dorian D, thanks, that makes sense, I'll be careful with that)
Comment: Where is the conflict? Dom knows his stuff so what have he and I said that are not the same?
Comment: Dom said the key would be written in D, you are saying the key would be written in C major
Comment: @JohnandLynHenry I'm saying you _could_ write it in C, but it's very rare to see it that way.  Most of the time you'll use D minor instead.
Answer: First off, the key of D is ambiguous. A key represents a tonal center and expected harmony with the the normal two being major and minor. Just saying key of D you aren't specifying if it is major or minor.
Again modes are not tonal and the idea of a key is so not everything translates 100% between tonal and modal ideas. You could say the key is D Dorian which has the same key signature as C major and A minor, but rarely is that ever done in print. The more natural route especially in notation is to say if it's a major mode say it's in D major and use that key signature or if it's a minor mode to say it's in D minor and use that key signature. This seems counter intuitive, but it stresses the tonic and gives a pretty close harmony that is typically just off by one accidental in the key signature. So for D Dorian you would notate the key signature as D minor, but you would write in naturals for all of your B notes to make them natural.
A good example of this in the wild is Led Zepplin's Good Times Bad Times which is almost always written with a key signature of  E major, but it's pretty obvious that it is in E Mixolydian with it constantly during the verse going from E to D back to E.
Comment: that is really not intuitive.
Comment: @JohnandLynHenry most people don't think in mode, but in major or minor. As such it makes sense to use a major or minor key signature to denote it.
Comment: that is really not intuitive. It doesn't seem like that could be correct, cause that would mean, if i wrote something in D Locrian it would have that sound, but the key would be D Major. This means that the scale Locrian is derived from, E flat would be the true major scale from which the song is written, but the notation would use D major. The issue with this, is they are very very different(you'd have accidents everywhere)
Comment: If people don't think in modes, then in the example you gave for Zepplin, it would make more sense that the song be notated in the key of A major
Comment: No, because the tonic is E Good Times Bad Times so if the key signature is A major that can confuse basic readers. Locrian is not a major mode and is diminished so is an oddball and most likely would not use the term key when talking about it. You only do what I said if it's a major or minor mode. When you say key of D Dorian you are trying to fit a modal idea into a tonal idea which doesn't make sense most of the time hence why talking about it in terms of major and minor is more natural to most.
Comment: sorry, just one more question on this. So if I wrote in D Dorian then it will be written as D minor cause it's a minor chord. So when this would be written it would be in the key of D minor. So the reader wouldn't expect to see C major chord or G major chord, but there is a good change one or both will be in the song. So it would be up to the reader to understand modes are being used. It seems like a serious shortfall in notation
Comment: @JohnandLynHenry again, modes are not tonal. A key signature is not a strict set of notes there are notes used outside the key signature all the time. Key signatures were designed with tonal ideas in mind so if you tried to use the key of C major to write D dorian,  most people will default to thinking C or A is the tonic rather than D. If you use D minor and put naturals for the B, people will know the tonic is D and still understand the ideas of the harmony used. It won't really matter that you never use Bb and use B instead as there are other ideas that go along with the key signature.
Comment: Thanks Dom, I can see what you meant yesterday when you said the tonic doesn't translate in modes

Key of a Song in Modes


Where dinâmico Linq to SQL

Question: Preciso montar uma cláusula where com o campo e o valor dinâmico, por exemplo, em SQL puro seria:
WHERE :CAMPO = :VALOR

Porém, vasculhando as pesquisas não consegui encontrar nada em específico, já estou realizando consultas no banco de dados com um uma cláusula where fixa sem problemas. Não consigo alterar dinamicamente, o meu trecho de código está da seguinte maneira:
string campo = "NOME";
string valor = "JOAO";

listEmpresa = db.EMPRESA.Where(...).ToList();

Answer: Eu estou trabalhando com isso atualmente, e recomendo utilizar System.Linq.Expressions.Expression, Lambda e um pouco de Reflection para isso.
Exemplo:
string campo = "Campo";
string valor = "valor";

// recupera o objeto IQueryable da Context do EF
IQueryable<Empresa> query = db.EMPRESA;
// cria alias do objecto Lambda
ParameterExpression param = Expression.Parameter(typeof(Empresa), "x");
// obtem tipo da propriedade
Type type = typeof(Empresa).GetProperty(campo).PropertyType;
// cria Expression para o campo
MemberExpression propertyExpression = Expression.PropertyOrField(param, campo);
// cria Expression para o valor
ConstantExpression valueExpression = Expression.Constant(Convert.ChangeType(valor, type), type);

EXEMPLO Equals
// cria predicate Lambda Expression
var predicate = Expression.Lambda<Func<Empresa, bool>>(
    // aplica tipo de Filtro, no caso do exemplo Equal (campo == valor)
    Expression.Equal(propertyExpression, valueExpression)
, param);

EXEMPLO Contains (LIKE)
MethodInfo methodInfo = type.GetMethod("Contains", new[] { type });
var predicate = Expression.Lambda<Func<Empresa, bool>>(
    // aplica tipo de Filtro, no caso do exemplo Contains (LIKE campo '%valor%')
    Expression.Call(propertyExpression, methodInfo, valueExpression)
, param);

Continuação código...
// adiciona predicate ao where da query
query = query.Where(predicate);
// executa a consulta no banco de dados
var result = query.ToList();

Fonte: Use string as field name in LINQ
Comment: muito obrigado, Fernando!
Comment: @AndreR só pra constar: você só pode escolher uma resposta como correta.
Answer: Como você quer tudo dinâmico, existe o ótimo pacote System.Linq.Dynamic que faz isto por você. Aí com ele seria:
listEmpresa = db.EMPRESA.Where(campo + "==@0", valor).ToList();

Comment: @ThiagoLunardi Acho que ele quer montar tudo dinâmico, aí tem que ser pelo System.Linq.Dynamic mesmo.
Comment: @Fernando A parametrização é feita através de `SqlParameters`. No mais, o tratamento das variáveis deve receber alguma atenção do programador.
Comment: mas no caso, o e.Nome seria dinamico, e o valor "JOAO" também, eu precisaria passar o nome das variáveis no caso...
Comment: Atualizei a resposta.
Comment: Ah! Eu tinha editado para passar `"JOAO"` em uma variável, mas não deu tempo... rs
Comment: @AndreR, vc pode fazer assim:
`var nomeParaPesquisar = "JOAO";`
`listEmpresa = db.EMPRESA.Where(e => e.Nome == nomeParaPesquisar).ToList();`
Comment: @ThiagoLunardi Parece que ele precisa passar o **campo** dinamicamente também.
Comment: obrigado Cigano, consegui resolver o problema, abraços!
Comment: @CiganoMorrisonMendez, esse `Where` dinâmico tem algum risco de permitir SQL Injection (no caso no nome do campo, já que o valor ta parametrizado)? Ou o ORM já se previne de alguma forma em relação a isso?
Answer: Você pode também estender o System.Linq adicionando um WhereIf. Eu usei uma vez, e funciona bacaninha.
Primeiro adicionar a extenção no seu projeto:
public static class LinqExtensions
{
    public static IQueryable<TSource> WhereIf<TSource>(
        this IQueryable<TSource> source, bool condition,
        Expression<Func<TSource, bool>> predicate)
    {
        if (!condition) return source;
        return source.Where(predicate);
    }
}

Depois usa com sabedoria:
// a clausula WHERE somente será aplicado se variável 'condicao' for true
var resultado = MeusDados
                    .WhereIf(condicao == true, dado => dado.campo == "valor")
                    .ToList();

UPDATE:
Exemplo de aplicação:
[HttpGet]
public async Task<IEnumerable<pessoa>> BuscarPessoas(string nome, int idade, DateTime dataNascimento)
{
    var pessoas = await Task.FromResult(_contexto.Pessoas
                      .WhereIf(!string.IsNullOrEmpty(nome), p => p.Nome.Contains(nome))
                      .WhereIf(idade > 0, p => p.Idade == idade)
                      .WhereIf(dataNascimento != null, p => p.DataNascimento = dataNascimento)
                      .ToList();
    return pessoas;
}

Comment: Eu não quero parecer chato. Mas não consigo ver como, usando esta solução, o campo do where seria passado dinamicamente.
Comment: muito obrigado de qualquer forma Thiago, abraço!
Comment: Tem razão @jbueno , literalmente, não seria. Mandei pq eu jamais faria algo do tipo, pois acho que é inseguro, pois aceitaria **SQL Injection**, sei lá. Eu faria o seguinte, no front escolhe por qual campo vai filtrar no back faria um WhereIf para cara campo possível.
Comment: Mas acredite, é uma maneira bem legal de lidar. Eu gosto, acho super limpo, e é rápido. :)
Comment: @ThiagoLunardi, eu tentei entender como esse `WhereIf` pode ajudar no problema da pergunta e não encontrei relação. Pode tentar editar para ser mais claro com sua resposta e como ela ajuda a resolver o problema da pergunta? Pois da forma que está não vejo muita vantagem em utiliza-la ao invés do `Where` normal!
Comment: @Fernando, adicionei um exemplo de aplicação. Veja se atende, pf?
Comment: @ThiagoLunardi, o que não vejo na sua solução é como utilizar o nome da coluna/propriedade dinâmico, apartir de uma string, que é o problema relatado na pergunta?
Comment: @Fernando, Linq é fortemente tipado. LambdaExpression trabalha apenas com predicados. Então, sem usar *workarounds* não é possível.
Comment: @ThiagoLunardi, então sua resposta não responde a pergunta, pois a principal questão da pergunta é como criar consultas com campo dinâmico. Concordo que é uma boa solução para validar registros antes de adiciona-los no `Where`. Mas no meu entendimento não tem real relação com a pergunta (posso estar errado =D). E no caso a pergunta quer realmente uma forma alternativa (_workarounds_), e a sua extensão também já é uma forma alternativa. =/

Where dinâmico Linq to SQL


Posso ter procedures com o mesmo nome e quantidade de parâmetros num mesmo package (ORACLE)?

Question: Posso ter um package com duas procedures de mesmo nome, quantidade e tipo de parâmetros apenas diversificando o nome dos parâmetros?
Comment: Qual o sentido disso? O que vai mudar nelas além do nome dos parâmetros? Elas vão executar a mesma ação?
Comment: @Laerte, um sistema no qual estou dando manutenção está gerando um erro genérico o suficiente para não ajudar em nada. Creio que a causa do erro seja a tentativa de execução de uma procedure no cenário descrito. Obviamente não executam a mesma ação.
Answer: Sim, é possível criar uma ou mais procedures, functions, etc... no mesmo escopo(Ex. package) tanto com a diferentes ou iguais quantidades de parâmetros, nomes e tipos.
O compilador irá chamar o subprograma na qual os parâmetros passados se identificam, tanto em quantidade ou tipo de valor, caso o tipo de um parâmetro não coincida com a declaração um erro será retornado.
Leia sobre este tema nas documentações da oracle:
Overloading Packaged Subprograms
Overloading Subprogram Names


Unable to understand the a question from solved exercise. Please Help.

Question: I am unable to understand how the writer has derived the value of "a" in part a, and P.M.F in part "b" in the following question of "Introduction to Probability by Bertsekas":

I am completely clueless about the part "a", regarding part "b", I feel only one value of "z" satisfies the condition x^2=z, that is when x, and z both are 1, why the author has written probability z/28 + z/28?
Please elaborate both parts, thank you!
Comment: Let for example $z=4$. There are two values of $x$ such that $x^2=4$, $x=-2$ and $x=2$. The probability that $X=-2$ is $\frac{4}{28}$, as is the probability that $X=2$, for a total probability of $\frac{4}{28}+\frac{4}{28}$, that is, $2\cdot \frac{z}{28}$.
Answer: We want that $\sum\limits_{x\in \Omega}p_X(x)=1$, otherwise it contradicts the definition of a probability distribution function.
You have the only terms with nonzero $p_X(x)$ are those $x\in \{-3,-2,-1,1,2,3\}$ (as per the definition of the specific $p$)
The total will be:
$\sum\limits_{x\in\Omega} p_X(x) = \frac{(-3)^2}{a}+\frac{(-2)^2}{a}+\frac{(-1)^2}{a}+\frac{(1)^2}{a}+\frac{(2)^2}{a}+\frac{(3)^2}{a} = \frac{9+4+1+1+4+9}{a}=\frac{28}{a}$
Remembering that we wanted $a$ to be picked so that $\sum\limits_{x\in\Omega} p_X(x)=1$, that implies that $a$ must be $28$.
For calculating $E[X]$, it is $\sum\limits_{x\in \Omega} xp_X(x)$, which in this case is equal to:
$E[X] = (-3)\cdot \frac{(-3)^2}{28} + (-2)\cdot \frac{(-2)^2}{28}+(-1)\cdot \frac{(-1)^2}{28}+0+1\cdot\frac{1^2}{28}+2\cdot\frac{2^2}{28}+3\cdot\frac{3^2}{28} = 0$


How to plot multiple classifiers' ROC curves using scikitplot?

Question: I have classified a data with multiple classes (not binary) by using several classifiers, and I would like to compare the performance of these classifiers by drawing their ROC curves using scikitplot.
The code below produces the ROC curves for each model separately, I would like to get them on the same figure and keep using scikitplot.
Any suggestions would be highly appreciated!
from sklearn.pipeline import make_pipeline
import matplotlib.pyplot as plt
import scikitplot as skplt
import matplotlib.pyplot as plt
from matplotlib.pyplot import *
fig = plt.figure()
for i in range(0,6):
    num+=1
    predicted_probas = model[i].predict_proba(X_test)
    skplt.metrics.plot_roc(y_test, predicted_probas, plot_micro=False, plot_macro=False, classes_to_plot=1)
    plt.title('ROC Curve of '+model_name[i])
    plt.show()

Comment: have you tried indenting the last code line 'plt.show' (to the left)?
Comment: Yes, but that doesn't plot them in a one figure!
Answer: In version 0.22, scikit-learn introduced the plot_roc_curve function and a new plotting API (release highlights)
This is the example they provide to add multiple plots in the same figure.
svc = SVC(random_state=42)
svc.fit(X_train, y_train)
rfc = RandomForestClassifier(random_state=42)
rfc.fit(X_train, y_train)

svc_disp = plot_roc_curve(svc, X_test, y_test)
rfc_disp = plot_roc_curve(rfc, X_test, y_test, ax=svc_disp.ax_)
rfc_disp.figure_.suptitle("ROC curve comparison")

plt.show()

I hope that helps


Why does SPF_Not_Pass reject on "neutral" result?

Question: I have troubles understanding the default HELO checking policy of policyd-spf. RFC 4408 states in section 2.5.2, that

A "Neutral" result MUST be treated exactly like the "None" result

But the man page of policyd-spf defines SPF_Not_pass as follows:

SPF_Not_Pass (default) - Reject if result not Pass, None, or Temperror
         (alternatively put, reject if the SPF result is Fail, Softfail,
         Neutral, PermError). Unlike Mail From checking, there are no standard
         e-mail use cases where a HELO check should not Pass if there is an SPF
         record for the HELO name (transparent forwarding, for example, is not
         an issue). Technically this option is not fully RFC 4408 compliant
         since the SPF check for the Mail From identity is mandatory and Neutral
         and None results must be treated the same.  HELO/EHLO is known first in
         the SMTP dialogue and there is no practical reason to waste resources
         on Mail From checks if the HELO check will already cause the message to
         be rejected. These deviations should not cause interoperability
         problems when used for HELO.

This description explains why it is ok to omit the SPF check of the Mail From identity but does not answer the question: Why is Neutral rejected?
Answer: I'm not sure what answer you'd like.  Neutral is rejected because that's what the daemon says it's going to do, if you invoke that configuration option.  It notes, as you've highlighted, that this is not RFC-compliant.  But here's the rub: you are not obligated to accept any particular email at your server.  There is no Central Internet Court where, beneath a stern portrait of Jon Postel, a bench of nanae veterans rule on whether a particular server operator wrongly rejected an email.
The RFCs are technically binding, but not operationally so; the more you violate them, the more you'll fail to properly communicate with others - but you're free to do that if that's what you want to do.  You can choose to configure your server to reject emails that have an SPF neutral result, or are over 750 kB in length, or that have more than one e in the header-From address, or that fail to contain the phrase squeamish ossifrage.  It's your server; you can accept what you like.
Edit: some admins around these parts consider SPF records that don't end in -all to be an active sign of a spammer, and penalise or reject mail from such domains; I mention this to illustrate that how people use SPF-derived information varies a great deal from admin to admin.
Presumably, the authors of policyd-spf felt that rejecting Neutral mail led to better outcomes (less spam, more ham) than not doing so.  But that's speculation on my part; only they can say for sure.
Comment: I do understand that I can decide which mail to accept or not. But I don't understand the reasoning behind this default setting. For example: A client of ours has an SPF record `v=spf1 mx ?all` and some mails originate from a server that is not MX for that domain - which results in a neutral SPF result. Now I changed the policy to `Softfail` because I _do_ want to accept those mails.
But why is policyd-spf designed to reject on Neutral SPF result by default? Isn't that quite pessimistic?
Comment: See edit above.


Como alterar atributos de componentes entre Forms?

Question: Tenho uma aplicação em C# com um Form pai (FRM_PRINCIPAL) que contém um botão (BTN_ACT) que chama um Form filho (Form2), que por sua vez contém um botão (BTN_REG) contendo algumas funções, entre elas uma seria tornar o BTN_ACT em invisível (BTN_ACT.Visible=False;). Como eu faria isso?
Simplificando: Basicamente tornar o botão do primeiro Form em invisível através do botão de um segundo Form.
Answer: No seu FRM_PRINCIPAL, você precisa criar um método público para definir a visibilidade do seu botão.
public void AlteraVisibilidadeBtnAct(bool visivel)
{
    this.BTN_ACT.Visible = visivel;
}

No método click do seu botão BTN_REG, você chama o método criado acima da seguinte forma, se o Form2 for filho do seu FRM_PRINCIPAL. Um form é filho do outro quando a propriedade MdiParent é definida para o filho.
private void BTN_REG_Click(object sender, System.EventArgs e)
{
    ParentForm.AlteraVisibilidadeBtnAct(false);
}

Se o Form2 não for filho do FRM_PRINCIPAL, você deve adicionar o FRM_PRINCIPAL no construtor do Form2, para depois acessá-lo no evento click.
private FRM_PRINCIPAL frmPrincipal;

public Form2(FRM_PRINCIPAL frmPrincipal)
{
    this.frmPrincipal = frmPrincipal;
}

private void BTN_REG_Click(object sender, System.EventArgs e)
{
    frmPrincipal.AlteraVisibilidadeBtnAct(false);
}

Comment: Obrigado Bernardo! O código que estou compilando que aparentemente se encaixa em meu caso é o que você disse "Se o Form2 não for filho do FRM_PRINCIPAL...". Porém estou recebendo "An unhandled exception of type 'System.NullReferenceException' occurred in...". Este erro está acontecendo na linha frmPrincipal.AlteraVisibilidadeBtnAct(false); no meu Form2.
Comment: Você precisa passar como parâmetro o FRM_PRINCIPAL para o Form2, na linha onde o Form2 é criado. O código ficaria algo assim: Form2 form2 = new Form2(this), se você estiver criando o Form2 dentro da classe FRM_PRINCIPAL.
Comment: Muito obrigado, funcionou perfeitamente!


Annoying unnecessary overflow and margin-top/bottom doesn't work

Question: I've been working on  a personal website for a class project. I've come across some bugs in it that I can't seem to get fixed. You can find the website at bnb.im or at CodePen (the codepen is mostly copy and paste; I did the best I could with it).
So, the first problem is the white space to the right of the screen. I can't tell what's causing it--when I use the Select element feature on FF, it just selects . I asked on another site, and someone said that it was caused by the animation of the portfolio items sliding in--I tried the fix they suggested, adding overflow: hidden; to body, but it didn't work (the page became unscrollable). I also tried making the portfolio items smaller (45% instead of 50%), but that didn't help, either. Any ideas?
The second problem is with the portfolio items and/or the social section. Whenever I try to add margin-top or margin-bottom to put some white space between the last portfolio item and the social section, nothing happens for the most part. The only time I've gotten it to work is when I put the margin-top on the social section to 200%, but it was too much so that won't work. Any ideas with this one?
Thanks a lot--I really appreciate you taking the time to read through this and (hopefully!) look at my site.
Answer: The first problem looks fixed to me? Did you figure it out?
The second one take off height:100%;from .portfolio
Comment: Great - so sorted? If my help answered your question, could you mark this question answered? Happy coding!
Comment: My previous comment disappeared. Maybe I closed the tab or something. Anyway, the first problem you've got to scroll right to see the whitespace. You can use middle click and move your cursor right or drag the scrollbar at the bottom of the screen. It's still there for me. Removing `height: 100%;` fixed the second one, though. Thanks!
Comment: Ah yes I see, add `overflow: hidden;` to `html` - should fix it uo
Comment: Doing that completely nullifies the ability to scroll on FF, unless you middle click. I just remembered that there are `overflow-y` and `overflow-x` properties--using `overflow-x: hidden;` does the job on Firefox.


Firebase query isn't working

Question: I am trying to check if a username is already taken.
My Database looks like that:

That is the query I try to use:
var returning = true
        print("test101")

        ref.child("users")
            .queryOrderedByChild("name")
            .observeEventType(.ChildAdded, withBlock: { snapshot in

                print("test102")
                if let nname = snapshot.value!["name"] as? String{
                    if self.nicknameTextField.text! == nname{
                        returning = false
                    }
                    print(returning)

                }
            })

My problem is that the Compiler doesn't go into the nested function and I don't understand why?
The Console prints "test101" but not "test102"
Comment: Sounds like a permission issue. Try setting  `FIRDatabase.setLoggingEnabled(true)` and se what it says
Comment: Good call @Chris. If that is the case, have a look at the first blue box on the  [page about reading data](https://firebase.google.com/docs/database/ios/retrieve-data).
Answer: Don't forget:

To read or write data from the database, you need an instance of FIRDatabaseReference:

var ref: DatabaseReference!
ref = Database.database().reference()

Comment: Of course I have this statement. This wasn't my question

Firebase query isn't working


Practical usage of the bias variance tradeoff

Question: I understand the bias-variance tradeoff. But, I have never come across a scenario where that has changed anything in the modelling process. Is there any practical scenario that you have encountered where you dug into the bias and the variance tradeoff and the way you proceeded with the modeling changed because of that?
I have been through scenarios where I have had models that had pretty different performances on different validation sets (in cross-validation) and then I reduced the model complexity as a consequence of that but that is just dealing with the observation that "maybe the model is too complex". But, I have not had any scenario where the tradeoff between bias or variance or that knowledge came in handy and led to an actual action.
Comment: The main motivation for *tuning* a model is to find a good bias-variance tradeoff. This obviously has a direct impact on the final model, even if you do not explicitly quantify the bias and the variance.
Comment: "I have had pretty different performances on different validation sets... and then I reduced the model complexity". That basically *is* the bias-variance tradeoff. You found an overfit model with low bias but high variance, and based on that observation, decided to use a less overfit model that probably performed worse on the training data (higher bias) but better on the test data (lower variance). Anytime you're evaluating train/test performance, you are implicitly evaluating model bias/variance.
Comment: The bias variance tradeoff is the sea in which model selection swims.  Any time you choose a model, whether it's the type of model (tree? OLS? MARS?), the number of variables, the types of transformation etc., you are using the bias variance tradeoff.
Comment: [It might be helpful not to think of it as a "tradeoff". To me, such a term implies that the mean squared error is held constant while the bias and variance change, when the goal of, say, regularization, is to increase the bias only a little bit so that the large reduction in variance leads to a smaller, not equal, mean squared error.](https://stats.stackexchange.com/a/611164/247274)
Comment: https://stats.stackexchange.com/questions/491501/is-the-idea-of-a-bias-variance-tradeoff-a-false-construct?rq=1
Answer: "Although the bias-variance decomposition may provide some interesting insights into the model complexity issue from a frequentist perspective, it is of limited practical value, because the bias-variance decomposition is based on averages
with respect to ensembles of data sets, whereas in practice we have only the single
observed data set. If we had a large number of independent training sets of a given
size, we would be better off combining them into a single large training set, which
of course would reduce the level of over-fitting for a given model complexity." - Pattern Recognition and Machine Learning (Bishop).


Need to execute a curl statement in OCP Cron

Question: I am very new with working on OCP . I have a task to schedule a curl statement via crontab but I'm unable to figure out where to pass the curl statement.
Not sure how to even start. I looked up some examples but do not see anything that matches my requirement
Answer: OCP is based on Kubernetes. In Kubernetes you have the CronJob resource, which seems to be what you're looking for for your resource and allows you to run a job on a specific schedule.
As you need to use curl, you can use the curlimage/curl image, which has the curl binary included:
<code>apiVersion: batch/v1
kind: CronJob
metadata:
  name: my-curl-job
spec:
  schedule: "* * * * *"
  jobTemplate:
    spec:
      template:
        spec:
          containers:
          - name: curl-job
            image: curlimages/curl
            imagePullPolicy: IfNotPresent
            args:
            - "http://your.url.you.want.to.curl"
          restartPolicy: Never
</code>


Load the value of an entity field type in another form

Question: I have created a custom field and I wish to load the value dynamically in another form in relation to the specific node entity the value belongs to.
I understand that to get the value I have to use/know the field_name like this
<code>$entity->get('field_name')->getValue();
</code>
What I want is to get the field_name set via content configurations with only the type of node and the field name as defined in the fieldItem Plugin
<code>$field_definitions = \Drupal::service('entity_field.manager')->getFieldStorageDefinitions('node');
</code>
When I dump $field_definitions am able to see all the fields array with all the details but I can't get my node.field_name in relation to the fieldItem name defined in the specific field plugin, in my case field_custom_example
<code>/**
 * Plugin implementation of the 'field_custom_example' field type.
 *
 * @FieldType(
 *   id = "field_custom_example",
 *   label = @Translation("Custom Example"),
 *   description = @Translation("Stores data for Custom Example Field"),
 *   default_widget = "custom_example_widget",
 *   default_formatter = "custome_example_formatter"
 * )
 */
</code>
that's where am stuck.
Answer: Use the method FieldDefinitionInterface::getType:

Returns the field type.
Return value
(string) The field type, i.e. the id of a field type
  plugin. For example 'text'.

In your case for example:
<code>foreach ($field_definitions as $name => $definition) {
  if ($definition->getType() == 'field_custom_example') {
    // found field $name
  }
}
</code>
Comment: thanks alot for pointing me that way..I could upvote the answer..but unfortunately am not qualified yet..am grateful.


class "org.bouncycastle.asn1.ASN1ObjectIdentifier"'s signer information does not match signer information of other classes in the same package

Question: Can someone help me with this exception?  Does this mean that I have to run keytool with the java version of 1.5?
I had it working before, but now I get this.
<code>Exception in thread "main" java.lang.ExceptionInInitializerError
at com.itextpdf.text.pdf.security.CertificateInfo.getSubjectFields(CertificateInfo.java:356)
at com.itextpdf.text.pdf.PdfSignatureAppearance.getAppearance(PdfSignatureAppearance.java:884)
at com.itextpdf.text.pdf.PdfSignatureAppearance.preClose(PdfSignatureAppearance.java:1268)
at com.itextpdf.text.pdf.security.MakeSignature.signDetached(MakeSignature.java:140)
at org.deloitte.cms.efi.controller.signature.SignatureAppearance.sign4(SignatureAppearance.java:181)
at org.deloitte.cms.efi.controller.signature.SignatureAppearance.main(SignatureAppearance.java:208)
</code>
Caused by: java.lang.SecurityException: class "org.bouncycastle.asn1.ASN1ObjectIdentifier"'s signer information does not match signer information of other classes in the same package
This is my code:
<code>    public void sign4(String src, String name, String dest,
        Certificate[] chain, PrivateKey pk,
        String digestAlgorithm, String provider, CryptoStandard subfilter,
        String reason, String location)
                throws GeneralSecurityException, IOException, DocumentException {
    // Creating the reader and the stamper
    PdfReader reader = new PdfReader(src);
    FileOutputStream os = new FileOutputStream(dest);
    PdfStamper stamper = PdfStamper.createSignature(reader, os, '\0');
    // Creating the appearance
    PdfSignatureAppearance appearance = stamper.getSignatureAppearance();
    //appearance.setReason(reason);
    //appearance.setLocation(location);
    appearance.setVisibleSignature(name);
    // Default text and scaled background image
    appearance.setImage(Image.getInstance(IMG));
    //appearance.setImageScale(-1);
    appearance.setImageScale(0);
    // Creating the signature
    PrivateKeySignature pks = new PrivateKeySignature(pk, digestAlgorithm, provider);
    ExternalDigest digest = new BouncyCastleDigest();
    MakeSignature.signDetached(appearance, digest, pks, chain, null, null, null, 0, subfilter);
}
</code>
This is my pom.xml
<code>       <dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itextpdf</artifactId>
    <version>5.5.6</version>
   </dependency>
   <dependency>
       <groupId>org.bouncycastle</groupId>
       <artifactId>bcpkix-jdk15on</artifactId>
       <version>1.52</version>
    </dependency>
   <dependency>
       <groupId>org.bouncycastle</groupId>
       <artifactId>bcprov-jdk15on</artifactId>
       <version>1.52</version>
    </dependency>
    <dependency>
        <groupId>org.apache.santuario</groupId>
        <artifactId>xmlsec</artifactId>
        <version>2.0.4</version>
    </dependency>
</code>
Comment: This sounds like you have multiple BouncyCastle versions on your class path, not only the version you have declared as dependency.
Answer: Please check your maven dependency tree. Your pom requests bc version 1.5.2, but according to http://mvnrepository.com/artifact/com.itextpdf/itextpdf/5.5.6 , itext expects version 1.49. Remove the two bc elements from your pom.
Comment: Thanks you save my life :-)


javascript filter an array of strings, matching case insensitive substring

Question: I have an array of names filtered by a certain string. How can I match all names that include this string, but insensitive of case?
this.employeeDisplayList = this.employeeList.filter(e => e.employeeName.includes(this.searchStr));

Comment: Does this answer your question? [javascript includes() case insensitive](https://stackoverflow.com/questions/48145432/javascript-includes-case-insensitive)
Answer: this.employeeDisplayList = this.employeeList.filter(e => {
    const emp = e.employeeName.toLowerCase();
    const str = this.searchStr.toLowerCase();
    return emp.includes(str);
});

Answer: You can just apply .toLowerCase() to both the employeeName and the searchString.

let employeeDisplayList = [{employeeName: "Jules 1"}, {employeeName: "jules 2"}, {employeeName: "Max"}];

let searchStr = "Jules";

console.log(employeeDisplayList.filter(e => e.employeeName.toLowerCase().indexOf(searchStr.toLowerCase()) >= 0));

Another way would be to search with a case insensitive regex: string.match(/word/i)
Comment: Apparently I got here a minute too late XD


Module version format

Question: I would like to know what is the correct version format for custom modules in Drupal 7.
I see some contributed modules come with 7.x-1.2-rc1. I don't know what is rc1.
When I name my custom module with version 7.x, my module didn't work in module installation and it wasn't enabled. When I name the version 7.x-1.2, it works fine.
Is there any documentation for Drupal module version format?
Answer: Release naming conventions reports exactly the format used for the release names, and how they are formatted.
In short, the format is [Drupal version].x-[major version]-[minor version]-[flags].

Drupal version is the Drupal version with which the module is compatible
flags are extra identifiers that starts with one of the following string:

unstable
alpha
beta
rc [a.k.a. release candidate]

For a development snapshot, the format is [Drupal version].x-[major version]-x-dev.
"Major version" and "minor version" refer to the module version, where "minor version" is a progressive number.
As for the module not working if the release number doesn't follow the schema, I think the problem is another one; as far as I know, Drupal doesn't check the format, and the release name is only used from the update manager, when it is looking for the module updates, and the module is hosted on Drupal.org.
You should not be worried about the format used for the release version identifier, if not when you are developing a module that is host on Drupal.org. If you are developing a custom module that is not hosted there, you don't need to report the module version. In fact, in my test site I have a test module that doesn't report its version, and Drupal is still able to use it; the only difference is when another custom module depends from that, and it is reporting with which version of the first module is compatible. Then, Drupal will not show the module version in the module page, if the .info file doesn't report that.
Answer: The use of a version is discouraged, the value that is required is core, and you can only set it to 7.x.
See the community documentation: Writing .info files (Drupal 7.x) for more information.
For your info, "rc1" means "release candidate #1". Modules can have different version: Alpha, Beta and Release candidate.

Module version format