text:
Q: xsl:for-each Loop is duplicating things I am not expecting (Using XSLT 1.0 and running through FOP 1.1)
Cut down XML
<?xml version="1.0"?>
<Report schema="1.01">
    <Item id="1" name="cabinet">
        <VSection id="0" vsection="main">
            <HSection id="22">
                <Component id="1" idfull="00102201">
                    <DisplayName>Board</DisplayName>
                    <Category>Carcass</Category>
                    <Brand>Melamine</Brand>
                    <Color>Black</Color>
                    <Finish></Finish>
                    <Material>16mm Black</Material>

                    <PartNo></PartNo>
                    <Comment>End-R</Comment>
                    <Optimising></Optimising>
                    <IsOptimised>No</IsOptimised>
                    <IsGrained>No</IsGrained>
                    <IsRecutPanel>No</IsRecutPanel>
                    <IsRecutPiece>No</IsRecutPiece>
                    <Boring></Boring>
                    <Edging>1L</Edging>
                    <IsEdgedOnTop>No</IsEdgedOnTop>
                    <IsEdgedOnRight>No</IsEdgedOnRight>
                    <IsEdgedOnBottom>No</IsEdgedOnBottom>
                    <IsEdgedOnLeft>Yes</IsEdgedOnLeft>
                    <EdgeMatTop></EdgeMatTop>
                    <EdgeMatRight></EdgeMatRight>
                    <EdgeMatBottom></EdgeMatBottom>
                    <EdgeMatLeft>1mm</EdgeMatLeft>
                    <Hinging></Hinging>
                    <HingePos>Outside</HingePos>
                    <IsPresent>Yes</IsPresent>
                    <IsStock>No</IsStock>

                    <DimName1>16mm Black</DimName1>
                    <Dim1>720mm</Dim1>
                    <DimCut1>720mm</DimCut1>
                    <DimName2>Width</DimName2>
                    <Dim2>560mm</Dim2>
                    <DimCut2>559mm</DimCut2>
                    <DimName3>Thickness</DimName3>
                    <Dim3>16mm</Dim3>
                    <DimCut3>16mm</DimCut3>
                    <Time>0.00mn</Time>
                    <UnitCost>$0.00</UnitCost>
                    <Cost>$0.00</Cost>
                    <UnitSell>$0.00</UnitSell>
                    <Sell>$0.00</Sell>
                    <Quantity>1</Quantity>
                </Component>
            </HSection>
            <HSection id="33">
                <Component id="1" idfull="00103301">
                    <DisplayName>Board</DisplayName>
                    <Category>Carcass</Category>
                    <Brand>Melamine</Brand>
                    <Color>White</Color>
                    <Finish></Finish>
                    <Material>16mm White HMR</Material>

                    <PartNo></PartNo>
                    <Comment>Shelf Adj</Comment>
                    <Optimising></Optimising>
                    <IsOptimised>No</IsOptimised>
                    <IsGrained>No</IsGrained>
                    <IsRecutPanel>No</IsRecutPanel>
                    <IsRecutPiece>No</IsRecutPiece>
                    <Boring></Boring>
                    <Edging>1L</Edging>
                    <IsEdgedOnTop>No</IsEdgedOnTop>
                    <IsEdgedOnRight>Yes</IsEdgedOnRight>
                    <IsEdgedOnBottom>No</IsEdgedOnBottom>
                    <IsEdgedOnLeft>No</IsEdgedOnLeft>
                    <EdgeMatTop></EdgeMatTop>
                    <EdgeMatRight>1mm</EdgeMatRight>
                    <EdgeMatBottom></EdgeMatBottom>
                    <EdgeMatLeft></EdgeMatLeft>
                    <Hinging></Hinging>
                    <HingePos>Outside</HingePos>
                    <IsPresent>Yes</IsPresent>
                    <IsStock>No</IsStock>

                    <DimName1>_16.0mm Carcase White</DimName1>
                    <Dim1>816mm</Dim1>
                    <DimCut1>816mm</DimCut1>
                    <DimName2>Width</DimName2>
                    <Dim2>533mm</Dim2>
                    <DimCut2>532mm</DimCut2>
                    <DimName3>Thickness</DimName3>
                    <Dim3>16mm</Dim3>
                    <DimCut3>16mm</DimCut3>
                    <Time>0.00mn</Time>
                    <UnitCost>$0.00</UnitCost>
                    <Cost>$0.00</Cost>
                    <UnitSell>$0.00</UnitSell>
                    <Sell>$0.00</Sell>
                    <Quantity>1</Quantity>
                </Component>
                </HSection>
            <HSection id="18">
                <Component id="1" idfull="00101801">
                    <DisplayName>Board</DisplayName>
                    <Category>Carcass</Category>
                    <Brand>Melamine</Brand>
                    <Color>Black</Color>
                    <Finish></Finish>
                    <Material>16mm Black</Material>

                    <PartNo></PartNo>
                    <Comment>End-L</Comment>
                    <Optimising></Optimising>
                    <IsOptimised>No</IsOptimised>
                    <IsGrained>No</IsGrained>
                    <IsRecutPanel>No</IsRecutPanel>
                    <IsRecutPiece>No</IsRecutPiece>
                    <Boring></Boring>
                    <Edging>1L</Edging>
                    <IsEdgedOnTop>No</IsEdgedOnTop>
                    <IsEdgedOnRight>Yes</IsEdgedOnRight>
                    <IsEdgedOnBottom>No</IsEdgedOnBottom>
                    <IsEdgedOnLeft>No</IsEdgedOnLeft>
                    <EdgeMatTop></EdgeMatTop>
                    <EdgeMatRight>1mm</EdgeMatRight>
                    <EdgeMatBottom></EdgeMatBottom>
                    <EdgeMatLeft></EdgeMatLeft>
                    <Hinging></Hinging>
                    <HingePos>Outside</HingePos>
                    <IsPresent>Yes</IsPresent>
                    <IsStock>No</IsStock>

                    <DimName1>16mm Black</DimName1>
                    <Dim1>720mm</Dim1>
                    <DimCut1>720mm</DimCut1>
                    <DimName2>Width</DimName2>
                    <Dim2>560mm</Dim2>
                    <DimCut2>559mm</DimCut2>
                    <DimName3>Thickness</DimName3>
                    <Dim3>16mm</Dim3>
                    <DimCut3>16mm</DimCut3>
                    <Time>0.00mn</Time>
                    <UnitCost>$0.00</UnitCost>
                    <Cost>$0.00</Cost>
                    <UnitSell>$0.00</UnitSell>
                    <Sell>$0.00</Sell>
                    <Quantity>1</Quantity>
                </Component>
                </HSection>
            <HSection id="15">
                <Component id="1" idfull="00101501">
                    <DisplayName>Board</DisplayName>
                    <Category>Carcass</Category>
                    <Brand>Melamine</Brand>
                    <Color>White</Color>
                    <Finish></Finish>
                    <Material>16mm White HMR</Material>

                    <PartNo></PartNo>
                    <Comment>Bottom</Comment>
                    <Optimising></Optimising>
                    <IsOptimised>No</IsOptimised>
                    <IsGrained>No</IsGrained>
                    <IsRecutPanel>No</IsRecutPanel>
                    <IsRecutPiece>No</IsRecutPiece>
                    <Boring></Boring>
                    <Edging>1L</Edging>
                    <IsEdgedOnTop>No</IsEdgedOnTop>
                    <IsEdgedOnRight>Yes</IsEdgedOnRight>
                    <IsEdgedOnBottom>No</IsEdgedOnBottom>
                    <IsEdgedOnLeft>No</IsEdgedOnLeft>
                    <EdgeMatTop></EdgeMatTop>
                    <EdgeMatRight>1mm</EdgeMatRight>
                    <EdgeMatBottom></EdgeMatBottom>
                    <EdgeMatLeft></EdgeMatLeft>
                    <Hinging></Hinging>
                    <HingePos>Outside</HingePos>
                    <IsPresent>Yes</IsPresent>
                    <IsStock>No</IsStock>

                    <DimName1>_16.0mm Carcase White</DimName1>
                    <Dim1>818mm</Dim1>
                    <DimCut1>818mm</DimCut1>
                    <DimName2>Width</DimName2>
                    <Dim2>544mm</Dim2>
                    <DimCut2>543mm</DimCut2>
                    <DimName3>Thickness</DimName3>
                    <Dim3>16mm</Dim3>
                    <DimCut3>16mm</DimCut3>
                    <Time>0.00mn</Time>
                    <UnitCost>$0.00</UnitCost>
                    <Cost>$0.00</Cost>
                    <UnitSell>$0.00</UnitSell>
                    <Sell>$0.00</Sell>
                    <Quantity>1</Quantity>
                </Component>
                </HSection>
            <HSection id="30">
                <Component id="1" idfull="00103001">
                    <DisplayName>Board</DisplayName>
                    <Category>Carcass</Category>
                    <Brand>Melamine</Brand>
                    <Color>White</Color>
                    <Finish></Finish>
                    <Material>16mm White HMR</Material>

                    <PartNo></PartNo>
                    <Comment>Shelf Adj</Comment>
                    <Optimising></Optimising>
                    <IsOptimised>No</IsOptimised>
                    <IsGrained>No</IsGrained>
                    <IsRecutPanel>No</IsRecutPanel>
                    <IsRecutPiece>No</IsRecutPiece>
                    <Boring></Boring>
                    <Edging>1L</Edging>
                    <IsEdgedOnTop>No</IsEdgedOnTop>
                    <IsEdgedOnRight>Yes</IsEdgedOnRight>
                    <IsEdgedOnBottom>No</IsEdgedOnBottom>
                    <IsEdgedOnLeft>No</IsEdgedOnLeft>
                    <EdgeMatTop></EdgeMatTop>
                    <EdgeMatRight>1mm</EdgeMatRight>
                    <EdgeMatBottom></EdgeMatBottom>
                    <EdgeMatLeft></EdgeMatLeft>
                    <Hinging></Hinging>
                    <HingePos>Outside</HingePos>
                    <IsPresent>Yes</IsPresent>
                    <IsStock>No</IsStock>

                    <DimName1>_16.0mm Carcase White</DimName1>
                    <Dim1>816mm</Dim1>
                    <DimCut1>816mm</DimCut1>
                    <DimName2>Width</DimName2>
                    <Dim2>533mm</Dim2>
                    <DimCut2>532mm</DimCut2>
                    <DimName3>Thickness</DimName3>
                    <Dim3>16mm</Dim3>
                    <DimCut3>16mm</DimCut3>
                    <Time>0.00mn</Time>
                    <UnitCost>$0.00</UnitCost>
                    <Cost>$0.00</Cost>
                    <UnitSell>$0.00</UnitSell>
                    <Sell>$0.00</Sell>
                    <Quantity>1</Quantity>
                </Component>
                </HSection>
            <HSection id="39">
                <Component id="1" idfull="00103901">
                    <DisplayName>Board</DisplayName>
                    <Category>Carcass</Category>
                    <Brand>Melamine</Brand>
                    <Color>Black</Color>
                    <Finish></Finish>
                    <Material>16mm Black</Material>

                    <PartNo></PartNo>
                    <Comment>Top</Comment>
                    <Optimising></Optimising>
                    <IsOptimised>No</IsOptimised>
                    <IsGrained>No</IsGrained>
                    <IsRecutPanel>No</IsRecutPanel>
                    <IsRecutPiece>No</IsRecutPiece>
                    <Boring></Boring>
                    <Edging>1L</Edging>
                    <IsEdgedOnTop>No</IsEdgedOnTop>
                    <IsEdgedOnRight>Yes</IsEdgedOnRight>
                    <IsEdgedOnBottom>No</IsEdgedOnBottom>
                    <IsEdgedOnLeft>No</IsEdgedOnLeft>
                    <EdgeMatTop></EdgeMatTop>
                    <EdgeMatRight>1mm</EdgeMatRight>
                    <EdgeMatBottom></EdgeMatBottom>
                    <EdgeMatLeft></EdgeMatLeft>
                    <Hinging></Hinging>
                    <HingePos>Outside</HingePos>
                    <IsPresent>Yes</IsPresent>
                    <IsStock>No</IsStock>

                    <DimName1>16mm Black</DimName1>
                    <Dim1>818mm</Dim1>
                    <DimCut1>818mm</DimCut1>
                    <DimName2>Width</DimName2>
                    <Dim2>544mm</Dim2>
                    <DimCut2>543mm</DimCut2>
                    <DimName3>Thickness</DimName3>
                    <Dim3>16mm</Dim3>
                    <DimCut3>16mm</DimCut3>
                    <Time>0.00mn</Time>
                    <UnitCost>$0.00</UnitCost>
                    <Cost>$0.00</Cost>
                    <UnitSell>$0.00</UnitSell>
                    <Sell>$0.00</Sell>
                    <Quantity>1</Quantity>
                </Component>
                </HSection>
            <HSection id="10">
                <Component id="1" idfull="00101001">
                    <DisplayName>Board</DisplayName>
                    <Category>Carcass</Category>
                    <Brand>Melamine</Brand>
                    <Color>White</Color>
                    <Finish></Finish>
                    <Material>16mm White HMR</Material>

                    <PartNo></PartNo>
                    <Comment>Back</Comment>
                    <Optimising></Optimising>
                    <IsOptimised>No</IsOptimised>
                    <IsGrained>No</IsGrained>
                    <IsRecutPanel>Yes</IsRecutPanel>
                    <IsRecutPiece>No</IsRecutPiece>
                    <Boring></Boring>
                    <Edging></Edging>
                    <IsEdgedOnTop>No</IsEdgedOnTop>
                    <IsEdgedOnRight>No</IsEdgedOnRight>
                    <IsEdgedOnBottom>No</IsEdgedOnBottom>
                    <IsEdgedOnLeft>No</IsEdgedOnLeft>
                    <EdgeMatTop></EdgeMatTop>
                    <EdgeMatRight></EdgeMatRight>
                    <EdgeMatBottom></EdgeMatBottom>
                    <EdgeMatLeft></EdgeMatLeft>
                    <Hinging></Hinging>
                    <HingePos>Outside</HingePos>
                    <IsPresent>Yes</IsPresent>
                    <IsStock>No</IsStock>

                    <DimName1>_16.0mm Carcase White</DimName1>
                    <Dim1>720mm</Dim1>
                    <DimCut1>720mm</DimCut1>
                    <DimName2>Width</DimName2>
                    <Dim2>818mm</Dim2>
                    <DimCut2>818mm</DimCut2>
                    <DimName3>Thickness</DimName3>
                    <Dim3>16mm</Dim3>
                    <DimCut3>16mm</DimCut3>
                    <Time>0.00mn</Time>
                    <UnitCost>$0.00</UnitCost>
                    <Cost>$0.00</Cost>
                    <UnitSell>$0.00</UnitSell>
                    <Sell>$0.00</Sell>
                    <Quantity>1</Quantity>
                </Component>
                </HSection>
            <HSection id="36">
                <Component id="1" idfull="00103601">
                    <DisplayName>Board</DisplayName>
                    <Category>Carcass</Category>
                    <Brand>Melamine</Brand>
                    <Color>White</Color>
                    <Finish></Finish>
                    <Material>16mm White HMR</Material>

                    <PartNo></PartNo>
                    <Comment>Shelf Adj</Comment>
                    <Optimising></Optimising>
                    <IsOptimised>No</IsOptimised>
                    <IsGrained>No</IsGrained>
                    <IsRecutPanel>No</IsRecutPanel>
                    <IsRecutPiece>No</IsRecutPiece>
                    <Boring></Boring>
                    <Edging>1L</Edging>
                    <IsEdgedOnTop>No</IsEdgedOnTop>
                    <IsEdgedOnRight>Yes</IsEdgedOnRight>
                    <IsEdgedOnBottom>No</IsEdgedOnBottom>
                    <IsEdgedOnLeft>No</IsEdgedOnLeft>
                    <EdgeMatTop></EdgeMatTop>
                    <EdgeMatRight>1mm</EdgeMatRight>
                    <EdgeMatBottom></EdgeMatBottom>
                    <EdgeMatLeft></EdgeMatLeft>
                    <Hinging></Hinging>
                    <HingePos>Outside</HingePos>
                    <IsPresent>Yes</IsPresent>
                    <IsStock>No</IsStock>

                    <DimName1>_16.0mm Carcase White</DimName1>
                    <Dim1>816mm</Dim1>
                    <DimCut1>816mm</DimCut1>
                    <DimName2>Width</DimName2>
                    <Dim2>533mm</Dim2>
                    <DimCut2>532mm</DimCut2>
                    <DimName3>Thickness</DimName3>
                    <Dim3>16mm</Dim3>
                    <DimCut3>16mm</DimCut3>
                    <Time>0.00mn</Time>
                    <UnitCost>$0.00</UnitCost>
                    <Cost>$0.00</Cost>
                    <UnitSell>$0.00</UnitSell>
                    <Sell>$0.00</Sell>
                    <Quantity>1</Quantity>
                </Component>
                </HSection>
        </VSection>
    </Item>
</Report>

Below is the shortened XSL:FO that will produce the unexpected duplication.
    <?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"
                        xmlns:fo="http://www.w3.org/1999/XSL/Format">
<xsl:output indent="yes" method="xml" encoding="iso-8859-1"/>

<xsl:key name="cMaterial" match="Component[DisplayName='Board'][Category='Carcass']" use="concat(generate-id(../../..),'+',Material,'+',Color,'+',DimCut3)" />
<xsl:key name="UcMaterial" match="Component[DisplayName='Board'][Category='Carcass']" use="concat(generate-id(../../..),'+',Material,'+',Color,'+',DimCut3,'+',DimCut2,'+',DimCut1,'+',Comment,'+',Edging,'+',Quantity)" />

<xsl:template match="/">
    <fo:root xmlns:fo="http://www.w3.org/1999/XSL/Format">

        <fo:layout-master-set>
            <fo:simple-page-master master-name="first-page"
                    page-height="29.7cm"
                    page-width="21cm">
            <fo:region-body margin-top="2cm" margin-bottom="1.5cm"/>
            </fo:simple-page-master>
            <fo:simple-page-master master-name="other-pages"
                    page-height="29.7cm"
                    page-width="21cm">
            <fo:region-body margin-top="0cm" margin-bottom="1.5cm"/>
            <fo:region-before extent="1cm" region-name="other-pages-header"/>
            <fo:region-after extent="1.0cm"/>
            </fo:simple-page-master>

            <fo:page-sequence-master master-name="pages">
                <fo:repeatable-page-master-alternatives>
                    <fo:conditional-page-master-reference page-position="first" master-reference="first-page"/>
                    <fo:conditional-page-master-reference master-reference="other-pages"/>
                </fo:repeatable-page-master-alternatives>
            </fo:page-sequence-master>

        </fo:layout-master-set>

        <fo:page-sequence master-reference="pages">

            <fo:flow flow-name="xsl-region-body">
                <fo:table>
                    <fo:table-column column-number="1" column-width="100%" />
                    <fo:table-body>
                        <fo:table-row>
                            <fo:table-cell><xsl:apply-templates select="Report/Item"/></fo:table-cell>
                        </fo:table-row>
                    </fo:table-body>
                </fo:table>
                <fo:block id="LastPage"/>
            </fo:flow>
        </fo:page-sequence>
    </fo:root>
</xsl:template>

 <xsl:template match="Item">
    <xsl:variable name="carcass" select="VSection/HSection/Component[key('UcMaterial',concat(generate-id(../../..),'+',Material,'+',Color,'+',DimCut3,'+',DimCut2,'+',DimCut1,'+',Comment,'+',Edging,'+',Quantity))]" />
    <fo:table keep-together="always">
        <fo:table-column column-number="1" column-width="100%" />
        <fo:table-body>
            <fo:table-row>
                <fo:table-cell>
                    <xsl:if test="count($carcass) > 0">
                    <fo:table>
                        <fo:table-column column-number="1" column-width="40%" />
                        <fo:table-column column-number="2" column-width="10%" />
                        <fo:table-column column-number="3" column-width="15%" />
                        <fo:table-column column-number="4" column-width="15%" />
                        <fo:table-column column-number="5" column-width="10%" />
                        <fo:table-column column-number="6" column-width="10%" />
                        <fo:table-body>
                            <fo:table-row>
                                <fo:table-cell number-columns-spanned="6"><fo:block>Carcass</fo:block></fo:table-cell>
                            </fo:table-row>
                            <xsl:for-each select="VSection/HSection/Component[generate-id()=generate-id(key('cMaterial',concat(generate-id(../../..),'+',Material,'+',Color,'+',DimCut3))[1])]">
                                <xsl:variable name="this" select="." />
                                <fo:table-row>
                                    <fo:table-cell number-columns-spanned="4">
                                                        <fo:block>
                                                            <xsl:value-of select="Material" /><xsl:text>: </xsl:text>
                                                            <xsl:value-of select="Color" /><xsl:text>: </xsl:text>
                                                            <xsl:value-of select="DimCut3" />
                                                        </fo:block>
                                                    </fo:table-cell>
                                    <fo:table-cell><fo:block></fo:block></fo:table-cell>
                                    <fo:table-cell><fo:block></fo:block></fo:table-cell>
                                </fo:table-row>
                                    <xsl:for-each select="key('cMaterial',concat(generate-id(../../..),'+',$this/Material,'+',$this/Color,'+',$this/DimCut3))">
                                        <xsl:sort select="Comment" />
                                        <xsl:variable name="similar" select="key('UcMaterial',concat(generate-id(../../..),'+',Material,'+',Color,'+',DimCut3,'+',DimCut2,'+',DimCut1,'+',Comment,'+',Edging,'+',Quantity))" />
                                        <xsl:for-each select="../Component[generate-id()=generate-id(key('UcMaterial',concat(generate-id(../../..),'+',Material,'+',Color,'+',DimCut3,'+',DimCut2,'+',DimCut1,'+',Comment,'+',Edging,'+',Quantity))[1])]">
                                            <fo:table-row>
                                                <fo:table-cell><fo:block><xsl:value-of select="Comment" /></fo:block></fo:table-cell>
                                                <fo:table-cell><fo:block><xsl:value-of select="sum($similar/Quantity)" />@</fo:block></fo:table-cell>
                                                <fo:table-cell><fo:block><xsl:value-of select="DimCut1" /></fo:block></fo:table-cell>
                                                <fo:table-cell><fo:block><xsl:value-of select="DimCut2" /></fo:block></fo:table-cell>
                                                <fo:table-cell><fo:block></fo:block></fo:table-cell>
                                                <fo:table-cell><fo:block></fo:block></fo:table-cell>
                                            </fo:table-row>
                                        </xsl:for-each>
                                    </xsl:for-each>
                            </xsl:for-each>
                        </fo:table-body>
                    </fo:table>
                    </xsl:if>
                </fo:table-cell>
            </fo:table-row>
        </fo:table-body>
    </fo:table>
 </xsl:template>
</xsl:stylesheet>

My Expected result is to see the following sort of table form...
6mm Black
EnL 1@ 300mm 400mm 1L
EnR 1@ 300mm 400mm 1L
Shelf 1@ 250mm 388mm 1L

6mm White
Back 1@ 300mm 400mm 1L
Bottom 1@ 294mm 388mm 1L
Shelf 2@ 250mm 388mm 1L
Top 1@ 294mm 388mm 1L

But What I am seeing is:
6mm Black
EnL 1@ 300mm 400mm 1L
EnR 1@ 300mm 400mm 1L
Shelf 1@ 250mm 388mm 1L

6mm White
Back 1@ 300mm 400mm 1L
Bottom 1@ 294mm 388mm 1L
Shelf 2@ 250mm 388mm 1L
Top 1@ 294mm 388mm 1L

6mm Black
EnL 1@ 300mm 400mm 1L
EnR 1@ 300mm 400mm 1L
Shelf 1@ 250mm 388mm 1L

6mm White
Back 1@ 300mm 400mm 1L
Bottom 1@ 294mm 388mm 1L
Shelf 2@ 250mm 388mm 1L
Top 1@ 294mm 388mm 1L

The problem is why is it duplicating the task, I cannot seem to get my head around the <for-each> loops are picking up more than I am expecting.
(the original method of this tranformation came from this question, XSL Grouping nodes by multiple similar siblings with multiple similar unknown values)

A: This seems to be a bug in the Xalan processor. It is triggered by the
<xsl:sort select="Comment" />

instruction on line #86. If you remove it, the duplicates will go away.
I should add that I did not try to understand your code, but it seems to me it could be simplified significantly. Perhaps that too could prevent the bug from manifesting itself.

A: A work around has been given to me from an internal source, and it still doesn't change the fact that the answer from @Micahael.hor257k is correct.
if we use;
<xsl:key name="cMaterial" match="Component[DisplayName='Board'][Category='Carcass']" use="concat(generate-id(../../..),'+',Material,'+',Color,'+',DimCut3)" />
<xsl:key name="UcMaterial" match="Component[DisplayName='Board'][Category='Carcass']" use="concat(generate-id(../../..),'+',Material,'+',Color,'+',DimCut3,'+',DimCut2,'+',DimCut1,'+',Comment,'+',Edging,'+',Quantity)" />

Then what we need to do is use another key() of the first one to use inside the loop to prevent the duplication occuring, like so.
<xsl:key name="cMaterial" match="Component[DisplayName='Board'][Category='Carcass']" use="concat(generate-id(../../..),'+',Material,'+',Color,'+',DimCut3)" />
<xsl:key name="cMaterial2" match="Component[DisplayName='Board'][Category='Carcass']" use="concat(generate-id(../../..),'+',Material,'+',Color,'+',DimCut3)" />
    <xsl:key name="UcMaterial" match="Component[DisplayName='Board'][Category='Carcass']" use="concat(generate-id(../../..),'+',Material,'+',Color,'+',DimCut3,'+',DimCut2,'+',DimCut1,'+',Comment,'+',Edging,'+',Quantity)" />

now in the XSL we can change the code slightly to read the below snip;
<xsl:for-each select="VSection/HSection/Component[generate-id()=generate-id(key('cMaterial',concat(generate-id(../../..),'+',Material,'+',Color,'+',DimCut3))[1])]">
                                <xsl:variable name="this" select="." />
                                <fo:table-row>
                                    <fo:table-cell number-columns-spanned="4">
                                                        <fo:block>
                                                            <xsl:value-of select="Material" /><xsl:text>: </xsl:text>
                                                            <xsl:value-of select="Color" /><xsl:text>: </xsl:text>
                                                            <xsl:value-of select="DimCut3" />
                                                        </fo:block>
                                                    </fo:table-cell>
                                    <fo:table-cell><fo:block></fo:block></fo:table-cell>
                                    <fo:table-cell><fo:block></fo:block></fo:table-cell>
                                </fo:table-row>
                                    <xsl:for-each select="key('cMaterial2',concat(generate-id(../../..),'+',$this/Material,'+',$this/Color,'+',$this/DimCut3))">
                                        <xsl:sort select="Comment" />
                                        <xsl:variable name="similar" select="key('UcMaterial',concat(generate-id(../../..),'+',Material,'+',Color,'+',DimCut3,'+',DimCut2,'+',DimCut1,'+',Comment,'+',Edging,'+',Quantity))" />
                                        <xsl:for-each select="../Component[generate-id()=generate-id(key('UcMaterial',concat(generate-id(../../..),'+',Material,'+',Color,'+',DimCut3,'+',DimCut2,'+',DimCut1,'+',Comment,'+',Edging,'+',Quantity))[1])]">
                                            <fo:table-row>
                                                <fo:table-cell><fo:block><xsl:value-of select="Comment" /></fo:block></fo:table-cell>
                                                <fo:table-cell><fo:block><xsl:value-of select="sum($similar/Quantity)" />@</fo:block></fo:table-cell>
                                                <fo:table-cell><fo:block><xsl:value-of select="DimCut1" /></fo:block></fo:table-cell>
                                                <fo:table-cell><fo:block><xsl:value-of select="DimCut2" /></fo:block></fo:table-cell>
                                                <fo:table-cell><fo:block></fo:block></fo:table-cell>
                                                <fo:table-cell><fo:block></fo:block></fo:table-cell>
                                            </fo:table-row>
                                        </xsl:for-each>
                                    </xsl:for-each>
                            </xsl:for-each>

Now we can loop through as expected and avoid the duplication error due to the Xalan Processor.


text:
Q: How to change position of a JLabel? I'm trying to use a timer to change the position of a JLabel, from one spot on my JPanel to another. I'm not sure if I could use say .getLocation(), then change only the horizontal x value, and finally use .setLocation() to effectively modify the JLabel. I've also used .getBounds and .setBounds, but am still unsure how I can obtain the old horizontal x value to change and reapply to the new x value.
The code I tried looks something like this, but neither is a valid way to change the position of the JLabel.
// mPos is an arraylist of JLabels to be moved.

for(int m = 0; m < mPos.size(); m++){
        mPos.get(m).setLocation(getLocation()-100);
    }

or
    for(int m = 0; m < mPos.size(); m++){
        mPos.get(m).setBounds(mPos.get(m).getBounds()-100);
    }

If I could just get the position of the horizontal x value I can change the position of the label.

A: Try with Swing Timer if you are looking for some animation.
Please have a look at How to Use Swing Timers
Here is the sample code:
int delay = 1000; //milliseconds
ActionListener taskPerformer = new ActionListener() {
  public void actionPerformed(ActionEvent evt) {
      //...Perform a task...
  }
};
new Timer(delay, taskPerformer).start();

Find a Sample code here

Sample code: (Move Hello World message 10px horizontally left to right at interval of 200 ms)
private int x = 10;
...
final JPanel panel = new JPanel() {
    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawString("Hello World", x, 10);
    }
};

int delay = 200; // milliseconds
ActionListener taskPerformer = new ActionListener() {
    public void actionPerformed(ActionEvent evt) {
        x += 10;
        if (x > 100) {
            x = 10;
        }
        panel.repaint();
    }
};
new Timer(delay, taskPerformer).start();

A: I made a similar example just so you can get the basic jest of it, try copy pasting this in a new class called "LabelPlay" and it should work fine.
import java.awt.EventQueue;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class LabelPlay {

private JFrame frame;
private JLabel label;
private Random rand;

public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                LabelPlay window = new LabelPlay();
                window.frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

public LabelPlay() {
    initialize();
}

private void initialize() {
    frame = new JFrame();
    frame.setBounds(100, 100, 659, 518);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().setLayout(null);

    label = new JLabel("YEEEHAH!");
    label.setBounds(101, 62, 54, 21);
    frame.getContentPane().add(label);

    JButton btnAction = new JButton("Action!");
    rand = new Random();
    btnAction.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            int a = rand.nextInt(90)+10;
            int b = rand.nextInt(90)+10;
            int c = rand.nextInt(640)+10;
            int d = rand.nextInt(500)+10;
            label.setBounds(a, b, c, d);
        }
    });
    btnAction.setBounds(524, 427, 89, 23);
    frame.getContentPane().add(btnAction);

}

}
If you want this to happen in a loop at certain times, you can just put it in a loop and use Thread.sleep(amount of miliseconds) in the loop before you run the code.

A: Why don't you create a JLabel at position a, set it to visible, and another one at position b, setting it to not visible? After the timer is up, hide the first and show the second.

A: Are you planning on creating some moving imageIcon for some type of game? Or some label that moves pretty much everywhere ?
I would use an Absolute Layout and set Location manually everytime.
myPanel.setLayout(null);

// an initial point
int x = 100;
int y =100;

while (
    //some moving pattern
    x++;   // 1 pixel per loop
    y+=2;  // 2 pixels per loop
    myLabel.setLocation(x,y);
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why can't I click on a file? I would like to use tkinter with plotting. But I just want to click on a button and read the location of the file but I can't click on a file, I don't know at all where is the problem ? Here is my code :
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Button

import tkinter as tk
from tkinter.filedialog import askopenfilename

figure, ax1 = plt.subplots()

class Index(object):
    def next(self,event):
        root = tk.Tk()
        root.withdraw()
        file_name = askopenfilename()
        print(file_name)

callback = Index()
axnext = plt.axes([0.11,0.9,0.1,0.075])
bnext = Button(axnext, 'Open')
bnext.on_clicked(callback.next)

plt.show()

I don't understand when I click on Open I can't select file it is like the click was disabled.


text:
Q: **Undefined reference** error while linking two libraries referring to one-another I am getting undefined reference error while trying to compile main that refers to two libraries. I have two files lib1/func1.c and lib2/func2.c in separate folders. Those files contain two functions print1() and print2(), function print1() is calling print2().
I am compiling those separately into two libraries libfunc1.a and libfunc2.a.
But when I am trying to compile main which is calling print1(), I get the following error:
/usr/bin/ld: /home/sv/ztest2/lib1/libfunc1.a(func1.o): in function print1:
/home/sv/ztest2/lib1/func1.c:7: undefined reference to print2
collect2: error: ld returned 1 exit status
make: *** [Makefile:21: DP] Error 1

Here is the code and Makefiles:
Makefile:
TARGET = DP
HOME = /home/slav/FORECAST/ztest2

INCDIRS = -I./ \
      -I$(HOME)/lib1 \
      -I$(HOME)/lib2

LIBDIRS = -L$(HOME)/lib1 \
      -L$(HOME)/lib2

SRCFILES = DP.c
OBJFILES = DP.o

CFLAGS = -g -O3 $(INCDIRS)

all: $(TARGET)

$(TARGET): $(OBJFILES)
    cc $(CFLAGS) -o $(TARGET) $(OBJFILES) $(LIBDIRS) -lfunc2 -lfunc1

clean:
    -rm *.o $(TARGET)

DP.c:
#include "func1.h"
int main()
{
    print1();
    return 0;
}

func1.h:
void print1();

func1.c:
#include <stdio.h>
void print1()
{
    printf("print1 is called!\n");
    print2();
}

func2.h:
extern void print2();

func2.c:
#include <stdio.h>
void print2()
{
    printf("print2 is called!\n");
}

A: Libraries must be listed in the order their symbols are needed.
The command cc $(CFLAGS) -o $(TARGET) $(OBJFILES) $(LIBDIRS) -lfunc2 -lfunc1 tells the linker to first use the func2 library to resolve any pending references in the executable it is building and then to use the func1 library.
Since the linker processes func2 first, and, at the time it does so, there is no pending reference to print2, the linker does not include the module with print2 in the executable.
Later, when the linker is processing func1, it includes the module with print1 in the executable because main uses it. That module print1 uses print2, so including that module adds a new reference to print2. Then, when the linker is done processing func1, it has an unresolved reference. The linker does not go back to func2 to check it again.
Since the func1 library depends on func2, change the link command to cc $(CFLAGS) -o $(TARGET) $(OBJFILES) $(LIBDIRS) -lfunc1 -lfunc2.
(If the func2 library also depends on func1, that is a bad design and should be reconsidered. If it is not changed, asking the linker to reconsider the libraries multiple times, as with -lfunc1 -lfunc2 -lfunc1, might fix the immediate problem, but others can arise.)


text:
Q: How do you interpret negative levels in Mathematica? I am trying to gain a deeper understanding of how Mathematica expressions are represented internally, and am puzzled by the logic of the Level command in Mathematica.  If we have the following input:
In[1]:= a = z*Sin[x + y] + z1*Cos[x1 + y1]

Out[1]= z1 Cos[x1 + y1] + z Sin[x + y]

In[2]:= FullForm[a]

Out[2]= Plus[Times[z1,Cos[Plus[x1,y1]]],Times[z,Sin[Plus[x,y]]]]

In[3]:= TreeForm[a]

We get the following tree:

If we ask Mathematica to return Level 4 only, we get:
In[4]:= Level[a,{4}]
Out[4]= {x1,y1,x,y}

I understand that we are 4 levels down from the "stem" (the Plus operator at Level 0).  In fact, I think I understand that positive indexes are always in relation to the stem position of the tree.  (I hope I'm correct about that??)
In contrast, when you ask for a negative level, there is no common reference point (like the stem above), because different branches of the tree are of varying lengths.  So, if you ask Mathematica to provide only Level -1, we get:
In[6]:= Level[a,{-1}]
Out[6]= {z1,x1,y1,z,x,y}

I was surprised by this output, when I had guessed that I should get back {x1, y1, x, y} (without z1 & z).  But ok, if I try to understand this, I take -1 to mean "the end of each branch".  If this is so, then I would expect Level[a,{-2}] to return:
{z1*Cos[x1+y1],z*Sin[x+y],x1+y1,x+y}

But, this is not what I get back, Mathematica yields:
In[8]:= Level[a,{-2}]
Out[8]= {x1+y1,x+y}

So, now I am confused, and don't see a consistent way of understanding the output of negative levels.
Is there a consistent, easier way of understanding this topic?  Is there a certain "correct" way I should be reading the structure of the tree?
Sorry for the "long-winded question", but I hope you understand what I am asking.

A: If you look at the docs, they say:

A negative level -n consists of all parts of expr with depth n.

So negative levels are not counted from a reference point, but are defined based on the depth of subexpressions.  z1*Cos[x1+y1] is of depth 4, so it's not returned when you ask for Level[..., {-2}].


text:
Q: Fixed/frozen left column in table...but when table is wrapped I have a very similar scenario to the one described in how do I create an HTML table with fixed/frozen left column and scrollable body?. Essentially, that works for me but I need my table to be contained in a div which will be sitted next to another div (so, the scrollable table will have an options panel on the left side). The structure is:

All table contents here...

Unfortunately the solution proposed in the original question doesn't seem to work when the div is sit next to another, the absolute positioning of the left column will take it all the way left. See a fiddle here http://jsfiddle.net/odiseo/YMvk9/7106/

A: Okay so you could do the following:
Replace left:0 in .headcol with transform: translatex(-5em); and then add float:left; to #second.


text:
Q: Integral Expression in Complex Dynamics Let $\phi\in \mathbb{C}(z)$ be a degree $d\geq 2$ rational map, which we can write as $\phi = \frac{f}{g}$ for $f,g\in \mathbb{C}[z]$. Let $\omega_{FS}$ denote the Fubini-Study form on $\mathbb{P}^1(\mathbb{C})$. I recently came across the following integral expression:
$\int_{\mathbb{P}^1(\mathbb{C})} ||\phi(z) - z||^2 \omega_{FS}$,
where $||\cdot - \cdot||$ denotes the chordal metric on $\mathbb{P}^1(\mathbb{C})$. There is an analogous expression over $\mathbb{R}$:
$\int_{\mathbb{P}^1(\mathbb{R})} ||\phi(x) - x||^2 \omega$,
where here $\omega = \frac{1}{\pi(1+x^2)} dx$.
My question is whether anyone has seen this sort of expression before, and if so whether there is a closed form for this integral expression given in terms of, say, the coefficients of $f$ and $g$? Or in terms of the fixed points of $\phi$?

A: Only a partial and rather distant answer: There is ``this sort of expression" in dynamical Nevanlinna theory. The mean proximity of $f$ with respect to $a \in \hat{\mathbb{C}}$ is defined as
$m(a,f)=\int_{\hat{\mathbb{C}}}\log\frac{1}{[a,f(w)]}d\sigma(w)$, where $\sigma$ is the (normalized) spherical area measure on $\hat{\mathbb{C}}$ and $[\cdot,\cdot]$ the chordal distance normalized so that $[0,\infty]=1$. It can be generalized to a proximity of two holomorphic functions. It appears in the works of M. Sodin, @AlexandreEremenko (who is on MO and might provide a more insightful answer) and, particularly in applications to non-archimedean dynamics, of Y. Okuyama.


text:
Q: There are two dates. How to create a list of the intervals of months between these dates? Example (as 'dd.MM.yyyy HH:mm').

*

*java.util.Date begin  = 21.01.2018 00:00

*java.util.Date end   = 20.03.2018 00:00
I want to create java.util.List<MonthInterval> list like:

*

*21.01.2018 00:00 — 01.02.2018 00:00 (or 31.01.2018 23:59:59)

*01.02.2018 00:00 — 01.03.2018 00:00

*01.03.2018 00:00 — 20.03.2018 00:00

My Class:
class MonthInterval {
    Date monthBegin, monthEnd;
}

I tried to do it myself. However, in the class java.util.Calendar I did not understand how to calculate the number of days in this or another month for this year. But I think I went the wrong way. Any ideas?

A: You should really use java.time API, there is some interesting stuff, using
class MonthInterval {

    static DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm");

    LocalDateTime monthBegin, monthEnd;

    public MonthInterval(LocalDateTime monthBegin, LocalDateTime monthEnd) {
        this.monthBegin = monthBegin;
        this.monthEnd = monthEnd;
    }

    @Override
    public String toString() {
        return monthBegin.format(formatter) + " > " + monthEnd.format(formatter);
    }
}

You can do different ways, like

*

*With do-while loop
static List<MonthInterval> list(LocalDateTime begin, LocalDateTime end) {
    List<MonthInterval> list = new ArrayList<>();
    LocalDateTime nextDayMonth;
    do {
        nextDayMonth = begin.plusMonths(1).withDayOfMonth(1);
        list.add(new MonthInterval(begin, nextDayMonth));
        begin = nextDayMonth;
    } while (nextDayMonth.getMonthValue() != end.getMonthValue());
    list.add(new MonthInterval(begin, end));
    return list;
}

*With for-i loop
static List<MonthInterval> list(LocalDateTime begin, LocalDateTime end) {
    List<MonthInterval> list = new ArrayList<>();
    LocalDateTime nextDayMonth;
    for (int i = 0; i < ChronoUnit.MONTHS.between(begin, end) + 1; i++) {
        nextDayMonth = begin.plusMonths(1).withDayOfMonth(1);
        list.add(new MonthInterval(begin, nextDayMonth));
        begin = nextDayMonth;
    }
    list.add(new MonthInterval(begin, end));
    return list;
}

To use as
static DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm");

public static void main(String[] args) {
    LocalDateTime begin = LocalDateTime.parse("21.01.2018 00:00", formatter);
    LocalDateTime end = LocalDateTime.parse("20.03.2018 00:00", formatter);
    list(begin, end).forEach(System.out::println);
}

// And get
21.01.2018 00:00 > 01.02.2018 00:00
01.02.2018 00:00 > 01.03.2018 00:00
01.03.2018 00:00 > 20.03.2018 00:00

A: tl;dr
Interval.of(
    LocalDateTime.parse(                                    // Represent a date and a time-of-day but lacking a time zone or offset-from-UTC. So *not* a moment.
        "21.01.2018 00:00" ,
        DateTimeFormatter.ofPattern( "dd.MM.uuuu HH:mm" )   // Specify formatting pattern to match input strings.
    )                                                       // Returns a `LocalDateTime` object.
    .atZone(                                                // Apply a time zone to determine a moment.
        ZoneId.of( "Pacific/Auckland" )                     // Always use proper time zone in `Continent/Region` format, never 2-4 letter codes such as `IST` or `EST` or `PST`.
    )                                                       // Returns a `ZonedDateTime` object.
    .toInstant() ,                                          // Convert from a `ZonedDateTime` object to a `Instant` to adjust into UTC.
    …                                                       // Do the same as the above (the starting point) but for the stopping point.
)                                                           // Returns a `org.threeten.extra.Interval` object.
.toString()                                                 // Generate text representing both moments of this interval in standard ISO 8601 format, delimited by a `/` SOLIDUS character.

Avoid legacy date-time classes
Never use java.util.Date. That awful class was supplanted years ago by the modern java.time classes.
ThreeTen-Extra
The other Answer by azro is headed in the right direction. But there is no need to invent your own interval class. Look to the existing tried-and-true classes found in the ThreeTen-Extra project. That project is led by the same man, Stephen Colebourne, who led the JSR 310 java.time project and the Joda-Time project.
In the ThreeTen-Extra library you will find two class to represent a span-of-time attached to the timeline.

*

*Interval — A pair of moments in UTC, Instant objects.

*LocalDateRange — A pair of date-only values, LocalDate objects.

Moments
If you meant moments, parse your input strings at LocalDateTime objects. This are not moments, only potential moments, as they lack a time zone or offset-from-UTC.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd.MM.uuuu HH:mm" ) ;
LocalDateTime ldt = LocalDateTime.parse( "21.01.2018 00:00" , f ) ;

Give those LocalDateTime real meaning by assigning a time zone to determine actual moment.
ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
ZonedDateTime zdt = ldt.atZone( z ) ;

Adjust into UTC by extracting Instant. An Instant represents a moment always in UTC.
Instant instant = zdt.toInstant() ;

Pass a pair of such Instant objects to get an Interval.
org.threeten.extra.Interval interval = Interval.of( start , stop ) ;

You can compare Interval objects with handy methods such as isBefore, isAfter, overlaps, contains, encloses, and so on.
Dates
If you are focusing only on dates rather than moments, then use LocalDateRange. We must still process your inputs as seen above, as the date varies around the globe for any given moment. For example, a few minutes after midnight in Paris France is "tomorrow" while still "yesterday" in Montréal Québec.
For the dates, take the ZonedDateTime objects seen above and extract a LocalDate.
LocalDate ld = zdt.toLocalDate() ;  // Extract the date as seen at that moment through the wall-clock time used by the people of that region (that time zone).

Make a LocalDateRange with such dates
org.threeten.extra.LocalDateRange ldr = LocalDateRange.of( start , stop ) ;

Like Interval, the LocalDateRange class offers handy comparison methods such as overlaps, contains, etc.
Half-Open

21.01.2018 00:00 — 01.02.2018 00:00 (or 31.01.2018 23:59:59)

No, do not define a span-of-time by its last possible moment. That is awkward and problematic. One problem is an infinitely divisible fractional second.
Instead, use Half-Open method: the beginning is inclusive, while the ending is exclusive.
Search Stack Overflow for much more info.

About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?

*

*Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later  - Part of the standard Java API with a bundled implementation.

*

*Java 9 adds some minor features and fixes.

*Java SE 6 and Java SE 7

*

*Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.

*Android

*

*Later versions of Android bundle implementations of the java.time classes.

*For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.


text:
Q: Fetch results added today no earlier I am having trouble wrapping my head around a query I'm supposed to write.
I've got two tables: stock and articles
Columns in articles:

*

*id

*name

*price

Columns in stock:

*

*id

*articleId

*tstamp_in (yyyy-mm-dd hh:mm:ss)

For every article that is delivered to me by my suppliers, I create a new row in the stock table. That means that every article can have multiple rows in the stock table. One of my colleges asked if I could supply a list that shows him all new articles, so in other words all records from stock that have a tstamp_in value higher than last midnight.
I came to the following query but I really cant figure out how to get the result I am looking for.
SELECT *
FROM stock
LEFT JOIN articles ON stock.articleId=articles.id
WHERE tstamp_in>'2015-01-12 00:00:00'

This gives me all records in the stock table created after last midnight. However this does not mean that there aren't any previous records. What I'm trying to figure out is how I can get this in one query.
In short:
Select all from stock grouped by articleId where tstamp_in > 2015-01-12 00:00:00 and not having records with that articleId before 2015-01-12 00:00:00
Is this possible?

A: Think of the the problem a bit differently.  For what articles is the earliest tstamp_in today?  That leads you to an aggregation and having:
select s.articleId
from stock s
group by s.articleId
having min(tstamp_in) > '2015-01-12'


text:
Q: How to display a .jpg file using fbi in a bash script for set amount of time and then execute the next command in the script I am trying to use fbi in a bash script to display a series of .jpg images. But once fbi begins its process, it continues to cycle through the images and I only want to display each image once for a set period of time.

A: Disclaimer: I didn't actually test this with fbi, I used watch with a bunch of text files (watch displays text, not images, but it also runs until it's killed, like fbi), so in theory this (or similar) technique should also work with fbi.
#!/bin/sh

# Where are the files?
IMG_PATH="/foo/bar/fred/"

cd $IMG_PATH

# File list. Can either be hard-coded, space separated,
# or to use the output of a command, use $(command). The
# safest approach is to use a shell glob as I have done here.
FILE_LIST=*.txt

# How long to run the command in seconds before killing it?
TIMEOUT=1

# For every file on the list...
for FILE in $FILE_LIST
do
  # OK, this is where the magic happens...
  # First invoke a shell and feed the mini script (in double quotes)
  # to that shell. The mini script first executes fbi with whatever
  # filename is now set to $FILE by the loop, meanwhile, whatever is
  # in brackets gets executed simultaneously (sleep for $TIMEOUT seconds
  # then force kill the second shell and all its children, including fbi).
  # What the heck is \$\$? Well, $$ normally refers to the process ID
  # of the script itself. But we don't want to kill the main script with
  # the for loop - we want to loop to go on. So we escape the $$ with
  # backslashes like so \$\$ so that literally "$$" gets passed to the
  # second subshell, so it kills only itself (and fbi as its child).
  #########################
  # You can add parameters to fbi if you need to.
  # Also you may want to try removing the -9 parameter to kill in
  # case it messes up your framebuffer... not sure how well fbi
  # handles a forceful (-9) vs. graceful (no -9) kill.
  sh -c "(sleep $TIMEOUT; kill -9 \$\$) & exec fbi $FILE"
done

I hope that this at least points you in the right direction... :)


text:
Q: Error in Bazel Build Installation of Tensorflow From Source Recently, I have attempted to install the TensorFlow module from source on a MacOS computer. I have, so far, progressed by installing Python 3.6, the TensorFlow pip package dependencies (I have already installed pip) and installing Bazel using the commands given on their website. I configured the source tree, first with Python 3.6 and later with 2.7 after learning of this error. However, soon after, when I entered the command:
bazel build -config=opt//tensorflow/tools/pip_package:build_pip_package

I received this message:
Starting local Bazel server and connecting to it...
INFO: Invocation ID: 2028ac42-5ccd-4c28-9156-e7d547c89263
ERROR:          /private/var/tmp/_bazel_surengrigorian/c9e5c7de228d990fbf93866f2deac188/external/local_config_cc/BUILD:58:5: in apple_cc_toolchain rule
@local_config_cc//:cc-compiler-watchos_arm64_32: Xcode version must   be specified to use an Apple CROSSTOOL. If your Xcode version has    changed recently, try: "bazel clean --expunge" to re-run Xcode   configuration
ERROR: Analysis of target '//tensorflow/tools/pip_package:build_pip_package' failed; build   aborted: Analysis of target '@local_config_cc//:cc-compiler-   watchos_arm64_32' failed; build aborted
INFO: Elapsed time: 11.538s
INFO: 0 processes.
FAILED: Build did NOT complete successfully (171 packages loaded,    3109 targets\
configured)
    currently loading: tensorflow/core/kernels
    Fetching @swig; fetching 4s
    Fetching @grpc; fetching

Thank you for any assistance you can provide as to how to fix this error.

A: I had the same issue. I solved it by downgrading the Bazel version. In my case, Bazel 21.0 did not work. Reinstalling bazel to 18.0 works fine. https://github.com/bazelbuild/bazel/releases/tag/0.18.0

A: Downgrading to Bazel 0.29.1 worked for me.


text:
Q: addition and multiplication of functions in function space, continuous? I have a norm that works in function space of C[0,1]. How do I show that addition and multiplication of functions (C[0,1]xC[0,1]->C[0,1]) are continuous functions?

A:
*

*To use C[0,1] to show continuity within Function Composition you will have to take into consideration only a few concepts for concluding that (C[0,1]xC[0,1]->C[0,1]) can create a paradigm for continuous functions [within structures].

*We will assume that C[0,1] can become a Function of Several Real Variables by using a seminorm. In a Euclidean norm Vector spaces must be allowed to use (0,0) for magnitude within any cartesian. So, we have precedent for understanding how norms can function as both zero vector spaces, by using (0,1) you actually solve your own problem by assigning an Integer [at least 1].

*

*Proving Continuity and Limit:

*

*Consider the distance function of ℝᵤ, where

C[0,1] ≐ d ≑ d(x,y)=d(x₁,…,xᵤ,y₁,...yᵤ)= √((x₁-y₁)²+…+(xᵤ-yᵤ)²)

Proving Continuity and Limit:

consider the function ƒ in C[0,1] such that ƒ(0,0)=0 is otherwise defined by
      ƒ(x,y)=x²y/x²*²+y²

The functions
x→C(x,0)
         and
y→C(0,y)
        are both constant and equal to zero, and are therefore continuous

*Providing C[0,1] as a seminorm and concluding its use for Functional Continuity :

*

*For every real number

ε > 0 and δ > 0
                   such that
                  ∣ƒ(x)—L<ε∣
x evaluates in its domain as
               d(x,a) < δ

If the limit exists, it is unique.
            If a is in the interior of the domain:
            The limit exists if and only if the function is continuous at a
            For our instance
ƒ(a)=lim┬(x→a)  ƒ(x)

*When a is in the boundary of the domain of f

f has a limit at a
               the latter formula allows the extension of continuity

which essentially is the domain of

f to a

So since the seminorm C[0,1] can accommodate a series of functions, such as;
C(x,y)=C(x,y)=C(x₁,…,xᵤ,y₁,...yᵤ)= √((x₁-y₁)²+…+(xᵤ-yᵤ)²)

On another note, I believe that Functional Composition can restate:
ξ : X→Ξ
ζ : Ξ→ℝ


text:
Q: Is there a non-constructive proof that the determinant exists? Let $k$ be a field where $2\neq0$, and $V$ an $n$-dimensional $k$-vector space. Then there exists a unique function $\det:V^n\to k$ that has the following properties:

*

*$\det$ is multilinear (linear in each variable)

*$\det$ is alternating (permuting two arguments changes the sign)

*$\det(B)=1$ for some basis $B$
Without providing an explicit formula (à la Leibniz), how can existence be proved?

A: A standard approach is to use the machine of wedge products (alternating tensors):

*

*Pick a basis: $B = \{ v_1,\dots,v_n \}$ for $V$ over a field $\mathbb{K}$.

*Construct tensor product powers of $V^{\otimes k} = V \otimes \cdots \otimes V$ ($k$-copies).

*Quotient by the subspace $U$ spanned by vectors of the form: $a_1 \otimes \cdots \otimes a_k$ where $a_i=a_j$ for some $i \not= j$. Call such a space $\wedge^k V = V^{\otimes k}/U$. Let $w_1 \wedge \cdots \wedge w_k = w_1\otimes \cdots \otimes w_k + U$ (the coset represented by $w_1\otimes \cdots \otimes w_k$).

*Prove that $B_k = \{ v_{i_1} \wedge \cdots \wedge v_{i_k} \;|\; i_1 < i_2 < \cdots < i_k \}$ is a basis for $\wedge^k V$. This means $\dim(\wedge^k V) = {n \choose k} = \dfrac{n!}{k!(n-k)!}$. In particular, $\wedge^n V$ is $1$-dimensional and has basis $v_1\wedge \cdots \wedge v_n$.

*The dual space $(\wedge^n V)^* = \{ f:\wedge^n V \to \mathbb{K} \;|\; f \mbox{ is linear }\}$ is $1$-dimensional. Select the unique linear functional $D$ such that
$D(v_1 \wedge \cdots \wedge v_n) =1$ (i.e., $\{D\}$ is the basis dual to $\{v_1\wedge\cdots \wedge v_n \}$).

*One can show that every $k$-multilinear map $\hat{f}:V \times \cdots \times V \to W$ uniquely factors as $\hat{f}(w_1,\dots,w_k) = f(w_1 \otimes \cdots \otimes w_k)$ where $f:V^{\otimes k} \to W$ is linear (this universal property essentially defines what a tensor product is). Likewise, every alternating $k$-multilinear map $\hat{f}$ factors as $\hat{f}(w_1,\dots,w_k) = f(w_1\wedge \cdots \wedge w_k)$ where $f:\wedge^k V \to W$ is linear (this universal property captures what $\wedge^k V$ is).

*Finally, the alternating, multilinear map, $\hat{D}=\det$ associated with $D$ is the unique such map such that $\det(v_1,\dots,v_n)=1$.
Or you could just construct the determinant. :)


text:
Q: How do I transfer a javascript value to a php variable? I have an html table containing values that are being generated from javascript.  How do I transfer those values to php variables?

A: Encode the table contents as JSON and POST it to your PHP script.

A: What you are going to want to do is make an AJAX request to a PHP file with the data you want somewhere in the request. You can do this with POST or GET variables. If you haven't used AJAX before I would recommend you have a look at jQuery's documentation of it.

A: Using jQuery, you can get the value for the input named "music" as follows:
var value = $("input[name$='music']").val();

You can then use the jQuery AJAX libraries to send it somewhere, and it will then be available to the using script in $_GET or $_POST, depending on the AJAX method used, e.g.
var value = $("input[name$='music']").val();
$.post('somewhere.php', { 'music' : value });

And the PHP would be something like
<?php
if (!empty($_POST['music'])) {
  echo 'Received music: ' . htmlentities($_POST['music'], ENT_QUOTES, 'UTF-8');
}
?>

A: I think you most likely want to actually calculate the values in php and return them to the html table.
If this isn't what you actually want then you need to make a request to the php script. You can do this using a form that gets submitted.


text:
Q: How to close a `Userform` after clicking a button I have a Corel Draw issue using Exit Sub to close a Userform after clicking a button.
It will run the script to completion, but  won't execute the Exit Sub command.

I tried setting a dummy variable to a true value If X=1 then Exit Sub but that didn't do the trick either.
Private Sub CommandButton1_Click()
MsgBox "Script Ran!"
Exit Sub
End Sub

My hope is to click a button, and have the userform close after it runs. My impression was Exit Sub is the way to do this.

A: Exit Sub functions as an exit point of the current Sub.
Having it before End Sub does literally nothing except leaving the Sub one line earlier.
What you want is Unload Me.
See the relevant VBA documentation of the Unload Statement.


text:
Q: Create new column with max value with groupby From the following dataframe, I am trying to add a new column, with the condition that for every id check the maximium value. Then place the maximium value for each row of every id in the new column.
df

id  value
1   0
1   0
1   0
2   0
2   1
3   1
3   1

Expected result:
id  value new_column
1   0     0
1   0     0
1   0     0
2   0     1
2   1     1
3   1     1
3   1     1

I have tried:
df['new_column'] = df.groupby(['id'])['value'].idxmax()

Or:
df['new_column'] = df.groupby(['id'])['value'].max()

But neither of these give the desired result.

A: You need to use transform for this:
df['new_column'] = df.groupby(['id'])['value'].transform('max')

This more succinctly replicates the following:
df['new_column'] = df['id'].map(df.groupby(['id'])['value'].max())

Remember that the result of a groupby operation is a series with index set to grouper column(s).
Since indices are not aligned between your original dataframe and the groupby object, assignment will not happen automatically.


text:
Q: Why doesn't my code in "test.py" display anything when I "import test"? I have this code in a file called test.py:
person = {'name': 'Jemm', 'age': '23'}
sentence = 'My name is ' + person['name'] + 'and i am' + person['age'] + 'years old.'

print(sentence)

When I try import test, I don't get any output. Why?

A: >>> import test
>>> print(test)
<module 'test' from '/opt/local/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/test/__init__.py'>

There is a test module in Python itself. Be sure you are running your module. You must be in the same directory as your file test.py to import your file instead of the Python one.
Update: Python uses a search path list mechanism for finding modules when importing. The "current working directory" is usually at the first place in this list (the empty string). See PYTHONPATH and sys.path.
You can add your own path(s) into PYTHONPATH (in shell/command line) or sys.path (in Python).

A: I guess the problem is that you didn't save the file after you did all the code in test.py, what happens if save it then run import test somewhere else, that's what i think
Also as Messa said, "There is a test module in Python itself. Be sure you are running your module. You must be in the same directory as your file test.py to import your file instead of the Python one." that's also useful information, have to be same directory as test.py (your file)
If you're not in the same directory, do:
__import__('whole filepath')

For it.


text:
Q: Broadcasting UDP packets using multiple NICs I'm building an embedded system for a camera controller in Linux (not real-time).  I'm having a problem getting the networking to do what I want it to do.  The system has 3 NICs, 1 100base-T and 2 gigabit ports.  I hook the slower one up to the camera (that's all it supports) and the faster ones are point-to-point connections to other machines.  What I am attempting to do is get an image from the camera, do a little processing, then broadcast it using UDP to each of the other NICs.
Here is my network configuration:
eth0: addr: 192.168.1.200 Bcast 192.168.1.255 Mask: 255.255.255.0  (this is the 100base-t)
eth1: addr: 192.168.2.100 Bcast 192.168.2.255 Mask: 255.255.255.0
eth2: addr: 192.168.3.100 Bcast 192.168.3.255 Mask: 255.255.255.0
The image is coming in off eth0 in a proprietary protocol, so it's a raw socket.  I can broadcast it to eth1 or eth2 just fine.  But when I try to broadcast it to both, one after the other, I get lots of network hiccups and errors on eth0.
I initialize the UDP sockets like this:
sock2=socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP); // Or sock3
sa.sin_family=AF_INET;
sa.sin_port=htons(8000);
inet_aton("192.168.2.255",&sa.sin_addr); // Or 192.168.3.255
setsockopt(sock2, SOL_SOCKET, SO_BROADCAST, &broadcast, sizeof(broadcast));
bind(sock2,(sockaddr*)&sa,sizeof(sa));

sendto(sock2,&data,sizeof(data),0,(sockaddr*)&sa,sizeof(sa)); // sizeof(data)<1100 bytes

I do this for each socket separately, and call sendto separately.  When I do one or the other, it's fine.  When I try to send on both, eth0 starts getting bad packets.
Any ideas on why this is happening?  Is it a configuration error, is there a better way to do this?
EDIT:
Thanks for all the help, I've been trying some things and looking into this more.  The issue does not appear to be broadcasting, strictly speaking.  I replaced the broadcast code with a unicast command and it has the same behavior.  I think I understand the behavior better, but not how to fix it.
Here is what is happening.  On eth0 I am supposed to get an image every 50ms.  When I send out an image on eth1 (or 2) it takes about 1.5ms to send the image.  When I try to send on both eth1 and eth2 at the same time it takes about 45ms, occasionally jumping to 90ms.  When this goes beyond the 50ms window, eth0's buffer starts to build.  I lose packets when the buffer gets full, of course.
So my revised question.  Why would it go from 1.5ms to 45ms just by going from one ethernet port to two?
Here is my initialization code:
sock[i]=socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP);
sa[i].sin_family=AF_INET;
sa[i].sin_port=htons(8000);
inet_aton(ip,&sa[i].sin_addr);

//If Broadcasting
char buffer[]="eth1" // or eth2
setsockopt(sock[i],SOL_SOCKET,SO_BINDTODEVICE,buffer,5);
int b=1;
setsockopt(sock[i],SOL_SOCKET,SO_BROADCAST,&b,sizeof(b));

Here is my sending code:
for(i=0;i<65;i++) {
  sendto(sock[0],&data[i],sizeof(data),0,sa[0],sizeof(sa[0]));
  sendto(sock[1],&data[i],sizeof(data),0,sa[1],sizeof(sa[1]));
}

It's pretty basic.
Any ideas?  Thanks for all your great help!
Paul

A: Maybe your UDP stack runs out of memory?
(1) Check /proc/sys/net/ipv4/udp_mem (see man 7 udp for details). Make sure that the first number is at least 8x times the image size. This sets the memory for all UDP sockets in the system.
(2) Make sure you per-socket buffer for sending socket is big enough. Use setsockopt(sock2, SOL_SOCKET, SO_SNDBUF, image_size*2) to set send buffer on both sockets. You might need to increase maximumu allowed value in /proc/sys/net/core/wmem_max. See man 7 socket for details.
(3) You might as well increase RX buffer for receiving socket. Write a big number to .../rmem_max, then use SO_RCVBUF to increase the receiving buffer size.

A: A workaround until this issue is actually solved may be to createa  bridge for eth1+eth2 and send the packet to that bridge.
Thus it's only mapped to kernel-memory once and not twice per image.

A: It's been a long time, but I found the answer to my question, so I thought I would put it here in case anyone else ever finds it.
The two Gigabit Ethernet ports were actually on a PCI bridge off the PCI-express bus.  The PCI-express bus was internal to the motherboard, but it was a PCI bus going to the cards.  The bridge and the bus did not have enough bandwidth to actually send out the images that fast.  With only one NIC enabled the data was sent to the buffer and it looked very quick to me, but it took much longer to actually get through the bus, out the card, and on to the wire.  The second NIC was slower because the buffer was full.  Although changing the buffer size masked the problem, it did not actually send the data out any faster and I was still getting dropped packets on the third NIC.
In the end, the 100Base-T card was actually built onto the motherboard, therefore had a faster bus to it, resulting in overall faster bandwidth than the gigabit ports..  By switching the camera to a gigabit line and one of the gigabit lines to the 100Base-T line I was able to meet the requirements.
Strange.


text:
Q: Results extraction for a dynamic result using selenium webdriver I am working on application, were I need to provide search criteria available in a database and no. of results displayed are not equal every time.
For Ex: Search with 1234 , it may display 4 results today and 3 results next day, so my requirements are below:

*

*How to provide the search criteria dynamically for under search(BDD).

*How to display the results in console for the given input.

*And I want to display the results and validate by clicking on each and every result.

Note: App is developed using Angular JS. I have tried using WebElement List but it is not extracting for dynamic search result for the drop down only looking in the page.
Also anyone can suggest how to provide search result under Behavioral Driven Development.
Please suggest using Selenium Commands.
Thanks for all your support and co-operations.


text:
Q: cats.ReaderT[F,A,B] from dependency A in for-comprehension Here is a usecase:
import cats.data.ReaderT
trait Service{
  type OptionFromMap[A] = ReaderT[Option, Map[String, String], A]
  def f1(nameKey:String): OptionFromMap[String] = ReaderT(_.get(nameKey))
  def f2(addressKey:String, name:String): OptionFromMap[String] =
    ReaderT(map => Option(s"name: $name, address: ${map(addressKey)}"))
}
trait Service2 {
  type Env = (Service, Map[String,String])
  type OptionFromEnv[A] = ReaderT[Option, Env, A]
  import cats.syntax.applicative._
  import cats.instances.option._
  def f(nameKey:String, addressKey:String): OptionFromEnv[String] =
    for {
      //wrong try:
      s1 <- ReaderT((_:Env) => Option((_:Env)._1))
      //wrong try:
      s2 <- (_:Env).pure[OptionFromEnv]
      name <- s1.f1(nameKey).local((_: Env)._2)
      r <- s1.f2(addressKey, name).local((_: Env)._2)
    } yield r
}

So I want to be able to invoke f1 and f2 methods of Service.
The question is how to do it inside for-comprehension. Via ReaderT.apply, I can get it done via:
  def c(nameKey:String, addressKey:String): OptionFromEnv[String] =
    ReaderT(env =>
      (for {
        name <- env._1.f1(nameKey).local((_: Env)._2)
        r <- env._1.f2(addressKey, name).local((_: Env)._2)
      } yield r)
      .run(env)
    )

But I try to achieve something, that looks like:
import cats.data.Reader
trait Service{
  def f1: Reader[Map[String, Int], Int] = Reader(_("name"))
  def f2: Reader[Map[String, Int], Int] = Reader(_("age"))
}
trait Service2 {
  type Env = (Service, Map[String,Int])
  def f(i: Int): Reader[Env, Int] =
    for {
      s <- Reader((_: Env)._1)          //extract input type Service
      r1 <- s.f1.local((_: Env)._2)
      r2 <- s.f2.local((_: Env)._2)
    } yield r1 + r2 + i
}

A: Try to replace
//wrong try:
s1 <- ReaderT((_:Env) => Option((_:Env)._1))

with
s1 <- ReaderT((env: Env) => Option(env._1))

A: Found additional way to solve it via Kleisli.ask. Cannot say which option is better. Just as an alternative:
trait Service2 {

  def f(nameKey:String, addressKey:String): OptionFromEnv[String] =
    for {
      env <- Kleisli.ask[Option, Env]
      s <- Kleisli.pure(env._1)
      name <- env._1.f1(nameKey).local((_: Env)._2)
      r <- s.f2(addressKey, name).local((_: Env)._2)
    } yield r
}

In general, we have a way to get access to env, inside of the for-comprehension. For sure it is not necessary to get also s from env.


text:
Q: DolphinDB HttpClient error message "url must be a string scalar" I got the following error message when using HttpClient in DolphinDB:
url must be a string scalar

Does anyone know what to do with this error message? Thanks!

A: The plugin version needs to match the DolphinDB server version. Right now the plugin version is 130 so you need to get server version 1.30


text:
Q: color of QPushButton or QToolButton I am using a Qstylesheet to control the behavior of some QPushButtons and QToolButtons.  When I hover over them, they turn black, as I want them to.  However, once I press them, they turn a funny greyish reddish color, and there is a red box drawn inside of them.
What is the property or pseudo state that I have to set in order to avoid this behavior?  I have been through all the properties related to selection, and background, and cant get this to go away

A: Without seeing your style it's a little difficult to fix your problem.  So what I'll do is explain a little how things work, and hopefully you can decide how best to address your problem.
First, it's important when your styling your button to ensure that you cover all your bases.  I'm sure you know most of this, but just in case...
A QPushButton and QToolButton have a number of states that can be styled, so you want to make sure that you make your button noticeably different for each state so that the user can tell the difference.
QPushButton
{
   //  The default look of your button
}

QPushButton:disabled
{
}

QPushButton:pressed
{
}

QPushButton:focus
{
}

QPushButton:hover
{
}

QPushButton:checked
{
}

Use things like the background color, foreground color, border color, and generally you are good to go.
background-color: red;
color: white;  // foreground color
border-width: 1px;
border-color: black;

The second thing to know is this, styles can be inherited.  So be really careful when you add a style to a widget.  When you create a style try to be specific.  If you give this style to something in your UI, the background color will be blue, but the dangerous thing, is that all child widgets of this one will also inherit this style.
QWidget
{
    background-color: blue;
}

Maybe that's what you want, but often not.  So if you are styling buttons always put the QPushButton or QToolButton selector around them, the same should apply for other things you are styling too.  So it's possible that's where your greyish reddish color is coming from.
Now, the last thing to know about styling buttons is the focus rectangle. It is the irritating dotted line that appears when your button has been focussed.  See the picture below.

The unfortunate thing is that there is there is no way to style the focus rectangle using style sheets. But you can get rid of it, if that's what you want. See the following link:
Getting rid of the focus rectangle
So, in summary...

*

*Make sure that your button style covers all the states that you
need.

*Make sure that your button isn't influenced by any other
    styles you have added to other widgets.

*Either change, or get rid
    of the focus rectangle as needed.

I hope that helps.  If you want more specific help, then please post your style, and I'll take a look at it.


text:
Q: How to remove the element from DOM in Jquery I need to remove the below 3 DOM elements using Jquery based on my custom condition, Please help me , I am new to Jquery. Its not repeat question.
Here is the Image Link - https://imgur.com/a/3K7dbpH
Please help me.
I have tried this, it did not fix the issue -
thiz.element.find('input[name=IsGovernment' + thiz.options.customerId + ']).hide();

From UI I don't want to see the Label and radio button options based on some condition.

A: There are a few problems. First, you mispelled this. Instead of this you have "thiz" at the the beginning of your code and in the selector.
The other problem is that you have an an incorrect ' at the end of your selector. An easy way to fix the problem is to use " instead of ' for the entire string inside the selector, and then use ' for the attribute value inside the attribute selector.
So putting everything together, it should be like this:
this.element.find("input[name='IsGovernment" + this.options.customerId + "']").hide();

If you want to hide both the <input> and its sibling <span>, you will need to change the above solution to something like this. Notice this hides the parent <label>, so everything inside will be hidden.
$("input[name='IsGovernment" + this.options.customerId + "']").parent().hide();


text:
Q: How does tf.contrib.seq2seq.gather_tree work? How exactly does gather_tree in contrib.seq2seq work? I can see that it takes the predicted ids and beam parent ids and somehow returns the final beams, but what's actually going underneath the hood? There doesn't seem to be any Python code base I could examine to figure it out. The API isn't very explanatory;
Is there any code source for tf.contrib.seq2seq.gather_tree? I am using TensorFlow 1.3 and looking inside gen_beam_search_ops.py doesn't seem helpful.

A: The codes are detailed as follows:
def gather_tree_py(values, parents):
  """Gathers path through a tree backwards from the leave nodes. Used
  to reconstruct beams given their parents."""

  beam_length = values.shape[0]
  num_beams = values.shape[1]
  res = np.zeros_like(values)
  res[-1, :] = values[-1, :]
  for beam_id in range(num_beams):
    parent = parents[-1][beam_id]
    for level in reversed(range(beam_length - 1)):
      res[level, beam_id] = values[level][parent]
      parent = parents[level][parent]
  return np.array(res).astype(values.dtype)

def gather_tree(values, parents):
  """Tensor version of gather_tree_py"""

  res = tf.py_func(
      func=gather_tree_py, inp=[values, parents], Tout=values.dtype)
  res.set_shape(values.get_shape().as_list())
  return res

github: seq2seq beam_search


text:
Q: SQL TempDB PCI-E NVMe card - 4K or 64K Our primary OLTP workload is tempdb heavy (both reads & writes) based on virtual_file_stats DMV, and based on SPs all of which heavily use #tmp tables.
The server has 400GB of memory, more than enough to fit all tables in databases within in.
Tempdb was previously on a local SSD.
We recently bought and installed a Micron PCI-E card, and placed SQL (2016 Ent) tempdb data and log files on it.
However, I did not see a great improvement in performance, for some workloads it was even worse. The vendor specs lists 4K read-write speeds, whereas SQL uses 64KB (right?).
Before I ask the SAN team to run benchmarks on the existing SSD vs new PCI-E disks, would it make sense to format the PCI-E disk as 4KB block size, instead of 64KB.. or does it not make difference for tempdb ?


text:
Q: Flutter Get Number Value from Currency format currently my textfield display in currency format example
IDR 120.000
and i want to get the value as 120000, how can i get that value easily?

A: I would split at the space and parse the remaining part:
var numValue = double.tryParse(currValue.split(' ')[1])


text:
Q: How to order the way in which categories are shown in plotly.graph_objects.Scatterpolar plot I am doing a Dash Project for a company, and I am stuck in plotting a Multiple Trace Radar Chart in plotly.
My current progress looks like this:-

What I want is to find a way to get Data Science and Profile Building theta category close to each other, so that the February-2020 trace is not a line but a fill, similar to how it shows in March-2020 trace. Till now I couldn't find any solution to it.
The data I used to plot the chart is as follows:-

Code for the chart:-
fig = go.Figure()
months = np.unique(df['month'].values).tolist()
months.reverse()
for i in months:
    temp = df.query('month=="{}"'.format(str(i)))
    q = temp['module'].values.tolist()
    r = temp['rating'].values.tolist()
    q.append(q[0])
    r.append(r[0])
    fig.add_trace(go.Scatterpolar(theta=q,r=r,fill='toself',name=str(i),hoveron='points'))
fig.update_layout(
  polar=dict(
    radialaxis=dict(
      visible=True,
      range=[0, 10]
    )),
  showlegend=True
)
fig.show()

Any help would be greatly appreciated! Thanks in Advance


text:
Q: javascriptexecutor not working with angularjs forms I am trying to automate a login form by selenium webdriver (javascriptexucutor) which is built in angularjs. The script is entering data in email textbox; but when submit button is clicked error message shows that textbox is not filled. I have also used events like onkeyup, blur; but error shows these functions are not accepted. Textbox validaton works fine with sendkeys() and it takes time; but facing issue when javascriptexecutor is used.
html code:
<input type="text" ng-keypress="logindata($event)" ng-model="email" placeholder="Email ID" value="" name="email" class="form-control ng-pristine ng-valid ng-touched" id="email">`

selenium-java code:
JavascriptExecutor executor = (JavascriptExecutor) driver;
WebElement emailElement = driver.findElement(By.id("email"));
executor.executeScript("arguments[0].value='tester'", emailElement);

A: your code works for me but you Try this alternative way
JavascriptExecutor myExecutor = ((JavascriptExecutor) driver);
myExecutor.executeScript("document.getElementsByName('email"')[0].value='Tester'");


text:
Q: Erro ao selecionar banco "Erro no database selected" Eu estava fazendo um sistema de comentários, mas está dando erro:

Erro no database selected

Código:
<?php
$link=mysqli_connect("127.0.0.1","root","");
$banco=mysqli_select_db($link,"bdcomentario");
?>
<form name='form' method="post" action="#">
Nome:
<input type='text' name='nome'>

 E-mail:
<input type='email' name='email'>

Comentario:
<textarea name='coment'></textarea>

<input type='submit' value='Enviar'>
<input type="reset" value='Limpar'>
</form>
<?php
$nome=$_POST['nome'];
$email=$_POST['email'];
$data= date("d/m/Y");
$comentario=$_POST['coment'];
$st="INSERT INTO tbcomentarios(nome,email,data,coment)
values('$nome','$email','$data','$comentario')";
if(strlen($_POST['nome'])){
$insert= mysqli_query($link,$vrau);
}
$sql="SELECT * FROM tbcomentarios ORDER BY id desc";
$executar=mysqli_query($link, $sql)
or die("Error: ".mysqli_error($link));
while( $exibir=mysqli_fetch_assoc($executar)){
echo $exibir['data'];
echo '
';
echo $exibir['nome'];
echo '
';
echo $exibir['email'];
echo '
';
echo $exibir['coment'];
echo '
';
mysqli_free_result($executar);
}
mysqli_close($link);
?>

A: Tente isto:
$link = mysqli_connect("127.0.0.1", "root", "", "bdcomentario");

E use isto somente se precisar alternar entre os bancos:
mysqli_select_db($link, "OUTRO BANCO");

Um exemplo:
<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "test");

/* verifica conexão */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* retorna o nome do banco atual */
if ($result = mysqli_query($link, "SELECT DATABASE()")) {
    $row = mysqli_fetch_row($result);
    printf("Default database is %s.\n", $row[0]);
    mysqli_free_result($result);
}

/* Troca de banco */
mysqli_select_db($link, "world");

if ($result = mysqli_query($link, "SELECT DATABASE()")) {
    $row = mysqli_fetch_row($result);
    printf("Default database is %s.\n", $row[0]);
    mysqli_free_result($result);
}

mysqli_close($link);

Você pode passar o nome do banco junto ao SELECT (o unico problema disto é que vai ter que escrever um pouco mais):
$link = mysqli_connect("127.0.0.1", "root", "", "bdcomentario");

mysqli_query($link, "SELECT * FROM bdcomentario.tabela WHERE ...");

Documentação:

*

*http://php.net/manual/en/function.mysqli-connect.php

*http://php.net/manual/en/mysqli.select-db.php


text:
Q: Как получить соседние элементы list'a и изменить их? Как получить, соседние элементы списка, чтобы их потом заменить.
Например вот список:
[-1, 0, -1, 0, 1, -1]

Нужно получить
[-1, 1, -1, 0, 2, -1]

Т.е. относительно всех элементов -1 слева от них, добавить всем элементам 1

A: Если сделать как в комментарии, вы обработаете только последнее вхождение -1 в исходный лист и замените предыдущий элемент на 1
Чтобы обработать каждый элемент == -1 нужно перебрать список циклом и не присваивать, а добавлять единицу к предыдущему элементу:
//формируем массив
Integer[] arr = {-1, 0, -1, 0, 1, -1};
ArrayList<Integer> list =  new ArrayList<>();
list.addAll(Arrays.asList(arr));

//проходимся циклом с проверкой
for (int i = 1; i < list.size(); i++)
    if (list.get(i) == -1) {
        list.set(i - 1, list.get(i - 1) + 1);
    }

//смотрим результат
System.out.println(list);

Проверять список нужно начиная со второго элемента, т.к. попытка добавить единичку к элементу левее первого вызовет исключение.


text:
Q: How to effectively call properties in another class - Objective-C I am a beginner with Objective-C and iOS development, and I can't figure out how to send data from one class to another without it returning null or in this case "0.0000"
I'll give the code I have-
In ClassA.h I have two properties
@interface ClassA : UIView

// This is public property!
@property (nonatomic, assign) CGFloat touchPointX;
@property (nonatomic, assign) CGFloat touchPointY;

// My test getters
- (CGFloat) touchLocationX;
- (CGFloat) touchLocationY;

@end;

Then in ClassA.m I implement these.
@implementation ClassA

- (void)baseInit {
}

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:self.frame];
    if (self) {
        [self baseInit];
    }
    return self;
}

- (id)initWithCoder:(NSCoder *)aDecoder {
    if ((self = [super initWithCoder:aDecoder])) {
        [self baseInit];
    }
    return self;
}

- (void) touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event
{
    for (UITouch *touch in touches) {

        CGPoint touchLocation = [touch locationInView:self];

        // Save the touch locations in our local variables.
        self.touchPointX = touchLocation.x;
        self.touchPointY = touchLocation.y;
        [self setNeedsDisplay];
    }
}

- (CGFloat) touchLocationX {
    return self.touchPointX;
}

- (CGFloat) touchLocationY {
    return self.touchPointY;
}

@end

Then I try to log the values in AppDelegate using some code I found on here
AppDelegate.h
@interface AppDelegate : UIResponder <UIApplicationDelegate>

@property (nonatomic, copy) ClassA *touchLocationX;
@property (nonatomic, copy) ClassA *touchLocationY;

@end

AppDelegate.m
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,
                                             (unsigned long)NULL), ^(void) {
        NSLog(@"(%@, %@)", _touchLocationX, _touchLocationY");

    });

    return YES;
}

I haven't been able to figure out how to do something like:
ClassA * myView = [[ClassA alloc] init];
myView = [myViewController theUIViewForClassA];

In the long run all I want is the properties to return the correct values

A: There are several ways in which data can be shared across an application.
In your example, you want to "send" touchpoints from ClassA to some other class, in this case the AppDelegate, which is fine as it demonstrates how this can work with other classes.
To accomplish this, several design patterns come to mind: Delegate Protocol, Notifications or Singleton.
I'll use the example of a singelton for convenience, because it allows us to use your AppDelegate, which is already a singleton, so this example can closely resemble your existing code.
Note that a singleton design pattern is one in which a singleton class is instantiated only once, whose methods and properties can be accessed by other classes throughout the application.
Example:
AppDelegate.h
Add a method for receiving touch events
@interface AppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;
- (void) notifyTouchEvents:(CGFloat)touchX :(CGFloat)touchY;
@end

AppDelegate.m
Implement the method
@implementation AppDelegate

// Method for receiving touch event data from another class
- (void) notifyTouchEvents:(CGFloat)touchX :(CGFloat)touchY
{
    NSLog(@"touchX: %f, touchY: %f", touchX, touchY);
}

ClassA.h
Import the App Delegate
Note: This example doesn't require touchPointX and touchPointY properties.
#import <UIKit/UIKit.h>
#import "AppDelegate.h"

@interface ViewController : UIViewController
@property (nonatomic, assign) CGFloat touchPointX;
@property (nonatomic, assign) CGFloat touchPointY;
@end

ClassA.m
Access the AppDelegate touch notification method during touch events
#import "ViewController.h"

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

- (void) touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event
{
    for (UITouch *touch in touches) {

        CGPoint touchLocation = [touch locationInView:self.view];

        // Access the AppDelegate singleton and notification method
        AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
        [appDelegate notifyTouchEvents:touchLocation.x :touchLocation.y];
    }
}

@end

In practice, you may find that a combination of using NSNotificationCenter and a Singleton can works best. Search around for more information on using delegates and singletons with Objective C.


text:
Q: Drag a sprite attached to a body I have a CCSprite that is attached to body in a b2world .
When someone is touch it, i want to move it with the touch location.
With a regular sprite that works fine , but with a sprite that has a body- it does not .
it gets the touch but not move the sprite (the body follow the sprite or the opposite?)
How should i do that ? apply a force relative to the touch is a problem..
- (void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{

    UITouch *touch = [touches anyObject];
    CGPoint currentPosition = [touch locationInView: [touch view]];

    //detect a touch ont the button
    for (b2Body* b = world->GetBodyList(); b; b = b->GetNext())
    {

        CGPoint location=[[CCDirector sharedDirector] convertToGL: currentPosition];

        CCSprite *tempSprite = (CCSprite *) b->GetUserData();
        if( tempSprite.tag==2  )
        {

            if(CGRectContainsPoint([tempSprite boundingBox], location))
            {
                tempSprite.position=location;
                NSLog(@"touched");
             }
        }

    }

}

A: Try changing the position of the body using SetTransform function. I think it's looking something like:
- (void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
CGPoint currentPosition = [touch locationInView: [touch view]];

//detect a touch ont the button
for (b2Body* b = world->GetBodyList(); b; b = b->GetNext())
{

    CGPoint location=[[CCDirector sharedDirector] convertToGL: currentPosition];

    CCSprite *tempSprite = (CCSprite *) b->GetUserData();
    if( tempSprite.tag==2  )
    {

        if(CGRectContainsPoint([tempSprite boundingBox], location))
        {
            b->SetTransform( b2Vec2( location.x/PTM_RATIO, location.y/PTM_RATIO ), 0 ); //change position of the body
            NSLog(@"touched");
         }
    }

}

}
Don't forget, if you want to change body position apply force or set linear velocity you must use kinematic or dynamic body type.


text:
Q: Is there a way to print a barcode using Web-Bluetooth? I've recently gotten a Zebra ZQ210 printer and I've been using Web-Bluetooth to print text on it, but I cannot seem to find how to print a barcode on it. Here's my algorithm for printing text:
 writeMessage(message) {
    return this.device.gatt.getPrimaryService("38eb4a80-c570-11e3-9507-0002a5d5c51b")

        .then(service => service.getCharacteristic("38eb4a82-c570-11e3-9507-0002a5d5c51b"))
        .then(characteristic => {
          var maxChunk = 500;
          var j = 0;

          if ( message.length > maxChunk ) {
            for ( var i = 0; i < message.length; i += maxChunk ) {
              var subStr;
              if ( i + maxChunk <= message.length ) {
                subStr = message.substring(i, i + maxChunk);

              } else {
                subStr = message.substring(i, message.length);
              }

              setTimeout(writeStrToCharacteristic, 4900 * j, subStr);
              j++;
            }
          } else {
            writeStrToCharacteristic(message);
          }

          function writeStrToCharacteristic (str) {
            let buffer = new ArrayBuffer(str.length);
            let dataView = new DataView(buffer);
            for (var i = 0; i <str.length; i++) {
              dataView.setUint8( i, str.charAt(i).charCodeAt() );
            }
            return characteristic.writeValue(buffer);
          }
        }).catch(error => { console.error(
          error.message
        ); });
  }

If there's a way to print barcodes on it using Web-Bluetooth I would love to know how. Thank you in advance!
EDIT: I have tried sending zpl codes as text to the printer, and it hasn't worked. I've also tried to send ESC/POS codes but it also didn't do anything, so far I'm lost.


text:
Q: Application closes automatically This code doesn't show the Window, it just closes automatically. Why is this happening?
class Program
{
    [STAThread]
    static void Main(string[] args)
    {
        var window = new MainWindow();
        window.ShowDialog();
    }
}

I know that you can fix it adding a new Application.Run(window) but I would like to know why it has this behavior and why you have to invoke the Run method over the window instance.
EDIT:
Extending the previous question, I've noticed that this code will work:

*

*Create a new WPF Application.

*Go to App.xaml and delete the StartupUri

*Modify the App.xaml.cs overriding the method OnStartup
public partial class App : Application
{
    protected override void OnStartup(StartupEventArgs e)
    {
        base.OnStartup(e);

        var window = new MainWindow();
        window.Show();
    }
}

With this, the window remains open. What's going on under the hood?

A: Microsoft Windows programs are event-based. They act upon messages that the operating system posts to the main thread of the application. These messages are received from the message queue by the application by repeatedly calling the GetMessage (or PeekMessage) function in a section of code called the "event loop."
When Run is called, Application attaches a new Dispatcher instance to the UI thread. Next, the Dispatcher object's Run method is called, which starts a message loop to process windows messages. Finally, the Dispatcher object calls the Application object's OnStartup method to raise the Startup event.
Without a message loop, the application is unable to support the UI.


text:
Q: Do R modeling packages treat character variables the same as unordered factors? I have categorical variables that are character columns. For example, a character column whose values are all either "yes" or "no". Will R modeling packages correctly handle them as nominal categorical variables even if I leave them as character columns, or do these packages require them to be unordered factors?

A: Each function is free to do what it wants but if the function uses model.matrix then it will treat character strings as factors.
2 levels
x2 <- c("yes", "no", "yes")
model.matrix(~ x2)

giving:
  (Intercept) xyes
1           1    1
2           1    0
3           1    1
attr(,"assign")
[1] 0 1
attr(,"contrasts")
attr(,"contrasts")$x
[1] "contr.treatment"

3 levels
x3 <- letters[1:3]
model.matrix(~ x3)

giving:
  (Intercept) xxb xxc
1           1   0   0
2           1   1   0
3           1   0   1
attr(,"assign")
[1] 0 1 1
attr(,"contrasts")
attr(,"contrasts")$xx
[1] "contr.treatment"

A: To follow up on @GaborGrothendieck's answer: the answer is "usually yes", because most statistical modeling packages make use of model.matrix() to handle various types of predictors, interactions, etc..
That said, it's probably best practice to convert to factors explicitly so that you have control/know what's going on. What's the downside? Converting to factors explicitly also allows to you to control order of levels, contrasts, etc..