问:
JAXB Provide Empty XML Element as <xmlelement/> And Remove Namespace Name
I am writing a utility to integrate between an internal system and a third party product.  I am trying to produce an xml file that can be loaded by the third party product but I am having trouble getting the xml to be produced exactly as they require it to be.  I have created a simplified version just for testing.

The expected output should be as follows:

```<code><?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Programme xmlns="http://www.awebsite.co.uk/ns/">
    <Editorial>
        <SeriesTitle>Series 1</SeriesTitle>
        <ProgrammeTitle>Test Programme</ProgrammeTitle>
        <EpisodeTitleNumber>Episode 1</EpisodeTitleNumber>
        <ProductionNumber/>
        <Synopsis/>
        <Originator/>
        <CopyrightYear/>
    </Editorial>
    <Technical>
        <ShimName/>
        <ShimVersion>1.0</ShimVersion>
        <ContactInformation>
            <ContactEmail/>
            <ContactTelephoneNumber/>
        </ContactInformation>
    </Technical>
</Programme>
</code>```

The output that I am getting is as follows:

```<code><?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ns2:Programme xmlns:ns2="http://www.awebsite.co.uk/ns/">
    <Editorial>
        <SeriesTitle>Series 1</SeriesTitle>
        <ProgrammeTitle>Test Programme</ProgrammeTitle>
        <EpisodeTitleNumber>Episode 1</EpisodeTitleNumber>
        <ProductionNumber xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true"/>
        <Synopsis xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true"/>
        <Originator xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true"/>
        <CopyrightYear xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true"/>
    </Editorial>
    <Technical>
        <ShimName xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true"/>
        <ShimVersion>1.0</ShimVersion>
        <ContactInformation>
            <ContactEmail xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true"/>
            <ContactTelephoneNumber xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true"/>
        </ContactInformation>
    </Technical>
</ns2:Programme>
</code>```

The 2 areas that I can't get right is the namespace having a value assigned to it and the null tags being self closing without the addition of:  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true".  I have tried empty tags but they get rejected as invalid xml.

My code is as follows:

Main:

```<code>public class TestXMLBuilder {

    public static void main (String ... args) {
        File file = new File("myxmltest.xml");
        JAXBContext jaxbContext;

        Editorial editorial = new Editorial();
        editorial.setProgrammeTitle("Test Programme");
        editorial.setEpisodeTitleNumber("Episode 1");
        editorial.setSeriesTitle("Series 1");
        Programme programme = new Programme();
        programme.setEditorial(editorial);

        try {
            jaxbContext = JAXBContext.newInstance(Programme.class);
            Marshaller marshaller = jaxbContext.createMarshaller();
            // output pretty printed
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

            marshaller.marshal(programme, file);
            marshaller.marshal(programme, System.out);
        } catch (JAXBException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
}
</code>```

Programme Class:

```<code>import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "Programme", namespace = "http://www.awebsite.co.uk/ns/")
@XmlAccessorType(XmlAccessType.FIELD)
public class Programme {

    @XmlElement(name = "Editorial", required = true)
    private Editorial editorial = new Editorial();

    @XmlElement(name = "Technical", required = true)
    private Technical technical = new Technical();

    /**
     * @return the editorial
     */
    public Editorial getEditorial() {
        return editorial;
    }

    /**
     * @param editorial the editorial to set
     */
    public void setEditorial(Editorial editorial) {
        this.editorial = editorial;
    }

    /**
     * @return the technical
     */
    public Technical getTechnical() {
        return technical;
    }

    /**
     * @param technical the technical to set
     */
    public void setTechnical(Technical technical) {
        this.technical = technical;
    }

}
</code>```

Editorial Class:

```<code>import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "Editorial")
@XmlAccessorType(XmlAccessType.FIELD)
public class Editorial {

    @XmlElement(name = "SeriesTitle", required = true, nillable = true)
    private String seriesTitle = null;

    @XmlElement(name = "ProgrammeTitle", required = true, nillable = true)
    private String programmeTitle = null;

    @XmlElement(name = "EpisodeTitleNumber", required = true, nillable = true)
    private String episodeTitleNumber = null;

    @XmlElement(name = "ProductionNumber", required = true, nillable = true)
    private String productionNumber = null;

    @XmlElement(name = "Synopsis", required = true, nillable = true)
    private String synopsis = null;

    @XmlElement(name = "Originator", required = true, nillable = true)
    private String originator = null;

    @XmlElement(name = "CopyrightYear", required = true, nillable = true)
    private String copyrightYear = null;

    /**
     * @return the seriesTitle
     */
    public String getSeriesTitle() {
        return seriesTitle;
    }

    /**
     * @param seriesTitle the seriesTitle to set
     */
    public void setSeriesTitle(String seriesTitle) {
        this.seriesTitle = seriesTitle;
    }

    /**
     * @return the programmeTitle
     */
    public String getProgrammeTitle() {
        return programmeTitle;
    }

    /**
     * @param programmeTitle the programmeTitle to set
     */
    public void setProgrammeTitle(String programmeTitle) {
        this.programmeTitle = programmeTitle;
    }

    /**
     * @return the episodeTitleNumber
     */
    public String getEpisodeTitleNumber() {
        return episodeTitleNumber;
    }

    /**
     * @param episodeTitleNumber the episodeTitleNumber to set
     */
    public void setEpisodeTitleNumber(String episodeTitleNumber) {
        this.episodeTitleNumber = episodeTitleNumber;
    }

    /**
     * @return the productionNumber
     */
    public String getProductionNumber() {
        return productionNumber;
    }

    /**
     * @param productionNumber the productionNumber to set
     */
    public void setProductionNumber(String productionNumber) {
        this.productionNumber = productionNumber;
    }

    /**
     * @return the synopsis
     */
    public String getSynopsis() {
        return synopsis;
    }

    /**
     * @param synopsis the synopsis to set
     */
    public void setSynopsis(String synopsis) {
        this.synopsis = synopsis;
    }

    /**
     * @return the originator
     */
    public String getOriginator() {
        return originator;
    }

    /**
     * @param originator the originator to set
     */
    public void setOriginator(String originator) {
        this.originator = originator;
    }

    /**
     * @return the copyrightYear
     */
    public String getCopyrightYear() {
        return copyrightYear;
    }

    /**
     * @param copyrightYear the copyrightYear to set
     */
    public void setCopyrightYear(String copyrightYear) {
        this.copyrightYear = copyrightYear;
    }

}
</code>```

Technical Class:

```<code>import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "Technical")
@XmlAccessorType(XmlAccessType.FIELD)
public class Technical {

    @XmlElement(name = "ShimName", required = true, nillable = true)
    private String shimName = null;

    @XmlElement(name = "ShimVersion", required = true, nillable = true)
    private String shimVersion = "1.0";

    @XmlElement(name = "ContactInformation", required = true, nillable = true)
    private ContactInformation contactInformation = new ContactInformation();

}
</code>```

ContactInformation Class:

```<code>import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "ContactInformation")
@XmlAccessorType(XmlAccessType.FIELD)
public class ContactInformation {

    @XmlElement(name = "ContactEmail", required = true, nillable = true)
    private String contactEmail = null;

    @XmlElement(name = "ContactTelephoneNumber", required = true, nillable = true)
    private String contactTelephoneNumber = null;

    /**
     * @return the contactEmail
     */
    public String getContactEmail() {
        return contactEmail;
    }

    /**
     * @param contactEmail the contactEmail to set
     */
    public void setContactEmail(String contactEmail) {
        this.contactEmail = contactEmail;
    }

    /**
     * @return the contactTelephoneNumber
     */
    public String getContactTelephoneNumber() {
        return contactTelephoneNumber;
    }

    /**
     * @param contactTelephoneNumber the contactTelephoneNumber to set
     */
    public void setContactTelephoneNumber(String contactTelephoneNumber) {
        this.contactTelephoneNumber = contactTelephoneNumber;
    }

}
</code>```

答:
Unfortunately, I ended up having to manipulate(hack) the xml as follows: </p>

```<code>        StringWriter stringWriter = new StringWriter();
        marshaller.marshal(programme, stringWriter);

        String xmlContent = stringWriter.toString();
        xmlContent = xmlContent.replaceAll("xsi:nil=\"true\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"", "");
        xmlContent = xmlContent.replaceAll("</ns2:", "</");
        xmlContent = xmlContent.replaceAll(":ns2=", "=");
        xmlContent = xmlContent.replaceAll("<ns2:", "<");

        result = xmlContent;
</code>```

Body:
I am writing a utility to integrate between an internal system and a third party product.  I am trying to produce an xml file that can be loaded by the third party product but I am having trouble getting the xml to be produced exactly as they require it to be.  I have created a simplified version just for testing.

The expected output should be as follows:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Programme xmlns="http://www.awebsite.co.uk/ns/">
    <Editorial>
        <SeriesTitle>Series 1</SeriesTitle>
        <ProgrammeTitle>Test Programme</ProgrammeTitle>
        <EpisodeTitleNumber>Episode 1</EpisodeTitleNumber>
        <ProductionNumber/>
        <Synopsis/>
        <Originator/>
        <CopyrightYear/>
    </Editorial>
    <Technical>
        <ShimName/>
        <ShimVersion>1.0</ShimVersion>
        <ContactInformation>
            <ContactEmail/>
            <ContactTelephoneNumber/>
        </ContactInformation>
    </Technical>
</Programme>

The output that I am getting is as follows:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ns2:Programme xmlns:ns2="http://www.awebsite.co.uk/ns/">
    <Editorial>
        <SeriesTitle>Series 1</SeriesTitle>
        <ProgrammeTitle>Test Programme</ProgrammeTitle>
        <EpisodeTitleNumber>Episode 1</EpisodeTitleNumber>
        <ProductionNumber xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true"/>
        <Synopsis xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true"/>
        <Originator xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true"/>
        <CopyrightYear xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true"/>
    </Editorial>
    <Technical>
        <ShimName xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true"/>
        <ShimVersion>1.0</ShimVersion>
        <ContactInformation>
            <ContactEmail xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true"/>
            <ContactTelephoneNumber xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true"/>
        </ContactInformation>
    </Technical>
</ns2:Programme>

The 2 areas that I can't get right is the namespace having a value assigned to it and the null tags being self closing without the addition of:  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true".  I have tried empty tags but they get rejected as invalid xml.

My code is as follows:

Main:

public class TestXMLBuilder {

    public static void main (String ... args) {
        File file = new File("myxmltest.xml");
        JAXBContext jaxbContext;

        Editorial editorial = new Editorial();
        editorial.setProgrammeTitle("Test Programme");
        editorial.setEpisodeTitleNumber("Episode 1");
        editorial.setSeriesTitle("Series 1");
        Programme programme = new Programme();
        programme.setEditorial(editorial);

        try {
            jaxbContext = JAXBContext.newInstance(Programme.class);
            Marshaller marshaller = jaxbContext.createMarshaller();
            // output pretty printed
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

            marshaller.marshal(programme, file);
            marshaller.marshal(programme, System.out);
        } catch (JAXBException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
}

Programme Class:

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "Programme", namespace = "http://www.awebsite.co.uk/ns/")
@XmlAccessorType(XmlAccessType.FIELD)
public class Programme {

    @XmlElement(name = "Editorial", required = true)
    private Editorial editorial = new Editorial();

    @XmlElement(name = "Technical", required = true)
    private Technical technical = new Technical();

    /**
     * @return the editorial
     */
    public Editorial getEditorial() {
        return editorial;
    }

    /**
     * @param editorial the editorial to set
     */
    public void setEditorial(Editorial editorial) {
        this.editorial = editorial;
    }

    /**
     * @return the technical
     */
    public Technical getTechnical() {
        return technical;
    }

    /**
     * @param technical the technical to set
     */
    public void setTechnical(Technical technical) {
        this.technical = technical;
    }

}

Editorial Class:

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "Editorial")
@XmlAccessorType(XmlAccessType.FIELD)
public class Editorial {

    @XmlElement(name = "SeriesTitle", required = true, nillable = true)
    private String seriesTitle = null;

    @XmlElement(name = "ProgrammeTitle", required = true, nillable = true)
    private String programmeTitle = null;

    @XmlElement(name = "EpisodeTitleNumber", required = true, nillable = true)
    private String episodeTitleNumber = null;

    @XmlElement(name = "ProductionNumber", required = true, nillable = true)
    private String productionNumber = null;

    @XmlElement(name = "Synopsis", required = true, nillable = true)
    private String synopsis = null;

    @XmlElement(name = "Originator", required = true, nillable = true)
    private String originator = null;

    @XmlElement(name = "CopyrightYear", required = true, nillable = true)
    private String copyrightYear = null;

    /**
     * @return the seriesTitle
     */
    public String getSeriesTitle() {
        return seriesTitle;
    }

    /**
     * @param seriesTitle the seriesTitle to set
     */
    public void setSeriesTitle(String seriesTitle) {
        this.seriesTitle = seriesTitle;
    }

    /**
     * @return the programmeTitle
     */
    public String getProgrammeTitle() {
        return programmeTitle;
    }

    /**
     * @param programmeTitle the programmeTitle to set
     */
    public void setProgrammeTitle(String programmeTitle) {
        this.programmeTitle = programmeTitle;
    }

    /**
     * @return the episodeTitleNumber
     */
    public String getEpisodeTitleNumber() {
        return episodeTitleNumber;
    }

    /**
     * @param episodeTitleNumber the episodeTitleNumber to set
     */
    public void setEpisodeTitleNumber(String episodeTitleNumber) {
        this.episodeTitleNumber = episodeTitleNumber;
    }

    /**
     * @return the productionNumber
     */
    public String getProductionNumber() {
        return productionNumber;
    }

    /**
     * @param productionNumber the productionNumber to set
     */
    public void setProductionNumber(String productionNumber) {
        this.productionNumber = productionNumber;
    }

    /**
     * @return the synopsis
     */
    public String getSynopsis() {
        return synopsis;
    }

    /**
     * @param synopsis the synopsis to set
     */
    public void setSynopsis(String synopsis) {
        this.synopsis = synopsis;
    }

    /**
     * @return the originator
     */
    public String getOriginator() {
        return originator;
    }

    /**
     * @param originator the originator to set
     */
    public void setOriginator(String originator) {
        this.originator = originator;
    }

    /**
     * @return the copyrightYear
     */
    public String getCopyrightYear() {
        return copyrightYear;
    }

    /**
     * @param copyrightYear the copyrightYear to set
     */
    public void setCopyrightYear(String copyrightYear) {
        this.copyrightYear = copyrightYear;
    }

}

Technical Class:

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "Technical")
@XmlAccessorType(XmlAccessType.FIELD)
public class Technical {

    @XmlElement(name = "ShimName", required = true, nillable = true)
    private String shimName = null;

    @XmlElement(name = "ShimVersion", required = true, nillable = true)
    private String shimVersion = "1.0";

    @XmlElement(name = "ContactInformation", required = true, nillable = true)
    private ContactInformation contactInformation = new ContactInformation();

}

ContactInformation Class:

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "ContactInformation")
@XmlAccessorType(XmlAccessType.FIELD)
public class ContactInformation {

    @XmlElement(name = "ContactEmail", required = true, nillable = true)
    private String contactEmail = null;

    @XmlElement(name = "ContactTelephoneNumber", required = true, nillable = true)
    private String contactTelephoneNumber = null;

    /**
     * @return the contactEmail
     */
    public String getContactEmail() {
        return contactEmail;
    }

    /**
     * @param contactEmail the contactEmail to set
     */
    public void setContactEmail(String contactEmail) {
        this.contactEmail = contactEmail;
    }

    /**
     * @return the contactTelephoneNumber
     */
    public String getContactTelephoneNumber() {
        return contactTelephoneNumber;
    }

    /**
     * @param contactTelephoneNumber the contactTelephoneNumber to set
     */
    public void setContactTelephoneNumber(String contactTelephoneNumber) {
        this.contactTelephoneNumber = contactTelephoneNumber;
    }

}

Body:
Unfortunately, I ended up having to manipulate(hack) the xml as follows:

        StringWriter stringWriter = new StringWriter();
        marshaller.marshal(programme, stringWriter);

        String xmlContent = stringWriter.toString();
        xmlContent = xmlContent.replaceAll("xsi:nil=\"true\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"", "");
        xmlContent = xmlContent.replaceAll("</ns2:", "</");
        xmlContent = xmlContent.replaceAll(":ns2=", "=");
        xmlContent = xmlContent.replaceAll("<ns2:", "<");

        result = xmlContent;


来源: stackexchange

问:
ASM: MethodVisitor's methods are not called by the ClassReader
I am writing a small tool to perform static analysis of bytecode using ASM 5. I give my input Java class to a ClassReader which triggers events of a custom ClassVisitor. My ClassVisitor overrides visitMethod to return my custom MethodVisitor if certain conditions are met, and null if they are not.

The problem is, the ClassReader never invokes the MethodVisitor's methods; I debugged it with NetBeans and i saw that the visitor is correctly returned (it is not null) but still the execution never enters the visitMethodInsn even though there are method instruction in the classes I'm using for testing.

I have used ASM before, but this is the first time i encounter this problem.

Here is my code for MyClassVisitor.visitMethod:

```<code>@Override
public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) {
    InvokeFinder visitor;
    if(condition.isMet()) {
        visitor = new InvokeFinder(api);
        visitor.doStuff();
    } else {
        visitor = null;
    }
    return visitor;
}
</code>```

Here the code of InvokeFinder, which is never entered during execution:

```<code>public class InvokeFinder extends MethodVisitor {

    public InvokeFinder(int api) {
        super(api);
    }

    void unrelatedMethod(String parameter) {
        doStuff(parameter);
    }

    @Override
    public void visitMethodInsn(int opcode, String owner, String name, String desc) {
        switch (opcode) {
            case Opcodes.INVOKEVIRTUAL:
            case Opcodes.INVOKESPECIAL:
            case Opcodes.INVOKEDYNAMIC:
                doSomething();
                break;
            case Opcodes.INVOKEINTERFACE:
                doSomethingElse();
                break;
            case Opcodes.INVOKESTATIC:
                doSomethingDifferentAgain();
                break;
            default: break;
        }
    }
}
</code>```

And finally this is the class I'm testing on (this is not meant to be ever executed, its sole purpose is to be compiled and then analyzed by my tool):

```<code>public class MyTestClass{

  public MyTestClass(String s) {
    System.out.println( "Function Name" );
  }

  public static void main(String args[]) {
    CGraph g = new CGraph("entry");

    g.enterBF(new CGVisitor() {
        @Override
        public void nodeOperations(CGraph graph, CGraphNode currentNode) {
            System.out.println("20");
        }

        @Override
        public String getString() {
            throw new UnsupportedOperationException("No string can be returned from this anonymous implementation of CGVisitor.");
        }
    });

    a( 11 );
  }

  public static void a(int n) {
    b( n );
  }

  public static void b(int m) {
    int n;

    if (m >= 10)
      a( m-1 );
    else
      System.out.println(m);
  }
}
</code>```

I double checked that the visitMethod method above is always executed, returns a non-null instance of InvokeFinderand that this instance never happens to be executed; how is it possible that under these conditions InvokeFinder.visitMethodInsn is never called by the ClassReader, even if there are invocation instruction in some methods of MyTestClass (e.g. inside method a(int))?

EDIT: Going further with the debugging, i found out that ClassReader calls the default MethodVisitor.visitMethodInsn instead of calling the overridden version InvokeFinder.visitMethodInsn. Why does this happen?

答:
Turned out that i changed API version of ASM and the signature of MethodVisitor.visitMethodInsn is different between versions 4 and 5. The dynamic binding no longer recognized it as an overriding method.

I could fix this by adding the missing parameters to InvokeFinder.visitMethodInsn, whose signature now is

```<code>public void visitMethodInsn(int opcode, String owner, String name, String desc, boolean itf)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am writing a small tool to perform static analysis of bytecode using ASM 5. I give my input Java class to a ClassReader which triggers events of a custom ClassVisitor. My ClassVisitor overrides visitMethod to return my custom MethodVisitor if certain conditions are met, and null if they are not.

The problem is, the ClassReader never invokes the MethodVisitor's methods; I debugged it with NetBeans and i saw that the visitor is correctly returned (it is not null) but still the execution never enters the visitMethodInsn even though there are method instruction in the classes I'm using for testing.

I have used ASM before, but this is the first time i encounter this problem.

Here is my code for MyClassVisitor.visitMethod:

@Override
public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) {
    InvokeFinder visitor;
    if(condition.isMet()) {
        visitor = new InvokeFinder(api);
        visitor.doStuff();
    } else {
        visitor = null;
    }
    return visitor;
}

Here the code of InvokeFinder, which is never entered during execution:

public class InvokeFinder extends MethodVisitor {

    public InvokeFinder(int api) {
        super(api);
    }

    void unrelatedMethod(String parameter) {
        doStuff(parameter);
    }

    @Override
    public void visitMethodInsn(int opcode, String owner, String name, String desc) {
        switch (opcode) {
            case Opcodes.INVOKEVIRTUAL:
            case Opcodes.INVOKESPECIAL:
            case Opcodes.INVOKEDYNAMIC:
                doSomething();
                break;
            case Opcodes.INVOKEINTERFACE:
                doSomethingElse();
                break;
            case Opcodes.INVOKESTATIC:
                doSomethingDifferentAgain();
                break;
            default: break;
        }
    }
}

And finally this is the class I'm testing on (this is not meant to be ever executed, its sole purpose is to be compiled and then analyzed by my tool):

public class MyTestClass{

  public MyTestClass(String s) {
    System.out.println( "Function Name" );
  }

  public static void main(String args[]) {
    CGraph g = new CGraph("entry");

    g.enterBF(new CGVisitor() {
        @Override
        public void nodeOperations(CGraph graph, CGraphNode currentNode) {
            System.out.println("20");
        }

        @Override
        public String getString() {
            throw new UnsupportedOperationException("No string can be returned from this anonymous implementation of CGVisitor.");
        }
    });

    a( 11 );
  }

  public static void a(int n) {
    b( n );
  }

  public static void b(int m) {
    int n;

    if (m >= 10)
      a( m-1 );
    else
      System.out.println(m);
  }
}

I double checked that the visitMethod method above is always executed, returns a non-null instance of InvokeFinderand that this instance never happens to be executed; how is it possible that under these conditions InvokeFinder.visitMethodInsn is never called by the ClassReader, even if there are invocation instruction in some methods of MyTestClass (e.g. inside method a(int))?

EDIT: Going further with the debugging, i found out that ClassReader calls the default MethodVisitor.visitMethodInsn instead of calling the overridden version InvokeFinder.visitMethodInsn. Why does this happen?

Body:
Turned out that i changed API version of ASM and the signature of MethodVisitor.visitMethodInsn is different between versions 4 and 5. The dynamic binding no longer recognized it as an overriding method.

I could fix this by adding the missing parameters to InvokeFinder.visitMethodInsn, whose signature now is

public void visitMethodInsn(int opcode, String owner, String name, String desc, boolean itf)


问:
Encountered undefined provider (angular4)
i work on angular4 and i've been fighting for several days with this mistake :

```<code>Encountered undefined provider! Usually this means you have a circular
 dependencies (might be caused by using 'barrel' index.ts files.
</code>```

thought it was related to injecting services (providers: [services, ...]) or components into @ngModule. I changed everything and checked it out, but it doesn't change anything. Where can this mistake come from?

Thank you for your help.

答:
I found the answer, I post it here in case people have the same problem.
If you are on a big project like mine with several people. Don't forget to update your nodes_modules locally:

rm -rf node_modules/ (on master or dev...)

npm cache clean -f

npm i (to install everything)

once the master branch has been updated you can update your branch :

git rebase master

Solved conflicts and it's over.

Body:
i work on angular4 and i've been fighting for several days with this mistake :

Encountered undefined provider! Usually this means you have a circular
 dependencies (might be caused by using 'barrel' index.ts files.

thought it was related to injecting services (providers: [services, ...]) or components into @ngModule. I changed everything and checked it out, but it doesn't change anything. Where can this mistake come from?

Thank you for your help.


问:
Cross-thread exception throwing
I have an application that allows users to write their own code in a language of our own making that's somewhat like C++. We're getting problems, however, where sometimes our users will accidentally write an infinite loop into their script. Once the script gets into the infinite loop, the only way they can get out is to shut the application down and restart, potentially losing their work. I'd like to add some means where the user, when he realizes that his code is in an infinite loop, can hit a special key, like F10 or something, and the code will break out of the loop. But I'd like to do it without implementing a ton of checks within the script runtime. Optimally, I'd like to have a separate "debugger" thread that's mostly idle, but as one of its tasks it listens for that F10 key, and when it gets the F10 key, it will cause the script runtime thread to throw an exception, so that it will stop executing the script. So my question is, is there a way to have one thread cause another thread to throw an exception? My application is written in C++.</p>

答: Whether you code it explicitly or not, you will need to check a "interrupt" variable in the message loop. If you implement this by a simple volatile int, you will have both a very simple test and very little overhead.

OwnerDisplayName: Anthony Johnson

ContentLicense: CC BY-SA 2.5

Title: Cross-thread exception throwing

OwnerDisplayName: MSalters


问:
npm: Add a platform specific dependency
In NPM documentation, there is an os option for platform specific dependency.

My package.json contains fsevents, which is a must on MacOS for performance reasons. On the other hand, it causes error on Windows.

```<code>"dependencies": {
        "axios": "^0.17.0",
        "electron": "^1.6.11",
        "electron-packager": "^8.7.2",
        "electron-reload": "^1.2.2",
        "electron-store": "^1.3.0",
        "flatpickr": "^4.0.7",
        "fsevents": "^1.1.2",
</code>```

So how exactly do I use the os option?

答:
fsevents should be an optional dependency which raises a warning but not an error during install. Which version of npm are you using? Try upgrading. There are at least a couple of buggy versions of npm will break this.

https://github.com/npm/npm/releases/tag/v3.10.10

```<code>REGRESSION FIX: 9aebe98 #14117 Fixes a bug where installing a shrinkwrapped
package would fail if the platform failed to install an optional dependency
included in the shrinkwrap.
</code>```

https://github.com/npm/npm/releases/tag/v5.4.2

```<code>0b28ac72d #18458 Fix a bug on Windows where rolling back of failed optional
dependencies would fail.
</code>```

Title: npm: Add a platform specific dependency

Body:
In NPM documentation, there is an os option for platform specific dependency.

My package.json contains fsevents, which is a must on MacOS for performance reasons. On the other hand, it causes error on Windows.

"dependencies": {
        "axios": "^0.17.0",
        "electron": "^1.6.11",
        "electron-packager": "^8.7.2",
        "electron-reload": "^1.2.2",
        "electron-store": "^1.3.0",
        "flatpickr": "^4.0.7",
        "fsevents": "^1.1.2",

So how exactly do I use the os option?

Body:
fsevents should be an optional dependency which raises a warning but not an error during install. Which version of npm are you using? Try upgrading. There are at least a couple of buggy versions of npm will break this.

https://github.com/npm/npm/releases/tag/v3.10.10

REGRESSION FIX: 9aebe98 #14117 Fixes a bug where installing a shrinkwrapped
package would fail if the platform failed to install an optional dependency
included in the shrinkwrap.

https://github.com/npm/npm/releases/tag/v5.4.2

0b28ac72d #18458 Fix a bug on Windows where rolling back of failed optional
dependencies would fail.


问:
Having trouble with Linq list sorting
Good evening.

I have a list of a class that I would like to index for different reasons, one being that I would like to read the data in different orders at different times. The trouble I am having is that I cannot get my head around sorting with LINQ.

The class I have in my list is similar to this (this is a smaller version)

```<code>List<SalesRecord> Records = new List<SalesRecord>();
class SalesRecord
{
    public Int16 SalesID { get; set; }
    public Int32 Invoice { get; set; }
    public DateTime BookoutDate { get; set; }
}
</code>```

The count size of Records is roughly 500,000

My thoughts were to create a couple of lists that would reference each item in Records in a particular order

Eg:

```<code>List<int> BookoutDateIndex;
List<int> InvoiceIndex;

Records[BookoutDateIndex[0]].BookoutDate // Oldest date
Records[BookoutDateIndex[1]].BookoutDate // Second oldest date
                                         // etc
</code>```

Based on the information I have seen, the closest I have found that almost does what I want is this...

```<code>// Copy dates to new list
List<DateTime> BookoutDates = new List<DateTime>();

for (int salesRecordIndex = 0; salesRecordIndex < records.Count; salesRecordIndex++)
    BookoutDates.Add(Records[salesRecordIndex].BookoutDate);

// Sort list

var sorted = Indexes.BookoutDates
    .Select((x, i) => new KeyValuePair<DateTime, int>(x, i))
    .OrderBy(x => x.Key)
    .ToList();
</code>```

Although this works, I don't want the actual date in the Index and I don't want to have to copy the dates in a new list beforehand.

I realize this would be easier to do by loading the data into something like a Access database, but I prefer to do it without a database option.

Any assistance would be appreciated.

答:
Summary of what you want: a list of the indexes of the main list sorted by some field on the main list?

As LINQ's OrderBy doesn't actually change the input, one ends up with your:

```<code>var sorted = Indexes.BookoutDates
                     .Select((x, i) => new KeyValuePair<DateTime, int>(x, i))
                     .OrderBy(x => x.Key)
                     .ToList();
</code>```

You are using a value type (KeyValuePair) to reduce the allocations that an anonymous type would bring. But there is no need to create a separate list of just the date you need first. Just take from the underlying list to start with.

And the Key property of the KeyValuePair is the first constructor parameter.

```<code>var sorted = Records
    .Select((r, x) => new KeyValuePair<DateTime, int>(r.BookoutDate, x))
    .OrderBy(x => x.Key)
    .Select(x => x.Value)
    .ToList();
</code>```

Title: Having trouble with Linq list sorting

Body:
Good evening.

I have a list of a class that I would like to index for different reasons, one being that I would like to read the data in different orders at different times. The trouble I am having is that I cannot get my head around sorting with LINQ.

The class I have in my list is similar to this (this is a smaller version)

List<SalesRecord> Records = new List<SalesRecord>();
class SalesRecord
{
    public Int16 SalesID { get; set; }
    public Int32 Invoice { get; set; }
    public DateTime BookoutDate { get; set; }
}

The count size of Records is roughly 500,000

My thoughts were to create a couple of lists that would reference each item in Records in a particular order

Eg:

List<int> BookoutDateIndex;
List<int> InvoiceIndex;

Records[BookoutDateIndex[0]].BookoutDate // Oldest date
Records[BookoutDateIndex[1]].BookoutDate // Second oldest date
                                         // etc

Based on the information I have seen, the closest I have found that almost does what I want is this...

// Copy dates to new list
List<DateTime> BookoutDates = new List<DateTime>();

for (int salesRecordIndex = 0; salesRecordIndex < records.Count; salesRecordIndex++)
    BookoutDates.Add(Records[salesRecordIndex].BookoutDate);

// Sort list

var sorted = Indexes.BookoutDates
    .Select((x, i) => new KeyValuePair<DateTime, int>(x, i))
    .OrderBy(x => x.Key)
    .ToList();

Although this works, I don't want the actual date in the Index and I don't want to have to copy the dates in a new list beforehand.

I realize this would be easier to do by loading the data into something like a Access database, but I prefer to do it without a database option.

Any assistance would be appreciated.

Body:
Summary of what you want: a list of the indexes of the main list sorted by some field on the main list?

As LINQ's OrderBy doesn't actually change the input, one ends up with your:

var sorted = Indexes.BookoutDates
                     .Select((x, i) => new KeyValuePair<DateTime, int>(x, i))
                     .OrderBy(x => x.Key)
                     .ToList();

You are using a value type (KeyValuePair) to reduce the allocations that an anonymous type would bring. But there is no need to create a separate list of just the date you need first. Just take from the underlying list to start with.

And the Key property of the KeyValuePair is the first constructor parameter.

var sorted = Records
    .Select((r, x) => new KeyValuePair<DateTime, int>(r.BookoutDate, x))
    .OrderBy(x => x.Key)
    .Select(x => x.Value)
    .ToList();


问:
Disable auto scroll on JQuery datetime plugin
I am using a JQuery datetime plugin in my application. When I scroll down or up my page and if my mouse pointer comes across date field text boxes then it changes dates because of scrolling. Even if date is not entered in date field then also it scrolls up or down from the current date. How to disable the scrolling on these date fields. You can see this behavior in the official page of this plugin for DatePicker field here:
http://xdsoft.net/jqplugins/datetimepicker/

答:
Pass options scrollMonth and scrollInput to false.

```<code>$('.myDatePicker').datetimepicker({
    timepicker : false,
    closeOnDateSelect : true,
    format : 'd-m-Y',
    scrollMonth : false,
    scrollInput : false
});
</code>```

Body:
Pass options scrollMonth and scrollInput to false.

$('.myDatePicker').datetimepicker({
    timepicker : false,
    closeOnDateSelect : true,
    format : 'd-m-Y',
    scrollMonth : false,
    scrollInput : false
});


问:
Terracotta EhCache - concurrent modification creates huge byte array during serialization
If my heapdump Dominator Tree view looks like below, can I assume the major contributor (~1GB) to my heap is the Thread instance created by Weblogic? And in that Thread a reference to ByteArrayOutputStream is the reason for 1GB?

Follow up question: Can I also assume it is due to object serialization? Maybe triggered by Terracotta ehcahce (from the third line. Not because it is next to the ByeArrayOS, because in our code that is the only place serialization can happen)?

答:
Ehcache does indeed rely on Java Serialization the moment your cache goes beyond heap.

However, it will only ever serialize what you put in the cache. So is it possible that some cached mappings have such huge value or even key?


问:
How can I update the [[UIApplication sharedApplication] scheduledLocalNotifications] array?
This may be more of a question regarding how to update arrays in general, but I have an app that is utilizing UILocalNotifications, and I want to allow users to select the notifications they have set, and edit them.

So what could I do to update an object at an index?

```<code>[[[UIApplication sharedApplication] scheduledLocalNotifications] ??];
</code>```

Thanks for any help!

答:
You can not able to edit an already existing notification.

But you can able to cancel it by using cancelLocalNotification: and create a fresh notification.

Body:
This may be more of a question regarding how to update arrays in general, but I have an app that is utilizing UILocalNotifications, and I want to allow users to select the notifications they have set, and edit them.

So what could I do to update an object at an index?

[[[UIApplication sharedApplication] scheduledLocalNotifications] ??];

Thanks for any help!


问:
How to obtain a log file for Audit Window from JBoss Drools Eclipse plugin?
I'm using JBoss Drools 6.5.0 Final plugin in Eclipse Neon. When creating a new project, I choose the option of sample code generation. When I run example code from Drools 5.5.0 Final, it produces a file called test.log which I could then use in Audit window of Drools perspective. This was done in this part of the default code:

```<code>KnowledgeRuntimeLogger logger = KnowledgeRuntimeLoggerFactory.newFileLogger(ksession, "test");
</code>```

This is not the case with 6.5.0 Final, because the example code does not contain the above line. When I tried to add it:

```<code>KieServices ks = KieServices.Factory.get();
KieContainer kContainer = ks.getKieClasspathContainer();
KieSession kSession = kContainer.newKieSession("ksession-rules");

KnowledgeRuntimeLogger logger = KnowledgeRuntimeLoggerFactory.newFileLogger(kSession, "test");
</code>```

I got a compilation error:

```<code>The method newFileLogger(KnowledgeRuntimeEventManager, String) in the type KnowledgeRuntimeLoggerFactory is not applicable for the arguments (KieSession, String)
</code>```

This is because new example code uses KieSession object and not StatefulKnowledgeSession. I tried casting the kSession to StatefulKnowledgeSession, but I get a cast exception.

What is the current way of obtaining test.log file?

答:
You need to cast your ksession to KnowledgeRuntimeEventManager :

KnowledgeRuntimeLogger logger = KnowledgeRuntimeLoggerFactory.newFileLogger((KnowledgeRuntimeEventManager) kSession, "test");

Body:
I'm using JBoss Drools 6.5.0 Final plugin in Eclipse Neon. When creating a new project, I choose the option of sample code generation. When I run example code from Drools 5.5.0 Final, it produces a file called test.log which I could then use in Audit window of Drools perspective. This was done in this part of the default code:

KnowledgeRuntimeLogger logger = KnowledgeRuntimeLoggerFactory.newFileLogger(ksession, "test");

This is not the case with 6.5.0 Final, because the example code does not contain the above line. When I tried to add it:

KieServices ks = KieServices.Factory.get();
KieContainer kContainer = ks.getKieClasspathContainer();
KieSession kSession = kContainer.newKieSession("ksession-rules");

KnowledgeRuntimeLogger logger = KnowledgeRuntimeLoggerFactory.newFileLogger(kSession, "test");

I got a compilation error:

The method newFileLogger(KnowledgeRuntimeEventManager, String) in the type KnowledgeRuntimeLoggerFactory is not applicable for the arguments (KieSession, String)

This is because new example code uses KieSession object and not StatefulKnowledgeSession. I tried casting the kSession to StatefulKnowledgeSession, but I get a cast exception.

What is the current way of obtaining test.log file?


问:
Animating a fade out element in a react component
I am creating a fade out warning/error message (bootstrap style) in a react component, and I am having some issues with the fade out timing.

My fade out works fine so far, and this is how it's done now:

```<code>import React, { Component } from 'react'
import classnames from 'classnames'

class AlertMessage extends Component {
    state = ({ autoHide: false })

    componentDidMount(){
        const { autoHide } = this.props
        if (autoHide && !this.state.hasClosed) {
            setTimeout(() => {
                    this.setState({ autoHide: true, hasClosed: true })
            }, 5000)
        }
    }

    render() {
        const { error, info, success, warning, text } = this.props

        const classNames = {
            'error': error,
            'info': info,
            'success': success,
            'warning': warning,
            'alert-hidden': this.state.autoHide
        }

        return (
            <div className={classnames("alert-message", classNames)}>
                {text}
            </div>
        )
    }
}

export default AlertMessage
</code>```

Now, I would like to remove the setTimeout and the state, making it a functional stateless component. My problem is that the transition-delay in my style seems not to work, and I am afraid it is related to how classNames applies the classes to the component.

Here my style:

```<code>.alert-message{
    overflow-y: hidden;
    opacity: 1;
    max-height: 80px;
    transition-property: all 450ms;
    transition-duration: 450ms;
    transition-timing-function: cubic-bezier(0, 1, 0.5, 1);
    transition-delay: 5000ms;
</code>```

Thanks

答:
Toast component of the BluePrint framework handles that with a timeout functionality. You can extract out the same functionality from its source code

As far as I know, you cannot achieve the animation only through CSS in react at the moment.

Body:
I am creating a fade out warning/error message (bootstrap style) in a react component, and I am having some issues with the fade out timing.

My fade out works fine so far, and this is how it's done now:

import React, { Component } from 'react'
import classnames from 'classnames'

class AlertMessage extends Component {
    state = ({ autoHide: false })

    componentDidMount(){
        const { autoHide } = this.props
        if (autoHide && !this.state.hasClosed) {
            setTimeout(() => {
                    this.setState({ autoHide: true, hasClosed: true })
            }, 5000)
        }
    }

    render() {
        const { error, info, success, warning, text } = this.props

        const classNames = {
            'error': error,
            'info': info,
            'success': success,
            'warning': warning,
            'alert-hidden': this.state.autoHide
        }

        return (

                {text}

        )
    }
}

export default AlertMessage

Now, I would like to remove the setTimeout and the state, making it a functional stateless component. My problem is that the transition-delay in my style seems not to work, and I am afraid it is related to how classNames applies the classes to the component.

Here my style:

.alert-message{
    overflow-y: hidden;
    opacity: 1;
    max-height: 80px;
    transition-property: all 450ms;
    transition-duration: 450ms;
    transition-timing-function: cubic-bezier(0, 1, 0.5, 1);
    transition-delay: 5000ms;

Thanks


问:
How to align the input fields?

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

Contact Person

      Name
      <input class="form-control" id="ex1" placeholder="First name" type="text">

      <input class="form-control" id="ex1" placeholder="Last name" type="text">

```

The two input fields do not align in the same line when i take the label off the second field how can this be corrected ?

答:
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

Contact Person

      Name
      <input class="form-control" id="ex1" placeholder="First name" type="text">

    Last Name
      <input class="form-control" id="ex2" placeholder="Last name" type="text">

```

Title: How to align the input fields?

Body:
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

Contact Person

      Name
      <input class="form-control" id="ex1" placeholder="First name" type="text">

      <input class="form-control" id="ex1" placeholder="Last name" type="text">

The two input fields do not align in the same line when i take the label off the second field how can this be corrected ?

Body:
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

<section class="section-component">
  <div class="col-xs-12"><h1>Contact Person</h1> </div>

  <div class="form-group">
    <div class="col-xs-6 form-field">
      <label for="ex1">Name</label>
      <input class="form-control" id="ex1" placeholder="First name" type="text">
    </div>
 </div>

 <div class="form-group">
    <div class="col-xs-6 form-field">
    <label for="ex2">Last Name</label>
      <input class="form-control" id="ex2" placeholder="Last name" type="text">
    </div>
 </div>
</section>


问:
how to detect when android app in background and foreground to handle some code
I need to know when user send my android app to background and then bring it back to foreground

when user send app to background I should perform server call and when back to foreground I have to clear some data

I have implemented it in the following way

```<code>public class MyApplication implements Application.ActivityLifecycleCallbacks {

@Override
    public void onActivityStopped(final Activity activity) {

// my logic goes here
}
}
</code>```

but this way make a lot of ANRs in background, and when I put my logic inside AsyncTask it does not work and also it close app in background

can any one advice me how to meet my requirement in another way without generating ANR's

答:
```<code>private boolean isAppInBackground(Context context) {
        boolean isInBackground = true;
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT_WATCH) {
            List<ActivityManager.RunningAppProcessInfo> runningProcesses = am.getRunningAppProcesses();
            for (ActivityManager.RunningAppProcessInfo processInfo : runningProcesses) {
                if (processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                    for (String activeProcess : processInfo.pkgList) {
                        if (activeProcess.equals(context.getPackageName())) {
                            isInBackground = false;
                        }
                    }
                }
            }
        } else {
            List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
            ComponentName componentInfo = taskInfo.get(0).topActivity;
            if (componentInfo.getPackageName().equals(context.getPackageName())) {
                isInBackground = false;
            }
        }

        return isInBackground;
    }
</code>```

<p>and add below permission in manifest </p>

```<code><uses-permission android:name="android.permission.GET_ACCOUNTS" />
</code>```

Body:
I need to know when user send my android app to background and then bring it back to foreground

when user send app to background I should perform server call and when back to foreground I have to clear some data

I have implemented it in the following way

public class MyApplication implements Application.ActivityLifecycleCallbacks {

@Override
    public void onActivityStopped(final Activity activity) {

// my logic goes here
}
}

but this way make a lot of ANRs in background, and when I put my logic inside AsyncTask it does not work and also it close app in background

can any one advice me how to meet my requirement in another way without generating ANR's

Body:
private boolean isAppInBackground(Context context) {
        boolean isInBackground = true;
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT_WATCH) {
            List<ActivityManager.RunningAppProcessInfo> runningProcesses = am.getRunningAppProcesses();
            for (ActivityManager.RunningAppProcessInfo processInfo : runningProcesses) {
                if (processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                    for (String activeProcess : processInfo.pkgList) {
                        if (activeProcess.equals(context.getPackageName())) {
                            isInBackground = false;
                        }
                    }
                }
            }
        } else {
            List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
            ComponentName componentInfo = taskInfo.get(0).topActivity;
            if (componentInfo.getPackageName().equals(context.getPackageName())) {
                isInBackground = false;
            }
        }

        return isInBackground;
    }

and add below permission in manifest

<uses-permission android:name="android.permission.GET_ACCOUNTS" />


问:
deferring an ajax call
I have a bit of js code on one of my pages that uses ajax to load some page elements.  These happen at the very top of the page and unfortunately slow down loading of the rest of the page.  I was wondering if there is a way to defer this so it loads after the page has loaded.

Here is the code I am using and it is located right before the closing body tag:

```<code>function countrySnippet() {
      $.ajax({
          url: '/country_snippets.php?sites=<?php echo json_encode($jam_sites); ?>&disabled=<?php echo json_encode($array_disabled); ?>&no_cat=<?php echo json_encode($category_disabled); ?>&hide=<?php echo $hide_overlay; ?>&use_id=<?php echo $use_id; ?>&snippet=<?php echo $display_country_snippet; ?>&title_top=<?php echo $snippet_title_top; ?>&title_bottom=<?php echo $snippet_title_bottom; ?>&theme=<?php echo $theme_detail['
          select_theme ']; ?>&code=<?php echo $country_code; ?>&region=<?php echo $country_region; ?>&thumbs=<?php echo $snippet_number_thumbs; ?>&size=<?php echo $settings_detail['
          index_thumbs_size ']; ?>',
          type: "get",
          beforeSend: function() {
            $('.ajax-load-snippet').show();
          }
        })
        .done(function(data) {
          $('.ajax-load-snippet').hide();
          $("#country-snippet").append(data).hide().fadeIn(1000);
        })
        .fail(function(jqXHR, ajaxOptions, thrownError) {
          $('.ajax-load-snippet').hide();
        });
    }
    countrySnippet();
</code>```

答:
As suggested by @KamalSingh,

$(document).ready(function() {
  function countrySnippet() {
    $.ajax({
        url: '/country_snippets.php?sites=<?php echo json_encode($jam_sites); ?>&disabled=<?php echo json_encode($array_disabled); ?>&no_cat=<?php echo json_encode($category_disabled); ?>&hide=<?php echo $hide_overlay; ?>&use_id=<?php echo $use_id; ?>&snippet=<?php echo $display_country_snippet; ?>&title_top=<?php echo $snippet_title_top; ?>&title_bottom=<?php echo $snippet_title_bottom; ?>&theme=<?php echo $theme_detail['
        select_theme ']; ?>&code=<?php echo $country_code; ?>&region=<?php echo $country_region; ?>&thumbs=<?php echo $snippet_number_thumbs; ?>&size=<?php echo $settings_detail['
        index_thumbs_size ']; ?>',
        type: "get",
        beforeSend: function() {
          $('.ajax-load-snippet').show();
        }
      })
      .done(function(data) {
        $('.ajax-load-snippet').hide();
        $("#country-snippet").append(data).hide().fadeIn(1000);
      })
      .fail(function(jqXHR, ajaxOptions, thrownError) {
        $('.ajax-load-snippet').hide();
      });
  }
  countrySnippet();
});```

Title: deferring an ajax call

Body:
I have a bit of js code on one of my pages that uses ajax to load some page elements.  These happen at the very top of the page and unfortunately slow down loading of the rest of the page.  I was wondering if there is a way to defer this so it loads after the page has loaded.

Here is the code I am using and it is located right before the closing body tag:

function countrySnippet() {
      $.ajax({
          url: '/country_snippets.php?sites=<?php echo json_encode($jam_sites); ?>&disabled=<?php echo json_encode($array_disabled); ?>&no_cat=<?php echo json_encode($category_disabled); ?>&hide=<?php echo $hide_overlay; ?>&use_id=<?php echo $use_id; ?>&snippet=<?php echo $display_country_snippet; ?>&title_top=<?php echo $snippet_title_top; ?>&title_bottom=<?php echo $snippet_title_bottom; ?>&theme=<?php echo $theme_detail['
          select_theme ']; ?>&code=<?php echo $country_code; ?>&region=<?php echo $country_region; ?>&thumbs=<?php echo $snippet_number_thumbs; ?>&size=<?php echo $settings_detail['
          index_thumbs_size ']; ?>',
          type: "get",
          beforeSend: function() {
            $('.ajax-load-snippet').show();
          }
        })
        .done(function(data) {
          $('.ajax-load-snippet').hide();
          $("#country-snippet").append(data).hide().fadeIn(1000);
        })
        .fail(function(jqXHR, ajaxOptions, thrownError) {
          $('.ajax-load-snippet').hide();
        });
    }
    countrySnippet();


问:
Get last but one value using SQL function FIRST_VALUE
Is it possible to get last but one value of sorted variable using SQL function FIRST_VALUE? Here is a way to get the last value.

```<code>select
[MyVal_Last] = FIRST_VALUE([MyValue]) OVER (PARTITION BY [Category] ORDER BY [MyValue] DESC)
from tbl
</code>```

Is it possible to modify it to get second last value?

Update. I am familiar with different ways of getting the last but one value mentioned i.e. here Those answers are old and have grown long beards. I wonder if new version of SQL Server can do it in a more elegant way, using new functions.

答:
you can also use OFFSET FETCH function to get second last row.</p>

```<code>CREATE TABLE Cinema
    ([CinemaID] int, [Name] varchar(7))
;

INSERT INTO Cinema
    ([CinemaID], [Name])
VALUES
    (1, 'Odeon'),
    (2, 'Mercury'),
    (3, 'Apollo'),
    (4, 'Venus')
;

 SELECT c.*
    FROM dbo.Cinema AS c
    ORDER BY CinemaID DESC
    OFFSET 1 ROW
    FETCH FIRST 1 ROW ONLY ;
</code>```

Body:
Is it possible to get last but one value of sorted variable using SQL function FIRST_VALUE? Here is a way to get the last value.

select
[MyVal_Last] = FIRST_VALUE([MyValue]) OVER (PARTITION BY [Category] ORDER BY [MyValue] DESC)
from tbl

Is it possible to modify it to get second last value?

Update. I am familiar with different ways of getting the last but one value mentioned i.e. here Those answers are old and have grown long beards. I wonder if new version of SQL Server can do it in a more elegant way, using new functions.

Body:
you can also use OFFSET FETCH function to get second last row.

CREATE TABLE Cinema
    ([CinemaID] int, [Name] varchar(7))
;

INSERT INTO Cinema
    ([CinemaID], [Name])
VALUES
    (1, 'Odeon'),
    (2, 'Mercury'),
    (3, 'Apollo'),
    (4, 'Venus')
;

 SELECT c.*
    FROM dbo.Cinema AS c
    ORDER BY CinemaID DESC
    OFFSET 1 ROW
    FETCH FIRST 1 ROW ONLY ;


问:
Compatible DDL (CREATE TABLE) across different SQL databases?
I'm working on a desktop application that must support (currently) MS Access and SQL Server back ends.  The application is under constant development and changes are frequently being made to the database, mostly the addition of tables and views to support new features (but also some DROPs and ALTER TABLEs to add new columns).

I have a system that compiles the DDL into the executable, checks the database to see if the executable has any new DDL that has to be executed, and executes it.  This works fine for a single database.

My immediate problem is that SQL Server and Access support wildly different names for data types so a CREATE TABLE statement that executes against Access will not execute against SQL Server (or worse, will execute but create a table with different datatypes).

Is there a method that can be used to create DDL (especially CREATE TABLE commands) that can be executed through ADO against both of these databases without having to craft separate DDL for each provider?

答:
Since you are already using ADO, you should look into Microsoft ADOX

This allows you to manipulate structures in a data source using an ADO object model that is independent of the underlying data source type.  i.e. without resorting to explicit DDL

Support for ADOX is not guaranteed by any given ADO Provider, and the level of ADOX support may vary even when it is available.  But for MS Access and MS SQL Server I think you will find all the capability you require (and quite possibly more!)


问:
Identify XPath from particular element
I'm working on a page, where page loads dynamically and the data gets added while scrolling. To identify the properties of an item, I identified the parent div, where to identify the address, I have to locate an XPath from the parent to span element.
Below is my DOM structure:

```<code><div class = "parentdiv">
    <div class = "search">
    <div class="header">
    <div class="data"></div>
    <div class="address-data">
      <div class="address" itemprop="address">
        <a itemprop="url" href="/search/Los-Angeles-CA-90025">
                <span itemprop="streetAddress">
                    Avenue
                </span>

                <br>
                <span itemprop="Locality">Los Angeles</span>
                <span itemprop="Region">CA</span>
            </a>
        </div>
        </div>
        </div>
    </div>
</div>
</div>
</code>```

Here I want to locate the three spans, where I' currently in parent div.
Can someone guide how to locate an element using XPath from particular div?

答:
Your DOM might become fairly large, since it adds elements while scrolling, so using CSS selectors might be quicker.

To get all the span tags in the div, use:

```<code>div[class='address'] span
</code>```

To get a specific span by using the itemprop attribute use:

```<code>div[class='address'] span[itemprop='streetAddress']
div[class='address'] span[itemprop='Locality']
div[class='address'] span[itemprop='Region']
</code>```

You can store the elements in a variable like so:

```<code>var streetAddress = driver.FindElement(By.CssSelector("div[class='address'] span[itemprop='streetAddress']"));
var locality = driver.FindElement(By.CssSelector("div[class='address'] span[itemprop='Locality']"));
var region = driver.FindElement(By.CssSelector("div[class='address'] span[itemprop='Region']"));
</code>```

Title: Identify XPath from particular element

Body:
I'm working on a page, where page loads dynamically and the data gets added while scrolling. To identify the properties of an item, I identified the parent div, where to identify the address, I have to locate an XPath from the parent to span element.
Below is my DOM structure:

                    Avenue

                Los Angeles
                CA

Here I want to locate the three spans, where I' currently in parent div.
Can someone guide how to locate an element using XPath from particular div?

Body:
Your DOM might become fairly large, since it adds elements while scrolling, so using CSS selectors might be quicker.

To get all the span tags in the div, use:

div[class='address'] span

To get a specific span by using the itemprop attribute use:

div[class='address'] span[itemprop='streetAddress']
div[class='address'] span[itemprop='Locality']
div[class='address'] span[itemprop='Region']

You can store the elements in a variable like so:

var streetAddress = driver.FindElement(By.CssSelector("div[class='address'] span[itemprop='streetAddress']"));
var locality = driver.FindElement(By.CssSelector("div[class='address'] span[itemprop='Locality']"));
var region = driver.FindElement(By.CssSelector("div[class='address'] span[itemprop='Region']"));


问:
jquery add remove form input on toggle
I have the following html and form elements

```<code><div class='ticket-sold' id='1' >RAFFLE-1-NOVEMBER</div>
<div class='ticket' id='2'>RAFFLE-2-NOVEMBER</div>
<div class='ticket' id='3'>RAFFLE-3-NOVEMBER</div>
<div class='ticket' id='4'>RAFFLE-4-NOVEMBER</div>
<div class='ticket' id='5'>RAFFLE-5-NOVEMBER</div>

<form class="paypal" action="./includes/gateways/payments.php" method="post" id="paypal_form" target="_blank">
    <input type="hidden" name="cmd" value="_xclick" />
    <input type="hidden" name="no_note" value="1" />
    <input type="hidden" name="lc" value="UK" />
    <input type="hidden" name="currency_code" value="GBP" />
    <input type="hidden" name="payer_email" value="customer@example.com"  />
   <input name="item_name_1" value="TICKET NUMBER 5" id="input_5" type="hidden">
   <input name="item_name_2" value="TICKET NUMBER 20" id="input_20" type="hidden">
   <input name="item_name_3" value="TICKET NUMBER 27" id="input_27" type="hidden">
   <input type="hidden" name="amount_1" value="10" id="input_5" />
   <input type="hidden" name="amount_2" value="10" id="input_20" />
   <input type="hidden" name="amount_3" value="10" id="input_27" />
   <input type="submit" name="submit" value="Submit Payment"/>
</form>
</code>```

Basically, I have jquery that when the Div class 'ticket' is selected, the 'amount' field is updated based on the number of 'ticket' elements selected.

```<code>var counter = 0;
$(".ticket").on("click", function() {
$(this).toggleClass("green");
$(this).toggleClass('selected');
var selectedIds = $('.selected').map(function() {
        return this.id;
}).get();
var id = $(this).attr('id');
if(!$(this).hasClass('selected')) {
    $('#paypal_form #input_' + id).remove();
    counter--;
} else {
    counter++;
    $('#paypal_form').append('<input type="hidden" name="item_name_'+counter+'" value="TICKET NUMBER ' + id + '" id="input_'+id+'">');
    $('#paypal_form').append('<input type="hidden" name="amount_'+counter+'" value="' + $(".ticketprice").text() +'" id="input_'+id +'">');
    }
    $(".totaltickets").text(selectedIds.length -1);
    $(".totalprice").text((selectedIds.length - 1)*$(".ticketprice").text());
</code>```

What I would like to do, is at the same time of the onclick function on the 'ticket' div, I would like another input type ie <input type="hidden" name="item_name" value="Selected ID from Div"> added dynamically to the Form ("paypal_form").  And if the 'ticket' DIV is toggled, ie Clicked to deselect the item, the added  element should be removed.

thanks
Craig.

答:
You could approach it similar to this. It checks if the class selected is assigned to the selected div. If so, it appends a hidden input with a specific ID to the form. If the div is unselected, it removes that input from the form.

$(document).ready(function() {
  $(".ticket").on("click", function() {
    $(this).toggleClass("green");
    $(this).toggleClass('selected');

    var selectedIds = $('.selected').map(function() {
      return this.id;
    }).get();

    var id = $(this).attr('id');

    if(!$(this).hasClass('selected')) {
      $('#paypal_form #input_' + id).remove();
    } else {
      $('#paypal_form').append('<input type="hidden" id="input_' + id + '">');
    }

    $('[name=amount]').val((selectedIds.length - 1) * $(".ticketprice").text());
    $('[name=item_name]').val((selectedIds.length - 1) + " Ticket(s) selected");
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='ticket-sold' id='1'>RAFFLE-1-NOVEMBER</div>
<div class='ticket' id='2'>RAFFLE-2-NOVEMBER</div>
<div class='ticket' id='3'>RAFFLE-3-NOVEMBER</div>
<div class='ticket' id='4'>RAFFLE-4-NOVEMBER</div>
<div class='ticket' id='5'>RAFFLE-5-NOVEMBER</div>

<form class="paypal" action="./includes/gateways/payments.php" method="post" id="paypal_form" target="_blank">
  <input type="hidden" name="cmd" value="_xclick" />
  <input type="hidden" name="no_note" value="1" />
  <input type="hidden" name="lc" value="UK" />
  <input type="hidden" name="currency_code" value="GBP" />
  <input type="hidden" name="payer_email" value="customer@example.com" />
  <input type="hidden" name="item_name" value="" />
  <input type="hidden" name="amount" value="0" />
  <input type="submit" name="submit" value="Submit Payment" />
</form></code>```

Title: jquery add remove form input on toggle

Body:
I have the following html and form elements

RAFFLE-1-NOVEMBER

RAFFLE-2-NOVEMBER

RAFFLE-3-NOVEMBER

RAFFLE-4-NOVEMBER

RAFFLE-5-NOVEMBER

<form class="paypal" action="./includes/gateways/payments.php" method="post" id="paypal_form" target="_blank">
    <input type="hidden" name="cmd" value="_xclick" />
    <input type="hidden" name="no_note" value="1" />
    <input type="hidden" name="lc" value="UK" />
    <input type="hidden" name="currency_code" value="GBP" />
    <input type="hidden" name="payer_email" value="customer@example.com"  />
   <input name="item_name_1" value="TICKET NUMBER 5" id="input_5" type="hidden">
   <input name="item_name_2" value="TICKET NUMBER 20" id="input_20" type="hidden">
   <input name="item_name_3" value="TICKET NUMBER 27" id="input_27" type="hidden">
   <input type="hidden" name="amount_1" value="10" id="input_5" />
   <input type="hidden" name="amount_2" value="10" id="input_20" />
   <input type="hidden" name="amount_3" value="10" id="input_27" />
   <input type="submit" name="submit" value="Submit Payment"/>
</form>

Basically, I have jquery that when the Div class 'ticket' is selected, the 'amount' field is updated based on the number of 'ticket' elements selected.

var counter = 0;
$(".ticket").on("click", function() {
$(this).toggleClass("green");
$(this).toggleClass('selected');
var selectedIds = $('.selected').map(function() {
        return this.id;
}).get();
var id = $(this).attr('id');
if(!$(this).hasClass('selected')) {
    $('#paypal_form #input_' + id).remove();
    counter--;
} else {
    counter++;
    $('#paypal_form').append('<input type="hidden" name="item_name_'+counter+'" value="TICKET NUMBER ' + id + '" id="input_'+id+'">');
    $('#paypal_form').append('<input type="hidden" name="amount_'+counter+'" value="' + $(".ticketprice").text() +'" id="input_'+id +'">');
    }
    $(".totaltickets").text(selectedIds.length -1);
    $(".totalprice").text((selectedIds.length - 1)*$(".ticketprice").text());

What I would like to do, is at the same time of the onclick function on the 'ticket' div, I would like another input type ie <input type="hidden" name="item_name" value="Selected ID from Div"> added dynamically to the Form ("paypal_form").  And if the 'ticket' DIV is toggled, ie Clicked to deselect the item, the added  element should be removed.

thanks
Craig.

Body:
You could approach it similar to this. It checks if the class selected is assigned to the selected div. If so, it appends a hidden input with a specific ID to the form. If the div is unselected, it removes that input from the form.

$(document).ready(function() {
  $(".ticket").on("click", function() {
    $(this).toggleClass("green");
    $(this).toggleClass('selected');

    var selectedIds = $('.selected').map(function() {
      return this.id;
    }).get();

    var id = $(this).attr('id');

    if(!$(this).hasClass('selected')) {
      $('#paypal_form #input_' + id).remove();
    } else {
      $('#paypal_form').append('<input type="hidden" id="input_' + id + '">');
    }

    $('[name=amount]').val((selectedIds.length - 1) * $(".ticketprice").text());
    $('[name=item_name]').val((selectedIds.length - 1) + " Ticket(s) selected");
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='ticket-sold' id='1'>RAFFLE-1-NOVEMBER</div>
<div class='ticket' id='2'>RAFFLE-2-NOVEMBER</div>
<div class='ticket' id='3'>RAFFLE-3-NOVEMBER</div>
<div class='ticket' id='4'>RAFFLE-4-NOVEMBER</div>
<div class='ticket' id='5'>RAFFLE-5-NOVEMBER</div>

<form class="paypal" action="./includes/gateways/payments.php" method="post" id="paypal_form" target="_blank">
  <input type="hidden" name="cmd" value="_xclick" />
  <input type="hidden" name="no_note" value="1" />
  <input type="hidden" name="lc" value="UK" />
  <input type="hidden" name="currency_code" value="GBP" />
  <input type="hidden" name="payer_email" value="customer@example.com" />
  <input type="hidden" name="item_name" value="" />
  <input type="hidden" name="amount" value="0" />
  <input type="submit" name="submit" value="Submit Payment" />
</form>


问:
Merge two arrays into one associative array
I have two arrays that I want to merge into one associative array.
My first array looks like this:

```<code>$names_array = ["John", "Paul", "George"];
</code>```

The second one looks like this:

```<code>$ages_array = [26, 29, 22];
</code>```

I would like to merge these two arrays and obtain this structure:

```<code>$members_infos = [{"name": "John", "age": 26}, {"name": "Paul", "age":
29}, {"name": "George", "age": 22}];
</code>```

Do I have to use a for loop in order to achieve what I want or can use a php function ?

Thank you

答:
By using array combine function you can join names, ages </p>

```<code>$names_array = ["John", "Paul", "George"];
    $ages_array = [26, 29, 22];
    $result = [];
    $members_infos = array_combine($names_array,$ages_array);
    foreach ($members_infos as $key => $value) {
        $result[] = ['name'=>$key, 'age'=>$value];
    }

    $output = json_encode($result);
    echo "```";
    print_r($output);
    echo "```";
    exit;
</code>```

Body:
I have two arrays that I want to merge into one associative array.
My first array looks like this:

$names_array = ["John", "Paul", "George"];

The second one looks like this:

$ages_array = [26, 29, 22];

I would like to merge these two arrays and obtain this structure:

$members_infos = [{"name": "John", "age": 26}, {"name": "Paul", "age":
29}, {"name": "George", "age": 22}];

Do I have to use a for loop in order to achieve what I want or can use a php function ?

Thank you

Body:
By using array combine function you can join names, ages

$names_array = ["John", "Paul", "George"];
    $ages_array = [26, 29, 22];
    $result = [];
    $members_infos = array_combine($names_array,$ages_array);
    foreach ($members_infos as $key => $value) {
        $result[] = ['name'=>$key, 'age'=>$value];
    }

    $output = json_encode($result);
    echo "<pre>";
    print_r($output);
    echo "</pre>";
    exit;


问:
Geotools: bounding box for a buffer in wgs84
I am need a Java function that will generate a bounding box (rectangle) around a buffer. The buffer is defined by the center point (WGS84 coordinate) and the radius (in meters).

Getting a bounding box for a buffer in JTS seems to be quite simple:

```<code>Point center = ....
Geometry boundingBox = center.buffer(...).getEnvelope();
</code>```

This however is pure planar geometry. Is there a way to do this using a coordinate reference system with the distance given in meters?

Optimally with Geotools but other Java solutions will also work...

答:
Although you have approached it in another way, I have another solution for that. The results will be way more precise than with your proposed solution.

```<code>GeometryFactory GEOMETRY_FACTORY = JTSFactoryFinder.getGeometryFactory();

// Remember, order is (longitude, latitude)
Coordinate center = Coordinate(2.29443, 48.85816);
Point point = GEOMETRY_FACTORY.createPoint(center);

// Buffer 50KM around the point, then get the envelope
Envelope envelopeInternal = buffer(point, 50000).getEnvelopeInternal();

// Then you can play with the envelope, e.g.,
double minX = envelopeInternal.getMinX();
double maxX = envelopeInternal.getMaxX();

// The buffer using distanceInMeters
private Geometry buffer(Geometry geometry, double distanceInMeters) throws FactoryException, TransformException {
     String code = "AUTO:42001," + geometry.getCentroid().getCoordinate().x + "," + geometry.getCentroid().getCoordinate().y;
     CoordinateReferenceSystem auto = CRS.decode(code);

     MathTransform toTransform = CRS.findMathTransform(DefaultGeographicCRS.WGS84, auto);
     MathTransform fromTransform = CRS.findMathTransform(auto, DefaultGeographicCRS.WGS84);

     Geometry pGeom = JTS.transform(geometry, toTransform);
     Geometry pBufferedGeom = pGeom.buffer(distanceInMeters);
     return JTS.transform(pBufferedGeom, fromTransform);
}
</code>```

And here is the map with the result, buffer in red, envelope in black.

Body:
I am need a Java function that will generate a bounding box (rectangle) around a buffer. The buffer is defined by the center point (WGS84 coordinate) and the radius (in meters).

Getting a bounding box for a buffer in JTS seems to be quite simple:

Point center = ....
Geometry boundingBox = center.buffer(...).getEnvelope();

This however is pure planar geometry. Is there a way to do this using a coordinate reference system with the distance given in meters?

Optimally with Geotools but other Java solutions will also work...

Body:
Although you have approached it in another way, I have another solution for that. The results will be way more precise than with your proposed solution.

GeometryFactory GEOMETRY_FACTORY = JTSFactoryFinder.getGeometryFactory();

// Remember, order is (longitude, latitude)
Coordinate center = Coordinate(2.29443, 48.85816);
Point point = GEOMETRY_FACTORY.createPoint(center);

// Buffer 50KM around the point, then get the envelope
Envelope envelopeInternal = buffer(point, 50000).getEnvelopeInternal();

// Then you can play with the envelope, e.g.,
double minX = envelopeInternal.getMinX();
double maxX = envelopeInternal.getMaxX();

// The buffer using distanceInMeters
private Geometry buffer(Geometry geometry, double distanceInMeters) throws FactoryException, TransformException {
     String code = "AUTO:42001," + geometry.getCentroid().getCoordinate().x + "," + geometry.getCentroid().getCoordinate().y;
     CoordinateReferenceSystem auto = CRS.decode(code);

     MathTransform toTransform = CRS.findMathTransform(DefaultGeographicCRS.WGS84, auto);
     MathTransform fromTransform = CRS.findMathTransform(auto, DefaultGeographicCRS.WGS84);

     Geometry pGeom = JTS.transform(geometry, toTransform);
     Geometry pBufferedGeom = pGeom.buffer(distanceInMeters);
     return JTS.transform(pBufferedGeom, fromTransform);
}

And here is the map with the result, buffer in red, envelope in black.


问:
Select Price value only from td in python
I am trying to capture just price value from html td tag but the problem is there are other td with same class name: please see the picture below. enter image description here

here is the code i have written

```<code>from  builtins import any as b_any
from urllib.parse import urlparse
from urllib.parse import urljoin
from collections import Counter
import urllib.request
import csv
import schedule
import time
import re
from bs4 import BeautifulSoup

url="http://offer.ebay.es/ws/eBayISAPI.dll?ViewBidsLogin&item=122713288532&rt=nc&_trksid=p2047675.l2564"

req = urllib.request.Request(url, headers={'User-agent': 'Mozilla/5.0'})

htmlpage = urllib.request.urlopen(req)

html = htmlpage.read().decode('utf-8')

soup = BeautifulSoup(html,"html.parser")

table = soup.find_all('td',{'class':'onheadNav'})

'''for txt in table:
    nametxt = txt.text
    result = ''.join([i for i in nametxt if not i.isdigit()])
    cleantxt = result.replace('(','')
    print(cleantxt.replace(')',''))

    rank = txt.a.text
    print(rank)'''
price = soup.select('td.contentValueFont')
for pr in price:
    print(pr.text)
</code>```

If i slice price in for loop it will get only first price but i want to have all prices at once.

Edited description:
I want to capture all prices but problem is there are three td with same class name one td is for price one for Cantidad(quantity) and the one which is for date these all have same class. and when i try to get only price section my code returns all three td's. I hope you get it now

答:
What you need to do is find all the 'tr' tags in the table you want scraped and then iterate over all those to get the text from the particular 'td'.

Something like this:

```<code>table = soup.find_all('table')
for tr in table[9].find_all('tr')[1:-1]:
    price = tr.find_all('td')[2].text.strip()
    print(price)
</code>```

After some research we can find out that the table we want is the 10th table on the page, hence table[9]. Also, since we don't want the first and the last 'tr' we do find_all('tr')[1:-1]

Hope this solves your problem.

Body:
I am trying to capture just price value from html td tag but the problem is there are other td with same class name: please see the picture below. enter image description here

here is the code i have written

from  builtins import any as b_any
from urllib.parse import urlparse
from urllib.parse import urljoin
from collections import Counter
import urllib.request
import csv
import schedule
import time
import re
from bs4 import BeautifulSoup

url="http://offer.ebay.es/ws/eBayISAPI.dll?ViewBidsLogin&item=122713288532&rt=nc&_trksid=p2047675.l2564"

req = urllib.request.Request(url, headers={'User-agent': 'Mozilla/5.0'})

htmlpage = urllib.request.urlopen(req)

html = htmlpage.read().decode('utf-8')

soup = BeautifulSoup(html,"html.parser")

table = soup.find_all('td',{'class':'onheadNav'})

'''for txt in table:
    nametxt = txt.text
    result = ''.join([i for i in nametxt if not i.isdigit()])
    cleantxt = result.replace('(','')
    print(cleantxt.replace(')',''))

    rank = txt.a.text
    print(rank)'''
price = soup.select('td.contentValueFont')
for pr in price:
    print(pr.text)

If i slice price in for loop it will get only first price but i want to have all prices at once.

Edited description:
I want to capture all prices but problem is there are three td with same class name one td is for price one for Cantidad(quantity) and the one which is for date these all have same class. and when i try to get only price section my code returns all three td's. I hope you get it now

Body:
What you need to do is find all the 'tr' tags in the table you want scraped and then iterate over all those to get the text from the particular 'td'.

Something like this:

table = soup.find_all('table')
for tr in table[9].find_all('tr')[1:-1]:
    price = tr.find_all('td')[2].text.strip()
    print(price)

After some research we can find out that the table we want is the 10th table on the page, hence table[9]. Also, since we don't want the first and the last 'tr' we do find_all('tr')[1:-1]

Hope this solves your problem.


问:
Query with subquery returns null
I Have a query with returns no results despite there are still plenty of rows to process.

```<code>SELECT O.[OrderLineId]
, O.[Article]
, O.[ArticleDescription]
, O.[QtyOrdered]
, O.[QtyDelivered]
, O.[BoxId]
, O.[Status]
, O.[Picker]
, O.[PickLocation]
, O.[Sorting]
, O.[DateCreated]
, O.[DateModified]
FROM [dbo].[PickBatch] P
INNER JOIN [dbo].[Boxes] B ON P.PickBatchId = B.PickBatchId
INNER JOIN [dbo].[OrderLines] O ON B.BoxId = O.BoxId
WHERE P.PickBatchId = @PickBatchId
AND (O.[Status] = @Status)
AND (O.[PickLocation] = (SELECT TOP(1) O.[PickLocation]
                        FROM [dbo].[PickBatch] P
                      INNER JOIN [dbo].[Boxes] B ON P.PickBatchId = B.PickBatchId
                      INNER JOIN [dbo].[OrderLines] O ON B.BoxId = O.BoxId
                      WHERE P.PickBatchId = @PickBatchId
                      AND O.[Status] = @Status
                      ORDER BY O.Sorting))
</code>```

It looks like the subquery returns a result and meanwhile the status is changed so that the main query returns no results. Is this possible? Or do I make another mistake?

When the query returns no results the users is prompted that everything is picked and he can start a new batch. When he want's to start a new batch there a check if he hasn't an open batch. This fires few queries and this query. Then the query returns a result. So basically query is fired no results, sec. later same query returns results.

答:
I want to suppose your query is exact but you can't use the same alias in main query and sub query. Aliases are used to differentiate the same table. So in your subquery:

instead of P use P2

instead of B use B2

instead of O use O2

So. If your query doens't work please post a data set and expected result set

Title: Query with subquery returns null

Body:
I Have a query with returns no results despite there are still plenty of rows to process.

SELECT O.[OrderLineId]
, O.[Article]
, O.[ArticleDescription]
, O.[QtyOrdered]
, O.[QtyDelivered]
, O.[BoxId]
, O.[Status]
, O.[Picker]
, O.[PickLocation]
, O.[Sorting]
, O.[DateCreated]
, O.[DateModified]
FROM [dbo].[PickBatch] P
INNER JOIN [dbo].[Boxes] B ON P.PickBatchId = B.PickBatchId
INNER JOIN [dbo].[OrderLines] O ON B.BoxId = O.BoxId
WHERE P.PickBatchId = @PickBatchId
AND (O.[Status] = @Status)
AND (O.[PickLocation] = (SELECT TOP(1) O.[PickLocation]
                        FROM [dbo].[PickBatch] P
                      INNER JOIN [dbo].[Boxes] B ON P.PickBatchId = B.PickBatchId
                      INNER JOIN [dbo].[OrderLines] O ON B.BoxId = O.BoxId
                      WHERE P.PickBatchId = @PickBatchId
                      AND O.[Status] = @Status
                      ORDER BY O.Sorting))

It looks like the subquery returns a result and meanwhile the status is changed so that the main query returns no results. Is this possible? Or do I make another mistake?

When the query returns no results the users is prompted that everything is picked and he can start a new batch. When he want's to start a new batch there a check if he hasn't an open batch. This fires few queries and this query. Then the query returns a result. So basically query is fired no results, sec. later same query returns results.


问:
Using Or in Php
I am trying to use or logical operator in Php to display a message if either of the argument is true, but am always getting the wrong output here is my code. Any suggestions are welcome. Thanks in advance.

```<code><?php

$username = test_input(mysqli_real_escape_string($conn,$_POST['username']));

$emailregex = preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/", $username); //ValidatingEmail

$usernameregex = preg_match("/^[a-zA-Z]+$/",$username);  //checking if name   contains only letters and white spaces;

if ( !$emailregex   || !$usernameregex ) { //if it didn't match either
    echo "InvalidUserName";
    exit();
} else if ( $emailregex  || $usernameregex ) { //in case either matched
    $myusername =$username;
    echo("Hello".$myusername);
}?>
</code>```

Problem is even if I enter a valid name or email am getting "invalidusername"
Is my logic wrong?

答:
<?php

$username = test_input(mysqli_real_escape_string($conn,$_POST['username']));

$emailregex = preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/", $username); //ValidatingEmail

$usernameregex = preg_match("/^[a-zA-Z]+$/",$username);  //checking if name   contains only letters and white spaces;

if (!$emailregex && !$usernameregex ) {
echo "Username must be valid name or email";
exit();
}
else {
$myusername =$username;
echo("Hello".$myusername);
}
?>```

Title: Using Or in Php

Body:
I am trying to use or logical operator in Php to display a message if either of the argument is true, but am always getting the wrong output here is my code. Any suggestions are welcome. Thanks in advance.

<?php

$username = test_input(mysqli_real_escape_string($conn,$_POST['username']));

$emailregex = preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/", $username); //ValidatingEmail

$usernameregex = preg_match("/^[a-zA-Z]+$/",$username);  //checking if name   contains only letters and white spaces;

if ( !$emailregex   || !$usernameregex ) { //if it didn't match either
    echo "InvalidUserName";
    exit();
} else if ( $emailregex  || $usernameregex ) { //in case either matched
    $myusername =$username;
    echo("Hello".$myusername);
}?>

Problem is even if I enter a valid name or email am getting "invalidusername"
Is my logic wrong?


问:
Primefaces excel export is not working - no open/save dialog is shown
I am trying to export collection of dtos to excel with primefaces like this (the same as primefaces showcase demo, which is working).

```<code><p:commandButton value="Export">
    <p:dataExporter type="xls" target="results" fileName="game_statistics" />
</p:commandButton>
</code>```

I observed with firebug and it makes request, also the response looks like file content, but no file save/open dialog is popping.
I am using mojarra 2.1.1 and tomcat 6 for app server.

答:
Enclose it into <h:form>...</h:form> and it will work
For example:

```<code><h:form>
<p:commandButton value="Export">
    <p:dataExporter type="xls" target="results" fileName="game_statistics" />
</p:commandButton>
</h:form>
</code>```

Body:
I am trying to export collection of dtos to excel with primefaces like this (the same as primefaces showcase demo, which is working).

I observed with firebug and it makes request, also the response looks like file content, but no file save/open dialog is popping.
I am using mojarra 2.1.1 and tomcat 6 for app server.

Body:
Enclose it into <h:form>...</h:form> and it will work
For example:

<h:form>
<p:commandButton value="Export">
    <p:dataExporter type="xls" target="results" fileName="game_statistics" />
</p:commandButton>
</h:form>


问:
How do I configure Google Cloud Datalab to use GPUs for TensorFlow?
I can import tensorflow and run models inside of Cloud Datalab, but how do I configure it to use GPUs?

The documentation here only talks about machines, which I'm not sure how to configure through Datalab:
https://cloud.google.com/ml-engine/docs/how-tos/using-gpus

I've tried this:

```<code>datalab create --machine-type standard_gpu ml
</code>```

and when I select the us-east1 region, I get the error:

```<code>Creating the instance ml
ERROR: (gcloud.compute.instances.create) Some requests did not succeed:
- Invalid value for field 'resource.machineType': 'https://www.googleapis.com/compute/v1/projects/project-160204/zones/us-east1-d/machineTypes/standard_gpu'. Machine type with name 'standard_gpu' does not exist in zone 'us-east1-d'.
</code>```

答:
It is now possible to create datalab instances with GPUs:
https://cloud.google.com/datalab/docs/reference/command-line/create</p>

```<code>datalab beta create-gpu datalab-instance-name
</code>```

Body:
I can import tensorflow and run models inside of Cloud Datalab, but how do I configure it to use GPUs?

The documentation here only talks about machines, which I'm not sure how to configure through Datalab:
https://cloud.google.com/ml-engine/docs/how-tos/using-gpus

I've tried this:

datalab create --machine-type standard_gpu ml

and when I select the us-east1 region, I get the error:

Creating the instance ml
ERROR: (gcloud.compute.instances.create) Some requests did not succeed:
- Invalid value for field 'resource.machineType': 'https://www.googleapis.com/compute/v1/projects/project-160204/zones/us-east1-d/machineTypes/standard_gpu'. Machine type with name 'standard_gpu' does not exist in zone 'us-east1-d'.

Body:
It is now possible to create datalab instances with GPUs:
https://cloud.google.com/datalab/docs/reference/command-line/create

datalab beta create-gpu datalab-instance-name


问:
How to get the RGB Code (INT) from an UIColor in Swift
I would like to get the RGB Value of an UIColor in Swift:

```<code>let swiftColor = UIColor(red: 1, green: 165/255, blue: 0, alpha: 1)
println("RGB Value is:");
println(swiftColor.getRGB()); <<<<<< How to do that ?
</code>```

In Java I would do it as follows:

```<code>Color cnew = new Color();
int iColor = cnew.rgb(1, 165/255, 0);
System.out.println(iColor);
</code>```

How should I get this value?

答:
Swift 4. Getting hex code (UInt) from UIColor:</p>

```<code>extension UIColor {
    var coreImageColor: CIColor {
        return CIColor(color: self)
    }
    var hex: UInt {
        let red = UInt(coreImageColor.red * 255 + 0.5)
        let green = UInt(coreImageColor.green * 255 + 0.5)
        let blue = UInt(coreImageColor.blue * 255 + 0.5)
        return (red << 16) | (green << 8) | blue
    }
}
</code>```

Body:
I would like to get the RGB Value of an UIColor in Swift:

let swiftColor = UIColor(red: 1, green: 165/255, blue: 0, alpha: 1)
println("RGB Value is:");
println(swiftColor.getRGB()); <<<<<< How to do that ?

In Java I would do it as follows:

Color cnew = new Color();
int iColor = cnew.rgb(1, 165/255, 0);
System.out.println(iColor);

How should I get this value?

Body:
Swift 4. Getting hex code (UInt) from UIColor:

extension UIColor {
    var coreImageColor: CIColor {
        return CIColor(color: self)
    }
    var hex: UInt {
        let red = UInt(coreImageColor.red * 255 + 0.5)
        let green = UInt(coreImageColor.green * 255 + 0.5)
        let blue = UInt(coreImageColor.blue * 255 + 0.5)
        return (red << 16) | (green << 8) | blue
    }
}


问:
Hystrix command key decision, Service Name+Instance IP+Api Name?
I want to implement Hystrix in gateway(like zuul).
The gateway will discover service A, B or C, assume the service A has 10 instances and 10 Api. My question is.

What is the best practice for the command key decision? Service Name+Instance IP+Api Name.

it seems this gain the best detail level, as the different api, different instance fail will not circle break the other, But it may occupy large volume of command key.

Here is the example. Suppose I talk to service A, there are 5 instances of service A, I talk to service A with a load balancer, and the ip as below

192.168.1.1

192.168.1.2

192.168.1.3

192.168.1.4

192.168.1.5

and service A has 4 api, like

createOrder

deleteOrder

updateOrder

getOrder

Now there are many options for the command key choosen.

serivce level, like serviceA

instance level, like 192.168.1.1

instance + api level like 192.168.1.1_getOrder

for the first option, there are only one hystrix command, it take less cpu or memory, but if one api fail, all api are circle breaks.

答:
Your HystrixCommandKey identifies a HystrixCommand, which encapsulates aService.anOperation(). Thus a HystrixCommandKey could be named using the composite key Service+Command (but not instances running the service or the IP addresses). If you do not provide an explicit name, the class name of HystrixCommand is used as the default HystrixCommandKey.

The Hystrix Dashboard then aggregates metrics for each of the HystrixCommandKey (Service+Command), from each instance running in the service cluster.

In your example, it would be serviceA_createOrder.