Evaluate $ \sum_{n=1}^{\infty} \frac{\sin \ n}{ n } $ using the fourier series

Question: I am a beginner with Fourier series and I have to evaluate the sum
$$\sum_{n  =1}^{\infty}{\sin\left(n\right) \over n}$$
I don't know which function I have to take to evaluate the fourier series ...
Someone can give me a hint ?
Thanks in advance!
Comment: possible duplicate of [Does $\sum\dfrac{\sin n}{n}$ converge?](http://math.stackexchange.com/questions/342637/does-sum-dfrac-sin-nn-converge)
Comment: @yoknapatawpha: I don't see Fourier series in the answers.
Comment: @BeniBogosel I grabbed the wrong link. It was supposed to be this one: http://math.stackexchange.com/questions/13490/proving-that-the-sequence-f-nx-sum-limits-k-1n-frac-sinkxk-is. Setting $x = 1$ gives the answer to this question.
Comment: There is something similar to your question over here   --->     http://math.stackexchange.com/a/582932/85343
Comment: $\displaystyle{\large{1 \over 2}\,\left(\pi - 1\right)}$.
Answer: $\newcommand{\+}{^{\dagger}}%
 \newcommand{\angles}[1]{\left\langle #1 \right\rangle}%
 \newcommand{\braces}[1]{\left\lbrace #1 \right\rbrace}%
 \newcommand{\bracks}[1]{\left\lbrack #1 \right\rbrack}%
 \newcommand{\ceil}[1]{\,\left\lceil #1 \right\rceil\,}%
 \newcommand{\dd}{{\rm d}}%
 \newcommand{\ds}[1]{\displaystyle{#1}}%
 \newcommand{\equalby}[1]{{#1 \atop {= \atop \vphantom{\huge A}}}}%
 \newcommand{\expo}[1]{\,{\rm e}^{#1}\,}%
 \newcommand{\fermi}{\,{\rm f}}%
 \newcommand{\floor}[1]{\,\left\lfloor #1 \right\rfloor\,}%
 \newcommand{\half}{{1 \over 2}}%
 \newcommand{\ic}{{\rm i}}%
 \newcommand{\iff}{\Longleftrightarrow}
 \newcommand{\imp}{\Longrightarrow}%
 \newcommand{\isdiv}{\,\left.\right\vert\,}%
 \newcommand{\ket}[1]{\left\vert #1\right\rangle}%
 \newcommand{\ol}[1]{\overline{#1}}%
 \newcommand{\pars}[1]{\left( #1 \right)}%
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\pp}{{\cal P}}%
 \newcommand{\root}[2][]{\,\sqrt[#1]{\,#2\,}\,}%
 \newcommand{\sech}{\,{\rm sech}}%
 \newcommand{\sgn}{\,{\rm sgn}}%
 \newcommand{\totald}[3][]{\frac{{\rm d}^{#1} #2}{{\rm d} #3^{#1}}}
 \newcommand{\ul}[1]{\underline{#1}}%
 \newcommand{\verts}[1]{\left\vert\, #1 \,\right\vert}$
$\ds{\sum_{n = 1}^{\infty}{\sin\pars{n} \over n} = \half\pars{\,\sum_{n = -\infty}^{\infty}{\sin\pars{n} \over n} - 1}.\quad}$  See $\large\tt details$
over here .

\begin{align}
\sum_{n = -\infty}^{\infty}{\sin\pars{n} \over n}&=
\int_{-\infty}^{\infty}{\sin{x} \over x}\sum_{n = -\infty}^{\infty}\expo{2n\pi x\ic}
\,\dd x
=
\int_{-\infty}^{\infty}\half\int_{-1}^{1}\expo{\ic kx}\,\dd k
\sum_{n = -\infty}^{\infty}\expo{-2n\pi x\ic}\,\dd x
\\[3mm]&=
\pi\sum_{n = -\infty}^{\infty}\int_{-1}^{1}\dd k
\int_{-\infty}^{\infty}\expo{\ic\pars{k - 2n\pi}x}\,{\dd x \over 2\pi}
=
\pi\sum_{n = -\infty}^{\infty}\int_{-1}^{1}\delta\pars{k - 2n\pi}\,\dd k
\\[3mm]&=
\pi\sum_{n = -\infty}^{\infty}\Theta\pars{{1 \over 2\pi} - \verts{n}}
= \pi\,\Theta\pars{1 \over 2\pi} = \pi
\end{align}

Then,
$$\color{#0000ff}{\large%
\sum_{n = 1}^{\infty}{\sin\pars{n} \over n} = \half\pars{\pi - 1}}
$$
Comment: For this you have to believe the computations with divergent series that physicists use.
Comment: @GEdgar  You're right. Thanks.
Answer: What is the function that has its fourier coefficients $A_n=0$ and $B_n = \frac{1}{n}$, i.e
$$
f(x) = \sum_{n=1}^{\infty} \frac{1}{n} \sin(n x)$$
Once you have figured out $f(x)$, find $f(1)$.
By the way $f(x)$ is a "standard" function in engineering analysis.
Answer: By the way, note that $\frac{\sin n}{n}$ is exactly the n-th Fourier coefficient of the function
$
 \sqrt{\frac{\pi}{2}}\chi_{[-1,1]}(x).
$
Since $\chi_{[-1,1]}(x)$ has a compact support, one can use the Poisson formula:
$$
    \sum_{n\in\mathbb{Z}} \widehat{\chi_{[-1,1]}}(n) = \sqrt{2\pi} \sum_{n \in \mathbb{Z}} \chi_{[-1,1]}(2\pi n) = \sqrt{2\pi},
$$
and get
$$
   \sum_{n\in\mathbb{Z}} \frac{\sin n}{n} = \pi.
$$
Answer: Hint: $$\sum_{n=1}^\infty \frac{\sin (n)}{n}= \text{Im }\sum_{n=1}^\infty \frac{e^{in}}{n}=\text{Im } \sum_{n=1}^\infty \int_0^1 x^{n-1} \mathrm{d} x \bigg|_{x=e^i}=\text{Im } \int_0^1 \frac{\mathrm{d} x}{1-x} \bigg|_{x=e^i}=\text{Im Log }(1-e^i) $$


Could we use extern "C" in C file without #ifdef __cplusplus?

Question: Why shouldn't extern "C" be specified for a function that needs to be defined as a C function? What effect would that have on the compiler when compiling the file as a C source?
If there is no effect on the C compiler, can't we just define a function in a header file as below by removing the #ifdef __cplusplus check?
extern "C" {
    int MyFunc();
}

An answer to another question says that the #ifdef is needed, but I don't understand why:

Regarding #2: __cplusplus will be defined for any compilation unit that is being run through the C++ compiler. Generally, that means .cpp files and any files being included by that .cpp file. The same .h (or .hh or .hpp or what-have-you) could be interpreted as C or C++ at different times, if different compilation units include them. If you want the prototypes in the .h file to refer to C symbol names, then they must have extern "C" when being interpreted as C++, and they should not have extern "C" when being interpreted as C -- hence the #ifdef __cplusplus checking.
Answer: The construct extern "C" is a C++ construct and is not recognized by a C compiler. Typically, it will issue a syntax error message.
A common trick is to define a macro, for example EXTERN_C, that would expand to different thing depending on if you compile using C or C++. For example:
In a common header file:
#ifdef __cplusplus
#define EXTERN_C extern "C" {
#define EXTERN_C_END }
#else
#define EXTERN_C
#define EXTERN_C_END
#endif

In other files:
EXTERN_C
int MyFunc(void);
EXTERN_C_END

Comment: Thanks. I didn't knew it was a C++ construct.
Answer: If you compile a source file as C, it will not recognize extern "C", and would usually result in a compilation error.
If you compile a source file as C++, it will recognize extern "C", and the correct names will be linked.
Therefore, you can only use it reliably to specify C symbol names for files you compile as C++.
If you compile sources as C and C++, or your interfaces are intended for C and C++ clients, you would need to specify this one way or another in order for your clients to get the correct symbols when linking (and so on).
Related: You are allowed to write extern "C++" - for C++ translations.


How can I recognize flooding?

Question: how can I discover if my server is performing some illegal actions, like flooding?
Comment: Technically flooding isn't illegal...just really rude. Or against your terms of service for your upstream provider.
Comment: Why was this closed? Imagine he got an email from someone stating his servers IP has been flooding that persons host - how can he check?
Answer: Packet sniffing.
Monitoring network I/O.
You don't mention platform, internet connection, etc...
Run malware scans/virus scans. Again, don't know your platform so can't recommend anything.
Check your routing/ARP tables for unusual activities. You didn't mention what kind of server it is, so can't recommend anything there...
Comment: It's Linux and Apache combination

How can I recognize flooding?


SAML SSO - received urn:oasis:names:tc:SAML:2.0:status:AuthnFailed error status on saml response from IdP

Question: Our app lies on SAML SSO 2.0 for login. We just got this error in the saml response status from the IdP and I'm not sure what this actually means and what needs to be done in order to get it fixed.
The Identity Provider our clients are using is Ping Federate and we have already configured SSO settings successfully between their IdP and our app long before.
No issue so far and now suddenly we're getting this Authentication Failed error out of nowhere while the user tries to login.
Can some one clarify what this actually means?
There hasn't been any change on the app (Service Provider) side on the SSO recently so does this mean the issue is on the IdP end?
Let me know. Thanks.
Here's the saml response (signature & client identifers changed)
<code><samlp:Response Version="2.0" ID="hbj8oC64PBip6qPoM9jrpS1OCfI" IssueInstant="2018-08-28T15:16:43.824Z" InResponseTo="_9a55c2b67dcd76cee19828ff496206a61b4c51237c" Destination="https://exampleapp.com/saml/login/callback"
    xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol">
    <saml:Issuer xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion">foobar</saml:Issuer>
    <ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
        <ds:SignedInfo>
            <ds:CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/>
            <ds:SignatureMethod Algorithm="http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"/>
            <ds:Reference URI="#hbj8oC64PBip6qPoM9jrpS1OCfI">
                <ds:Transforms>
                    <ds:Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"/>
                    <ds:Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/>
                </ds:Transforms>
                <ds:DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/>
                <ds:DigestValue>rVffko3J5H6izfHOi4m0r4vtLHVLKbZqX6VmhYW7wIw=</ds:DigestValue>
            </ds:Reference>
        </ds:SignedInfo>
        <ds:SignatureValue>
CuLJsdfsdfxc9C81bcFYtahXu98eS2izTwXUp7Hi592Qh5/b/bNgyaDjV1l3r0R4dcx+wP6IDPnqIxpk7h BezfbD8bqm1cBC3AFgLh0b9RByGto2qpxJv1HP1sMkAk03x6JPq7ec6fAFJdrkeKMq5dyl8eodjy lNu0Ql3qY3k1gIerTToQZULkAZp8WLIekPpaOKzvXotzZx3dLoprn/XA+BKZZgR8WP7jZ4t/3jJF YF1l2WjaSWOJgoz8PIjwPJZ7mvqjvYbY3u726vra3x+c0wzp+qlNZNbUzqg2CQ07RICMgHbnLKMA /PiF81helnjOCOdOTIrFmkxoiwvYz3Th6/1sLA==
        </ds:SignatureValue>
    </ds:Signature>
    <samlp:Status>
        <samlp:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Responder">
            <samlp:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:AuthnFailed"/>
        </samlp:StatusCode>
        <samlp:StatusMessage>Authentication Failed</samlp:StatusMessage>
        <samlp:StatusDetail>
            <Cause>org.sourceid.websso.profiles.idp.FailedAuthnSsoException</Cause>
        </samlp:StatusDetail>
    </samlp:Status>
</samlp:Response>
</code>
Comment: `status:Responder` suggests an issue at the IdP side. Check logs and perform common maintenance, it could be something as trivial as the database went offline etc.
Answer: Yes, the issue is on the IDP end: it was not able to authenticate the user for some reason. The logs at the IDP side should tell you (or: them) more.


Construir uma tabela na página B com dados do BD e descarregar na página A por ajax_jquery

Question: Preciso agora num arquivo b.asp, construir e popular uma tabela(html) e depois descarregar por ajax no arquivo a.asp. Assim:
Arquivo b.asp
<%@ LANGUAGE="VBSCRIPT" %>
<%
Option explicit

%>

<%

dim oPesquisa
dim rsPesquisa
dim ind_selecionado
dim origem
dim ind_internacao, ind_emergencia, ind_day_hospital
dim sXML, vetPL(1, 4)
dim cod_prestador_ts
dim ind_vinculacao
dim cod_operadora

cod_prestador_ts = Request("cod_prestador_ts")
ind_vinculacao   = Request("ind_vinculacao")
origem           = Request("origem")

'if trim(cod_prestador_ts) <> "" then
    sXML = ""
    sXML = sXML & "<?xml version=""1.0"" encoding=""ISO-8859-1"" ?>" & _
                              "<parametros>"

    sXML = sXML & "<sCodPrestadorTs>" & Request("cod_prestador_ts") & "</sCodPrestadorTs>" &_
                              "<sIndVinculacao>" & Request("ind_vinculacao") & "</sIndVinculacao>"  & _
                              "<sCodOperadora>" & Request("cod_operadora") & "</sCodOperadora>"  & _
                              "</parametros>"

    vetPL(1, 1) = "IN"
    vetPL(1, 2) = "adLongVarChar"
    vetPL(1, 3) = "p_xml_parametros"
    vetPL(1, 4) = sXML

    set rsPesquisa = rsCursorOracle( CStr(Session("ace_usuario")),_
                                 CStr(Session("ace_senha")),_
                                 CStr(Session("ace_ip")),_
                                 CStr(Session("ace_sistema")),_
                                 CStr(Session("ace_modulo")),_
                                 "prs_rcs_gestao.get_prestador_tipo", _
                                 vetPL, _
                                 false )

    if ucase(origem) = "CONSULTA" then
        Do While Not rsPesquisa.eof

            if IsNull(rsPesquisa("cod_prestador_ts")) then
                ind_selecionado = "N"
            else
                ind_selecionado = "S"
            end if

            if ind_selecionado = "S" then
                ind_internacao      = lerCampo(rsPesquisa("ind_internacao"))
                ind_emergencia      = lerCampo(rsPesquisa("ind_emergencia"))
                ind_day_hospital    = lerCampo(rsPesquisa("ind_day_hospital"))
            end if

            rsPesquisa.movenext
        loop
            '
    else
        Do While Not rsPesquisa.eof

            if IsNull(rsPesquisa("cod_prestador_ts")) then
                ind_selecionado = "N"
            else
                ind_selecionado = "S"
            end if

            ind_internacao      = lerCampo(rsPesquisa("ind_internacao"))
            ind_emergencia      = lerCampo(rsPesquisa("ind_emergencia"))
            ind_day_hospital    = lerCampo(rsPesquisa("ind_day_hospital"))

            rsPesquisa.movenext
        loop

    end if

    set oPesquisa      = nothing
    set rsPesquisa     = nothing

'end if

function lerCampo(campo)
    if isNull(campo) then
        lerCampo = ""
    else
        lerCampo = campo
    end if
end function

function verificaLeitos(internacao, emergencia, day_hospital)

    if internacao = "S" or emergencia = "S" or day_hospital = "S" then
        verificaLeitos = "S"
    else
        verificaLeitos = "N"
    end if

end function

%>

E aqui está minha função jquery/ajax e onde será descarregado essa table.
function CarregaTabela() {
       var cod_ts   = '<%= Request.QueryString("cod_prestador_ts")%>';
       var ori      = '<%= Request.QueryString("Origem")%>';
       var ind_vinc = $("#ind_vincul").val();
       var cod_oper = '<%= Request.QueryString("cod_operadora")%>';
       var ind_aut  = '<%= Request.QueryString("ind_autorizacao")%>';

       alert(ind_vinc);

        $.ajax({
            url: 'prs0061b_crossbrowser.asp?cod_prestador_ts=' + cod_ts + '&ind_vinculacao=' + ind_vinc + '&origem=' + ori + '&ind_autorizacao=' + ind_aut + '&cod_operadora_principal=' + cod_oper + '',
            type: 'POST',
            success: function (data) {

                $("divOperadora_<%=iCont %>").html(a_table);//aqui nessa posição será montada a table

            },
            error: function (error) {

                alert(3);
            }
        })
    }

A tabela terá todos os campos que vem na variável rsPesquisa, dados vindos do Oracle.
Answer: Resolvi assim no arquivo B.asp:
sRetorno = "
"
sRetorno = sRetorno & "
"
sRetorno = sRetorno & "
"
sRetorno = sRetorno & "Código	"
sRetorno = sRetorno & "Nome	"
sRetorno = sRetorno & "Principal ?	"
sRetorno = sRetorno & "Divulgação ?	"
sRetorno = sRetorno & "Validar primeira Sequência ?	"
sRetorno = sRetorno & "leitos	"
sRetorno = sRetorno & "Observação	"
sRetorno = sRetorno & "Acomodação	"
sRetorno = sRetorno & "ind_hospital_geral	"
sRetorno = sRetorno & "
"
sRetorno = sRetorno & "
"

sRetorno = sRetorno & "
"

'if trim(cod_prestador_ts) <> "" then
    sXML = ""
    sXML = sXML & "<?xml version=""1.0"" encoding=""ISO-8859-1"" ?>" & _
                              "<parametros>"

    sXML = sXML & "<sCodPrestadorTs>" & Request("cod_prestador_ts") & "</sCodPrestadorTs>" &_
                              "<sIndVinculacao>" & Request("ind_vinculacao") & "</sIndVinculacao>"  & _
                              "<sCodOperadora>" & Request("cod_operadora") & "</sCodOperadora>"  & _
                              "</parametros>"

    vetPL(1, 1) = "IN"
    vetPL(1, 2) = "adLongVarChar"
    vetPL(1, 3) = "p_xml_parametros"
    vetPL(1, 4) = sXML

    set rsPesquisa = rsCursorOracle( CStr(Session("ace_usuario")),_
                                 CStr(Session("ace_senha")),_
                                 CStr(Session("ace_ip")),_
                                 CStr(Session("ace_sistema")),_
                                 CStr(Session("ace_modulo")),_
                                 "prs_rcs_gestao.get_prestador_tipo", _
                                 vetPL, _
                                 false )

    if ucase(origem) = "CONSULTA" then
        Do While Not rsPesquisa.eof

            if IsNull(rsPesquisa("cod_prestador_ts")) then
                ind_selecionado = "N"
            else
                ind_selecionado = "S"
            end if

            if ind_selecionado = "S" then
                ind_internacao      = lerCampo(rsPesquisa("ind_internacao"))
                ind_emergencia      = lerCampo(rsPesquisa("ind_emergencia"))
                ind_day_hospital    = lerCampo(rsPesquisa("ind_day_hospital"))
            end if

                sRetorno = sRetorno & "
"
                sRetorno = sRetorno & ""&rsPesquisa("cod_tipo_prestador")&"	"
                sRetorno = sRetorno & ""&rsPesquisa("nome_tipo_prestador")&"	"
                sRetorno = sRetorno & ""&ind_selecionado&"	"
                sRetorno = sRetorno & ""&ind_selecionado&"	"
                sRetorno = sRetorno & ""&rsPesquisa("ind_principal")&"	"
                sRetorno = sRetorno & ""&rsPesquisa("ind_divulgacao")&"	"
                sRetorno = sRetorno & ""&verificaLeitos(ind_internacao, ind_emergencia, ind_day_hospital)&"	"
                sRetorno = sRetorno & ""&rsPesquisa("txt_obs_nao_divulgacao")&"	"
                sRetorno = sRetorno & ""&rsPesquisa("ind_tipo_acomodacao")&"	"

                sRetorno = sRetorno & "
"

            rsPesquisa.movenext
        loop

            sRetorno = sRetorno & "
"
            sRetorno = sRetorno & "
"
            Response.write sRetorno
    else
        Do While Not rsPesquisa.eof

            if IsNull(rsPesquisa("cod_prestador_ts")) then
                ind_selecionado = "N"
            else
                ind_selecionado = "S"
            end if

            ind_internacao      = lerCampo(rsPesquisa("ind_internacao"))
            ind_emergencia      = lerCampo(rsPesquisa("ind_emergencia"))
            ind_day_hospital    = lerCampo(rsPesquisa("ind_day_hospital"))

                sRetorno = sRetorno & "
"
                sRetorno = sRetorno & ""&rsPesquisa("cod_tipo_prestador")&"	"
                sRetorno = sRetorno & ""&rsPesquisa("nome_tipo_prestador")&"	"

                sRetorno = sRetorno & "
"

            rsPesquisa.movenext
        loop

        sRetorno = sRetorno & "
"
        sRetorno = sRetorno & "
"
        Response.write sRetorno

    end if

E no Arquivo A.asp fiz essa chamada assim:
crio a div que vai receber o resultado vindo de B.asp

Aqui eu chamo via ajax:
function CarregaTabela() {
       var cod_ts   = '<%= Request.QueryString("cod_prestador_ts")%>';
       var ori      = '<%= Request.QueryString("Origem")%>';
       var ind_vinc = $("#ind_vincul").val();
       var cod_oper = '<%= Request.QueryString("cod_operadora")%>';
       var ind_aut  = '<%= Request.QueryString("ind_autorizacao")%>';
        $.ajax({
            url: 'prs0061b_crossbrowser.asp?cod_prestador_ts=' + cod_ts + '&ind_vinculacao=' + ind_vinc + '&origem=' + ori + '&ind_autorizacao=' + ind_aut + '&cod_operadora_principal=' + cod_oper + '',
            type: 'POST',
            success: function (data) {

                $('#testeRetorno').html(data);

            },
            error: function (error) {
            }
        })
    }


Specify SQL Server connectionstring on a messed up network

Question: The current scenario before i start asking my question

A C# Winforms application needs to be deployed on our LAN.
The network contains 200+ computers running Windows XP (& above) having the same domain/workgroup.
Unfortunately, there's still some mixups and IP conflicts throughout the network.
The network still works !!... (ahem..)
A central server (with unique name & IP) hosts the database (SQL Server 2008 R2)
The application has a provision to specify the connectionstring on the client machine
The application validates this string (open > close connection else exception) and stores in a local file.

Now, My problem is that...

The application connects successfully to the server (open > close connection) during the checking phase, but fails when there's actual datasets are to be fetched from the server.

Which is the most reliable way to address the server in the connection string in this mixed up scene ?

This holds true even if i use the "sa" account, i have used machine name / IP to address the server
Comment: "there's still some mixups and IP conflicts throughout the network." - Fix Them. To do otherwise would be insane.
Comment: The server IP/Name is unique though...    (The networking guy might take time to fix up)
Comment: Can pipes / secondary routing be of any help ?
Answer: When you say your application "fails when there's actual datasets are to be fetched", what do you mean?  What's the error?  Encapsulate your SqlDataAdapter.Fill() method in a try catch block and out that error to a log or the GUI for quick debugging purposes.  What does the error say?  Is it a network or instance related issue..?
The application connects successfully to the server
Are you talking about the server as a physical machine, or are you talking about the SQL Server instance that houses the database you are trying to connect to?
Here's a big "gotcha".  If you are using a named instance, then you need to make sure that the SQL Server Browser service is running on the server that houses the SQL Server instance(s).  That is the service that, when reached out over port 1434, tells the application what dynamic port the named instance is listening to.
Also, your connection string could have some issues in it.
Long story short, it is almost impossible to tell what your problem is with the very little given information.  It is all just guessing troubleshooting here.  Please give me more information.
Edit: if you have a DHCP/DNS server on your network, then I don't see why you should be getting "messed up" workstation network issues, at least with IP assigning and name resolution.  Your workstations need to be able to resolve the server name to reach it.  But it doesn't sound like that's your issue.
Comment: "SQL Server Browser service" is now running on the Central Server.


Syntax error on inner join

Question: My tables on MySQL
Table Suppliers
---------------------------------------------------
SupplierID |    SupplierName |  ContactName Address
---------------------------------------------------

Table Products
-----------------------------------------------
ProductID | ProductName |SupplierID Unit| Price
-----------------------------------------------

The Query
SELECT Suppliers.SupplierName
       , ProductName
       , Price
FROM Products
INNER JOIN (SELECT SupplierID
                   , MAX(Price) AS maxPrice
            FROM Products
            GROUP BY SupplierID) as gp ON Products.Price = gp.maxPrice
INNER JOIN Suppliers ON Suppliers.SupplierID = Products.SupplierID;

What im trying to do is to obtain is the name of the product, the name of the supplier and their respective prices, based on the price of the most expensive product of each supplier (that's what is the subquery is extracting), but the rest of query doesn't work, not sure why
the SQL error
Syntax error (missing operator) in query expression 'Products.Price =
gp.maxPrice INNER JOIN Suppliers ON Suppliers.SupplierID =
Products.SupplierID'.

Answer: SELECT Suppliers.SupplierName,ProductName,Price
FROM Products
INNER JOIN (SELECT SupplierID,  MAX(Price) maxPrice
            FROM Products GROUP BY SupplierID) gp
ON Products.Price = gp.maxPrice and products.supplierid = gp.supplierid
INNER JOIN Suppliers ON Suppliers.SupplierID = Products.SupplierID;

You can try this. The join has also been done on supplierid for the subquery. Also make sure you include tablenames before column names in the select clause, to avoid ambiguity.
Comment: I just tried that query and this the error: "Syntax error (missing operator) in query expression ''.  "  This leaves me more confused
Comment: try this..removed `as` in the sub-query. not sure what difference it would make.
Answer: SELECT Suppliers.SupplierName,ProductName,Price FROM (Products
INNER JOIN (SELECT SupplierID,  MAX(Price) AS maxPrice FROM Products GROUP BY SupplierID) as gp ON Products.Price = gp.maxPrice)
INNER JOIN Suppliers ON Suppliers.SupplierID = Products.SupplierID;

Does it work ?
Comment: Yes!! this one displays the data i need, i'm trying to understand why the parenthese are needed thou

Syntax error on inner join


Android auto text reply using broadcast receiver sending multiple texts.

Question: The following code sends a text to the incoming calling number, however it sends a different amount of texts every time. Sometimes it only sends one, but it varies up to 6. When monitoring my code while it functions I also get different numbers of broadcasts. What am I doing wrong?
Receiver:
package com.biapps.makin_biscuits;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.PhoneStateListener;
import android.telephony.SmsManager;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.Toast;

/**
 * Created by Jake on 3/21/2016.
 */

public class IncomingCallReceiver extends BroadcastReceiver {

private static final String TAG = "MyListener";
    private Context mContext;
    private Intent mIntent;

    @Override
    public void onReceive(Context context, Intent intent) {
        mContext = context;
        mIntent = intent;
        TelephonyManager tm = (TelephonyManager)mContext.getSystemService(Context.TELEPHONY_SERVICE);
        int events = PhoneStateListener.LISTEN_CALL_STATE;

        tm.listen(phoneStateListener, events);
    }

    private final PhoneStateListener phoneStateListener = new PhoneStateListener() {
        @Override

        public void onCallStateChanged(int state, String incomingNumber) {
            super.onCallStateChanged(state, incomingNumber);

            Log.i(TAG, "number: " + incomingNumber + "");
            Toast.makeText(mContext,"Incoming Call: " + incomingNumber + "",Toast.LENGTH_LONG).show();
            switch (state) {
                case TelephonyManager.CALL_STATE_RINGING:

                        SmsManager smsManager =     SmsManager.getDefault();
                        smsManager.sendTextMessage(incomingNumber, null, "I'm busy bruh", null, null);
                    TelephonyManager tm = (TelephonyManager)mContext.getSystemService(Context.TELEPHONY_SERVICE);
                    tm.listen(phoneStateListener, PhoneStateListener.LISTEN_NONE);

            }

                   }
    };
}

Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.biapps.makin_biscuits">
    <uses-sdk android:minSdkVersion="4" />

    <uses-permission android:name="android.permission.READ_CONTACTS" />
    <uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.SEND_SMS"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity android:name=".ContactsList">
            <intent-filter>
                <category android:name="android.intent.category.ALTERNATIVE" />
            </intent-filter>
        </activity>

        <receiver
            android:name=".IncomingCallReceiver"
            android:enabled="true"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.PHONE_STATE" />
                <action android:name="android.intent.action.Trigger" />

            </intent-filter>
        </receiver>
    </application>

</manifest>

MainActivity:
package com.biapps.makin_biscuits;

import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageButton;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    //set object labels and states here
    private ImageButton icon;
    private AudioManager am;
    private ImageButton people;
    private ImageButton ring;

    @Override

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);

        icon = (ImageButton) findViewById(R.id.icon);
        icon.setOnClickListener(imgButtonHandler);
        people = (ImageButton) findViewById(R.id.people);
        //people.setOnClickListener(peopleButtonHandler);
        ring = (ImageButton) findViewById(R.id.ring);

    }

    int buttonstate = 0;
    public View.OnClickListener imgButtonHandler = new View.OnClickListener() {

        public void onClick(View v) {
            if (buttonstate == 0) {

                icon.setImageResource(R.drawable.buttonup);
                buttonstate = 1;
                am.setRingerMode(0);
                Toast.makeText(getApplicationContext(), "Go!!",
                        Toast.LENGTH_SHORT).show();

                Intent intent = new Intent();
                intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
                intent.setAction("android.intent.action.Trigger");
                sendBroadcast(intent);
            } else {

                icon.setImageResource(R.drawable.button);
                buttonstate = 0;
                am.setRingerMode(2);
                Toast.makeText(getApplicationContext(), "Come back!!",
                        Toast.LENGTH_SHORT).show();
            }
        }
    };
}

Answer: I added some code to recognize the previous state and determine whether or not to do the actions. This fixed the problem.
package com.biapps.makin_biscuits;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.PhoneStateListener;
import android.telephony.SmsManager;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.Toast;

/**
 * Created by Jake on 3/21/2016.
 */

public class IncomingCallReceiver extends BroadcastReceiver {

private static final String TAG = "MyListener";
    private Context mContext;
    private Intent mIntent;

    @Override
    public void onReceive(Context context, Intent intent) {
        mContext = context;
        mIntent = intent;
        TelephonyManager tm = (TelephonyManager)mContext.getSystemService(Context.TELEPHONY_SERVICE);
        int events = PhoneStateListener.LISTEN_CALL_STATE;

        tm.listen(phoneStateListener, events);
    }

    int previousState=TelephonyManager.CALL_STATE_OFFHOOK;
    private final PhoneStateListener phoneStateListener = new PhoneStateListener() {
        @Override

        public void onCallStateChanged(int state, String incomingNumber) {
            super.onCallStateChanged(state, incomingNumber);

            int Call_State_Ringing = TelephonyManager.CALL_STATE_RINGING;
            int Call_State_OffHook = TelephonyManager.CALL_STATE_OFFHOOK;
            if (Call_State_Ringing == state && Call_State_OffHook == previousState){
            Log.i(TAG, "number: " + incomingNumber + "");
            Toast.makeText(mContext,"Incoming Call: " + incomingNumber + "",Toast.LENGTH_LONG).show();
            switch (state) {
                case TelephonyManager.CALL_STATE_RINGING:

                        SmsManager smsManager =     SmsManager.getDefault();
                        smsManager.sendTextMessage(incomingNumber, null, "I'm busy bruh", null, null);
                    TelephonyManager tm = (TelephonyManager)mContext.getSystemService(Context.TELEPHONY_SERVICE);
                    tm.listen(phoneStateListener, PhoneStateListener.LISTEN_NONE);

            }

                   }
            previousState = state;
    }
};}

Answer: In your code:
you are registering PhoneStateListener inside onReceive(), so whenever your onReceive method invoked it will add one more PhoneStateListener to TelephonyManager. So, you have multiple listeners for the same event over the period.
What you can do is, you need to check if the listener is added before if so just skip that part.
Comment: How do I check for the listener?


How to add GIF images to Assets folder and load them in UIImageView programmatically

Question: I am trying to put my @2x and @3x GIF images into the Assets folder in Xcode. I have tried the following links but it didn't work for me.
Link 1 and Link 2.
I am currently loading the GIF files by adding them to my project bundle and accessing it using this
let bundleURL = NSBundle.mainBundle()
            .URLForResource("phone_animation", withExtension: "gif")

But I want to load them from my Assets folder. Is there a way I can do it? And how do I load them into my imageview after adding it to Assets?
Answer: According to your comment, this is the solution that you are searching:

make an extension of UIImage which uses SwiftGif:
extension UIImage {
  public class func gif(asset: String) -> UIImage? {
    if let asset = NSDataAsset(name: asset) {
       return UIImage.gif(data: asset.data)
    }
    return nil
  }
}

Then tuning @Ganesh suggestion with the extension you might do something like:
imageView.image = UIImage.gif(asset: "YOUR_GIF_NAME_FROM_ASSET")

Comment: Thanks, just what I needed. Although it is not possible to add 2x and 3x GIF in the same dataset is it?
Comment: @Amogh I guess It should be possible (I tried in my local test)
Comment: how are you doing it? I am using xcode 7.3 and I am not getting option to add another GIF to the same dataset
Comment: I am running Xcode9 and I have possibility to add 1,2,3x. Check to have selected "Individual Scales" for "Image Set/Scales"
Comment: could you please tell me the code in your Contents.json file?
Comment: {
  "images" : [
    {
      "idiom" : "universal",
      "filename" : "mygif.gif",
      "scale" : "1x"
    },
    {
      "idiom" : "universal",
      "filename" : "email@example.com",
      "scale" : "2x"
    },
    {
      "idiom" : "universal",
      "filename" : "firstname.lastname@example.com",
      "scale" : "3x"
    }
  ],
  "info" : {
    "version" : 1,
    "author" : "xcode"
  }
}
Answer: To load gif into UIImage I suggest two libraries
1) you can use this library
simply you can load it into UIImageView
let imageData = try! Data(contentsOf: Bundle.main.url(forResource: "logo-animation", withExtension: "gif")!)
let gifImage = UIImage.gif(data: data!)
imageView.image = gifImage

2) Or you can use this library
import FLAnimatedImage

then add outlet
@IBOutlet weak var fashImage: FLAnimatedImageView!

then use this code
let imageData = try! Data(contentsOf: Bundle.main.url(forResource: "logo-animation", withExtension: "gif")!)
fashImage.animatedImage = FLAnimatedImage(animatedGIFData: imageData)

Hope this will help you
Comment: give gif name directly which is in your asset
Comment: I want to load GIF from Assets folder only
Comment: @Ganesh the library seems to be not supporting asset name, only full path from bundle
Comment: @AndreaMugnaini library will support asset name check it clearly
Comment: @Ganesh I checked again, according to this: https://github.com/bahlo/SwiftGif/blob/master/SwiftGifCommon/UIImage%2BGif.swift UIImage can be initialized only from: Data, url as String, or bundleURL as String. So there is no way to use resource from *.xcassets furthermore you can try making a test project and see that you'll receive: SwiftGif: This image named "YOUR_GIF_NAME" does not exist
Comment: any solution to load gif from Assets folder to FLAnimatedImage? Data(contentsOf: Bundle.main.url(forResource: "logo-animation", withExtension: "gif") doesn't work for assets folder access


SyntaxError: Unexpected token '('

Question: I started learning jQuery and JavaScript this morning and I've run in to some issues.
I'm trying to make a extremely simple application that can count up and down. I've experimented back and forth and this is my code so far.
    $(document).ready(function() {
    function Number(startingNumber) {
        if($.type(startingNumber)=="number"){
            number = startingNumber;
        }else{
            number = 0;
        }

        inc: function(number) { //Error Here!
            this.number = this.number + number;
            updateNumberText();
        }

        dec: function(number) {
            this.number = this.number - number;
            updateNumberText();
        }
    };

    var newN = new Number(50);
    updateNumberText();

    function updateNumberText() {
        $('#number').text(newN.number + "");
        console.log('number updated!');
    }

    $('#decButton').on('click', function() {
        newN.dec(1);
    });

    $('#incButton').on('click', function() {
        newN.inc(1);
    });
});

And I've got the following error: SyntaxError: Unexpected token '('.
I just can't get my head around what's wrong, can't find any syntax errors.
Here are my HTML and CSS files as well.

    <link rel="stylesheet" type="text/css" href="randtime.css"/>

    <title>learning</title>

0

    <button id="incButton">increase</button>
    <button id="decButton">decrease</button>

div {
font-size: 400%;
}

#number {
    text-align: center;
}

Comment: add }); on the last line :)
Comment: Your code contains lot of syntax error, just open your console and fix everything..
Comment: @RajaprabhuAravindasamy , he couldn't so he asked here .
Comment: @PratikJoshi Then we should close it under `"why this code not working..?"` :)
Comment: Wow, my mistake. Accidentally missed out on }); when I copied my code, so that's not the problem unfortunately.
Answer: The private methods for "functional objects" in JavaScript should be defined in a different way:
function Number(startingNumber) {
    // ...

    this.inc = function(number) {
        this.number += number;
        updateNumberText();
    }

    // ...
}

Comment: I tried declaring them like this but then I received errors when calling them from outside the object. newN.inc(); for example
Comment: @frsvll This should work fine if you don't have other errors: http://jsfiddle.net/LqAEL/.

SyntaxError: Unexpected token '('


Why is AIC from multinom and corresponding glm different?

Question: I'm reading the example of the book: "S-PLUS (and R) Manual to Accompany Agresti's Categorical Data Analysis (2002) 2nd edition " (page 55) and when I try to reproduce the example I get this:
snoring<-c(0,2,4,5)

logit.irls<-glm(cbind(yes=c(24,35,21,30), no=c(1355,603,192,224))~snoring,
family=binomial(link=logit))

summary(logit.irls)

Null deviance: 65.9045  on 3  degrees of freedom
Residual deviance:  2.8089  on 2  degrees of freedom
**AIC: 27.061**

Ok, I get a Akaike information criterion of 27.061.
But when I use the multinorm function from the "nnet" library I get this:
modLogit = multinom(cbind(c(24,35,21,30),c(1355,603,192,224))~snoring)

summary(modLogit)

Coefficients:
  (Intercept)    snoring
2    3.866248 -0.3973366

Std. Errors:
  (Intercept)    snoring
2   0.1662144 0.05001066

Residual Deviance: 837.7316
**AIC: 841.7316**

Why the AIC (and the Residual Deviance) are too big?
Answer: It's because the minus-log-likelihood function is really only defined up to an additive constant and the absolute values of AIC and residual deviance depend on this constant. Hence, for different implementations you can, in general, expect different choices of constant. Hopefully, the difference in AIC (or the difference in the residual deviance) between two models is the same whether you use multinom or glm.
N.B. In multinom the residual deviance and AIC are computed based on the minus-log-likelihood of independent observations of 0-1-variables, thus
$$l = - \sum_{i} y_i \log \hat{\pi}_i + (1-y_i) \log(1-\hat{\pi}_i)$$
and AIC$= 2l + 2p$. This is the case even when the data are given in tabulated form. For the AIC computation in glm the minus-log-likelihood is based on independent observations of binomial variables, thus
$$l = - \sum_{k} n_{k1} \log(\hat{\pi}_k) + (n_k - n_{k1}) \log(1-\hat{\pi}_k) + \log {n_k \choose n_{1k}}.$$
When data are in tabulated form as in the question, the difference between the two reported AIC's is precisely twice the sum of the log of the binomial coefficients.
Comment: I would say that unless you know precisely what is computed you should not expect to be able to compare AIC, say, from two different implementations in two different packages in R.
Comment: That's mean the log-likelihood of the multinom have to be computed with another function?
Comment: @Galled, question not really understood. Both R functions compute valid residual deviances and AICs, but the absolute values can not be compared between the functions. This is a matter that one should always be careful about. AIC is only defined up to an additive constant and if you compare two models in terms of AIC you better make sure that you use the same constant (in technical terms, the same reference measure).
Comment: What I meant is that if I could use both AIC to check the fit of a binomial (or multinomial of a responding variable of two choices) model. In any case, how could sure use the same constant, for example if I want to compare the fit of a multinomial model with a log-linear model? ¿Can I use the AIC from multinom?


How to change background color in static text visual studio?

Question: I am trying to change background color of static text in our project. We use BCG library also.
In h. file I have
afx_msg HBRUSH CtlColor(CDC * pDC, CWnd * pWnd, UINT nCtlColor);
COLORREF m_bckNewsClr;

In cpp. I have:
m_bckNewsClr = RGB(255, 255, 255);

HBRUSH CStartPage::CtlColor(CDC * pDC, CWnd * pWnd, UINT nCtlColor)
{
    pWnd->GetDlgItem(IDC_STATIC_NEWS_CAPTION_1);
    pDC->SetBkColor(m_bckNewsClr);
    return (HBRUSH)m_Brush.GetSafeHandle();
}

In massage map:
ON_WM_CTLCOLOR()

Anyway, it is even not visible the function CtlColor, when I put the breakpoint.
Does someone know how to change this backgound static text in this case?
Comment: You can use Spy++ (if x64 target platform: Spy++ 64) to discover if the message is really `WM_CTLCOLOR` . I suspect in the specific case is `WM_CTLCOLORSTATIC` . Some more guidance on https://stackoverflow.com/a/43120662/383779
Comment: `ON_WM_CTLCOLOR` redirects the message to **On**CtlColor
Answer: The ON_WM_CTLCOLOR expects a method named:
afx_msg HBRUSH OnCtlColor(
   CDC* pDC,
   CWnd* pWnd,
   UINT nCtlColor
);

See also CWnd::OnCtlColor for a sample how to do it.
And also https://stackoverflow.com/a/12007350/8918119


C++ passing a struct and passing a pointer interchangeable?

Question: If the function is:
void foo(struct* bar)
{
}

And
struct foobar;

Is a single instance of struct, will the call
foo(foobar);

Be treated as if it were a pointer to a one member array?  Will the call be legal or does it require an overload?
Comment: That shouldn't compile a) because you used the `struct` keyword as a class name, and b) because you're missing an ampersand (&) in your call, or put in an extra asterisk into your function parameter list (presumably the former based on your question).
Answer:
Is a single instance of struct, will the call  foo(foobar);
  Be treated as if it were a pointer to a one member array? Will the call be legal or does it require an overload?

No, it will not. The call is not legal, and an overload could make the call work.
If a function needs a pointer to a struct, then you have to give it a pointer to a struct. Arrays are special since they decay to a pointer to the first element.


What are non-zero-sized values in Rust?

Question: I just read the documentation of the std::boxed module and encountered a sentence

For non-zero-sized values, a Box will use the Global allocator for its allocation

What are non-zero-sized values (in this context and in general)?
Comment: Relevant doc link: [Zero Sized Types (ZSTs)](https://doc.rust-lang.org/nomicon/exotic-sizes.html#zero-sized-types-zsts)
Comment: A better question is what are zero-sized values, because those are the exception. Zero-sized values are types whose values carry no information at run-time. Examples are a struct with no fields or the empty tuple `()` (sometimes also called the unit type). Those types have the run-time size of 0, which means they have to be handled specially in some contexts. For example, it doesn't make sense to allocate them, and a `Vec` of such types will have all elements point to the same address in memory, and so on.
Comment: Also, to explain what that sentence means: allocators in general refuse to allocate 0 bytes, so if you have a type whose size is actually 0 (for instance, `()`), it has to be handled specially. In C++, it won't try very hard and just allocate the minimum size possible instead of 0. Rust is a bit smarter, so it won't allocate *at all* for these types, but this also means there is much more hassle. For this reason, ZST have some special handling rules.
Comment: @BlackBeans In C and C++ the issue doesn't exist to begin with because every type has a size of at least 1. This cause issues in many contexts, too.
Comment: @user4815162342 Yes that's what I meant by "it just allocates the minimum size possible".
Comment: @BlackBeans I understood your comment to imply that `malloc(0)` behaves like `malloc(1)`, whereas in fact `malloc(0)` is (in normal circumstances) never called to begin with.
Comment: in addition to user4815162342's comment, the never type (`!`) is also zero-sized. it is implemented as an empty enum (aka [`Infallible`](https://doc.rust-lang.org/std/convert/enum.Infallible.html)), but since it looks so different from any normal type it seems worth mentioning.
Comment: As far as I understood, the ZSTs (zero-sized-types) are types that occupy 0 space in the memory: `()`, `vec![(), (), ()]`, `[]`, `""` (I used [`mem::size_of`](https://doc.rust-lang.org/std/mem/fn.size_of.html) to verify their size). And non-zero-sized-types are opposite to ZST that require memory to be stored within a program: `1` (i32), `"Text"` (&str) etc.
Comment: Fun bit of trivia: according to [this tweet](https://twitter.com/nevi_me/status/1532772034291310592), the capacity of a `Vec<()>` is always `usize::MAX`.
Comment: @user4815162342 yes my bad it was poorly described. But what you said is what I meant. In my comment, it was not the allocator that is smart about allocating ZST, it's Rust, and, likewise, it's C++ that does not try hard about being smart about it and will just allocate something anyways.
Comment: Note that according to the `malloc` man page: _If `size` is 0, then `malloc()` returns either `NULL`, or a unique pointer value that can later be successfully passed to `free()`_.
Comment: Note that while `[(), (), ()]` (type: `[(); 3]`) is zero-sized, `vec![(), (), ()]` (type: `Vec<()>` is not: it has a size of 24 (or more generally `3*size_of::()`), as all `Vec`s do. But it's true that the slice *pointed to* by the `Vec` is zero-sized, and takes up no space on the heap.
Answer: Non-zero-sized types are types that occupy one or more bytes in memory. This is typical of most types, since the point of most data structures is to, well, store data.
Zero-sized types are types that do not occupy any space in memory, like () and PhantomData. They have certain uses, but allocators need to handle them specially.

What are non-zero-sized values in Rust?


Pesquisa em MYSQL em campos com nomes iguais

Question: Olá, estou precisando fazer uma pesquisa no mysql em que utilizo diversos inner joins, e por se tratar de relacionamentos muitos pra muitos, alguns dos campos se relacionam com mais um campo da outra tabela, segue um exemplo em que ficará mais fácil de se entender
SELECT livros.id_livro, livros.nome, livros.caminho, categorias.nome as categoria FROM livros INNER JOIN categorizados ON categorizados.id_livro = livros.id_livro INNER JOIN categorias ON categorizados.id_categoria = categorias.id_categoria WHERE categorias.nome LIKE 'Terror' AND categorias.nome LIKE 'Suspense'
Aqui deixo em destaque o seguinte trecho: WHERE categorias.nome LIKE 'Terror' AND categorias.nome LIKE 'Suspense'
E é sobre ele que a dúvida está relacionada, em um dos meus livros cadastrados, tenho um que se tem duas categorias nele cadastrado, uma com nome 'Terror' e outro com nome 'Suspense'
Porém não consigo filtra esse livro com essa requisição, acredito que exista alguma forma de fazer essa requisição, porém não sei como ainda, gostaria que me ajudassem, obrigado!
Edit1: A pesquisa após o WHERE são em registros diferentes, um registro tem o campo nome como 'Terror' e o outro registro tem o campo nome como 'Suspense'
Comment: Se é que eu entendi você não deveria utilizar OR no lugar de AND já que, pelo que entendo, um campo não pode ter simultaneamente os valores 'Terror' e 'Suspense'. Pode ser que, caso queira selecionar aqueles que tem dois registros na tabela categorias você possa utilizar a cláusual GROUP BY com COUNT e a cláusula HAVING COUNT(id_categoria) > 1.
Comment: São registros diferentes, as duas tabelas estão relacionadas, e tenho dois registros, um com o campo nome como 'Terror' e outro com o campo nome como 'Suspense'
Answer: Creio que o que deseja é algo do tipo:
SELECT livros.id_livro, livros.nome, livros.caminho, GROUP_CONCAT(categorias.nome SEPARATOR ';') as categoria
FROM livros INNER JOIN categorizados ON categorizados.id_livro = livros.id_livro
            INNER JOIN categorias ON categorizados.id_categoria = categorias.id_categoria
WHERE categorias.nome LIKE 'Terror' OR categorias.nome LIKE 'Suspense'
GROUP BY livros.id_livro
HAVING count(categorias.id_categoria) > 1

Comment: Manin, no where eu preciso que tenha um AND entre as duas condições, não um OR
Comment: Meu caro, se você tem em cada registro de sua tabela categorias um campo nome que contém um texto ('Terror', 'Suspense', etc) então, pelo que entendi de sua descrição, é impossível que cada registro contenha diferentes nomes, que é o significado do AND. Pelo que você descreveu não é um registro com 'Terror' **outro registro** com 'Suspense' e assim por diante?
Comment: Olhe, acredito que você não tenha compreendido o que eu quis dizer, mas o que tenho é uma tabela chamada categorias como você já deve ter notado, e dentro dela eu tenho uma coluna que se chama nome
E então eu tenho 2 registros nessa tabela, um tem dentro da coluna nome 'Terror' e o outro 'Suspense', observe que ambos compartilham a mesma tabela, e mesma coluna, mas registros diferentes, por isso a requisição de ambos é categorias.nome
E então eu tenho uma tabela (livros) que se relaciona com essa tabela através de uma intermediaria (categorizados), em resumo não é apenas 1 registro, mas 2
Comment: Perdão se eu me expressei mal antes o que tenha resultado em mal entendimento, mas é que eu ainda sou um pouco iniciante
Comment: Teste a query que apresentei e verifique se o resultado apresentado não é exatamente o que deseja. Estude a cláusula HAVING pois ela é que irá determinar os livros que estejam classificados em `Terror` **e** em `Suspense`. Utilizo `OR` porque são em registros diferentes.


Leitura da porta serial no delphi xe8

Question: Qual componente eu uso no delphi xe8 para fazer a leitura da porta COM, já vi que no delphi 7 tem a tcomport queria saber para o delhi xe qual seria?
Answer: Existe o TComPort para as versões XE também. link
Comment: @Maurício Souza se a resposta foi útil para você, favor aceitá-la para que outros usuários possam se beneficiar do conhecimento compartilhado. Abraço.

Leitura da porta serial no delphi xe8


MS Edge support crossorigin attribute?

Question: I am trying to load riot.js tag file. I had a cross domain issue but fixed it by crossorigin attribute on the script tag.
It is working for all of the browsers except on Microsoft Edge.
There, getting this error:
"... not found in Access-Control-Allow-Origin header"
Anyone knows if MS Edge support the crossorigin attribute?
Comment: It looks like you proved it does not ... Why don't you setup classic CORS ? You should show some code or describe your setup.
Comment: Relatedly, Edge 14 has a serious bug when there is a crossorigin attribute on a script element. It sometimes will not execute the script, even though Edge doesn't technically support the crossorigin attribute (https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/9299606/).
Answer: Microsoft Edge currently does not support the <code>[crossorigin]</code> attribute on script tags. If you would like to see support added, please consider voting for this feature on UserVoice. You can track platform additions on the Microsoft Edge Status resource.

MS Edge support crossorigin attribute?


I want to check if cnic already exist it never insert the cnic

Question: THis is another pattern  but it also have errors
DECLARE
DCNIC varchar(50);
BEGIN
 DCNIC :='';
    Select count(*) into DCNIC from EMPLOYEE where CNIC=:P36_CNIC;
    if DCNIC = 0
    then
   insert into EMPLOYEE(CNIC) values (DCNIC);
    else
    DCNIC := 1;
    end if;
RETURN DCNIC;
END;

Comment: Is it MySQL or Oracle?
Comment: It's Sql query but it have so many mistakes
Answer: Please change your Query 1 to this:
DECLARE
DCNIC VARCHAR(50)
DCNIC :=0;

BEGIN

    if not exists (Select * from EMPLOYEE where CNIC=:P36_CNIC)
    then
  insert into EMPLOYEE(CNIC) values (DCNIC);
END;

Comment: ORA-06550: line 1, column 106: PLS-00103: Encountered the symbol "DECLARE" when expecting one of the following: ( - + case mod new not null    continue avg count current exists max min prior sql stddev sum variance execute forall merge time timestamp interval date    pipe <an alternatively-quoted string literal with character s            This error is raised
Comment: DECLARE
DCNIC varchar(50);

    BEGIN
     DCNIC :='';
        Select count(*) into DCNIC from EMPLOYEE where CNIC=:P36_CNIC;
        if DCNIC = 0
        then
       insert into EMPLOYEE(CNIC) values (DCNIC);
        else
        DCNIC := 1;
        end if;
    RETURN DCNIC;
    END;           THis is another pattern  but it also have errors
Answer: The correct way to do this is to have a unique constraint (or index) on the column.  So:
alter table employee add constraint unq_employee_cnic on employee(cnic);

Then, just do the insert.  It will fail if the constraint is violated.  If necessary, you might want to catch the exception when it fails.
Why is this the correct way?  First, having the database enforce data integrity is allowing the database to do what it is designed to do.
Second, your code introduces race conditions.  Two different threads could both run the if, see that a given cnic value is not in the table, and then both could insert it.  You would have duplicates in that case.
Third, your code protects against one particular insert.  However, somewhere else in the code may be another insert that doesn't follow this logic.  And, no check is done.  Or, someone could decide that they want to "fix" the data and accidentally insert duplicates.
Fourth, your code protects against inserts. But updates can also introduce duplicate values.
Let the database do the work for you.


How is music theory helpful in fitting notes together?

Question: I'm very new to music; i've played a guitar before but without a real direction in my practice. I'd like to learn to play the guitar properly, but before that can happen I need a clarification regarding a few things, namely:
If I'm most interested in the ability to create progressions of notes that will sound "well",  I should focus on learning scales, right? How important are scales in finding the right follow up sounds? Do artists mix scales in the same part of a song or do they come in order, as in one part is written using notes from one particular scale and the next part using notes from one another particular scale? Is there something else to learn from music theory that would help me know what notes i could play next?
Thank you in advice!
Comment: What style of music? Theory, performance methods, and aesthetics (what sounds good) aren't completely the same between different styles.
Comment: How helpful? Really helpful.
Answer: Scales are very useful, as they are a 'list' of diatonic notes. That 'list' is a set of notes recognised to work well together (with a little prudence). I guess the majority of pieces, if examined, would comprise notes from a particular scale - which then can be construed as constituting a particular key.
'Mixing scales' - is one way to put it, but it's usually more a case of using an occasional note from another key. Think about it - in one key, 7 out of the 12 notes available can be drawn upon, only leaving another 5.
At the beginner stage, it's safer to stick to diatonic notes - even pentatonics - as they will work well together, and produce fewer problems with harmonies - which also, safely, will contain diatonic notes. When you improve, you'll want to include other notes, but it's not that good an idea to consider that you're 'using other scales', unless the piece has modulated, at which point, that's exactly what's happening.
You will also find, when you meet the 'circle of fourths', that as it goes round, one key has only one note changed at a time. For example, key C and key F are next to each other. They both contain exactly the same notes, but with a single change. C has B, whereas F has B♭. There is a greater chance of a piece in key C having a B♭ (in the next door neighbour key), than a D♭ (in a key much further round that circle).
Answer: You've got a lot of opinions, some disagreements, and a few answers. Or an attempt at an answer.
I'm going to put my 2 cents in and try to add to the proceedings.  First, my answers to your questions.

If I'm most interested in the ability to create progressions of notes that will sound "well", I should focus on learning scales, right?

Right.  You are asking for validation in this question rather than direction, but scales should be learned.  Chords are made from scales, and whole progressions can be derived from and fit into scales.  Even when there are "out" notes, the majority of what appears in music follows this trend.  The scale can be thought of as a basic part of our language; from it many things are constructed.  You should keep a couple things in mind.
(1) Songs will modulate and the "scale" used may change; that doesn't mean that the previous statements are invalid, they apply to each new key (scale) that comes along.
(2) We frequently use accidentals to create more texture; this doesn't mean that the key has been thrown out the window.  The basic structure is likely still going to follow the traditional key and scale with some deviation.
(3) When accidentals are used they are usually motivated by voice leading, creating a smooth chromatic movement on one or more voices.  Common example is IV --> iv --> I, where the b6 of the key is introduced.

How important are scales in finding the right follow up sounds?

I don't know what you mean by "follow up sounds" but I'd say an understanding of scales and the chords that naturally fit into them is important for creating harmony and chord progressions easily.

Do artists mix scales in the same part of a song or do they come in order, as in one part is written using notes from one particular scale and the next part using notes from one another particular scale?

Both.  In classical music one commonly encounters song structure that is in a well defined key for a section then modulates to a new key, perhaps a 4th up, then back down.  And in some tunes a melodic theme may wind through more than one scale or mode, or even key in one section.
>
Is there something else to learn from music theory that would help me know what notes i could play next?
Yes, a lot.
Now here are some of my suggestions based on my experience.  Some have stated that you should start here or there and mentioned a little theory.  My approach to teaching is a little more holistic.  You'll never win the chicken vs egg debate.  You need to expose yourself to music and a lot of it.  But that is not enough for everyone to learn the patterns that exist in classical western music and like it or not this has dominated the musical landscape for 100's of years.  On the other hand you can't really learn music by only looking at text book information.  So, I'd recommend you do both at the same time.  The theory study will add to your depth of thought about the songs you play and the constant exposure to well structured music will enhance your understanding of the theory.  By the way all theory books are written in SMN so there is no reason why you can't "play" your theory book and most state up front that you SHOULD!
Along these lines, the classic approach to harmonizing melodies is based on Church multi voice vocal music.  While that may not seem relevant to modern music you might be surprised at just how strong the influence is.  I would highly recommend going through a basic theory and harmony text.  The virtue in my option is that (1) you start very basic using triads and that is easy to follow, and (2) you learn why certain combinations of notes and note movement work.  While a fancy modern Jazz progression may seem to not follow, these basic patterns are actually embedded in the more complex chords and chord movement.  Here are a few suggested texts:
Basic Theory - Harmony by Paulson and Cheyette
How to Create Jazz Chord Progressions by Chuck Marohnic
there are many more books available but I learned from these so I'm familiar with them.  The key is to integrate the two forms of study.  Again, PLAY YOUR THEORY BOOK.  And analyze your playing and listening.
Answer: Chords and scales really go hand in hand.  Each note of a scale has a specific chord built around it.  These are called diatonic chords.  They naturally have a tendency to "fit" together.  There are even certain patterns they tend to appear in (called harmonic function).  But they are far from the only options.  Here is my recommendation:

Learn what a scale is.  Try here
Learn how chords are derived from scales.  Try here
Learn harmonic function.  (This will help with the "what to play next" part.)  Try here

Hopefully this helps.  If you have any other questions, feel free to contact me directly here (shameless plug).
Answer: As a guitarist, you will find that you have to focus more on chords. Guitars are better suited to playing chords, pianos are better suited to playing scales. Guitars have become the world's most famous instrument largely through the introduction of jazz (and, subsequently, blues, rock'n'roll and other genres) to the Western world. How you approach your instrument also depends on the genre(s) you play in. Jazz progressions and scales are usually more chord-based than classical ones.
Composition-wise, not all genres employ key changes. Even classical music sometimes doesn't jump out of the confines of a particular key. In fact, you should not expect too many key changes within most classical works before the 20th century. You will probably hear them a lot in modern classical and jazz music and extreme genres like mathcore, but not in "older" classical music or the more "primitive" genres, like punk rock and grindcore.
What Tim refers to as the "circle of fourths" you will find is called "the circle of fifths" when it comes to classical music (it's the same thing, just clockwise).
Of course you should not discard music theory, but don't beat yourself over the head with it either. I started out as a percussionist (drums, xylophone, kettle drums) when I was a teenager and had played for 8 years ignoring my teacher's attempts at teaching me theory. I felt the effect the moment I started playing saxophone. Now, the saxophone is less complicated and more linear compared to guitar, as it is a monophonic instrument, but I would probably want to kill myself if I focused on the fact that I have to play 84 scales from memory too much.
Scales are meant to prepare you for improvisation later on. The idea is that you will have them down your fingers so well after playing the instrument of your choice every day for a number of years that you will be able to go over them "intuitively" while everyone else is playing within the same (or a related) scale.
Scales can also be a wonderful tool in musical composition. For example, you might make your 12-tone neo-classical composition more interesting if you have one instrument play in C natural major and another one - in C# pentatonic major. Those scales only have one note in common (F), so you will have plenty of room for dissonance while also segregating the chromaticism into 2 separate parts.
I've only scraped the tip of the iceberg here. The question you ask is a big one, and I hope my response will help you see where to go from where you are at the moment.
Answer: Don't try to work outward from theory.   Just play plenty of existing good music (being able to read notation will be a great help).  SEE what works. Copy and extend it.
Answer: music (or what you mean is: songs and melodies) are based on scales and chords. The best way is to play tunes you have in your ear (as you have learnt by your mother, even baby songs! as they are in burnt scheme in your mind and try to play hits you like  - just playing the melody) try to find out the chords and the tabs of it. this will be the elements to you to progress. then just tap with your fingers on the frets of your guitar and find out and develop your own patters. try to notate them in a tab or staff system. and zou have to study the elementary music theory. it will help you a lot to advance. You will hardly create new progressions that other not have used. just listen to music won't help you as far as you don't have the basic knowledge to analyse what happens.
search here for questions about basic patterns and chord progression, you will find a lot of useful examples.
look at this guy. he is just cleaning his bass guitar and finds a lot of music:


How to pass a array to a constructor and use it in a class?

Question: This is my main method, i am trying to get back into coding, for i failed at it repeatedly in school. I want to take an array from my main method with user input from a loop, and pass it to a constructor in my "TestScoresTwo.java" class. I want to then take that array and use it to sum the values and find the average in a method in the class, and then return the sum.
import java.math.*;
import java.text.DecimalFormat;
import java.io.*;

public class labBookFortyTwo
{
public static void main(String[] args)
{

Scanner myInput = new Scanner(System.in);

System.out.println("Please enter the amount of grades there are ");

int size = myInput.nextInt();

double grade = 0;

double[] myArray = new double[size];

for(int count = 0; count < myArray.length; count++)
{
    System.out.println("enter grade ");

    grade = myInput.nextDouble();

    myArray[count] = grade;

    System.out.println("grade is " + myArray[count] );

}

TestScoresTwo myScore = new TestScoresTwo(myArray, size);

double avg = myScore.avgGrade();

System.out.println("avg is" + avg);

}

}

This is my TestScoresTwo.java Class.
public class TestScoresTwo
{

int size = 0;

double[] tScore = new double[size];

double sum = 0;

public TestScoresTwo(double[] scores ,int sizE)
{

    double[] tScore = scores;

    size = sizE;

}

public double avgGrade()
{

        for(int count = 0; count < tScore.length ; count++)
        {
            sum = tScore[count] + sum;

        }

    double avg = sum / size;

    return avg;

}

}

When it compiles my output is:
"Please enter the amount of grades there are"
3
"enter grade"
11
"grade is 11.0"
50
"grade is 50.0"
70
"grade is 70.0"
"avg" is 0.0"
"Press any key to continue..."
So for some reason in my class TestScoresTwo.java, the for loop inst being entered, and im not sure why. They are two separate files , and i cant think of any other information to include. Thank you for any help you can give.
Comment: You need to learn how to debug.  If you don't have an interactive debugger, insert System.out.println statements to show your progress and the values that are present.
Answer: Your proble; is in TestScoresTwo class:
public TestScoresTwo(double[] scores ,int sizE)
{
    double[] tScore = scores;
    size = sizE;
}

tScore is local to the constructor. So you're assigning the passed variable to a local variable, which is lost once the end of the constructor is reached.
So when you call avgGrade() to calculate the average, the array it,s calculating the average from is empty.
Replace it by:
public class TestScoresTwo
{
    int size = 0;
    double[] tScore; // no need to create it here, it's already created and filled in outside
    double sum = 0;

    public TestScoresTwo(double[] scores ,int sizE)
    {
        this.tScore = scores; // "this." added for clarity
        this.size = sizE; // "this." added for clarity
    }

Answer: You declared your array double[] tScore = new double[size]; to be of zero size.  You intended to replace it with a new array in your constructor here:
double[] tScore = scores;

However, all you did is declare a local variable of the same name, and assign the parameter to it, which immediately goes out of scope at the end of the constructor.  The for loop appears not to be entered, because tScore is still empty and of zero length.
Remove double[] so that tScore resolves to your instance variable and get assigned properly.
tScore = scores;

Also, it's confusing to see a parameter named sizE and an instance variable named size.  It's common to use this to refer to the instance variable, so that they can be named the same name and yet be clear.  Try naming the parameter size also, and use this line in your constructor:
this.size = size;

Comment: Thank you very much for the help, it worked, and the reason i use sizE, is because using this. is confusing to me, but i will try and consider it in the future.


Delphi, Override Custom controls setCaption

Question: i have a custom control,
with the Ancestor being another custom control,
who's Ancestor is a TPanel;
i.e.
TNotMyCustomControl = class(Tpanel);

TMyCustomControl    = class(TNotMyCustomControl);

Is i possible to react when the Caption is being set (run time or design time), and still have the changed passed to the Ancestor controls?
Answer: It is possible. Just add a CMTextChanged message handler to your custom TPanel:
type
  TMyPanel = class(TPanel)
  private
    procedure CMTextChanged(var Message: TMessage); message CM_TEXTCHANGED;
  end;

{ ... }

procedure TMyPanel.CMTextChanged(var Message: TMessage);
begin
  inherited;
  ShowMessage('caption has been changed');
end;


What model can be used when the constant variance assumption is violated?

Question: Since we can not fit ARIMA model when the constant variance assumption is violated, what model can be used to fit univariate time series?
Comment: Assuming there are no independant regressors in the fitted model, non constant variance is really only a problem when the variance of the error term is time-dependant. Then: arma+[garch](http://en.wikipedia.org/wiki/Autoregressive_conditional_heteroskedasticity)
Answer: There are a number of modelling options to account for a non-constant variance, for example ARCH (and GARCH, and their many extensions) or stochastic volatility models.
An ARCH model extend ARMA models with an additional time series equation for the square error term. They tend to be pretty easy to estimate (the fGRACH R package for example).
SV models extend ARMA models with an additional time series equation (usually a AR(1)) for the log of the time-dependent variance. I have found these models are best estimated using Bayesian methods (OpenBUGS has worked well for me in the past).
Answer: You can fit ARIMA model, but first you need to stabilize the variance by applying suitable transformation. You can also use Box-Cox transformation. This has been done in the book Time Series Analysis: With Applications in R, page 99, and then they use Box-Cox transformation. Check this link Box-Jenkins modelling
Another reference is page 169, Introduction to Time Series and Forecasting, Brockwell and Davis, "Once the data have been transformed (e.g., by some combination of Box–Cox and differencing transformations or by removal of trend and seasonal components) to the point where the transformed series X_t can potentially be fitted by a zero-mean ARMA model, we are faced with the problem of selecting appropriate values for the orders p and q."
Therefore, you need to stabilize the variance prior to fit the ARIMA model.
Comment: I don't see how variance stabilizing can be done first.  You need to see the residuals from the model first to see if the residual variance is changing with time.  Then looking at the residuals might suggest how to change the model or stabilize the variance.
Comment: Stat and @Michael, You both have valid points: Stat because often an initial Box-Cox transformation is *clearly* indicated--so why not begin the iterative modeling process by tentatively applying that transformation?--yet Michael is also right to point out that the focus should be on the model residuals rather than the raw dependent values (a distinction frequently misunderstood in questions here). Neither downvotes nor accusations of making mistakes are needed to carry out this discussion. If you're going to argue, do it about something about which you both truly disagree!
Comment: Yes I was the one who downvoted your answer. I agree that you can get a sense of variance inhomogeneity from a plot of the series.  But I still do not think it is a good idea to apply a variance stabilizing transformation before trying out models.  The models are all tentative.  You fit, look at the residuals and modify as necessary.  That is the three step Box-Jenkins approach.  Initial model identification, followed by fitting and then diagnostic checking with the cycle repeated if the model does not appear to be adequate.
Comment: By simply plotting the time series, you can find out if the variance stabilizing should be used or not. This has been done in the book "Time Series Analysis with Applications in R", page 99, and then they use Box-Cox transformation. You can check it by yourself. If you fit without stabilizing the variance, then it will be shown in the residual's plot. The thing is that we should try fixing any violations in the assumption of the ARIMA model before fitting them.
I strongly suggest you to be more careful when giving negative points to an answer! Good luck.
Comment: This means that you did not read Box-Jenkins carefully. Check this link http://robjhyndman.com/papers/BoxJenkins.pdf Another reference, page 169, Introduction to Time Series and Forecasting, Brockwell and Davis, "Once the data have been transformed (e.g., by some combination of Box–Cox and differencing transformations or by removal of trend and seasonal components) to the point where the transformed series X_t can potentially be fitted by a zero-mean ARMA model, we are faced with the problem of selecting appropriate values for the orders p and q." You can simply admit that you made a mistake.
Comment: Okay good point.
Answer: I would first ask why the residuals from an ARIMA model don't have constant variance before I would abandon the approach. Do the residuals themselve exhibit no correlation structure?  If they do maybe some moving average terms need to be incorporated into the model.
But now let us suppose that the residuals do not appear to have any autocorrelation structure.  then in what ways is the variance changing with time (increasing, decreasing, or fluctuating up and down)?  The way the variance is changing may be a clue to what is wrong with the existing model.  Perhaps there are covariates that are crosscorrelated with this time series.  In that case the covariates could be added to the model.  The residuals may then no longre exhibit nonconstant variance.
You may say that if the series is cross correlated with a covariate that show show up in the autocorrelation of the residuals.  But that would not be the case if the correlation is mostly at lag 0.
If neither the addition of moving average terms nor the introduction of covariates helps solve the problem, you could perhaps consider identifying a time varying function for the residual variance based on a few parameters.  Then that relationship could be incorporated in the likelihood function in order to modify the model estimates.


Calculating the total price of products from different dbs with php

Question: I have several databases with same tables. Anytime a user registers on my app a new database is created for him/her with same tables as all the other dbs.
Now what I want to do is

calculate the value ie sum total of "price" from table_1(produts) for all the dbs
And add these values from all the databases.

The idea is to show how much transaction pass through my system. so I want to add the total price of each users products together to get the sum of all transaction been carried out on my system and echo it.
I am new to programming so I would appreciate detail explanation of the solution
Comment: You're creating a new database for every user? I don't think this is right.
Comment: Is there any reason why your creating a new database for each client?
Answer: This does not answer your question.
You should stop now and change your design.  There is no reason that you should ever, ever, ever create a new table for every user, let alone a new DB.  This is really, really inefficient, resource hungry and will get very complicated very quickly (as you are finding out).
Change your design today to put all your users in a single table in a single database.
Comment: Much as I hate to upvote an answer that starts with "This does not answer your question", this is frankly better advice than explaining how to query across databases...
Comment: @djacobson Thats why I decided to be upfront about it :) - thanks for the upvote.


Why is RCX not used for passing parameters to system calls, being replaced with R10?

Question: According to System V X86-64 ABI, function calls in the applications use the following sequence of registers to pass integer arguments:
rdi, rsi, rdx, rcx, r8, r9

But system call arguments (other than syscall number) are passed in another sequence of registers:
rdi, rsi, rdx, r10, r8, r9

Why does the kernel use r10 instead of rcx for the fourth argument? Is it somehow related to the fact that rcx is not preserved while r10 is?
Comment: `r10` is used for passing the http://c2.com/cgi/wiki?StaticChain pointer, in languages where that's needed (ABI footnote 13 and Figure 3.4 (pg21)).  Otherwise `r10` is caller-saved: i.e. functions are free to use it *without* saving/restoring it.  I don't see any commentary in the ABI about why they chose to use `r10` for syscalls instead of `rcx`.  The kernel does destroy `rcx` and `r11`, though.
Comment: http://stackoverflow.com/questions/21322100/linux-x64-why-does-r10-come-before-r8-and-r9-in-syscalls discussed this question from a different angle.  Some of the comments are relevant, but in the end,  @technosaurus says "I never did track down exactly why rcx was used to save the entry point instead of r10".  So we haven't figured out why they didn't keep the register -> arg mapping for system calls the same as for function calls.  It appears it would have been possible.
Answer: X86-64 system calls use syscall instruction. This instruction saves return address to rcx, and after that it loads rip from IA32_LSTAR MSR. I.e. rcx is immediately destroyed by syscall. This is the reason why rcx had to be replaced for system call ABI.
This same syscall instruction also saves rflags into r11, and then masks rflags using IA32_FMASK MSR. This is why r11 isn't saved by the kernel.
So, these changes reflect how the syscall mechanism works. This is why the kernel is forced to declare rcx and r11 as not saved and even can't use them for parameter passing.
Reference: Intel's Instruction Set Reference, look for SYSCALL.


How would I apply a transition to a State Machine field?

Question: I am trying to transition a state_machine field on the User entity during an event. What I have thus far is:
/* @var \Drupal\user\Entity\User $user */
$user = User::load($id);

/* @var \Drupal\Core\Field\FieldItemListInterface $state_field */
$state_field = $user->get('field_screening_status');

/* @var \Drupal\state_machine\Plugin\Field\FieldType\StateItemInterface $state */
$state = $state_field->get(0);

$transitions = $state->getTransitions();

$state->applyTransition($transitions['mark_needs_screening']);

Of course, this does not actually save it to the user. I would actually need to call:
$user->set('field_screening_status', 'needs_screening');
$user->save();

But, how might I instead use the state_machine API to apply the transition to a user field?
Answer: Here's what I ended up with. Would be curious if the community has a better solution.
/* @var \Drupal\user\Entity\User $user */
$user = User::load(\Drupal::currentUser());

/* @var \Drupal\state_machine\Plugin\Field\FieldType\StateItemInterface $state */
$state = $user->get('field_screening_status')->get(0);

$transitions = $state->getTransitions();

if (array_key_exists('mark_needs_screening', $transitions)) {
  $user->set('field_screening_status', 'needs_screening');
  $user->save();
}

UPDATE: Thanks to @lisastreeter in #commerce on drupal.slack.com
$user = User::load($id);
$state = $user->get('field_screening_status')->first();
$transition = $state->getWorkflow()->getTransition('mark_needs_screening');

if ($transition) {
  $state->applyTransition($transition);
}

Not sure if that get(0) change to first() really made the difference, but it works now.


Call Erlang from Ruby

Question: What is the most awesome gem I should use to call Erlang functions from Ruby app? I wish to use rspec for testing some gen_server stuff.
Erlectricity looking solid, but there is no something like Node#rpc, just message passing. Any ideas?
Comment: If you have message passing, you can "mimic" rpc by maintain a server process in Erlang which will listen for your messages and spawn workers to execute them. (rpc in erlang is implemented similarly)
Comment: Maybe I'm stupid but do you mean "start a erl node, expose some function in a module and send the result back to ruby" when you say "call erlang functions" ? Or do you mean "I have a running erl node that expose some functions from a module via tcp/ip or a stdin/stdout"
Comment: "What is the ost awesome gem I should use"...lol. I'm going to get voted down for this, but is this how all Ruby devs talk?
Answer: Well. I am using BERT-RPC and happy with it.
http://github.com/mojombo/bertrpc
Answer: For rpc calls, rinterface might be the right option.
From the README:
<code>r = Erlang::Node.rpc("math","math_server","add",[10,20])
if r[0] == :badrpc
   puts "Got and Error. Reason #{r[1]}"
else
   puts "Success: #{r[1]}"
end
</code>
Answer: I think (someone prove me wrong) that you shouldn't use rspec for a gen_server at all.
Instead you could, depening on what your gen_server actually does, use eunit.
http://salientblue.com/codenotes/?name=erl_start
and no, its a long way from rspec.

Call Erlang from Ruby


JSON from ruby to mongoDB

Question: I'm new in ruby and mongo. I developed a Ruby script, which generates JSON from YAML files. How can I send this JSON to MongoDB?
I started from:
require "mongo"
client = Mongo::Client.new(['localhost:27017'])
database = Mongo::Database.new(client,'test')
collection = Mongo::Collection.new(database,test)
collection.create()

and when I want to insert my JSON files in a collection, I do this:
collection.insert(ActiveSupport::JSON.decode(my_json_files)

but that doesn't work, becuse when I look in mongoDB, the collection result is empty.
Answer: To insert JSON data into a MongoDB database using Ruby, you need to use the MongoDB Ruby driver, which you have already required in your script. However, your code is slightly incorrect. Here are the steps you need to follow:
First, ensure that you have installed the MongoDB Ruby driver. If you haven't, you can install it using the following command:
require 'mongo'
client = Mongo::Client.new(['localhost:27017'], :database => 'test')

Next, you need to convert your JSON data into a Ruby hash object before inserting it into the MongoDB collection. The JSON.parse method can be used for this:
require 'json'
my_hash = JSON.parse(my_json_files)

Now, you are ready to insert your data into the MongoDB collection. You can use the insert_one or insert_many methods of the collection to insert one or many documents respectively:
client[:test].insert_one(my_hash)

This will insert the hash object into the 'test' collection in the 'test' database. If the collection does not exist, it will be created automatically.
Comment: first of all, thank you so much for answer. I just try to run the script with this suggestion, but ruby console say me "JSON::ParseError: unecpected token at ...(rest of json that try to parse)"
Comment: Are you sure your JSON is valid? You can use an online JSON validation tool to check that (just make sure it does not include any sensitive data)
Comment: i check json files and i adjust the format, but now occurred another problem when i run the script.  That is: #
Comment: Do you see where the 'map' method is used that could cause the issue?
Comment: yes, i saw, but i dont understand why occured another problem:  i wrote your exact code and when i try to run ruby script,the script doesnt write on the collection. sorry but  i dont know why

JSON from ruby to mongoDB


Show that functional $f(x)$ is unbounded and norm $\|A\|=\infty$

Question: Let  $(H;(\cdot|\cdot))$ be separable Hilbert space where $\dim$ $H=\infty$. We define norm $\|x\|=\sqrt{\langle x|x\rangle}$ and linear operator $A:H\to H$. Show that:
a) functional $f(x):=\langle Ax|a \rangle \in \mathbb{C}$ is unbounded and $\ker f$ is dense in $H$, when vector $a\notin \operatorname{dom} A^{*}$, $ A^{*}:H\to H$.
b) show that $\|A\|=\infty$.
I would ask for a draft proof or a solution because I don't know where to start.
Comment: This need a lot of cleaning up. As-is, it's barely understandable.
Comment: I would suggest you look up the definition of $dom(A^\star)$, then it should be not too difficult. Also, $b.)$ is simply wrong, the correct question would be to ask "If $dom(A^\star) \neq H$, then $\Vert A \Vert = \infty.$
Comment: Yes, I forgot to add that assumption to b) thanks, I will try to figure it out
Answer: If $f$ is bounded then (by Riesz Theoem) there exists $y$ such that $\langle Ax , a \rangle =\langle x , y \rangle$ for  all $x$. By definition this means $a \in dom(A^{*})$ and $A^{*}a=y$. This is a  contradiction.  Hence $f$ is unbounded.
Now $ker f$ has co-dimension $1$. (This is true for  any non-zero linear functional). If $ker (f)$ is a proper subspace of $H$ then we would have the struct inclusions $\ker (f) \subset \overline {\ker (f)} \subset H$ but this contradicts the fact that co-dimension is $1$. Hence $ker (f)$ is dense. Of course $\|A\|=\infty$ becasue $A$ is unbounded.
Comment: @Michal Hint: if $f\neq 0$ then there exists $x_0$ such that $f(x_0) \neq 0$. For any $x$ we can find $c$ such that $f(x-cx_0)=0$ ($c=\frac {f(x)} {f(x_0)}$. So $x =cx_0+y$ where $y =x-cx_0 \in ker (f)$. Hence co-dimension of $ker (f)$ is $1$.
Comment: Why we take that ker(f) has co-dimension 1?


Creating a Batch with multiple functions

Question: i'm trying to optimise my setup of a Drupal Batch process.
I am reading in thousands of rows of data from an Excel spreadsheet, from multiple worksheets, and creating nodes from the Rows. My import functions work fine, and I can create a Batch, but at present I am creating a batch operation for each row. This means that my batch is very slow (because I'm having to bootstrap Drupal on every row).
What I can't seem to figure out is a way to setup my batch to deal with 'chunks' rather than individual rows.
An example of my import function (of which there are 18) is:
function governbim_coordinate($value){
    module_load_include('inc','phpexcel');
    global $user;
    $project = $_SESSION['governbim']['projnid'];
//Load the required worksheet from the excel file passed to the function as $value
    $result = phpexcel_import($value,TRUE,TRUE,array('setLoadSheetsOnly' => array('Coordinate')));
//Define some common values for our entity
    $values = array(
            'type' => 'coordinate',
            'uid' => $user->uid,
            'status' => 1,
            'comment' => 0,
            'promote' => 0,
            );
//step through each row in the worksheet
    foreach($result['Coordinate'] as $coordinate){
        $title = $coordinate['Name'];
//check to see if this is a new row or if we are updating an existing entity
        $action = governbim_node_actions_node_check('assembly',$title);
        switch($action['op']){
            case 'new':
                $e = entity_create('node',$values);
                $entity = entity_metadata_wrapper('node',$e);
                break;
            case 'update':
                 $e = entity_create('node',$values);
                   $entity = entity_metadata_wrapper('node',$action['nid']);
                break;
        }
//*** Here is where we write everything to the database with the entity values and $entity->save() ****/
    }
}

My batch is setup (currently) as:
function governbim_excel_import_batch(){
    drupal_set_message("Importing Data...");
    $path = 'public://imports/';
    $file = 'COBie-UK-2012-example1.xls';
    $datafile = $path.$file;

       $operations[]=array('governbim_coordinate',array($datafile));

        //another 17 $operations[] defined as above

    $batch = array(
        'operations' => $operations,
        'init_message' => t('Constructing batch operation...'),
        'progress_message' => t('Importing Excel data'),
        'finished' => 'governbim_excel_import_batch_finished',
        'error_message' => t('Importing of Excel data encountered an error.'),
        );
    return $batch;
}

I realise I need to get some $context stuff into the import function, but I can't seem to figure out how to setup that aspect properly.
Is anyone able to assist me in re-tuning things so that I can get the batch (with 18 function calls) to display progress of the overall batch and get the batch to execute (say) groups of iterations (as in $limit = 10)?
Answer: I do one batch operation but with multiple entry.
/**
 * Batch start function.
 */
function mymodule_batch_start() {
  $batch = array(
    'title' => t('Importing Excel data'),
    'operations' => array(
      array('_mymodule_import', array()),
    ),
    'progress_message' => t('Importing Excel data. Operation @current out of @total.'),
    'error_message' => t('Error!'),
    'finished' => 'mymodule_batch_finished',
  );
  // Run batch in background
  batch_set($batch);

Here is the pattern fot the operation:
/**
 * Import operation.
 */

function _mymodule_import(&$context) {

  // Get your import data with some custom function.
  $import_data = _mymodule_get_import_data($context);

  // Get Count of items
  if (empty($context['sandbox']['progress'])) {
    $context['sandbox']['progress'] = 0;
    $context['sandbox']['max'] = count($import_data);
    $context['results']['total_count'] = $context['sandbox']['max'];
  }
  // Create Iteration variable
  if (empty($context['sandbox']['iteration'])) {
    $context['sandbox']['iteration'] = 0;
  }

  // Check for the end of cycle
  if ($context['sandbox']['iteration'] < $context['sandbox']['max']) {

    // Count of operation in one butch step
    $limit = 10;
    // Counts completed operations in one butch step
    $counter = 0;
    if ($context['sandbox']['progress'] != 0) {
      $context['sandbox']['iteration'] = $context['sandbox']['iteration'] + $limit;
    }

    // Main loop of all import items
    for ($i = $context['sandbox']['iteration']; $i < $context['sandbox']['max'] && $counter < $limit; $i++) {

      // Do smth custom here with import data item $import_data[$i].
      _mymodule_handle_import_item($import_data[$i]);

      // Update Progress
      $context['sandbox']['progress']++;
      $counter++;
      // Messages
      $context['message'] = t('Item %progress of %count', array(
        '%progress' => $context['sandbox']['progress'],
        '%count' => $context['sandbox']['max'],
      ));
      $context['results']['processed'] = $context['sandbox']['progress'];
    }
  }

  if ($context['sandbox']['progress'] != $context['sandbox']['max']) {
    $context['finished'] = $context['sandbox']['progress'] / $context['sandbox']['max'];
  }
}

P.S. Sometines I need to import data and then remove some old data. You can store some results of 1st operation in $context and then use it in other operation. I can do import in one batch with two operations:
'operations' => array(
  array('_mymodule_import', array()),
  array('_mymodule_remove_data_after_import', array()),
),