AngularJS module .run order and e2e mocks

Question: I am working on some E2E tests for AngularJS.
I have implemented a $httpBackend ngMockE2E.
This works well, however in some instances HTTP requests are being made before my mocks have been completely set up.
The Mock is set up as:
  angular.module('Mock', ['ngMockE2E']).

    run(function($httpBackend) {

      $httpBackend.whenPOST('/path1').respond({ exampleresponse: 'valid' });
      $httpBackend.whenPOST('/path2').respond({ exampleresponse: 'valid' });

And it is used as below:
angular.module('Application', ['FirstDependency', 'Mock', 'ThirdDependency']);

However FirstDependency and ThirdDependency can make HTTP requests which sometimes happen before the Mock .run() block has been executed. This results in request errors.
Am I setting up my mocks correctly? What is the best way to ensure my mocks are loaded in the right order?
Answer: This is what the doc says:
Dependencies:

Modules can list other modules as their dependencies.
Depending on a module implies that required module needs to be loaded
before the requiring module is loaded. In other words the
configuration blocks of the required modules execute before the
configuration blocks of the requiring module. The same is true for the
run blocks. Each module can only be loaded once, even if multiple
other modules require it.

However what it doesn't say is that it will first execute the config blocks for all modules (dependencies first) and then it will execute all the other blocks in a row for each module in turn. For an illustration of this take a look at this jsfiddle:
http://jsfiddle.net/9FJnZ/2/


What is the difference between the heaviside distribution and the dirac delta distriubtion?

Question: I know that the heaviside distribition is a piecewise function that deals with a discontinuous forcing functions but does the dirac delta function deal with the same type of situations? If so, what is the difference between them?
Comment: You may want to check: http://math.stackexchange.com/q/479810/137035
Answer: The Heaviside function is usually defined to be an antiderivative of the Dirac distribution:
$$
H'(x) = \delta(x)
$$
For some $a < 0$ one gets:
$$
\int\limits_a^x \delta(\xi) \, d\xi =
\left\{
\begin{array}{rc}
0 & x < 0 \\
1 & x > 0
\end{array}
\right.
= H(x)
$$
Comment: The Heaviside function is interpreted as  a step, some value changes to a new value suddenly and stays that value, like turning on the light.The Dirac distribution is interpreted as an impulse, some value changing suddenly and then taking the old value, like the impact of a hammer on a nail. I am looking for a nice example where both show up, but fail to find one.
Comment: So if I am given one Heaviside Distribution (just the general form) and the general form of a dirac distribution, the difference is that the heaviside is just the antiderviative of the dirac?
Comment: No I mean what makes them different from one another. Is there a physical example that would pertian to each to help me better understand?
Comment: They are not different distributions.  One could say the Dirac delta function is the density function and the Heaviside function is the cumulative distribution function, but of course the Dirac delta function isn't even really a function in the sense in which mathematicians usually define that term.


Problema em compilar código no Keras

Question: Eu estava criando um classificador simples em Keras no Python3, ma seu fico recebendo a mesma mensagem de erro:

RuntimeError: You must compile your model before using it.

Segue o código:
import keras
from keras.layers import Activation, MaxPooling2D, Convolution2D
from keras.layers import Dense, Flatten, Dropout
from keras.preprocessing.image import ImageDataGenerator

class OwnClassificator:
    def __init__(self):

# Preparando os dados de treino

        self.preparing_train = ImageDataGenerator(rescale=1. /225,
           shear_range=0.2, zoom_range=0.2, horizontal_flip=True)

        self.data_train = self.preparing_train.flow_from_directory(
           directory=r'C:Meu diretório',
           target_size=(200, 200), batch_size=15,
           class_mode='binary')

# Preparando os dados de validação

        self.validation_preparing = ImageDataGenerator(rescale=1. /225,
           shear_range=0.2, zoom_range=0.2, horizontal_flip=True)

        self.data_validation =self.validation_preparing.flow_from_directory(
            directory=r'C:meu diretório', target_size=(200, 200), batch_size=10, class_mode='binary')

    # **************************************************************************************************************

    self.model = keras.Sequential()

    self.model.add(Convolution2D((32, 3, 3), kernel_size=15))
    self.model.add(Activation('relu'))
    self.model.add(MaxPooling2D(pool_size=(2, 2)))

    self.model.add(Convolution2D((32, 3, 3), kernel_size=15))
    self.model.add(Activation('relu'))
    self.model.add(MaxPooling2D(pool_size=(2, 2)))

    self.model.add(Convolution2D((32, 3, 3), kernel_size=15))
    self.model.add(Activation('relu'))
    self.model.add(MaxPooling2D(pool_size=(2, 2)))

    # **************************************************************************************************************

    self.model.add(Flatten())
    self.model.add(Dense(64))
    self.model.add(Activation('relu'))
    self.model.add(Dropout(0.5))

    self.model.add(Dropout(1))
    self.model.add(Activation('sigmoid'))

    # **************************************************************************************************************

    self.model.compile(loss='binary_crossentropy', optimizer='rmsprop', metrics=['accuracy'])

    self.model.fit_generator(generator=self.data_train, steps_per_epoch=554 // 15, epochs=80,
                validation_data=self.data_validation)

    self.model.save_weights('models/simple_CNN.h5')

    # **************************************************************************************************************

    self.img = keras.preprocessing.image.load_img(r'C:meu diretorio',
                                                  target_size=(200, 200))
    self.predict = self.model.predict(self.img)
    print(f'PREDICTION: {self.predict}')

FirstModel = OwnClassificator()

Answer: Esse código está mal indentado e não executa. Em python, isso é um erro mortal.
A primeira coisa que você precisa fazer é arrumar indentação. Eu recebo o erro:
NameError: name 'self' is not defined
Em segundo lugar, para modelos simples, uma implementação baseada em classes não é a mais inteligente.
Siga a Zen do Python:

Flat is better than nested.

Tente fazer um script raso apenas com o código que você quer executar. Usando variáveis locais ao script.
Use este exemplo keras como referência. Consulte também a documentação do flow_from_directory.

Problema em compilar código no Keras


$\lim_{y \to 0^+} (g(x+iy)-g(x-iy))$, where the analytic function $g$ is $g(z) = \int_0^1 \frac{dt}{t-z}$

Question:
Let $g(z) = \int_0^1 \frac{dt}{t-z}$, analytic on $O=
 \mathbb{C}-[0,1]$. Find $\lim_{y \to 0^+} (g(x+iy)-g(x-iy))$, where $x
 \in (0,1)$.

I think I could explore the fact that $g(z)-g(\bar{z}) = \int_0^1 \frac{1}{t}(\frac{1}{1-\frac{z}{t}} - \frac{1}{1-\frac{\bar{z}}{t}}) dt$, but it it unclear. Is anyone could help me at this point?
Comment: $g(z) = \lim_{\epsilon \to 0^+} \int_\epsilon^{1-\epsilon} \frac{dt}{t-z}$. what is the derivative of $\log(t-z)$ ? (and be careful with the branch of the logarithm, that's what the $\lim_{\epsilon\to 0^+}$ is useful for)
Comment: @user1952009 I would like to know your solution with your hint to compare with the answer of Friedrich Philipp. Could you display an answer? It is curious how could pass of $\log$ to $\arctan$.
Comment: Where did you get the factor of $\frac{1}{t}$ from?
Answer: If I have calculated correctly, then
$$
g(x+iy)-g(x-iy) = -2i\left(\arctan\left(\frac{1-x}{y}\right) - \arctan\left(-\frac x y\right)\right).
$$
Now, let $y\to 0+$ and take care of $x$.
EDIT: In your original post, you have a $\frac 1 t$ too much in the integral. For your understanding, here is my calculation:
\begin{align*}
g(x+iy)-g(x-iy)
&= \int_0^1\left(\frac 1 {(t-x)+iy} - \frac 1 {(t-x)-iy}\right)\,dt\\
&= \int_0^1 \frac{(t-x)-iy - ((t-x)+iy)}{(t-x)^2 + y^2}\,dt\\
&= -2iy\int_0^1 \frac{1}{(t-x)^2 + y^2}\,dt.
\end{align*}
Now, substitute $s = (t-x)/y$. Then $ds/dt = 1/y$ and
\begin{align*}
g(x+iy)-g(x-iy)
&= -2i\int_{-x/y}^{(1-x)/y} \frac{1}{s^2 + 1}\,ds.
\end{align*}


How can I set the path environnment variable in Visual Studio?

Question: I'm using ILMerge in my post build step.
For interoperability reason I would like use ILMerge relative path.
How can I set the path environment variable accessible from my post build step?
Answer: The default ILMerge install path isn't relative to anything.  If you want to add it to the PATH environment variable then write this in your postbuild event:
<code>set path = %path%;$(programfiles)\microsoft\ilmerge
</code>
Comment: Change your system environment.  Control Panel + System + Advanced.  Not recommended if you like your project to build on other machines without hassle.
Comment: This would be the trick to my current project. Isn't there a way to set the path one time for all my project?
Comment: I accept your post but I don't agree with you: The build environment is a per-machine configuration. If I want to build my app on another machine I should install ILMerge then add it to the path. Your first proposition leads to add ILMerge path to all your current projects.
Comment: No need to agree.  I just hand out the bullets, you have to pull the trigger yourself.


Why do I get a null error using @Autowired in serviceBoleta?

Question: I am doing an electronic invoice system project in spring boot with the SOAP library, now when I issue the XML file of the electronic invoice, I get a hashcode of the XML file of the electronic invoice, I am trying to update hashcode in an existing record of the invoice. The invoice has its own classes like Repository, Service, Controller. Until then I have no problem, the problem is the LecturaXML class to inject into the invoice service class. I get an error, indicating NULL.
BoletaRepository
<code>@Repository
public interface BoletaRepository extends SearchRepository<Boleta, Long> {

    public Long countById(Long id);

    @Query("SELECT MAX(numeroBoleta) FROM Boleta")
    public Integer obtenerUltimoNumeroSerieBoleta();

    @Query("SELECT c FROM Boleta c WHERE c.numeroBoleta LIKE %?1%")
    @Override
    public Page<Boleta> findAll(String keyword, Pageable pageable);

    @Query("UPDATE Boleta c SET c.enabled = ?2 WHERE c.id = ?1")
    @Modifying
    public void updateBoletaEnabledStatus(Long id, boolean enabled);

    @Query("UPDATE Boleta c SET c.hashcodeticketBoleta = ?2 WHERE c.id = ?1")
    @Modifying
    public void actualizarHashCodeBoleta(Long id, String hashcodeticketBoleta);

    @Query("UPDATE Boleta c SET c.pendienteticketBoleta = ?2 WHERE c.id = ?1")
    @Modifying
    public void actualizarEstadoBoleta(Long id, String pendienteticketBoleta);
}
</code>
BoletaService
<code>@Service
@Configurable
public class BoletaService {

    public static final Logger LOGGER = Logger.getLogger(BoletaService.class.getName());

    public static final int BOLETAS_PER_PAGE = 15;

    @Autowired
    private BoletaRepository boletaRepo;

    public Boleta saveBoleta(Boleta boleta) {
        return boletaRepo.save(boleta);
    }

    public void actualizarHashCodeBoleta(Long id, String hashcodeticketBoleta) {
        boletaRepo.actualizarHashCodeBoleta(id, hashcodeticketBoleta);
    }

    public void actualizarEstadoBoleta(Long id, String estadoBoleta) {
        boletaRepo.actualizarEstadoBoleta(id, estadoBoleta);
    }

    public Boleta get(Long id) throws BoletaNotFoundException {
        try {
            return boletaRepo.findById(id).get();
        } catch (NoSuchElementException ex) {
            throw new BoletaNotFoundException("NO ENCONTRAMOS BOLETA CON ESTE NUMERO " + id);
        }
    }
}
</code>
LecturaXML
<code>@Component
public class LecturaXML {

    private static final Log log = LogFactory.getLog(LecturaXML.class);

    @Autowired
    private BoletaService serviceBoleta;

    private String codehash;
    private String estado;

    public String getCodehash() {
        return codehash;
    }

    public void setCodehash(String codehash) {
        this.codehash = codehash;
    }

    public String getEstado() {
        return estado;
    }

    public void setEstado(String estado) {
        this.estado = estado;
    }

    public String getRespuestaSunat(String path) {
        String respuesta = null;
        String nota = null;

        try {
            log.info("LecturaXML.getRespuestaSunat - iniciamos Lectura del contenido del CDR " + path);
            DocumentBuilderFactory fabricaCreadorDocumento = DocumentBuilderFactory.newInstance();
            DocumentBuilder creadorDocumento = fabricaCreadorDocumento.newDocumentBuilder();
            Document documento = creadorDocumento.parse(path);
            //Obtener el elemento raíz del documento
            Element raiz = documento.getDocumentElement();

            //Obtener la lista de nodos que tienen etiqueta "ds:Reference"
            NodeList responsecode = raiz.getElementsByTagName("cbc:ResponseCode");
            for (int i = 0; i < responsecode.getLength(); i++) {
                Node empleado = responsecode.item(i);
                Node datoContenido = empleado.getFirstChild();
                respuesta = datoContenido.getNodeValue();
            }
            NodeList nodesc = raiz.getElementsByTagName("cbc:Description");
            for (int i = 0; i < nodesc.getLength(); i++) {
                Node empleado = nodesc.item(i);
                Node datoContenido = empleado.getFirstChild();
                respuesta = respuesta + "|" + datoContenido.getNodeValue();
            }
            NodeList note = raiz.getElementsByTagName("cbc:Note");
            for (int i = 0; i < note.getLength(); i++) {
                Node empleado = note.item(i);
                Node datoContenido = empleado.getFirstChild();
                nota = nota + datoContenido.getNodeValue() + "\\n";
            }

            String[] cdr = respuesta.split("\\|", 0);
            //=== Guardar el link
            if (cdr[0].equals("0")) {
                this.setEstado("A");
            }
            log.info("LecturaXML.getRespuestaSunat - resultado del CDR Observacion: " + Arrays.toString(cdr).trim());
            log.info("LecturaXML.getRespuestaSunat - resultado del CDR Observacion: " + nota);
            log.info("LecturaXML.getRespuestaSunat - resultado del CDR codigo: " + cdr[0]);
            log.info("LecturaXML.getRespuestaSunat - resultado del CDR Nota: " + cdr[1]);

        } catch (org.xml.sax.SAXException ex) {
            respuesta = "LecturaXML.getRespuestaSunat - ERROR: org.xml.sax.SAXException - El formato XML del fichero no es correcto\n : " + ex.getMessage();
            log.error(respuesta);
        } catch (IOException ex) {
            respuesta = "LecturaXML.getRespuestaSunat - ERROR: IOException - Error al leer el archivo de respuesta : " + ex.getMessage();
            log.error(respuesta);
        } catch (ParserConfigurationException ex) {
            respuesta = "LecturaXML.getRespuestaSunat - ERROR: ParserConfigurationException - ERROR: No se ha podido crear el generador de documentos XML\n : " + ex.getMessage();
            log.error(respuesta);
        } catch (DOMException ex) {
            respuesta = "LecturaXML.getRespuestaSunat - ERROR: DOMException : " + ex.getMessage();
            log.error(respuesta);
        }
        return respuesta;
    }

    /**
     * Metodo para obtener Respuesta Sunat con ticket
     *
     * @param path
     * @return respuesta
     */
    public String getRespuestaSunatTicketfe(String path) {
        String respuesta = null;
        String nota = "";

        try {
            log.info("LecturaXML.getRespuestaSunatTicket - iniciamos Lectura del contenido del CDR " + path);
            DocumentBuilderFactory fabricaCreadorDocumento = DocumentBuilderFactory.newInstance();
            DocumentBuilder creadorDocumento = fabricaCreadorDocumento.newDocumentBuilder();
            Document documento = creadorDocumento.parse(path);
            //Obtener el elemento raíz del documento
            Element raiz = documento.getDocumentElement();
            //Obtener la lista de nodos que tienen etiqueta "ds:Reference"
            NodeList responsecode = raiz.getElementsByTagName("cbc:ResponseCode");
            for (int i = 0; i < responsecode.getLength(); i++) {
                Node empleado = responsecode.item(i);
                Node datoContenido = empleado.getFirstChild();
                respuesta = datoContenido.getNodeValue();
            }
            NodeList nodesc = raiz.getElementsByTagName("cbc:Description");
            for (int i = 0; i < nodesc.getLength(); i++) {
                Node empleado = nodesc.item(i);
                Node datoContenido = empleado.getFirstChild();
                respuesta = respuesta + "|" + datoContenido.getNodeValue();
            }
            NodeList note = raiz.getElementsByTagName("cbc:Note");
            for (int i = 0; i < note.getLength(); i++) {
                Node empleado = note.item(i);
                Node datoContenido = empleado.getFirstChild();
                nota = nota + datoContenido.getNodeValue() + "\\n";
            }

            String[] cdr = respuesta.split("\\|", 0);
            //=== Guardar el link
            log.info("LecturaXML.getRespuestaTicketSunatTicket - resultado del CDR Observacion: " + nota);
            log.info("LecturaXML.getRespuestaTicketSunatTicket - resultado del CDR codigo: " + cdr[0]);
            log.info("LecturaXML.getRespuestaTicketSunatTicket - resultado del CDR Nota: " + cdr[1]);
        } catch (org.xml.sax.SAXException ex) {
            respuesta = "LecturaXML.getRespuestaSunatTicket - ERROR: org.xml.sax.SAXException - El formato XML del fichero no es correcto\n : " + ex.getMessage();
            log.error(respuesta);
        } catch (IOException ex) {
            respuesta = "LecturaXML.getRespuestaSunatTicket - ERROR: IOException - Error al leer el archivo de respuesta : " + ex.getMessage();
            log.error(respuesta);
        } catch (ParserConfigurationException ex) {
            respuesta = "LecturaXML.getRespuestaSunatTicket - ERROR: ParserConfigurationException - ERROR: No se ha podido crear el generador de documentos XML\n : " + ex.getMessage();
            log.error(respuesta);
        } catch (DOMException ex) {
            respuesta = "LecturaXML.getRespuestaSunatTicket - ERROR: DOMException : " + ex.getMessage();
            log.error(respuesta);
        } finally {

        }
        return respuesta;
    }

    public void guardarHashYBarCodePDF417(String tipoDoc, String trans, String accion, String pathXMLFile) {

        try {
            String hashCode = obtenerDigestValue(pathXMLFile);
            /*============ALMACENANDO  BarcodePDF417(codigo de Barra)=========*/
            BarcodePDF417 barcode = new BarcodePDF417();
            String infobarcode = tipoDoc.equals("20") ? getInfoToBarCodeOD(pathXMLFile) : getInfoToBarCode(pathXMLFile);
            infobarcode = infobarcode.replaceAll("\n", "");
            log.info("==>infoBarcode:" + infobarcode);
            barcode.setCode(infobarcode);
            java.awt.Image img = barcode.createAwtImage(Color.BLACK, Color.WHITE);
            BufferedImage outImage = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_RGB);
            outImage.getGraphics().drawImage(img, 0, 0, null);
            ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
            ImageIO.write(outImage, "png", bytesOut);
            bytesOut.flush();
            byte[] pngImageData = bytesOut.toByteArray();
            InputStream is = new ByteArrayInputStream(pngImageData);
            log.info("LecturaXML.obtenerDigestValue BarCodePDF417 - resultado HashCode : " + hashCode);

        } catch (IOException ex) {
            log.error("==>Error en generación de hash o barCode:" + ex.getMessage());
        } finally {
        }
    }

    public void guardarHashYBarCodeQR(String tipoDoc, String numeroDocu, String pathXMLFile, Boleta boleta) {
        try {
            String hashCode = obtenerDigestValue(pathXMLFile);
            this.codehash = hashCode;
            /*============ALMACENANDO  BarcodePDF417(codigo de Barra)=========*/
            //QRCodeWriter barcode = new QRCodeWriter();
            String infobarcode = tipoDoc.equals("20") ? getInfoToBarCodeOD(pathXMLFile) : getInfoToBarCode(pathXMLFile);
            infobarcode = infobarcode.replaceAll("\n", "");
            log.info("==>infoBarcode:" + infobarcode);
            QRCodeWriter qrCodeWriter = new QRCodeWriter();
            BitMatrix bitMatrix = qrCodeWriter.encode(infobarcode, BarcodeFormat.QR_CODE, 350, 350);

            Path path = FileSystems.getDefault().getPath(pathXMLFile.replace("xml", "png"));
            MatrixToImageWriter.writeToPath(bitMatrix, "PNG", path);

            ByteArrayOutputStream pngOutputStream = new ByteArrayOutputStream();
            MatrixToImageWriter.writeToStream(bitMatrix, "PNG", pngOutputStream);
            byte[] pngImageData = pngOutputStream.toByteArray();
            InputStream is = new ByteArrayInputStream(pngImageData);
            log.info("LecturaXML.obtenerDigestValue BarCodeQR - resultado HashCode : " + hashCode);
            log.info("LecturaXML Guardando HashCode en la Boleta : " + this.codehash);
            System.out.println("Estado de la Boleta : " + this.getEstado());
            serviceBoleta.actualizarHashCodeBoleta(boleta.getId(), this.codehash);
        } catch (WriterException | IOException ex) {
            log.error("==>Error en generación de hash o barCode:" + ex.getMessage());
        }
    }

    public String obtenerDigestValue(String path) {
        String firma = null;
        try {
            DocumentBuilderFactory fabricaCreadorDocumento = DocumentBuilderFactory.newInstance();
            DocumentBuilder creadorDocumento = fabricaCreadorDocumento.newDocumentBuilder();
            Document documento = creadorDocumento.parse(path);
            //Obtener el elemento raíz del documento
            Element raiz = documento.getDocumentElement();
            //Obtener la lista de nodos que tienen etiqueta "ds:Reference"
            NodeList listaEmpleados = raiz.getElementsByTagName("ds:Reference");
            //Recorrer la lista de empleados
            for (int i = 0; i < listaEmpleados.getLength(); i++) {
                //Obtener de la lista un empleado tras otro
                Node empleado = listaEmpleados.item(i);
                //Obtener la lista de los datos que contiene ese ds:Reference
                NodeList datosEmpleado = empleado.getChildNodes();
                //Recorrer la lista de los datos que contiene el ds:Reference
                for (int j = 0; j < datosEmpleado.getLength(); j++) {
                    //Obtener de la lista de datos un dato tras otro
                    Node dato = datosEmpleado.item(j);
                    //Comprobar que el dato se trata de un nodo de tipo Element
                    if (dato.getNodeType() == Node.ELEMENT_NODE) {
                        //Mostrar el nombre del tipo de dato
                        if (dato.getNodeName() == "ds:DigestValue") {
                            //El valor está contenido en un hijo del nodo Element
                            Node datoContenido = dato.getFirstChild();
                            //Mostrar el valor contenido en el nodo que debe ser de tipo Text
                            if (datoContenido != null && datoContenido.getNodeType() == Node.TEXT_NODE) {
                                //System.out.println(datoContenido.getNodeValue());
                                if (datoContenido.getNodeValue() != null) {
                                    firma = datoContenido.getNodeValue();
                                }
                            }
                        }
                    }
                }
            }

        } catch (org.xml.sax.SAXException ex) {
            log.error("ERROR: El formato XML del fichero no es correcto\n" + ex.getMessage());
        } catch (IOException ex) {
            log.error("ERROR: Se ha producido un error al leer el fichero\n" + ex.getMessage());
        } catch (ParserConfigurationException ex) {
            log.error("ERROR: No se ha podido crear el generador de documentos XML\n" + ex.getMessage());
        }
        return firma;
    }

    public String getInfoToBarCode(String path) {
        String respuesta = "";
        try {
            String IssueDate = "";
            DocumentBuilderFactory fabricaCreadorDocumento = DocumentBuilderFactory.newInstance();
            DocumentBuilder creadorDocumento = fabricaCreadorDocumento.newDocumentBuilder();
            Document documento = creadorDocumento.parse(path);
            //Obtener el elemento raíz del documento
            Element raiz = documento.getDocumentElement();

            //=====RUC
            NodeList nodlist = raiz.getElementsByTagName("cac:PartyIdentification");
            respuesta += nodlist.item(0).getTextContent() + "|";

            //=====InvoiceTypeCode
            NodeList InvoiceTypeCode = raiz.getElementsByTagName("cbc:InvoiceTypeCode").item(0) == null ? raiz.getElementsByTagName("cbc:ResponseCode") : raiz.getElementsByTagName("cbc:InvoiceTypeCode");
            respuesta += InvoiceTypeCode.item(0).getTextContent() + "|";
            //=====cbc:ID
            nodlist = raiz.getChildNodes();
            for (int i = 0; i < nodlist.getLength(); i++) {
                Node nod = nodlist.item(i);
                if (nod.getNodeName().equals("cbc:ID")) {
                    respuesta += nod.getTextContent().replaceAll("-", "|") + "|";
                }
                if (nod.getNodeName().equals("cbc:IssueDate")) {
                    IssueDate = nod.getTextContent();
                }
            }
            //=====>LegalMonetaryTotal

            nodlist = raiz.getElementsByTagName("cac:LegalMonetaryTotal").item(0) == null ? raiz.getElementsByTagName("cac:RequestedMonetaryTotal").item(0).getChildNodes() : raiz.getElementsByTagName("cac:LegalMonetaryTotal").item(0).getChildNodes();
            for (int i = 0; i < nodlist.getLength(); i++) {
                Node nod = nodlist.item(i);
                if (nod.getNodeName().equals("cbc:TaxExclusiveAmount")) { //NO EN : ND
                    respuesta += nod.getTextContent() + "|";
                }
                if (nod.getNodeName().equals("cbc:PayableAmount")) {
                    respuesta += nod.getTextContent() + "|";
                }
            }
            //=====>IssueDate
            respuesta += IssueDate + "|";
            log.info(respuesta);

            //=====>AccountingCustomerParty
            nodlist = raiz.getElementsByTagName("cac:AccountingCustomerParty").item(0).getChildNodes();
            for (int i = 0; i < nodlist.getLength(); i++) {
                Node nod = nodlist.item(i);
                if (nod.getNodeName().equals("cbc:AdditionalAccountID")) {
                    respuesta += nod.getTextContent() + "|";
                }
            }
            for (int i = 0; i < nodlist.getLength(); i++) {
                Node nod = nodlist.item(i);
                if (nod.getNodeName().equals("cbc:CustomerAssignedAccountID")) {
                    respuesta += nod.getTextContent() + "|";
                }
            }

        } catch (org.xml.sax.SAXException ex) {
            respuesta = "LecturaXML:org.xml.sax.SAXException - ERROR: Al leer el archivo de respuesta" + ex.getMessage();
            log.error(respuesta);
        } catch (IOException ex) {
            respuesta = "LecturaXML:Error IOException - ERROR: Al leer el archivo de respuesta" + ex.getMessage();
            log.error(respuesta);
        } catch (ParserConfigurationException ex) {
            respuesta = "LecturaXML:Error ParserConfigurationException - ERROR: No se ha podido crear el generador de documentos XML\n" + ex.getMessage();
            log.error(respuesta);
        } catch (DOMException exg) {
            respuesta = "LecturaXML:Error DOMException - ERROR: Al leer el archivo de respuesta" + path + "en getInfoToBarCode" + exg.getMessage();
            log.error(respuesta);
        }
        return respuesta;
    }

    public String getInfoToBarCodeOD(String path) {
        String respuesta = "";
        try {
            String IssueDate = "";
            DocumentBuilderFactory fabricaCreadorDocumento = DocumentBuilderFactory.newInstance();
            DocumentBuilder creadorDocumento = fabricaCreadorDocumento.newDocumentBuilder();
            Document documento = creadorDocumento.parse(path);
            //Obtener el elemento raíz del documento
            Element raiz = documento.getDocumentElement();

            //=====RUC
            NodeList nodlist = raiz.getElementsByTagName("cac:PartyIdentification");
            respuesta += nodlist.item(0).getTextContent() + "|";

            //=====InvoiceTypeCode
            //NodeList InvoiceTypeCode = raiz.getElementsByTagName("cbc:InvoiceTypeCode").item(0) == null ? raiz.getElementsByTagName("cbc:ResponseCode") : raiz.getElementsByTagName("cbc:InvoiceTypeCode");
            respuesta += "20" + "|";//InvoiceTypeCode.item(0).getTextContent() + "|";
            //=====cbc:ID
            nodlist = raiz.getChildNodes();
            for (int i = 0; i < nodlist.getLength(); i++) {
                Node nod = nodlist.item(i);
                if (nod.getNodeName().equals("cbc:ID")) {
                    respuesta += nod.getTextContent().replaceAll("-", "|") + "|";
                }
                if (nod.getNodeName().equals("cbc:IssueDate")) {
                    IssueDate = nod.getTextContent();
                }
            }
            //=====>LegalMonetaryTotal

            nodlist = raiz.getElementsByTagName("cbc:TotalInvoiceAmount");
            respuesta += nodlist.item(0).getTextContent() + "|";

            nodlist = raiz.getElementsByTagName("sac:SUNATTotalPaid");
            respuesta += nodlist.item(0).getTextContent() + "|";
            //=====>IssueDate
            respuesta += IssueDate + "|";

            //=====>AccountingCustomerParty
            nodlist = raiz.getElementsByTagName("cac:ReceiverParty").item(0).getChildNodes();
            for (int i = 0; i < nodlist.getLength(); i++) {
                Node nod = nodlist.item(i);
                if (nod.getNodeName().equals("cac:PartyIdentification")) {
                    NodeList noi = nod.getChildNodes();
                    for (int x = 0; x < noi.getLength(); x++) {
                        Node nodx = noi.item(x);
                        if (nodx.getNodeName().equals("cbc:ID")) {

                            respuesta += nodx.getAttributes().getNamedItem("schemeID").getTextContent() + "|";
                            respuesta += nodx.getTextContent() + "|";
                        }
                    }
                }
            }
            for (int i = 0; i < nodlist.getLength(); i++) {
                Node nod = nodlist.item(i);
                if (nod.getNodeName().equals("cbc:CustomerAssignedAccountID")) {
                    respuesta += nod.getTextContent() + "|";
                }
            }

        } catch (org.xml.sax.SAXException ex) {
            System.out.println("ERROR: El formato XML del fichero no es correcto\n" + ex.getMessage());
            respuesta = "Error al leer el archivo de respuesta";
        } catch (IOException ex) {
            System.out.println("Error al leer el archivo de respuesta\n" + ex.getMessage());
            respuesta = "Error al leer el archivo de respuesta";
        } catch (ParserConfigurationException ex) {
            System.out.println("ERROR: No se ha podido crear el generador de documentos XML\n" + ex.getMessage());
            respuesta = "Error al leer el archivo de respuesta";
        } catch (DOMException exg) {
            System.out.println("==>Error while reading file " + path + " on getInfoToBarCode(path)\n");
        }
        return respuesta;
    }
}
</code>
I get this error on Null
<code>2023-09-10T16:32:12.240-05:00  INFO 36024 --- [nio-8081-exec-5] p.com.carbonstar.admin.util.LecturaXML   : LecturaXML.obtenerDigestValue BarCodeQR - resultado HashCode : MTIpa+f0o7DYKtZebc7jJOviqjc=
2023-09-10T16:32:12.240-05:00  INFO 36024 --- [nio-8081-exec-5] p.com.carbonstar.admin.util.LecturaXML   : LecturaXML Guardando HashCode en la Boleta : MTIpa+f0o7DYKtZebc7jJOviqjc=
Estado de la Boleta : null
2023-09-10T16:32:12.243-05:00 ERROR 36024 --- [nio-8081-exec-5] o.a.c.c.C.[.[.[.[dispatcherServlet]      : Servlet.service() for servlet [dispatcherServlet] in context with path [/admin] threw exception [Request processing failed: java.lang.NullPointerException: Cannot invoke "pe.com.carbonstar.admin.boleta.BoletaService.actualizarHashCodeBoleta(java.lang.Long, String)" because "this.serviceBoleta" is null] with root cause

java.lang.NullPointerException: Cannot invoke "pe.com.carbonstar.admin.boleta.BoletaService.actualizarHashCodeBoleta(java.lang.Long, String)" because "this.serviceBoleta" is null
    at pe.com.carbonstar.admin.util.LecturaXML.guardarHashYBarCodeQR(LecturaXML.java:231) ~[classes/:na]
    at pe.com.carbonstar.admin.cpews.BolElectronica.generarXMLZipiadoBoleta(BolElectronica.java:89) ~[classes/:na]
    at pe.com.carbonstar.admin.boleta.BoletaController.generarBoletaElectronica(BoletaController.java:620) ~[classes/:na]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
</code>
Comment: Add relevant code from `BolElectronica.java` and `BoletaController.java:620`. I suspect you're using a POJO LecturaXML  object as I already commented on your previous question.
Comment: Please share the package details of these classes as well as your `@ComponentScan` annotation configuration in addition to what @void void requested. Since you might be using the aforementioned annotation implicitly via `@SpringBootApplication` , please include the class with this annotation and its package name as well.
Comment: I'm going to try to upload it on Github. Stackoverflow doesn't allow me to add more code.
Comment: It was added to a repository on github  https://github.com/croelanjr/erpcarbonstar.git
Answer: This is the relevant snippet from your repository (BolElectronica.java):
<code>        LecturaXML lectura = new LecturaXML();
        org.apache.xml.security.Init.init();
        String resultado = "";
        String unidadEnvio = Util.getPathZipFilesEnvio(items.getEmpr_nroruc(), items.getDocu_fecha());
        log.info("Ruta de Unidad de Envio : " + unidadEnvio);
        String pathXMLFile;

        try {
            log.info("generarXMLZipiadoBoleta - Extraemos datos para preparar XML ");
            log.info("generarXMLZipiadoBoleta - Ruta de directorios " + unidadEnvio);
            log.info("generarXMLZipiadoBoleta - Iniciamos cabecera ");

            if (items != null) {
                pathXMLFile = unidadEnvio + items.getEmpr_nroruc() + "-03-" + items.getDocu_numero() + ".xml";
                //======================crear XML =======================
                resultado = creaXml(items, detdocelec, leyendas, unidadEnvio);
                log.info(resultado);
                //======================guardar Hash Y Barcode QR =======================
                log.info("generarXMLZipiadoBoleta - Crear Hashcode y CodeBarQR");
                lectura.guardarHashYBarCodeQR(items.getDocu_tipodocumento(), items.getDocu_numero(), pathXMLFile, items.getDocu_boleta());
</code>
The <code>lectura</code> instance is not a bean managed by spring, so it does not have the dependencies injected. Either provide them with a constructor or in some other way, or use the <code>BolElectronica</code> instance from the spring context by injecting it somewhere appropriate.
To clarify: the <code>serviceBoleta</code> private field is null in your <code>lectura</code> instance because you created the <code>lectura</code> instance yourself, and this is probably not what you want to do as you already have a singleton instance in the spring context which has the <code>serviceBoleta</code> field injected using reflection because you are using the <code>@Autowired</code> annotation.
Comment: Thank you @void-void, So, I make a little code to update in the class BolElectronica.java
Comment: I have tried to do it in the Class BolElectronica.java, and the same error also appears.


Ajax sending Null to .net core MVC controller and unsure why

Question: I am very new to Ajax and for me it's something I can't get my head around (well jQuery in general to be honest).
I am trying to pass an object containing two string arrays, one of search parameters, another of search values.
The issue, is that when i press the submit button, the Ajax call hits the MVC controller but the Model in the Controller returns Null in both arrays.
The Ajax call:
    function onActivation() {
    var send = { queryParameters: queryParameters, queryValues: queryValues };
    $.ajax({
        url: '@Url.Action("Index", "SearchResults")',
        type: "POST",
        contentType: "application/json; charset=utf-8;",
        data: JSON.stringify({ advancedSearch: send }),
        success: function (response) {
            response ? alert("It worked!") : alert("It didn't work.");
        }
    });
}

The Model:
public class AdvancedSearch
    {
        public string[] queryParameters { get; set; }
        public string[] queryValues { get; set; }
    }

The first line of the controller where things go wrong:
public async Task<IActionResult> Index(AdvancedSearch advancedSearch)

Comment: Use just `data: JSON.stringify(send),`. You may also be able to use just `data: send,` depending on how your ModelBinder is configured
Comment: @RoryMcCrossan that doesn't seem to have worked, I have changed it to your first suggestion but still returning null.
Comment: If it's *returning* null then it's a problem with your C# logic. Your question states that it's *sending* null, though...?
Comment: @RoryMcCrossan sorry i'm using the wrong terminology i think, i'm still learning my way. It is on the first line of the controller when it is hit that I check the value of advancedSearch. When looking at both arrays within it, they are both Null.
Comment: Ok. Have you checked the value of `send` using `console.log()` before you make the request to ensure it's been populated correctly?
Comment: Yep, here's the result:
queryParameters: Array [ "FirstName" ]

queryValues: Array [ "Charles" ]
Comment: Try if adding `[FromBody]` helps, like this: `Index([FromBody] AdvancedSearch advancedSearch)`
Comment: @PeterB it works!!! Thank you so much!! :)
Answer: For this to work you need to submit the Ajax with just data: send. For the model data binding to happen you can try to add another parameter in Ajax which is traditional: true as suggested in
Send array via Ajax and bind to List<string> on MVC 4
Comment: Thanks for you suggestion :) PeterB's suggestion worked for me.


Why does executing a count() return a PhpMyAdmin error with backtrace

Question: I am trying to execute the following command over PHPMyAdmin 4.8.4:
SELECT *, count(ref_id) AS c FROM `articles_test` group by ref_id order by c desc

This returns the following error message:

Followed by this error backtrace:

Notice in ./libraries/classes/Display/Results.php#2488  Trying to get
  property of non-object
Backtrace
./libraries/classes/Display/Results.php#2389:
  PhpMyAdmin\Display\Results->_addClass( string 'data hide ', boolean
  false, NULL, string '', )
  ./libraries/classes/Display/Results.php#3818:
  PhpMyAdmin\Display\Results->_buildNullDisplay( string 'data hide ',
  boolean false, NULL, ) ./libraries/classes/Display/Results.php#3071:
  PhpMyAdmin\Display\Results->_getDataCellForNonNumericColumns( NULL,
  string 'data hide ', NULL, array, array, boolean false, array, array,
  array, boolean false, array, , NULL, )
  ./libraries/classes/Display/Results.php#2695:
  PhpMyAdmin\Display\Results->_getRowValues( , array, integer 24, array,
  array, string 'grid_edit click2', array, string 'SELECT *,
  count(ref_id) AS c FROM articles_test group by ref_id order by c
  desc', array, ) ./libraries/classes/Display/Results.php#4287:
  PhpMyAdmin\Display\Results->_getTableBody( , array, array, array,
  boolean false, ) ./libraries/classes/Sql.php#1738:
  PhpMyAdmin\Display\Results->getTable( , array, array, boolean false, )
  ./libraries/classes/Sql.php#2031:
  PhpMyAdmin\Sql->getHtmlForSqlQueryResultsTable( , string
  './themes/pmahomme/img/', NULL, array, boolean true, string '2554',
  integer 25, NULL, , array, ) ./libraries/classes/Sql.php#2252:
  PhpMyAdmin\Sql->getQueryResponseForResultsReturned( , array, string
  'test', string 'articles_test', NULL, NULL, , string
  './themes/pmahomme/img/', string '2554', integer 25, NULL, NULL, NULL,
  NULL, NULL, string 'SELECT *, count(ref_id) AS c FROM articles_test
  group by ref_id order by c desc', NULL, ) ./import.php#736:
  PhpMyAdmin\Sql->executeQueryAndGetQueryResponse( array, boolean false,
  string 'test', string 'articles_test', NULL, NULL, NULL, NULL, NULL,
  NULL, string 'tbl_structure.php', string './themes/pmahomme/img/',
  NULL, NULL, NULL, string 'SELECT *, count(ref_id) AS c FROM
  articles_test group by ref_id order by c desc', NULL, NULL, )

I am running the following system:

5.7.24-0ubuntu0.16.04.1 - Apache/2.4.18 (Ubuntu) Datenbank-Client
  Version: libmysql - mysqlnd 5.0.12-dev - 20150407 - $Id:
  b5c5906d452ec590732a93b051f3827e02749b83 $ PHP-Erweiterung:
  mysqliDokumentation curlDokumentation mbstringDokumentation
  PHP-Version: 7.0.32-0ubuntu0.16.04.1

Is this a bug, or might there be a problem with the db? No errors are visible, tables look OK.
Comment: Do simple queries work? like "SELECT * FROM articles_test LIMIT 1" ?
Comment: Maybe same issue: https://stackoverflow.com/questions/51972998/phpmyadmin-crashing
Comment: Yes, everything else seems to work. I now upgraded to the newest version, but still the same error.
Comment: 4.8.4 is 11 days old. Maybe its a bug? Try downgrade to 4.8.3?
Answer: What is the MySQL version you are using. The query
SELECT *, count(ref_id) AS c
FROM `articles_test`
group by ref_id order by c desc

will not run on default settings in MySQL 5.7 and greater due to the default sql_mode only_full_group_by. The problem is that you are mixing the all columns notation (*) with an aggregate function. Older MySQL versions allowed this (erroneous) query, but MySQL 5.7 by default is more strict.
If you want to list all rows from articles_test with count for each ref_id (same value repeated for same ref_id's), use a subquery:
SELECT a.*, count(ref_id) AS c
FROM articles_test a
  JOIN (
    SELECT at.ref_id, count(*) as refid_count
    FROM articles_test at
    GROUP BY at.ref_id
  ) q as q.ref_id=a.ref_id

Comment: I am runnning the following version: Server-Version: 5.7.24-0ubuntu0.16.04.1 - (Ubuntu). So this might be the issue. Is there another notation that will return all results and the counter?


Rerender MathJax text?

Question: I have a web app running on Apache that has a text input box. Here the users can publish text and preview it. I have been able to dynamically render mathematical formulas using MathJax in the preview. The issue is after a uploads the HTML code (their publish text) to the MySQL server and then when any user visits that site, the MathJax does not render. I save the exact same HTML code that is generated after the user making some text italic, render mathematical formulas, etc. So the saved HTML does not contain "x^2" but rather the code generated by MathJax to actually view the maths correctly.
How do I go from the "raw" HTML code and render the math jax tags and code that is inside a
? It is there, it just does not render anything, just some blank square that is taking up space.
I have tried using MathJax.rerender(); using window.onload() { ... } so that the MathJax renders when the page renders. I have also tried MathJax.Hub.Queue(["Typeset", MathJax.Hub]); as well as MathJax.typeset();
All of these are placed at the end of window.onload { ...  [code] }.
Edit: I am using MathJax 3.x, I have seen some people commenting on other posts that the notation is changed from MathJax 2.x however searching in their documentation for the keyword "Rerender" gives only one, very useless comment about returning false when calling rerender and not how to actually rerender equations.
Comment: Please provide a code sample that shows either how you save the rendering or how/what you inject it. A random guess would be that you're using the SVG output with its default "font-caching" behavior and are not storing the SVG paths that are separtely in the DOM.
Comment: @PeterKrautzberger It takes the text (`document.getElementById('input').innerHTML`), enters it into an output div and calls `MathJax.typeset();`. It generates MathJax specific tags that for obvious reasons (they are not put through a renderer) are not rendered again because when I visit the post there is no `$5x+x^2$` only the MathJax tags. How do I re-render MathJax tags is my question.
Comment: @linker Does my answer solve your problem?
Answer: Instead of calling MathJax.typeset() in the window.onload() event, call MathJax.typeset() when the entire document has loaded.
For example:
document.addEventListener('load', function(){
    MathJax.typeset()
})

Comment: This does not re-render the math.
Comment: @linker Sorry, I am not sure I understood your problem correctly. Is the raw HTML of the format `\(x^2\)` or `x^2`? If it is the latter, are you trying to figure out how to change it to the former?
Comment: I am rendering the html tags that is generated from MathJax.typeset(). Its multiple tags, with different layers and references. Try to genereate x^2 using mathjax and then inspect the element in your browser, looking at the generated html/js code. That is what I am trying to re-render

Rerender MathJax text?


Consulta Mysql - Duas tabelas e intervalo de datas

Question: Tenho duas tabelas, uma para o cadastro de técnicos e uma para as tarefas.
É uma relação 1-->N.
Tabela 1 (TECNICO):
cd_tecnico | nome

Tabela 2 (TAREFA)
cd_tarefa | cd_tecnico | dt_inicio | dt_fim

Preciso de dois filtros para verificar em uma data qualquer (informada pelo usuário) quem está e quem não está em uma tarefa.
1 - Listar quem está em uma tarefa na data informada. Aqui está funcionando OK.
Select * from TECNICO tec
inner join TAREFA ta ON
ta.cd_tecnico = tec.cd_tecnico
and
(ta.dt_inicio <='2016-03-10' and ta.dt_conclusao>='2016-03-10')

2 - Listar quem está não está em uma tarefa na data informada.
Aqui está a minha dúvida na melhor forma de fazer. Tentei um select de outro select mas ficou muito lento e não funcionou direto.
Qual seria a melhor solução neste caso?
Answer: Você pode usar o left join para trazer todos os TECNICO, e um Case para verificar quem tem ou não tarefa.
declare @TECNICO table
(
  cd_tecnico int,
  nome varchar (30)
)

declare @TAREFA table
(
  cd_tecnico int,
  cd_tarefa int,
  nome varchar (30),
  dt_inicio date,
  dt_conclusao date
)

insert into @TECNICO values
(1, 'João'),
(2, 'Pedro'),
(3, 'Maria'),
(4, 'Carlos'),
(5, 'Antonio')

insert into @TAREFA values
(1, 1 ,'Correção banco', '2016-03-10', '2016-03-10' ),
(2, 1 ,'Correção app', '2016-03-10', '2016-03-10' ),
(3, 1 ,'Correção grid', '2016-03-11', '2016-03-11' ),
(5, 1 ,'Correção banco', '2016-03-10', '2016-03-10' )

Select *, case when ta.cd_tecnico is not null then 'Tem tarefa'  else 'não tem tarefa' end as Tarefa
from @TECNICO tec
left join @TAREFA ta
ON ta.cd_tecnico = tec.cd_tecnico
and (ta.dt_inicio <='2016-03-10' and ta.dt_conclusao >= '2016-03-10')

Comment: Valeu Dot Net. Obrigado pela ajuda.
Comment: ótima solução (case when) e performático!! :-D Parabéns!
Answer: Uma resposta completa para você refletir (não coloquei as condições da clausula where, fica a seu critério).
Um jeito tradicional é usar sub-consultas para o que você precisa isto funcionará na maioria dos SGBDs e não somente no MySQL. Claro, esta é uma solução caso o SGBD não possua recurso disponível de Case When, utilizado na outra resposta pelo amigo @DotNet.
Vale lembrar que é importante medir o desempenho da consulta, pois quando se utiliza subconsultas, o consumo pode ser elevado.
CREATE TABLE TECNICO(
    CODIGO INTEGER NOT NULL PRIMARY KEY,
    NOME VARCHAR(500) NOT NULL
);

CREATE TABLE TAREFA(
    CODIGO INTEGER NOT NULL PRIMARY KEY,
    DESCRICAO VARCHAR(500) NOT NULL,
    DATA_INICIO DATETIME NOT NULL,
    DATA_FIM DATETIME NOT NULL,
    TECNICO INTEGER NOT NULL,
    CONSTRAINT FK_TAREFA_TECNICO FOREIGN KEY (TECNICO)
    REFERENCES TECNICO(CODIGO)
);

INSERT INTO TECNICO VALUES (1,'MATEUS');
INSERT INTO TECNICO VALUES (2,'JOSÉ');
INSERT INTO TECNICO VALUES (3,'CARLOS');
INSERT INTO TECNICO VALUES (4,'PATRÍCIA');

INSERT INTO TAREFA VALUES (100, 'CRIAR EJBs',
STR_TO_DATE('1/6/2016 8:06:26 AM', '%d/%m/%Y %r'),
STR_TO_DATE('30/6/2016 8:06:26 AM', '%d/%m/%Y %r'),1);

INSERT INTO TAREFA VALUES (101, 'Criar testes unitarios',
STR_TO_DATE('15/6/2016 8:06:26 AM', '%d/%m/%Y %r'),
STR_TO_DATE('30/6/2016 8:06:26 AM', '%d/%m/%Y %r'),1);

INSERT INTO TAREFA VALUES (102, 'Gerar build',
STR_TO_DATE('1/6/2016 8:06:26 AM', '%d/%m/%Y %r'),
STR_TO_DATE('2/6/2016 8:06:26 AM', '%d/%m/%Y %r'),2);

-- Aqui temos uma junção interna (só trará as correspondências que existem)
SELECT * FROM TECNICO te
inner join TAREFA ta ON te.CODIGO = ta.TECNICO;

-- Trará quem tem ou não tarefa (juntos - à esquerda)
SELECT * FROM TECNICO te
left outer join TAREFA ta ON te.CODIGO = ta.TECNICO;

-- Só os técnicos que não possuem tarefa. A query interna retorna os tecnicos que possuem tarefas e a externas aqueles que estão fora do conjunto. bastaria você acescentar a clausula where no select interno (subconsulta).
SELECT * FROM TECNICO te where te.codigo NOT IN (SELECT te.codigo FROM TECNICO te
inner join TAREFA ta ON te.CODIGO = ta.TECNICO)

Comment: @DotNet exato! Por isso mesmo que na resposta acrescentei que pode ser um banco legado que não tenha recurso de Case When. Já tive problemas com um DB2 antigo que não oferecia esse recurso.
Comment: NOT IN, tem um custo alto nesse caso.
Comment: Se tive suporte nesse caso o exists seria melhor
Comment: Sim! No Oracle por exemplo, 11g é recomendável o NOT EXISTS, no DB2, tanto faz ;-)
Comment: Agradeço a ajuda Mateus.


Ideas how to store code snippets/objects (not json) in mongodb?

Question: So let's say I am doing converting csv to json in node.js, and doing mapping between the fields found in the customer's input file and the object that my platform requires, such as:
 var objInvoice = {
        "id" : guid.create().value,
        "financingType" : "scf",
        "batchId" : batchId,
        "recordTypeCode" : inv.kayittipi,
        "buyerReference" : result[0].tedarikcireferans,
        "supplierReference" : inv.tedarikcireferans,
        "invoiceDate" : moment(inv.faturatarih +"-140000"  , "YYMMDD-HHmmss").toISOString(),
        "certifiedInvoiceAmount" : inv.odenecekfaturatutar,
        "currencyCode" : inv.parabirimi,
        "maturityDate" : moment(inv.orjvadetarihi +"-140000"  , "YYMMDD-HHmmss").toISOString(),
        "correctedMaturityDate" : moment(inv.orjvadetarihi +"-140000"  , "YYMMDD-HHmmss").toISOString(),
        "originalInvoiceAmount" : inv.orjfaturatutar,
        "invoiceNo" : inv.faturano,
        "invoiceSerialNo" : inv.faturaserino,
        "noterizedDocNo" : inv.belgenoteryevmiyeno,
        "hashCode" : inv.hashCode,
        "forecastDate" : inv.fiilivadetarihi,
        "supplierTaxId" : inv.tedarikcivkn,
        "supplierName" : inv.tedarikciadi,
        "invoiceType" : inv.faturatipi,
        "buyerAccountNumber" : inv.aliciiban,
        "buyerTaxId" : inv.alicivkn,
        "fiReference" : inv. bankakodu,
        "bankBranchCode" : inv.bankasubeno,
        "invoiceUploadStatus" : inv.dosyakayitstatu,
        "gwCode" : "111110000000",
        "gwCodeExplanation" : "",
        "invoiceDiscountDate" : null,
        "additionalInformation1" : inv.aciklama1,
        "additionalInformation2" : inv.aciklama2,
        "additionalInformation3" : inv.aciklama3,
        "lastModificationDate" : null,
        "newInvoiceId" : "00000000-0000-0000-0000-000000000000",
        "oldInvoiceId" : "00000000-0000-0000-0000-000000000000",
        "supplierIban" : "",
        "supplierBankName" : "",
        "customUniqueId" : "",
        "deductionReason" : "",
        "paymentObligationNo" : null,
        "deductionAmount" : "",
        "sellAmount" : "",
        "invoiceAmountWithoutVat" : "",
        "uploadDate" : now.toISOString(),

    }

but a customer2 may have a different positioned fields,or even different headers in file - such as:
var objInvoice = {
        "id" : guid.create().value,
        "financingType" : "scf",
        "batchId" : batchId,
        "recordTypeCode" : inv.element1,
        "buyerReference" : result[0].element2,
        "supplierReference" : inv.element2,
        "invoiceDate" : moment(inv.element3 +"-140000"  , "YYMMDD-HHmmss").toISOString(),
        "certifiedInvoiceAmount" : inv.element4,
        "currencyCode" : inv.element5,
        "maturityDate" : moment(inv.element6 +"-140000"  , "YYMMDD-HHmmss").toISOString(),
        "correctedMaturityDate" : moment(inv.element6 +"-140000"  , "YYMMDD-HHmmss").toISOString(),
        "originalInvoiceAmount" : inv.element7,
        "invoiceNo" : inv.element8,
        "invoiceSerialNo" : inv.element9,
        "noterizedDocNo" : inv.element10,
        "hashCode" : inv.element11,
        "forecastDate" : inv.element12,
        "supplierTaxId" : inv.element13,
        "supplierName" : inv.element14,
        "invoiceType" : inv.element15,
        "buyerAccountNumber" : inv.element16,
        "buyerTaxId" : inv.element17,
        "fiReference" : inv. element18,
        "bankBranchCode" : inv.element19,
        "invoiceUploadStatus" : inv.element20,
        "gwCode" : "111110000000",
        "gwCodeExplanation" : "",
        "invoiceDiscountDate" : null,
        "additionalInformation1" : inv.element21,
        "additionalInformation2" : inv.element22,
        "additionalInformation3" : inv.element23,
        "lastModificationDate" : null,
        "newInvoiceId" : "00000000-0000-0000-0000-000000000000",
        "oldInvoiceId" : "00000000-0000-0000-0000-000000000000",
        "supplierIban" : "",
        "supplierBankName" : "",
        "customUniqueId" : "",
        "deductionReason" : "",
        "paymentObligationNo" : null,
        "deductionAmount" : "",
        "sellAmount" : "",
        "invoiceAmountWithoutVat" : "",
        "uploadDate" : now.toISOString(),

     }

so I was thinking if it's possible to store each 'mapping' per customer in mongodb? and pulls the correct objInvoice via customer reference?
The issue is, objInvoice cannot be stored as a json document since it contains variables such as inv.element1.
I've also tried to store as a one big string  (I tried with {} and without {} ), I was able to store it fine but when I pulled it from the code and unstringnified it the vars didn't get processed as expected.
Any ideas fellow good programmers?
Or the only way is to store those in seperate js files per customer?
Comment: Did you (de)stringify with JSON.stringify and JSON.parse? Also, does the different order matter and needs to be saved?
Comment: I have tried JSON.parse, but the object is not a valid json object after all, since it contains variables  ( json values need to be either string or number or boolean)  - i did try to store them as string but the vars didn't get processed in code after i turned it back to object.   How does the order affect the logic?
Comment: Unfortunately this is not even a valid Javascript object... you should restructure your data in order to be valid Javascript object and/or JSON
Answer: Unfortunately, your data is not even valid Javascript Objects or JSON.
An idea is to convert values, like moment(inv.orjvadetarihi +"-140000"  , "YYMMDD-HHmmss").toISOString() which are not valid, into strings (escaping correctly). As a result you will be able to JSON.stringify and JSON.parse. The strings can then be evaluated in your code.
Preprocessing your data to escape non-string values into strings certainly works. You may use regexes.
Comment: That entirely depends on your code. If it doesn't in its simplest form, some more complex eval logic depending on some parsing will. If push comes to shove, you will have to parse.
Comment: eval worked like a charm, all i had to do was fetching (dbobjInvoice) from mongo then var objInvoice =  eval(dbobjInvoice)  ....where dbobjInvoice is a big string stored in mongodb
Comment: Awesome, glad to have helped


Update de Date e Time para verificar se está online

Question: No meu app android tenho um serviço que envia de tempos em tempos uma localização do usuário e salva em outro campo lastUpdate o dia e horário em que aconteceu o update.
Atualmente uso Calendar.getInstance().getTime() para pegar o Date e enviar para o banco, porém o que percebo é que a hora de muitos às vezes está mais adiantada do que a hora corrente, o que fazer para padronizar?
Answer: Para que tudo funcione como tu pretendes, o dispositivo que recebe a data tem de estar sincronizado com a máquina onde está o servidor. Não há como dar a volta a esta situação.
O Calendar.getInstance().getTime() depende da data/hora do dispositivo android.
No entanto se já efectuas-te algum tipo de sincronização e o erro acontece a uma escala reduzida aconselho-te a usar o System.currentTimeMillis(); para efetuares as comparações.


Boundary of the image of a continuous function contained in image of the boundary of the domain

Question: I am having trouble solving the following exercise:

Let $U$ be a bounded domain, and let $f(z)$ be a continuous function on $U \cup \partial U$ that is holomorphic on $U$. Show that $\partial\left( f(U)\right)\subseteq f(\partial U)$, that is, the boundary of the open set $f(U)$ is contained in the image under $f(z)$ of the boundary of $U$.

One of the main issues I have with this exercise is that my teacher has defined the open mapping theorem as:

Open mapping theorem: if $\Omega \subseteq \mathbb{C}$ is a connected open set and $f$ is holomorphic and not constant on $\Omega$, then $f(\Omega)$ is an open set in $\mathbb{C}$.

The additional hypothesis that the domain be connected means that we cannot apply the theorem directly. This is my approach:

Suppose $f$ is not constant (if it is the result is clear). Since $\stackrel{\circ}{U}$ is open, for each $z\in\stackrel{\circ}{U}$ there exists $r_z>0$ such that the open disk of center $z$ and radius $r_z$, $D(z, r_z)$, is contained in $\stackrel{\circ}{U}$. Then we can write $\stackrel{\circ}{U}$ as:

$\stackrel{\circ}{U} = \bigcup_{z\in\stackrel{\circ}{U}} D(z, r_z)$

Hence:

$f(\stackrel{\circ}{U}) = f\left(\bigcup_{z\in\stackrel{\circ}{U}} D(z, r_z)\right) = \bigcup_{z\in\stackrel{\circ}{U}} f\left(D(z, r_z)\right)$

Since $f$ is holomorphic in $\stackrel{\circ}{U}$, disks are open connected sets and the arbitrary union of open sets is open, we can apply the Open mapping theorem to conclude that $f(\stackrel{\circ}{U})$ is an open set. This means that $f$ maps interior points of $U$ to interior points of $f(U)$.

Let $w$ be a point of $\partial f(U)$, then there exists a sequence $w_n \subseteq f(U)$ that converges to $w$, for $\partial f(U)$ is a compact set (1). By definition of $f(U)$, for all $k\in\mathbb{N}$ there exists $z_k\in\stackrel{\circ}{U}$ such that $f(z_k) = w_k$. By hypothesis $U$ is bounded, and therefore $z_k\rightarrow z\in\partial U$ and $f(z_k) \rightarrow f(z) = w\in\partial f(U)$, which implies:

$\forall w \in\partial f(U) : \exists z\in\partial U \mid f(z) = f(w) \implies \partial f(U) \subseteq f(\partial U)$.

One of my concerns is that $U$ is an infinite union of open sets, and I am not sure that $f(\bigcup_{k=0}^{\infty} U_k) = \bigcup_{k=0}^{\infty} f(U_k)$ still holds in such conditions. My other issue is that I am not sure that $(1)$ is true.
Thank you.
Comment: It's always true that $f(\bigcup_{k=0}^\infty U_k)=\bigcup_{k=0}^\infty f(U_k)$. Just prove inclusion in both directions (it follows directly from definition).
Comment: In case anyone else is wondering, this is from Theodore Gamelin's *Complex Analysis*: Section VIII.4, exercise 8.
Answer: Your proof is absolutely correct.
As Yanko said in his comment, each function $\phi : X \to Y$ between sets $X,Y$ has the property $\phi(\bigcup_{\alpha \in A} M_\alpha) = \bigcup_{\alpha \in A} \phi(M_\alpha)$, where $(M_\alpha)_{\alpha \in A}$ is an arbitrary family of subsets of $X$.
However, to show that a non-constant holomorphic $f : U \to \mathbb{C}$ defined on arbitrary open $U \subset \mathbb{C}$ has an open image $f(U)$, it is unnecessary to consider unions. Let $w \in f(U)$. Choose $z \in U$ such that $f(z) = w$. Since $U$ is open, there exists an open disk $D(z,r) \subset U$. Now $V = f(D(z,r))$ is open and we have $w \in V \subset f(U)$.


For polynomial with degree 3, when $a + ib$ is a root show $a-ib$ is a root, and it also has a rational root.

Question:
Let $p(x)$ be a cubic (i.e. degree $3$) polynomial with
  rational coefficients. Suppose $p(x)$ has a root of the
  form $a + ib$, where $a, b$ are rational,
Prove that $a-ib$ is also a root of $p(x)$, and that $p(x)$ must also have a rational root.

My Attempts:
By assumption, we have:
\begin{align}
p(a + ib)
&=c_3(a + ib)^3+c_2(a + ib)^2+c_1(a + ib)+c_0\\
&=a^3 c_3
+ 3 i a^2 b c_3
+ a^2 c_2
+ 2 i a b c_2
+ a c_1
+ i b c_1
- 3 a b^2 c_3
- i b^3 c_3
- b^2 c_2
+ c_0\\
&=0
\end{align}
This implies:
$$
c_0=
- a^3 c_3
- 3 i a^2 b c_3
- a^2 c_2
- 2 i a b c_2
- a c_1
- i b c_1
+ 3 a b^2 c_3
+ i b^3 c_3
+ b^2 c_2$$
Then for $p(a - ib)$ we have:
\begin{align}
p(a - ib)
&=c_3(a - ib)^3+c_2(a - ib)^2+c_1(a - ib)+c_0\\
&=
a^3 c_3
+ a^2 c_2
+ a c_1
+ i b^3 c_3
- 3 i a^2 b c_3
- 3 a b^2 c_3
- b^2 c_2 - i b c_1
- 2 i a b c_2 \\
&- a^3 c_3
- a^2 c_2
- a c_1
+ i b^3 c_3
- 3 i a^2 b c_3
+ 3 a b^2 c_3
+ b^2 c_2
- i b c_1
- 2 i a b c_2
\\
&=- 6 i a^2 b c_3+ 2i b^3 c_3- 2i b c_1- 4 i a b c_2 \\
\end{align}
I think this isn't a good approache, and I'm stucked now, that didn't give $p(a - ib)=0$ $\dots$ how do I prove this $?$
Any help or hint or suggestion would be appreciated.
Comment: Your first implication should instead be
$$
c_0 + a c_1 + a^2 c_2 - b^2 c_2 + a^3 c_3 - 3 a b^2 c_3=0
$$
and
$$
b (c_1 + 2 a c_2 + 3 a^2 c_3 - b^2 c_3)=0
$$
for the real and imaginary parts respectively. (Rather than as a whole) Expanding for $p(a-ib)$ should give you the same real part and a negative imaginary part, so it's still zero. (You can check via your expansion directly.)
Comment: If $P(z)=0$ then $\overline{P(z)}$ is also 0 and here your polynomial has rational coefficients.
Comment: This will hold if $a,b,c$ are real and rational. Or more generally, if $a/b, b/c, c/a$ are real and rational.
Comment: The tag "elementary-number-theory" is inappropriate. The tag should be "polynomials".
Answer: Hint
Such a polynomial can be expressed as $$p(x){=k(x-a-ib)(x-a+ib)(x-c)\\=k(x^2+a^2+b^2-2xa)(x-c)}$$where $a,b,c\in\Bbb Q$ and $k\in\Bbb C$. Now, what can you say about $K$ and $c$ after expanding the terms?
Answer: The problem really ought to assume that $b\neq0$. I will assume so in the below answer.
For a polynomial with real coefficients (including if the coefficients are rational), we have $p(\bar z)=\overline{p(z)}$. If $p(a+bi)$ (and therefore $\overline{p(a+bi)}$) happens to be $0$, then $p(\overline{a+bi})=p(a-bi)$ must be zero also.
And since both $a+bi$ and $a-bi$ are roots of $p$, that means that
$$
(x-a-bi)(x-a+bi)=x^2 -2ax+a^2+b^2
$$
is a factor of $p(x)$ (this is where $b \neq 0$ comes in; if $b = 0$, then the two roots from the preceeding paragraph are really the same root, and thus we don't know that we can divide out by that one root twice). All coefficients here are rational, and performing the long division $p(x)\div (x^2 -2ax+a^2+b^2)$ can only ever keep all coefficients rational. The result of that division is therefore a degree 1 polynomial with rational coefficients, which thus must have a rational root.
Answer: Lemma: let P be a polynomial from R[X].and degP>2.then if p(s)=0,one has p(s•)=0 where  s• is the conjugate of a.
Proof:
Using the fact that (a•+b•)=(a+b)• we are done
Answer: Since a cubic always has a real root $r$, dividing the cubic by $x-r$ simplifies the problem to a quadratic. Just have to show if $a+ib$ is a root then $a-ib$ is also a root:
$$x^2-(a+ib+c+id)x+(a+ib)(c+id)=0$$
For the coefficients to be rational, we get conditions:
$$b+d=0\\bc+ad=0$$
Answer: $a-ib$ is also a root of $p$ :
The conjugation $\sigma : z \mapsto \bar{z}$ is an automorphism of $\mathbb{Q}[i]$ over $\mathbb{Q}$. Since $p$ has a root in $\mathbb{Q}[i]$, namely $z=a + ib$, we must have $$p(\bar{z}) = p(\sigma(z)) = \sigma(p(z)) = \sigma(0) = 0$$
Hence, $\bar{z} = a - ib$ is also a root of $p$.
$p$ has a root in $\mathbb{Q}$ :
Since $z$ and $\bar{z}$ are roots of $p$, we get that the polynomial $(X - z)(X - \bar{z})$ divides $p$. But $(X - z)(X - \bar{z}) = X^2 - 2aX +a^2-b^2 \in \mathbb{Q}[X]$. Hence, the quotient $q:=\frac{p}{(X - z)(X - \bar{z})}$ is a degree 1 polynomial in $\mathbb{Q}[X]$. Clearly, $q$ has a root, say $r$, in $\mathbb{Q}$. $r$ is the rational root of $p$.


Only allow root to do su specific user

Question: I'm on RHEL 6.8
I have a user "myuser" with sudoer rights and other users with no sudoers rights.
Can I only allow root to do a "su myuser" in local ?
Thank you
Comment: No, you can't. root can do whatever he wants.
Comment: Hello Actually it is not my problem. There is no problem to let root become "myuser", but I don't want other users to become "myuser".
Comment: Well, that's not what you are asking in the question. Anyway, the only way for "otheruser" to su to "myuser" is by knowing the password of "myuser". In that case the user can just log in as "myuser". What are you trying to accomplish?
Answer: Well, once you allow a user to become root, short of using SELinux there's no way to restrict them. Which is why you shouldn't hand out root permissions willy-nilly.
I'd recommend moving away from su to sudo.
That being said, you could cook up something with gpasswd and pam_wheel.so, but at best it might break scripts and at worst it's a security risk:
Use pam_wheel in /etc/pam.d/su.
Quoting man pam_wheel:
NAME
       pam_wheel - Only permit root access to members of group wheel

SYNOPSIS
       pam_wheel.so [debug] [deny] [group=name] [root_only] [trust] [use_uid]
[...]
group=name
       Instead of checking the wheel or GID 0 groups, use the name group to perform the authentication.

References:
https://askubuntu.com/questions/601682/restrict-su-to-a-group-of-users
Comment: Hello, thank you for your answer.
Actually your link and your exemple are short but obvious, I've been able to understand now. Thank you :)

Only allow root to do su specific user


Why does hypothesis of SVM output 0 or 1?

Question: Prof. Andrew Ng in his Machine Learning class says that unlike Logistic Regression, SVM outputs hypothesis as 1 or 0. But I don't understand why SVM's behavior differs from that of logistic regression even though both these algorithms use the same sigmoid function?
In other words, $h(x)$ for Logistic Regression is continuous: $0 \le h(x) \le 1$. But $h(x)$ for SVM is discrete: $h(x) = \{0, 1\}.$
Why?
Comment: It is unfortunate that SVM classifiers are often thought of as yielding *only* binary labels. The SVM decision value that is always implicitly generated is far more informative. Binary labels are merely thresholded decision values.
Comment: It is hard determine what your "why" is trying to ask.  By their very construction, logistic regression outputs log odds and SVM outputs a binary classification. Beyond that fundamental (obvious and trivial) observation, what more are you looking for?
Comment: @MarcClaesen what exactly distance to the separating hyperplane measures? How it can be used if different cases when variables have different levels of measurements?
Comment: Here's an analogy: I can build a spoon out of metal or I can build a fork out of metal. They're both made of metal, but they're shaped differently.
Answer: SVM can output distance to the separating hyperplane, which is not an probability but other metric. It can also ouput class probability via Platts methods.
Basic output from the logistic regression is of course logit, which can be transformed into probability and when used with loss function L(T(c,b)) can be used as a basis for decision. In loss function threshold T is a function of costs and benefits associated with various misclassifications/correct classifications.


Como listar nomes repetidos

Question: Como que faz para listar nome no banco de dados com nomes iguais
por exemplo listar todas pessoas com nomes Pedro.
<code>create database agenda;

create table contatos(
    id int not null auto_increment primary key,
    nome varchar(40),
    idade int,
    dataCadastro date
);
</code>
Comment: Poxa pessoal é sua uma duvida, não precisar colocar -1 no meu post
Comment: Depende, você considera o nome completo? Se tiver "Fulano de Silva" e "Fulano de Souza", o nome (Fulano) é igual, ou só é igual se considerar o nome completo?
Comment: Só um meio para fazer filtragem
Comment: por exemplo Fulano e aparecer todos fulanos
Answer: Você tem que usar o comando SELECT
Ex: SELECT * FROM contatos WHERE nome='Pedro'
Basicamente seria "SELECIONE tudo da tabela CONTATOS ONDE o nome é igual a Pedro"
Você pode encontrar mais em: https://www.w3schools.com/mysql/mysql_select.asp
Mas assim, essa pergunta é extremamente básica, procura dar uma pesquisada sobre o básico de SQL.

Como listar nomes repetidos


How to scroll to a position in Flutter Stepper?

Question: I'm using the vertical type stepper, where I have multiple steps (over 20), I want the step with the isActive property to appear at the beginning, but I can still scroll up to see the previous ones.

Stepper(
                  key: key_1,
                  physics: ClampingScrollPhysics(),
                  onStepTapped: (step) => goTo(step),
                  currentStep: currentStep,
                  controlsBuilder: (BuildContext context,
                      {VoidCallback onStepContinue,
                        VoidCallback onStepCancel}) {
                    return Row(
                      children: <Widget>[
                        Container(
                          child: null,
                        ),
                        Container(
                          child: null,
                        ),
                      ],
                    );
                  },
                  steps: steps)

Example: if step 2 is active, I want it to appear at the beginning and that step 1 when scrolling above can see it, but visually the one that is at the beginning is step 2
enter image description here
Comment: you just need to set current step initially to propper one
Comment: could it be more specific please
Answer: In my case what I did was a modification in the Stepper widget.
Declare the scrollController variable, as follows:
const Stepper({
    Key key,
    @required this.steps,
    this.physics,
    this.scrollController, //Declarate ScrollController
    this.type = StepperType.vertical,
    this.currentStep = 0,
    this.onStepTapped,
    this.onStepContinue,
    this.onStepCancel,
    this.controlsBuilder,
  })  : assert(steps != null),
        assert(type != null),
        assert(currentStep != null),
        assert(0 <= currentStep && currentStep < steps.length),
        super(key: key);
  final ScrollController scrollController;

Once the variable is declared, in the ListView you proceed to add the scrollController as follows:
  Widget _buildVertical() {
    return ListView(
      shrinkWrap: true,
      physics: widget.physics,
      controller: widget.scrollController,//Add ScrollController here
      children: <Widget>[
        for (int i = 0; i < widget.steps.length; i += 1)
          Column(
            key: _keys[i],
            children: <Widget>[
              InkWell(
                onTap: widget.steps[i].state != StepState.disabled
                    ? () {
                        // In the vertical case we need to scroll to the newly tapped
                        // step.
                        Scrollable.ensureVisible(
                          _keys[i].currentContext,
                          curve: Curves.fastOutSlowIn,
                          duration: kThemeAnimationDuration,
                        );

                        if (widget.onStepTapped != null) widget.onStepTapped(i);
                      }
                    : null,
                canRequestFocus: widget.steps[i].state != StepState.disabled,
                child: _buildVerticalHeader(i),
              ),
              _buildVerticalBody(i),
            ],
          ),
      ],
    );
  }

Once that is done, you will have control in the Stepper class, just declare a final variable as scrollController in your document, like this:
final _controller = new ScrollController();

Attach the controller to the Stepper.
When you press onStepContinue, move the animation to the position you want in the controller. I leave you my detailed example below:
import 'package:flutter/material.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';

class MyStepper extends StatefulWidget {
  @override
  _MyStepperState createState() => _MyStepperState();
}

class _MyStepperState extends State<MyStepper> {
  int _currentStape = 0;
  final _controller = new ScrollController();
  @override
  Widget build(BuildContext context) {
    return Material(
      child: Container(
        width: double.infinity,
        height: double.infinity,
        child: Stepper(
          currentStep: _currentStape,
          scrollController: _controller,
          physics: ClampingScrollPhysics(),
          onStepContinue: () {
            _currentStape++;
            _controller.animateTo(
              0,
              duration: Duration(milliseconds: 100),
              curve: Curves.bounceIn,
            );
            setState(() {});
          },
          onStepTapped: (value) {
            _currentStape = value;
          },
          steps: [
            Step(
              title: FaIcon(
                FontAwesomeIcons.dog,
              ),
              subtitle: Text('Ingresa la información de tu mascota'),
              content: Container(
                height: 500,
              ),
            ),
            Step(
              title: FaIcon(
                FontAwesomeIcons.userAlt,
              ),
              subtitle: Text('Ingresa tú información personal'),
              content: Container(
                height: 500,
              ),
            ),
            Step(
              title: FaIcon(
                FontAwesomeIcons.image,
              ),
              subtitle: Text('Agrega algunas imágenes'),
              content: Text('Contenido'),
            ),
          ],
        ),
      ),
    );
  }
}

I'm use Flutter 1.17.3


Convert List to ArrayList>

Question: I want to convert the Android WiFi scan results a List<ScanResults> to a List<? extends Map<String, ?>>
This is for use with the SimpleAdapter which I would like to use
I have tried converting scans to a String[] for each BSSID and SSID then adding them to an ArrayList with a loop, but was unable to do with without overriding each as I went.
Comment: What do you mean by overriding? I think your step is correct. Do a loop for the scan result and assign relevant values as the map key and value.
Answer: I put the scan result into a hash map. Here is what I did.
List<ScanResult> results = wifiMgr.getScanResults();
rssiList = new HashMap<String, Integer>();

for (ScanResult result : results) {
    rssiList.put(result.BSSID, result.level);
}

Hope this helps.
Comment: You can put the HashMap into an ArrayList like [this](http://ykyuen.wordpress.com/2010/01/03/android-simple-listview-using-simpleadapter/).
Comment: Am I able to put this into an `ArrayList` or other type of list I could use with a `SimpleAdapter`?

Convert List to ArrayList>


Remover objeto de um ArrayList

Question: Eu tenho um arraylist de objetos, e preciso remover um objeto dele  da seguinte forma.
Eu preciso que esse objeto seja removido caso o atributo 'box' dele armazenar o mesmo valor que foi digitado no meu TextBox.
Por que eu estou montando um sistema de estacionamento, e quando o cliente faz o checkout e informa sua vaga, o objeto que tiver o valor do numero da vaga dele terá que ser excluído, eu tentei da seguinte forma.
foreach (cadastro cad in listVagas)
{
    if(cad.getBox() == Convert.ToInt32(consulta_box.Text))
    {
        listVagas.Remove(cadOBj);
    }
}

porém ele me da um erro quando eu clico no botão para fazer o checkout, no erro ele aponta para o foreach, o erro é o seguinte

An unhandled exception of type 'System.InvalidOperationException' occurred in mscorlib.dll
  Additional information: Coleção foi modificada; talvez a operação de enumeração não seja executada.

O erro acredito que seja por que eu tenha que informar o índice do objeto no vetor, e eu já procurei no Google porem não achei, como fazer para um objeto que tenha o valor de um atributo específico retornar seu índice.
Alguém teria alguma dica? Sabe alguma outra forma de conseguir remover este objeto? Ou como contornar este erro? Ou como descobrir o índice do objeto que armazene o valor especificado em determinado atributo?
Answer: Você pode tentar acrescentando o ToList
foreach (cadastro cad in listVagas.ToList())
        {
            if(cad.getBox() == Convert.ToInt32(consulta_box.Text))
            {
                listVagas.Remove(cadOBj);
            }
        }

POR QUE FUNCIONA
Simplesmente o ToList irá criar uma nova lista (em cache) e não sofrerá alterações subsequentes na coleção (a list original foi alterada).
Se por algum acaso, durante o foreach, for necessário tratar ocasionalmente um novo add ou mesmo o remove, a nova lista não reconhecerá essas alterações.
DOCUMENTAÇÃO MSDN
O método ToList <TSource> (IEnumerable <TSource>) força a avaliação de consulta imediata e retorna uma Lista <T> que contém os resultados da consulta. Você pode anexar este método à sua consulta para obter uma cópia em cache dos resultados da consulta.
Answer: O erro ocorre porque a coleção listVagas foi alterada durante o foreach. Crie uma coleção temporária e adicione nela os objetos que você deseja:
var listaTemp = new List<seuObjeto>();

foreach(var objeto in listaReal){
   if(!suaCondicao)
     listaTemp.add(objeto);
}

Outra solução é usar um for
for(var i = listaReal.Count - 1; i>=0 ;i--){
  if(suaCondicao)
    listaReal.RemoveAt(i);
}

Answer: Voce pode utilizar uma expressão lambda
int idConsulta = Convert.ToInt32(consulta_box.Text);
listVagas = listVagas.Where(x=>x.getBox() != idConsulta).ToList();

Comment: Isso funciona com `ArrayList`?
Comment: Para fazer utilizando arrayList seria necessário primeiro converter o O ArrayList em um Array e depois em uma lista. Não seria muito performatico, eu não havia reparado que voce estava utilizando ArrayList. Como o bigown comentou na sua pergunta, seria interessante trabalhar direto com uma List, visto que o ArrayList está obsoleto...
Comment: A pergunta não é minha, só pra constar.
Answer: Você pode tentar utilizar um for iterando da última posição para a primeira.
for(int i = listVagas.Count-1;i >=0; i--)
{
 if(listVagas[i].getBox() == Convert.ToInt32(consulta_box.Text))
    {
        listVagas.RemoveAt(i);
    }
}

Remover objeto de um ArrayList


IP Tables Port Forwarding

Question: I have 4 servers behind a load balancer, but only 1 of them is running a particular service. I want three of them to forward requests to the fourth, based on the port. So, at present all 4 are running nginx on port 80, but only one is running the required service on port 7070.
All 4 are amazon EC2 instances running CentOS 5, behind an amazon elastic load balancer. I've setup the load balancer to forward port 7070 through to all the machines. I need server 1,2 and 3 to forward requests to port 7070 through to port 7070 on server 4 (which is running the service).
I did try a few existing question/answers here on sf, but for whatever reason i instantly lost connectivity to my servers and had to reboot; seeing as theses servers are running live services, I was suddenly nervous about trying a hit and miss approach!
So just to be clear, servers 1, 2 and 3 do not run anything on port 7070, but server 4 does. None of them are running any other type of port forwarding, so IP Tables isn't setup at all at present.
Thanks.
Comment: Elastic load balancers can't forward to specific servers for specific ports - they can just forward a port to all servers beneath the balancer.
Comment: Also, it is balancing on port 80. mydomain.com is pointed at the balancer, which distributes requests to all four servers. Therefore mydomain.com:7070 has to go through the balancer, even though only one of the servers is running the service...
Answer: In terms of why this didn't work for you based on the previous instructions, I'm guessing iptables blocked everything by default.  If you followed an existing set of instructions from this site (say, this one), they probably didn't also include instructions for making sure the ports you need are also opened.  You'll want 22 for SSH, 80 for your web server, and possibly others.
Reasonable guide: https://help.ubuntu.com/community/IptablesHowTo
Note this command which will ensure established sessions (e.g. your current SSH session) will continue to work even if you block yourself:
sudo iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT

Since you are using EC2, I'd recommend booting up a 5th instance outside of your load balanced, production set, for testing.  Sometimes setting up dev/production splits is hard or expensive, but not with EC2. The six cents will be well worth if it you break something.
Note that rebooting wiped your test rules out; once you have something set up that you tested and approve of, be sure to use iptables-save.
Comment: Mike - I think you're right re the blocking. Is there a way to allow everything by default? as you know, EC2 firewall is managed externally in the AWS interface anyway, so opening everything up isn't really an issue...
Comment: Assuming you trust the EC2 security groups implementation... there's no evidence you shouldn't of course, and if you are new to iptables I'd trust them more than I'd trust you. :)  `iptables -P OUTPUT ACCEPT` and `iptables -P INPUT ACCEPT` accept all input / output (-P is the flag to set the default).  Run your port forwarding iptables command, then `iptables -L -v` to make sure everything is working.  Then `iptables-save`.

IP Tables Port Forwarding


How to load multiple documents based on ids?

Question: I'm trying to load a set of ids from mongodb in C# to a list. Can anyone help to suggest any collection or filter method of mongodb? I'm very new to this
Comment: Please edit the question to limit it to a specific problem with enough detail to identify an adequate answer.
Answer: In addition to the answer of @Llama, you can also use Expression to achieve the same result.
var documentIds = GetDocumentIds();
var documents = await mongoContext
    .GetCollection<MyModel>("collectionName")
    .Find(model => documentIds.Contains(model.Id))
    .ToListAsync();

You can also use the Linq extensions from MongoDB.Driver.Linq namespace.
var documents = await mongoContext
    .GetCollection<MyModel>("collectionName")
    .AsQueryable()
    .Where(model => documentIds.Contains(model.Id))
    .ToListAsync()

Answer: Assuming you have a model something like this:
public class MyModel
{
    [BsonId]
    public ObjectId Id {get;set;}
}

You can use In:
List<ObjectId> documentsToLoad = getDocumentsToLoad();

List<MyModel> documents = await myCollection
    .Find(
        Builders<MyModel>.Filter.In(m => m.Id, documentsToLoad)
    )
    .ToListAsync();

Alternatively, if you're just getting the "raw" BsonDocument objects you can write:
List<BsonDocument> documents = await myCollection
    .Find(
        Builders<BsonDocment>.Filter.In("_id", documentsToLoad)
    )
    .ToListAsync();

Comment: I assume your answer will run more efficiently than Alexandra's above? I feel as if your answer will be faster since it uses Mongo's Filter.In syntax rather than the standard C# .Contains
Comment: @walnut_salami I'm not 100% certain here, but I think they might be translated to effectively the same thing. I'm not sure about the efficiency of doing that conversion though.


Backwards Euler Matlab

Question: I am asked to code Backwards Euler for the given differential:
dy/dt = sin(3*t)-2*y , y0=1.2 ,x = [0 8]
I know that Euler Forward is:
y= y+h*(sin(3*t)-2*y)
and the general formula for Backwards Euler is:
y = y_i + h*y_i+1
I saw that for Backwards Euler,
y_i+1 = y_i / (1 + h)
so should my function be:
y_i+1 = sin(3*t)/(1+h)
y = y + h *sin(3*t)/(1+h)
Is this correct?
Thank you!
Answer: BE has the following numerical scheme: $y_{n+1}=y_n+h\cdot f(t_{n+1},y_{n+1})$.
Just consider $f(t,y)=\sin(3t)-2y$.
You'll get: $y_{n+1}(1+2h)=y_n+h\cdot \sin(3t_{n+1})$, and then
$y_{n+1}=\frac{y_n+h\cdot \sin(3t_{n+1})}{(1+2h)}$, where $y_0=1.2$.
$h$ is given by $h=\frac{N}{8}$, where $N$ is the number of discretization points
Note that this is a linear ODE, and then you can collect together the $y_{n+1}$-term. Otherwise, you should solve at each time-step a non-linear equation which defines implicitely $y_{n+1}$.
Anyway, your code will be just a for loop for $n$ which ranges from $1$ no $N$ and you can compute each $y_n$ with the expression above.
EDIT
As I wrote in the second(!) line, you have just to write the current expression for $f$ as a function of $t_{n+1},y_{n+1}$.
$y_{n+1}=y_n+h \cdot (\sin(3t_{n+1})-2y_{n+1})$
$y_{n+1}=y_n+h \cdot \sin(3t_{n+1})-2h \cdot y_{n+1})$
Now we need to write $y_{n+1}$ as a function of $y_n$, so we can compute explicitely at each time step $y_n$. So, we collect $y_{n+1}$.
$y_{n+1}+2 h \cdot y_{n+1}=y_n+h \cdot \sin(3t_{n+1})$
$y_{n+1}(1+2h)=y_n+h \cdot \sin(3t_{n+1})$
and hence, by dividing:
$y_{n+1}=\frac{y_n+h \cdot \sin(3t_{n+1})}{(1+2h)}$
Comment: Oh I got it now. Thank you very much for your help!  :)
Comment: How did you get $y_{n+1}(1+2h)=y_n + h*sin(3t_{n+1})$?
Comment: See my last edit
Comment: there's nothing to invent... I jus used the definition of the rhs given by the problem. Look at the edit

Backwards Euler Matlab


Graph Terminology: What is an ancestral path?

Question: Shortest ancestral path: An ancestral path between two vertices v and w in a digraph is a directed path from v to a common ancestor x, together with a directed path from w to the same ancestor x. A shortest ancestral path is an ancestral path of minimum total length. We refer to the common ancestor in a shortest ancestral path as a shortest common ancestor. Note also that an ancestral path is a path, but not a directed path.

I am quite confused by this description for two reasons.
First, what does the sentence - "An ancestral path between two vertices v and w in a digraph is a directed path from v to a common ancestor x, together with a directed path from w to the same ancestor x" - mean because there is no directed path from v to w since the path to the ancestor from v is in the "opposite direction" of the path to the ancestor from w. What I mean is in the picture to the left, it's claimed that the shortest ancestral path is 3-1-5-9-10 but this doesn't make sense because we can't do 1-5 since that direction doesn't exist. It seems that they combined the directed path from v to the ancestor with the directed path from w to the ancestor in the opposite direction, essentially treating the path as undirected.
Second, and relatedly, the first sentence says that an ancestral path is a "directed path" but the last sentence says "Note also that an ancestral path is a path, but not a directed path."
Can someone clarify?
Answer: The sentence

An ancestral path between two vertices $v$ and $w$ in a digraph is a directed path from $v$ to a common ancestor $x$, together with a directed path from $w$ to the same ancestor $x$.

is not saying that an ancestral path is a directed path. It's saying that an ancestral path is made up of two pieces. One piece is a directed path from $v$ to $x$. The other piece is a directed path from $w$ to $x$.
If we ignore the orientations, and allow our paths to backtrack, then we can combine the first directed path with the reverse of the second, and get an undirected path. This is what the sentence

Note also that an ancestral path is a path, but not a directed path.

is saying.
Not everyone's definitions allow a path to repeat edges (or vertices), but maybe the source you're consulting does. In any case, when we take a shortest ancestral path, there will be no repetition, so this will be a path (undirected path) by anyone's definition.
Comment: Thank you so very much!


Can the mean be a random variable?

Question: Can the mean of some sample of random variables be itself a random variable?
Yes?

I think the particular confusion here is that since the calculation procedure for statistics is known, then they do not seem like "random draws". But they can take r.v.s as input and thus could be r.v.s. in the sense of being linear combinations of r.v.s, for example.
Comment: The situation in your question is not sufficiently clear. For example, if you're talking about *sample means* they can certainly be random variables. If you're talking about the population mean for a given random variable, then that's a fixed number (while it could be regarded as a degenerate random variable, it would be unusual to do so with a population parameter). Please clarify the circumstances in your question.
Comment: This is called conditional probability: the mean of $X$ may be $Y$ conditional on $Y$ and $Y$ still be a random variable.
Comment: But the mean is also (at least in some cases) the expected value.
Comment: I'm asking for "mean" in general. Which would ask for an answer considering also means that cannot be r.v.s.
Answer: The mean of a collection of random variables is itself a random variable.
So if you have say, $X_1,X_2,X_3,...,X_n$, then $\bar{X}=\frac{1}{n}(X_1+X_2+X_3+...+X_n)$ is a random variable.
If you're talking about a sample of particular observations, $x_1, x_2, ..., x_n$, then you could look at the sample mean, $\bar{x}$ as another kind of observation, relating to the random variable $\bar{X}$ in the same way that the observation $x_1$ relates to the random variable $X_1$, which is to say it's a realization of the random variable $\bar{X}$.
[On the other hand, when we're talking about the mean of the distribution of a random variable, that is a parameter; it's not a variable $-$ at least not in a frequentist framework; it may be treated as one in a Bayesian framework, in which case it can be taken to represent the uncertainty in our belief/knowledge about its value.]
Answer: It's expected value of the random variable. Random variable itself is a function from sample space to real number. If some how one can define this function in a random way one may get random expected values. Given E(X) exist.
Comment: The mean of a sample is *not* the expected value of the variable.  Perhaps you have misinterpreted the question?
Comment: Sorry, your answer sounds a bit vague to me. Can you show by means of an example?

Can the mean be a random variable?


Kaplan Meier curve with different time lengths across groups

Question: I'm not too familiar with survival analysis, so this may be a somewhat basic question.
I am interested in the time between two events [$A$ - medication] and [$B$ - time of first treatment], the latter which can be equal to $A$. Specifically, I want to know if this varies across years.
The subjects in question have at least 5 years of data, and I have data from 2001-2011. Because of this, tests on summary statistics won't do (subjects in 2011 have the capacity to have up to 11 years while subjects in 2006 only have the capacity to have 6).
So instead, I'm considering the value $A-B$ to be censored if $B$ falls within one year of the subject entering the dataset, and then constructing a KM curve. However, the time length covered by each group will still end up different, like so:

By visual inspection, the survival curves are different, though only the 2011 vs any other group comparisons are significant by the logrank test.
Alternatively, I can truncate time differences greater than 5 years (considering them censored):

This results in the exact same curve for years <= 5 as expected, however, the logrank test returns more significant differences (2010 vs any other group).
I'm not sure which of these setups is more appropriate.
Comment: You can't group subjects based on the timing of a future event. You have to do a forward-looking analysis. The fact that a subject could have gotten medication in 2005 but did not, and finally got it in 2011 is relevant to 2005 as well as 2011 (and all the years in between). You have a time-dependent predictor. It is difficult to make plots for it, but SAS can handle the analysis in PROC PHREG.
Comment: You are grouping by year - is it the year of the first treatment? How come later years have more follow-up? You have to be _very_ careful in combining time to event data with calendar year data, because it can get tricky fast.
Comment: @Aniko It's the year of A (medication of interest), so it's the later years have the possibility of a longer time difference. And yes, I'm wary of the calendar year division, though I'm not sure how else to proceed given that the question of interest is "Has A-B changed over time"
Comment: @Aniko That makes sense. Someone "failing" in a 2011 group is also a censored event for 2010 (though I'm not exactly sure how to set this up, again, not very familiar with survival). However, it seems a forward-looking analysis would answer a different question than we really want - among those that start taking drug B, how long did they wait; versus how long does it take for subjects to reach drug B
Comment: If you are conditioning on having received the medication, then where does the censoring come from? Perhaps you don't know the time of first treatment for some subjects?
Comment: @Aniko Yes, that is correct. We're considering the first treatment censored if it falls within 1Y of the subject entering the dataset (these are prescription claims). In addition, due to data limits (2001-2011 data), later subjects can have a difference of up to 11 years, while earlier patients cap out.
Comment: After all these clarifications, I would second Rob Hall's statement that you should have equal censoring patterns in the groups. Except I would censor at 4 years, because the 2006 group cannot have a longer observed outcome. Though there are some methods to try to deal with unequal censoring, it is probably not worthwhile in your case.
Answer: The censoring process needs to be independent of the survival process. I would advocate the second method of censoring at 5 years, as this ensures that the censoring time is independent of the survival process and any relevant covariates.
Also note that time A and time B may be influenced by the same covariates (e.g. disease severity, but also year due to treatment protocol changes), so using B-A as the time of interest may be problematic. A classic example of this problem is the change in breast cancer mortality due to earlier detection.
Answer: First off, I would switch to time at risk instead of calendar time approach: that is, the time horizon of your analysis should start when patient starts to be at risk for the event you're investigating. This makes sense in that, in empirical study, time for patients enrollment can lasts two or more years, but calendar year is meaningless and survival analysis starts when patients becomes at t0. As a sidelight, time when patient enters the study may differ from time at risk (let's assume that, to be considered (or not) at risk, patient enters the study and undergoes a lab routine to assess her/his risk factors for the disease under investigation. If all the lab tests are negative for those risk factors, patient is not at risk).
As a second remark, your research approach (KM curve) is a non-parametric one. Therefore, it "lets data speak for themselves", but doesn't allow you to consider risk predictors on the right hand side of the equation (as some other previous replies pointed out). If you suspect that time can impact on the risk of the event you're interested in, you may want to test this assumption via a parametric model for survival analysis, such as Weibull regression.