text:
Q: Transformar Tabela HTML em Excel boa tarde!
Eu estou alguma tempo tentando transformar uma tabela dinamicamente vinda do banco para um arquivo Excel.
O procedimento que eu faço é pegar essa tabela via JavaScript, envia-la para um arquivo PHP via Ajax e nesse arquivo forçar o download da tabela em Excel. O que não está funcionando é "Forçar" o download do arquivo.

// Gerar tabela statica via Ajax
    tabelaHtml = document.getElementById("table").innerHTML;

    $("#exportar").click(function(){
        $.ajax({
            type: "POST",
            url: "recebe-dados.php",
            cache: false,
            data:{
                origem: '<?php echo "$origem"; ?>',
                dadosExcel: tabelaHtml
            },
            success: function(e){
                alert("Dados exportados com sucesso!");
                console.log(e);
            },
            error: function(e){
                alert("Houve algum problema, tente novamente mais tarde!");
                console.error(e);
            }
        });
    });
mv1.com.br | LP Pré-matrícula

         02/09/2019   =   2

        626
        Leandro Dutra Ribeiro
        leandro.durbeiro@gmail.com
        Icaraí
        (22) 98170-0530
        2019-09-02 10:10:20
        mv1.com.br | LP Pré-matrícula

        627
        Pwmranbwajve
        poppyhaynes3565@gmail.com

        5066343676
        2019-09-02 21:45:42
        mv1.com.br | LP Pré-matrícula

         04/09/2019   =   3

        628
        Renata de Andrade Ribeiro
        renatadearibeiro@gmail.com
        Ilha
        (21) 97593-1215
        2019-09-04 07:13:23
        mv1.com.br | LP Pré-matrícula

        629
        Juliana Candido Bastos Almeida
        julianacandidobetero@hotmail.com
        Icaraí
        (21) 99748-4757
        2019-09-04 10:35:55
        mv1.com.br | LP Pré-matrícula

        630
        Beatriz Imbroisi Ximenes
        biaimbroisi1@gmail.com
        Volta Redonda
        (21) 96450-4605
        2019-09-04 11:32:50
        mv1.com.br | LP Pré-matrícula

         05/09/2019   =   1

        631
        Beatriz Pensabem de Menezes Guimarães
        beatrizpensabem@gmail.com
        São Gonçalo
        (21) 3583-3551
        2019-09-05 15:15:12
        mv1.com.br | LP Pré-matrícula

         06/09/2019   =   3

        632
        Maira de Souza
        mairaebranca@gmail.com
        Tijuca
        (21) 99488-3420
        2019-09-06 15:25:08
        mv1.com.br | LP Pré-matrícula

        633
        Kelly Cristina Garcia de Figueiredo
        kellycgfig@gmail.com
        Tijuca
        (21) 98083-7461
        2019-09-06 17:26:28
        mv1.com.br | LP Pré-matrícula

        634
        Daniele dos Santos Xavier
        anaclaraxavier777@gmail.com
        Icaraí
        (21) 99994-3168
        2019-09-06 19:18:51
        mv1.com.br | LP Pré-matrícula

         07/09/2019   =   2

        635
        Mariana Dias Sampaio
        marianasampaio.libras@gmail.com
        São Gonçalo
        (21) 96511-5066
        2019-09-07 11:28:50
        mv1.com.br | LP Pré-matrícula

        636
        Aclessiani
        aclessiani@gmail.com
        Volta Redonda
        (24) 99885-1763
        2019-09-07 14:41:06
        mv1.com.br | LP Pré-matrícula

         09/09/2019   =   7

        637
        Gazlcfudonkb
        danielwilliamson7992@gmail.com

        3069411081
        2019-09-09 08:40:17
        mv1.com.br | LP Pré-matrícula

        638
        Vinícius  Alves Couzi
        viniciuscouzi@hotmail.com
        Volta Redonda
        (24) 99878-2303
        2019-09-09 12:05:35
        mv1.com.br | LP Pré-matrícula

        639
        Fernando Sergio Teixeira dos Santos
        fsergiobr@gmail.com
        Tijuca
        (21) 98135-8961
        2019-09-09 13:14:49
        mv1.com.br | LP Pré-matrícula

        640
        Juliana Rodrigues  de Mello
        julianarmello7@hotmail.com
        São Gonçalo
        (21) 97014-7127
        2019-09-09 14:44:59
        mv1.com.br | LP Pré-matrícula

        641
        Juliana Rodrigues  de Mello
        julianarmello7@hotmail.com
        São Gonçalo
        (21) 97014-7127
        2019-09-09 14:45:29
        mv1.com.br | LP Pré-matrícula

        642
        Andrea Pinto Leite Ribeiro
        andreapintoleite@yahoo.com.br
        Icaraí
        (21) 9832-58871
        2019-09-09 15:27:55
        mv1.com.br | LP Pré-matrícula

        643
        Fernanda da Costa Diniz
        fernandadiniz915@gmail.com
        Icaraí
        (21) 99389-3390
        2019-09-09 16:27:17
        mv1.com.br | LP Pré-matrícula

         11/09/2019   =   5

        644
        Isabel C T Bergonzi
        isatrindadeb@gmail.com
        Tijuca
        (21) 98059-9201
        2019-09-11 07:09:13
        mv1.com.br | LP Pré-matrícula

        645
        Thais Miguel
        thais.eng@gmail.com
        Volta Redonda
        24999553326
        2019-09-11 12:52:06
        mv1.com.br | LP Pré-matrícula

        646
        Lislaine Sperandio Mendes
        lissperandio@gmail.com
        Icaraí
        (21) 98538-0528
        2019-09-11 14:42:12
        mv1.com.br | LP Pré-matrícula

        647
        Paula Lopez
        paulafrlopez@gmail.com
        Tijuca
        (21) 97281-7709
        2019-09-11 17:21:14
        mv1.com.br | LP Pré-matrícula

        648
        Talyne Mayana Ferreira Sales
        talynemayanaf@yahoo.com.br
        Ilha
        (71) 99616-8935
        2019-09-11 20:22:06
        mv1.com.br | LP Pré-matrícula

         12/09/2019   =   3

        649
        Dora
        dorenilceviegas@hotmail.com
        Ilha
        (21) 97415-8318
        2019-09-12 11:42:07
        mv1.com.br | LP Pré-matrícula

        650
        Rosimeire Parra Macedo
        dra.rosimeire.adv@bol.com.br
        Tijuca
        (21) 98170-5838
        2019-09-12 21:51:00
        mv1.com.br | LP Pré-matrícula

        651
        Rosimeire Parra Macedo
        dra.rosimeire.adv@bol.com.br
        Tijuca
        (21) 98170-5838
        2019-09-12 21:51:37
        mv1.com.br | LP Pré-matrícula

         13/09/2019   =   7

        652
        Teste Pai
        teste@teste.com.br
        Volta Redonda
        (24) 99999-9999
        2019-09-13 10:52:16
        mv1.com.br | LP Pré-matrícula

        653
        Aluno Teste Setembro
        aluno@aluno.com.br
        Volta Redonda
        (24) 12345-6789
        2019-09-13 11:51:36
        mv1.com.br | LP Pré-matrícula

        654
        Davi Teodoro Pereira
        daviteo@gmail.com
        Volta Redonda
        (24) 99831-3816
        2019-09-13 11:53:12
        mv1.com.br | LP Pré-matrícula

        655
        Luciana Barcellos de Paula Motta
        lubarpa45@gmail.com
        Volta Redonda
        (24) 99257-9444
        2019-09-13 15:29:24
        mv1.com.br | LP Pré-matrícula

        656
        Narciso Felicio de Lima Junior
        narcisojr.rj@gmail.com
        Ilha
        (21) 98082-0991
        2019-09-13 17:45:48
        mv1.com.br | LP Pré-matrícula

        657
        Leonardo Mendes Santiago
        lmsantiago@hotmail.com
        Tijuca
        (21) 98292-5932
        2019-09-13 20:58:53
        mv1.com.br | LP Pré-matrícula

        658
        Juan Filgueiras
        j.phelipe@bol.com.br
        Tijuca
        21967796737
        2019-09-13 23:37:10
        mv1.com.br | LP Pré-matrícula

         14/09/2019   =   2

        659
        Patrícia de Abreu Cândido
        patriciapclaudio@yahoo.com.br
        Volta Redonda
        (24) 97401-5585
        2019-09-14 17:02:54
        mv1.com.br | LP Pré-matrícula

        660
        Lucia de Figueiredo Souza Rodrigues
        lucia.naturalmenteorganicos@gmail.com
        Tijuca
        (21) 97681-6929
        2019-09-14 21:41:49
        mv1.com.br | LP Pré-matrícula

         15/09/2019   =   2

        661
        Karine Conceição da Costa
        karineconceicaodacosta@gmail.com
        Tijuca
        (21) 97022-0975
        2019-09-15 21:32:18
        mv1.com.br | LP Pré-matrícula

        662
        Karine Conceição da Costa
        karineconceicaodacosta@gmail.com
        Tijuca
        (21) 97022-0975
        2019-09-15 21:34:03
        mv1.com.br | LP Pré-matrícula

         16/09/2019   =   7

        663
        Ferbando António Orlando da Rocha
        rocha.fer@uol.com.br
        Volta Redonda
        (24) 99215-8008
        2019-09-16 11:56:38
        mv1.com.br | LP Pré-matrícula

        664
        Ferbando António Orlando da Rocha
        rocha.fer@uol.com.br
        Volta Redonda
        (24) 99215-8008
        2019-09-16 11:57:41
        mv1.com.br | LP Pré-matrícula

        665
        Mariana Leao
        maryleao@yahoo.com
        Tijuca
        (21) 98272-7716
        2019-09-16 13:42:48
        mv1.com.br | LP Pré-matrícula

        666
        Priscilla Cruz
        priscillacruz18@hotmail.com
        Tijuca
        (21) 96913-3837
        2019-09-16 14:37:31
        mv1.com.br | LP Pré-matrícula

        667
        Flavio da Cruz Lima
        flaviocruz0403@gmail.com
        Icaraí
        (71) 99984-4516
        2019-09-16 14:43:51
        mv1.com.br | LP Pré-matrícula

        668
        Flavio da Cruz Lima
        flaviocruz0403@gmail.com
        Icaraí
        (71) 99984-4516
        2019-09-16 14:44:29
        mv1.com.br | LP Pré-matrícula

        669
        Adelcio Lara de Resende
        adelciolara@gmail.com
        Icaraí
        (31) 98801-0454
        2019-09-16 16:13:05
        mv1.com.br | LP Pré-matrícula

         17/09/2019   =   11

        670
        Juliana Silva
        juliana_jubi@yahoo.com.br
        Tijuca
        (21) 99389-2663
        2019-09-17 09:25:23
        mv1.com.br | LP Pré-matrícula

        671
        Ana Paula Araujo A. Vieira
        anapvieira@hotmail.com
        Icaraí
        (21) 9791-25083
        2019-09-17 12:39:01
        mv1.com.br | LP Pré-matrícula

        672
        Sheila da Silva Amaral
        sheilas1@uol.com.br
        Icaraí
        (21) 98331-5005
        2019-09-17 13:16:46
        mv1.com.br | LP Pré-matrícula

        673
        Fernando Oliveira Pinto
        fernanop@bol.com.br
        Volta Redonda
        (24) 9817-41423
        2019-09-17 15:31:34
        mv1.com.br | LP Pré-matrícula

        674
        Rondinele Santos Andrade
        rondmg@yahoo.com.br
        São Gonçalo
        (21) 99691-0618
        2019-09-17 15:31:49
        mv1.com.br | LP Pré-matrícula

        675
        Lorena Ribeiro Molinaro
        loreneventoskids01@gmail.com
        Icaraí
        (21) 99115-0506
        2019-09-17 15:34:38
        mv1.com.br | LP Pré-matrícula

        676
        Luzivanda Almeida de Oliveira
        luzioliveiray@gmail.com
        Ilha
        (21) 98881-6044
        2019-09-17 15:38:34
        mv1.com.br | LP Pré-matrícula

        677
        William Alves Ferreira
        williamjunior1210@gmail.com
        Tijuca
        (24) 99843-0984
        2019-09-17 17:08:34
        mv1.com.br | LP Pré-matrícula

        678
        Elismar Batista Duarte
        elis.tuquinha@gmail.com
        Ilha
        (21) 99568-0934
        2019-09-17 19:05:56
        mv1.com.br | LP Pré-matrícula

        679
        Marcelo de Souza Mendonça
        mds.mendonca.vr@gmail.com
        Volta Redonda
        (24) 3350-0532
        2019-09-17 21:50:21
        mv1.com.br | LP Pré-matrícula

        680
        Marcelo Braga
        braga.marcelobraga@gmail.com
        Ilha
        (21) 98686-1207
        2019-09-17 22:04:08
        mv1.com.br | LP Pré-matrícula

         18/09/2019   =   4

        681
        Diane Cunha Gonçalves
        dianegoncalves@yahoo.com
        Volta Redonda
        (24) 99237-7926
        2019-09-18 12:08:46
        mv1.com.br | LP Pré-matrícula

        682
        Lucilene
        lucilene.gayani@gmail.com
        Tijuca
        (21) 98371-4577
        2019-09-18 14:07:57
        mv1.com.br | LP Pré-matrícula

        683
        Nathalia Lameira Lisboa
        natlisboaa@yahoo.com.br
        Icaraí
        (21) 98077-1729
        2019-09-18 17:41:00
        mv1.com.br | LP Pré-matrícula

        684
        Sergio Guimarães Soares
        soaresttai@gmail.com
        São Gonçalo
        (21) 97349-0967
        2019-09-18 21:36:16
        mv1.com.br | LP Pré-matrícula

         19/09/2019   =   4

        685
        Neuza Maria Gomes Leao
        nmgleao@gmail.com
        Tijuca
        (21) 99266-0311
        2019-09-19 10:30:48
        mv1.com.br | LP Pré-matrícula

        686
        Deyse Sant Anna dos Santos
        deyse.uerj@gmail.com
        São Gonçalo
        (21) 98825-6713
        2019-09-19 15:30:41
        mv1.com.br | LP Pré-matrícula

        687
        Staffony Katry Fonseca dos Santos
        staffony@gmail.com
        São Gonçalo
        (21) 99096-3737
        2019-09-19 19:11:35
        mv1.com.br | LP Pré-matrícula

        688
        Marcia Loredo Pereira
        aicrammlp@hotmail.com
        Ilha
        (21) 98341-8920
        2019-09-19 22:56:15
        mv1.com.br | LP Pré-matrícula

         20/09/2019   =   3

        689
        Juliana
        jullyvicente@hotmail.com
        São Gonçalo
        (21) 98400-9468
        2019-09-20 16:18:48
        mv1.com.br | LP Pré-matrícula

        690
        Mariana Pinto Vieira Souto
        marianadt7@gmail.com
        Volta Redonda
        (22) 99787-4749
        2019-09-20 19:54:40
        mv1.com.br | LP Pré-matrícula

CÓDIGO PHP ABAIXO:
<?php

if(isset($_POST['dadosExcel']) && $_POST['dadosExcel'] != ''){

    $nomeTabela = $_POST['origem'];

    $tabela = $_POST['dadosExcel'];

    $arquivo = $nomeTabela . '.xls';

    header('Content-Type: application/x-msexcel');
    header('Content-type: application/force-download');
    header("Content-Disposition: attachment; filename=\"{$arquivo}\"");
    header("Content-Description: PHP Generated Data" );

    /*header("Content-type: application/vnd.ms-excel");
    header("Content-type: application/force-download");
    header("Content-Disposition: attachment; filename=$arquivo.xls");
    header("Pragma: no-cache");*/

    echo $arquivo;
    echo $tabela;

}else{
    echo "Não possivel completar a exportação!";
}

*** Algumas soluções que eu tentei foi chamar o arquivo no topo do documento antes de qualquer html, o que não funcionou.

A: Salve o código abaixo com a extensão XLS:

                1
                2

                3
                4

Para a exportação, use o Data URI, que permite adicionar dados nem um endereço.
Monte este código e coloque na tabela um id:

        Página Exemplo

        th > td {
            font-weight: bold;
        }

        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin quis blandit ante. Ut nec urna luctus, sodales purus sagittis, convallis orci. Cras non tincidunt augue.
Duis tempor est non tortor placerat, sed malesuada tellus rhoncus. Suspendisse quis ligula ut magna finibus luctus. Integer sollicitudin lectus non erat imperdiet, id suscipit eros ultricies. Morbi vel congue neque. Curabitur varius nibh nec purus cursus ullamcorper.

                    Janeiro
                    Fevereiro
                    Março
                    Abril
                    Maio
                    Junho

                    Valor
                    123.45
                    567.89
                    901.23
                    456.78
                    234.56
                    789.01

                    Valor
                    901.45
                    456.62
                    234.94
                    478.91
                    870.11
                    123.67

        Salva Planilha

        function salvaPlanilha() {

    }
</script>

crie um Data URI com base na tabela, isole o código da tabela:
function salvaPlanilha() {
    var htmlPlanilha = "" + document.getElementById("tabela").innerHTML + "";
}
coloque as informações num endereço
function salvaPlanilha() {
    var htmlPlanilha = "" + document.getElementById("tabela").innerHTML + "";
var htmlBase64 = btoa(htmlPlanilha);

}
una as duas primeiras informações
function salvaPlanilha() {
    var htmlPlanilha = "" + document.getElementById("tabela").innerHTML + "";
var htmlBase64 = btoa(htmlPlanilha);
var link = "data:application/vnd.ms-excel;base64," + htmlBase64;

}
para o navegador baixar o arquivo basta forçar o acesso ao endereço
function salvaPlanilha() {
    var htmlPlanilha = "" + document.getElementById("tabela").innerHTML + "";
var htmlBase64 = btoa(htmlPlanilha);
var link = "data:application/vnd.ms-excel;base64," + htmlBase64;

window.open(link);

}


text:
Q: How do I set the image when pulling data from another data file in react native? Actually, I prepared this data and koala.png does not show up. But the other picture I took from the website looks. how can I fix this?

    export default [
        {
            "unit": "Letters",
            "a": 0,
            "picture": "../src/img/koala.png",
        },
        {
            "unit": "Numbers",
            "a": 1
        "picture": "https://randomuser.me/api/portraits/men/1.jpg",
        },

    ];

A: Use this way if the local image
 export default [
        {
            "unit": "Letters",
            "a": 0,
            "picture": require('./assets/images/photo1.jpg'), // like this
        },
        {
            "unit": "Numbers",
            "a": 1
        "picture": "https://randomuser.me/api/portraits/men/1.jpg",
        },

];

<Image source={item.picture} />

redpajama_set_name: RedPajamaStackExchange


text:
Q: Tomcat returning 403 - forbidden error On apache-tomcat-7.0.55/ubuntu 12.04 behind apache2 mod ajk.
I am noticing a strange problem - tomcat is returning 403 status code for some files. This application is not under any kind authentication/authorization. As a matter of fact, this application is our static resources such as javascript/css and images.
As far as I can see in the logs tomcat randomly returns 403 when accessing fonts (.ttf, .woff files). If I copy the request from chrome (copy as curl) and try it using curl, I do get proper file back with 200, but in chrome it shows 403 error randomly. Copy as curl in chorme provides the headers that chrome had used to access the resoure. Any other files in the same application do not get 403 errors at all.
I have checked tomcat mime type and it looks ok. Its random (at least so far I don't know the reason) 403 that worries me as tomcat does serve the file sometimes and returns 403 other times.
Any ideas what can be happening?

A: This is an old question, but I use ubuntu and apache2 and normally with 403 file permission errors coming my server/localhost it's because, while the files may have the correct permissions, the directories that the files are in may not, or vice-versa.
Usually in terminal I type ls -l to see the permissions and then chmod 755 [file or directory] to turn on read/execute permissions.


text:
Q: Error when trying to install mysql server in ubuntu server 12.04 LTS I try to reinstall mysql server in my ubuntu 12.04 LTS server and I get always the same error.
Configuring mysql-server-5.5
Unable to set password for the MySQL "root" user
An error occurred while setting the password for the MySQL administrative user. This may have happened because the account already has a password, or because of a communication problem with the MySQL server.
                                                                                You should check the account's password after the package installation.
                                                                                Please read the /usr/share/doc/mysql-server-5.5/README.Debian file for more information.
PLEASE FIND ATTACHED the screen shot in the link:
screenshot
I searched a lot in all forums for similar cases and I followed all recommended commands without success.
Does anybody have an idea how can I solve this?

A: You seem to have a permissions error, try completely removing and then reinstalling
sudo apt-get remove --purge mysql-server

sudo apt-get install mysql-server && apt-get upgrade

Here is the documentation for mysql on ubuntu LINK


text:
Q: Localtunnel: Unable to register tunnel. Perhaps service is down? I tried running localtunnel with this command:
localtunnel 3000

and got this error:
[Error] Unable to register tunnel. Perhaps service is down?

Is the service down or is there something I can do to fix it?

A: localtunnel has been down for a while now

*

*https://github.com/progrium/localtunnel/issues/105

*https://github.com/progrium/localtunnel/issues/98
Try ngrok as an atlernative

A: Use similar service which works:
https://pagekite.net


text:
Q: Extracting empty arrays with akka and circe? I have a project in akka and circe.  I am currently sending this json in the response body:
{ "a": 33, "things": [{ "id1": ["2"], "id2": [], "id4": [], "id5": [] } ] }

I am trying to extract it to this case class:
  case class Body(things: Option[List[Things]])
  case class Things(id1: Option[List[String]] = None, id2: Option[List[String]] = None, id3: Option[List[String]] = None, id4:Option[List[String]] = None)

I am doing this using this code :
  entity(as[Body]).as(Body.getIds)

This code relies on the below companion object
  object Body extends ErrorAccumulatingCirceSupport {

    def getIds(body: Body): List[String] =
      body.things.get.flatMap(_.id4.getOrElse(List()))
    }

However, unless I actually pass in a value in the objects within the things array (e.g. "id2": [ "33"])
It never finishes unmarshalling the json.  Grateful for any advice!


text:
Q: Delete p tag inside
* tags xslt 1 I need to remove
 tags inside
 tags.
Example:

  WHAT IS CARRER DEVELOPMENT PLAIN ?

Desired output:

 WHAT IS CARRER DEVELOPMENT PLAIN ?

Thanks in advance.

A: You can use the following XSLT-1.0 template. The Identity Template just copies all elements as they are. The second template does essentially the same, but without copying the current element (here only for the
 element).
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
  <xsl:output method="xml" indent="yes" omit-xml-declaration="yes"/>

  <xsl:template match="node()|@*">
    <xsl:copy>
      <xsl:apply-templates select="node()|@*"/>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="p[ancestor::li]">
      <xsl:apply-templates select="@*|node()"/>
  </xsl:template>

</xsl:stylesheet>

If you also want to remove the spaces/prettify the output, then add the following line at the top-level (just after xsl:stylesheet):
<xsl:strip-space elements="*" />


text:
Q: Show protocols of packets captured and saved in a .pcap with scapy on python I am capturing live air WiFi traffic and saving only the headers of the packets captures in a .pcap file.
Is it possible to find out what protocols have been used on the whole capture? If yes, how can I keep track of the number of packets under every protocol found?
I've found a lot of info on injecting packets with Scapy but not on analyzing.
So far I've tried:
from scapy.all import * # import scapy package
from scapy.utils import rdpcap # import module for loading pcaps
pkts = rdpcap("./traffic/capture20131120-001.pcap") # load pcap
pkts.summary(lambda(r): r.sprintf("%Dot11.proto%")) # protocol?
print -(256-ord(pkts[24].notdecoded[-4:-3])) # signal strength of packet 24

Seems like pkts.summary(lambda(r): r.sprintf("%Dot11.proto%")) returns 0L and I don't understand that.

A: Currently, Scapy does not support very many protocols, so it's great for some tasks, but not others. Using pyshark instead (a Python wrapper for Wireshark), there are many more supported protocols.

Using Scapy:
from scapy.all import *

def process_with_scapy(fileName):
    protocol_count = {}

    pcap_data = rdpcap(fileName)
    sessions = pcap_data.sessions()
    for session in sessions:
        for packet in sessions[session]:
            for i in range(len(packet.layers())):
                layer = packet.getlayer(i)
                protocol = layer.name

                # Count the number of occurences for each protocol type
                if protocol not in protocol_count: protocol_count[protocol] = 1
                else: protocol_count[protocol] += 1

    # Sort the dictionary in descending order
    protocol_count = dict(sorted(protocol_count.items(), key=lambda item: item[1], reverse=True))

    # Print the output
    for protocol in protocol_count:
        print(f'{protocol_count[protocol]} packets have layer "{protocol}"')

process_with_scapy('./traffic/capture20131120-001.pcap')

Documentation:
https://readthedocs.org/projects/scapy/downloads/pdf/latest

Using PyShark (slower but more supported):
import pyshark

def process_with_pyshark(fileName):
    protocol_count = {}

    pcap_data = pyshark.FileCapture(fileName)
    for packet in pcap_data:
        for layer in packet:
            protocol = layer.layer_name

            # Count the number of occurences for each protocol type
            if protocol not in protocol_count: protocol_count[protocol] = 1
            else: protocol_count[protocol] += 1

    # Sort the dictionary in descending order
    protocol_count = dict(sorted(protocol_count.items(), key=lambda item: item[1], reverse=True))

    # Print the output
    for protocol in protocol_count:
        print(f'{protocol_count[protocol]} packets have layer "{protocol}"')

process_with_pyshark('./traffic/capture20131120-001.pcap')

*

*For information on a specific protocol:
https://www.wireshark.org/docs/dfref/

*The source code for a specific protocol dissector can also sometimes be useful:
https://github.com/wireshark/wireshark/tree/master/epan/dissectors


text:
Q: Is There an Overkill on Bribes? I'm looking at the Final Fantasy X bribes bestiary.

Each bribe amount is followed by parenthesis. What does that mean?
For example, the Chimera Brain's bribe field reads:
196,000 Lv. 4 Key Sphere x 1(2)
Is there an Overkill for bribes or something? I just keep getting 1 every time I try.

A: Bribes appear to have a minimum value, and a maximum value. As found in this thread, the rewards can range between 50% and 150%. When working with small values, like 1 or 2 items, this is rounded by the game. So, in your example, this would mean that 1 is the minimum value, and (2) is the maximum value.
Furthermore, there's some speculation that bribing can even succeed with a lower amount than listed, but with a much lower chance. I haven't much experience in regards to this myself, though.

A: Bribe doesn't overkill, if they accept the bribe the enemy simply leaves the fight.
To prove this you can go to some enemies in the early game after you get the airship and save, then bribe an enemy using all your money, it still just simply succeeds - no overkill.
More money does mean more of the item, but it depends on how much you give and what item you're getting, my advice would be to save scrub it, and work out what the best figure is for the item you are trying to accumulate.


text:
Q: Xcode 8 random command failed due to signal segmentation fault 11 I have a strange problem with the new Xcode 8 (no beta version) and swift3.
Once every other 3-4 times that I compile my code I get a 'command failed due to signal segmentation fault 11' error. I just need to enter new empty line, or sometimes changing some spaces, or add a comment (everywhere in the code) and the error disappears and I can compile again.
This is really strange because I'm not changing anything in the code! And sometimes I can compile and it works, then I don't change anything, I compile again and I get the error.
This is really annoying!
I have noticed this is happening since I have installed several 'Firebase' pods (Firebase, Firebase/Auth etc...). But I need them.
Anyone has any suggestion?
PS: I have set the Enable Bitcode of my project to No as many solution suggested, but nothing. In the error message it is not indicated any swift page where the error can be, an example is:

*

*While loading members for 'Class_name' at

*While deserializing 'func_name' (FuncDecl #42)

'func_name' is this one:
public class func loginUser(fir_user: FIRUser) {
    let user = SFUser()
    user.email = fir_user.email
    user.isLogged = true
    try! sfRealm.write() {
        sfRealm.add(user, update:true)
    }

    var userToAdd = [String:AnyObject]()
    userToAdd["email"] = fir_user.email! as NSString

    let ref=FIRDatabase.database().reference()
    let usersRef = ref.child(childName)
    usersRef.setValue([key:value])
}

But then, as I said, I can just enter an empty row in another file and it compiles!
Thanks

A: I have the same issue i just figure out that i was using xcode 8.1 and the project's working copy was in xcode 8.2.1 so i just re install xcode 8.2.1 and problem got solved. Hope other can get the help trough this.

A: Ok, it seems that I have found the solution: it is a problem with Firebase and cocoapods, so 2 solutions:
Download Firebase and import into your project
I, instead, updated cocoapods to the last version and it worked. Upgraded Firebase - Now Getting Swift Compile Error

A: In my case there was some type checking issue deep down the compiler so the editor didn't give error in the gutter but on building the project I was getting signal setmentation fault 11 error:
1.  While type-checking 'GetStoreAPIRequestModel' at /Users/.../StoreAPIModel.swift:9:1
2.  While type-checking expression at [/Users/.../StoreAPIModel.swift:15:18 - line:15:31] RangeText="[Dictionary]()"
3.  While resolving type [Dictionary] at [/Users/.../StoreAPIModel.swift:15:18 - line:15:29] RangeText="[Dictionary]"

So I changed my code from:
var stores = [Dictionary]() {
        willSet {
            allStores.removeAll()

            for model in newValue {
                allStores.append(StoreAPIModel(dictionary: model as! Dictionary).getModel())
            }
        }
    }

To (more descriptive dictionary):
var stores = [[String : Any]]() {
        willSet {
            allStores.removeAll()

            for model in newValue {
                allStores.append(StoreAPIModel(dictionary: model as [String : AnyObject]).getModel())
            }
        }
    }

A: This is tricky problem. Issue can be with line of code or syntax. I was getting similar error and it was due to incorrect usage of dictionary. I was trying to increment the value of dictionary element.
Solution is to triage the code, detailed error provide which module has issue, so try commenting part of code until you find the line which is causing the issue.

A: Hi i had the same issue with FireBase , my problem was that i was extending FIRStorageReference and FIRDatabaseReference and some time it compile successfully some time i get

command failed due to signal segmentation fault 11

so i removed that files and implement the method other way , now everything works fine.

A: Found my problem when this occurred. (No cocoapods.) I thought I had left the program in a working state, but I was wrong. I am writing a straightforward command-line program. What it does is somewhat general, so I defined all the strings that make it specific in let statements at the top of the program so that I could someday use the program in a different context.
Since that was working so well, I thought I'd be clever and do the same with a filter of an array of dictionaries. I turned:
list.filter { $0["SearchStrings"] == nil }

into:
let test = { $0["SearchStrings"] == nil }
// ...
list.filter(test)

meaning to continue working on the let, but I never went back and did that. Building gave me the segmentation fault error. Defining test as a function fixed the problem.
(Incidentally, I understand how to strip a filtering function down to the terse braces notation in the context of the call to Array.filter, and why that works, but I don't understand why I can't assign the brace expression to a constant and use it as such.)


text:
Q: Configure amplify-flutter for existing User pool without Cognito Identity pool How to configure aws amplify in flutter for an existing user pool? There is no identity pool configured for this user pool. I want to configure it without creating an identity pool. Following is my current amplifyconfiguration.dart file,
const amplifyConfig = ''' {
  "UserAgent": "aws-amplify-cli/2.0",
  "Version": "1.0",
  "auth": {
      "plugins": {
          "awsCognitoAuthPlugin": {
              "IdentityManager": {
                  "Default": {

                  }
              },
              "CognitoUserPool": {
                  "Default": {
                      "PoolId": "**********",
                      "AppClientId": "**********",
                      "Region": "**********"
                  }
              },
              "Auth": {
                  "Default": {
                      "authenticationFlowType": "USER_SRP_AUTH"
                  }
              }
          }
      }
  }
}''';

Every time I try to signIn I get this error with above config,
Amplify.Auth.signIn(
      username: 'test@gmail.com',
      password: 'test'
    );

java.lang.Exception: Federation is not enabled, please check if you have CognitoIdentity configured.

How can I fix this without using a identity pool?


text:
Q: How to get kendo ui grid sort event? I currently have a Kendo-UI grid.  It has a few column where user can sort on, works great.  I also have a details link on each row, so if the user clicks on this they are taken to a details page.  I need to pass the current sort into the details page as a value. How can I get the current sort? is there an event I can bind to?
Thanks

A: You can get the sorting configuration whenever you want using sort method.
Example: Being grid the id of your Grid. Do:
// Get the grid object
var grid = $("#grid").data("kendoGrid");
// Get the datasource bound to the grid
var ds = grid.dataSource;
// Get current sorting
var sort = ds.sort();
// Display sorting fields and direction
if (sort) {
    for (var i = 0; i < sort.length; i++) {
        alert ("Field:" + sort[i].field + " direction:" + sort[i].dir);
    }
} else {
    alert("no sorting");
}

A: I ran into this need today and learned that the event is now present as of  2016 R3 release (2016.3.914).
Example usage:

See: http://docs.telerik.com/kendo-ui/api/javascript/ui/grid#events-sort


text:
Q: Can't show popover controller with UIBarButtonItem i use storyboard for developing UI for my project. There are many issues were solved, but this problem killing me. I have added action for UIBarButtonItem :
- (IBAction)pressAddActionButton:(UIBarButtonItem *)sender {
if (_mode == itemSelect) {

    LookUpTableViewController *vc =  [self.storyboard instantiateViewControllerWithIdentifier:@"lookupTable"];
    vc.key = @"title";
    vc.data = [Linesheet MR_findAllSortedBy:@"title" ascending:YES];
    vc.lookUpDelegate = self;

    self.myPopoverController = [[UIPopoverController alloc] initWithContentViewController:vc];
    [self.myPopoverController presentPopoverFromBarButtonItem:sender permittedArrowDirections:UIPopoverArrowDirectionUp animated:YES];
} else {
    self.mode = itemSelect;
}

}
If i using storyBoard segue for showing popover - all good, but if i do it in runtime a popover does not show. I should manually create UIBarButtonItem.
Thanks for help!!!
Update, code for buttons:
- (void)setupNavigationItems {

    self.navigationController.navigationBarHidden = NO;

    UIBarButtonItem *addItem;
    if (_mode == itemSelect) {
        addItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd
                                                                target:self
                                                                action:@selector(pressAddActionButton:)];
    } else {
        addItem = [[UIBarButtonItem alloc] initWithTitle:@"Done" style:UIBarButtonItemStyleDone
                                                  target:self
                                                  action:@selector(pressDoneButton:)];
    }
    [addItem setStyle:UIBarButtonItemStyleBordered];

    UIBarButtonItem *separator = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace
                                                                               target:self
                                                                               action:nil];

    UIBarButtonItem *action = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAction
                                                                            target:self
                                                                            action:@selector(pressActionButton:)];
    [action setStyle:UIBarButtonItemStyleBordered];

    [toolbar setItems:[NSArray arrayWithObjects:separator, addItem, action, nil] animated:YES];
}

A: Make sure you're hitting the code as you expect using a breakpoint on the presentPopoverFromBarButtonItem line. Also, make sure that the myPopoverController property is declared strong if you're using arc, as otherwise it will be nil before the presenting line.

A: The code is right.  Try replacing the sender with self.navigationItem.leftBarButtonItem or self.navigationItem.rightBarButtonItem. The sender may not be what you are expecting.
Also remove the if (_mode == itemSelect) clause for testing I'm  not sure why you need to access the ivar _mode ivar directly.

A: Did you check if LookUpTableViewController *vc actually gets a proper instance? If not then check that your storyboard does have @"lookupTable" set as your controller's identifier.


text:
Q: Ever-present RoutingErrors for javascript/workbox/ files in Rails 5 + React app Specs:  Rails 5.2, Ruby 2.5.1, Yarn 1.91.1, React-Rails 2.6.0, Postgresql 10, Ubuntu 18.04
Issue: Getting these ever present error messages in my logs after I set up a rails app with react.  The errors are all looking for routes for javascript/workbox/ files once I start the server with rails s

Started GET "/service-worker.js" for 127.0.0.1 at 2019-11-14 09:28:15 -0700
  Started GET "/javascripts/workbox/workbox-sw.js" for 127.0.0.1 at 2019-11-14 09:28:15 -0700
  Started GET
  "/javascripts/workbox/workbox-expiration.prod.js" for 127.0.0.1 at
  2019-11-14 09:28:15 -0700
  Started GET
  "/javascripts/workbox/workbox-core.prod.js" for 127.0.0.1 at
  2019-11-14 09:28:15 -0700
  Started GET
  "/javascripts/workbox/workbox-strategies.prod.js" for 127.0.0.1 at
  2019-11-14 09:28:15 -0700
ActionController::RoutingError (No route matches [GET] "/service-worker.js"):

Notice the errors begin on the last line and will continue from there for each of those GET requests.
What I did:  I followed instructions from multiple sources (Here's 1 and another) telling me to do basically the same thing.  I ran rails new app --database=postgresql --webpack=react which runs normally.  Then I add the gem react-rails to my gemfile and bundle install again.  I next run rails generate react:install and everything seems fine except for a few warnings.  Here are some of the warnings, I don't know if these are causing the issue or not.

warning " > @babel/preset-react@7.7.0" has unmet peer dependency
  "@babel/core@^7.0.0-0".
  warning
  "@babel/preset-react >
  @babel/plugin-transform-react-display-name@7.2.0" has unmet peer
  dependency "@babel/core@^7.0.0-0".
  warning "@babel/preset-react >
  @babel/plugin-transform-react-jsx@7.7.0" has unmet peer dependency
  "@babel/core@^7.0.0-0".
  warning "@babel/preset-react >
  @babel/plugin-transform-react-jsx-self@7.2.0" has unmet peer
  dependency "@babel/core@^7.0.0-0".
  warning "@babel/preset-react >
  @babel/plugin-transform-react-jsx-source@7.5.0" has unmet peer
  dependency "@babel/core@^7.0.0-0".
  warning "@babel/preset-react >
  @babel/plugin-transform-react-jsx > @babel/plugin-syntax-jsx@7.2.0"
  has unmet peer dependency "@babel/core@^7.0.0-0".
  warning " >
  webpack-dev-server@3.9.0" has unmet peer dependency "webpack@^4.0.0".
  warning "webpack-dev-server > webpack-dev-middleware@3.7.2" has unmet
  peer dependency "webpack@^4.0.0".

Not sure if those warnings matter or if there is another reason that my app isn't setting up Workbox properly.
React itself is working.  The default Hello world rails app works fine.  It is just the constant failed GET requests to Workbox files that is causing me grieve.


text:
Q: How make Custom Processor follow failure relationship A newbie question.
I presume that the flow from a Processor will follow a failure relationship if there is some failure in processing the FlowFile ?
If I have a custom Processor and I want the failure relationship to be followed, eg if an Oauth token does not contain a valid role, how do I do this in the code ? Do I just throw an exception from the onTrigger method, and if so, does it need to be any particular exception ?
Thanks very much in advance.
pxm

A: There are basically two ways to handle an error...
1) Throw an exception out of onTrigger - this rolls back the session for the given execution of onTigger, which puts any flow files back in the incoming queue to be tried again.
2) Transfer a flow file to a failure relationship - you have to handle this yourself by catching any expected errors and transferring the flow file to the desired relationship, the same as you would for transferring to success.


text:
Q: Workfront: Forcing project 'Recalculate Finance' operation from API I bet this falls on deft ears...
I'm working on a application that uses the workfront api for automating custom price calculations of project tasks.
The idea here is to obtain the list of tasks, apply certain business rules to each to calculate the pricing/revenue/etc., and then push these values back to the tasks in the respected workfront project.
Problem is, when you now open the project directly in workfront, the changes from this interaction are present until you perform a manual:

while what I would prefer is this is done already without having to do this since the user would not have any reason to believe it was necessary (they didn't make any manual changes to the tasks through workfront directly, why would they think otherwise?).
Some time ago I stumbled on a hint that toggling the project to "Current" will force the recalc, but I've done this through the API (I save the original state, change it to "CUR" and toggle it back to the original state since I can't leave it a "CUR") but this has no effect.
Any ideas on how I might be able to force this behavior?

A: It did indeed fall on deft ears.
PUT https://[base_url].my.workfront.com/attask/api/v9.0/proj/[UUID]?action=calculateFinance&apiKey=[api_key]


text:
Q: Reporting parse errors from PLY to caller of parser So I've implemented a parser using PLY — but all the PLY documentation deals with parse and tokenization errors by printing out error messages. I'm wondering what the best way to implement non-fatal error-reporting is, at an API level, to the caller of the parser. Obviously the "non-fatal" restriction means exceptions are out — and it feels like I'd be misusing the warnings module for parse errors. Suggestions?

A: PLY has a t_error() function that you can override in your parser to do whatever you want. The example provided in the documentation prints out an error message and skips the offending character - but you could just as easily update a list of encountered parsing failures, have a threshold that stops after X amount of failures, etc. - http://www.dabeaz.com/ply/ply.html

4.9 Error handling
Finally, the t_error() function is used to handle lexing errors that
  occur when illegal characters are detected. In this case, the t.value
  attribute contains the rest of the input string that has not been
  tokenized. In the example, the error function was defined as follows:

# Error handling rule
def t_error(t):
    print "Illegal character '%s'" % t.value[0]
    t.lexer.skip(1)

You can utilize this by making your parser a class and storing error state within it - this is a very crude example since you'd have to make multiple MyLexer instances, then build() them, then utilize them for parsing if you wanted multiple lexers running concurrently.
You could marry the error storage to the __hash__ of the lexer instance itself to only have to build once. I'm hazy on the details of running multiple lexer instances within one class, but really this is just to give a rough example of how you can capture and report non-fatal errors.
I've modified the simple calculator class example from Ply's documentation for this purpose.
#!/usr/bin/python

import ply.lex as lex

class MyLexer:

    errors = []

    # List of token names.   This is always required
    tokens = (
       'NUMBER',
       'PLUS',
       'MINUS',
       'TIMES',
       'DIVIDE',
       'LPAREN',
       'RPAREN',
    )

    # Regular expression rules for simple tokens
    t_PLUS    = r'\+'
    t_MINUS   = r'-'
    t_TIMES   = r'\*'
    t_DIVIDE  = r'/'
    t_LPAREN  = r'\('
    t_RPAREN  = r'\)'

    # A regular expression rule with some action code
    # Note addition of self parameter since we're in a class
    def t_NUMBER(self,t):
        r'\d+'
        t.value = int(t.value)
        return t

    # Define a rule so we can track line numbers
    def t_newline(self,t):
        r'\n+'
        t.lexer.lineno += len(t.value)

    # A string containing ignored characters (spaces and tabs)
    t_ignore  = ' \t'

    # Error handling rule
    def t_error(self,t):
        self.errors.append("Illegal character '%s'" % t.value[0])
        t.lexer.skip(1)

    # Build the lexer
    def build(self,**kwargs):
        self.errors = []
        self.lexer = lex.lex(module=self, **kwargs)

    # Test it output
    def test(self,data):
        self.errors = []
        self.lexer.input(data)
        while True:
             tok = self.lexer.token()
             if not tok: break
             print tok

    def report(self):
        return self.errors

Usage:
# Build the lexer and try it out
m = MyLexer()
m.build()           # Build the lexer
m.test("3 + 4 + 5")     # Test it
print m.report()
m.test("3 + A + B")
print m.report()

Output:
LexToken(NUMBER,3,1,0)
LexToken(PLUS,'+',1,2)
LexToken(NUMBER,4,1,4)
LexToken(PLUS,'+',1,6)
LexToken(NUMBER,5,1,8)
[]
LexToken(NUMBER,3,1,0)
LexToken(PLUS,'+',1,2)
LexToken(PLUS,'+',1,6)
["Illegal character 'A'", "Illegal character 'B'"]

A: Check out section 9.2:

9.2 Run-time Debugging
To enable run-time debugging of a parser, use the debug option to parse. This option can either be an integer (which simply turns debugging on or off) or an instance of a logger object. For example:
log = logging.getLogger()
parser.parse(input,debug=log)

If a logging object is passed, you can use its filtering level to control how much output gets generated. The INFO level is used to produce information about rule reductions. The DEBUG level will show information about the parsing stack, token shifts, and other details. The ERROR level shows information related to parsing errors.

The logging module is part of CPython's standard library.


text:
Q: Who gets the correct solution check? I submitted a question on Stack Overflow and when I went back to check answers I saw two. I immediately saw two answers, but the first one which happens to be more detailed and a better explanation (to some degree).
I checked that one as the correct solution. I saw the other person's solution, and it is also correct. He commented to me that he was first.
I want to clarify in a thread where there are multiple right answers. Should whomever's first get the correct solution or whomever is better explained when the next person comes?
Question: jQuery-mobile popup won't appear at all

A: You accept whichever answer you want to.
You don't have to explain it.
The consensus is - the better answer should get it, but it is entirely up to you.


text:
Q: How can I avoid using a variable in a Keras Lambda layer? In my model training program, I have this fragment...
if args.thr > 0.0:
    s = layers.Lambda(lambda a: a / args.thr)(s)
    s = layers.Lambda(lambda a: a / (1.0+a*a))(s)
    u = layers.Subtract()([x, s])

The args.thr value is set by argparse. I have a separate program that loads the model, and uses it on a set of images. As this is written, if args.thr is greater than zero, the Lambda layer is included, and it will expect a value for args.thr.
I could edit the code and write the value into the Lambda line instead of passing it as an argument. Is there some way of effectively doing the same thing from an argument? This works...
    s = eval('layers.Lambda(lambda a: a / {0:f})(s)'.format(args.thr))

It isn't very pretty: I turn the float into a string, and the string back into a float, ugh. Is there a nicer way of doing this?
PS:
If there isn't support, perhaps I shouldn't be doing it. In this case, the layer has no trainable parameters, so it is not an active part of the model. I have since managed to re-arrange things so this is handled outside of the model. Nevertheless, it worked even though it wasn't perfect.


text:
Q: Resize image on upload, not after upload? I'm uploading images with HTML and PHP.
<form action="" method="post">
    <input type="file" name="image" id="image">
</form>

How would I use imagemagick to resize the image if it is larger than 1500(width)x700(height) whichever is larger comes first, then reside the image.
As far as I looked for, imagemagick can only resize images after upload. Is it possible to resize images while upload and then store into directory/folder?

A: You can resize the temp file then save the file after it is completed.
Here is how I typically handle it.. PLEASE NOTE YOU NEED TO DO A LOT MORE WITH SECURING THIS UP! Make sure you are checking the upload allowed type, size ect..
I use this function to resize..
function img_resize($target, $newcopy, $w, $h, $ext) {
list($w_orig, $h_orig) = getimagesize($target);
$scale_ratio = $w_orig / $h_orig;
if (($w / $h) > $scale_ratio) {
    $w = $h * $scale_ratio;
} else {
    $h = $w / $scale_ratio;
}
$img = "";
$ext = strtolower($ext);
if ($ext == "gif"){
    $img = imagecreatefromgif($target);
} else if($ext =="png"){
    $img = imagecreatefrompng($target);
} else {
    $img = imagecreatefromjpeg($target);
}
$tci = imagecreatetruecolor($w, $h);
// imagecopyresampled(dst_img, src_img, dst_x, dst_y, src_x, src_y, dst_w,
dst_h, src_w, src_h)
imagecopyresampled($tci, $img, 0, 0, 0, 0, $w, $h, $w_orig, $h_orig);
imagejpeg($tci, $newcopy, 80);
}

Then I call the function with the temp file..
 $fileName = $_FILES["image"]["name"]; // The file name
 $target_file = $_FILES["image"]["tmp_name"];
 $kaboom = explode(".", $fileName); // Split file name into an array using the dot
 $fileExt = end($kaboom); // Now target the last array element to get the file extension
 $fname = $kaboom[0];
 $exten = strtolower($fileExt);

 $resized_file = "uploads/newimagename.ext"; //need to change this make sure you set the extension and file name correct.. you will want to secure things up way more than this too..
 $wmax = 1500;
 $hmax = 700;
 img_resize($target_file, $resized_file, $wmax, $hmax, $exten);


text:
Q: How to find this using Regular Expression? I thought I understood C# regular expressions, but clearly it's not the case. I need some help devising an expression that would find everything from START|BEGIN until )). Expression can be multi line.
Ex.
START( FTP_STATE, XXX(
   VAL( FTP_INITIAL_STATE, 0 )
   VAL( FTP_INBOUND,       1 )
   AL( FTP_OUTBOUND,      2 )
))

/**************************************************************/

BEGIN( FTP_TIMER_MODE, YYY(
   VAL( FTP_REMOVE_TIMER,     0 )
   VAL( FTP_NOT_REMOVE_TIMER, 1 )
))

/**************************************************************/

Any help greatly appreciated

A: Try this:
(?:START|BEGIN)(?:[^)]+|\)[^)])+\)\)

To explain it:

*

*(?:START|BEGIN)   Start with either START or BEGIN.

*(?:[^)]+|\)[^)])+    After that either any character other than a ) ([^)]+) or a ) that is followed by any character other than ) (\)[^)]) may follow. (So there is no way to match )) with this expression.)

*\)\)   Finally the )).

I hope this will reduce backtracking.

A: It is straight forward; START or BEGIN, then any number of any symbol but non greedy and finaly the two closing parenthesis. .*? takes any number of any symbol, but as few as possible. To match over more then one line the single line option (?s) must be enabled (Thanks Alan M. for pointing that out.)
(?s)(START|BEGIN).*?\)\)

A: Actually you need to account for the VAL( ... )'s as well.
In perl it would be:
(BEGIN|START)\([^(\)\)\))].+\)\)\)

*

*Starts with BEGIN or START

*Has a opening bracket

*Allows anything NOT ))) in between, to avoid greedy matching

*Ends with three closing brackets )))

A: @"(?s)(?:START|BEGIN).*?\)\)"

What some of the others are calling "multiline mode" is actually single-line (or DOTALL) mode. That's the mode that lets the dot match newlines.  Multiline mode lets '^' match the beginning of a line '$' match the end of a line (normally, the only match the start and end of the whole string. I'm using DOTALL mode with the inline modifier "(?s)".

A: I don't know the syntax for C#, but in Perl it's:
m/(BEGIN|START).*?\)\)/s

The s makes it multiline.
You just have to see how to make the regex multiline in C#

A: If you don't understand, and want to learn, regexps then let me recommend this regexp site
The solution is probably something like /(START|BEGIN).*))/

A: ResultString = Regex.Match(subject, @"(START|BEGIN).*?\)\)", RegexOptions.Singleline).Value;

A: Try this
MatchCollection m = Regex.Matches(input, "(START|BEGIN).+?\\)\\)", RegexOptions.Multiline);


text:
Q: What Level of Video Card do I need to run 2 Dell Ultrasharp U2415 Monitors I'm going to be purchasing a new desktop computer soon, and I'm getting 2 Dell Ultrasharp monitors. These are 24" 1920x1280 monitors.
I'm going to be doing web development, and maybe watching 1080p video on one screen. I won't be using them for gaming. What kind of video card do I need?

A: An entry-level graphics card should do fine (unless you're doing extensive WebGL work). As long as it has 2 HDMI or DVI ports, you'll be OK for web development.

A: 4K is basically 4x the pixels of 2K, and essentially what you have is 2x 2K monitors.As such except for gaming, any 4K capable video adaptor should be able to handle it. Generally You only really need a very capable video card for gaming. Even a humble onboard video adaptor on a bay trail can handle 4K video and should handle 2x HD screens fine.
Video ram is less important (except for gaming). Even with that, games scale reasonably well. For regular use, consider a few things.

*

*Interfaces - most modern video cards can handle more than one output (for that matter, the onboard gpu on the bay trail processors found in intel tablets and low end NUCs can). However you want the right mix of outputs. If your monitors do DP, that should be your preferred connection, followed by HDMI (tho, at mere HD resolutions that should be a non issue - DP's really the only choice when doing 4K at 60hz, but HDMI has plenty of bandwidth for HD). DVI's fine but bulky and many modern displays may drop the physical interfaces for them.

*Even a mid range card from the last few years should be able to handle 2x full HD (a nvidia 660 is supposed to be 4K capable), and even onboard intel processors can push that many pixels. For non gaming use, you might end up being able to use onboard graphics.
In the modern context, nearly any up to date GPU or iGPU should be handle what you want to .
If you're gaming, its a whole different ballgame, and you probably want to look up some benchmarks.  It'll also depend a lot on the settings you want.
I'd confidently go with nearly any modern video card or igpu with the outputs for my display here.

A: i almost have the same setup
and i use AMD Eyefinity3 with U2412M 1920x1200 off a radeon HD 7970
You can also make it a single surface
https://www.youtube.com/watch?v=JMbHZ8Mn__g
You can find eyefinity cards for every price bracket.
I do recommend a midrange. not the lowest end. just because its nice to have a little 3d perf than none at all
Radeon R7 360 and R7 370 etc
(Important! pick the one with DisplayPort+HDMI+DVI)
Demo of eyefinity from Guru3D
https://www.youtube.com/watch?v=CIqkYHePo-Q
and i almost forgot
AMD Kaveri based APUs support eyefinity as well (max 3 displays)


text:
Q: how to install glib2 package in docker I use docker to install centos 6.5 and opensource c++ mysql proxy : DBPORXY(https://github.com/Meituan-Dianping/DBProxy.git), when I run into the last command, I failed.From the error info, I think that is glib2 problem,but I have installed glib2! that is my public docker : [
docker pull xujianhai/dbproxy], the method I use to implement glib2 :
cd  glib-2.42.0
./configure
make
make install
vi /etc/ld.so.conf
add a row and exit: /usr/local/lib
ldconfig

the detail error message when I run into the last command :
bash-4.1# make
make  all-recursive
make[1]: Entering directory `/DBProxy'
Making all in src
make[2]: Entering directory `/DBProxy/src'
make  all-am
make[3]: Entering directory `/DBProxy/src'
/bin/sh ../libtool  --tag=CC   --mode=compile gcc -DHAVE_CONFIG_H -I. -I..  -I/usr/include/mysql -I/usr/include/glib-2.0 -I/usr/lib64/glib-2.0/include   -pthread -I/usr/include/glib-2.0 -I/usr/lib64/glib-2.0/include   -ggdb   -g -O0 -MT libmysql_chassis_glibext_la-glib-ext.lo -MD -MP -MF .deps/libmysql_chassis_glibext_la-glib-ext.Tpo -c -o libmysql_chassis_glibext_la-glib-ext.lo `test -f 'glib-ext.c' || echo './'`glib-ext.c
libtool: compile:  gcc -DHAVE_CONFIG_H -I. -I.. -I/usr/include/mysql -I/usr/include/glib-2.0 -I/usr/lib64/glib-2.0/include -pthread -I/usr/include/glib-2.0 -I/usr/lib64/glib-2.0/include -ggdb -g -O0 -MT libmysql_chassis_glibext_la-glib-ext.lo -MD -MP -MF .deps/libmysql_chassis_glibext_la-glib-ext.Tpo -c glib-ext.c  -fPIC -DPIC -o .libs/libmysql_chassis_glibext_la-glib-ext.o
glib-ext.c: In function 'g_string_get_time':
glib-ext.c:121: error: expected '=', ',', ';', 'asm' or '__attribute__' before 'm'
glib-ext.c:121: error: 'm' undeclared (first use in this function)
glib-ext.c:121: error: (Each undeclared identifier is reported only once
glib-ext.c:121: error: for each function it appears in.)
make[3]: *** [libmysql_chassis_glibext_la-glib-ext.lo] Error 1
make[3]: Leaving directory `/DBProxy/src'
make[2]: *** [all] Error 2
make[2]: Leaving directory `/DBProxy/src'
make[1]: *** [all-recursive] Error 1
make[1]: Leaving directory `/DBProxy'
make: *** [all] Error 2


text:
Q: Where to plug LED on Arduino due for blink demo? so, I got a Arduino Due, but I am somewhat confused about the pin layout.
As a simple setup, I want to have some LEDs blinking. On my host laptop, I use Node and Johnny-five like here: https://github.com/rwaldron/johnny-five/wiki/Getting-Started
But when it comes to the Arduino board, I am confused.
I found a board schematic here: http://forum.arduino.cc/index.php?topic=132130.0
But how and where should I connect the LED to have some basic strobe.

A: According to that link you provided:
// Create an Led on pin 13
var led = new five.Led(13);

Connect the LED to pin 13 or any other pin as long as you modify this code.


text:
Q: Which approach is better for using an SQL database? I'm working on a project that needs to read some diffrent query from database and after making lots of changes in data decide to save it on the server or not.
Right now I'm using linq to sql but the problem is that, if I want to submit changes in the end, I can't make diffrent query on tables, because my changes will be lost.
So is there any way to make an in memory database, then manipulate data, and finally save data on the server?
What would be the best approach for this kinda cases?


text:
Q: Unity pathfinding script causes unity to crash when running I'm trying to get pathfinding to work in unity - A gameobject navigating around other gameobjects to a target. I don't want to use navmeshes because they require previous setup and that will not work will what I'm trying to do. When I run my project with the script set up, it freezes and goes to 'not responding' on task manager.
I'm unfortunately not smart enough to make a pathfinding script - my attempts so far have been abysmal - so I resorted to this one I found (I think it uses A*).
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Pathfinding : MonoBehaviour {

    public Transform target;
    public float speed = 5f;
    public float nodeRadius = 0.5f;
    public LayerMask obstacleMask;

    private List<Node> path = new List<Node>();

    private void Update()
    {
        if (target != null)
        {
            FindPath(transform.position, target.position);
            Move();
        }
    }

    private void FindPath(Vector3 startPosition, Vector3 targetPosition)
    {
        Node startNode = new Node(startPosition);
        Node targetNode = new Node(targetPosition);

        List<Node> openSet = new List<Node>();
        HashSet<Node> closedSet = new HashSet<Node>();
        openSet.Add(startNode);

        while (openSet.Count > 0)
        {
            Node currentNode = openSet[0];
            for (int i = 1; i < openSet.Count; i++)
            {
                if (openSet[i].fCost < currentNode.fCost || (openSet[i].fCost == currentNode.fCost && openSet[i].hCost < currentNode.hCost))
                {
                    currentNode = openSet[i];
                }
            }

            openSet.Remove(currentNode);
            closedSet.Add(currentNode);

            if (currentNode == targetNode)
            {
                RetracePath(startNode, targetNode);
                return;
            }

            foreach (Node neighbor in GetNeighbors(currentNode))
            {
                if (closedSet.Contains(neighbor))
                {
                    continue;
                }

                float newCostToNeighbor = currentNode.gCost + GetDistance(currentNode, neighbor);
                if (newCostToNeighbor < neighbor.gCost || !openSet.Contains(neighbor))
                {
                    neighbor.gCost = newCostToNeighbor;
                    neighbor.hCost = GetDistance(neighbor, targetNode);
                    neighbor.parent = currentNode;

                    if (!openSet.Contains(neighbor))
                    {
                        openSet.Add(neighbor);
                    }
                }
            }
        }
    }

    private List<Node> GetNeighbors(Node node)
    {
        List<Node> neighbors = new List<Node>();
        Vector3[] directions = { Vector3.up, Vector3.right, Vector3.down, Vector3.left, Vector3.forward, Vector3.back };
        foreach (Vector3 direction in directions)
        {
            Vector3 neighborPosition = node.position + direction;
            if (Physics.CheckSphere(neighborPosition, nodeRadius, obstacleMask))
            {
                continue;
            }

            neighbors.Add(new Node(neighborPosition));
        }

        return neighbors;
    }

    private void RetracePath(Node startNode, Node endNode)
    {
        path.Clear();
        Node currentNode = endNode;

        while(currentNode != startNode)
    {
            path.Add(currentNode);
            currentNode = currentNode.parent;
        }

        path.Reverse();
    }

    private void Move()
    {
        if (path.Count > 0)
        {
            Vector3 direction = (path[0].position - transform.position).normalized;
            transform.position += direction * speed * Time.deltaTime;
            if (Vector3.Distance(transform.position, path[0].position) < nodeRadius)
            {
                path.RemoveAt(0);
            }
        }
    }

    private float GetDistance(Node nodeA, Node nodeB)
    {
    float distanceX = Mathf.Abs(nodeA.position.x - nodeB.position.x);
    float distanceY = Mathf.Abs(nodeA.position.y - nodeB.position.y);
    float distanceZ = Mathf.Abs(nodeA.position.z - nodeB.position.z);

    if (distanceX > distanceZ)
    {
            return 14 * distanceZ + 10 * (distanceX - distanceZ) + 10 * distanceY;
    }
        else
    {
            return 14 * distanceX + 10 * (distanceZ - distanceX) + 10 * distanceY;
        }
    }
}

Where the Node class is
public class Node
{
    public Vector3 position;
    public Node parent;
    public float gCost;
    public float hCost;

    public float fCost
    {
        get
    {
            return gCost + hCost;
        }
    }

    public Node(Vector3 position)
    {
        this.position = position;
    }
}

I've looked around for other A* path algorithms for unity (like Unity A* Pathfinding Crashes or AStar Shortest Path using C#), and really I would be more comfortable with a method that returns a list of nodes which I then move through independently of the function, but both of them don't contain the definitions for some of the functions they use (like RetracePath or GetManhattanDistance).


text:
Q: Windows 2012 R2 closesocket() hangs on listening socket I have a weird situation on a production server.
We have network application written on C++ which serves users requests by TCP written using IOCP.
Two days ago we did an update of Windows 2012 R2 (it installed latest security updates. The previous update was 6 month ago). And after the update when trying to stop the service we see in logs that server hangs on call to close listening socket
closesocket(session->listen_socket);

The schema of stopping the network system is the next:

*

*PostQueuedCompletionStatus(m_completion_port, 0, NULL, NULL); x
the number of worker threads

*Wait all worker threads finish their job

*CloseHandle(m_completion_port);

*closesocket(session->accept_socket);
closesocket(session->listen_socket);
This was working good for the last 4 years, but suddenly after Windows 2012 R2 update the server hangs forever on call closesocket(session->listen_socket);
I've alsi tried as a solution to set LINGER option with 0 timeout to make abotive closure, but it didn't help.
All ideas how to fix this or make any additional diagnostics?

A: The issue was brought by patch from Microsoft KB4338815, which caused closesocket tо hang forever on Intel Xeon processors and this was also posted by FileZilla guys in this thread
https://forum.filezilla-project.org/viewtopic.php?t=49308


text:
Q: Table and column naming conventions when plural and singular forms are odd or the same In my search I found mostly arguments for whether to use plurality in database naming conventions, and ways to handle it in either case. I have decided I prefer plural table names, so I don't want to argue that.
I need to represent an animal's species and genus and so on in a database. The plural and singular form for 'species' are the same, and the plural of 'genus' is 'genera'.
I'm using Microsoft's Entity Data Model, by the way. My concern is mainly about whether I'll have problems later on depending on my naming choices.
I think I can get by with:
Table: Genera | Column: Genus
But I'm unsure how I should handle:
Table: Species | Column: Species
If I really wanted to be lazy about this I'd just name them 'species > specie' and 'genuses > genus', but I would prefer to read them in their correct forms.
Any advice would be appreciated.

A: I would go for Genera/Genus and Species/Species. That's how you say it in English, so why using an incorrect form of the word?

A: I generally avoid have a column name that is the same as a table name because it can be confusing to human readers. The database engine knows whether it expects a table name or column name in any given context, I don't recall that ever being a problem. (Is there some context where either would be valid? I can't think of one.)
That said, if you run into this issue, it indicates to me that you have a poorly chosen name for one or the other. Species makes good sense as a table name: this table contains data about a species. So if a field in that table is called "species" ... what about the species? Presumably everything in the table is about a species. I'd guess it was probably some sort of identifier and not, say, the number of chromosomes or method of reproduction. But is it an ID number? An abbreviation? The common name? The binomial nomenclature name? Etc. If it's, say, the common name, I'd call it "common_name" and not "species".
By the way, another naming convention you should decide on is whether column names that could be ambiguous if taken out of context should have names that specify the context, or whether you use the table name to eliminate the ambiguity. For example, you could have many things that have a "name". You could call any such field simply "name", and if there's ambiguity, qualify it, like "species.name", "laboratory.name", etc. Or you could give each field a unique name, like "species_name", "laboratory_name", etc. That's one of those questions that I think has no definitively right answer, just pros and cons and make a decision and be consistent.


text:
Q: Return sum of multiple values and corresponding category field of max value I have the following data
ID  CATEGORY VALUE
x   A        10
x   B        2
x   C        1
y   B        11
y   A        6
z   D        13
z   E        0

I would like to group by ID and Category such that Value is summed for a single ID and the Category returned is that of the corresponding max Value within the ID group.
The results would look like this.
ID  CATEGORY    VALUE
x   A           13
y   B           17
z   D           13

Is this possible in SQL?
Thanks

A: Try window function rank:
select id, category, value
  from (
   select id, category, sum(value) over (partition by id) as value,
          rank() over (partition by id order by value desc) as rnk
    from mytable) t
where rnk=1;

If you have duplicates with same value it'll show both. (if 'x','B' had value 10):
id  cat value
x   A   21
x   B   21
y   B   17
z   D   13


text:
Q: Setting common colorbox for all graphs in multiplot in gnuplot I am generating a multiplot with 2 rows and 2 columns. I am using pm3d map for individual graphs. The generated picture is shown below:

In this picture, each individual graph has its own colorbox and axes labels. I would like to have common colorbox for all these graphs and would like to give common i and j indices after drawing common x and y axes. How can I do this? Thanks in advance.

A: As Christoph mentioned, this can be done with set/unset colorbox. In your case, I highly recommend that you plot ... with image rather than use set pm3d map. But it can be done both ways, see Christoph's comment below.
What you need is something along these lines (change the details to accommodate it to your needs):
set multiplot
# Set left and right margins for both plots:
set lmargin screen 0.1 ; set rmargin screen 0.8
# Set ranges and *in this case* isosamples to make the graph look better
set xrange [-1:1] ; set yrange [-1:1] ; set isosamples 100
# Options for the first graph: set top and bottom margins and unset colorbox
set tmargin screen 0.9 ; set bmargin screen 0.6 ; unset colorbox
# Plot it
plot "++" u ($1):($2):(sin($1*$2)) with image
# Options for second graph
set tmargin screen 0.4 ; set bmargin screen 0.1
# Set colorbox with customize options
set colorbox user origin 0.85,0.1 size 0.05,0.8
# Plot it
plot "++" u ($1):($2):(cos($1*$2)) with image

Voilà:


text:
Q: couldn't passing the data from axios to data return variable in vuejs I have an issue in my vue template down below. I fetched data from axios but it couldn't store the data on this.sub_brand variable. console.log(this.sub_brand) is only working for inside axios. here is the full code -
<template>

{{sub_brand}}

Star

RM869.00

Variation

Quantity:

                <input type="number" class="form-control pl-4" placeholder="0" style="width: 12%; margin-left: 4%" min="0">

                <button class="btn btn-secondary ml-3">Add to Cart</button>
                <button class="btn btn-primary ml-3">Buy Now</button>

Samsung

                Chat
                Video Chat
                View

                Shipping Details

2A, Changkat Duta Kiara, Mont Kiara, 50480 Kuala Lumpur, Willayah Persekutuan Kuala Lumpur

                From: China Logistic, Shankal

                To: Kuala Lumpur, Willayah Persekutuan

                Shipping Fee: RM8.00

Authentic

15 Days Return

Free Shipping

Product Description

                Samsung

Review

                Samsung

You may also like other product from same merchant

                Samsung

</template>

A: Look, the problem is, your context this. works inside axios with context of axios
If you want to use context this. of vue component, you have to get data from axios outside.
You have to use async/await for you vue method fetchProduct
Something like that
methods: {
    async fetchProduct() {
      let result = await axios.get("https://admin.globalshopping-mall.site/api/single_sub_brand_detail/" +this.product_id)
        .then((res) => {
          return res.data.data[0];
        })
        .catch((err) => {console.log(err);});

      this.single_product = result;
      this.sub_brand = result.GUID;
    },
  },

or
You can save your context this to the variable before axios
and use this variable inside the axios function
Something like this
methods: {
    fetchProduct() {
      let _this = this;
      axios.get("https://admin.globalshopping-mall.site/api/single_sub_brand_detail/" + this.product_id)
        .then((res) => {
          _this.single_product = res.data.data[0];
          _this.sub_brand = res.data.data[0].GUID;
        })
        .catch((err) => {console.log(err);});
      console.log(this);
    },
  },

A: Root cause : As axios API calls works asynchronously, But other code will execute synchronously. Hence, While trying to logging this.sub_brand it will work synchronously and will invoke before the axios call (response time might vary).
Solution : If you want to access the API response immediately after a call. You have to use async/await which make promises easier to write.

*

*async makes a function return a Promise

*await makes a function wait for a Promise

Live Demo :
methods: {
    async fetchProduct(){
        const res = await axios.get('https://admin.globalshopping-mall.site/api/single_sub_brand_detail/'+ this.product_id)
        .then(res => {
          return res.data.data[0];
        }).catch(err => {console.log(err);});
    }
    this.single_product = res;
    this.sub_brand = res.GUID;
}


text:
Q: Isomorphism and multiplication table According to this image:

I would like to know why isomorphism implies that if $AB=C$ then $A'B'=C'$
To do this, I have to prove that the isomorphism, call it f, has to satisfy: $f(AB) = f(A)f(B)$, but how do I prove this?

A: As mentioned in the comments, the definition of a group isomorphism in the quoted text is incorrect. The standard definition is as follows:
Let $G$ and $H$ be groups.

*

*A function $\varphi: G \to H$ is a group homomorphism if for all $x , y \in G$, $\varphi(xy) = \varphi(x)\varphi(y)$.

*A function $\varphi : G \to H$ is a group isomorphism if it is a group homomorphism and a bijection (equivalently  $\varphi$ is a bijection and there exists a group homomorphism $\psi : H \to G$ such that $\varphi \circ \psi = \operatorname{id}_H$ and $\psi \circ \varphi = \operatorname{id}_G$).

Therefore the desired $\varphi(gh) = \varphi(g)\varphi(h)$ is simply part of the definition.


text:
Q: R delete rows in data frame where nrow of index is smaller than certain value I want to delete certain rows in a data frame when the number of rows with the same index is smaller than a pre-specified value.
> fof.6.5[1:15, 1:3]
   draw Fund.ID Firm.ID
1     1    1667     666
2     1    1572     622
3     1    1392     553
4     1     248      80
5     1    3223     332
6     2    2959    1998
7     2    2659    1561
8     2   14233    2517
9     2   10521   12579
10    2    3742    1045
11    3    9093   10121
12    3   15681   21626
13    3   26371   70170
14    4   27633   52720
15    4   13751     656

In this example, I want each index to have 5 rows. The third draw (which is my index) has fewer than 5 rows. How can I delete the draws like the third one if they have fewer than 5 rows?

A: You could do this using dplyr (assuming your data is in a data frame called dt:
dt %>% group_by(draw) %>% filter(n() >= 5) %>% ungroup()

Or you could use table or xtabs:
tab <- xtabs(~ draw, dt)

dt[!dt$draw %in% as.numeric(names(which(tab < 5))), ]

A: Here is another option using data.table.  Convert the 'data.frame' to 'data.table' (setDT(df1), grouped by 'draw', if the nrows (.N) are greater than or equal to 'n' then get the Subset of Data.table (.SD)
library(data.table)
n <- 5
setDT(df1)[, if(.N >= n) .SD, by = draw]
#    draw Fund.ID Firm.ID
# 1:    1    1667     666
# 2:    1    1572     622
# 3:    1    1392     553
# 4:    1     248      80
# 5:    1    3223     332
# 6:    2    2959    1998
# 7:    2    2659    1561
# 8:    2   14233    2517
# 9:    2   10521   12579
#10:    2    3742    1045

If we want only 'n' number of rows, use the head
setDT(df1)[, if(.N >= n) head(.SD, n), by = draw]

A: Code below makes that:
library(dplyr)
fof.6.5 <- data.frame(draw = rep(1:4, c(5, 5, 3, 2)),
                      Fun.ID = rnorm(15),
                      Firm.ID = rnorm(15))
fof_filter <- fof.6.5 %>% group_by(draw) %>% mutate(freq = n()) %>%
  filter(freq >= 5) %>% select(-freq)
fof_filter

*

*group_by join (in someway) profiles with the same value of draw

*mutate add a new variable "freq" that give the number of profiles
per each group of draw and repeats it.

*filter selects only those
profiles with "freq" greater or equals to 5

*select delete the "freq"
column because is not needed anymore


text:
Q: Pass the columns of each row in a result set to a stored function in single step The following is my stored function
            DELIMITER $$;
            CREATE FUNCTION set_credit_values (emp_id bigint, lpc_id int, elc_date date) RETURNS date DETERMINISTIC
            BEGIN

                SELECT do_credit(emp_id, lpc_id, elc_date,ltp_id, lpb_cr_count, lpb_cr_on, lpb_next_cr,  lpb_cr_period)
                FROM erp_leave_policy_body,erp_leave_type
                WHERE lpb_fk_leave_policy = lpc_id AND ltp_id = lpb_fk_leave_type AND ltp_status=1;

                RETURN elc_date;
            END $$;
            DELIMITER ;

I need to pass the selected values in each row in the result set (by the SELECT query) to do_credit() function. But it is showing errors as
#1415 - Not allowed to return a result set from a function

The do_credit() function is as
            DELIMITER $$;
            CREATE FUNCTION do_credit (emp_id bigint, lpc_id int, new_elc_date date,ltp_id int, cr_count tinyint, cr_on tinyint, next_cr date, cr_period tinyint)
            RETURNS boolean DETERMINISTIC
            BEGIN
                DECLARE next_credit_date DATE DEFAULT NULL;
                DECLARE is_credited INT(11) DEFAULT 0;

                SET next_credit_date = get_next_credit(emp_id, lpc_id, new_elc_date,ltp_id, cr_on, next_cr, cr_period);

                IF next_credit_date = new_elc_date THEN

                    SELECT COUNT(*) INTO is_credited FROM erp_employee_leave_credits WHERE
                    elc_fk_employees = emp_id AND elc_fk_leave_policy = lpc_id AND elc_fk_leave_type = ltp_id AND elc_date = new_elc_date;
                    -- If the leave is not credited yet
                    IF is_credited = 0 THEN
                        INSERT INTO erp_employee_leave_credits(elc_fk_employees,elc_fk_leave_policy,elc_fk_leave_type,elc_date,elc_cr_count) VALUES (emp_id,lpc_id,ltp_id,new_elc_date,cr_count);
                    END IF;

                END IF;
                RETURN 1;

            END $$;
            DELIMITER ;

It is working successfully.
I know using cursor. But when using cursor I should traverse through each row in the result set. So may take more time. If I call the function with the select query it works faster than cursor. So How can solve this error.


text:
Q: What's the smallest number that can be written as the sum of two abundant numbers? I was trying to solve a problem when I found this statement

As 12 is the smallest abundant number, 1 + 2 + 3 + 4 + 6 = 16, the smallest number that can be written as the sum of two abundant numbers is 24.

I understand what an abundant number is. My question is How can "24" be the smallest number that can be written as the sum of two abundant numbers?

A: Suppose we have a non-empty set of natural numbers, which we'll call $X$ (in your case, $X$ consists of the abundant numbers). Then

*

*the smallest natural number that can be written as a sum of two elements of $X$ is necessarily the two times the smallest element of $X$.

*the smallest natural number that can be written as a sum of two distinct elements of $X$ is necessarily the smallest element of $X$ plus the next-smallest element of $X$ (assuming that $X$ does in fact have at least two elements).
In the case of $X=$ the abundant numbers, we therefore have that

*

*the smallest natural number that can be written as a sum of two abundant numbers is
$$12+12=24$$

*the smallest natural number that can be written as a sum of two distinct abundant numbers is
$$12+18=30$$


text:
Q: mysql 6 tables join together in one query I have 6 tables: users, journals, files, flags, flag_details
users (id, avatar, fullname)
journals (id, container, container_id, user_id, title)
files (id, container, container_id, user_id, title)
flags (id, container, container_id, total)
flag_details (id, container, container_id, reason, comment, user_id)
trend_item (id, container, container_id, user_id)

Relation is:
if(flags.container='look') then flags.container_id = journals.id

So I take all records from journals table
if(flags.container='photo') then flags.container_id = files.id

So I take all records from files table
if(flags.container='trend') then flags.container_id = trend_item.id

So I take all records from trend_item table
So my view to be like this:
id | container | things      | total flag
1  | look      | 123 - guy   | 2
2  | photo     | 321 - budi  | 4
3  | trend     | 345 - elvis | 3
4  | look      | 876 - cans  | 6

So I got the query like this:
SELECT DISTINCT (id), created_at, container, IF( container =  'look', (

SELECT a.container_id
FROM flags a, journals b
WHERE a.container_id = b.id
), IF( container =  'photo', (

SELECT a.container_id
FROM flags a, files b
WHERE a.container_id = b.id
), (

SELECT a.container_id
FROM flags a, trend_items b
WHERE a.container_id = b.id
) ) ) , total,
`status`
FROM flags
ORDER BY created_at DESC

But answer is subquery return more than 1 row.
There's any possible if all of that put together in one query?

A: I suppose you can safely join all these tables with a single query, like this:
    SELECT fl.*
      FROM flags fl
 LEFT JOIN journals jo
        ON fl.container_id = jo.id AND fl.container = 'look'
 LEFT JOIN files fi
        ON fl.container_id = fi.id AND fl.container = 'photo'
       ...

Here's something of a demo to illustrate the concept.

A: SELECT t6.username AS username, MAX( t1.earn_status ) AS genx, MAX( t2.earn_status ) AS grnplus, MAX( t3.earn_status ) AS genpower, MAX( t4.earn_status ) AS genpro, MAX( t5.earn_status ) AS geextra
FROM genx_commission t1
    LEFT JOIN gen_plus_commission t2 ON ( t1.user_id = t2.user_id )
    LEFT JOIN gen_power_commission t3 ON ( t1.user_id = t3.user_id )
    LEFT JOIN gen_pro_commission t4 ON ( t1.user_id = t4.user_id )
    LEFT JOIN gen_extra_commission t5 ON ( t1.user_id = t5.user_id )
    LEFT JOIN users t6 ON ( t1.user_id = t6.id )
WHERE t1.user_id =1654


text:
Q: Htaccess 404 redirect not working, it doesnt redirect Whit this code, the 404 redirect doesnt work. I dont get any error. If i type in an url that doesnt exists, i only get an empty white page.
Code updated:
   <IfModule mod_rewrite.c>
    RewriteBase /
    RewriteBase /
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ htaccess.php?q=$1 [QSA]
</IfModule>

<ifModule mod_gzip.c>
    mod_gzip_on Yes
    mod_gzip_dechunk Yes
    mod_gzip_item_include file .(html?|txt|css|js|php|pl)$
    mod_gzip_item_include handler ^cgi-script$
    mod_gzip_item_include mime ^text/.*
    mod_gzip_item_include mime ^application/x-javascript.*
    mod_gzip_item_exclude mime ^image/.*
    mod_gzip_item_exclude rspheader ^Content-Encoding:.*gzip.*
</ifModule>

#RewriteEngine On
#RewriteCond %{HTTPS} !=on
#RewriteCond %{REQUEST_URI} !^/[0-9]+\..+\.cpaneldcv$
#RewriteCond %{REQUEST_URI} !^/[A-F0-9]{32}\.txt(?:\ Comodo\ DCV)?$
#RewriteRule ^.*$ https://%{SERVER_NAME}%{REQUEST_URI} [R,L]

RewriteEngine On
RewriteBase /
ErrorDocument 404 404.php/
RewriteCond %{REQUEST_URI} ^/404/$
RewriteRule ^(.*)$ 404.php [L]

A: Change ErrorDocument 404 /index.php to
RewriteEngine On
RewriteBase /

ErrorDocument 404 http://yourdomain.com/404.php/

RewriteCond %{REQUEST_URI} ^/404/$
RewriteRule ^(.*)$ /path/to/404.php [L]

The Rewrite rules map that URL to your 404.php script.
See this link for more information: http://httpd.apache.org/docs/current/mod/core.html#errordocument


text:
Q: insert into database, then send email I'm forced to use PHP against my will, so I'll need some help with this.
After googling, I have the following basic code and am wondering whether it is OK.
This is for a pre-launch "coming soon" page, where user enter an email address, which gets inserted into a mysql database and gets a reply message. This is all happening on a hosted server.
Ideally, I want to generate some HTML with images etc and send that HTML in the email body. Does someone have any idea how to do that in PHP?
<?php
    $servername = "localhost:3306";
    $username = "userblah";
    $password = "passblah";
    $dbname = "blah";

    // Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);
    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }

    $sql = "INSERT INTO prelaunch_users (email)
    VALUES ($_GET['email'];)";

    if ($conn->query($sql) === TRUE) {
        echo "New record created successfully";
    } else {
        echo "Error: " . $sql . "<br>" . $conn->error;
    }

    $conn->close();

    $to      = $_GET['email'];
    $subject = 'Welcome';
    $message = 'hello';
    $headers = 'From: blah@blah.co.nz' . "\r\n" .
        'Reply-To: blah@blah.co.nz' . "\r\n" .
        'X-Mailer: PHP/' . phpversion();

    mail($to, $subject, $message, $headers);
?>

I think I'd need a username and password for the hosted mail server there probably as well.
Thank you
Paul

A: You can use prpared statment like below:-
<?php
    if(!empty(trim($_GET['email']))){
        $conn = new mysqli("localhost:3306", "userblah", "passblah", "blah");

        if ($conn->connect_error) {
            die("Connection failed: " . $conn->connect_error);
        }

        if ($stmt = $conn->prepare("INSERT INTO prelaunch_users (email) VALUES (?)")) {

            $stmt->bind_param("s",$_GET['email']);

            if($stmt->execute()){
               // Add you mail code here
            }else{
                 echo "Error: ". $conn->error;
            }

            $stmt->close();
        }
        $conn->close();
    }else{
        die('email is required');
    }
?>

And for sending html mail with image. Please check below thread
Sending HTML Email With Images - PHP Tutorial


text:
Q: Azure Log Analytics - new Search REST API Azure announced the ability to upgrade Azure Log Analytics workspace recently. It comes with a new query language (https://docs.loganalytics.io/index). But after the upgrade their Search REST API (https://learn.microsoft.com/en-us/azure/log-analytics/log-analytics-log-search-api) isn't working anymore. I wasn't able to find a way to execute new Search Queries via REST. I would imagine that it would be similar to AppInsights API (https://dev.applicationinsights.io/).
It also seems like they have actual API but no documentation as of yet, because Microsoft Flow has ability to integrate and execute Search Queries with the upgraded workspace (https://learn.microsoft.com/en-us/azure/log-analytics/log-analytics-flow-tutorial).
Any help in pointing on how to execute new Search API via REST is greatly appreciated.
Thanks

A: Documentation for new REST API wasn't available when this question was posted. Here is the MS response:
https://social.msdn.microsoft.com/Forums/azure/en-US/0c044c41-6642-4bb0-9a61-64d6f6b8b042/new-log-analytics-search-rest-api?forum=opinsights


text:
Q: Customize spacing between section number and its caption? is there any chance to customize the spacing between the (sub)section number and its title in every appearance in the document? That is, in any header or footer as well as in the table of contents and the main part of the document?
In this particular case, I have a scrartcl document, but a class-independent solution would be really helpful.

A: Those section numbers are used in several places using different formatting commands, such as in the TOC, in headers and in the body text. That's why the answer consists of several parts.
For a class independent solution you could use packages:

*

*titlesec is very useful for customizing headings in the text.

*titletoc or the powerful tocloft could help formatting the numbers in the TOC.

*scrpage2 or fancyhdr could be used to modify the header and the footer.
In that case have a look at the respective package documentation.
With LaTeX's base classes you could redefine internal macros. KOMA-Script classes provide additional formatting macros, which are described in the manual.
Let's have a look at the base LaTeX side. LaTeX formats section numbers by \@seccntformat which is defined this way:
\def\@seccntformat#1{\csname the#1\endcsname\quad}

You could redefine it to replace the \quad by your customized distance:
\makeatletter
\renewcommand*{\@seccntformat}[1]{\csname the#1\endcsname\hspace{1em}}
\makeatother

Within the TOC, LaTeX uses \numberline for the section numbers, defined by
\def\numberline#1{\hb@xt@\@tempdima{#1\hfil}}

Also this could be redefined:
\makeatletter
\renewcommand*{\numberline}[1]{\hb@xt@1em{#1\hfil}}
\makeatother

Now we come to the headings. Since you're using a KOMA-Script class, let's redefine a KOMA formatting command for the number:
Originally it uses \enskip:
\newcommand*\sectionmarkformat{\thesection\autodot\enskip}

\enskip is skips half of 1 em, as defined in the LaTeX kernel:
`\def\enskip{\hskip.5em\relax}`.

Redefinition:
\renewcommand*{\sectionmarkformat}{\thesection\autodot\hspace{1em}\relax}

Do similarly for \subsectionmarkformat.
With base classes you could redefine \sectionmark etc. which uses \quad for the spacing.


text:
Q: Apache - Rewriting trailing extension with .htaccess To remove trailing extension (a .php in this case), I have tried the following two set of rules
RewriteCond %{THE_REQUEST} (\S*?)/(.*?)\.php [NC]
RewriteRule ^ %1/%2 [L,R=301]
RewriteCond %{REQUEST_URI} ^(.*)$
RewriteRule !\.php$ %1.php [NC,L]

and
RewriteRule ^(.*?)\.php$ $1 [NC,L,R=301]
RewriteCond %{REQUEST_URI} ^(.*)$
RewriteRule !\.php$ %1.php [NC,L]

To convert a url like test.com/test.php to test.com/test, the first one works while the second one ends up looping infinitely. The rewrite_log is just confusing, so can anyone tell what is the problem with the second set?

PS: The rules might be inefficient or even not sufficient for a case like test.com but that's not the issue. I just want to understand how the rewrite is working BTS.

A: As mentioned in the comments, in the first case, there is no looping using %{THE_REQUEST} as the value is static and doesn't change once it is received by the server even after redirecting / "looping". So the rule will remove trailing .php and redirect. As the rewrite rule is substituting values from %{THE_REQUEST} in the rewritecond, after redirection, the value will not contain the trailing .php and thus proceed on to the second rewritecond and then finally redirect internally. After a second redirect, both the conditions will fail to match thus stopping the process
Whereas in the second case, the rewrite rule checks values from the uri which will remove .php and redirect. After redirection, the second rule will internally redirect back to the uri with php extension. Then finally in the supposed third final check which is supposed to not match both the rules, the first rule will again be matching thus infinitely looping the entire process.


text:
Q: Delayed animation when a pan gesture leaves a UIView, with debouncing? Are there one or two idiomatic ways to handle the kind of UI interaction described below?  Perhaps a custom class is unnecessary?
I am implementing drag and drop in an iPadd app and would like to handle the case where the draggable is not released upon the droppable and the pan gesture leaves the UIView.

*

*The view expands and gets a border when the draggable is over it, and it will return to its previous size and lose the border when the draggable leaves the area. There will be a noticeable delay before the down-scale animation begins.

*It is possible the draggable will be brought back over the zone before the scale-down animation begins, suggesting the need for some kind of debouncing, i.e., something to collect the events that occur within a period of time and treat them as one event.

*I know a large number of events are fired off during a pan gesture, and I don't want to allocate unnecessary resources (e.g., timers).

I was thinking of using a single custom timer, perhaps along these lines, but perhaps there's something much simpler for this?

A: Following code will inflate the view with inflate-animation of 300ms whenever a finger moves over the view and will deflate the view back to normal whenever the touch is outside. No panGestureRecognizerRequired.
@interface CustomView : UIView
{
    BOOL hasExpanded;
    CGRect initialFrame;
    CGRect inflatedFrame;
}
@end

@implementation CustomView
-(id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if(self)
    {
        hasExpanded = NO;

        initialFrame = frame;

        CGFloat inflateIncrement = 50.0f;

        inflatedFrame = CGRectMake(self.frame.origin.x-(inflateIncrement*0.5f),
                                        self.frame.origin.y-(inflateIncrement*0.5f),
                                        self.frame.size.width+inflateIncrement,
                                        self.frame.size.height+inflateIncrement);

    }
    return self;
}

-(void)forceDeflate
{
    if (hasExpanded)
    {
        //start deflating view animation
        [UIView animateWithDuration:0.3 animations:^{
            self.frame = initialFrame;

        }];
        hasExpanded = NO;
    }
}

-(void)inflateByCheckingPoint:(CGPoint)touchPoint
{
    if(!hasExpanded)
    {
        if(CGRectContainsPoint(self.frame,touchPoint))
        {
            //start inflating view animation
            [UIView animateWithDuration:0.3 animations:^{
                self.frame = inflatedFrame;

            }];

            hasExpanded = YES;
        }

    }
    else
    {
        if(!CGRectContainsPoint(self.frame,touchPoint))
        {
            //start deflating view animation
            [UIView animateWithDuration:0.3 animations:^{
                self.frame = initialFrame;

            }];

            hasExpanded = NO;
        }
    }
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *singleTouch = [touches anyObject];
    CGPoint touchPoint = [singleTouch locationInView:self.superview];
    [self inflateByCheckingPoint:touchPoint];
}

-(void)touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event
{
    UITouch *singleTouch = [touches anyObject];
    CGPoint touchPoint = [singleTouch locationInView:self.superview];
    [self inflateByCheckingPoint:touchPoint];
}

-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self forceDeflate];
}

-(void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self forceDeflate];
}

@end


text:
Q: SourceUnavailableError when requesting getUserMedia for video from about: page Requesting mic with audio:true works perfectly fine, however requesting webcam video, or screen video is failing with SourceUnavailbleError. I have added the string of browser to the preference media.getusermedia.screensharing.allowed_domains
Code for requesting webcam video:
        var param = {
            // audio: true, // if just this it works fine
            video: true // {mediaSource: 'screen'} does not work either
        };
        navigator.mediaDevices.getUserMedia(param).then(function(stream) {
            console.log('success');
        })
        .catch(function(err) {
            console.error('err:', err)
        });

To reproduce this error, open up browser console, and paste the code above like this:

Error given is:
err: MediaStreamError { name: "SourceUnavailableError", message: "Failed to allocate videosource", constraint: "", stack: "" }
Do you know how I can get around this SourceUnvailableError?
I did a lot of digging here - https://dxr.mozilla.org/mozilla-central/source/browser/modules/webrtcUI.jsm#201 - but no success yet.
Thanks


text:
Q: python-taking part of the text stored within a combo box I have a combo box on a form that I created. This combo box displays an ID and a name together. I am writing the contents of the combo box to a database. So far it writes correctly when I use this piece of code
self.ui.residentComboBox.currentText()

Now what I want to be able to do is pull only the ID from the combo box instead of the ID and the name together. Can anyone help?

A: If self.ui.residentComboBox.currentText() returns a string, and the ID is just the first word, you can do this:
self.ui.residentComboBox.currentText().split()[0]

which splits the string into a list of words (separated by whitespace) and then the [0] gives the first item in that list.
For example:
t = "3426523 askew chan"
print t.split()
#['3426523','askew','chan']
print t.split()[0]
#'3426523'


text:
Q: PowerShell Copy on a mapped or UNC Drive (SQL Server Job Agent) What am I doing wrong?
As a step in a Job I am trying to overwrite file by copying the drive is mapped, but I am using unc path just in case.
In PowerShell this works in the command line interface.

Copy \V240\folder\foo.txt \V240\folder\bar.txt

1
When I put it in a Job Agent in SQL Server with the PowerShell option it says successfully completed but the file has not been copied.

A: The Powershell SQL Agent job step starts Powershell sqlps host in the SQL Server provider. I would try setting location (cd) to the filesystem provider before copying
set-location c:\
Copy \V240\folder\foo.txt \V240\folder\bar.txt