问:
Javascript: create UTF-16 text file?
I have some string need to be a UTF-16 text file. For example:

```<code>var s = "aosjdfkzlzkdoaslckjznx";
var file = "data:text/plain;base64," + btoa(s);
</code>```

This will result a UTF-8 encoding text file. How can I get a UTF-16 text file with string s?

答:
Related: Javascript to csv export encoding issue

This should do it:

document.getElementById('download').addEventListener('click', function(){

 downloadUtf16('Hello, World', 'myFile.csv')
});

function downloadUtf16(str, filename) {

 // ref: https://stackoverflow.com/q/6226189
 var charCode, byteArray = [];

 // BE BOM
  byteArray.push(254, 255);

 // LE BOM
  // byteArray.push(255, 254);

  for (var i = 0; i < str.length; ++i) {

    charCode = str.charCodeAt(i);

    // BE Bytes
    byteArray.push((charCode & 0xFF00) >>> 8);
    byteArray.push(charCode & 0xFF);

    // LE Bytes
    // byteArray.push(charCode & 0xff);
    // byteArray.push(charCode / 256 >>> 0);
  }

  var blob = new Blob([new Uint8Array(byteArray)], {type:'text/plain;charset=UTF-16BE;'});
  var blobUrl = URL.createObjectURL(blob);

 // ref: https://stackoverflow.com/a/18197511
  var link = document.createElement('a');
  link.href = blobUrl;
  link.download = filename;

  if (document.createEvent) {
    var event = document.createEvent('MouseEvents');
    event.initEvent('click', true, true);
    link.dispatchEvent(event);
  } else {
    link.click();
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button id="download">Download</button></code>```

Title: Javascript: create UTF-16 text file?

Body:
I have some string need to be a UTF-16 text file. For example:

var s = "aosjdfkzlzkdoaslckjznx";
var file = "data:text/plain;base64," + btoa(s);

This will result a UTF-8 encoding text file. How can I get a UTF-16 text file with string s?

Body:
Related: Javascript to csv export encoding issue

This should do it:

document.getElementById('download').addEventListener('click', function(){

 downloadUtf16('Hello, World', 'myFile.csv')
});

function downloadUtf16(str, filename) {

 // ref: https://stackoverflow.com/q/6226189
 var charCode, byteArray = [];

 // BE BOM
  byteArray.push(254, 255);

 // LE BOM
  // byteArray.push(255, 254);

  for (var i = 0; i < str.length; ++i) {

    charCode = str.charCodeAt(i);

    // BE Bytes
    byteArray.push((charCode & 0xFF00) >>> 8);
    byteArray.push(charCode & 0xFF);

    // LE Bytes
    // byteArray.push(charCode & 0xff);
    // byteArray.push(charCode / 256 >>> 0);
  }

  var blob = new Blob([new Uint8Array(byteArray)], {type:'text/plain;charset=UTF-16BE;'});
  var blobUrl = URL.createObjectURL(blob);

 // ref: https://stackoverflow.com/a/18197511
  var link = document.createElement('a');
  link.href = blobUrl;
  link.download = filename;

  if (document.createEvent) {
    var event = document.createEvent('MouseEvents');
    event.initEvent('click', true, true);
    link.dispatchEvent(event);
  } else {
    link.click();
  }
}

<button id="download">Download</button>


来源: stackexchange

问:
Click other element same as click this element
Sorry for the title may seem confusing.

i have 2 element. with no relation like parent or child.

```<code><div class="alpha"></div>
<div class="beta"></div>
</code>```

The class=alpha have event, if we click it's, there is will be a fade in or fade out element (which is done by jQuery).

now i want to make simulation like. if we click class="beta" it will be the same as we click class="beta".

more details is like if we click beta the alpha will show it's fadein fadeout effect :)

how we can make it?

many thanks

答:
I think you mean "if we click class="beta" it will be the same as we click class="alpha"

If that's the case

```<code>$('div.beta').click(function(){
    $('div.aplha').trigger('click');
});
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Sorry for the title may seem confusing.

i have 2 element. with no relation like parent or child.

The class=alpha have event, if we click it's, there is will be a fade in or fade out element (which is done by jQuery).

now i want to make simulation like. if we click class="beta" it will be the same as we click class="beta".

more details is like if we click beta the alpha will show it's fadein fadeout effect :)

how we can make it?

many thanks

Body:
I think you mean "if we click class="beta" it will be the same as we click class="alpha"

If that's the case

$('div.beta').click(function(){
    $('div.aplha').trigger('click');
});


问:
ReentrantReadWriteLock - why can't reader acquire writer's lock?
In ReentrantReadWriteLock documentation it is said:

```<code>writer can acquire the read lock, but not vice-versa
</code>```

If I understand correctly it means that from the same thread you can execute:

```<code>//thread1
lock.writeLock().lock()
lock.readLock().lock()
print("this line executes")
</code>```

This makes sense: if you already locked write no other thread can enter the locked code. But if you locked read, why can't you enter the write block in the same thread if no other thread make read lock? So this doesn't work:

```<code>//thread1
lock.readLock().lock()
lock.writeLock().lock()
print("this line doesn't execute")
</code>```

Why do you have to unlock the read before locking write in the same thread?

答:
I don't actually know the answer, but it may be to help you avoid writing code that can deadlock.

Suppose you have two threads that execute the same code.  Both threads have acquired a read lock.  Then, both threads attempt to acquire the write lock.  Neither thread will be able to proceed until the other thread releases its read lock, but neither thread will release it's read lock while it's waiting to upgrade.

A different implementation could detect the deadlock, and throw exceptions in both threads when it is discovered, but maybe someone thought that would either (A) adversely impact the performance for applications that do not require deadlock detection, or (B) complicate the API too much.

By disallowing you to upgrade a read lock to a write lock, they've made it impossible for you to write a program that deadlocks in that particular way.

ContentLicense: CC BY-SA 3.0

Body:
In ReentrantReadWriteLock documentation it is said:

writer can acquire the read lock, but not vice-versa

If I understand correctly it means that from the same thread you can execute:

//thread1
lock.writeLock().lock()
lock.readLock().lock()
print("this line executes")

This makes sense: if you already locked write no other thread can enter the locked code. But if you locked read, why can't you enter the write block in the same thread if no other thread make read lock? So this doesn't work:

//thread1
lock.readLock().lock()
lock.writeLock().lock()
print("this line doesn't execute")

Why do you have to unlock the read before locking write in the same thread?


问:
Multiple cell Range as Value
I am new to VBA so please excuse my ignorance :)

I am having trouble writing (and understanding) why my code isn't working in VBA. I am trying to reference multiple cells. My code reads

```<code>    If sheet4.range("G2:G26").value = "" Then
        Sheet4.range("G2:G26").value = "No Gas"
           Exit Sub
               End If
    End Sub
</code>```

I know I cant use multiple cell as value, but how would I write the code? Also, why am i not able to use multiple cell as value? Thanks everyone for the help

答: Thank you everyone for the help. Scott's solution worked perfectly. I am trying to understand the other solutions as well. I really want to be a pro at this.</p>

Title: Multiple cell Range as Value

Body:
I am new to VBA so please excuse my ignorance :)

I am having trouble writing (and understanding) why my code isn't working in VBA. I am trying to reference multiple cells. My code reads

    If sheet4.range("G2:G26").value = "" Then
        Sheet4.range("G2:G26").value = "No Gas"
           Exit Sub
               End If
    End Sub

I know I cant use multiple cell as value, but how would I write the code? Also, why am i not able to use multiple cell as value? Thanks everyone for the help


问:
Prevent generation of empty @XmlType annotation from XSD with JAXB
Let me start with what my question boils down to. I am generating a class named MyServiceResponse from an XSD schema using the maven-jaxb2-plugin. The resulting MyServiceResponse class contains @XmlType annotations with an empty name attribute.

```<code> @XmlAccessorType(XmlAccessType.FIELD)
    @XmlType(name = "", propOrder = {

    })
</code>```

I'd like to either generate MyServiceResponse with filled name attributes OR without @XmlType annotations altogether. Is this possible using a custom binding in a XJB file or in some other way? In any case, I want to solve this during generation if that is possible, because manual edits to MyserviceResponse will get overwritten on every run of the Maven plugin.

Below is a Java class that demonstrates my actual problem. The class uses an XmlStreamReader and JAXB to unmarshall XML messages starting from any element in the message. The 'xml' variable does not get fully unmarshalled. The 'car' property stays null. This happens because the xmlns="http://www.example.com/type" namespace gets copied to the Body element by the XmlStreamReader, but not to the Car child element. Somehow JAXB is unable to see that I want it to continue unmarshalling the Car element. (Big question mark here)

I already know some fixes, but they involve manual changes to the XSD or the MyServiceResponse class.

First, I could set elementFormDefault="qualified" on the XSD from which I generate the MyServiceResponse class, the ObjectFactory and a package-info.java. This works, but it also causes my request XML message to be marshalled with qualified name spaces and this is not accepted by the service that I send the message to. Also, it requires a change in the XSD which I prefer to avoid if possible.

Secondly, setting names on the Body and Car @XmlType annotations works: @XmlType(name = "Body", propOrder = {}) and @XmlType(name = "Car", propOrder = {}). But it involves manually editing MyServiceResponse.

Thirdly, Removing the @XmlType(name = "", propOrder = {}) annotations works, but it also involves manual editing of MyServiceResponse.

This is a copy-pastable demo class:

```<code>import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.*;
import javax.xml.namespace.QName;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import java.io.Reader;
import java.io.StringReader;

public class XmlStreamReaderUnmarshallingTest {

    private static JAXBContext jaxbContext;

    static {
        try {
            jaxbContext = JAXBContext.newInstance(ObjectFactory.class);
        } catch (JAXBException e) {
            e.printStackTrace();
        }
    }

    private static String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
            "<soapenv:Envelope xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" \n" +
            "\txmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" \n" +
            "\txmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\n" +
            "\t<soapenv:Body>\n" +
            "\t\t<response xmlns=\"http://www.example.com/type\">\n" +
            "\t\t\t<type:serviceResponse xmlns:type=\"http://www.example.com/type\">\n" +
            "\t\t\t\t<Body>\n" +
            "\t\t\t\t\t<Car>\n" +
            "\t\t\t\t\t\t<Brand>Mitsubishi</Brand>\n" +
            "\t\t\t\t\t\t<Color>Red</Color>\n" +
            "\t\t\t\t\t</Car>\n" +
            "\t\t\t\t</Body>\n" +
            "\t\t\t</type:serviceResponse>\n" +
            "\t\t</response>\n" +
            "\t</soapenv:Body>\n" +
            "</soapenv:Envelope>";

    private static String xmlStripped = "<type:serviceResponse xmlns:type=\"http://www.example.com/type\">\n" +
            "\t\t\t\t<Body>\n" +
            "\t\t\t\t\t<Car>\n" +
            "\t\t\t\t\t\t<Brand>Mitsubishi</Brand>\n" +
            "\t\t\t\t\t\t<Color>Red</Color>\n" +
            "\t\t\t\t\t</Car>\n" +
            "\t\t\t\t</Body>\n" +
            "\t\t\t</type:serviceResponse>";

    public static void main(String[] args) throws JAXBException, XMLStreamException {
        readXml(xml, "serviceResponse");
        readXml(xmlStripped, "serviceResponse");
    }

    private static void readXml(String inputXml, String startFromElement) throws JAXBException, XMLStreamException {

        final XMLInputFactory xmlInputFactory = XMLInputFactory.newFactory();
        final Reader reader = new StringReader(inputXml);
        final XMLStreamReader xmlStreamReader = xmlInputFactory.createXMLStreamReader(reader);
        final XMLStreamReader streamReader = skipToElement(xmlStreamReader, startFromElement);
        final MyServiceResponse serviceResponse = (MyServiceResponse) unmarshal(streamReader);

        if(serviceResponse.getBody().getCar() == null) {
            System.out.println("It didn't work :-(");
        } else {
            System.out.println("It worked");
        }
    }

    private static XMLStreamReader skipToElement(final XMLStreamReader xsr, final String startAtElement) throws XMLStreamException {
        while (startAtElement != null && xsr.hasNext()) {
            xsr.next();
            if (xsr.hasName()) {
                final String name = xsr.getName().getLocalPart();
                if (name.equals(startAtElement)) {
                    return xsr;
                }
            }
        }

        throw new IllegalArgumentException(String.format("Could not find element %s in response", startAtElement));
    }

    private static Object unmarshal(final XMLStreamReader xsr) throws JAXBException {
        final Object entity = unmarshaller(jaxbContext).unmarshal(xsr);
        return (entity instanceof JAXBElement ? ((JAXBElement) entity).getValue() : entity);
    }

    // Create unmarshaller every time
    private static Unmarshaller unmarshaller(JAXBContext context) throws JAXBException {

        return context.createUnmarshaller();

    }
}

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "MyServiceResponse", propOrder = {

})
class MyServiceResponse {

    @XmlElement(name = "Body")
    protected MyServiceResponse.Body body;

    /**
     * Gets the value of the body property.
     *
     * @return
     *     possible object is
     *     {@link MyServiceResponse.Body }
     *
     */
    public MyServiceResponse.Body getBody() {
        return body;
    }

    /**
     * Sets the value of the body property.
     *
     * @param value
     *     allowed object is
     *     {@link MyServiceResponse.Body }
     *
     */
    public void setBody(MyServiceResponse.Body value) {
        this.body = value;
    }

    /**
     * <p>Java class for anonymous complex type.
     *
     * <p>The following schema fragment specifies the expected content contained within this class.
     *
     * ```
     * <complexType>
     *   <complexContent>
     *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
     *       <all>
     *         <element name="Car" minOccurs="0">
     *           <complexType>
     *             <complexContent>
     *               <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
     *                 <all>
     *                   <element name="Brand" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
     *                   <element name="Color" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
     *                 </all>
     *               </restriction>
     *             </complexContent>
     *           </complexType>
     *         </element>
     *       </all>
     *     </restriction>
     *   </complexContent>
     * </complexType>
     * ```
     *
     *
     */
    @XmlAccessorType(XmlAccessType.FIELD)
    @XmlType(name = "", propOrder = {

    })
    public static class Body {

        @XmlElement(name = "Car")
        protected MyServiceResponse.Body.Car car;

        /**
         * Gets the value of the car property.
         *
         * @return
         *     possible object is
         *     {@link MyServiceResponse.Body.Car }
         *
         */
        public MyServiceResponse.Body.Car getCar() {
            return car;
        }

        /**
         * Sets the value of the car property.
         *
         * @param value
         *     allowed object is
         *     {@link MyServiceResponse.Body.Car }
         *
         */
        public void setCar(MyServiceResponse.Body.Car value) {
            this.car = value;
        }

        /**
         * <p>Java class for anonymous complex type.
         *
         * <p>The following schema fragment specifies the expected content contained within this class.
         *
         * ```
         * <complexType>
         *   <complexContent>
         *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
         *       <all>
         *         <element name="Brand" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
         *         <element name="Color" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
         *       </all>
         *     </restriction>
         *   </complexContent>
         * </complexType>
         * ```
         *
         *
         */
        @XmlAccessorType(XmlAccessType.FIELD)
        @XmlType(name = "", propOrder = {

        })
        public static class Car {

            @XmlElement(name = "Brand")
            protected String brand;
            @XmlElement(name = "Color")
            protected String color;

            /**
             * Gets the value of the brand property.
             *
             * @return
             *     possible object is
             *     {@link String }
             *
             */
            public String getBrand() {
                return brand;
            }

            /**
             * Sets the value of the brand property.
             *
             * @param value
             *     allowed object is
             *     {@link String }
             *
             */
            public void setBrand(String value) {
                this.brand = value;
            }

            /**
             * Gets the value of the color property.
             *
             * @return
             *     possible object is
             *     {@link String }
             *
             */
            public String getColor() {
                return color;
            }

            /**
             * Sets the value of the color property.
             *
             * @param value
             *     allowed object is
             *     {@link String }
             *
             */
            public void setColor(String value) {
                this.color = value;
            }

        }

    }

}

@XmlRegistry
class ObjectFactory {

    private final static QName _ServiceResponse_QNAME = new QName("http://www.example.com/type", "serviceResponse");

    /**
     * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: com.example.type
     *
     */
    public ObjectFactory() {
    }

    /**
     * Create an instance of {@link MyServiceResponse }
     *
     */
    public MyServiceResponse createMyServiceResponse() {
        return new MyServiceResponse();
    }

    /**
     * Create an instance of {@link MyServiceResponse.Body }
     *
     */
    public MyServiceResponse.Body createMyServiceResponseBody() {
        return new MyServiceResponse.Body();
    }

    /**
     * Create an instance of {@link MyServiceResponse.Body.Car }
     *
     */
    public MyServiceResponse.Body.Car createMyServiceResponseBodyCar() {
        return new MyServiceResponse.Body.Car();
    }

    /**
     * Create an instance of {@link JAXBElement }{@code <}{@link MyServiceResponse }{@code >}}
     *
     */
    @XmlElementDecl(namespace = "http://www.example.com/type", name = "serviceResponse")
    public JAXBElement<MyServiceResponse> createServiceResponse(MyServiceResponse value) {
        return new JAXBElement<MyServiceResponse>(_ServiceResponse_QNAME, MyServiceResponse.class, null, value);
    }

}
</code>```

My XSD:

```<code><?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns="http://www.example.com/type"
           targetNamespace="http://www.example.com/type" elementFormDefault="qualified" >
    <xs:element name="serviceResponse" type="MyServiceResponse"/>
    <xs:complexType name="MyServiceResponse">
        <xs:all>
            <xs:element name="Body" minOccurs="0">
                <xs:complexType>
                    <xs:all>
                        <xs:element name="Car" minOccurs="0">
                            <xs:complexType>
                                <xs:all>
                                    <xs:element name="Brand" type="xs:string" minOccurs="0"/>
                                    <xs:element name="Color" type="xs:string" minOccurs="0"/>
                                </xs:all>
                            </xs:complexType>
                        </xs:element>
                    </xs:all>
                </xs:complexType>
            </xs:element>
        </xs:all>
    </xs:complexType>
</xs:schema>
</code>```

Added:

This is the XML that is in the XmlStreamReader when it starts unmarshalling. JAXB unmarshalls the ServiceResponse element, the Body, but not Car.

```<code><type:serviceResponse xmlns:type="http://www.example.com/type">
    <Body xmlns="http://www.example.com/type">
        <Car>
            <Brand>Mitsubishi</Brand>
            <Color>Red</Color>
        </Car>
    </Body>
</type:serviceResponse>
</code>```

答:
@XmlType name's attribute is empty because Car and Body are anonymous types. (http://docs.oracle.com/javaee/5/api/javax/xml/bind/annotation/XmlType.html)

Create complexTypes in the global namespace and use them as the type of the element. (Small snippet)

```<code><xs:element name="Body" type="Body" minOccurs="0" />
<xs:complexType name="Body">
</code>```

Or create a JAXB binding like this: https://www.ibm.com/developerworks/library/ws-avoid-anonymous-types/#N100BB

Transformed XSD:

```<code><?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns="http://www.example.com/type"
    targetNamespace="http://www.example.com/type" elementFormDefault="unqualified" >

    <xs:element name="serviceResponse" type="MyServiceResponse"/>

    <xs:complexType name="MyServiceResponse">
        <xs:all>
            <xs:element name="Body" type="Body" minOccurs="0" />
        </xs:all>
    </xs:complexType>
    <xs:complexType name="Body">
        <xs:all>
            <xs:element name="Car" type="Car" minOccurs="0"/>
        </xs:all>
    </xs:complexType>
    <xs:complexType name="Car">
        <xs:all>
            <xs:element name="Brand" type="xs:string" minOccurs="0"/>
            <xs:element name="Color" type="xs:string" minOccurs="0"/>
        </xs:all>
    </xs:complexType>
</xs:schema>
</code>```

Body:
Let me start with what my question boils down to. I am generating a class named MyServiceResponse from an XSD schema using the maven-jaxb2-plugin. The resulting MyServiceResponse class contains @XmlType annotations with an empty name attribute.

 @XmlAccessorType(XmlAccessType.FIELD)
    @XmlType(name = "", propOrder = {

    })

I'd like to either generate MyServiceResponse with filled name attributes OR without @XmlType annotations altogether. Is this possible using a custom binding in a XJB file or in some other way? In any case, I want to solve this during generation if that is possible, because manual edits to MyserviceResponse will get overwritten on every run of the Maven plugin.

Below is a Java class that demonstrates my actual problem. The class uses an XmlStreamReader and JAXB to unmarshall XML messages starting from any element in the message. The 'xml' variable does not get fully unmarshalled. The 'car' property stays null. This happens because the xmlns="http://www.example.com/type" namespace gets copied to the Body element by the XmlStreamReader, but not to the Car child element. Somehow JAXB is unable to see that I want it to continue unmarshalling the Car element. (Big question mark here)

I already know some fixes, but they involve manual changes to the XSD or the MyServiceResponse class.

First, I could set elementFormDefault="qualified" on the XSD from which I generate the MyServiceResponse class, the ObjectFactory and a package-info.java. This works, but it also causes my request XML message to be marshalled with qualified name spaces and this is not accepted by the service that I send the message to. Also, it requires a change in the XSD which I prefer to avoid if possible.

Secondly, setting names on the Body and Car @XmlType annotations works: @XmlType(name = "Body", propOrder = {}) and @XmlType(name = "Car", propOrder = {}). But it involves manually editing MyServiceResponse.

Thirdly, Removing the @XmlType(name = "", propOrder = {}) annotations works, but it also involves manual editing of MyServiceResponse.

This is a copy-pastable demo class:

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.*;
import javax.xml.namespace.QName;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import java.io.Reader;
import java.io.StringReader;

public class XmlStreamReaderUnmarshallingTest {

    private static JAXBContext jaxbContext;

    static {
        try {
            jaxbContext = JAXBContext.newInstance(ObjectFactory.class);
        } catch (JAXBException e) {
            e.printStackTrace();
        }
    }

    private static String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
            "<soapenv:Envelope xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" \n" +
            "\txmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" \n" +
            "\txmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\n" +
            "\t<soapenv:Body>\n" +
            "\t\t<response xmlns=\"http://www.example.com/type\">\n" +
            "\t\t\t<type:serviceResponse xmlns:type=\"http://www.example.com/type\">\n" +
            "\t\t\t\t\n" +
            "\t\t\t\t\t<Car>\n" +
            "\t\t\t\t\t\t<Brand>Mitsubishi</Brand>\n" +
            "\t\t\t\t\t\t<Color>Red</Color>\n" +
            "\t\t\t\t\t</Car>\n" +
            "\t\t\t\t\n" +
            "\t\t\t</type:serviceResponse>\n" +
            "\t\t</response>\n" +
            "\t</soapenv:Body>\n" +
            "</soapenv:Envelope>";

    private static String xmlStripped = "<type:serviceResponse xmlns:type=\"http://www.example.com/type\">\n" +
            "\t\t\t\t\n" +
            "\t\t\t\t\t<Car>\n" +
            "\t\t\t\t\t\t<Brand>Mitsubishi</Brand>\n" +
            "\t\t\t\t\t\t<Color>Red</Color>\n" +
            "\t\t\t\t\t</Car>\n" +
            "\t\t\t\t\n" +
            "\t\t\t</type:serviceResponse>";

    public static void main(String[] args) throws JAXBException, XMLStreamException {
        readXml(xml, "serviceResponse");
        readXml(xmlStripped, "serviceResponse");
    }

    private static void readXml(String inputXml, String startFromElement) throws JAXBException, XMLStreamException {

        final XMLInputFactory xmlInputFactory = XMLInputFactory.newFactory();
        final Reader reader = new StringReader(inputXml);
        final XMLStreamReader xmlStreamReader = xmlInputFactory.createXMLStreamReader(reader);
        final XMLStreamReader streamReader = skipToElement(xmlStreamReader, startFromElement);
        final MyServiceResponse serviceResponse = (MyServiceResponse) unmarshal(streamReader);

        if(serviceResponse.getBody().getCar() == null) {
            System.out.println("It didn't work :-(");
        } else {
            System.out.println("It worked");
        }
    }

    private static XMLStreamReader skipToElement(final XMLStreamReader xsr, final String startAtElement) throws XMLStreamException {
        while (startAtElement != null && xsr.hasNext()) {
            xsr.next();
            if (xsr.hasName()) {
                final String name = xsr.getName().getLocalPart();
                if (name.equals(startAtElement)) {
                    return xsr;
                }
            }
        }

        throw new IllegalArgumentException(String.format("Could not find element %s in response", startAtElement));
    }

    private static Object unmarshal(final XMLStreamReader xsr) throws JAXBException {
        final Object entity = unmarshaller(jaxbContext).unmarshal(xsr);
        return (entity instanceof JAXBElement ? ((JAXBElement) entity).getValue() : entity);
    }

    // Create unmarshaller every time
    private static Unmarshaller unmarshaller(JAXBContext context) throws JAXBException {

        return context.createUnmarshaller();

    }
}

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "MyServiceResponse", propOrder = {

})
class MyServiceResponse {

    @XmlElement(name = "Body")
    protected MyServiceResponse.Body body;

    /**
     * Gets the value of the body property.
     *
     * @return
     *     possible object is
     *     {@link MyServiceResponse.Body }
     *
     */
    public MyServiceResponse.Body getBody() {
        return body;
    }

    /**
     * Sets the value of the body property.
     *
     * @param value
     *     allowed object is
     *     {@link MyServiceResponse.Body }
     *
     */
    public void setBody(MyServiceResponse.Body value) {
        this.body = value;
    }

    /**
     *
Java class for anonymous complex type.
     *
     *
The following schema fragment specifies the expected content contained within this class.
     *
     *

     * <complexType>
     *   <complexContent>
     *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
     *       <all>
     *         <element name="Car" minOccurs="0">
     *           <complexType>
     *             <complexContent>
     *               <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
     *                 <all>
     *                   <element name="Brand" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
     *                   <element name="Color" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
     *                 </all>
     *               </restriction>
     *             </complexContent>
     *           </complexType>
     *         </element>
     *       </all>
     *     </restriction>
     *   </complexContent>
     * </complexType>
     *

     *
     *
     */
    @XmlAccessorType(XmlAccessType.FIELD)
    @XmlType(name = "", propOrder = {

    })
    public static class Body {

        @XmlElement(name = "Car")
        protected MyServiceResponse.Body.Car car;

        /**
         * Gets the value of the car property.
         *
         * @return
         *     possible object is
         *     {@link MyServiceResponse.Body.Car }
         *
         */
        public MyServiceResponse.Body.Car getCar() {
            return car;
        }

        /**
         * Sets the value of the car property.
         *
         * @param value
         *     allowed object is
         *     {@link MyServiceResponse.Body.Car }
         *
         */
        public void setCar(MyServiceResponse.Body.Car value) {
            this.car = value;
        }

        /**
         *
Java class for anonymous complex type.
         *
         *
The following schema fragment specifies the expected content contained within this class.
         *
         *

         * <complexType>
         *   <complexContent>
         *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
         *       <all>
         *         <element name="Brand" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
         *         <element name="Color" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
         *       </all>
         *     </restriction>
         *   </complexContent>
         * </complexType>
         *

         *
         *
         */
        @XmlAccessorType(XmlAccessType.FIELD)
        @XmlType(name = "", propOrder = {

        })
        public static class Car {

            @XmlElement(name = "Brand")
            protected String brand;
            @XmlElement(name = "Color")
            protected String color;

            /**
             * Gets the value of the brand property.
             *
             * @return
             *     possible object is
             *     {@link String }
             *
             */
            public String getBrand() {
                return brand;
            }

            /**
             * Sets the value of the brand property.
             *
             * @param value
             *     allowed object is
             *     {@link String }
             *
             */
            public void setBrand(String value) {
                this.brand = value;
            }

            /**
             * Gets the value of the color property.
             *
             * @return
             *     possible object is
             *     {@link String }
             *
             */
            public String getColor() {
                return color;
            }

            /**
             * Sets the value of the color property.
             *
             * @param value
             *     allowed object is
             *     {@link String }
             *
             */
            public void setColor(String value) {
                this.color = value;
            }

        }

    }

}

@XmlRegistry
class ObjectFactory {

    private final static QName _ServiceResponse_QNAME = new QName("http://www.example.com/type", "serviceResponse");

    /**
     * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: com.example.type
     *
     */
    public ObjectFactory() {
    }

    /**
     * Create an instance of {@link MyServiceResponse }
     *
     */
    public MyServiceResponse createMyServiceResponse() {
        return new MyServiceResponse();
    }

    /**
     * Create an instance of {@link MyServiceResponse.Body }
     *
     */
    public MyServiceResponse.Body createMyServiceResponseBody() {
        return new MyServiceResponse.Body();
    }

    /**
     * Create an instance of {@link MyServiceResponse.Body.Car }
     *
     */
    public MyServiceResponse.Body.Car createMyServiceResponseBodyCar() {
        return new MyServiceResponse.Body.Car();
    }

    /**
     * Create an instance of {@link JAXBElement }{@code <}{@link MyServiceResponse }{@code >}}
     *
     */
    @XmlElementDecl(namespace = "http://www.example.com/type", name = "serviceResponse")
    public JAXBElement<MyServiceResponse> createServiceResponse(MyServiceResponse value) {
        return new JAXBElement<MyServiceResponse>(_ServiceResponse_QNAME, MyServiceResponse.class, null, value);
    }

}

My XSD:

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns="http://www.example.com/type"
           targetNamespace="http://www.example.com/type" elementFormDefault="qualified" >
    <xs:element name="serviceResponse" type="MyServiceResponse"/>
    <xs:complexType name="MyServiceResponse">
        <xs:all>
            <xs:element name="Body" minOccurs="0">
                <xs:complexType>
                    <xs:all>
                        <xs:element name="Car" minOccurs="0">
                            <xs:complexType>
                                <xs:all>
                                    <xs:element name="Brand" type="xs:string" minOccurs="0"/>
                                    <xs:element name="Color" type="xs:string" minOccurs="0"/>
                                </xs:all>
                            </xs:complexType>
                        </xs:element>
                    </xs:all>
                </xs:complexType>
            </xs:element>
        </xs:all>
    </xs:complexType>
</xs:schema>

Added:

This is the XML that is in the XmlStreamReader when it starts unmarshalling. JAXB unmarshalls the ServiceResponse element, the Body, but not Car.

<type:serviceResponse xmlns:type="http://www.example.com/type">

        <Car>
            <Brand>Mitsubishi</Brand>
            <Color>Red</Color>
        </Car>

</type:serviceResponse>

Body:
@XmlType name's attribute is empty because Car and Body are anonymous types. (http://docs.oracle.com/javaee/5/api/javax/xml/bind/annotation/XmlType.html)

Create complexTypes in the global namespace and use them as the type of the element. (Small snippet)

<xs:element name="Body" type="Body" minOccurs="0" />
<xs:complexType name="Body">

Or create a JAXB binding like this: https://www.ibm.com/developerworks/library/ws-avoid-anonymous-types/#N100BB

Transformed XSD:

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns="http://www.example.com/type"
    targetNamespace="http://www.example.com/type" elementFormDefault="unqualified" >

    <xs:element name="serviceResponse" type="MyServiceResponse"/>

    <xs:complexType name="MyServiceResponse">
        <xs:all>
            <xs:element name="Body" type="Body" minOccurs="0" />
        </xs:all>
    </xs:complexType>
    <xs:complexType name="Body">
        <xs:all>
            <xs:element name="Car" type="Car" minOccurs="0"/>
        </xs:all>
    </xs:complexType>
    <xs:complexType name="Car">
        <xs:all>
            <xs:element name="Brand" type="xs:string" minOccurs="0"/>
            <xs:element name="Color" type="xs:string" minOccurs="0"/>
        </xs:all>
    </xs:complexType>
</xs:schema>


问:
jQuery selector based on deep children text content
This is an example of HTML I am working with.

```<code><html>
    <div class="parent-div">
        <ul>
            <li class="title">Color</li>
            <li>Red</li>
            <li class="title">Shape</li>
            <li>Squared</li>
        </ul>
    </div>
</html>
</code>```

I would like to convert the current HTML in the following list-item

Color: Red

Shape: Squared

And this is what I tried so far:

$("html > div.parent-div > ul > li:contains('Color')")

However it throws an exception:

Uncaught DOMException: Failed to execute 'querySelectorAll' on
  'Document': html > div.parent-div > ul > li:contains('Color')'
  is not a valid selector.

答:
That's because html is the same as document. Leave the html out of the selector.

```<code>$("div.parent-div > ul > li:contains('Color')")
</code>```

The inner working of the jQuery is that it uses document.querySelectorAll. Since document is the root, you don't need to specify it again inside the selector. If you do it will fail because HTML (document) doesn't contain an element called "HTML".

The following snippet will do what you desire.

$("document").ready(function(){
  //select all the list elements with the class title
  $("div.parent-div > ul > li.title").each(function(){
    //concat the text of the title element and the next sibling into one string.
    var text = $(this).text() + ": " + $(this).next().text();
    $(this).html(text); //change the title element's html to set string
    $(this).next().detach(); //delete the value element from the DOM.
  })
 });```
<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>
<html>
    <div class="parent-div">
        <ul>
            <li class="title">Color</li>
            <li>Red</li>
            <li class="title">Shape</li>
            <li>Squared</li>
        </ul>
    </div>
</html></code>```

Body:
This is an example of HTML I am working with.

Color

Red

Shape

Squared

I would like to convert the current HTML in the following list-item

Color: Red

Shape: Squared

And this is what I tried so far:

$("html > div.parent-div > ul > li:contains('Color')")

However it throws an exception:

Uncaught DOMException: Failed to execute 'querySelectorAll' on
  'Document': html > div.parent-div > ul > li:contains('Color')'
  is not a valid selector.

Body:
That's because html is the same as document. Leave the html out of the selector.

$("div.parent-div > ul > li:contains('Color')")

The inner working of the jQuery is that it uses document.querySelectorAll. Since document is the root, you don't need to specify it again inside the selector. If you do it will fail because HTML (document) doesn't contain an element called "HTML".

The following snippet will do what you desire.

$("document").ready(function(){
  //select all the list elements with the class title
  $("div.parent-div > ul > li.title").each(function(){
    //concat the text of the title element and the next sibling into one string.
    var text = $(this).text() + ": " + $(this).next().text();
    $(this).html(text); //change the title element's html to set string
    $(this).next().detach(); //delete the value element from the DOM.
  })
 });

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
    <div class="parent-div">
        <ul>
            <li class="title">Color</li>
            <li>Red</li>
            <li class="title">Shape</li>
            <li>Squared</li>
        </ul>
    </div>
</html>


问:
Create a process to update child record when the parent is updated
You've been given a requirement to keep Contact addresses in sync with the Account they belong to. Use Process Builder to create a new process that updates all child Contact addresses when the address of the Account record is updated. This process:

Can have any name.

Must be activated.

Must update Contact mailing address fields (Street, City, State, Post Code, Country) when the parent Account shipping address field values are updated.

NOTE: You may have to deactivate the validation rule for the Contacts object (created from a previous challenge) in order to complete this challenge.

I developed some Process Builder

And when I check this Process Builder I see the below error:

I have activated this process already, but not working.

答:
This challenge is completed when Contact mailing address fields (Street, City, State, Post Code, Country) are updated on changing the parent Account's shipping address. So to do this I created a Process Builder UpdateChildOnParentUpdate.
And here is the step by step solution.

We have to create Process builder on Account because we checks the changes on Account.

Check if there is any change in the shipping address(Street, City, State, Post Code, Country) of Account and if there is any change in any of them field we set boolean is true.(All these condition are in AND condition).

Finally we update Contact mailing address fields (Street, City, State, Post Code, Country) by taking the reference of its Account(Parent).

Here all the images of process builder according to above steps

Checks if there is any change in shipping address of Account

Update all contact's mailing address attached to updated Account

**Cheers , Salesforce is Awesome !! **


问:
Cannot Compile .CS code in VS 2010
I want to write quick console apps and compile them with VS 2010, but if I create a .cs file, then open it in VS 2010 (by simply double-clicking on the .cs file as these are registered by VS 2010), it opens, but there is no possible way to compile it.

e.g. here is some simplistic code:

```<code>using System;
public class Hello
{
   public static void Main()
   {
      Console.WriteLine("Hello C# World");
   }
}
</code>```

I can compile this from the command line using    csc.exe hello.cs

But, if I can edit it in VS 2010, I should (sensibly) be able to compile it from the VS 2010 interface (plus debug, step through etc). In fact, although I can open and edit, it seems that Microsoft have made it impossible to compile in this way.

Could someone with knowledge of this please explain how to compile a simple .cs file from within the VS 2010 editor please ?

答:
.cs files need to be part of a solution.

What you are looking for is Snippet Complier. This will allow you to compile small files very quickly.
http://www.sliver.com/dotnet/SnippetCompiler/

Title: Cannot Compile .CS code in VS 2010

Body:
I want to write quick console apps and compile them with VS 2010, but if I create a .cs file, then open it in VS 2010 (by simply double-clicking on the .cs file as these are registered by VS 2010), it opens, but there is no possible way to compile it.

e.g. here is some simplistic code:

using System;
public class Hello
{
   public static void Main()
   {
      Console.WriteLine("Hello C# World");
   }
}

I can compile this from the command line using    csc.exe hello.cs

But, if I can edit it in VS 2010, I should (sensibly) be able to compile it from the VS 2010 interface (plus debug, step through etc). In fact, although I can open and edit, it seems that Microsoft have made it impossible to compile in this way.

Could someone with knowledge of this please explain how to compile a simple .cs file from within the VS 2010 editor please ?


问:
valgrind finds errors passing pointer to function, but no errors when the code is in the same scope
I am wondering why, in this example code, valgrind finds no errors or lost memory:

```<code>#include <stdio.h>
#include <stdlib.h>

int main()
{
   char *str;

   /* Initial memory allocation */
   str = (char *) malloc(8);
   strcpy(str, "example");
   printf("String = %s,  Address = %u\n", str, str);

   /* Reallocating memory */
   str = (char *) realloc(str, 14);
   strcat(str, ".com");
   printf("String = %s,  Address = %u\n", str, str);

   free(str);

   return(0);
}
</code>```

However, when I replace these lines with a function:

```<code>int main() {
   ...
   /* Reallocating memory */
   newstr(str);
   ...
}

void newstr(char *str) {
   str = (char *) realloc(str, 14);
   strcat(str, ".com");
}
</code>```

I am getting 19 errors on valgrind, complaining mostly about invalid reads. However, the program executes and outputs everything the same, without an error. Is there something going on when I pass str into the function that happens in memory that valgrind is notifying me of? What can I do to fix this? How can I learn more about this behavior and what the implications are?

This is the output of the program in either case:

```<code>String = example,  Address = 16445456
String = example.com,  Address = 16445456
</code>```

答:
Passing by reference allows you to , among other things, change the referred-to value inside the function. You can do this with a pointer

But in

```<code>void newstr(char *str) {
   str = (char *) realloc(str, 25); <-- changed the pointer
   strcat(str, ".com");
}
</code>```

the value altered inside the function IS the pointer. So you must pass the pointer by reference (or return the altered pointer as shown by BayK)

```<code>void newstr(char *& str) {
   str = (char *) realloc(str, 25);
   strcat(str, ".com");
}
</code>```

Or you can embrace the power of this fully armed and operational C++ programming language and use a std::string.

```<code>#include <iostream>
#include <string>
int main()
{
    std::string str = "example";

    std::cout << "String = " << str << ",  Address = "  << &str << "\n";
    str += ".com";
    std::cout << "String = " << str << ",  Address = "  << &str << "\n";
    return(0);
}
</code>```

Body:
I am wondering why, in this example code, valgrind finds no errors or lost memory:

#include <stdio.h>
#include <stdlib.h>

int main()
{
   char *str;

   /* Initial memory allocation */
   str = (char *) malloc(8);
   strcpy(str, "example");
   printf("String = %s,  Address = %u\n", str, str);

   /* Reallocating memory */
   str = (char *) realloc(str, 14);
   strcat(str, ".com");
   printf("String = %s,  Address = %u\n", str, str);

   free(str);

   return(0);
}

However, when I replace these lines with a function:

int main() {
   ...
   /* Reallocating memory */
   newstr(str);
   ...
}

void newstr(char *str) {
   str = (char *) realloc(str, 14);
   strcat(str, ".com");
}

I am getting 19 errors on valgrind, complaining mostly about invalid reads. However, the program executes and outputs everything the same, without an error. Is there something going on when I pass str into the function that happens in memory that valgrind is notifying me of? What can I do to fix this? How can I learn more about this behavior and what the implications are?

This is the output of the program in either case:

String = example,  Address = 16445456
String = example.com,  Address = 16445456

Body:
Passing by reference allows you to , among other things, change the referred-to value inside the function. You can do this with a pointer

But in

void newstr(char *str) {
   str = (char *) realloc(str, 25); <-- changed the pointer
   strcat(str, ".com");
}

the value altered inside the function IS the pointer. So you must pass the pointer by reference (or return the altered pointer as shown by BayK)

void newstr(char *& str) {
   str = (char *) realloc(str, 25);
   strcat(str, ".com");
}

Or you can embrace the power of this fully armed and operational C++ programming language and use a std::string.

#include <iostream>
#include <string>
int main()
{
    std::string str = "example";

    std::cout << "String = " << str << ",  Address = "  << &str << "\n";
    str += ".com";
    std::cout << "String = " << str << ",  Address = "  << &str << "\n";
    return(0);
}


问:
"Facebook error: Application is not visible to this person."
I am using Facebook invite in my IONIC 2 app. I am getting this error, When I click "app invite button" in my app.

"Facebook error: Application is not visible to this person."

Could anyone help me how to fix this issue?

答:
Had the same problem today with exactly the same error message.
I have an ionic 1 app using the appInvite function in the cordova-plugin-facebook4.

It started working again after doing updates of ios and android platforms and plugins.
I can not pinpoint what actually made it work again, but among the plugins I updated were inappbrowser and facebook4.
For facebook4 I actually copied the android source from the github repo to the plugin directory.
Remember to remove and add the platforms after updating the plugins.


问:
using aggregate to generate report based on multiple categories in r
I have a .dbf containing roughly 2.8 million records that contain residential parcel data with a year built category field, a county code field, and a windzone field (for building code restrictions). There are 3  year built categories and 5 wind zones. I need to get the number of parcels for each year built category in each windzone for each county. Basically I have a county (CNTY_ID = 11) with three year built categories (BUILT_CAT = "1" , "2" , "3") each that are also assigned to one of five windspeed categories (WINDSPEED = "100", "110", "120", etc.). I think I need to use the aggregate() function but haven't had any luck. Optimally the generated table would look something like:

```<code>CNTY_ID = 11
                  BUILT_CAT
             1        2        3
WINDSPEED
   100       x        x        x
   120       x        x        x
    .
    .
    .
   150       x        x        x

CNTY_ID = 12
                  BUILT_CAT
             1        2        3
WINDSPEED
   100       x        x        x
   120       x        x        x
    .
    .
    .
   150       x        x        x
</code>```

Is this kind of task possible to accomplish?

答:
What you essentially need is a way to group your data.

I think dplyr is the way to go. You can use aggregate too.

Using dplyr

```<code>library(dplyr)
library(datasets)

temp <- airquality %>%
  group_by(Month, Day) %>%
  summarise(TOT = sum(Ozone))

View(temp)
</code>```

This will give you the data in a normalized format where the data is grouped first by Month and then by Day of the month and then sums the provided variable. Ozone in this case. You can also count the values by using length in stead.

Using aggregate

```<code>temp2 <- aggregate(Ozone ~ Month + Day, data = airquality, sum)
View(temp2)
</code>```

The key difference in the approach is the treatment of NA.

Since base R functions do not have a very intuitive treatment of NAs and would add the record whenever it encounters it. As a result in group by the sum fails for that grouped entity and it is dropped from the resultant.

Here is a link to other group by treatments using data.table or ddply. You can also achieve this by plyr or tapply.

Body:
I have a .dbf containing roughly 2.8 million records that contain residential parcel data with a year built category field, a county code field, and a windzone field (for building code restrictions). There are 3  year built categories and 5 wind zones. I need to get the number of parcels for each year built category in each windzone for each county. Basically I have a county (CNTY_ID = 11) with three year built categories (BUILT_CAT = "1" , "2" , "3") each that are also assigned to one of five windspeed categories (WINDSPEED = "100", "110", "120", etc.). I think I need to use the aggregate() function but haven't had any luck. Optimally the generated table would look something like:

CNTY_ID = 11
                  BUILT_CAT
             1        2        3
WINDSPEED
   100       x        x        x
   120       x        x        x
    .
    .
    .
   150       x        x        x

CNTY_ID = 12
                  BUILT_CAT
             1        2        3
WINDSPEED
   100       x        x        x
   120       x        x        x
    .
    .
    .
   150       x        x        x

Is this kind of task possible to accomplish?

Body:
What you essentially need is a way to group your data.

I think dplyr is the way to go. You can use aggregate too.

Using dplyr

library(dplyr)
library(datasets)

temp <- airquality %>%
  group_by(Month, Day) %>%
  summarise(TOT = sum(Ozone))

View(temp)

This will give you the data in a normalized format where the data is grouped first by Month and then by Day of the month and then sums the provided variable. Ozone in this case. You can also count the values by using length in stead.

Using aggregate

temp2 <- aggregate(Ozone ~ Month + Day, data = airquality, sum)
View(temp2)

The key difference in the approach is the treatment of NA.

Since base R functions do not have a very intuitive treatment of NAs and would add the record whenever it encounters it. As a result in group by the sum fails for that grouped entity and it is dropped from the resultant.

Here is a link to other group by treatments using data.table or ddply. You can also achieve this by plyr or tapply.


问:
WordPress: Why Isn't add_rewrite_rule Working?

Goal

A visible URL of:

```<code>/products/building-automation/details/productSKU
</code>```

Should point to the real WordPress page of:

```<code>/products/details/?SKU=productSKU
</code>```

Code

```<code>public function setup_frontend() {

    add_rewrite_rule(
        'products/(building-automation|lighting-controls)/details/([^/]*)',
        'products/details/?SKU=$matches[2]',
        'top'
    );

    // Other code logic...

}
</code>```

From what I can tell, the $matches points to the portions of the regex that are in (), so in the example, $matches[1] would be building-automation, and $matches[2] would be productSKU.

I have tried the flushing the rules, many times. This is being called from inside a class, but that doesn't appear to be the issue. I'm attaching the function to the init event.

What is Happening

I am getting the 404 template. What am I doing wrong?

Edit

Turns out, the second part of the parameter HAS to be index.php. Since I was trying to point to products/..., it broke. So I've updated to this:

```<code>    add_rewrite_rule(
        'products/(building-automation|lighting-controls)/details/([^/]*)',
        '?pagename=products/details&SKU=$matches[2]',
        'top'
    );
</code>```

It's not working and point to the right page and template. However, the $matches part is still not coming through. In fact, $_GET['SKU'] is coming through as '$matches[2]'.

答:
The first problem is that it's pointing to something that doesn't start with index.php. It has to point to index.php?stuff, unfortunately. But you can still use the page name, as shown below.

```<code>add_rewrite_rule(
    'products/(building-automation|lighting-controls)/details/([^/]*)',
    'index.php?pagename=products/details&SKU=$matches[2]',
    'top'
);
</code>```

Second, you need to register your query string, which is SKU. Add this:

```<code>add_filter( 'query_vars', 'product_details_rewrite_filter' );

function product_details_rewrite_filter( $query_vars ){
    $query_vars[] = 'SKU';
    return $query_vars;
}
</code>```

You will still have a problem. $_GET['SKU'] will be $matches[2], not RIBU1C. To fix this, change $matches[2] to $2. Then it will work:

```<code>add_rewrite_rule(
    'products/(building-automation|lighting-controls)/details/([^/]*)',
    'index.php?pagename=products/details&SKU=$2',
    'top'
);
</code>```

Body:
Goal

A visible URL of:

/products/building-automation/details/productSKU

Should point to the real WordPress page of:

/products/details/?SKU=productSKU

Code

public function setup_frontend() {

    add_rewrite_rule(
        'products/(building-automation|lighting-controls)/details/([^/]*)',
        'products/details/?SKU=$matches[2]',
        'top'
    );

    // Other code logic...

}

From what I can tell, the $matches points to the portions of the regex that are in (), so in the example, $matches[1] would be building-automation, and $matches[2] would be productSKU.

I have tried the flushing the rules, many times. This is being called from inside a class, but that doesn't appear to be the issue. I'm attaching the function to the init event.

What is Happening

I am getting the 404 template. What am I doing wrong?

Edit

Turns out, the second part of the parameter HAS to be index.php. Since I was trying to point to products/..., it broke. So I've updated to this:

    add_rewrite_rule(
        'products/(building-automation|lighting-controls)/details/([^/]*)',
        '?pagename=products/details&SKU=$matches[2]',
        'top'
    );

It's not working and point to the right page and template. However, the $matches part is still not coming through. In fact, $_GET['SKU'] is coming through as '$matches[2]'.

Body:
The first problem is that it's pointing to something that doesn't start with index.php. It has to point to index.php?stuff, unfortunately. But you can still use the page name, as shown below.

add_rewrite_rule(
    'products/(building-automation|lighting-controls)/details/([^/]*)',
    'index.php?pagename=products/details&SKU=$matches[2]',
    'top'
);

Second, you need to register your query string, which is SKU. Add this:

add_filter( 'query_vars', 'product_details_rewrite_filter' );

function product_details_rewrite_filter( $query_vars ){
    $query_vars[] = 'SKU';
    return $query_vars;
}

You will still have a problem. $_GET['SKU'] will be $matches[2], not RIBU1C. To fix this, change $matches[2] to $2. Then it will work:

add_rewrite_rule(
    'products/(building-automation|lighting-controls)/details/([^/]*)',
    'index.php?pagename=products/details&SKU=$2',
    'top'
);


问:
How to read a string one letter at a time in python
I need to convert a string inputed by a user into morse code. The way our professor wants us to do this is to read from a morseCode.txt file, seperate the letters from the morseCode into two lists, then convert each letter to morse code (inserting a new line when there is a space).

I have the beginning. What it does is reads the morseCode.txt file and seperates the letters into a list [A, B, ... Z] and the codes into a list ['– – . . – –\n', '. – . – . –\n'...].

We haven't learned "sets" yet, so I can't use that. How would I then take the string that they inputed, go through letter by letter, and convert it to morse code? I'm a bit caught up. Here's what I have right now (not much at all...)

EDIT: completed the program!

```<code># open morseCode.txt file to read
morseCodeFile = open('morseCode.txt', 'r') # format is <letter>:<morse code translation><\n>
# create an empty list for letters
letterList = []
# create an empty list for morse codes
codeList = []
# read the first line of the morseCode.txt
line = morseCodeFile.readline()
# while the line is not empty
while line != '':
    # strip the \n from the end of each line
    line = line.rstrip()
    # append the first character of the line to the letterList
    letterList.append(line[0])
    # append the 3rd to last character of the line to the codeList
    codeList.append(line[2:])
    # read the next line
    line = morseCodeFile.readline()
# close the file
morseCodeFile.close()

try:
    # get user input
    print("Enter a string to convert to morse code or press <enter> to quit")
    userInput = input("")
    # while the user inputs something, continue
    while userInput:
        # strip the spaces from their input
        userInput = userInput.replace(' ', '')
        # convert to uppercase
        userInput = userInput.upper()

        # set string accumulator
        accumulateLetters = ''
        # go through each letter of the word
        for x in userInput:
            # get the index of the letterList using x
            index = letterList.index(x)
            # get the morse code value from the codeList using the index found above
            value = codeList[index]
            # accumulate the letter found above
            accumulateLetters += value
        # print the letters
        print(accumulateLetters)
        # input to try again or <enter> to quit
        print("Try again or press <enter> to quit")
        userInput = input("")

except ValueError:
    print("Error in input. Only alphanumeric characters, a comma, and period allowed")
    main()
</code>```

答:
I can't leave this question in this state with that final code in the question hanging over me...

dan: here's a much neater and shorter version of your code. It would be a good idea to look at how this is done and code more this way in future. I realise you probably have no further need of this code, but learning how you should do it is a good idea. Some things to note:

There are only two comments - and even the second is not really necessary for someone familiar with Python, they'll realise NL is being stripped. Only write comments where it adds value.

The with statement (recommended in another answer) removes the bother of closing the file through the context handler.

Use a dictionary instead of two lists.

A generator comprehension ((x for y in z)) is used to do the translation in one line.

Wrap as little code as you can in a try/except block to reduce the probability of catching an exception you didn't mean to.

Use the input() argument rather than print()ing first - Use '\n' to get the new line you want.

Don't write code across multiple lines or with intermediate variables like this just for the sake of it:

```<code>a = a.b()
a = a.c()
b = a.x()
c = b.y()
</code>```

Instead, write these constructs like this, chaining the calls as is perfectly valid:

```<code>a = a.b().c()
c = a.x().y()
</code>```

```<code>code = {}
with open('morseCode.txt', 'r') as morse_code_file:
    # line format is <letter>:<morse code translation>
    for line in morse_code_file:
        line = line.rstrip()  # Remove NL
        code[line[0]] = line[2:]

user_input = input("Enter a string to convert to morse code or press <enter> to quit\n")
while user_input:
    try:
        print(''.join(code[x] for x in user_input.replace(' ', '').upper()))
    except KeyError:
        print("Error in input. Only alphanumeric characters, a comma, and period allowed")

    user_input = input("Try again or press <enter> to quit\n")
</code>```

Body:
I need to convert a string inputed by a user into morse code. The way our professor wants us to do this is to read from a morseCode.txt file, seperate the letters from the morseCode into two lists, then convert each letter to morse code (inserting a new line when there is a space).

I have the beginning. What it does is reads the morseCode.txt file and seperates the letters into a list [A, B, ... Z] and the codes into a list ['– – . . – –\n', '. – . – . –\n'...].

We haven't learned "sets" yet, so I can't use that. How would I then take the string that they inputed, go through letter by letter, and convert it to morse code? I'm a bit caught up. Here's what I have right now (not much at all...)

EDIT: completed the program!

# open morseCode.txt file to read
morseCodeFile = open('morseCode.txt', 'r') # format is <letter>:<morse code translation><\n>
# create an empty list for letters
letterList = []
# create an empty list for morse codes
codeList = []
# read the first line of the morseCode.txt
line = morseCodeFile.readline()
# while the line is not empty
while line != '':
    # strip the \n from the end of each line
    line = line.rstrip()
    # append the first character of the line to the letterList
    letterList.append(line[0])
    # append the 3rd to last character of the line to the codeList
    codeList.append(line[2:])
    # read the next line
    line = morseCodeFile.readline()
# close the file
morseCodeFile.close()

try:
    # get user input
    print("Enter a string to convert to morse code or press <enter> to quit")
    userInput = input("")
    # while the user inputs something, continue
    while userInput:
        # strip the spaces from their input
        userInput = userInput.replace(' ', '')
        # convert to uppercase
        userInput = userInput.upper()

        # set string accumulator
        accumulateLetters = ''
        # go through each letter of the word
        for x in userInput:
            # get the index of the letterList using x
            index = letterList.index(x)
            # get the morse code value from the codeList using the index found above
            value = codeList[index]
            # accumulate the letter found above
            accumulateLetters += value
        # print the letters
        print(accumulateLetters)
        # input to try again or <enter> to quit
        print("Try again or press <enter> to quit")
        userInput = input("")

except ValueError:
    print("Error in input. Only alphanumeric characters, a comma, and period allowed")
    main()

Body:
I can't leave this question in this state with that final code in the question hanging over me...

dan: here's a much neater and shorter version of your code. It would be a good idea to look at how this is done and code more this way in future. I realise you probably have no further need of this code, but learning how you should do it is a good idea. Some things to note:

There are only two comments - and even the second is not really necessary for someone familiar with Python, they'll realise NL is being stripped. Only write comments where it adds value.

The with statement (recommended in another answer) removes the bother of closing the file through the context handler.

Use a dictionary instead of two lists.

A generator comprehension ((x for y in z)) is used to do the translation in one line.

Wrap as little code as you can in a try/except block to reduce the probability of catching an exception you didn't mean to.

Use the input() argument rather than print()ing first - Use '\n' to get the new line you want.

Don't write code across multiple lines or with intermediate variables like this just for the sake of it:

a = a.b()
a = a.c()
b = a.x()
c = b.y()

Instead, write these constructs like this, chaining the calls as is perfectly valid:

a = a.b().c()
c = a.x().y()

code = {}
with open('morseCode.txt', 'r') as morse_code_file:
    # line format is <letter>:<morse code translation>
    for line in morse_code_file:
        line = line.rstrip()  # Remove NL
        code[line[0]] = line[2:]

user_input = input("Enter a string to convert to morse code or press <enter> to quit\n")
while user_input:
    try:
        print(''.join(code[x] for x in user_input.replace(' ', '').upper()))
    except KeyError:
        print("Error in input. Only alphanumeric characters, a comma, and period allowed")

    user_input = input("Try again or press <enter> to quit\n")


问:
How to Implement Keyboard Interrupt in Python
I'm writing a port scanning program in python everything works fine but I wanted to implement crtl+c interrupt function to terminate the program it stops the main program but there are threads still running. How to terminate the program completely using the ctrl+c keys?</p>

```<code>class StatusChecker(threading.Thread):
    """
    The thread that will check HTTP statuses.
    """

    #: The queue of urls
    url_queue = None

    #: The queue our results will go into
    result_queue = None

    #: An event that tells the thread to stop
    stopper = None

    def __init__(self, url_queue, result_queue, stopper):
        super().__init__()
        self.url_queue = url_queue
        self.result_queue = result_queue
        self.stopper = stopper

    def run(self):
        print_lock = threading.Lock()
        while not self.stopper.is_set():
            try:
                # this will throw queue.Empty immediately if there's
                # no tasks left
                to_check = self.url_queue.get_nowait()
            except queue.Empty:
                break # empty queue, we're done!
            else:
                with print_lock:
                    print(to_check,' ')
                self.url_queue.task_done() # the the queue we're done

class SignalHandler:
    """
    The object that will handle signals and stop the worker threads.
    """

    #: The stop event that's shared by this handler and threads.
    stopper = None

    #: The pool of worker threads
    workers = None

    def __init__(self, stopper, workers):
        self.stopper = stopper
        self.workers = workers

    def __call__(self, signum, frame):
        """
        This will be called by the python signal module

        https://docs.python.org/3/library/signal.html#signal.signal
        """
        self.stopper.set()

        for worker in self.workers:
            worker.join()

        sys.exit(0)

if __name__ == '__main__':
    # all the variables we'll need
    num_workers = 2
    stopper = threading.Event()
    result_queue = queue.Queue()
    url_queue = queue.Queue()

    # populate our work queue
    for i in range(65535):
        url_queue.put(i)

    # we need to keep track of the workers but not start them yet
    workers = [StatusChecker(url_queue, result_queue, stopper) for i in range(num_workers)]

    # create our signal handler and connect it
    #handler = SignalHandler(stopper, workers)
    #signal.signal(signal.SIGINT, handler)

    # start the threads!
    for i, worker in enumerate(workers):
        print('Starting worker {}'.format(i))
        worker.daemon = True
        worker.start()

    # wait for the queue to empty
    try:
        while threading.active_count() > 0:
            time.sleep(0.1)
    except:
        sys.exit(0)
    while not result_queue.empty():
        url, status = result_queue.get_nowait()
        print('{} - {}'.format(url, status))
</code>```

答: Threads share the same memory space as the main process. So technically doing ctrl-c on the main process should deallocate the thread memory. If the threads are in the middle of writing then it could be unsafe, but otherwise it should be ok. Otherwise you can use python's signal library and create a signal handler to trap a SIGINT.</p>

Body:
I'm writing a port scanning program in python everything works fine but I wanted to implement crtl+c interrupt function to terminate the program it stops the main program but there are threads still running. How to terminate the program completely using the ctrl+c keys?

class StatusChecker(threading.Thread):
    """
    The thread that will check HTTP statuses.
    """

    #: The queue of urls
    url_queue = None

    #: The queue our results will go into
    result_queue = None

    #: An event that tells the thread to stop
    stopper = None

    def __init__(self, url_queue, result_queue, stopper):
        super().__init__()
        self.url_queue = url_queue
        self.result_queue = result_queue
        self.stopper = stopper

    def run(self):
        print_lock = threading.Lock()
        while not self.stopper.is_set():
            try:
                # this will throw queue.Empty immediately if there's
                # no tasks left
                to_check = self.url_queue.get_nowait()
            except queue.Empty:
                break # empty queue, we're done!
            else:
                with print_lock:
                    print(to_check,' ')
                self.url_queue.task_done() # the the queue we're done

class SignalHandler:
    """
    The object that will handle signals and stop the worker threads.
    """

    #: The stop event that's shared by this handler and threads.
    stopper = None

    #: The pool of worker threads
    workers = None

    def __init__(self, stopper, workers):
        self.stopper = stopper
        self.workers = workers

    def __call__(self, signum, frame):
        """
        This will be called by the python signal module

        https://docs.python.org/3/library/signal.html#signal.signal
        """
        self.stopper.set()

        for worker in self.workers:
            worker.join()

        sys.exit(0)

if __name__ == '__main__':
    # all the variables we'll need
    num_workers = 2
    stopper = threading.Event()
    result_queue = queue.Queue()
    url_queue = queue.Queue()

    # populate our work queue
    for i in range(65535):
        url_queue.put(i)

    # we need to keep track of the workers but not start them yet
    workers = [StatusChecker(url_queue, result_queue, stopper) for i in range(num_workers)]

    # create our signal handler and connect it
    #handler = SignalHandler(stopper, workers)
    #signal.signal(signal.SIGINT, handler)

    # start the threads!
    for i, worker in enumerate(workers):
        print('Starting worker {}'.format(i))
        worker.daemon = True
        worker.start()

    # wait for the queue to empty
    try:
        while threading.active_count() > 0:
            time.sleep(0.1)
    except:
        sys.exit(0)
    while not result_queue.empty():
        url, status = result_queue.get_nowait()
        print('{} - {}'.format(url, status))


问:
Use Cloud Functions for Firebase HTTPS with GET Method
Can someone tell me how to use firebase-functions.https.onRequest() for GET method?
So the problem is I want to have get url like : /getData/{type}/{id}

I have tried

```<code>exports.getProduct = functions.https.onRequest("/getProduct/{type}/{id}",(request, response) =>{});
</code>```

But its still not working, what I can do with that snippet code is https://firebase-url/getProduct which I cant put some parameter.

答:
The https function trigger setup does not have any path matching baked in, however you can achieve this by using an Express app (as an example) for your HTTPS function:

```<code>var functions = require('firebase-functions');
var express = require('express');

var app = express();
app.get('/:type/:id', (req, res) => {
  res.send(req.params);
});

exports.getProduct = functions.https.onRequest(app);
</code>```

In general you can also simply inspect req.url of the request, it is a path relative to the function name:

```<code>var functions = require('firebase-functions');

exports.getProduct = functions.https.onRequest((req, res) => {
  res.send(req.url);
});
</code>```

In the above function, a GET to /getProduct/foo/bar would have a req.url equal to /foo/bar.

Body:
Can someone tell me how to use firebase-functions.https.onRequest() for GET method?
So the problem is I want to have get url like : /getData/{type}/{id}

I have tried

exports.getProduct = functions.https.onRequest("/getProduct/{type}/{id}",(request, response) =>{});

But its still not working, what I can do with that snippet code is https://firebase-url/getProduct which I cant put some parameter.

Body:
The https function trigger setup does not have any path matching baked in, however you can achieve this by using an Express app (as an example) for your HTTPS function:

var functions = require('firebase-functions');
var express = require('express');

var app = express();
app.get('/:type/:id', (req, res) => {
  res.send(req.params);
});

exports.getProduct = functions.https.onRequest(app);

In general you can also simply inspect req.url of the request, it is a path relative to the function name:

var functions = require('firebase-functions');

exports.getProduct = functions.https.onRequest((req, res) => {
  res.send(req.url);
});

In the above function, a GET to /getProduct/foo/bar would have a req.url equal to /foo/bar.


问:
excel loop thru cells to open pdf
I can get my code to open the selected cells PDF. How can I loop this to run from A9 to finalrow? This is what I have working but only for selected cell.

```<code>Function OpenAnyFile(strPath As String)
Set objShell = CreateObject("Shell.Application")
objShell.Open (strPath)
End Function

Sub Cutsheets()
Application.ScreenUpdating = False
On Error GoTo whoa

Dim ordersheet As Worksheet
Dim I As Integer
Dim finalrow As Integer
Dim pdfPath As String
Set ordersheet = Sheet1

finalrow = Cells(Rows.Count, 1).End(xlUp).Row
pdfPath = "P:\ESO\1790-ORL\OUC\_Materials\Material Cutsheets\" & ActiveCell & ".pdf"

'loop through the rows to find PDFs
For I = 9 To finalrow
    If Cells(I, 1) = Application.Intersect(ActiveCell, Range("A9:A" & finalrow)) Then
    Call OpenAnyFile(pdfPath)
    End If
    ordersheet.Select
Next I

whoa:
Exit Sub

Application.ScreenUpdating = True
End Sub
</code>```

答:
```<code>Sub Cutsheets()
    Application.ScreenUpdating = False
    On Error GoTo whoa

    Dim I As Integer
    Dim finalrow As Integer
    Dim pdfPath As String

    'loop through the rows to find PDFs
    With Sheet1
        finalrow = .Cells(.Rows.Count, 1).End(xlUp).Row
        For I = 9 To finalrow
            pdfPath = "P:\ESO\1790-ORL\OUC\_Materials\Material Cutsheets\" & Cells(I, 1).Value & ".pdf"
            Call OpenAnyFile(pdfPath)
        Next I
    End With

whoa:
    Application.ScreenUpdating = True

End Sub
</code>```

Title: excel loop thru cells to open pdf

Body:
I can get my code to open the selected cells PDF. How can I loop this to run from A9 to finalrow? This is what I have working but only for selected cell.

Function OpenAnyFile(strPath As String)
Set objShell = CreateObject("Shell.Application")
objShell.Open (strPath)
End Function

Sub Cutsheets()
Application.ScreenUpdating = False
On Error GoTo whoa

Dim ordersheet As Worksheet
Dim I As Integer
Dim finalrow As Integer
Dim pdfPath As String
Set ordersheet = Sheet1

finalrow = Cells(Rows.Count, 1).End(xlUp).Row
pdfPath = "P:\ESO\1790-ORL\OUC\_Materials\Material Cutsheets\" & ActiveCell & ".pdf"

'loop through the rows to find PDFs
For I = 9 To finalrow
    If Cells(I, 1) = Application.Intersect(ActiveCell, Range("A9:A" & finalrow)) Then
    Call OpenAnyFile(pdfPath)
    End If
    ordersheet.Select
Next I

whoa:
Exit Sub

Application.ScreenUpdating = True
End Sub


问:
Responsive circles in a row with flexbox
I want to draw 4 circles, being all 4 flex-items, and I need them to scale with the container they are in. I have seen some solutions where padding-bottom is used, but I can´t really understand it.

I managed to get the result that I want with specific width and height in the flex-items. Can anyone do the same but without that and keeping the same structure in my HTML?

This is the fiddle.

.container {
  display: flex;
  flex-wrap: nowrap;
  width: 200px;
  height: 50px;
}
.holder {
  margin-right: 5px;
  width: 30px;
  height: 30px;
  border-radius: 50%;
}
.h1 {
  background: blue;
}
.h2 {
  background: red;
}
.h3 {
  background: green;
}
.h4 {
  background: grey;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="holder h1"></div>
  <div class="holder h2"></div>
  <div class="holder h3"></div>
  <div class="holder h4"></div>
</div></code>```

答:
This can be achieved with viewport units, i.e. "vw".
The width and height of circles can be adjusted in comparison to viewport, if your container is the screen or you can adjust your container in a predictable way.
This works with flex-direction: column.
You can put a text with font-size in vw inside the circle and the text will grow and shrink accordingly.

example

        .flexbox {
            display:flex;
            flex-drection:row;
            justify-content:center;
            align-items:center;
            }

        .item {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            width: 22vw;
            height: 22vw;
            background-color: RGBA(252, 102, 32, 1);
            border-radius: 100%;
            }```
<pre class="snippet-code-html lang-html prettyprint-override"><code>        <div class="flexbox">
        <div class="item">text</div>
        <div class="item">text</div>
        <div class="item">text</div>
        <div class="item">text</div>
        </div></code>```

Body:
This can be achieved with viewport units, i.e. "vw".
The width and height of circles can be adjusted in comparison to viewport, if your container is the screen or you can adjust your container in a predictable way.
This works with flex-direction: column.
You can put a text with font-size in vw inside the circle and the text will grow and shrink accordingly.

example

        .flexbox {
            display:flex;
            flex-drection:row;
            justify-content:center;
            align-items:center;
            }

        .item {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            width: 22vw;
            height: 22vw;
            background-color: RGBA(252, 102, 32, 1);
            border-radius: 100%;
            }

        <div class="flexbox">
        <div class="item">text</div>
        <div class="item">text</div>
        <div class="item">text</div>
        <div class="item">text</div>
        </div>

ContentLicense: CC BY-SA 4.0


问:
Prefilling SMS based on device type (IOS, Android, etc)
I have two buttons on a webpage that allow the user to call or text the displayed record in our database.

```<code><a style="..." href="tel:<%= model.get('phone_alternate').split("-").join("") %>">Make a Call</a>
<a style="..." href="sms:<%= model.get('phone_alternate').split("-").join("") %>">Send a Text</a>
</code>```

I'd like to populate the SMS message using the second button, but since IOS doesn't use the same format as others, using the ?body=message won't work for all of my users (it'd need to be ;body=message instead).

In trying to find a resultion, I came across this page...Prefilling an SMS on Mobile Devices... but don't quite understand how to implement it in my setting.

His code shows:

```<code>var ua = navigator.userAgent.toLowerCase();
var url;

if (ua.indexOf("iphone") > -1 || ua.indexOf("ipad") > -1)
    url = "sms:;body=" + encodeURIComponent("I'm at " + mapUrl + " @ " + pos.Address);
else
    url = "sms:?body=" + encodeURIComponent("I'm at " + mapUrl + " @ " + pos.Address);

location.href = url;
</code>```

...but where would I put this in my page to have it work?

Thanks for your help.

答:
For anyone who stumbles across this question in the future, I was able to accomplish it very easily with...

Send a Text with the ?& allowing it to work on both IOS and Android.

Body:
I have two buttons on a webpage that allow the user to call or text the displayed record in our database.

<a style="..." href="tel:<%= model.get('phone_alternate').split("-").join("") %>">Make a Call
<a style="..." href="sms:<%= model.get('phone_alternate').split("-").join("") %>">Send a Text

I'd like to populate the SMS message using the second button, but since IOS doesn't use the same format as others, using the ?body=message won't work for all of my users (it'd need to be ;body=message instead).

In trying to find a resultion, I came across this page...Prefilling an SMS on Mobile Devices... but don't quite understand how to implement it in my setting.

His code shows:

var ua = navigator.userAgent.toLowerCase();
var url;

if (ua.indexOf("iphone") > -1 || ua.indexOf("ipad") > -1)
    url = "sms:;body=" + encodeURIComponent("I'm at " + mapUrl + " @ " + pos.Address);
else
    url = "sms:?body=" + encodeURIComponent("I'm at " + mapUrl + " @ " + pos.Address);

location.href = url;

...but where would I put this in my page to have it work?

Thanks for your help.

Body:
For anyone who stumbles across this question in the future, I was able to accomplish it very easily with...

<a href="sms:15555555555;?&body=Message%20Text%20Here">Send a Text</a> with the ?& allowing it to work on both IOS and Android.


问:
Selecting from table when two fields satisfy OR condition. And if they satisfy AND condition on same fields select the ones with early date
```ID1  ID2     DATE        INITIAL   FINAL
20   328    2016/11/08    01         01
21   328    2016/11/11    01         01
53   766    2016/09/26    00         01
39   766    2016/11/25    01         00```

There are two entries for each ID2

In the above example I want to select records with INITIAL = 01 or FINAL = 01 but also when INITIAL = 01 and FINAL = 01 for same ID2, I want to select the one with earlier date

I am looking for a final set that looks like this

```ID1  ID2     DATE        INITIAL   FINAL
20   328    2016/11/08    01         01
53   766    2016/09/26    00         01
39   766    2016/11/25    01         00```

答:
in this example 'OR' includes 'AND'

try it

```<code>select * from (select  * from myTable where INITIAL = '01' or FINAL = '01' order by Date) where Rownum=1
</code>```

Body:
ID1  ID2     DATE        INITIAL   FINAL
20   328    2016/11/08    01         01
21   328    2016/11/11    01         01
53   766    2016/09/26    00         01
39   766    2016/11/25    01         00

There are two entries for each ID2

In the above example I want to select records with INITIAL = 01 or FINAL = 01 but also when INITIAL = 01 and FINAL = 01 for same ID2, I want to select the one with earlier date

I am looking for a final set that looks like this

ID1  ID2     DATE        INITIAL   FINAL
20   328    2016/11/08    01         01
53   766    2016/09/26    00         01
39   766    2016/11/25    01         00

Body:
in this example 'OR' includes 'AND'

try it

select * from (select  * from myTable where INITIAL = '01' or FINAL = '01' order by Date) where Rownum=1


问:
Monkey patching a db model class in Rails with Mongoid causes weird behaviour
I am using a development script file to check out new possible ideas. Recently I tried to monkey patch MyDBObject from within that script file.
Assume an empty dev.rb file and add a monkey patch right in the top like so:

```<code>class MyDBObject
  def test_function
    'function works'
  end
end
</code>```

Starting up the pry console and loading the file yields random results.
First I received:

```<code>NoMethodError: undefined method `relations' for MyDBObject:Class
</code>```

Later the script loaded, but I couldn't access the original class any longer:

```<code>undefined method `first' for MyDBObject:Class
</code>```

I noticed that prepending the line:

```<code>MyDBObject
</code>```

right before the monkey patching, the intended functionality is achieved.
This appears to be some sort of lazy loading of the class objects. Can somebody cast some light on this for me please?

答:
Depending on the order in which source files are loaded, you'll either be redefining the entire class, or having your changes replaced.

I highly recommend giving this a read: http://www.justinweiss.com/articles/3-ways-to-monkey-patch-without-making-a-mess/ (TLDR - put your patch in a module and explicitly include it)

Body:
I am using a development script file to check out new possible ideas. Recently I tried to monkey patch MyDBObject from within that script file.
Assume an empty dev.rb file and add a monkey patch right in the top like so:

class MyDBObject
  def test_function
    'function works'
  end
end

Starting up the pry console and loading the file yields random results.
First I received:

NoMethodError: undefined method `relations' for MyDBObject:Class

Later the script loaded, but I couldn't access the original class any longer:

undefined method `first' for MyDBObject:Class

I noticed that prepending the line:

MyDBObject

right before the monkey patching, the intended functionality is achieved.
This appears to be some sort of lazy loading of the class objects. Can somebody cast some light on this for me please?


问:
Python-How to perform operation on a function call?
I am building a function that uses another function I've already defined. The first completed function is get_value_at_location, which tells me the value at the location (a tuple,) inside a list (puzzle.)

Here is the code for that function:

```<code>def get_value_at_location(puzzle,loc):
    val_loc= puzzle[loc[0]][loc[1]]
    return val_loc
</code>```

Now I am trying to build a function called is_valid_solution, which accepts the parameters puzzle (given list,) op (operation to be done ex: + - *,) expected total (outcome we want,) and locations (tuple) to determine if the operation yields the expected outcome and then returns True or False.

Here is the code I've got so you can see what I'm thinking:

```<code>def is_valid_solution(puzzle, op, expected_total, locations):
    loc=location
    if (get_value_at_location(puzzle,loc)) +(op) ==expected_total:
        return True
    else:
        return False
</code>```

example input/output:

([[1]],    '+',    1,  [(0,0)]) →  True

([[1,2],[2,1]],    '-',    1,  [(0,0),(1,0)])   →  True

([[1,2],[2,1]],    '+',    4,  [(0,0),(0,1)])   →  False

Obviously this is in correct, I just don't know the method of doing what I want to do? How can I implement this?

答:
Option A

Instead of attempting to use "+" or "*" as strings, use the operator module.

```<code>> import operator
> operator.add(2, 3)
5
> operator.mul(2, 3)
6
</code>```

You can pass operator.add as the op parameter, then call in your function:

```<code>def apply(a, b, op):
    return op(a, b)

apply(2, 3, operator.add) # 5
</code>```

Option B

Use if to choose the operation by its string name:

```<code>def apply(a, b, op):
    if op == '+':
        return a + b
    if op == '*':
        return a * b

apply(2, 3, '*') # 6
</code>```

Body:
I am building a function that uses another function I've already defined. The first completed function is get_value_at_location, which tells me the value at the location (a tuple,) inside a list (puzzle.)

Here is the code for that function:

def get_value_at_location(puzzle,loc):
    val_loc= puzzle[loc[0]][loc[1]]
    return val_loc

Now I am trying to build a function called is_valid_solution, which accepts the parameters puzzle (given list,) op (operation to be done ex: + - *,) expected total (outcome we want,) and locations (tuple) to determine if the operation yields the expected outcome and then returns True or False.

Here is the code I've got so you can see what I'm thinking:

def is_valid_solution(puzzle, op, expected_total, locations):
    loc=location
    if (get_value_at_location(puzzle,loc)) +(op) ==expected_total:
        return True
    else:
        return False

example input/output:

([[1]],    '+',    1,  [(0,0)]) →  True

([[1,2],[2,1]],    '-',    1,  [(0,0),(1,0)])   →  True

([[1,2],[2,1]],    '+',    4,  [(0,0),(0,1)])   →  False

Obviously this is in correct, I just don't know the method of doing what I want to do? How can I implement this?

Body:
Option A

Instead of attempting to use "+" or "*" as strings, use the operator module.

> import operator
> operator.add(2, 3)
5
> operator.mul(2, 3)
6

You can pass operator.add as the op parameter, then call in your function:

def apply(a, b, op):
    return op(a, b)

apply(2, 3, operator.add) # 5

Option B

Use if to choose the operation by its string name:

def apply(a, b, op):
    if op == '+':
        return a + b
    if op == '*':
        return a * b

apply(2, 3, '*') # 6


问:
Node.js convert 128 bytes of 8 bit integers to string
How in node.js/JS convert big array with 8-bit values like
[28, 27, ... 250] to bignumber representation in string?

Is there a lib for that? I cant find it.

答:
128 BYTES number ? what ? are you trying to count the number of atoms in the universe or something ?

AFAIU javascript can't handle this. And not any other language I now of. Not any lib I know of.Also Buffer can handle only 64 BIT numbers, not bytes. Which is the usual limit to most languages.

You can't do math in such a large value. If this is just a case of comparing values in a faster way than array loops, what you can do is get a string representation in HEX (cause you can treat bytes separately). Here are a way to get the hex representation:

var arrn = [28, 27, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 250];

function bytetohex(byte){
return (byte & 0xFF).toString(16);
}
var n = arrn.reduce((last,curr,ix)=>(ix==1?bytetohex(arrn[0]):last)+bytetohex(curr));
console.log(n);```

Edit

If wall you want is RSA decrypt, you could have asked that in the first place. You would have received a response much more quickly.
There are several libraries available for that.

This question has some links: Javascript RSA decryption using private key

There is more here: RSA encryption/decryption compatible with Javascript and PHP

And there are plenty of resources on the web for that.

Body:
128 BYTES number ? what ? are you trying to count the number of atoms in the universe or something ?

AFAIU javascript can't handle this. And not any other language I now of. Not any lib I know of.Also Buffer can handle only 64 BIT numbers, not bytes. Which is the usual limit to most languages.

You can't do math in such a large value. If this is just a case of comparing values in a faster way than array loops, what you can do is get a string representation in HEX (cause you can treat bytes separately). Here are a way to get the hex representation:

var arrn = [28, 27, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 250];

function bytetohex(byte){
return (byte & 0xFF).toString(16);
}
var n = arrn.reduce((last,curr,ix)=>(ix==1?bytetohex(arrn[0]):last)+bytetohex(curr));
console.log(n);

Edit

If wall you want is RSA decrypt, you could have asked that in the first place. You would have received a response much more quickly.
There are several libraries available for that.

This question has some links: Javascript RSA decryption using private key

There is more here: RSA encryption/decryption compatible with Javascript and PHP

And there are plenty of resources on the web for that.


问:
T-SQL : compare values return occurrences matched
I'm looking to "score" two columns of addresses based on how many characters appear in common.Below is how the data appears and the intended result. Any solutions will be appreciated.

答:
With the help a a Table-Valued-Function and a Cross Apply

Example

```<code>Declare @YourTable table (Address1 varchar(25),Address2 varchar(25))
Insert Into @YourTable values
('123 Foo St','12 Foo'),
('123 Foo St','Bar Street'),
('123 Foo St','321 Foo St'),
('123 Foo St','Bar Lane')

Select A.*
      ,B.*
 From  @YourTable A
 Cross Apply (
               Select Cnt = count(*)
                From (Select Distinct RetSeq,RetVal From [dbo].[udf-Str-Parse-Char](replace(A.Address1,' ',''))) C1
                Join (Select Distinct RetVal From [dbo].[udf-Str-Parse-Char](replace(A.Address2,' ',''))) C2
                  on C1.RetVal=C2.RetVal
             ) B
</code>```

Returns

```<code>Address1    Address2    Cnt
123 Foo St  12 Foo      5
123 Foo St  Bar Street  2
123 Foo St  321 Foo St  8
123 Foo St  Bar Lane    0
</code>```

The UDF if Interested

```<code>CREATE FUNCTION [dbo].[udf-Str-Parse-Char] (@String varchar(max))
Returns Table
As
Return (
    with   cte1(N) As (Select 1 From (Values(1),(1),(1),(1),(1),(1),(1),(1),(1),(1)) N(N)),
           cte2(N) As (Select Top (IsNull(DataLength(@String),0)) Row_Number() over (Order By (Select NULL)) From cte1 a,cte1 b,cte1 c,cte1 d,cte1 e,cte1 f)

    Select RetSeq=N
          ,RetVal=Substring(@String,N,1)
     From  cte2
)
--Max 1 Million Observations
--Select * from [dbo].[udf-Str-Parse-Char]('this is a string')
</code>```

Body:
With the help a a Table-Valued-Function and a Cross Apply

Example

Declare @YourTable table (Address1 varchar(25),Address2 varchar(25))
Insert Into @YourTable values
('123 Foo St','12 Foo'),
('123 Foo St','Bar Street'),
('123 Foo St','321 Foo St'),
('123 Foo St','Bar Lane')

Select A.*
      ,B.*
 From  @YourTable A
 Cross Apply (
               Select Cnt = count(*)
                From (Select Distinct RetSeq,RetVal From [dbo].[udf-Str-Parse-Char](replace(A.Address1,' ',''))) C1
                Join (Select Distinct RetVal From [dbo].[udf-Str-Parse-Char](replace(A.Address2,' ',''))) C2
                  on C1.RetVal=C2.RetVal
             ) B

Returns

Address1    Address2    Cnt
123 Foo St  12 Foo      5
123 Foo St  Bar Street  2
123 Foo St  321 Foo St  8
123 Foo St  Bar Lane    0

The UDF if Interested

CREATE FUNCTION [dbo].[udf-Str-Parse-Char] (@String varchar(max))
Returns Table
As
Return (
    with   cte1(N) As (Select 1 From (Values(1),(1),(1),(1),(1),(1),(1),(1),(1),(1)) N(N)),
           cte2(N) As (Select Top (IsNull(DataLength(@String),0)) Row_Number() over (Order By (Select NULL)) From cte1 a,cte1 b,cte1 c,cte1 d,cte1 e,cte1 f)

    Select RetSeq=N
          ,RetVal=Substring(@String,N,1)
     From  cte2
)
--Max 1 Million Observations
--Select * from [dbo].[udf-Str-Parse-Char]('this is a string')