问:
Create XSL file to pull value of child element
I have this XML file:

```<code><?xml version="1.0" encoding="UTF-8"?>
<wd:Report_Data xmlns:wd="urn:com.workday.report/xxxxxxxxxxxxxxxxx">
  <wd:Report_Entry>
    <wd:EmployerName>ABC Company</wd:EmployerName>
    <wd:EmployeeID>123456789</wd:EmployeeID>
    <wd:FirstName>Jane</wd:FirstName>
    <wd:LastName>Doe</wd:LastName>
    <wd:Email>jane.l.doe@emcins.com</wd:Email>
    <wd:SSN>111-22-3333</wd:SSN>
    <wd:PostalCode>54321</wd:PostalCode>
    <wd:Division>0</wd:Division>
    <wd:Group>Eligible</wd:Group>
    <wd:Country>0</wd:Country>
    <wd:HealthPlan>Non-Health Plan User</wd:HealthPlan>
    <wd:Location wd:Descriptor="Wichita Branch">
        <wd:ID wd:type="WID">zdf238f821r818890f54c9324ee609db</wd:ID>
        <wd:ID wd:type="Location_ID">Wichita Branch</wd:ID>
    </wd:Location>
    <wd:Region wd:Descriptor="Married (United States of America)">
        <wd:ID wd:type="WID">faf237f571f81088909963455816061f</wd:ID>
        <wd:ID wd:type="Marital_Status_ID">Married_United_States_of_America</wd:ID>
    </wd:Region>
    <wd:Store>2017-01-09-08:00</wd:Store>
    <wd:AgeRange>22</wd:AgeRange>
    <wd:BargainingUnit>Established</wd:BargainingUnit>
    <wd:Class wd:Descriptor="Salary">
        <wd:ID wd:type="WID">faf237f471f81567d35c25d274eef713</wd:ID>
        <wd:ID wd:type="Pay_Rate_Type_ID">Salary</wd:ID>
    </wd:Class>
    <wd:CurrentWalking>0</wd:CurrentWalking>
    <wd:Department wd:Descriptor="Human Resources - General">
        <wd:ID wd:type="WID">faf237f671f41589c20f6681d436e539</wd:ID>
        <wd:ID wd:type="Organization_Reference_ID">Human Resources - General</wd:ID>
        <wd:ID wd:type="Cost_Center_Reference_ID">Human Resources - General</wd:ID>
    </wd:Department>
    <wd:Gender wd:Descriptor="Female">
        <wd:ID wd:type="WID">faf571h561f810889012149c7346059p</wd:ID>
        <wd:ID wd:type="Gender_Code">Female</wd:ID>
    </wd:Gender>
    <wd:Status wd:Descriptor="Regular">
        <wd:ID wd:type="WID">fac242f671f8108555784cb0357608cc</wd:ID>
        <wd:ID wd:type="Employee_Type_ID">Regular</wd:ID>
    </wd:Status>
    <wd:BirthDate>1995-02-17-07:00</wd:BirthDate>
    <wd:RelationshipCode>0</wd:RelationshipCode>
    <wd:Address1 wd:Descriptor="1115 Bellflower Dr">
        <wd:ID wd:type="WID">c70dbf571214999732564dah2m1358f8</wd:ID>
    </wd:Address1>
    <wd:City>Des Moines</wd:City>
    <wd:State wd:Descriptor="Iowa">
        <wd:ID wd:type="WID">a9be12393ccd692ea44d58c678ce6c8b</wd:ID>
        <wd:ID wd:type="Country_Region_ID">USA-IA</wd:ID>
        <wd:ID wd:type="ISO_3166-2_Code">IA</wd:ID>
    </wd:State>
    <wd:spouseSId>s123456789</wd:spouseSId>
    <wd:spouseSFirstName>Tom</wd:spouseSFirstName>
    <wd:spouseSLastName>Doe</wd:spouseSLastName>
    <wd:spouseSDob>1990-05-12-08:00</wd:spouseSDob>
    <wd:spouseSPreferredEmail>tdoe@gmail.com</wd:spouseSPreferredEmail>
</wd:Report_Entry>
</wd:Report_Data>
</code>```

I created this XSL file:

```<code><?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:wd="urn:com.workday.report/xxxxxxxxxxxxxxxxx" exclude-result-prefixes="xs"
version="2.0" xmlns:functx="http://www.functx.com">
<xsl:output method="text"/>
<xsl:param name="separator" select="','"/>
<xsl:param name="padding" select="' '"/>
<xsl:param name="spouse" select="'S'"/>
<xsl:variable name="allowednum" select="'0123456789-'"/>
<xsl:variable name="dateFormat" select="'[M01]/[D01]/[Y0001]'"/>
<xsl:variable name="spaces" select="concat('          ','          ','          ','          ','          ','          ','          ','          ','          ','          ','          ','          ','          ','          ')"/>
<xsl:template match="wd:Report_Data">
    <xsl:for-each select="wd:Report_Entry">
        <xsl:value-of select="substring(concat(wd:EmployerName,$spaces),1,13)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:EmployeeID,$spaces),1,9)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:FirstName,$spaces),1,30)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:LastName,$spaces),1,30)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:Email,$spaces),1,30)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:SSN,$spaces),1,11)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:PostalCode,$spaces),1,5)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:JobCode,$spaces),1,9)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:Division,$spaces),1,9)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:Group,$spaces),1,9)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:Country,$spaces),1,30)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:HealthPlan,$spaces),1,30)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:Location/wd:ID[@type='Location_ID']/text(),$spaces),1,50)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:Region,$spaces),1,50)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:Store,$spaces),1,30)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:AgeRange,$spaces),1,3)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:BargainingUnit,$spaces),1,30)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:Class,$spaces),1,30)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:CurrentWalking,$spaces),1,9)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:Department,$spaces),1,50)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:District,$spaces),1,30)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:Facility,$spaces),1,30)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:Gender,$spaces),1,6)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:Status,$spaces),1,30)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:BirthDate,$spaces),1,10)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:TerminationDate,$spaces),1,10)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:RelationshipCode,$spaces),1,1)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:SubscriberID,$spaces),1,9)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:Address1,$spaces),1,50)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:Address2,$spaces),1,50)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:City,$spaces),1,50)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:State,$spaces),1,30)"/>
        <xsl:value-of select="$separator"/>
        <xsl:choose>
            <xsl:when test="wd:spouseSFirstName != ''">
                <xsl:text>
</xsl:text>
                <xsl:value-of select="substring(concat(wd:EmployerName,$spaces),1,13)"/>
                <xsl:value-of select="$separator"/>
                <xsl:value-of select="substring(concat($spouse,wd:EmployeeID,$spaces),1,10)"/>
                <xsl:value-of select="$separator"/>
                <xsl:value-of select="substring(concat(wd:spouseSFirstName,$spaces),1,30)"/>
                <xsl:value-of select="$separator"/>
                <xsl:value-of select="substring(concat(wd:spouseSLastName,$spaces),1,30)"/>
                <xsl:value-of select="$separator"/>
                <xsl:value-of select="substring(concat(wd:spouseSPreferredEmail,$spaces),1,30)"/>
                <xsl:value-of select="$separator"/>
                <xsl:value-of select="$separator"/>
                <xsl:value-of select="$separator"/>
                <xsl:value-of select="$separator"/>
                <xsl:value-of select="$separator"/>
                <xsl:value-of select="$separator"/>
                <xsl:value-of select="$separator"/>
                <xsl:value-of select="$separator"/>
                <xsl:value-of select="$separator"/>
                <xsl:value-of select="$separator"/>
                <xsl:value-of select="$separator"/>
                <xsl:value-of select="$separator"/>
                <xsl:value-of select="$separator"/>
                <xsl:value-of select="$separator"/>
                <xsl:value-of select="$separator"/>
                <xsl:value-of select="$separator"/>
                <xsl:value-of select="$separator"/>
                <xsl:value-of select="$separator"/>
                <xsl:value-of select="$separator"/>
                <xsl:value-of select="$separator"/>
                <xsl:value-of select="substring(concat(wd:spouseSDob,$spaces),1,10)"/>
                <xsl:value-of select="$separator"/>
            </xsl:when>
            <xsl:otherwise>
            </xsl:otherwise>
        </xsl:choose>
        <xsl:text>
</xsl:text>
    </xsl:for-each>
</xsl:template>
</xsl:stylesheet>
</code>```

I need to read the value "Wichita Branch" from wd:Location/wd:ID wd:type="Location_ID".

```<code><wd:Location wd:Descriptor="Wichita Branch">
        <wd:ID wd:type="WID">zdf238f821r818890f54c9324ee609db</wd:ID>
        <wd:ID wd:type="Location_ID">Wichita Branch</wd:ID>
    </wd:Location>
</code>```

I have tried the following with no luck:

```<code><xsl:value-of select="substring(concat(wd:Location,$spaces),1,50)"/>
</code>```

The one above concatenates "faf237f827f810890f85c091c1fe09cc" with "Wichita Branch".  The three below return an empty value.

```<code><xsl:value-of select="substring(concat(wd:Location/ID[@type='Location_ID',$spaces),1,50)"/>

<xsl:value-of select="substring(concat(wd:Location/wd:ID[@type='Location_ID'],$spaces),1,50)"/>

<xsl:value-of select="substring(concat(wd:Location/wd:ID[@type='Location_ID']/text(),$spaces),1,50)"/>
</code>```

I am new to creating XSL files and will admit I copied the basic format of the XSL file from another XSL file created at my company to get started.  I would appreciate help.  Thank you.

答:
It looks like you just have a minor typo in your select attribute. You need to add the wd namespace prefix to the type attribute so it becomes @wd:type.

You should also be able to remove the text() from the XPath since there are aren't any child elements in wd:ID.

Try changing:

```<code><xsl:value-of select="substring(concat(wd:Location/wd:ID[@type='Location_ID']/text(),$spaces),1,50)"/>
</code>```

to:

```<code><xsl:value-of select="substring(concat(wd:Location/wd:ID[@wd:type='Location_ID'],$spaces),1,50)"/>
</code>```

Also, if you're getting strange line breaks in your text output, try adding:

```<code><xsl:strip-space elements="*"/>
</code>```

as a child of xsl:stylesheet.

Body:
I have this XML file:

<?xml version="1.0" encoding="UTF-8"?>
<wd:Report_Data xmlns:wd="urn:com.workday.report/xxxxxxxxxxxxxxxxx">
  <wd:Report_Entry>
    <wd:EmployerName>ABC Company</wd:EmployerName>
    <wd:EmployeeID>123456789</wd:EmployeeID>
    <wd:FirstName>Jane</wd:FirstName>
    <wd:LastName>Doe</wd:LastName>
    <wd:Email>jane.l.doe@emcins.com</wd:Email>
    <wd:SSN>111-22-3333</wd:SSN>
    <wd:PostalCode>54321</wd:PostalCode>
    <wd:Division>0</wd:Division>
    <wd:Group>Eligible</wd:Group>
    <wd:Country>0</wd:Country>
    <wd:HealthPlan>Non-Health Plan User</wd:HealthPlan>
    <wd:Location wd:Descriptor="Wichita Branch">
        <wd:ID wd:type="WID">zdf238f821r818890f54c9324ee609db</wd:ID>
        <wd:ID wd:type="Location_ID">Wichita Branch</wd:ID>
    </wd:Location>
    <wd:Region wd:Descriptor="Married (United States of America)">
        <wd:ID wd:type="WID">faf237f571f81088909963455816061f</wd:ID>
        <wd:ID wd:type="Marital_Status_ID">Married_United_States_of_America</wd:ID>
    </wd:Region>
    <wd:Store>2017-01-09-08:00</wd:Store>
    <wd:AgeRange>22</wd:AgeRange>
    <wd:BargainingUnit>Established</wd:BargainingUnit>
    <wd:Class wd:Descriptor="Salary">
        <wd:ID wd:type="WID">faf237f471f81567d35c25d274eef713</wd:ID>
        <wd:ID wd:type="Pay_Rate_Type_ID">Salary</wd:ID>
    </wd:Class>
    <wd:CurrentWalking>0</wd:CurrentWalking>
    <wd:Department wd:Descriptor="Human Resources - General">
        <wd:ID wd:type="WID">faf237f671f41589c20f6681d436e539</wd:ID>
        <wd:ID wd:type="Organization_Reference_ID">Human Resources - General</wd:ID>
        <wd:ID wd:type="Cost_Center_Reference_ID">Human Resources - General</wd:ID>
    </wd:Department>
    <wd:Gender wd:Descriptor="Female">
        <wd:ID wd:type="WID">faf571h561f810889012149c7346059p</wd:ID>
        <wd:ID wd:type="Gender_Code">Female</wd:ID>
    </wd:Gender>
    <wd:Status wd:Descriptor="Regular">
        <wd:ID wd:type="WID">fac242f671f8108555784cb0357608cc</wd:ID>
        <wd:ID wd:type="Employee_Type_ID">Regular</wd:ID>
    </wd:Status>
    <wd:BirthDate>1995-02-17-07:00</wd:BirthDate>
    <wd:RelationshipCode>0</wd:RelationshipCode>
    <wd:Address1 wd:Descriptor="1115 Bellflower Dr">
        <wd:ID wd:type="WID">c70dbf571214999732564dah2m1358f8</wd:ID>
    </wd:Address1>
    <wd:City>Des Moines</wd:City>
    <wd:State wd:Descriptor="Iowa">
        <wd:ID wd:type="WID">a9be12393ccd692ea44d58c678ce6c8b</wd:ID>
        <wd:ID wd:type="Country_Region_ID">USA-IA</wd:ID>
        <wd:ID wd:type="ISO_3166-2_Code">IA</wd:ID>
    </wd:State>
    <wd:spouseSId>s123456789</wd:spouseSId>
    <wd:spouseSFirstName>Tom</wd:spouseSFirstName>
    <wd:spouseSLastName>Doe</wd:spouseSLastName>
    <wd:spouseSDob>1990-05-12-08:00</wd:spouseSDob>
    <wd:spouseSPreferredEmail>tdoe@gmail.com</wd:spouseSPreferredEmail>
</wd:Report_Entry>
</wd:Report_Data>

I created this XSL file:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:wd="urn:com.workday.report/xxxxxxxxxxxxxxxxx" exclude-result-prefixes="xs"
version="2.0" xmlns:functx="http://www.functx.com">
<xsl:output method="text"/>
<xsl:param name="separator" select="','"/>
<xsl:param name="padding" select="' '"/>
<xsl:param name="spouse" select="'S'"/>
<xsl:variable name="allowednum" select="'0123456789-'"/>
<xsl:variable name="dateFormat" select="'[M01]/[D01]/[Y0001]'"/>
<xsl:variable name="spaces" select="concat('          ','          ','          ','          ','          ','          ','          ','          ','          ','          ','          ','          ','          ','          ')"/>
<xsl:template match="wd:Report_Data">
    <xsl:for-each select="wd:Report_Entry">
        <xsl:value-of select="substring(concat(wd:EmployerName,$spaces),1,13)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:EmployeeID,$spaces),1,9)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:FirstName,$spaces),1,30)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:LastName,$spaces),1,30)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:Email,$spaces),1,30)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:SSN,$spaces),1,11)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:PostalCode,$spaces),1,5)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:JobCode,$spaces),1,9)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:Division,$spaces),1,9)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:Group,$spaces),1,9)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:Country,$spaces),1,30)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:HealthPlan,$spaces),1,30)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:Location/wd:ID[@type='Location_ID']/text(),$spaces),1,50)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:Region,$spaces),1,50)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:Store,$spaces),1,30)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:AgeRange,$spaces),1,3)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:BargainingUnit,$spaces),1,30)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:Class,$spaces),1,30)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:CurrentWalking,$spaces),1,9)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:Department,$spaces),1,50)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:District,$spaces),1,30)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:Facility,$spaces),1,30)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:Gender,$spaces),1,6)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:Status,$spaces),1,30)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:BirthDate,$spaces),1,10)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:TerminationDate,$spaces),1,10)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:RelationshipCode,$spaces),1,1)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:SubscriberID,$spaces),1,9)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:Address1,$spaces),1,50)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:Address2,$spaces),1,50)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:City,$spaces),1,50)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:State,$spaces),1,30)"/>
        <xsl:value-of select="$separator"/>
        <xsl:choose>
            <xsl:when test="wd:spouseSFirstName != ''">
                <xsl:text>
</xsl:text>
                <xsl:value-of select="substring(concat(wd:EmployerName,$spaces),1,13)"/>
                <xsl:value-of select="$separator"/>
                <xsl:value-of select="substring(concat($spouse,wd:EmployeeID,$spaces),1,10)"/>
                <xsl:value-of select="$separator"/>
                <xsl:value-of select="substring(concat(wd:spouseSFirstName,$spaces),1,30)"/>
                <xsl:value-of select="$separator"/>
                <xsl:value-of select="substring(concat(wd:spouseSLastName,$spaces),1,30)"/>
                <xsl:value-of select="$separator"/>
                <xsl:value-of select="substring(concat(wd:spouseSPreferredEmail,$spaces),1,30)"/>
                <xsl:value-of select="$separator"/>
                <xsl:value-of select="$separator"/>
                <xsl:value-of select="$separator"/>
                <xsl:value-of select="$separator"/>
                <xsl:value-of select="$separator"/>
                <xsl:value-of select="$separator"/>
                <xsl:value-of select="$separator"/>
                <xsl:value-of select="$separator"/>
                <xsl:value-of select="$separator"/>
                <xsl:value-of select="$separator"/>
                <xsl:value-of select="$separator"/>
                <xsl:value-of select="$separator"/>
                <xsl:value-of select="$separator"/>
                <xsl:value-of select="$separator"/>
                <xsl:value-of select="$separator"/>
                <xsl:value-of select="$separator"/>
                <xsl:value-of select="$separator"/>
                <xsl:value-of select="$separator"/>
                <xsl:value-of select="$separator"/>
                <xsl:value-of select="$separator"/>
                <xsl:value-of select="substring(concat(wd:spouseSDob,$spaces),1,10)"/>
                <xsl:value-of select="$separator"/>
            </xsl:when>
            <xsl:otherwise>
            </xsl:otherwise>
        </xsl:choose>
        <xsl:text>
</xsl:text>
    </xsl:for-each>
</xsl:template>
</xsl:stylesheet>

I need to read the value "Wichita Branch" from wd:Location/wd:ID wd:type="Location_ID".

<wd:Location wd:Descriptor="Wichita Branch">
        <wd:ID wd:type="WID">zdf238f821r818890f54c9324ee609db</wd:ID>
        <wd:ID wd:type="Location_ID">Wichita Branch</wd:ID>
    </wd:Location>

I have tried the following with no luck:

<xsl:value-of select="substring(concat(wd:Location,$spaces),1,50)"/>

The one above concatenates "faf237f827f810890f85c091c1fe09cc" with "Wichita Branch".  The three below return an empty value.

<xsl:value-of select="substring(concat(wd:Location/ID[@type='Location_ID',$spaces),1,50)"/>

<xsl:value-of select="substring(concat(wd:Location/wd:ID[@type='Location_ID'],$spaces),1,50)"/>

<xsl:value-of select="substring(concat(wd:Location/wd:ID[@type='Location_ID']/text(),$spaces),1,50)"/>

I am new to creating XSL files and will admit I copied the basic format of the XSL file from another XSL file created at my company to get started.  I would appreciate help.  Thank you.

Body:
It looks like you just have a minor typo in your select attribute. You need to add the wd namespace prefix to the type attribute so it becomes @wd:type.

You should also be able to remove the text() from the XPath since there are aren't any child elements in wd:ID.

Try changing:

<xsl:value-of select="substring(concat(wd:Location/wd:ID[@type='Location_ID']/text(),$spaces),1,50)"/>

to:

<xsl:value-of select="substring(concat(wd:Location/wd:ID[@wd:type='Location_ID'],$spaces),1,50)"/>

Also, if you're getting strange line breaks in your text output, try adding:

<xsl:strip-space elements="*"/>

as a child of xsl:stylesheet.


来源: stackexchange

问:
What is the StreamSets architecture?
I am not very clear about the architecture even after going through tutorials. How do we scale streamset in a distributed environment? Let's say, our input data velocity increases from origin then how to ensure that SDC doesn't give performance issues? How many daemons will be running? Will it be Master worker architecture or peer to peer architecture?

If there are multiple daemons running on multiple machines (e.g. one sdc along with one NodeManager in YARN) then how it will show centralized view of data i.e. total record count etc.?

Also please do let me know architecture of Dataflow performance manager. Which all daemons are there in this product?

答:
StreamSets Data Collector (SDC) scales by partitioning the input data. In some cases, this can be done automatically, for example Cluster Batch mode runs SDC as a MapReduce job on the Hadoop / MapR cluster to read Hadoop FS / MapR FS data, while Cluster Streaming mode leverages Kafka partitions and executes SDC as a Spark Streaming application to run as many pipeline instances as there are Kafka partitions.

In other cases, StreamSets can scale by multithreading - for example, the HTTP Server and JDBC Multitable Consumer origins run multiple pipeline instances in separate threads.

In all cases, Dataflow Performance Manager (DPM) can give you a centralized view of the data, including total record count.

ContentLicense: CC BY-SA 3.0

Title: What is the StreamSets architecture?


问:
Python / Jinja2 - Trouble rendering list generated through python using HTML Syntax (Django)
Just learning python, Jinja and all, your help would be great!
 My Python program pulls data and put it into list form. My goal is to display three parts of each line of data in an html table online. I tried to do this by using string replacement and html syntax. The 3 variable are supposed to be under the name, price, and quantity tabs. It came out like this:

Below is how I created the format. I'm sure the way I'm rendering the code writes exactly what I put, which is the html syntax, but I'm unsure of how to input the data so that the html syntax is recognized

```<code>    card_list = []
    card_info = "<tbody> \
                    <tr> \
                        <th scope='row'>1</th> \
                        <td>{0}</td> \
                        <td>{1}</td> \
                        <td>{2}</td> \
                    </tr> \
                 </tbody>".format(card_name, buy_price, quantity)
                # 3 variables are one line of a list of data
    card_list.append(card_info)
    return card_list
</code>```

In Django view.py, I render the list like this:

```<code>from Buylist.buy import get_data
data = get_data(ixalan)
def card_data(request):
    return render(request, 'buylist/basic.html', {'content':data})
</code>```

And the HtML Using Jinja looks like:

```<code>{% extends "buylist/header.html" %}

{% block content %}

    <table class="table">
  <thead class="thead-inverse">
    <tr>
      <th>#</th>
      <th>Name</th>
      <th>Price</th>
      <th>Quantity</th>
    </tr>
  </thead>

      # For loop getting data from card_data is here
  {% for c in card_data %}
    {{c}}
  {% endfor %}
</table>
{% endblock %}
</code>```

I would really appreciate any help! Thanks so much!

答:
It's a good idea to keep your HTML code in templates, and not generate it from Python. You can access nested data structures from Jinja templates, for example tuples or dicts. Here's how you might accomplish this with dictionaries (tuples will probably be easier on memory, but dicts are more readable):

```<code>  {% block content %}
      <table class="table">
    <thead class="thead-inverse">
      <tr>
        <th>#</th>
        <th>Name</th>
        <th>Price</th>
        <th>Quantity</th>
      </tr>
    </thead>

    {% for item in card_data %}
    <tbody>
      <tr>
        <th scope='row'>1</th>
        <td>{{item.name}}</td>
        <td>{{item.price}}</td>
        <td>{{item.quantity}}</td>
      </tr>
    </tbody>
    {% endfor %}
  </table>
  {% endblock %}
</code>```

You can put your data in dicts and pass it in the same way:

```<code>data = [
    {'name': 'Card 1 Name', 'price': 'Card 1 Price', 'quantity': 'Card 1 Quantity'},
    {'name': 'Card 2 Name', 'price': 'Card 2 Price', 'quantity': 'Card 2 Quantity'},
    {'name': 'Card 3 Name', 'price': 'Card 3 Price', 'quantity': 'Card 3 Quantity'},
]

 render(request, 'buylist/basic.html', {'card_data': data})
</code>```

Body:
Just learning python, Jinja and all, your help would be great!
 My Python program pulls data and put it into list form. My goal is to display three parts of each line of data in an html table online. I tried to do this by using string replacement and html syntax. The 3 variable are supposed to be under the name, price, and quantity tabs. It came out like this:

Below is how I created the format. I'm sure the way I'm rendering the code writes exactly what I put, which is the html syntax, but I'm unsure of how to input the data so that the html syntax is recognized

    card_list = []
    card_info = "
 \

 \
                        1	 \
                        {0}	 \
                        {1}	 \
                        {2}	 \

 \

".format(card_name, buy_price, quantity)
                # 3 variables are one line of a list of data
    card_list.append(card_info)
    return card_list

In Django view.py, I render the list like this:

from Buylist.buy import get_data
data = get_data(ixalan)
def card_data(request):
    return render(request, 'buylist/basic.html', {'content':data})

And the HtML Using Jinja looks like:

{% extends "buylist/header.html" %}

{% block content %}

      #
      Name
      Price
      Quantity

      # For loop getting data from card_data is here
  {% for c in card_data %}
    {{c}}
  {% endfor %}

{% endblock %}

I would really appreciate any help! Thanks so much!

Body:
It's a good idea to keep your HTML code in templates, and not generate it from Python. You can access nested data structures from Jinja templates, for example tuples or dicts. Here's how you might accomplish this with dictionaries (tuples will probably be easier on memory, but dicts are more readable):

  {% block content %}
      <table class="table">
    <thead class="thead-inverse">
      <tr>
        <th>#</th>
        <th>Name</th>
        <th>Price</th>
        <th>Quantity</th>
      </tr>
    </thead>

    {% for item in card_data %}
    <tbody>
      <tr>
        <th scope='row'>1</th>
        <td>{{item.name}}</td>
        <td>{{item.price}}</td>
        <td>{{item.quantity}}</td>
      </tr>
    </tbody>
    {% endfor %}
  </table>
  {% endblock %}

You can put your data in dicts and pass it in the same way:

data = [
    {'name': 'Card 1 Name', 'price': 'Card 1 Price', 'quantity': 'Card 1 Quantity'},
    {'name': 'Card 2 Name', 'price': 'Card 2 Price', 'quantity': 'Card 2 Quantity'},
    {'name': 'Card 3 Name', 'price': 'Card 3 Price', 'quantity': 'Card 3 Quantity'},
]

 render(request, 'buylist/basic.html', {'card_data': data})


问:
Simplify overlapping And condition statements
I'm trying to figure out the best way to simplify conditional statements that are of the form:

```<code>if( ( A() && B() ) || ( B() && C() ) || ( C() && D() ) || .... )
{
    code
}
</code>```

The A/B/C/D/etc functions are relatively expensive, so it's not ideal that they could each be called twice.

Two alternatives I've thought of:

```<code>bool a = A();
bool b = B();
bool c = C();
bool d = D();
if( ( a && b ) || ( b && c ) || ( c && d ) || .... )
{
    code
}
</code>```

This version is not ideal because C(), D(), and any additional conditions are evaluated every time even if A() and B() were both true.  In the original version, they wouldn't have been called at all in that case.

```<code>bool b = B();
if( ( A() && b ) )
{
    code
}
else
{
    bool c = C();
    if( ( b && c ) )
    {
        code
    }
    else
    {
        bool d = D();
        if( ( c && D ) )
        {
            code
        }
        else
        {
            ...
        }
    }
}
</code>```

This version avoids any duplicate and unnecessary conditions from being evaluated, but is incredibly verbose and painful to write.

So I'm hopeful that there's some simpler but equally effective way to write it that I'm not thinking of...?

答:
You could use assignment expressions within the if.

```<code>bool b,c;
if (((b = B()) && A()) || ((c = C()) && b) || (c && D()) )    {
    cout << "done";
}
</code>```

As pointed out by @abdullah, one has to take care that due to shortcut evaluation, variable b might not have been initialized when used in the condition after the ||. So the expressions which's result shall be reused later must be on the left hand side of an &&-operator, which might introduce unnecessary evaluations.

A way to avoid this would be to use a tristate logic where the variable "knows" if it has been assigned yet. C++ does not have tristate booleans, but it can be simulated easily through data type int:

```<code>int a = A();
int b=-1;
int c=-1;
int d=-1;

if(
   ( a && (b=B()) ) || ( (b<0?b=B():b) && (c=C()) ) || ( (c<0?c=C():c) && (d=D()) )
   )
{
    cout << "done";
}
</code>```

Body:
I'm trying to figure out the best way to simplify conditional statements that are of the form:

if( ( A() && B() ) || ( B() && C() ) || ( C() && D() ) || .... )
{
    code
}

The A/B/C/D/etc functions are relatively expensive, so it's not ideal that they could each be called twice.

Two alternatives I've thought of:

bool a = A();
bool b = B();
bool c = C();
bool d = D();
if( ( a && b ) || ( b && c ) || ( c && d ) || .... )
{
    code
}

This version is not ideal because C(), D(), and any additional conditions are evaluated every time even if A() and B() were both true.  In the original version, they wouldn't have been called at all in that case.

bool b = B();
if( ( A() && b ) )
{
    code
}
else
{
    bool c = C();
    if( ( b && c ) )
    {
        code
    }
    else
    {
        bool d = D();
        if( ( c && D ) )
        {
            code
        }
        else
        {
            ...
        }
    }
}

This version avoids any duplicate and unnecessary conditions from being evaluated, but is incredibly verbose and painful to write.

So I'm hopeful that there's some simpler but equally effective way to write it that I'm not thinking of...?

Body:
You could use assignment expressions within the if.

bool b,c;
if (((b = B()) && A()) || ((c = C()) && b) || (c && D()) )    {
    cout << "done";
}

As pointed out by @abdullah, one has to take care that due to shortcut evaluation, variable b might not have been initialized when used in the condition after the ||. So the expressions which's result shall be reused later must be on the left hand side of an &&-operator, which might introduce unnecessary evaluations.

A way to avoid this would be to use a tristate logic where the variable "knows" if it has been assigned yet. C++ does not have tristate booleans, but it can be simulated easily through data type int:

int a = A();
int b=-1;
int c=-1;
int d=-1;

if(
   ( a && (b=B()) ) || ( (b<0?b=B():b) && (c=C()) ) || ( (c<0?c=C():c) && (d=D()) )
   )
{
    cout << "done";
}


问:
Delegate with generic type only known at runtime
In my code I have declared an interface as follows:

```<code>interface IGeneric
{
    T GetOfType<T>();
}
</code>```

And I want to invoke the interface's method with a generic type only known at runtime. This is how I do it currently, and it works:

```<code>Type genericArgument = ...
object interfaceImplementation = ...

MethodInfo methodInfo = typeof(IGeneric).GetMethod("GetOfType").MakeGenericMethod(genericArgument);
methodInfo.Invoke(interfaceImplementation, null);
</code>```

but because I have to call this part of code quite often, I would like to cache the method info in a delegate. I tried this delegate definition

```<code>private delegate T GetOfTypeDelegate<T>();
</code>```

and tried to create a delegate using the method info I retrieved like shown above like this:

```<code>GetOfTypeDelegate<?> deleg = (GetOfTypeDelegate<?>) Delegate.CreateDelegate(typeof(GetOfTypeDelegate<?>), methodInfo);
</code>```

but since I don't know the type of the generic argument at compile time, I don't know what to put where I used the ? or how to make this work at all.

Any help is gladly appreciated.

答:
I'd advise having generic and non-generic versions of the method, much like List<T> implements IEnumerable<T> while also explicitly implementing System.Collections.IEnumerable.

"Type known only at runtime" is exactly what generics aren't intended to be used for. The way you're calling this method, you only ever get object out of it anyway. Better to have a real ordinary non-generic method that just returns object.

```<code>   T GetOfType<T>();
   object GetOfType(Type t);
</code>```

You don't even need to worry about overload resolution. There's some extra burden placed on the class implementing the interface, admittedly. But as you've seen, there's going to be a burden somewhere.

Body:
In my code I have declared an interface as follows:

interface IGeneric
{
    T GetOfType<T>();
}

And I want to invoke the interface's method with a generic type only known at runtime. This is how I do it currently, and it works:

Type genericArgument = ...
object interfaceImplementation = ...

MethodInfo methodInfo = typeof(IGeneric).GetMethod("GetOfType").MakeGenericMethod(genericArgument);
methodInfo.Invoke(interfaceImplementation, null);

but because I have to call this part of code quite often, I would like to cache the method info in a delegate. I tried this delegate definition

private delegate T GetOfTypeDelegate<T>();

and tried to create a delegate using the method info I retrieved like shown above like this:

GetOfTypeDelegate<?> deleg = (GetOfTypeDelegate<?>) Delegate.CreateDelegate(typeof(GetOfTypeDelegate<?>), methodInfo);

but since I don't know the type of the generic argument at compile time, I don't know what to put where I used the ? or how to make this work at all.

Any help is gladly appreciated.

Body:
I'd advise having generic and non-generic versions of the method, much like List<T> implements IEnumerable<T> while also explicitly implementing System.Collections.IEnumerable.

"Type known only at runtime" is exactly what generics aren't intended to be used for. The way you're calling this method, you only ever get object out of it anyway. Better to have a real ordinary non-generic method that just returns object.

   T GetOfType<T>();
   object GetOfType(Type t);

You don't even need to worry about overload resolution. There's some extra burden placed on the class implementing the interface, admittedly. But as you've seen, there's going to be a burden somewhere.


问:
Can `mvn compile` be expected to work with multi-module Maven reactor builds?
Can mvn compile be expected to work with multi-module Maven reactor builds?

I am trying to work on a project that uses a reactor/multi-module Maven build.  When mvn compile failed*, I was told by persons familiar with the project that mvn install is needed, and not mvn compile, because it is  a reactor build.

While  mvn install indeed works because Maven can then pull the build dependency out of the local repository, it seems wrong to me that I must publish to the repository since doing so can create problems, especially in CI environments.

However, nearly every example I can find surrounding a multi-module project uses mvn clean install, including Maven by Example.  I have found no examples of mvn compile that I can attribute to multi-module projects, making me inclined to think there is a Maven limitation/requirement here.

I note that mvn compile did work for me with the example provided in Maven by Example, but that  is a relatively simple project so I know I cannot take that to  mean it should work in general.

* It failed because it could not find one of the dependencies that was built successfully earlier in the reactor build.

答: If your multi-module project has interdependencies on each other it is actually quite logical that you need to at least install these dependencies to your local repository before others are compile-able.


问:
TensorFlow: `tf.data.Dataset.from_generator()` does not work with strings on Python 3.x
I need to iterate through large number of image files and feed the data to tensorflow. I created a Dataset back by a generator function that produces the file path names as strings and then transform the string path to image data using map. But it failed as generating string values won't work, as shown below. Is there a fix or work around for this?

```<code>2017-12-07 15:29:05.820708: I tensorflow/core/platform/cpu_feature_guard.cc:137] Your CPU supports instructions that this TensorFlow binary was not compiled to use: SSE4.1 SSE4.2 AVX AVX2 FMA
producing data/miniImagenet/val/n01855672/n0185567200001000.jpg
2017-12-07 15:29:06.009141: W tensorflow/core/framework/op_kernel.cc:1192] Unimplemented: Unsupported object type str
2017-12-07 15:29:06.009215: W tensorflow/core/framework/op_kernel.cc:1192] Unimplemented: Unsupported object type str
     [[Node: PyFunc = PyFunc[Tin=[DT_INT64], Tout=[DT_STRING], token="pyfunc_1"](arg0)]]
Traceback (most recent call last):
  File "/Users/me/.tox/tf2/lib/python3.5/site-packages/tensorflow/python/client/session.py", line 1323, in _do_call
    return fn(*args)
  File "/Users/me/.tox/tf2/lib/python3.5/site-packages/tensorflow/python/client/session.py", line 1302, in _run_fn
    status, run_metadata)
  File "/Users/me/.tox/tf2/lib/python3.5/site-packages/tensorflow/python/framework/errors_impl.py", line 473, in __exit__
    c_api.TF_GetCode(self.status.status))
tensorflow.python.framework.errors_impl.UnimplementedError: Unsupported object type str
     [[Node: PyFunc = PyFunc[Tin=[DT_INT64], Tout=[DT_STRING], token="pyfunc_1"](arg0)]]
     [[Node: IteratorGetNext = IteratorGetNext[output_shapes=[[?,21168]], output_types=[DT_FLOAT], _device="/job:localhost/replica:0/task:0/device:CPU:0"](OneShotIterator)]]
</code>```

The test codes are shown below. It can work correctly with from_tensor_slices or by first putting the the file name list in a tensor. however, either work around would exhaust GPU memory.

```<code>import tensorflow as tf

if __name__ == "__main__":
    file_names = ['data/miniImagenet/val/n01855672/n0185567200001000.jpg',
                  'data/miniImagenet/val/n01855672/n0185567200001005.jpg']
    # note: converting the file list to tensor and returning an index from generator works
    # path_to_indexes = {p: i for i, p in enumerate(file_names)}
    # file_names_tensor = tf.convert_to_tensor(file_names)

    def dataset_producer():
        for s in file_names:
            print('producing', s)
            yield s
    dataset = tf.data.Dataset.from_generator(dataset_producer, output_types=(tf.string),
                                             output_shapes=(tf.TensorShape([])))

    # note: this would also work
    # dataset = tf.data.Dataset.from_tensor_slices(tf.convert_to_tensor(file_names))

    def read_image(filename):
        # filename = file_names_tensor[filename_index]
        image_file = tf.read_file(filename, name='read_file')
        image = tf.image.decode_jpeg(image_file, channels=3)
        image.set_shape((84,84,3))
        image = tf.reshape(image, [21168])
        image = tf.cast(image, tf.float32) / 255.0
        return image

    dataset = dataset.map(read_image)
    dataset = dataset.batch(2)
    data_iterator = dataset.make_one_shot_iterator()
    images = data_iterator.get_next()
    print('images', images)
    max_value = tf.argmax(images)
    with tf.Session() as session:
        result = session.run(max_value)
        print(result)
</code>```

答:
This is a bug affecting Python 3.x that was fixed after the TensorFlow 1.4 release. All releases of TensorFlow from 1.5 onwards contain the fix.

If you just use an earlier version, the workaround is to convert the strings to bytes before returning them from the generator. The following code should work:

```<code>def dataset_producer():
    for s in file_names:
        print('producing', s)
        yield s.encode('utf-8')  # Convert `s` to `bytes`.

dataset = tf.data.Dataset.from_generator(dataset_producer, output_types=(tf.string),
                                         output_shapes=(tf.TensorShape([])))
</code>```

Body:
I need to iterate through large number of image files and feed the data to tensorflow. I created a Dataset back by a generator function that produces the file path names as strings and then transform the string path to image data using map. But it failed as generating string values won't work, as shown below. Is there a fix or work around for this?

2017-12-07 15:29:05.820708: I tensorflow/core/platform/cpu_feature_guard.cc:137] Your CPU supports instructions that this TensorFlow binary was not compiled to use: SSE4.1 SSE4.2 AVX AVX2 FMA
producing data/miniImagenet/val/n01855672/n0185567200001000.jpg
2017-12-07 15:29:06.009141: W tensorflow/core/framework/op_kernel.cc:1192] Unimplemented: Unsupported object type str
2017-12-07 15:29:06.009215: W tensorflow/core/framework/op_kernel.cc:1192] Unimplemented: Unsupported object type str
     [[Node: PyFunc = PyFunc[Tin=[DT_INT64], Tout=[DT_STRING], token="pyfunc_1"](arg0)]]
Traceback (most recent call last):
  File "/Users/me/.tox/tf2/lib/python3.5/site-packages/tensorflow/python/client/session.py", line 1323, in _do_call
    return fn(*args)
  File "/Users/me/.tox/tf2/lib/python3.5/site-packages/tensorflow/python/client/session.py", line 1302, in _run_fn
    status, run_metadata)
  File "/Users/me/.tox/tf2/lib/python3.5/site-packages/tensorflow/python/framework/errors_impl.py", line 473, in __exit__
    c_api.TF_GetCode(self.status.status))
tensorflow.python.framework.errors_impl.UnimplementedError: Unsupported object type str
     [[Node: PyFunc = PyFunc[Tin=[DT_INT64], Tout=[DT_STRING], token="pyfunc_1"](arg0)]]
     [[Node: IteratorGetNext = IteratorGetNext[output_shapes=[[?,21168]], output_types=[DT_FLOAT], _device="/job:localhost/replica:0/task:0/device:CPU:0"](OneShotIterator)]]

The test codes are shown below. It can work correctly with from_tensor_slices or by first putting the the file name list in a tensor. however, either work around would exhaust GPU memory.

import tensorflow as tf

if __name__ == "__main__":
    file_names = ['data/miniImagenet/val/n01855672/n0185567200001000.jpg',
                  'data/miniImagenet/val/n01855672/n0185567200001005.jpg']
    # note: converting the file list to tensor and returning an index from generator works
    # path_to_indexes = {p: i for i, p in enumerate(file_names)}
    # file_names_tensor = tf.convert_to_tensor(file_names)

    def dataset_producer():
        for s in file_names:
            print('producing', s)
            yield s
    dataset = tf.data.Dataset.from_generator(dataset_producer, output_types=(tf.string),
                                             output_shapes=(tf.TensorShape([])))

    # note: this would also work
    # dataset = tf.data.Dataset.from_tensor_slices(tf.convert_to_tensor(file_names))

    def read_image(filename):
        # filename = file_names_tensor[filename_index]
        image_file = tf.read_file(filename, name='read_file')
        image = tf.image.decode_jpeg(image_file, channels=3)
        image.set_shape((84,84,3))
        image = tf.reshape(image, [21168])
        image = tf.cast(image, tf.float32) / 255.0
        return image

    dataset = dataset.map(read_image)
    dataset = dataset.batch(2)
    data_iterator = dataset.make_one_shot_iterator()
    images = data_iterator.get_next()
    print('images', images)
    max_value = tf.argmax(images)
    with tf.Session() as session:
        result = session.run(max_value)
        print(result)

Body:
This is a bug affecting Python 3.x that was fixed after the TensorFlow 1.4 release. All releases of TensorFlow from 1.5 onwards contain the fix.

If you just use an earlier version, the workaround is to convert the strings to bytes before returning them from the generator. The following code should work:

def dataset_producer():
    for s in file_names:
        print('producing', s)
        yield s.encode('utf-8')  # Convert `s` to `bytes`.

dataset = tf.data.Dataset.from_generator(dataset_producer, output_types=(tf.string),
                                         output_shapes=(tf.TensorShape([])))


问:
Differentiating between user scroll and programatic page change in ViewPager
I have a android.support.v4.view.ViewPager in my application and I would like to differentiate between a programmatically-initiated smooth scroll and a user-initiated touch scroll.

I've had a look at ViewPager.OnPageChangeListener and I believe that the answer may lie in there but I'm just not sure how.

答:
I have based myself on the answer mark as correct and in the comments below.

First I analyze how the complete listener behave:

```<code>USER
onPageScrollStateChanged:        1             SCROLL_STATE_DRAGGING
onPageScrollStateChanged:        2             SCROLL_STATE_SETTLING
onPageSelected:              SELECTION
onPageScrollStateChanged:        0             SCROLL_STATE_IDLE

PROGRAMATIC
onPageScrollStateChanged:        2             SCROLL_STATE_SETTLING
onPageSelected:              SELECTION
onPageScrollStateChanged:        0             SCROLL_STATE_IDLE
</code>```

Findings:

As you can see in both cases the events end when the onPageScrollStateChanged move to SCROLL_STATE_IDLE, this means idle is the end of the cycle

The user event is SCROLL_STATE_DRAGGING and then SCROLL_STATE_SETTLING which are 2 states different than only 1 state for the programmatic event SCROLL_STATE_SETTLING

onPageSelected happens before the end of the cycle, but after we are able to determinate if the change was triggered by the user or programmatically, so whatever happened before will tell us in that point if it was the user or not

Solution:

So I use a List<Integer> that is reset every time the cycle ends, and to be able to know if the user triggered the event in the onPageSelected method I check the size of the List. If the size is 2 that means the user scroll the pager.

```<code>abstract class PagerListenerActivity extends AppCompatActivity implements ViewPager.OnPageChangeListener {

    private static final int USER_SCROLL = 2;
    private List<Integer> validator = new ArrayList<>();

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
    }

    @Override
    public void onPageSelected(int position) {
        if (validator.size() == USER_SCROLL) {
            userScroll(position);
        }
    }

    @Override
    public void onPageScrollStateChanged(int state) {
        validator.add(state);
        if (ViewPager.SCROLL_STATE_IDLE == state) {
            validator.clear();
        }

    }

    protected abstract void userScroll(int position);
}
</code>```

Now, this class can conveniently be inherited by another that need it.

Body:
I have based myself on the answer mark as correct and in the comments below.

First I analyze how the complete listener behave:

USER
onPageScrollStateChanged:        1             SCROLL_STATE_DRAGGING
onPageScrollStateChanged:        2             SCROLL_STATE_SETTLING
onPageSelected:              SELECTION
onPageScrollStateChanged:        0             SCROLL_STATE_IDLE

PROGRAMATIC
onPageScrollStateChanged:        2             SCROLL_STATE_SETTLING
onPageSelected:              SELECTION
onPageScrollStateChanged:        0             SCROLL_STATE_IDLE

Findings:

As you can see in both cases the events end when the onPageScrollStateChanged move to SCROLL_STATE_IDLE, this means idle is the end of the cycle

The user event is SCROLL_STATE_DRAGGING and then SCROLL_STATE_SETTLING which are 2 states different than only 1 state for the programmatic event SCROLL_STATE_SETTLING

onPageSelected happens before the end of the cycle, but after we are able to determinate if the change was triggered by the user or programmatically, so whatever happened before will tell us in that point if it was the user or not

Solution:

So I use a List<Integer> that is reset every time the cycle ends, and to be able to know if the user triggered the event in the onPageSelected method I check the size of the List. If the size is 2 that means the user scroll the pager.

abstract class PagerListenerActivity extends AppCompatActivity implements ViewPager.OnPageChangeListener {

    private static final int USER_SCROLL = 2;
    private List<Integer> validator = new ArrayList<>();

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
    }

    @Override
    public void onPageSelected(int position) {
        if (validator.size() == USER_SCROLL) {
            userScroll(position);
        }
    }

    @Override
    public void onPageScrollStateChanged(int state) {
        validator.add(state);
        if (ViewPager.SCROLL_STATE_IDLE == state) {
            validator.clear();
        }

    }

    protected abstract void userScroll(int position);
}

Now, this class can conveniently be inherited by another that need it.

ContentLicense: CC BY-SA 4.0


问:
How to stop on the Sign Up Form when web page performs Postback?
I'm working on my final year project. In which:

I have Login and Signup forms on one page (WebForm):

When user click on anchor Sign Up the DropDown ddlType (hides) and TextBoxes - txtCustName, txtEmail and txtConfirmPassword (Displays) in Javascript client side:

```<code>function signupClick() {
  document.getElementById('divType').style.display = 'block' ? 'none' : 'block';

  document.getElementById('<%=txtCustName.ClientID%>').style.display = 'inherit';
  document.getElementById('<%=txtConfirmPassword.ClientID%>').style.display = 'inherit';

  document.getElementById('<%=btnLogin.ClientID%>').style.display = 'none';
  document.getElementById('<%=btnSignUp.ClientID%>').style.display = 'inherit';

  document.getElementById('lblLogin').style.display = 'inherit';
  document.getElementById('lblSignup').style.display = 'none';
}
</code>```

Login Form:-

And when user click on anchor Login the DropDown ddlType (Displays) and TextBoxes - txtCustName, txtEmail and txtConfirmPassword (Hides) in Javascript client side:

```<code>function loginClick() {
  document.getElementById('divType').style.display = 'none' ? 'block' : 'none';

  document.getElementById('<%=txtCustName.ClientID%>').style.display = 'none';
  document.getElementById('<%=txtConfirmPassword.ClientID%>').style.display = 'none';

  document.getElementById('<%=btnLogin.ClientID%>').style.display = 'inherit';
  document.getElementById('<%=btnSignUp.ClientID%>').style.display = 'none';

  document.getElementById('lblLogin').style.display = 'none';
  document.getElementById('lblSignup').style.display = 'inherit';
}
</code>```

Sign Up Form:-

The .aspx code of anchors and buttons is:

```<code><label id="lblSignup" style="float: right">
    For new account?
  <a href="javascript:;" id="signup" onclick="signupClick()">Sign Up</a>
</label>
  <label id="lblLogin" style="float: right; display: none">
      For existing account?
  <a href="javascript:;" id="login" onclick="loginClick()">Login</a>
  </label>
</div>
<label style="width: 28%">
  <asp:HyperLink ID="hlHome" NavigateUrl="Index.aspx" Text="Home" CssClass="btn btn-default" Width="100%" runat="server" />
</label>
<label style="width: 70%; float: right">
  <asp:Button ID="btnLogin" OnClick="btnLogin_Click" CssClass="btn btn-success" Width="100%" runat="server" Text="Login" />
  <asp:Button ID="btnSignUp" OnClick="btnSignUp_Click" Style="display: none" Width="100%" CssClass="btn btn-primary" runat="server" Text="Sign Up" />
</label>
</code>```

Question:

When user click on button Sign Up the DropDown ddlType (Displays) and TextBoxes - txtCustName, txtEmail and txtConfirmPassword (Hides) but I want to prevent this condition and the sign up form should be shown:

```<code>private void ShowMessage(string msg)
{
    ScriptManager.RegisterStartupScript(this, GetType(), null, "AutoHideAlert('" + msg + "');", true);
}
protected void btnSignUp_Click(object sender, EventArgs e)
{
    string cusname = txtCustName.Text;
    string email = txtEmail.Text;
    string pass = txtPassword.Text;
    string confirm = txtConfirmPassword.Text;

    if (string.IsNullOrEmpty(cusname) || string.IsNullOrEmpty(email) || string.IsNullOrEmpty(pass) || string.IsNullOrEmpty(confirm))
    {
        ShowMessage("Fill all cradentials of customer.");
    }
    else
    {
        //.. Register user

        Response.Redirect("~/CustomerPanel/Dashboard.aspx");
    }
}

--- JavaScript Function ---
function AutoHideAlert(msg) {
  // lblAlert is an asp:Label for displaying alert message
  var al = document.getElementById('<%=lblAlert.ClientID%>');

  al.innerText = msg;

  // alert is a DIV to show message
  $("#alert").fadeTo(3500, 500).slideUp(1500, function () {
      $("#alert").slideUp(500);
  });
}
</code>```

How I can stop it on the Sign Up Form?

Updated:

My problem is when click on Sign Up button it sets to the Login form as like:

答:
Use jquery which is "write less and do more", which is also easy and flexible for hide and show functionality. In the Below example i use simple Html element but you can also use it for asp.net element.

$(document).ready(function(){
sigin();
});

function sigin()
{
$("#Idselection").show();

$("#cutname").hide();
$("#cpass").hide();

}
function signUp()
{
$("#Idselection").hide();

$("#cutname").show();
$("#cpass").show();

}```
<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>

<select id="Idselection">
<option>opt1</option>
<option>opt2</option>
<option>opt3</option>
</select><br/>
<input id="cutname" type='text' placeholder="Customer Name" /><br/>
<input id="email" type='text' placeholder="Email *" /><br/>
<input id="pass" type='text' placeholder="Password *" /><br/>
<input id="cpass" type='text' placeholder="Confirm Password *" /><br/>

<input id="btnsigin" type='Button' onclick="sigin()" value="SignIn"/>
<br/>
<input id="btnsignup" type='Button' onclick="signUp()" value="Sign Up" /><br/></code>```

Body:
I'm working on my final year project. In which:

I have Login and Signup forms on one page (WebForm):

When user click on anchor Sign Up the DropDown ddlType (hides) and TextBoxes - txtCustName, txtEmail and txtConfirmPassword (Displays) in Javascript client side:

function signupClick() {
  document.getElementById('divType').style.display = 'block' ? 'none' : 'block';

  document.getElementById('<%=txtCustName.ClientID%>').style.display = 'inherit';
  document.getElementById('<%=txtConfirmPassword.ClientID%>').style.display = 'inherit';

  document.getElementById('<%=btnLogin.ClientID%>').style.display = 'none';
  document.getElementById('<%=btnSignUp.ClientID%>').style.display = 'inherit';

  document.getElementById('lblLogin').style.display = 'inherit';
  document.getElementById('lblSignup').style.display = 'none';
}

Login Form:-

And when user click on anchor Login the DropDown ddlType (Displays) and TextBoxes - txtCustName, txtEmail and txtConfirmPassword (Hides) in Javascript client side:

function loginClick() {
  document.getElementById('divType').style.display = 'none' ? 'block' : 'none';

  document.getElementById('<%=txtCustName.ClientID%>').style.display = 'none';
  document.getElementById('<%=txtConfirmPassword.ClientID%>').style.display = 'none';

  document.getElementById('<%=btnLogin.ClientID%>').style.display = 'inherit';
  document.getElementById('<%=btnSignUp.ClientID%>').style.display = 'none';

  document.getElementById('lblLogin').style.display = 'none';
  document.getElementById('lblSignup').style.display = 'inherit';
}

Sign Up Form:-

The .aspx code of anchors and buttons is:

    For new account?
  Sign Up

      For existing account?
  Login

  <asp:HyperLink ID="hlHome" NavigateUrl="Index.aspx" Text="Home" CssClass="btn btn-default" Width="100%" runat="server" />

  <asp:Button ID="btnLogin" OnClick="btnLogin_Click" CssClass="btn btn-success" Width="100%" runat="server" Text="Login" />
  <asp:Button ID="btnSignUp" OnClick="btnSignUp_Click" Style="display: none" Width="100%" CssClass="btn btn-primary" runat="server" Text="Sign Up" />

Question:

When user click on button Sign Up the DropDown ddlType (Displays) and TextBoxes - txtCustName, txtEmail and txtConfirmPassword (Hides) but I want to prevent this condition and the sign up form should be shown:

private void ShowMessage(string msg)
{
    ScriptManager.RegisterStartupScript(this, GetType(), null, "AutoHideAlert('" + msg + "');", true);
}
protected void btnSignUp_Click(object sender, EventArgs e)
{
    string cusname = txtCustName.Text;
    string email = txtEmail.Text;
    string pass = txtPassword.Text;
    string confirm = txtConfirmPassword.Text;

    if (string.IsNullOrEmpty(cusname) || string.IsNullOrEmpty(email) || string.IsNullOrEmpty(pass) || string.IsNullOrEmpty(confirm))
    {
        ShowMessage("Fill all cradentials of customer.");
    }
    else
    {
        //.. Register user

        Response.Redirect("~/CustomerPanel/Dashboard.aspx");
    }
}

--- JavaScript Function ---
function AutoHideAlert(msg) {
  // lblAlert is an asp:Label for displaying alert message
  var al = document.getElementById('<%=lblAlert.ClientID%>');

  al.innerText = msg;

  // alert is a DIV to show message
  $("#alert").fadeTo(3500, 500).slideUp(1500, function () {
      $("#alert").slideUp(500);
  });
}

How I can stop it on the Sign Up Form?

Updated:

My problem is when click on Sign Up button it sets to the Login form as like:

Body:
Use jquery which is "write less and do more", which is also easy and flexible for hide and show functionality. In the Below example i use simple Html element but you can also use it for asp.net element.

$(document).ready(function(){
sigin();
});

function sigin()
{
$("#Idselection").show();

$("#cutname").hide();
$("#cpass").hide();

}
function signUp()
{
$("#Idselection").hide();

$("#cutname").show();
$("#cpass").show();

}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<select id="Idselection">
<option>opt1</option>
<option>opt2</option>
<option>opt3</option>
</select><br/>
<input id="cutname" type='text' placeholder="Customer Name" /><br/>
<input id="email" type='text' placeholder="Email *" /><br/>
<input id="pass" type='text' placeholder="Password *" /><br/>
<input id="cpass" type='text' placeholder="Confirm Password *" /><br/>

<input id="btnsigin" type='Button' onclick="sigin()" value="SignIn"/>
<br/>
<input id="btnsignup" type='Button' onclick="signUp()" value="Sign Up" /><br/>


问:
How can I get 'edge' points (furthest edge coordinates) from a list of coordinates
I am new to mapbox and not so experienced with working with maps and I am trying to draw a polygon from a list of coordinates that I have. So far this is the code I have;

```<code>const accessToken = <myTokenHere>;
const center = [36.813288, -1.2813976];
const mycords = [
 [36.88888, -1.3008283333333335 ],
 [ 36.88977666666666,-1.30097 ],
 [36.88977666666666, -1.30097],
 [36.88977666666666, -1.30097 ],
 //...
];
mapboxgl.accessToken = accessToken;
var map = new mapboxgl.Map({
    container: 'map',
    style: 'mapbox://styles/mapbox/streets-v9',
    center,
    zoom: 7
});
map.on('load', () => {
map.addLayer({
    'id': 'vendors',
    'type': 'fill',
    'source': {
        'type': 'geojson',
        'data': {
            'type': 'Feature',
            'geometry': {
                'type': 'Polygon',
                'coordinates': [mycords]
            }
        }
    },
    'layout': {},
    'paint': {
        'fill-color': '#181A4A',
        'fill-opacity': 0.6
    }
  });
});
</code>```

The above code draws a polygon as depicted below.

My intention is to draw a polygon like the one below based off my coordinates;

I think I need to get the "edges" so that I can be able to pass those coordinates to the layer. My question is how do I achieve this? I have checked mapboxes API documentation but I haven't managed to come across a method that does this.

答:
By design, Mapbox GL doesn't provide many data processing tools. For that, we recommend using Turf. It's difficult for me to tell exactly what you've got and what you're trying to do but it looks like one of the following methods may be what you're looking for:

http://turfjs.org/Docs#polygonize

http://turfjs.org/Docs#concave

http://turfjs.org/Docs#convex

Body:
I am new to mapbox and not so experienced with working with maps and I am trying to draw a polygon from a list of coordinates that I have. So far this is the code I have;

const accessToken = <myTokenHere>;
const center = [36.813288, -1.2813976];
const mycords = [
 [36.88888, -1.3008283333333335 ],
 [ 36.88977666666666,-1.30097 ],
 [36.88977666666666, -1.30097],
 [36.88977666666666, -1.30097 ],
 //...
];
mapboxgl.accessToken = accessToken;
var map = new mapboxgl.Map({
    container: 'map',
    style: 'mapbox://styles/mapbox/streets-v9',
    center,
    zoom: 7
});
map.on('load', () => {
map.addLayer({
    'id': 'vendors',
    'type': 'fill',
    'source': {
        'type': 'geojson',
        'data': {
            'type': 'Feature',
            'geometry': {
                'type': 'Polygon',
                'coordinates': [mycords]
            }
        }
    },
    'layout': {},
    'paint': {
        'fill-color': '#181A4A',
        'fill-opacity': 0.6
    }
  });
});

The above code draws a polygon as depicted below.

My intention is to draw a polygon like the one below based off my coordinates;

I think I need to get the "edges" so that I can be able to pass those coordinates to the layer. My question is how do I achieve this? I have checked mapboxes API documentation but I haven't managed to come across a method that does this.


问:
Timestamp to string with custom format
I am to move data from BigQuery to an Oracle database and am trying to find the best way to deal with timestamps. The Oracle DB can only import csv files with dates in little endian format (dd/mm/yyyy hh:mi:ss) but by default BigQuery only supports big endian (yyyy-mm-dd hh:mi:ss).

SELECT
  t,
  STRING(t) s
FROM
  (SELECT TIMESTAMP(132456789101112) t)
```

<pre class="lang-none prettyprint-override"><code>Row   t                         s
1     1974-03-14 01:33:09 UTC   1974-03-14 01:33:09.101112
</code>```

I could of course extract the different components of the timestamp and paste them together manually (see below) or write some clever UDF, but I'd be surprised if there isn't any way to do this with BigQuery's standard functionality. It seems like such a common thing to do that I've in fact hesitated to ask for some time.

SELECT
  t,
  CONCAT(
    RIGHT(CONCAT("0", STRING(DAY(t))), 2), "/",
    RIGHT(CONCAT("0", STRING(MONTH(t))), 2), "/",
    RIGHT(CONCAT("000", STRING(YEAR(t))), 4), " ",
    TIME(t)
  ) s
FROM
  (SELECT TIMESTAMP(132456789101112) t)
```

<pre class="lang-none prettyprint-override"><code>Row   t                         s
1     1974-03-14 01:33:09 UTC   14/03/1974 01:33:09
</code>```

Is there anything like FORMAT(t, "dd/mm/yyyy hh:mi:ss") or a way to do it with regexps? (Without having to concat several REGEXP_EXTRACT.)

答:
For those of you using Bigquery's standard SQL, the right way to do this is with

FORMAT_TIMESTAMP or FORMAT_DATE depending on your input.

ex:

SELECT FORMAT_TIMESTAMP('%Y/%m/%d', TIMESTAMP('2017-11-01'))
will return
2017/11/01

Title: Timestamp to string with custom format

Body:
I am to move data from BigQuery to an Oracle database and am trying to find the best way to deal with timestamps. The Oracle DB can only import csv files with dates in little endian format (dd/mm/yyyy hh:mi:ss) but by default BigQuery only supports big endian (yyyy-mm-dd hh:mi:ss).

SELECT
  t,
  STRING(t) s
FROM
  (SELECT TIMESTAMP(132456789101112) t)

Row   t                         s
1     1974-03-14 01:33:09 UTC   1974-03-14 01:33:09.101112

I could of course extract the different components of the timestamp and paste them together manually (see below) or write some clever UDF, but I'd be surprised if there isn't any way to do this with BigQuery's standard functionality. It seems like such a common thing to do that I've in fact hesitated to ask for some time.

SELECT
  t,
  CONCAT(
    RIGHT(CONCAT("0", STRING(DAY(t))), 2), "/",
    RIGHT(CONCAT("0", STRING(MONTH(t))), 2), "/",
    RIGHT(CONCAT("000", STRING(YEAR(t))), 4), " ",
    TIME(t)
  ) s
FROM
  (SELECT TIMESTAMP(132456789101112) t)

Row   t                         s
1     1974-03-14 01:33:09 UTC   14/03/1974 01:33:09

Is there anything like FORMAT(t, "dd/mm/yyyy hh:mi:ss") or a way to do it with regexps? (Without having to concat several REGEXP_EXTRACT.)


问:
React Native Style check box and text separation
I am trying to make a register page for an application. I want to put a check box for accepting terms and conditions, but I can't find out how to put the check box slightly to the left of the text. Currently, it is put on the first letter of the text</p>

```<code><View style={{flexDirection: 'row', alignItems: 'center'}>
     <CheckBox style =checked={this.state.agreeTNCs} onPress={() => this.setState({agreeTNCs: !this.state.agreeTNCs})} testID="tncsBox"/>
     <Hyperlink linkStyle={{color: '#2980b9'}} onPress={() => this.props.screenChangeHandler(routes.loggedOut.termsAndConditions)}>
         <Text>I agree to the Nowzi Terms and Conditions</Text>
     </Hyperlink>
</View>
</code>```

答:
Try adding a non-breaking space between the two:</p>

```<code><View style={{flexDirection: 'row', alignItems: 'center'}>
     <CheckBox style =checked={this.state.agreeTNCs} onPress={() => this.setState({agreeTNCs: !this.state.agreeTNCs})} testID="tncsBox"/>

     <Hyperlink linkStyle={{color: '#2980b9'}} onPress={() => this.props.screenChangeHandler(routes.loggedOut.termsAndConditions)}>
         <Text>I agree to the Nowzi Terms and Conditions</Text>
     </Hyperlink>
</View>
</code>```

Body:
I am trying to make a register page for an application. I want to put a check box for accepting terms and conditions, but I can't find out how to put the check box slightly to the left of the text. Currently, it is put on the first letter of the text

<View style={{flexDirection: 'row', alignItems: 'center'}>
     <CheckBox style =checked={this.state.agreeTNCs} onPress={() => this.setState({agreeTNCs: !this.state.agreeTNCs})} testID="tncsBox"/>
     <Hyperlink linkStyle={{color: '#2980b9'}} onPress={() => this.props.screenChangeHandler(routes.loggedOut.termsAndConditions)}>
         <Text>I agree to the Nowzi Terms and Conditions</Text>
     </Hyperlink>
</View>

Body:
Try adding a non-breaking space between the two:

<View style={{flexDirection: 'row', alignItems: 'center'}>
     <CheckBox style =checked={this.state.agreeTNCs} onPress={() => this.setState({agreeTNCs: !this.state.agreeTNCs})} testID="tncsBox"/>
     &nbsp;
     <Hyperlink linkStyle={{color: '#2980b9'}} onPress={() => this.props.screenChangeHandler(routes.loggedOut.termsAndConditions)}>
         <Text>I agree to the Nowzi Terms and Conditions</Text>
     </Hyperlink>
</View>


问:
How to sum column values from two tables and preserve another column which is only in one table
i have created tables item and item2, I know maybe it's data redundancy but i want to know how can select it, and create a view?

```<code>create table item(
id  number(10) primary key,
name varchar2(20),
mark number(10));
insert into item values(10,'Apple1',23);
insert into item values(11,'Apple2',0);
insert into item values(12,'Apple3',0);
insert into item values(13,'Apple4',0);
insert into item values(14,'Apple4',0);
insert into item values(15,'Apple4',0);
insert into item values(16,'Apple4',0);

create table  item2(
id number(10),
mark number(10));
alter table item2 add(constraint id_fk FOREIGN KEY (id) references  item(id));
Insert into  item2 values(10,1);
Insert into  item2 values(10,1);
Insert into  item2 values(11,7);
Insert into  item2 values(12,14);
</code>```

I can query both:

```<code>select * from item;

ID  Name    Mark
10  Apple1    23
11  Apple2     0
12  Apple3     0
13  Apple4     0
14  Apple4     0
15  Apple4     0
16  Apple4     0

select * from item2;

ID  Mark
10     1
10     1
11     7
12    14
</code>```

I want to get the result set below using the select statement sum from the item and item2 tables:

```<code>ID  Name    Mark
10  Apple1    25
11  Apple2     7
12  Apple3    14
13  Apple4     0
14  Apple4     0
15  Apple4     0
16  Apple4     0
</code>```

How can I combine my queries to produce that output?

答:
How about this?</p>

```<code>select  id,name,(m1 +nvl(m2,0)) mark
from
(select t1.id,t1.name,t1.mark m1,t2.mark m2
from
item t1
LEFT OUTER JOIN
(select id,sum(mark) mark from item2
group by id) t2
ON
t2.id = t1.id
)
order by id;
</code>```

Body:
i have created tables item and item2, I know maybe it's data redundancy but i want to know how can select it, and create a view?

create table item(
id  number(10) primary key,
name varchar2(20),
mark number(10));
insert into item values(10,'Apple1',23);
insert into item values(11,'Apple2',0);
insert into item values(12,'Apple3',0);
insert into item values(13,'Apple4',0);
insert into item values(14,'Apple4',0);
insert into item values(15,'Apple4',0);
insert into item values(16,'Apple4',0);

create table  item2(
id number(10),
mark number(10));
alter table item2 add(constraint id_fk FOREIGN KEY (id) references  item(id));
Insert into  item2 values(10,1);
Insert into  item2 values(10,1);
Insert into  item2 values(11,7);
Insert into  item2 values(12,14);

I can query both:

select * from item;

ID  Name    Mark
10  Apple1    23
11  Apple2     0
12  Apple3     0
13  Apple4     0
14  Apple4     0
15  Apple4     0
16  Apple4     0

select * from item2;

ID  Mark
10     1
10     1
11     7
12    14

I want to get the result set below using the select statement sum from the item and item2 tables:

ID  Name    Mark
10  Apple1    25
11  Apple2     7
12  Apple3    14
13  Apple4     0
14  Apple4     0
15  Apple4     0
16  Apple4     0

How can I combine my queries to produce that output?

Body:
How about this?

select  id,name,(m1 +nvl(m2,0)) mark
from
(select t1.id,t1.name,t1.mark m1,t2.mark m2
from
item t1
LEFT OUTER JOIN
(select id,sum(mark) mark from item2
group by id) t2
ON
t2.id = t1.id
)
order by id;


问:
How do I use url fragments when other things get appended to them?
I have built a website that displays one table record at a time.
I have been using a URL fragment identifier (everything after the first #) to supply the record identifier, so to display the record with identifier '1', the URL would be: baseurl.org/record.html#1

In the code, I simply take window.location.hash, strip the leading #, and then query the table for the appropriate record identifier.

I recently found that certain URL shorteners will append things to the end of the URL, so some social media links to my site had '?platform=hootsuite' added to the end. Of course, my javascript can't find a record with the identifier '1?platform=hootsuite'

It's easy enough to write a short piece of javascript to extract the substring before a question mark, since I do not expect a question mark in my identifiers. The identifiers sometimes include letters as well, like 22a or 223C, but never special characters like ?, /, &, or #. I am wondering what other unexpected strings could be appended to my URL. I guess that anything appended would have to be preceded by a special character like a question mark, so I could come up with a list of special characters and ignore anything after those.

Is there a correct or conventional way to use the URL fragment and to handle things being appended to it? Are there other issues that might arise related to this simple way of using the URL fragment?

I'm just using html, javascript, and jQuery, and am not interested in a whole separate framework or library to handle this.

答:
Should only have to worry about ? and just parse your hash between # and first instance of ?

```<code>var hash = location.hash;
if(hash.length > 1){
  hash = hash.replace(/#|\?.+/g,'');// remove `#` and anything including and after `?`
  // do whatever with your hash records
}
</code>```

To be on the safe side I suggest you also send any mismatches to your server and store the url for analysis and future tweaks

Body:
Should only have to worry about ? and just parse your hash between # and first instance of ?

var hash = location.hash;
if(hash.length > 1){
  hash = hash.replace(/#|\?.+/g,'');// remove `#` and anything including and after `?`
  // do whatever with your hash records
}

To be on the safe side I suggest you also send any mismatches to your server and store the url for analysis and future tweaks


问:
in solr is there an way to fetch all results from a query something like start=0&rows=* or rows=all?
as far as I know this is not possible as the solr wiki. do you guys have any work around?</p>

答:
If you need to get everything out, you can either set the number of rows ridiculously high (as indicated above, with the caveat that, well, it won't work because you'll run out of memory) or iterate through your results using "rows" and "start"

Pseudocode:

```<code>numresults = <do an initial query and find out how many results there are>
rows = 100 (or 1000 or 100,000 or whatever you can handle)
start = 0
while (start) <= numresults
 url = "http://.../?q=<your query>&rows=<rows>&start=<start>&...
 result = <do the call with the url>
 <process the docs>
 start += rows
endwhile
</code>```

See http://wiki.apache.org/solr/CommonQueryParameters for use of "start"

Also remember that when you're grabbing gobs of documents, use the 'fl' parameter to only pull back what you're actually gonna use.

ContentLicense: CC BY-SA 2.5

Body:
If you need to get everything out, you can either set the number of rows ridiculously high (as indicated above, with the caveat that, well, it won't work because you'll run out of memory) or iterate through your results using "rows" and "start"

Pseudocode:

numresults = <do an initial query and find out how many results there are>
rows = 100 (or 1000 or 100,000 or whatever you can handle)
start = 0
while (start) <= numresults
 url = "http://.../?q=<your query>&rows=<rows>&start=<start>&...
 result = <do the call with the url>
 <process the docs>
 start += rows
endwhile

See http://wiki.apache.org/solr/CommonQueryParameters for use of "start"

Also remember that when you're grabbing gobs of documents, use the 'fl' parameter to only pull back what you're actually gonna use.


问:
Toggle between two colors when key is pressed
I'm currently learning C# with Unity and I created a simple game where you can change the color of the player (which is red by default) by clicking the "C" key (which will change to green).
The code works but, the problem is, I don't know how to create a code that changes the green color to red color again by using the same key ("C").
The only alternative I know is to create another if but with a different button.
Here is my code:

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class cubecolor : MonoBehaviour {

    // Use this for initialization
    void Start () {
        gameObject.GetComponent<Renderer> ().material.color = Color.red;

    }

    // Update is called once per frame
    void Update () {
        if (Input.GetKey(KeyCode.C))
            gameObject.GetComponent<Renderer> ().material.color = Color.green;

    }
}
</code>```

答:
It is easily done by using a bool variable:

```<code>            using System.Collections;
            using System.Collections.Generic;
            using UnityEngine;

            public class cubecolor : MonoBehaviour {
                private bool isGreen = false; /*Let's create a boolean to store if the cube
                is green or red*/

                // Use this for initialization
                void Start () {
                    gameObject.GetComponent<Renderer> ().material.color = Color.red;
                }

                // Update is called once per frame
                void Update () {
                    if (Input.GetKey(KeyCode.C){
                        if(isGreen){ //Check if the color is green
                            gameObject.GetComponent<Renderer> ().material.color = Color.red;
                        }else{
                            gameObject.GetComponent<Renderer> ().material.color = Color.green;
                        }
                        isGreen = !isGreen; //Switch the boolean.
                    }
            }
</code>```

Body:
I'm currently learning C# with Unity and I created a simple game where you can change the color of the player (which is red by default) by clicking the "C" key (which will change to green).
The code works but, the problem is, I don't know how to create a code that changes the green color to red color again by using the same key ("C").
The only alternative I know is to create another if but with a different button.
Here is my code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class cubecolor : MonoBehaviour {

    // Use this for initialization
    void Start () {
        gameObject.GetComponent<Renderer> ().material.color = Color.red;

    }

    // Update is called once per frame
    void Update () {
        if (Input.GetKey(KeyCode.C))
            gameObject.GetComponent<Renderer> ().material.color = Color.green;

    }
}

Body:
It is easily done by using a bool variable:

            using System.Collections;
            using System.Collections.Generic;
            using UnityEngine;

            public class cubecolor : MonoBehaviour {
                private bool isGreen = false; /*Let's create a boolean to store if the cube
                is green or red*/

                // Use this for initialization
                void Start () {
                    gameObject.GetComponent<Renderer> ().material.color = Color.red;
                }

                // Update is called once per frame
                void Update () {
                    if (Input.GetKey(KeyCode.C){
                        if(isGreen){ //Check if the color is green
                            gameObject.GetComponent<Renderer> ().material.color = Color.red;
                        }else{
                            gameObject.GetComponent<Renderer> ().material.color = Color.green;
                        }
                        isGreen = !isGreen; //Switch the boolean.
                    }
            }


问:
How can I copy the values of a variable to another variable in a NetCDF but not the dimension?
I have 2 dimensions X1, X2

And 3 variables V1(X1), V2(X2), V3(X3)

I want to copy the values of V2 to V1. But keep the dimensions as it is.

If I do:

```<code>ncap2 -s "V2=V1*1" in.nc out.nc
</code>```

the dimensions become V1(X2), V2(X2), V3(X3)

How can I retain the original dimension of V1?

答:
That's an unusual request. One solution is to follow the step you already have with one more command to append the values you want back into the original variable. Here lon and ilev are both the same size, but with different underlying dimensions:</p>

```<code>ncap2 -O -v -s 'lon=ilev' ~/in.nc ~/foo.nc # make lon a copy of ilev
ncks -A -C -v lon ~/foo.nc ~/in.nc # append lon back into itself
</code>```

Body:
I have 2 dimensions X1, X2

And 3 variables V1(X1), V2(X2), V3(X3)

I want to copy the values of V2 to V1. But keep the dimensions as it is.

If I do:

ncap2 -s "V2=V1*1" in.nc out.nc

the dimensions become V1(X2), V2(X2), V3(X3)

How can I retain the original dimension of V1?

Body:
That's an unusual request. One solution is to follow the step you already have with one more command to append the values you want back into the original variable. Here lon and ilev are both the same size, but with different underlying dimensions:

ncap2 -O -v -s 'lon=ilev' ~/in.nc ~/foo.nc # make lon a copy of ilev
ncks -A -C -v lon ~/foo.nc ~/in.nc # append lon back into itself


问:
Ensure that listbox and collection both start at same point (0 or 1)
I have the following code in a button click event:

```<code>    If myCollection.Count > 0 Then
        Dim curItemIndex As Integer = myListbox.SelectedIndex
        If myCollection.Item(curItemIndex) IsNot Nothing Then
            myCollection.Remove(curItemIndex)
            MessageBox.Show("Address removed!")
        Else
            MessageBox.Show("Could not delete entry!")
        End If
    Else
        MessageBox.Show("Address book is empty!")
    End If
</code>```

When I add an item to the collection, then try to remove it, I always get this error:

System.IndexOutOfRangeException: 'Collection index must be in the
  range 1 to the size of the collection.'

When I step through the debugger, I see this:

myCollection.Count = 1

SelectedIndex = 0

curItemIndex = 0

So I don't get why the currently selected item in the listbox is 0 when it says the collection starts at 1.

How can I fix this so that both start at 0?

Thanks!

答: It appears that this is a VB collection which is one based. Explore the System.Collections.Generic Namespace as Microsoft recommends. One of the simplest classes is List (Of T) if your collection is all the same datatype. Then your listbox index and your List index should match (both zero based). To keep them in sync be sure to remove the item from the listbox too.</p>

Body:
I have the following code in a button click event:

    If myCollection.Count > 0 Then
        Dim curItemIndex As Integer = myListbox.SelectedIndex
        If myCollection.Item(curItemIndex) IsNot Nothing Then
            myCollection.Remove(curItemIndex)
            MessageBox.Show("Address removed!")
        Else
            MessageBox.Show("Could not delete entry!")
        End If
    Else
        MessageBox.Show("Address book is empty!")
    End If

When I add an item to the collection, then try to remove it, I always get this error:

System.IndexOutOfRangeException: 'Collection index must be in the
  range 1 to the size of the collection.'

When I step through the debugger, I see this:

myCollection.Count = 1

SelectedIndex = 0

curItemIndex = 0

So I don't get why the currently selected item in the listbox is 0 when it says the collection starts at 1.

How can I fix this so that both start at 0?

Thanks!


问:
How do I disable a CSS rule?
I have the following CSS rule

#class {
    margin: 4px 5px 6px 7px;
    color: red;
}
```

<p>What I usualy do is</p>

```document.getElementById('class').style.margin= '0px';
```

<p>Then after doing that to reset I go the same step</p>

```document.getElementById('class').style.margin= '4px 5px 6px 7px';
```

How do I disable the margin using JavaScript\JQuery instead of changing the value to 0 then reset it to 4px 5px 6px 7px

答:
Can you make a second class and just add/remove it from your elements?</p>

```<code>.margin {
    margin: 4px 5px 6px 7px;
    color: red;
}
.noMargin {
    margin: 0px
    color: red;
}

document.getElementById("class").classList.add('margin');
document.getElementById("class").classList.remove('noMargin');

document.getElementById("class").classList.add('noMargin');
document.getElementById("class").classList.remove('margin');
</code>```

Title: How do I disable a CSS rule?

Body:
I have the following CSS rule

#class {
    margin: 4px 5px 6px 7px;
    color: red;
}

What I usualy do is

document.getElementById('class').style.margin= '0px';

Then after doing that to reset I go the same step

document.getElementById('class').style.margin= '4px 5px 6px 7px';

How do I disable the margin using JavaScript\JQuery instead of changing the value to 0 then reset it to 4px 5px 6px 7px

Body:
Can you make a second class and just add/remove it from your elements?

.margin {
    margin: 4px 5px 6px 7px;
    color: red;
}
.noMargin {
    margin: 0px
    color: red;
}

document.getElementById("class").classList.add('margin');
document.getElementById("class").classList.remove('noMargin');

document.getElementById("class").classList.add('noMargin');
document.getElementById("class").classList.remove('margin');


问:
Java Regex to extrac an javascript object from Javascript String
I am trying to extract an object from a JSText String in Java.

Regex that I am using (more accurate at this moment):

```<code>PJ\s?[=:]\s?\{(.*\s*\})
</code>```

This is the demo:
https://regex101.com/r/hlkEUc/3

If you appreciate, at the end its the full code in single line form. This is captured without problems but in the middle of the text you can see the regex is trying capture the same object but it's broken due the line break.

Object to extract:

```<code>var PJ={yF:function(a,b){var c=a[0];a[0]=a[b%a.length];a[b]=c},It:function(a){a.reverse()},yp:function(a,b){a.splice(0,b)}};
</code>```

答:
I think you probably want this: PJ\s?[=:]\s?\{(.*[\r\n].*?)*?\};.

Regex

Body:
I am trying to extract an object from a JSText String in Java.

Regex that I am using (more accurate at this moment):

PJ\s?[=:]\s?\{(.*\s*\})

This is the demo:
https://regex101.com/r/hlkEUc/3

If you appreciate, at the end its the full code in single line form. This is captured without problems but in the middle of the text you can see the regex is trying capture the same object but it's broken due the line break.

Object to extract:

var PJ={yF:function(a,b){var c=a[0];a[0]=a[b%a.length];a[b]=c},It:function(a){a.reverse()},yp:function(a,b){a.splice(0,b)}};


问:
ClassNotFoundException using Selenium Standalone Server
I have a grails/groovy project that has one feature that uses selenium standalone server to do some test automation.

I keep getting this error running my grails project in production mode. If I run it directly from IntelliJ it works perfectly so I'm not sure what exactly is wrong.

Here is the relevant code:

```<code> WebDriver driver
 DesiredCapabilities capability = DesiredCapabilities.chrome()
 capability.setBrowserName("chrome")
 capability.setPlatform(Platform.WINDOWS)
 driver = new RemoteWebDriver( new URL("http://192.168.83.124:4444/wd/hub"), capability);
</code>```

I'm getting a ClassNotFoundException error on the last line.

In my libraries for the project I'm using selenium-java-2.53.0.jar, selenium-server-standalone-2.53.0.jar and sources has selenium-java-2.53.0-srcs.jar

I have absolutely no idea what's wrong and I've searched the internet exhaustively to  find a solution but have found nothing. Any help is appreciated.

Here is the full text of the error:

```<code> 2017-12-08 15:59:56,381 [http-bio-8080-exec-1] ERROR
 errors.GrailsExceptionResolver  - ClassNotFoundException occurred when processing request: [GET] /Diversotron-0.1/api/edit
 com.google.common.base.Function. Stacktrace follows:
 java.lang.ClassNotFoundException: com.google.common.base.Function
    at java.lang.Class.privateGetDeclaredConstructors(Class.java:2585)
    at java.lang.Class.getDeclaredConstructors(Class.java:1906)
    at
 org.codehaus.groovy.util.LazyReference.getLocked(LazyReference.java:46)
    at org.codehaus.groovy.util.LazyReference.get(LazyReference.java:33)
    at diversotron.PropotronService.setPropotron(PropotronService.groovy:25)
    at diversotron.ApiController.edit(ApiController.groovy:53)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:745)
</code>```

答:
Map chrome Options = new Map();

ChromeOptions.put("binary","/use/lib/chromium-browser/chromium-browser");

DesiredCapabilities capabilities = DesiredCapabilities.chrome();

capabilities.setCapability(ChromeOptions.CAPABILITY, chromeOptions);

Web Driver driver = new Chrome Driver(capabilities);
try this

Body:
I have a grails/groovy project that has one feature that uses selenium standalone server to do some test automation.

I keep getting this error running my grails project in production mode. If I run it directly from IntelliJ it works perfectly so I'm not sure what exactly is wrong.

Here is the relevant code:

 WebDriver driver
 DesiredCapabilities capability = DesiredCapabilities.chrome()
 capability.setBrowserName("chrome")
 capability.setPlatform(Platform.WINDOWS)
 driver = new RemoteWebDriver( new URL("http://192.168.83.124:4444/wd/hub"), capability);

I'm getting a ClassNotFoundException error on the last line.

In my libraries for the project I'm using selenium-java-2.53.0.jar, selenium-server-standalone-2.53.0.jar and sources has selenium-java-2.53.0-srcs.jar

I have absolutely no idea what's wrong and I've searched the internet exhaustively to  find a solution but have found nothing. Any help is appreciated.

Here is the full text of the error:

 2017-12-08 15:59:56,381 [http-bio-8080-exec-1] ERROR
 errors.GrailsExceptionResolver  - ClassNotFoundException occurred when processing request: [GET] /Diversotron-0.1/api/edit
 com.google.common.base.Function. Stacktrace follows:
 java.lang.ClassNotFoundException: com.google.common.base.Function
    at java.lang.Class.privateGetDeclaredConstructors(Class.java:2585)
    at java.lang.Class.getDeclaredConstructors(Class.java:1906)
    at
 org.codehaus.groovy.util.LazyReference.getLocked(LazyReference.java:46)
    at org.codehaus.groovy.util.LazyReference.get(LazyReference.java:33)
    at diversotron.PropotronService.setPropotron(PropotronService.groovy:25)
    at diversotron.ApiController.edit(ApiController.groovy:53)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:745)