问:
Try/Except to Check String and perform the function in Python and Twilio
I am trying to parse through the body message then return the values that the user requests. I couldn't figure out how to store a 5 character zipcode so I decided to use a try and except within the function. So essentially, I want the user to send the text, such as "SenEmail", then be prompted for their zipcode and return the the data (I currently only having it return the API call url for simplicity). However, its not working properly, I keep getting an error that my indentation is off or invalid syntax on the 'body == 'SenWeb': " and when it does work, it returns all 3 API call links, and not just the one associated with it. So SenPhone will return(Sending 3 texts of all the info rather than just 1), SenPhone, SenWeb and SenEmail rather than just SenPhone. I am fairly new to python, as you can probably tell. Thank you for your consideration. </p>

```<code>import urllib.request as urlr
import urllib.parse as url
import urllib.error as urle
import json
import os
from flask import Flask, request, redirect
from twilio import twiml
from twilio.twiml.messaging_response import MessagingResponse

app = Flask(__name__)
@app.route('/sms', methods=['GET', 'POST'])

def sms_reply():
    r = MessagingResponse()
    body = request.values.get('Body', None)
    if body == 'SenPhone':
        r.message("Welcome to PollText! Reply with Zip for Senators Phone Num's.")
    try:
        if len(body) == 5:
            url = 'https://www.googleapis.com/civicinfo/v2/representatives?address='
            z_c = str(body)
            key = '&key=xxxxxxxxxxxxxxxxxxx'
            serviceurl = url+z_c+key
            address = serviceurl
            r.message(str(serviceurl + "Phone"))
        else:
            r.message("SenPhone, SenWeb, SenEmail")

    elif body == 'SenWeb':
        r.message("Welcome to PollText! Reply with Zip for Senators Website.")
        try:
            if len(body) == 5:
                url = 'https://www.googleapis.com/civicinfo/v2/representatives?address='
                z_c = str(body)
                key = '&key=xxxxxxxxxxxxxxxxxxx'
                serviceurl = url+z_c+key
                address = serviceurl
                r.message(str(serviceurl + "Website"))
            else:
                r.message("SenPhone, SenWeb, SenEmail")

    elif body == "SenEmail":
        r.message("Welcome to PollText! Reply with Zip for Senators Email's.")
        try:
            if len(body) == 5:
                url = 'https://www.googleapis.com/civicinfo/v2/representatives?address='
                z_c = str(body)
                key = '&key=xxxxxxxxxxxxxxxxxxx'
                serviceurl = url+z_c+key
                address = serviceurl
                r.message(str(serviceurl + "Email"))

        except:
            r.message('Sorry, that was not a valid input message.')

    return str(r)

if __name__ == "__main__":
    app.run(debug=True)
</code>```

答:
Twilio developer evangelist here.

I popped your code into a Python validator and it also told me that the elif was wrong.

However, I then looked up the file a bit and noticed that under your if, it looked like this:

```<code>if body == 'SenPhone':
    r.message("Welcome to PollText! Reply with Zip for Senators Phone Num's.")
try:
    if len(body) == 5:
</code>```

So, the issue is that the try is outdented and has ended the conditional. I think if you indent that, then your syntax error will go away and you can continue to debug the rest from there.

Body:
I am trying to parse through the body message then return the values that the user requests. I couldn't figure out how to store a 5 character zipcode so I decided to use a try and except within the function. So essentially, I want the user to send the text, such as "SenEmail", then be prompted for their zipcode and return the the data (I currently only having it return the API call url for simplicity). However, its not working properly, I keep getting an error that my indentation is off or invalid syntax on the 'body == 'SenWeb': " and when it does work, it returns all 3 API call links, and not just the one associated with it. So SenPhone will return(Sending 3 texts of all the info rather than just 1), SenPhone, SenWeb and SenEmail rather than just SenPhone. I am fairly new to python, as you can probably tell. Thank you for your consideration.

import urllib.request as urlr
import urllib.parse as url
import urllib.error as urle
import json
import os
from flask import Flask, request, redirect
from twilio import twiml
from twilio.twiml.messaging_response import MessagingResponse

app = Flask(__name__)
@app.route('/sms', methods=['GET', 'POST'])

def sms_reply():
    r = MessagingResponse()
    body = request.values.get('Body', None)
    if body == 'SenPhone':
        r.message("Welcome to PollText! Reply with Zip for Senators Phone Num's.")
    try:
        if len(body) == 5:
            url = 'https://www.googleapis.com/civicinfo/v2/representatives?address='
            z_c = str(body)
            key = '&key=xxxxxxxxxxxxxxxxxxx'
            serviceurl = url+z_c+key
            address = serviceurl
            r.message(str(serviceurl + "Phone"))
        else:
            r.message("SenPhone, SenWeb, SenEmail")

    elif body == 'SenWeb':
        r.message("Welcome to PollText! Reply with Zip for Senators Website.")
        try:
            if len(body) == 5:
                url = 'https://www.googleapis.com/civicinfo/v2/representatives?address='
                z_c = str(body)
                key = '&key=xxxxxxxxxxxxxxxxxxx'
                serviceurl = url+z_c+key
                address = serviceurl
                r.message(str(serviceurl + "Website"))
            else:
                r.message("SenPhone, SenWeb, SenEmail")

    elif body == "SenEmail":
        r.message("Welcome to PollText! Reply with Zip for Senators Email's.")
        try:
            if len(body) == 5:
                url = 'https://www.googleapis.com/civicinfo/v2/representatives?address='
                z_c = str(body)
                key = '&key=xxxxxxxxxxxxxxxxxxx'
                serviceurl = url+z_c+key
                address = serviceurl
                r.message(str(serviceurl + "Email"))

        except:
            r.message('Sorry, that was not a valid input message.')

    return str(r)

if __name__ == "__main__":
    app.run(debug=True)

Body:
Twilio developer evangelist here.

I popped your code into a Python validator and it also told me that the elif was wrong.

However, I then looked up the file a bit and noticed that under your if, it looked like this:

if body == 'SenPhone':
    r.message("Welcome to PollText! Reply with Zip for Senators Phone Num's.")
try:
    if len(body) == 5:

So, the issue is that the try is outdented and has ended the conditional. I think if you indent that, then your syntax error will go away and you can continue to debug the rest from there.


来源: stackexchange

问:
duplicate records when updating Spring boot
I'm trying to do an update on records but instead of doing the update a new record is created

I'm using spring boot and angular js.
I tried circling with an if but I did not succeed

this is my method that I get the json from the screen and it passes to the object.

```<code>@RequestMapping(method = RequestMethod.POST, value = "/pacientes")
    public HttpStatus cadastrarPacientes(@RequestBody ObjectNode json) throws ParseException  {

        SimpleDateFormat formato = new SimpleDateFormat("dd/MM/yyyy");

            Entidades entidades = new Entidades();
            if(json.get("pessoa") != null && json.get("pessoa").get("entidade") != null && json.get("pessoa").get("entidade").get("idEntidade") != null ){
                entidades.setIdEntidade(json.get("pessoa").get("entidade").get("idEntidade").asLong());
                }

            Pessoas pessoas = new Pessoas();
            pessoas.setFoto(json.get("pessoa").get("foto").textValue()  == null ? null : json.get("pessoa").get("foto").textValue());
            pessoas.setNomePai(json.get("pessoa").get("nomePai") == null ? null : json.get("pessoa").get("nomePai").textValue());
            pessoas.setNomeMae(json.get("pessoa").get("nomeMae") == null ? null : json.get("pessoa").get("nomeMae").textValue());
            pessoas.setDataNascimento(formato.parse(json.get("pessoa").get("dataNascimento").textValue()));

            Paises pais = new Paises();
            pais.setIdPais(Long.parseLong(json.get("pessoasEnderecos").get("pais").get("idPais").textValue()));

            Ufs uf = new Ufs();
            uf.setIdUf(Long.parseLong(json.get("pessoasEnderecos").get("uf").get("idUf").textValue()));

            Municipios municipio = new Municipios();
            municipio.setIdMunicipio(Long.parseLong(json.get("pessoasEnderecos").get("municipio").get("idMunicipio").textValue()));

            OrientacoesSexuais oSexual = new OrientacoesSexuais();
            IdentidadesGenero iGene = new IdentidadesGenero();
            TiposSanguineos tSanguineo = new TiposSanguineos();

            PessoasCaracteristicas pCarac = new PessoasCaracteristicas();
            if(json.get("estatura")== null) {
                pCarac.setEstatura(null);
            }
            else {
                pCarac.setEstatura(json.get("pessoasCaracteristicas").get("estatura").asDouble());
            }

            if( json.get("peso")== null) {
                pCarac.setPeso(null);
            }
            else {
                pCarac.setPeso(json.get("pessoasCaracteristicas").get("peso").asDouble());
            }

            pCarac.setPessoa(new Pessoas());
            pCarac.setPessoa(pessoas);
            pCarac.setEntidade(new Entidades());
            pCarac.setEntidade(entidades);
            if(json.get("flagDeficiente")== null) {
                pCarac.setFlagDeficiente(null);
            }
            else {
                pCarac.setFlagDeficiente(json.get("pessoasCaracteristicas").get("flagDeficiente").asInt());
            }

            if(json.get("flagDoador")== null) {
                pCarac.setFlagDoador(null);
            }
            else {
                pCarac.setFlagDoador(json.get("pessoasCaracteristicas").get("flagDoador").asInt());
            }

            if(json.get("pessoasCaracteristicas") != null && json.get("pessoasCaracteristicas").get("tipoSanguineo") != null && json.get("pessoasCaracteristicas").get("tipoSanguineo").get("idTipoSanguineo") != null ){
                tSanguineo.setIdTipoSanguineo(json.get("pessoasCaracteristicas").get("tipoSanguineo").get("idTipoSanguineo").asLong());
                pCarac.setTipoSanguineo(new TiposSanguineos());
                pCarac.setTipoSanguineo(tSanguineo);
                }
            pCarac.setTipoSanguineo(tSanguineo);

            if(json.get("pessoasCaracteristicas") != null && json.get("pessoasCaracteristicas").get("identidadeGenero") != null && json.get("pessoasCaracteristicas").get("identidadeGenero").get("idIdentidade") != null ){
                iGene.setIdIdentidade(json.get("pessoasCaracteristicas").get("identidadeGenero").get("idIdentidade").asInt());
                pCarac.setIdentidadeGenero(new IdentidadesGenero());
                pCarac.setIdentidadeGenero(iGene);
                }

            if(json.get("pessoasCaracteristicas") != null && json.get("pessoasCaracteristicas").get("orientacaoSexual") != null && json.get("pessoasCaracteristicas").get("orientacaoSexual").get("idOrientacao") != null ){
                oSexual.setIdOrientacao(json.get("pessoasCaracteristicas").get("orientacaoSexual").get("idOrientacao").asInt());
                pCarac.setOrientacaoSexual(new OrientacoesSexuais());
                pCarac.setOrientacaoSexual(oSexual);
                }

            RacaCor racaCor = new RacaCor();

            Sexo sexo = new Sexo();
            sexo.setIdSexo(Long.parseLong(json.get("pessoasFisicas").get("sexo").get("idSexo").textValue()));

            Nacionalidades nac = new Nacionalidades();

            Escolaridade escolaridade = new Escolaridade();

            Cbos cbos = new Cbos();

            EstadosCivis estadosCivis = new EstadosCivis();

            PessoasFisicas pFisicas = new PessoasFisicas();
            pFisicas.setCarteiraProfissional(json.get("pessoasFisicas").get("carteiraProfissional")== null ? null : json.get("pessoasFisicas").get("carteiraProfissional").textValue());
            pFisicas.setCertidaoObito(json.get("pessoasFisicas").get("certidaoObito")== null ? null : json.get("pessoasFisicas").get("certidaoObito").textValue());
            pFisicas.setCodigoReservista(json.get("pessoasFisicas").get("codigoReservista")== null ? null : json.get("pessoasFisicas").get("codigoReservista").textValue());

            if (json.get("dataObito") == null) {
                pFisicas.setDataCadastroPisPasep(null);
                } else {
                pFisicas.setDataCadastroPisPasep(
                        formato.parse(json.get("pessoasFisicas").get("dataObito").textValue()));
                }

            if (json.get("dataCadastroPisPasep") == null) {
            pFisicas.setDataCadastroPisPasep(null);
            } else {
            pFisicas.setDataCadastroPisPasep(
                    formato.parse(json.get("pessoasFisicas").get("dataCadastroPisPasep").textValue()));
            }

            if (json.get("emissaoCarteiraProfissional") == null) {
            pFisicas.setDataCadastroPisPasep(null);
            } else {
            pFisicas.setDataCadastroPisPasep(
                    formato.parse(json.get("pessoasFisicas").get("emissaoCarteiraProfissional").textValue()));
            }

            pFisicas.setCpf(json.get("pessoasFisicas").get("cpf")== null ? null : json.get("pessoasFisicas").get("cpf").textValue());
            pFisicas.setEntidade(new Entidades());
            pFisicas.setEntidade(entidades);
            if(json.get("pessoasFisicas") != null && json.get("pessoasFisicas").get("escolaridade") != null && json.get("pessoasFisicas").get("escolaridade").get("idEscolaridade") != null ){
                escolaridade.setIdEscolaridade(json.get("pessoasFisicas").get("escolaridade").get("idEscolaridade").asLong());
                pFisicas.setEscolaridade(new Escolaridade());
                pFisicas.setEscolaridade(escolaridade);
                }

            if(json.get("pessoasFisicas") != null && json.get("pessoasFisicas").get("estadoCivil") != null && json.get("pessoasFisicas").get("estadoCivil").get("idEstadoCivil") != null ){
                estadosCivis.setIdEstadoCivil(json.get("pessoasFisicas").get("estadoCivil").get("idEstadoCivil").asLong());
                pFisicas.setEstadoCivil(new EstadosCivis());
                pFisicas.setEstadoCivil(estadosCivis);
                }

            if(json.get("flagAtivo")== null) {
                pFisicas.setFlagAtivo(null);
            }
            else {
                pFisicas.setFlagAtivo(json.get("flagAtivo").intValue());
            }

            pFisicas.setIdentidadeRg(json.get("pessoasFisicas").get("identidadeRg")== null ? null : json.get("pessoasFisicas").get("identidadeRg").textValue());
            if(json.get("pessoasFisicas") != null && json.get("pessoasFisicas").get("nacionalidade") != null && json.get("pessoasFisicas").get("nacionalidade").get("idNacionalidade") != null ){
                nac.setIdNacionalidade(json.get("pessoasFisicas").get("nacionalidade").get("idNacionalidade").asLong());
                pFisicas.setNacionalidade(new Nacionalidades());
                pFisicas.setNacionalidade(nac);
                }
            pFisicas.setOrgaoEmissorRg(json.get("pessoasFisicas").get("orgaoEmissorRg")== null ? null : json.get("pessoasFisicas").get("orgaoEmissorRg").textValue());
            pFisicas.setPessoa( new Pessoas());
            pFisicas.setPessoa(pessoas);
            pFisicas.setPisPasep(json.get("pessoasFisicas").get("pisPasep")== null ? null : json.get("pessoasFisicas").get("pisPasep").textValue());

            if(json.get("pessoasFisicas") != null && json.get("pessoasFisicas").get("racaCor") != null && json.get("pessoasFisicas").get("racaCor").get("idRacaCor") != null ){
                racaCor.setIdRacaCor(json.get("pessoasFisicas").get("racaCor").get("idRacaCor").asLong());
                pFisicas.setRacaCor(new RacaCor());
                pFisicas.setRacaCor(racaCor);
                }

            pFisicas.setSecaoEleitoral(json.get("pessoasFisicas").get("secaoEleitoral")== null ? null : json.get("pessoasFisicas").get("secaoEleitoral").textValue());
            pFisicas.setSerieCarteiraProfissional(json.get("pessoasFisicas").get("serieCarteiraProfissional")== null ? null : json.get("pessoasFisicas").get("serieCarteiraProfissional").textValue());
            pFisicas.setSexo(new Sexo());
            pFisicas.setSexo(sexo);
            pFisicas.setTituloEleitor(json.get("pessoasFisicas").get("tituloEleitor")== null ? null : json.get("pessoasFisicas").get("tituloEleitor").textValue());
            pFisicas.setUfOrgaoEmissor(json.get("pessoasFisicas").get("ufOrgaoEmissor")== null ? null : json.get("pessoasFisicas").get("ufOrgaoEmissor").textValue());
            pFisicas.setZonaEleitoral(json.get("pessoasFisicas").get("zonaEleitoral")== null ? null : json.get("pessoasFisicas").get("zonaEleitoral").textValue());

            if(json.get("pessoasFisicas") != null && json.get("pessoasFisicas").get("cbo") != null && json.get("pessoasFisicas").get("cbo").get("idCbo") != null ){
                cbos.setIdCbo(json.get("pessoasFisicas").get("cbo").get("idCbo").asLong());
                pFisicas.setCbo(new Cbos());
                pFisicas.setCbo(cbos);
                }

            TiposContatos tContatos = new TiposContatos();

            PessoasContatos pContato = new PessoasContatos();
            pContato.setContato(json.get("contato")== null ? null : json.get("contato").textValue());
            pContato.setEntidade(new Entidades());

            if(json.get("pessoasContatos") != null && json.get("pessoasContatos").get("tipoContato") != null && json.get("pessoasContatos").get("tipoContato").get("idTipoContato") != null ){
                tContatos.setIdTipoContato(json.get("pessoasContatos").get("tipoContato").get("idTipoContato").asInt());
                pContato.setTipoContato(new TiposContatos());
                pContato.setTipoContato(tContatos);
                }

            PessoasEnderecos pessoasEnderecos = new PessoasEnderecos();
            pessoasEnderecos.setCep(json.get("pessoasEnderecos").get("cep")== null ? null : json.get("pessoasEnderecos").get("cep").textValue());
            pessoasEnderecos.setNomeLogradouro(json.get("pessoasEnderecos").get("nomeLogradouro")== null ? null : json.get("pessoasEnderecos").get("nomeLogradouro").textValue());

            Pacientes pac = new Pacientes();
            pac.setPessoa(new Pessoas());
            pac.setPessoa(pessoas);
            pac.setCns(json.get("cns")== null ? null : json.get("cns").textValue());
            pac.setObservacoesAlergias(json.get("observacoesAlergias")== null ? null : json.get("observacoesAlergias").textValue());
            if(json.get("flagAlergico")== null) {
                pac.setFlagAlergico(null);
            }
            else {
                pac.setFlagAlergico(json.get("flagAlergico").asInt());
            }

            pac.setCnsResponsavel(json.get("cnsResponsavel")== null ? null : json.get("cnsResponsavel").textValue());
            pac.setCpfResponsavel(json.get("cpfResponsavel")== null ? null : json.get("cpfResponsavel").textValue());
            pac.setNomeResponsavel(json.get("nomeResponsavel")== null ? null : json.get("nomeResponsavel").textValue());

            //update here
            if(json.get("idPaciente").asInt() != 0) {
                pacientesService.alterar(pFisicas, pCarac,pessoasEnderecos, pac);

            }
            else { //save here
                pacientesService.cadastrarPacientes(pFisicas, pCarac,pessoasEnderecos, pac );
            }

        return HttpStatus.CREATED;
    }
</code>```

i will show my service class.. nothing

```<code>    //save here
         @Transactional
                public void cadastrarPacientes(PessoasFisicas pFisicas,
 PessoasCaracteristicas pCarac,PessoasEnderecos pessoasEnderecos,  Pacientes pac) {
                    pacRepository.saveAndFlush(pac);
                    pessoasEnderecosRepository.saveAndFlush(pessoasEnderecos);
                    pesFisicasRepository.saveAndFlush(pFisicas);
                    pescaracteristicasRepository.saveAndFlush(pCarac);

                }
</code>```

// update here..

```<code>    @Transactional
       public void alterar(PessoasFisicas pFisicas, PessoasCaracteristicas
      pCarac,PessoasEnderecos pessoasEnderecos,  Pacientes pac) {
            pacRepository.saveAndFlush(pac);
            pessoasEnderecosRepository.saveAndFlush(pessoasEnderecos);
            pesFisicasRepository.saveAndFlush(pFisicas);
            pescaracteristicasRepository.saveAndFlush(pCarac);

        }
</code>```

Where is my mistake?

i got this json in my back

```<code>{"idPaciente":161,"pessoa":{"idPessoa":165,"dataNascimento":"02/01/1987"...
</code>```

答: You have the primary key(idPaciente) in your json but not in object pac, so you should set the primary key before updating the records.

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to do an update on records but instead of doing the update a new record is created

I'm using spring boot and angular js.
I tried circling with an if but I did not succeed

this is my method that I get the json from the screen and it passes to the object.

@RequestMapping(method = RequestMethod.POST, value = "/pacientes")
    public HttpStatus cadastrarPacientes(@RequestBody ObjectNode json) throws ParseException  {

        SimpleDateFormat formato = new SimpleDateFormat("dd/MM/yyyy");

            Entidades entidades = new Entidades();
            if(json.get("pessoa") != null && json.get("pessoa").get("entidade") != null && json.get("pessoa").get("entidade").get("idEntidade") != null ){
                entidades.setIdEntidade(json.get("pessoa").get("entidade").get("idEntidade").asLong());
                }

            Pessoas pessoas = new Pessoas();
            pessoas.setFoto(json.get("pessoa").get("foto").textValue()  == null ? null : json.get("pessoa").get("foto").textValue());
            pessoas.setNomePai(json.get("pessoa").get("nomePai") == null ? null : json.get("pessoa").get("nomePai").textValue());
            pessoas.setNomeMae(json.get("pessoa").get("nomeMae") == null ? null : json.get("pessoa").get("nomeMae").textValue());
            pessoas.setDataNascimento(formato.parse(json.get("pessoa").get("dataNascimento").textValue()));

            Paises pais = new Paises();
            pais.setIdPais(Long.parseLong(json.get("pessoasEnderecos").get("pais").get("idPais").textValue()));

            Ufs uf = new Ufs();
            uf.setIdUf(Long.parseLong(json.get("pessoasEnderecos").get("uf").get("idUf").textValue()));

            Municipios municipio = new Municipios();
            municipio.setIdMunicipio(Long.parseLong(json.get("pessoasEnderecos").get("municipio").get("idMunicipio").textValue()));

            OrientacoesSexuais oSexual = new OrientacoesSexuais();
            IdentidadesGenero iGene = new IdentidadesGenero();
            TiposSanguineos tSanguineo = new TiposSanguineos();

            PessoasCaracteristicas pCarac = new PessoasCaracteristicas();
            if(json.get("estatura")== null) {
                pCarac.setEstatura(null);
            }
            else {
                pCarac.setEstatura(json.get("pessoasCaracteristicas").get("estatura").asDouble());
            }

            if( json.get("peso")== null) {
                pCarac.setPeso(null);
            }
            else {
                pCarac.setPeso(json.get("pessoasCaracteristicas").get("peso").asDouble());
            }

            pCarac.setPessoa(new Pessoas());
            pCarac.setPessoa(pessoas);
            pCarac.setEntidade(new Entidades());
            pCarac.setEntidade(entidades);
            if(json.get("flagDeficiente")== null) {
                pCarac.setFlagDeficiente(null);
            }
            else {
                pCarac.setFlagDeficiente(json.get("pessoasCaracteristicas").get("flagDeficiente").asInt());
            }

            if(json.get("flagDoador")== null) {
                pCarac.setFlagDoador(null);
            }
            else {
                pCarac.setFlagDoador(json.get("pessoasCaracteristicas").get("flagDoador").asInt());
            }

            if(json.get("pessoasCaracteristicas") != null && json.get("pessoasCaracteristicas").get("tipoSanguineo") != null && json.get("pessoasCaracteristicas").get("tipoSanguineo").get("idTipoSanguineo") != null ){
                tSanguineo.setIdTipoSanguineo(json.get("pessoasCaracteristicas").get("tipoSanguineo").get("idTipoSanguineo").asLong());
                pCarac.setTipoSanguineo(new TiposSanguineos());
                pCarac.setTipoSanguineo(tSanguineo);
                }
            pCarac.setTipoSanguineo(tSanguineo);

            if(json.get("pessoasCaracteristicas") != null && json.get("pessoasCaracteristicas").get("identidadeGenero") != null && json.get("pessoasCaracteristicas").get("identidadeGenero").get("idIdentidade") != null ){
                iGene.setIdIdentidade(json.get("pessoasCaracteristicas").get("identidadeGenero").get("idIdentidade").asInt());
                pCarac.setIdentidadeGenero(new IdentidadesGenero());
                pCarac.setIdentidadeGenero(iGene);
                }

            if(json.get("pessoasCaracteristicas") != null && json.get("pessoasCaracteristicas").get("orientacaoSexual") != null && json.get("pessoasCaracteristicas").get("orientacaoSexual").get("idOrientacao") != null ){
                oSexual.setIdOrientacao(json.get("pessoasCaracteristicas").get("orientacaoSexual").get("idOrientacao").asInt());
                pCarac.setOrientacaoSexual(new OrientacoesSexuais());
                pCarac.setOrientacaoSexual(oSexual);
                }

            RacaCor racaCor = new RacaCor();

            Sexo sexo = new Sexo();
            sexo.setIdSexo(Long.parseLong(json.get("pessoasFisicas").get("sexo").get("idSexo").textValue()));

            Nacionalidades nac = new Nacionalidades();

            Escolaridade escolaridade = new Escolaridade();

            Cbos cbos = new Cbos();

            EstadosCivis estadosCivis = new EstadosCivis();

            PessoasFisicas pFisicas = new PessoasFisicas();
            pFisicas.setCarteiraProfissional(json.get("pessoasFisicas").get("carteiraProfissional")== null ? null : json.get("pessoasFisicas").get("carteiraProfissional").textValue());
            pFisicas.setCertidaoObito(json.get("pessoasFisicas").get("certidaoObito")== null ? null : json.get("pessoasFisicas").get("certidaoObito").textValue());
            pFisicas.setCodigoReservista(json.get("pessoasFisicas").get("codigoReservista")== null ? null : json.get("pessoasFisicas").get("codigoReservista").textValue());

            if (json.get("dataObito") == null) {
                pFisicas.setDataCadastroPisPasep(null);
                } else {
                pFisicas.setDataCadastroPisPasep(
                        formato.parse(json.get("pessoasFisicas").get("dataObito").textValue()));
                }

            if (json.get("dataCadastroPisPasep") == null) {
            pFisicas.setDataCadastroPisPasep(null);
            } else {
            pFisicas.setDataCadastroPisPasep(
                    formato.parse(json.get("pessoasFisicas").get("dataCadastroPisPasep").textValue()));
            }

            if (json.get("emissaoCarteiraProfissional") == null) {
            pFisicas.setDataCadastroPisPasep(null);
            } else {
            pFisicas.setDataCadastroPisPasep(
                    formato.parse(json.get("pessoasFisicas").get("emissaoCarteiraProfissional").textValue()));
            }

            pFisicas.setCpf(json.get("pessoasFisicas").get("cpf")== null ? null : json.get("pessoasFisicas").get("cpf").textValue());
            pFisicas.setEntidade(new Entidades());
            pFisicas.setEntidade(entidades);
            if(json.get("pessoasFisicas") != null && json.get("pessoasFisicas").get("escolaridade") != null && json.get("pessoasFisicas").get("escolaridade").get("idEscolaridade") != null ){
                escolaridade.setIdEscolaridade(json.get("pessoasFisicas").get("escolaridade").get("idEscolaridade").asLong());
                pFisicas.setEscolaridade(new Escolaridade());
                pFisicas.setEscolaridade(escolaridade);
                }

            if(json.get("pessoasFisicas") != null && json.get("pessoasFisicas").get("estadoCivil") != null && json.get("pessoasFisicas").get("estadoCivil").get("idEstadoCivil") != null ){
                estadosCivis.setIdEstadoCivil(json.get("pessoasFisicas").get("estadoCivil").get("idEstadoCivil").asLong());
                pFisicas.setEstadoCivil(new EstadosCivis());
                pFisicas.setEstadoCivil(estadosCivis);
                }

            if(json.get("flagAtivo")== null) {
                pFisicas.setFlagAtivo(null);
            }
            else {
                pFisicas.setFlagAtivo(json.get("flagAtivo").intValue());
            }

            pFisicas.setIdentidadeRg(json.get("pessoasFisicas").get("identidadeRg")== null ? null : json.get("pessoasFisicas").get("identidadeRg").textValue());
            if(json.get("pessoasFisicas") != null && json.get("pessoasFisicas").get("nacionalidade") != null && json.get("pessoasFisicas").get("nacionalidade").get("idNacionalidade") != null ){
                nac.setIdNacionalidade(json.get("pessoasFisicas").get("nacionalidade").get("idNacionalidade").asLong());
                pFisicas.setNacionalidade(new Nacionalidades());
                pFisicas.setNacionalidade(nac);
                }
            pFisicas.setOrgaoEmissorRg(json.get("pessoasFisicas").get("orgaoEmissorRg")== null ? null : json.get("pessoasFisicas").get("orgaoEmissorRg").textValue());
            pFisicas.setPessoa( new Pessoas());
            pFisicas.setPessoa(pessoas);
            pFisicas.setPisPasep(json.get("pessoasFisicas").get("pisPasep")== null ? null : json.get("pessoasFisicas").get("pisPasep").textValue());

            if(json.get("pessoasFisicas") != null && json.get("pessoasFisicas").get("racaCor") != null && json.get("pessoasFisicas").get("racaCor").get("idRacaCor") != null ){
                racaCor.setIdRacaCor(json.get("pessoasFisicas").get("racaCor").get("idRacaCor").asLong());
                pFisicas.setRacaCor(new RacaCor());
                pFisicas.setRacaCor(racaCor);
                }

            pFisicas.setSecaoEleitoral(json.get("pessoasFisicas").get("secaoEleitoral")== null ? null : json.get("pessoasFisicas").get("secaoEleitoral").textValue());
            pFisicas.setSerieCarteiraProfissional(json.get("pessoasFisicas").get("serieCarteiraProfissional")== null ? null : json.get("pessoasFisicas").get("serieCarteiraProfissional").textValue());
            pFisicas.setSexo(new Sexo());
            pFisicas.setSexo(sexo);
            pFisicas.setTituloEleitor(json.get("pessoasFisicas").get("tituloEleitor")== null ? null : json.get("pessoasFisicas").get("tituloEleitor").textValue());
            pFisicas.setUfOrgaoEmissor(json.get("pessoasFisicas").get("ufOrgaoEmissor")== null ? null : json.get("pessoasFisicas").get("ufOrgaoEmissor").textValue());
            pFisicas.setZonaEleitoral(json.get("pessoasFisicas").get("zonaEleitoral")== null ? null : json.get("pessoasFisicas").get("zonaEleitoral").textValue());

            if(json.get("pessoasFisicas") != null && json.get("pessoasFisicas").get("cbo") != null && json.get("pessoasFisicas").get("cbo").get("idCbo") != null ){
                cbos.setIdCbo(json.get("pessoasFisicas").get("cbo").get("idCbo").asLong());
                pFisicas.setCbo(new Cbos());
                pFisicas.setCbo(cbos);
                }

            TiposContatos tContatos = new TiposContatos();

            PessoasContatos pContato = new PessoasContatos();
            pContato.setContato(json.get("contato")== null ? null : json.get("contato").textValue());
            pContato.setEntidade(new Entidades());

            if(json.get("pessoasContatos") != null && json.get("pessoasContatos").get("tipoContato") != null && json.get("pessoasContatos").get("tipoContato").get("idTipoContato") != null ){
                tContatos.setIdTipoContato(json.get("pessoasContatos").get("tipoContato").get("idTipoContato").asInt());
                pContato.setTipoContato(new TiposContatos());
                pContato.setTipoContato(tContatos);
                }

            PessoasEnderecos pessoasEnderecos = new PessoasEnderecos();
            pessoasEnderecos.setCep(json.get("pessoasEnderecos").get("cep")== null ? null : json.get("pessoasEnderecos").get("cep").textValue());
            pessoasEnderecos.setNomeLogradouro(json.get("pessoasEnderecos").get("nomeLogradouro")== null ? null : json.get("pessoasEnderecos").get("nomeLogradouro").textValue());

            Pacientes pac = new Pacientes();
            pac.setPessoa(new Pessoas());
            pac.setPessoa(pessoas);
            pac.setCns(json.get("cns")== null ? null : json.get("cns").textValue());
            pac.setObservacoesAlergias(json.get("observacoesAlergias")== null ? null : json.get("observacoesAlergias").textValue());
            if(json.get("flagAlergico")== null) {
                pac.setFlagAlergico(null);
            }
            else {
                pac.setFlagAlergico(json.get("flagAlergico").asInt());
            }

            pac.setCnsResponsavel(json.get("cnsResponsavel")== null ? null : json.get("cnsResponsavel").textValue());
            pac.setCpfResponsavel(json.get("cpfResponsavel")== null ? null : json.get("cpfResponsavel").textValue());
            pac.setNomeResponsavel(json.get("nomeResponsavel")== null ? null : json.get("nomeResponsavel").textValue());

            //update here
            if(json.get("idPaciente").asInt() != 0) {
                pacientesService.alterar(pFisicas, pCarac,pessoasEnderecos, pac);

            }
            else { //save here
                pacientesService.cadastrarPacientes(pFisicas, pCarac,pessoasEnderecos, pac );
            }

        return HttpStatus.CREATED;
    }

i will show my service class.. nothing

    //save here
         @Transactional
                public void cadastrarPacientes(PessoasFisicas pFisicas,
 PessoasCaracteristicas pCarac,PessoasEnderecos pessoasEnderecos,  Pacientes pac) {
                    pacRepository.saveAndFlush(pac);
                    pessoasEnderecosRepository.saveAndFlush(pessoasEnderecos);
                    pesFisicasRepository.saveAndFlush(pFisicas);
                    pescaracteristicasRepository.saveAndFlush(pCarac);

                }

// update here..

    @Transactional
       public void alterar(PessoasFisicas pFisicas, PessoasCaracteristicas
      pCarac,PessoasEnderecos pessoasEnderecos,  Pacientes pac) {
            pacRepository.saveAndFlush(pac);
            pessoasEnderecosRepository.saveAndFlush(pessoasEnderecos);
            pesFisicasRepository.saveAndFlush(pFisicas);
            pescaracteristicasRepository.saveAndFlush(pCarac);

        }

Where is my mistake?

i got this json in my back

{"idPaciente":161,"pessoa":{"idPessoa":165,"dataNascimento":"02/01/1987"...


问:
deploy spring boot war into tomcat
i am using spring boot and i want to deploy a rest API war file into tomcat server.
There is no errors in the tomcat server logs but when i call any endpoint i got 404 "not found" and i got the same from the tomcat server .

java version : 8.
tomcat version : 9.

maybe i miss something , here are my code samples :

Pom :

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.test</groupId>
<artifactId>test</artifactId>
<version>1.1</version>
<packaging>war</packaging>

<name>test</name>
<description>test API</description>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.1.RELEASE</version>
    <relativePath /> <!-- lookup parent from repository -->
</parent>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-
8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
</properties>

<dependencies>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-tomcat</artifactId>
        <scope>provided</scope>
    </dependency>

        <!-- tag::security[] -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
    <!-- end::security[] -->

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-jdbc</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
</dependencies>

<build>
    <defaultGoal>install</defaultGoal>

    <pluginManagement>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-assembly-plugin</artifactId>
                <version>3.0.0</version>
            </plugin>

        </plugins>
    </pluginManagement>
    <!-- To use the plugin goals in your POM or parent POM -->
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-assembly-plugin</artifactId>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <configuration>
                <source>1.8</source>
                <target>1.8</target>
            </configuration>
        </plugin>
    </plugins>
 </build>
 </project>
</code>```

2.Application.java

```<code>@SpringBootApplication
public class TestApplication extends SpringBootServletInitializer {

@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder
application) {
    return application.sources(TestApplication.class);
    }

public static void main(String[] args) {
SpringApplication.run(TestApplication.class, args);
}

}
</code>```

答:
run your spring boot app in your tomcat server as a ROOT context.

u can do it by change ROOT.war in tomcat server with your spring boot app ( this is a bad way ) or u can configure it.

Title: deploy spring boot war into tomcat

Body:
i am using spring boot and i want to deploy a rest API war file into tomcat server.
There is no errors in the tomcat server logs but when i call any endpoint i got 404 "not found" and i got the same from the tomcat server .

java version : 8.
tomcat version : 9.

maybe i miss something , here are my code samples :

Pom :

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.test</groupId>
<artifactId>test</artifactId>
<version>1.1</version>
<packaging>war</packaging>

<name>test</name>
<description>test API</description>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.1.RELEASE</version>
    <relativePath />
</parent>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-
8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
</properties>

<dependencies>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-tomcat</artifactId>
        <scope>provided</scope>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-jdbc</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
</dependencies>

<build>
    <defaultGoal>install</defaultGoal>

    <pluginManagement>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-assembly-plugin</artifactId>
                <version>3.0.0</version>
            </plugin>

        </plugins>
    </pluginManagement>

    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-assembly-plugin</artifactId>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <configuration>
                <source>1.8</source>
                <target>1.8</target>
            </configuration>
        </plugin>
    </plugins>
 </build>
 </project>

2.Application.java

@SpringBootApplication
public class TestApplication extends SpringBootServletInitializer {

@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder
application) {
    return application.sources(TestApplication.class);
    }

public static void main(String[] args) {
SpringApplication.run(TestApplication.class, args);
}

}


问:
Debugging Python Fatal Error: GC Object already Tracked
My python code has been crashing with error 'GC Object already Tracked' . Trying to figure out the best approach to debug this crashes.

OS : Linux.

Is there a proper way to debug this issue.

There were couple of suggestions in the following article.
Python memory debugging with GDB

Not sure which approach worked for the author.

Is there a way to generate memory dumps in such scenario which could be analyzed. Like in Windows world.

Found some article on this. But not entirely answers my question:
http://pfigue.github.io/blog/2012/12/28/where-is-my-core-dump-archlinux/

答:
I ran into this problem using boost::python when our C++ code would trigger a python callback. I would occasionally get "GC object already tracked" and the program would terminate.

I was able to attach GDB to the process prior to triggering the error. One interesting thing, in the python code we were wrapping the callback with
a functools partial, which was actually masking where the real error was occuring. After replacing the partial with a simple callable wrapper class. The "GC object already tracked error" no longer popped up, instead I was now just getting a segfault.

In our boost::python wrapper, we had lambda functions to handle a C++ callback and the lambda function captured the boost::python::object  callback function. It turned out, for whatever reason, in the destructor for the lambda, it wasn't always properly acquiring the GIL when destroying the boost::python::object which was causing the segfault.

The fix was to not use a lambda function, but instead create a functor that makes sure to acquire the GIL in the destructor prior to calling PyDECREF() on the boost::python::object.

```<code>class callback_wrapper
{
public:
    callback_wrapper(object cb): _cb(cb), _destroyed(false) {
    }

    callback_wrapper(const callback_wrapper& other) {
        _destroyed = other._destroyed;
        Py_INCREF(other._cb.ptr());
        _cb = other._cb;
    }

    ~callback_wrapper() {
        std::lock_guard<std::recursive_mutex> guard(_mutex);
        PyGILState_STATE state = PyGILState_Ensure();
        Py_DECREF(_cb.ptr());
        PyGILState_Release(state);
        _destroyed = true;
    }

    void operator ()(topic_ptr topic) {
        std::lock_guard<std::recursive_mutex> guard(_mutex);
        if(_destroyed) {
            return;
        }
        PyGILState_STATE state = PyGILState_Ensure();
        try {
            _cb(topic);
        }
        catch(error_already_set) { PyErr_Print(); }
        PyGILState_Release(state);
    }

    object _cb;
    std::recursive_mutex _mutex;
    bool _destroyed;
};
</code>```

Body:
I ran into this problem using boost::python when our C++ code would trigger a python callback. I would occasionally get "GC object already tracked" and the program would terminate.

I was able to attach GDB to the process prior to triggering the error. One interesting thing, in the python code we were wrapping the callback with
a functools partial, which was actually masking where the real error was occuring. After replacing the partial with a simple callable wrapper class. The "GC object already tracked error" no longer popped up, instead I was now just getting a segfault.

In our boost::python wrapper, we had lambda functions to handle a C++ callback and the lambda function captured the boost::python::object  callback function. It turned out, for whatever reason, in the destructor for the lambda, it wasn't always properly acquiring the GIL when destroying the boost::python::object which was causing the segfault.

The fix was to not use a lambda function, but instead create a functor that makes sure to acquire the GIL in the destructor prior to calling PyDECREF() on the boost::python::object.

class callback_wrapper
{
public:
    callback_wrapper(object cb): _cb(cb), _destroyed(false) {
    }

    callback_wrapper(const callback_wrapper& other) {
        _destroyed = other._destroyed;
        Py_INCREF(other._cb.ptr());
        _cb = other._cb;
    }

    ~callback_wrapper() {
        std::lock_guard<std::recursive_mutex> guard(_mutex);
        PyGILState_STATE state = PyGILState_Ensure();
        Py_DECREF(_cb.ptr());
        PyGILState_Release(state);
        _destroyed = true;
    }

    void operator ()(topic_ptr topic) {
        std::lock_guard<std::recursive_mutex> guard(_mutex);
        if(_destroyed) {
            return;
        }
        PyGILState_STATE state = PyGILState_Ensure();
        try {
            _cb(topic);
        }
        catch(error_already_set) { PyErr_Print(); }
        PyGILState_Release(state);
    }

    object _cb;
    std::recursive_mutex _mutex;
    bool _destroyed;
};


问:
Enabled Brigded Network in Vmware Server
I have the vmware server with this error, anyone knows how to fix it?VMware Server Error http://soporte.cardinalsystems.com.ar/errorvmwareserver.jpg</p>

答:
No Idea what I do, but now its working.

this is all I have done:

reinstall Vmware server several times ( more than 4 )

Fix network adapter

prey ( more than 1000 times)

UPDATE: One of the three VM does not work the other works perfect.

OwnerDisplayName: Jedi Master Spooky

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Jedi Master Spooky


问:
How to determine the platform Qt is running on at runtime?
Is there a (Qt) way to determine the platform a Qt application is running on at runtime?</p>

答:
Note that the Q_WS_* macros are defined at compile time, but QSysInfo gives some run time details.

To extend gs's function to get the specific windows version at runtime, you can do

```<code>#ifdef Q_WS_WIN
switch(QSysInfo::windowsVersion())
{
  case QSysInfo::WV_2000: return "Windows 2000";
  case QSysInfo::WV_XP: return "Windows XP";
  case QSysInfo::WV_VISTA: return "Windows Vista";
  default: return "Windows";
}
#endif
</code>```

and similar for Mac.

If you are using a Qt version 5.9 or above, kindly use the below mentioned library function to retrieve correct OS details, more on this can be found here. There is also a QSysInfo class which can do some additional functionalities.

```<code>#ifdef Q_WS_WIN
#include <QOperatingSystemVersion>

switch(QOperatingSystemVersion::current())
{
  case QOperatingSystemVersion::Windows7: return "Windows 7";
  case QOperatingSystemVersion::Windows8: return "Windows 8";
  case QOperatingSystemVersion::Windows10: return "Windows 10";
  default: return "Windows";
}
#endif
</code>```

OwnerDisplayName: andreas buykx

Body:
Note that the Q_WS_* macros are defined at compile time, but QSysInfo gives some run time details.

To extend gs's function to get the specific windows version at runtime, you can do

#ifdef Q_WS_WIN
switch(QSysInfo::windowsVersion())
{
  case QSysInfo::WV_2000: return "Windows 2000";
  case QSysInfo::WV_XP: return "Windows XP";
  case QSysInfo::WV_VISTA: return "Windows Vista";
  default: return "Windows";
}
#endif

and similar for Mac.

If you are using a Qt version 5.9 or above, kindly use the below mentioned library function to retrieve correct OS details, more on this can be found here. There is also a QSysInfo class which can do some additional functionalities.

#ifdef Q_WS_WIN
#include <QOperatingSystemVersion>

switch(QOperatingSystemVersion::current())
{
  case QOperatingSystemVersion::Windows7: return "Windows 7";
  case QOperatingSystemVersion::Windows8: return "Windows 8";
  case QOperatingSystemVersion::Windows10: return "Windows 10";
  default: return "Windows";
}
#endif

OwnerDisplayName: Reed Hedges

ContentLicense: CC BY-SA 4.0


问:
Coordinate matching matrix's in R
currently I have to matrixs, and I am trying to return the index values where they match in z?
This is what I have currently

```<code>           x y
matrixloc 0 0
          2 1
          2 3
          2 6
          5 5
          6 7
          4 9
> z
 x y
[1,] 2 6
[2,] 3 4
[3,] 5 5
[4,] 2 1
[5,] 2 3
[6,] 6 7
[7,] 4 9
[8,] 6 8
</code>```

currently the output I am getting is  :

```<code>     match(matrixloc,z)
  NA  1  1  1  3  6  7 NA 12  2  6  3 14 15
</code>```

Any suggestions on how to fix this?

答:
Here is one (of many) ways using match on the pasted column entries

```<code># Your sample data
matrixloc <- as.matrix(read.table(text =
    "x y
     0 0
     2 1
     2 3
     2 6
     5 5
     6 7
     4 9", header = T));
z <- as.matrix(read.table(text =
    "x y
     2 6
     3 4
     5 5
     2 1
     2 3
     6 7
     4 9
     6 8", header = T));

match(apply(matrixloc, 1, paste, collapse = "_"), apply(z, 1, paste, collapse = "_"));
#[1] NA  4  5  1  3  6  7
</code>```

Also, the plural form of "matrix" is "matrices", not "matrixs".

Title: Coordinate matching matrix's in R

Body:
currently I have to matrixs, and I am trying to return the index values where they match in z?
This is what I have currently

           x y
matrixloc 0 0
          2 1
          2 3
          2 6
          5 5
          6 7
          4 9
> z
 x y
[1,] 2 6
[2,] 3 4
[3,] 5 5
[4,] 2 1
[5,] 2 3
[6,] 6 7
[7,] 4 9
[8,] 6 8

currently the output I am getting is  :

     match(matrixloc,z)
  NA  1  1  1  3  6  7 NA 12  2  6  3 14 15

Any suggestions on how to fix this?

Body:
Here is one (of many) ways using match on the pasted column entries

# Your sample data
matrixloc <- as.matrix(read.table(text =
    "x y
     0 0
     2 1
     2 3
     2 6
     5 5
     6 7
     4 9", header = T));
z <- as.matrix(read.table(text =
    "x y
     2 6
     3 4
     5 5
     2 1
     2 3
     6 7
     4 9
     6 8", header = T));

match(apply(matrixloc, 1, paste, collapse = "_"), apply(z, 1, paste, collapse = "_"));
#[1] NA  4  5  1  3  6  7

Also, the plural form of "matrix" is "matrices", not "matrixs".


问:
Firebase Security Rules - Checking if data.hasChild and keeps failing
I have a security rule that looks like this:

```<code>"user_feeds": {
     "$userId": {
        ".indexOn": ["timestamp"],
        ".read": "auth != null",
         "$postId" : {
           ".write": "auth != null && newData.parent().hasChild(newData.child('band_id').val())"
           }
         }
       }
</code>```

in my $postId sub-tree, I'm trying to check to see if the parent has a node that corresponds to the band_id value of the data that is being inserted.

The data looks like:

```<code>{
   post_id: 1,
   band_id: '-L-tyesfsdf13434',
   timestamp: 34234234234
}
</code>```

And an actual tree that these rules would correspond to look like:

```<code>{
   "user_feeds": {
     "userId1": {
        "-L-tyesfsdf13434": true
     }
   }
}
</code>```

I am using Ionic/Angular and here is my function that's actually trying to do the write operation:

```<code>addPostToFollowers(bandId, postId) {

    // 1. Get the user's connections
    this._bands.getBandFollowers(bandId).take(1).subscribe(connections => {
      if(connections.$value !== null) {
        delete connections['$key'];
        delete connections['$exists'];

        let connectionKeys = Object.keys(connections);
        // 2. Go through those connections and add the post
        let bandFeeds = {};
        connectionKeys.forEach(connectionKey => {
          bandFeeds[`/user_feeds/${connectionKey}/${postId}`] = {
            post_id: postId,
            band_id: bandId,
            timestamp: -(+(new Date()))
          }
        })

        // 3. Update the social feeds
        this.db.object(`social`).update(bandFeeds);
      }
    })
  }
</code>```

However, when I try to run this, I get a permission denied and I have no idea why. Am I doing something wrong here?

答:
So here are my updated rules. I needed to reference another path correctly:</p>

```<code>"user_feeds": {
    "$userId": {
       ".indexOn": ["timestamp"],
       "$postId" : {
          ".write": "auth != null && (root.child('social').child('user_band_follows').child($userId).hasChild(newData.child('band_id').val()) || root.child('social').child('user_band_follows').child($userId).hasChild(data.child('band_id').val()) || root.child('social').child('user_connections').child($userId).hasChild(auth.uid))"
     }
  }
}
</code>```

Body:
I have a security rule that looks like this:

"user_feeds": {
     "$userId": {
        ".indexOn": ["timestamp"],
        ".read": "auth != null",
         "$postId" : {
           ".write": "auth != null && newData.parent().hasChild(newData.child('band_id').val())"
           }
         }
       }

in my $postId sub-tree, I'm trying to check to see if the parent has a node that corresponds to the band_id value of the data that is being inserted.

The data looks like:

{
   post_id: 1,
   band_id: '-L-tyesfsdf13434',
   timestamp: 34234234234
}

And an actual tree that these rules would correspond to look like:

{
   "user_feeds": {
     "userId1": {
        "-L-tyesfsdf13434": true
     }
   }
}

I am using Ionic/Angular and here is my function that's actually trying to do the write operation:

addPostToFollowers(bandId, postId) {

    // 1. Get the user's connections
    this._bands.getBandFollowers(bandId).take(1).subscribe(connections => {
      if(connections.$value !== null) {
        delete connections['$key'];
        delete connections['$exists'];

        let connectionKeys = Object.keys(connections);
        // 2. Go through those connections and add the post
        let bandFeeds = {};
        connectionKeys.forEach(connectionKey => {
          bandFeeds[`/user_feeds/${connectionKey}/${postId}`] = {
            post_id: postId,
            band_id: bandId,
            timestamp: -(+(new Date()))
          }
        })

        // 3. Update the social feeds
        this.db.object(`social`).update(bandFeeds);
      }
    })
  }

However, when I try to run this, I get a permission denied and I have no idea why. Am I doing something wrong here?

Body:
So here are my updated rules. I needed to reference another path correctly:

"user_feeds": {
    "$userId": {
       ".indexOn": ["timestamp"],
       "$postId" : {
          ".write": "auth != null && (root.child('social').child('user_band_follows').child($userId).hasChild(newData.child('band_id').val()) || root.child('social').child('user_band_follows').child($userId).hasChild(data.child('band_id').val()) || root.child('social').child('user_connections').child($userId).hasChild(auth.uid))"
     }
  }
}


问:
How to make a fuzzy filter in Power Query according to a list
I want to filter a Power Query table according to another list:

The fact table is:

```<code>Location    Name

MEL/1F/101  zmel
SHA         zsha
BKK/2F      zbkk
SGN         zsgn
</code>```

And the lookup list is

{"BKK","SHA"}

The result I want is

```<code>Location    Name

SHA         zsha
BKK/2F      zbkk
</code>```

Now I use

```<code>l={"SHA","BKK"},
b=Table.SelectRows(#"Expanded Column1", each List.Contains(l,[location]))
</code>```

but the BKK/2F is omitted, only SHA shows.

Does any one knows to correct this? Thanks.

答:
You can create a new column using conditional Column by referencing to the table column that contains SHA & BKK. Replace the Column Name to your column.

You can use fill down function if you want to get rid of the nulls.

Update

For your case you might want to use the operator begins with since your BKK has extra text behind

Body:
I want to filter a Power Query table according to another list:

The fact table is:

Location    Name

MEL/1F/101  zmel
SHA         zsha
BKK/2F      zbkk
SGN         zsgn

And the lookup list is

{"BKK","SHA"}

The result I want is

Location    Name

SHA         zsha
BKK/2F      zbkk

Now I use

l={"SHA","BKK"},
b=Table.SelectRows(#"Expanded Column1", each List.Contains(l,[location]))

but the BKK/2F is omitted, only SHA shows.

Does any one knows to correct this? Thanks.


问:
Select a random position on the border of an array
I've initialized an array of zeros. I'd now like to randomly select positions on the border of the array. If the position is 0, I would then set it to 1, while if it is 1, I would do nothing and repeat the process.

Here's what I currently have:

```<code>D = 50 # lattice dims
N = 200 # total number of particles at the end
a = np.zeros((D,D)) # playing board array

# place particle at the center of the board
a[int(D/2), int(D/2)] = 1

border_list = [0, 1, 2, 3]

i = 0
while i < N:
    border = random.choice(border_list)
    pos = math.floor((D)*random.random())
    if border == 0:
        if a[0, pos] == 0:
            a[0, pos] = 1
            i += 1
    if border == 1:
        if a[pos, 0] == 0:
            a[pos, 0] = 1
            i += 1
    if border == 2:
        if a[int(D-1), pos] == 0:
            a[int(D-1), pos] = 1
            i += 1
    if border == 3:
        if a[pos, int(D-1)] == 0:
            a[pos, int(D-1)] = 1
            i += 1
</code>```

Seems pretty inefficient to me. Any advice regarding improving it?

答:
There is no efficiency issue with this code, it can be improved a bit:

```<code>...
while i < N:
    border = random.choice(border_list)
    pos = math.floor((D)*random.random())
    if border == 0 and a[0, pos] == 0:
        a[0, pos] = 1
        i += 1
    elif border == 1 and a[pos, 0] == 0:
        a[pos, 0] = 1
        i += 1
    elif border == 2 and a[int(D-1), pos] == 0:
        a[int(D-1), pos] = 1
        i += 1
    elif border == 3 and a[pos, int(D-1)] == 0:
        a[pos, int(D-1)] = 1
        i += 1
</code>```

This way if one of the if cases evaluates to True the following cases will not be checked.

Body:
I've initialized an array of zeros. I'd now like to randomly select positions on the border of the array. If the position is 0, I would then set it to 1, while if it is 1, I would do nothing and repeat the process.

Here's what I currently have:

D = 50 # lattice dims
N = 200 # total number of particles at the end
a = np.zeros((D,D)) # playing board array

# place particle at the center of the board
a[int(D/2), int(D/2)] = 1

border_list = [0, 1, 2, 3]

i = 0
while i < N:
    border = random.choice(border_list)
    pos = math.floor((D)*random.random())
    if border == 0:
        if a[0, pos] == 0:
            a[0, pos] = 1
            i += 1
    if border == 1:
        if a[pos, 0] == 0:
            a[pos, 0] = 1
            i += 1
    if border == 2:
        if a[int(D-1), pos] == 0:
            a[int(D-1), pos] = 1
            i += 1
    if border == 3:
        if a[pos, int(D-1)] == 0:
            a[pos, int(D-1)] = 1
            i += 1

Seems pretty inefficient to me. Any advice regarding improving it?

Body:
There is no efficiency issue with this code, it can be improved a bit:

...
while i < N:
    border = random.choice(border_list)
    pos = math.floor((D)*random.random())
    if border == 0 and a[0, pos] == 0:
        a[0, pos] = 1
        i += 1
    elif border == 1 and a[pos, 0] == 0:
        a[pos, 0] = 1
        i += 1
    elif border == 2 and a[int(D-1), pos] == 0:
        a[int(D-1), pos] = 1
        i += 1
    elif border == 3 and a[pos, int(D-1)] == 0:
        a[pos, int(D-1)] = 1
        i += 1

This way if one of the if cases evaluates to True the following cases will not be checked.


问:
Overriding type defintions in TypeScript
I'm trying to develop a Chrome Extension in TypeScript. I have installed @types/chrome and everything seemed in order.

Now I want to use chrome-extension-async which provides a Promisified version of the chrome extension objects, allowing me to async/await.

I can't seem to figure out how to enable this extension, though. The documentation just says I should add a

答:
the import works, but I can't await chrome.storage.sync.get('field) because TypeScript complains (quite rightly) that I'm not passing a callback.

Dont use @types/chrome and instead use https://github.com/KeithHenry/chromeExtensionAsync/blob/master/chrome-extension-async.d.ts

More

From the docs


问:
why I can't use google action in web simulator
Does anyone know why my action can NOT use in web simulator??

I set my invocation name for testing as "test", and in web simulator , I try to use my action by input "Talk to test", but it told me "Sorry, this action is not available in simulation"...

Is there anything wrong with me ??

答:
Turns out for me, even though I had turned on all the activity controls as the tutorial instructed, the organisation my login was associated with had them disabled.

Ask your admin to enable "Web & App Activity" in "My Account" > "Admin" > "Google Services"


问:
create a folder on an SD card
I'm trying to create a folder on the SD card that is named by user inputs, I get no errors when I run it, but it also doesn't create the folder.

the following is all the code I have written for this activity:

```<code>public class Jobselection extends AppCompatActivity
     implements OnClickListener {
     Button createButton;
     EditText photogname;
     EditText projnum;
     EditText phase;
     DatePicker datePicker;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_jobselection);
        createButton = (Button) findViewById(R.id.createButton);
        createButton.setOnClickListener(this);
        photogname = (EditText) findViewById(R.id.photographername);
        projnum = (EditText) findViewById(R.id.projectnumber);
        phase = (EditText) findViewById(R.id.phase);
        datePicker = (DatePicker) findViewById(R.id.datePicker);

    }

    public static java.util.Date getDateFromDatePicker(DatePicker datePicker) {
        int day = datePicker.getDayOfMonth();
        int month = datePicker.getMonth();
        int year = datePicker.getYear();
        Calendar calendar = Calendar.getInstance();
        calendar.set(year, month, day);
        return calendar.getTime();
    }
    public void onClick(View createButton) {
    String date = getDateFromDatePicker(datePicker).toString();
    String photog = photogname.getText().toString();
    String proj = projnum.getText().toString() + "." + phase.getText().toString();
    String state;
    state = Environment.getExternalStorageState();
    if (Environment.MEDIA_MOUNTED.equals(state)) {
        File appDirectory = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + date + "/" + proj + "/" + photog);
        boolean isDirectoryCreated = appDirectory.exists();
        if (!isDirectoryCreated) {
            isDirectoryCreated = appDirectory.mkdirs();
        }
        if (isDirectoryCreated) {
            Toast.makeText(Jobselection.this, "Folder is created", Toast.LENGTH_LONG).show();
        }
        else
            Log.d("error","dir.already exists");
    }

    Intent launchUnitLoc = new Intent(this, UnitLocation.class);
    startActivity(launchUnitLoc);
}
</code>```

答:
Instead of using this :-

```<code>File appDirectory = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + date + "/" + proj + "/" + photog);
</code>```

Try this  :-

```<code>File appDirectory = new File(Environment.getExternalStorageDirectory() + "/" + date + "/" + proj ,photog );
</code>```

Title: create a folder on an SD card

Body:
I'm trying to create a folder on the SD card that is named by user inputs, I get no errors when I run it, but it also doesn't create the folder.

the following is all the code I have written for this activity:

public class Jobselection extends AppCompatActivity
     implements OnClickListener {
     Button createButton;
     EditText photogname;
     EditText projnum;
     EditText phase;
     DatePicker datePicker;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_jobselection);
        createButton = (Button) findViewById(R.id.createButton);
        createButton.setOnClickListener(this);
        photogname = (EditText) findViewById(R.id.photographername);
        projnum = (EditText) findViewById(R.id.projectnumber);
        phase = (EditText) findViewById(R.id.phase);
        datePicker = (DatePicker) findViewById(R.id.datePicker);

    }

    public static java.util.Date getDateFromDatePicker(DatePicker datePicker) {
        int day = datePicker.getDayOfMonth();
        int month = datePicker.getMonth();
        int year = datePicker.getYear();
        Calendar calendar = Calendar.getInstance();
        calendar.set(year, month, day);
        return calendar.getTime();
    }
    public void onClick(View createButton) {
    String date = getDateFromDatePicker(datePicker).toString();
    String photog = photogname.getText().toString();
    String proj = projnum.getText().toString() + "." + phase.getText().toString();
    String state;
    state = Environment.getExternalStorageState();
    if (Environment.MEDIA_MOUNTED.equals(state)) {
        File appDirectory = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + date + "/" + proj + "/" + photog);
        boolean isDirectoryCreated = appDirectory.exists();
        if (!isDirectoryCreated) {
            isDirectoryCreated = appDirectory.mkdirs();
        }
        if (isDirectoryCreated) {
            Toast.makeText(Jobselection.this, "Folder is created", Toast.LENGTH_LONG).show();
        }
        else
            Log.d("error","dir.already exists");
    }

    Intent launchUnitLoc = new Intent(this, UnitLocation.class);
    startActivity(launchUnitLoc);
}

Body:
Instead of using this :-

File appDirectory = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + date + "/" + proj + "/" + photog);

Try this  :-

File appDirectory = new File(Environment.getExternalStorageDirectory() + "/" + date + "/" + proj ,photog );


答:
Function is also an object in TypeScript and you and make any object of type 'any'. Doing this it will accept whatever parameter you pass to this function.

try:
< any>(chrome.storage.sync.get)()

Title: Overriding type defintions in TypeScript

Body:
I'm trying to develop a Chrome Extension in TypeScript. I have installed @types/chrome and everything seemed in order.

Now I want to use chrome-extension-async which provides a Promisified version of the chrome extension objects, allowing me to async/await.

I can't seem to figure out how to enable this extension, though. The documentation just says I should add a


问:
Different CSS mask-position values per mask-image in a composite mask

I have two mask images to use for composite mask, being set as the mask-image property. I'd like to specify a different mask-position value for each image, since the images are different sizes and not positioned to the same scale.

```<code>.my-class {
  mask-image: url(/masks/foo.png), url(/masks/bar.png);
  mask-position: ?; /* Set 0 for foo.png, but 15px -50px for bar.png */
  mask-size: 100%;
  mask-repeat: no-repeat;
}
</code>```

foo.png and bar.png should have different mask-position values. I need an offset on bar.png before I can add it to foo.png.

Is this even possible?

答:
This is possible, per the current spec, which is in initial definition (and is experimental, so it may change). From https://developer.mozilla.org/en-US/docs/Web/CSS/mask-position:

```<code>mask-position: 0 0, 15px -50px;
</code>```

This follows the pattern for positioning multiple background images.

Body:
I have two mask images to use for composite mask, being set as the mask-image property. I'd like to specify a different mask-position value for each image, since the images are different sizes and not positioned to the same scale.

.my-class {
  mask-image: url(/masks/foo.png), url(/masks/bar.png);
  mask-position: ?; /* Set 0 for foo.png, but 15px -50px for bar.png */
  mask-size: 100%;
  mask-repeat: no-repeat;
}

foo.png and bar.png should have different mask-position values. I need an offset on bar.png before I can add it to foo.png.

Is this even possible?

Body:
This is possible, per the current spec, which is in initial definition (and is experimental, so it may change). From https://developer.mozilla.org/en-US/docs/Web/CSS/mask-position:

mask-position: 0 0, 15px -50px;

This follows the pattern for positioning multiple background images.


问:
Good way to generate GUIDs on app engine?
I was wondering if anyone knows of a good way to generate GUIDs on python google app engine. I feel like there is a simple way that people are using, what would you suggest.</p>

答: Assuming the module is available in Google App Engine, check out Python's uuid module.</p>


问:
Where can i download ICDAR pictures dataset from 2003 to 2015?
I need scene text pictures for evaluating the result of my OCR app so i want ICDAR picture datasets from 2003 to 2015, Please provide url or download link.</p>

答:
I can't find such site collecting all Robust Reading datasets, but I can still find some datasets with a simple DuckDuckGo search:

ICDAR 2003 Robust Reading Competition

ICDAR 2011-2017 Robust Reading Competitions

Hope you Google or Bing it first before you ask next time.


问:
CountDownTimer Service crashing when it is opened
I am trying to make a countdown timer screen that will keep counting down if I back out of the app or change screens or something. For some reason it keeps crashing saying that timeLeft is null. I can't figure out why it would be because I know the time variable in my Countdown class is there. Thanks for any help!

Countdown Activity

```<code>public class Countdown extends Activity {
public static String time;
public static String address;
@Override
protected void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_countdown);
    Intent confIntent = getIntent();
    time = confIntent.getStringExtra("time");
    address = confIntent.getStringExtra("address");
    LocalBroadcastManager.getInstance(this).registerReceiver(
            new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                    TextView textView= findViewById(R.id.t1);
                    String timeLeftString = intent.getStringExtra("timeSent");
                    int timeLeft = Integer.parseInt(timeLeftString);
                    if(timeLeft>0) {
                        textView.setText("You have " + timeLeft + " minutes left");
                    }
                    else{
                        textView.setText("Y'all outta time, see ya again soon!");
                        killIt();
                    }
                }
            }, new IntentFilter(CountdownService.ACTION_LOCATION_BROADCAST)
    );
    Intent toService = new Intent(this, CountdownService.class);
    startService(toService);

}
@Override
protected void onResume() {
    super.onResume();
    TextView textView= findViewById(R.id.t1);
    textView.setText("You have " + CountdownService.toSend + " minutes left");
}

@Override
protected void onPause() {
    super.onPause();

}

public void killIt(){
    stopService(new Intent(this, CountdownService.class));
}

}
</code>```

Countdown Service

```<code>public class CountdownService extends Service{
public static int toSend=0;
public int time;
public static final String
        ACTION_LOCATION_BROADCAST = CountdownService.class.getName() +
"LocationBroadcast";
public final String timeFromCD = Countdown.time;
public final String address = Countdown.address;

@Override
public void onCreate() {
super.onCreate();
    time = Integer.parseInt(timeFromCD);
    time = time*60000;
    new CountDownTimer(time, 5000) {
        public void onTick(long millisUntilFinished) {
            int timeLeftInt = (int) Math.ceil((double) millisUntilFinished / 60000);    //Whole number of minutes left, ceiling
            sendBroadcastMessage(timeLeftInt);
            toSend = timeLeftInt;
            if(timeLeftInt == 5){
                Notify("Not Done");
            }

        }

        public void onFinish() {
            sendBroadcastMessage(0);
            Notify("done");

            Response.Listener<String> response = new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    try {
                        //creating a jsonResponse that will receive the php json
                        JSONObject jsonResponse = new JSONObject(response);
                        boolean success = jsonResponse.getBoolean("success");

                        if (success) {

                        } else {
                            AlertDialog.Builder builder = new AlertDialog.Builder(CountdownService.this);
                            builder.setMessage("Login Failed")
                                    .setNegativeButton("Retry", null)
                                    .create()
                                    .show();
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            };

            SpotAmountRequest spotAmountRequest = new SpotAmountRequest(address, "0", response);
            RequestQueue queue = Volley.newRequestQueue(CountdownService.this);
            queue.add(spotAmountRequest);

        }
    }.start();

}

private void sendBroadcastMessage(int timeSent) {
        Intent intent = new Intent(ACTION_LOCATION_BROADCAST);
        intent.putExtra("timeSent", timeSent);
        LocalBroadcastManager.getInstance(this).sendBroadcast(intent);

}

@Override
public IBinder onBind(Intent intent) {
    return null;
}

private void Notify(String doneness){

    NotificationManager notificationManager = (NotificationManager)
            getSystemService(NOTIFICATION_SERVICE);

    Intent intent = new Intent(this, Map.class);
    PendingIntent pIntent = PendingIntent.getActivity(this, (int) System.currentTimeMillis(), intent, 0);
    if(doneness.equals("done")) {
        Notification n = new Notification.Builder(this)
                .setContentTitle("Time to leave!")
                .setContentText("Your PrePark spot has expired, time to go home!")
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentIntent(pIntent)
                .setAutoCancel(true)
                .build();

        notificationManager.notify(0, n);
        Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
        // Vibrate for 500 milliseconds
        v.vibrate(1000);
    }

    else{
        Notification n = new Notification.Builder(this)
                .setContentTitle("Ya got 5 minutes left in your PrePark spot!")
                .setContentText("Better get going soon here")
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentIntent(pIntent)
                .setAutoCancel(true)
                .build();

        notificationManager.notify(0, n);
    }
}

}
</code>```

答: You're storing an int value in the intent that you're broadcasting from the service, but you're then trying to get it out as a String where you receive the broadcast. Either change the receiver to use getIntExtra instead of getStringExtra, or convert the int to a String in the service before storing it in the intent.

Body:
I am trying to make a countdown timer screen that will keep counting down if I back out of the app or change screens or something. For some reason it keeps crashing saying that timeLeft is null. I can't figure out why it would be because I know the time variable in my Countdown class is there. Thanks for any help!

Countdown Activity

public class Countdown extends Activity {
public static String time;
public static String address;
@Override
protected void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_countdown);
    Intent confIntent = getIntent();
    time = confIntent.getStringExtra("time");
    address = confIntent.getStringExtra("address");
    LocalBroadcastManager.getInstance(this).registerReceiver(
            new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                    TextView textView= findViewById(R.id.t1);
                    String timeLeftString = intent.getStringExtra("timeSent");
                    int timeLeft = Integer.parseInt(timeLeftString);
                    if(timeLeft>0) {
                        textView.setText("You have " + timeLeft + " minutes left");
                    }
                    else{
                        textView.setText("Y'all outta time, see ya again soon!");
                        killIt();
                    }
                }
            }, new IntentFilter(CountdownService.ACTION_LOCATION_BROADCAST)
    );
    Intent toService = new Intent(this, CountdownService.class);
    startService(toService);

}
@Override
protected void onResume() {
    super.onResume();
    TextView textView= findViewById(R.id.t1);
    textView.setText("You have " + CountdownService.toSend + " minutes left");
}

@Override
protected void onPause() {
    super.onPause();

}

public void killIt(){
    stopService(new Intent(this, CountdownService.class));
}

}

Countdown Service

public class CountdownService extends Service{
public static int toSend=0;
public int time;
public static final String
        ACTION_LOCATION_BROADCAST = CountdownService.class.getName() +
"LocationBroadcast";
public final String timeFromCD = Countdown.time;
public final String address = Countdown.address;

@Override
public void onCreate() {
super.onCreate();
    time = Integer.parseInt(timeFromCD);
    time = time*60000;
    new CountDownTimer(time, 5000) {
        public void onTick(long millisUntilFinished) {
            int timeLeftInt = (int) Math.ceil((double) millisUntilFinished / 60000);    //Whole number of minutes left, ceiling
            sendBroadcastMessage(timeLeftInt);
            toSend = timeLeftInt;
            if(timeLeftInt == 5){
                Notify("Not Done");
            }

        }

        public void onFinish() {
            sendBroadcastMessage(0);
            Notify("done");

            Response.Listener<String> response = new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    try {
                        //creating a jsonResponse that will receive the php json
                        JSONObject jsonResponse = new JSONObject(response);
                        boolean success = jsonResponse.getBoolean("success");

                        if (success) {

                        } else {
                            AlertDialog.Builder builder = new AlertDialog.Builder(CountdownService.this);
                            builder.setMessage("Login Failed")
                                    .setNegativeButton("Retry", null)
                                    .create()
                                    .show();
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            };

            SpotAmountRequest spotAmountRequest = new SpotAmountRequest(address, "0", response);
            RequestQueue queue = Volley.newRequestQueue(CountdownService.this);
            queue.add(spotAmountRequest);

        }
    }.start();

}

private void sendBroadcastMessage(int timeSent) {
        Intent intent = new Intent(ACTION_LOCATION_BROADCAST);
        intent.putExtra("timeSent", timeSent);
        LocalBroadcastManager.getInstance(this).sendBroadcast(intent);

}

@Override
public IBinder onBind(Intent intent) {
    return null;
}

private void Notify(String doneness){

    NotificationManager notificationManager = (NotificationManager)
            getSystemService(NOTIFICATION_SERVICE);

    Intent intent = new Intent(this, Map.class);
    PendingIntent pIntent = PendingIntent.getActivity(this, (int) System.currentTimeMillis(), intent, 0);
    if(doneness.equals("done")) {
        Notification n = new Notification.Builder(this)
                .setContentTitle("Time to leave!")
                .setContentText("Your PrePark spot has expired, time to go home!")
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentIntent(pIntent)
                .setAutoCancel(true)
                .build();

        notificationManager.notify(0, n);
        Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
        // Vibrate for 500 milliseconds
        v.vibrate(1000);
    }

    else{
        Notification n = new Notification.Builder(this)
                .setContentTitle("Ya got 5 minutes left in your PrePark spot!")
                .setContentText("Better get going soon here")
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentIntent(pIntent)
                .setAutoCancel(true)
                .build();

        notificationManager.notify(0, n);
    }
}

}


问:
Mongoose find query vs $match
I have a following document inside mongodb

```<code>{
    "_id" : ObjectId("5a25f1b19c72e07ffc50a37d"),
    "name" : "test",
    "category" : ObjectId("5a1e6622a7739fb64c8c530b"),
    "recentDeveloperComment" : ObjectId("5a25f1b19c72e07ffc50a37c"),
    "fileName" : "test2.xlsx",
    "rawData" : ObjectId("5a21079ef99e75b2140fb77a"),
    "group" : {
        "year" : 2017,
        "month" : 1,
        "category" : "test1"
    },
    "unlocked" : false,
    "status" : "Pending",
    "updatedAt" : ISODate("2017-12-05T01:08:40.465Z"),
    "createdAt" : ISODate("2017-12-05T01:08:40.465Z"),
    "__v" : 0
}
</code>```

I can match this by using following find query with mongoose

```<code>Repo.find({'group.year' : year, 'group.month' : month, 'group.category' : category, name:repo})
    .exec((err, repoResult) => {
        //matches one document
    })
</code>```

However with the below aggregate $match I cannot get the same result

```<code>Repo.aggregate([
    {
        $match:
            {
                $and:[
                    {'group.year' : year},
                    {'group.month' : month},
                    {'group.category' : category},
                    {name : repo}
                ]
            }
    },
]).exec((err, commitsResult) => {
    //matches zero document
});
</code>```

Why is this?

答: It was because find parses all the query strings into the variable type that is defined in the database. For example year was a parameter parsed from url so it was a string form but in Mongodb the field is defined as an int. Find automatically parses this to the correct type but $match does not parse it so it has to be done manually.

Title: Mongoose find query vs $match

Body:
I have a following document inside mongodb

{
    "_id" : ObjectId("5a25f1b19c72e07ffc50a37d"),
    "name" : "test",
    "category" : ObjectId("5a1e6622a7739fb64c8c530b"),
    "recentDeveloperComment" : ObjectId("5a25f1b19c72e07ffc50a37c"),
    "fileName" : "test2.xlsx",
    "rawData" : ObjectId("5a21079ef99e75b2140fb77a"),
    "group" : {
        "year" : 2017,
        "month" : 1,
        "category" : "test1"
    },
    "unlocked" : false,
    "status" : "Pending",
    "updatedAt" : ISODate("2017-12-05T01:08:40.465Z"),
    "createdAt" : ISODate("2017-12-05T01:08:40.465Z"),
    "__v" : 0
}

I can match this by using following find query with mongoose

Repo.find({'group.year' : year, 'group.month' : month, 'group.category' : category, name:repo})
    .exec((err, repoResult) => {
        //matches one document
    })

However with the below aggregate $match I cannot get the same result

Repo.aggregate([
    {
        $match:
            {
                $and:[
                    {'group.year' : year},
                    {'group.month' : month},
                    {'group.category' : category},
                    {name : repo}
                ]
            }
    },
]).exec((err, commitsResult) => {
    //matches zero document
});

Why is this?


问:
Generate all possibilities for a string where some letters can be numbers, in Python
Say I have a string like this.

```<code>sentence = "i like to go fishing on saturday"
</code>```

And some letters can be numbers, in the tradition of '1337' speak i.e. h3110, h0w 4r3 y0u?

However I want to get all possible combinations where some letters are converted to numbers, but others are not. Some examples with the above sentence.

```<code>"i 1ik3 70 g0 fishing 0n s4turd4y"
"i lik3 70 g0 fishing 0n s4turd4y"
"i like 70 g0 fishing 0n s4turd4y"
"i 1ike 70 g0 fishing 0n s4turd4y"
etc.
</code>```

How could I write in Python a dictionary of substitutions for each letter and then a way to generate all possible combinations for the sentence?

答:
You can create a dictionary manual. But get all combinations with itertools.combinations

```<code>from itertools import combinations

sentence = "i like to go fishing on saturday"

d = {'l' : '1',
     'e' : '3',
     't' : '7'}

for l in range(len(d)):
    for x in combinations(d, l):
        for k in x:
            s = sentence.replace(k, d[k])
            print(s)
</code>```

But this version will replace all t to 7. Not match all your requirement.

Body:
Say I have a string like this.

sentence = "i like to go fishing on saturday"

And some letters can be numbers, in the tradition of '1337' speak i.e. h3110, h0w 4r3 y0u?

However I want to get all possible combinations where some letters are converted to numbers, but others are not. Some examples with the above sentence.

"i 1ik3 70 g0 fishing 0n s4turd4y"
"i lik3 70 g0 fishing 0n s4turd4y"
"i like 70 g0 fishing 0n s4turd4y"
"i 1ike 70 g0 fishing 0n s4turd4y"
etc.

How could I write in Python a dictionary of substitutions for each letter and then a way to generate all possible combinations for the sentence?

Body:
You can create a dictionary manual. But get all combinations with itertools.combinations

from itertools import combinations

sentence = "i like to go fishing on saturday"

d = {'l' : '1',
     'e' : '3',
     't' : '7'}

for l in range(len(d)):
    for x in combinations(d, l):
        for k in x:
            s = sentence.replace(k, d[k])
            print(s)

But this version will replace all t to 7. Not match all your requirement.