text:
Q: XSL 1.0 Multilevel grouping with empty tags This is my first time posting here, so I apologize in advance for the length and for any format issue or lack of information. I've been working on this problem for a few days and I've researched my problem extensively but haven't found a solution yet, so I am hoping someone here can help me. It's an xslt related issue and I only started coding in xslt a couple of months ago so I'm not so experienced.
Basically, I have an input XML which may contain duplicate records as well as empty tags and I need to reorganize them into a javascript associative array to be able to manipulate and display the values efficiently on the client side.
My question is: Is there a way to do a multilevel grouping even if the used field tag is empty. If not, is there a way I can edit the xml in xsl by replacing the empty tag with a keyword and then applying the rest of my templates?
To understand my problem here are the details.
This is my input XML
<cds>
    <sections>

            <detail name="">
                <record>
                    <field name="AGERANGEID">30-39</field>
                    <field name="NUMOFCOUNTAGE">1</field>
                    <field name="ORGUNITID">00001001</field>
                    <field name="PARENTORGUNITID">00000100</field>
                    <field name="ORGUNITNAME">Human Resources</field>
                </record>
                <record>
                    <field name="AGERANGEID">>=70</field>
                    <field name="NUMOFCOUNTAGE">5</field>
                    <field name="ORGUNITID">00001001</field>
                    <field name="PARENTORGUNITID">00000100</field>
                    <field name="ORGUNITNAME">Human Resources</field>
                </record>
            </detail>

            <detail name="">
                <record>
                    <field name="PARENTORGUNITID">00000100</field>
                    <field name="ORGUNITID">00001001</field>
                    <field name="ORGUNITNAME">Human Resources</field>
                    <field name="NUMOFGENDERCOUNT">5</field>
                    <field name="GENDER">2</field>
                </record>
                <record>
                    <field name="PARENTORGUNITID">00000100</field>
                    <field name="ORGUNITID">00001001</field>
                    <field name="ORGUNITNAME">Human Resources</field>
                    <field name="NUMOFGENDERCOUNT">7</field>
                    <field name="GENDER">1</field>
                </record>
            </detail>

            <detail name="">
                <record>
                    <field name="ORGUNITNAME">Human Resources</field>
                    <field name="PARENTORGUNITID">00000100</field>
                    <field name="ORGUNITID">00001001</field>
                    <field name="NUMOFRACE">10.0</field>
                    <field name="RACENAME" />
                </record>
                <record>
                    <field name="ORGUNITNAME">Human Resources</field>
                    <field name="PARENTORGUNITID">00000100</field>
                    <field name="ORGUNITID">00001001</field>
                    <field name="NUMOFRACE">1</field>
                    <field name="RACENAME">Asian</field>
                </record>
                <record>
                    <field name="ORGUNITNAME">Human Resources</field>
                    <field name="PARENTORGUNITID">00000100</field>
                    <field name="ORGUNITID">00001001</field>
                    <field name="NUMOFRACE">1</field>
                    <field name="RACENAME">American Indian</field>
                </record>
            </detail>

            <detail name="">
                <record>
                    <field name="AGERANGEID">40-49</field>
                    <field name="NUMOFCOUNTAGE">1</field>
                    <field name="ORGUNITID">50000013</field>
                    <field name="PARENTORGUNITID">00001001</field>
                    <field name="ORGUNITNAME">IT computer center (D)</field>
                </record>
                <record>
                    <field name="AGERANGEID">50-59</field>
                    <field name="NUMOFCOUNTAGE">2</field>
                    <field name="ORGUNITID">50000013</field>
                    <field name="PARENTORGUNITID">00001001</field>
                    <field name="ORGUNITNAME">IT computer center (D)</field>
                </record>
                <record>
                    <field name="AGERANGEID">>=70</field>
                    <field name="NUMOFCOUNTAGE">5</field>
                    <field name="ORGUNITID">50000013</field>
                    <field name="PARENTORGUNITID">00001001</field>
                    <field name="ORGUNITNAME">IT computer center (D)</field>
                </record>
            </detail>

            <detail name="">
                <record>
                    <field name="PARENTORGUNITID">00001001</field>
                    <field name="ORGUNITID">50000013</field>
                    <field name="ORGUNITNAME">IT computer center (D)</field>
                    <field name="NUMOFGENDERCOUNT">4</field>
                    <field name="GENDER">2</field>
                </record>
                <record>
                    <field name="PARENTORGUNITID">00001001</field>
                    <field name="ORGUNITID">50000147</field>
                    <field name="ORGUNITNAME">Personnel Administration (D)</field>
                    <field name="NUMOFGENDERCOUNT">3</field>
                    <field name="GENDER">1</field>
                </record>
                <record>
                    <field name="PARENTORGUNITID">00001001</field>
                    <field name="ORGUNITID">50000013</field>
                    <field name="ORGUNITNAME">IT computer center (D)</field>
                    <field name="NUMOFGENDERCOUNT">4</field>
                    <field name="GENDER">1</field>
                </record>
            </detail>

            <detail name="">
                <record>
                    <field name="PARENTORGUNITID">00001001</field>
                    <field name="ORGUNITID">50000013</field>
                    <field name="ORGUNITNAME">IT computer center (D)</field>
                    <field name="NUMOFGENDERCOUNT">4</field>
                    <field name="GENDER">2</field>
                </record>
                <record>
                    <field name="PARENTORGUNITID">00001001</field>
                    <field name="ORGUNITID">50000147</field>
                    <field name="ORGUNITNAME">Personnel Administration (D)</field>
                    <field name="NUMOFGENDERCOUNT">3</field>
                    <field name="GENDER">1</field>
                </record>
                <record>
                    <field name="PARENTORGUNITID">00001001</field>
                    <field name="ORGUNITID">50000013</field>
                    <field name="ORGUNITNAME">IT computer center (D)</field>
                    <field name="NUMOFGENDERCOUNT">4</field>
                    <field name="GENDER">1</field>
                </record>
            </detail>

            <detail name="">
                <record>
                    <field name="PARENTORGUNITID">00001001</field>
                    <field name="ORGUNITID">50000013</field>
                    <field name="ORGUNITNAME">IT computer center (D)</field>
                    <field name="NUMOFGENDERCOUNT">4</field>
                    <field name="GENDER">2</field>
                </record>
                <record>
                    <field name="PARENTORGUNITID">00001001</field>
                    <field name="ORGUNITID">50000147</field>
                    <field name="ORGUNITNAME">Personnel Administration (D)</field>
                    <field name="NUMOFGENDERCOUNT">3</field>
                    <field name="GENDER">1</field>
                </record>
            </detail>

    </sections>
</cds>

I looked online and found that the best way to deal with multilevel grouping is to use xsl:key and generate-id(). That worked great and the data came out exactly as I wanted to, so the flow of my xsl is correct. But unfortunately if the field used in the xsl:key is an empty tag, when I go into the multilevel grouping using concat(), it fails.

<xsl:variable name="ageFieldName" select="'AGERANGEID'" />
<xsl:variable name="genderFieldName" select="'GENDER'" />
<xsl:variable name="raceFieldName" select="'RACENAME'" />
<xsl:variable name="ouIdFieldName" select="'ORGUNITID'" />
<xsl:variable name="ouNameFieldName" select="'ORGUNITNAME'" />

<xsl:key use="field[@name='AGERANGEID']" name="AGERANGEID" match="detail/record" />
<xsl:key use="concat(field[@name='AGERANGEID'],'|', field[@name='ORGUNITID'])" name="AGERANGEID_merge" match="detail/record" />
<xsl:key use="field[@name='GENDER']" name="GENDER" match="detail/record" />
<xsl:key use="concat(field[@name='GENDER'],'|', field[@name='ORGUNITID'])" name="GENDER_merge" match="detail/record" />
<xsl:key use="field[@name='RACENAME']" name="RACENAME" match="detail/record" />
<xsl:key use="concat(field[@name='RACENAME'],'|', field[@name='ORGUNITID'])" name="RACENAME_merge" match="detail/record" />

<xsl:key use="field[@name='ORGUNITID']" name="ORGUNITID" match="detail/record" />

<xsl:template match="/">
    var analyticsMap = {<xsl:call-template name="buildAnalyticsTable" />};
</xsl:template>

<xsl:template name="buildAnalyticsTable">

    "<xsl:value-of select="$ageFieldName"/>" : {
    <xsl:apply-templates mode="buildAnalyticsTableRangeLevel" select="//detail/record[generate-id()=generate-id(key($ageFieldName, field[@name=$ageFieldName]))]">
        <xsl:with-param name="keyName" select="$ageFieldName"/>
        <xsl:with-param name="countField" select="'NUMOFCOUNTAGE'"/>
        <xsl:with-param name="label" select="'Age Range'" />
        <xsl:with-param name="isGender" select="'false'" />
    </xsl:apply-templates>
    },

    "<xsl:value-of select="$genderFieldName"/>" : {
    <xsl:apply-templates mode="buildAnalyticsTableRangeLevel" select="//detail/record[generate-id()=generate-id(key($genderFieldName, field[@name=$genderFieldName]))]">
        <xsl:with-param name="keyName" select="$genderFieldName"/>
        <xsl:with-param name="countField" select="'NUMOFGENDERCOUNT'"/>
        <xsl:with-param name="label" select="'Gender'" />
        <xsl:with-param name="isGender" select="'true'" />
    </xsl:apply-templates>
    },

    "<xsl:value-of select="$raceFieldName"/>" : {
    <xsl:apply-templates mode="buildAnalyticsTableRangeLevel" select="//detail/record[generate-id()=generate-id(key($raceFieldName, field[@name=$raceFieldName]))]">
        <xsl:with-param name="keyName" select="$raceFieldName"/>
        <xsl:with-param name="countField" select="'NUMOFRACE'"/>
        <xsl:with-param name="label" select="'Race'" />
        <xsl:with-param name="isGender" select="'true'" />
    </xsl:apply-templates>
    }

</xsl:template>

<xsl:template match="detail/record" mode="buildAnalyticsTableRangeLevel">
    <xsl:param name="keyName" />
    <xsl:param name="countField" />
    <xsl:param name="label" />
    <xsl:param name="isGender" />
    <xsl:variable name="value" >
        <xsl:call-template name="testForUnknown">
            <xsl:with-param name="name" select="field[@name=$keyName]"/>
        </xsl:call-template>
    </xsl:variable>
    <xsl:variable name="name">
        <xsl:call-template name="testForGender">
            <xsl:with-param name="isGender" select="$isGender"/>
            <xsl:with-param name="name" select="$value"/>
        </xsl:call-template>
    </xsl:variable>

    "<xsl:value-of select="$value"/>" : {
    "analyticsLabel" : "<xsl:value-of select="$label"/>",
    "analyticsName" : "<xsl:value-of select="$name"/>",
    <xsl:apply-templates mode="buildAnalyticsTableCountLevel" select="key($keyName, field[@name=$keyName])[generate-id()=generate-id(key(concat($keyName, '_merge'), concat(field[@name=$keyName],'|', field[@name=$ouIdFieldName])))]">
        <xsl:with-param name="countField" select="$countField"/>
    </xsl:apply-templates>
    },
</xsl:template>

<xsl:template match="detail/record" mode="buildAnalyticsTableCountLevel">
    <xsl:param name="countField" />
    "<xsl:value-of select="field[@name=$ouIdFieldName]"/>" : {
    "analyticsOUname" : "<xsl:value-of select="field[@name=$ouNameFieldName]"/>",
    "analyticsValue" : "<xsl:value-of select="field[@name=$countField]"/>"
    },
</xsl:template>

<xsl:template name="testForUnknown">
    <xsl:param name="name" />
    <xsl:choose>
        <xsl:when test="string-length($name) = 0">
            <xsl:value-of select="'Unknown'"/>
        </xsl:when>
        <xsl:otherwise>
            <xsl:value-of select="$name" />
        </xsl:otherwise>
    </xsl:choose>
</xsl:template>

<xsl:template name="testForGender">
    <xsl:param name="isGender" />
    <xsl:param name="name" />
    <xsl:choose>
        <xsl:when test="$isGender = 'true' and $name = 1">
            <xsl:value-of select="'male'" />
        </xsl:when>
        <xsl:when test="$isGender = 'true' and $name = 2">
            <xsl:value-of select="'female'" />
        </xsl:when>
        <xsl:otherwise>
            <xsl:value-of select="$name" />
        </xsl:otherwise>
    </xsl:choose>
</xsl:template>

Here is the output of my transformation
    var analyticsMap = {

    "AGERANGEID" : {

    "30-39" : {
    "analyticsLabel" : "Age Range",
    "analyticsName" : "30-39",

    "00001001" : {
    "analyticsOUname" : "Human Resources",
    "analyticsValue" : "1"
    },

    },

    ">=70" : {
    "analyticsLabel" : "Age Range",
    "analyticsName" : ">=70",

    "00001001" : {
    "analyticsOUname" : "Human Resources",
    "analyticsValue" : "5"
    },

    "50000013" : {
    "analyticsOUname" : "IT computer center (D)",
    "analyticsValue" : "5"
    },

    },

    "40-49" : {
    "analyticsLabel" : "Age Range",
    "analyticsName" : "40-49",

    "50000013" : {
    "analyticsOUname" : "IT computer center (D)",
    "analyticsValue" : "1"
    },

    },

    "50-59" : {
    "analyticsLabel" : "Age Range",
    "analyticsName" : "50-59",

    "50000013" : {
    "analyticsOUname" : "IT computer center (D)",
    "analyticsValue" : "2"
    },

    },

    },

    "GENDER" : {

    "2" : {
    "analyticsLabel" : "Gender",
    "analyticsName" : "female",

    "00001001" : {
    "analyticsOUname" : "Human Resources",
    "analyticsValue" : "5"
    },

    "50000013" : {
    "analyticsOUname" : "IT computer center (D)",
    "analyticsValue" : "4"
    },

    },

    "1" : {
    "analyticsLabel" : "Gender",
    "analyticsName" : "male",

    "00001001" : {
    "analyticsOUname" : "Human Resources",
    "analyticsValue" : "7"
    },

    "50000147" : {
    "analyticsOUname" : "Personnel Administration (D)",
    "analyticsValue" : "3"
    },

    "50000013" : {
    "analyticsOUname" : "IT computer center (D)",
    "analyticsValue" : "4"
    },

    },

    },

    "RACENAME" : {

    "Unknown" : {
    "analyticsLabel" : "Race",
    "analyticsName" : "Unknown",

    },

    "Asian" : {
    "analyticsLabel" : "Race",
    "analyticsName" : "Asian",

    "00001001" : {
    "analyticsOUname" : "Human Resources",
    "analyticsValue" : "1"
    },

    },

    "American Indian" : {
    "analyticsLabel" : "Race",
    "analyticsName" : "American Indian",

    "00001001" : {
    "analyticsOUname" : "Human Resources",
    "analyticsValue" : "1"
    },

    },

    }

};

As you can see, in the Race->Unknown section, it doesn't complete it by applying the template mode "buildAnalyticsTableCountLevel" so I never get the ORGUNITID information which is very important in what I am doing.
I unfortunately cannot edit the xml coming in as this is a part of a much bigger framework used in various projects and I cannot change it. So I have to work with what I get.
I tried using the string() method in xsl:key but that makes everything worse. Any tips or help is appreciated. Thanks in advance!

A: Change the start of the stylesheet like this:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
 xmlns:my="my:my">
 <xsl:output method="text"/>

 <my:unknown>Unknown</my:unknown>

and change one of the key definitions to:
 <xsl:key name="RACENAME_merge" match="detail/record"
  use="concat((field[@name='RACENAME']
              |document('')/*/my:unknown[not(field[@name='RACENAME'])]),
              '|', field[@name='ORGUNITID'])"  />

Finally, change one of the xsl:apply-templaes to this:
<xsl:apply-templates mode="buildAnalyticsTableCountLevel"
select="key($keyName, field[@name=$keyName])
          [generate-id()=generate-id(key(concat($keyName, '_merge'),
          concat((field[@name=$keyName]
                 |document('')/*/my:unknown[not(current()/field[@name='RACENAME'])]),
                 '|', field[@name=$ouIdFieldName])))]">
    <xsl:with-param name="countField" select="$countField"/>
</xsl:apply-templates>

The complete code after these changes becomes:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
 xmlns:my="my:my">
 <xsl:output method="text"/>

 <my:unknown>Unknown</my:unknown>

 <xsl:variable name="ageFieldName" select="'AGERANGEID'" />
 <xsl:variable name="genderFieldName" select="'GENDER'" />
 <xsl:variable name="raceFieldName" select="'RACENAME'" />
 <xsl:variable name="ouIdFieldName" select="'ORGUNITID'" />
 <xsl:variable name="ouNameFieldName" select="'ORGUNITNAME'" />

 <xsl:key use="field[@name='AGERANGEID']" name="AGERANGEID" match="detail/record" />
 <xsl:key use="concat(field[@name='AGERANGEID'],'|', field[@name='ORGUNITID'])" name="AGERANGEID_merge" match="detail/record" />
 <xsl:key use="field[@name='GENDER']" name="GENDER" match="detail/record" />
 <xsl:key use="concat(field[@name='GENDER'],'|', field[@name='ORGUNITID'])" name="GENDER_merge" match="detail/record" />
 <xsl:key use="field[@name='RACENAME']" name="RACENAME" match="detail/record" />
 <xsl:key use="concat((field[@name='RACENAME']
                     |document('')/*/my:unknown[not(current()/field[@name='RACENAME'])]),
                     '|', field[@name='ORGUNITID'])"
  name="RACENAME_merge" match="detail/record" />

 <xsl:key use="field[@name='ORGUNITID']" name="ORGUNITID" match="detail/record" />

 <xsl:template match="/">
    var analyticsMap = {<xsl:call-template name="buildAnalyticsTable" />};
 </xsl:template>

 <xsl:template name="buildAnalyticsTable">

    "<xsl:value-of select="$ageFieldName"/>" : {
    <xsl:apply-templates mode="buildAnalyticsTableRangeLevel" select="//detail/record[generate-id()=generate-id(key($ageFieldName, field[@name=$ageFieldName]))]">
        <xsl:with-param name="keyName" select="$ageFieldName"/>
        <xsl:with-param name="countField" select="'NUMOFCOUNTAGE'"/>
        <xsl:with-param name="label" select="'Age Range'" />
        <xsl:with-param name="isGender" select="'false'" />
    </xsl:apply-templates>
    },

    "<xsl:value-of select="$genderFieldName"/>" : {
    <xsl:apply-templates mode="buildAnalyticsTableRangeLevel" select="//detail/record[generate-id()=generate-id(key($genderFieldName, field[@name=$genderFieldName]))]">
        <xsl:with-param name="keyName" select="$genderFieldName"/>
        <xsl:with-param name="countField" select="'NUMOFGENDERCOUNT'"/>
        <xsl:with-param name="label" select="'Gender'" />
        <xsl:with-param name="isGender" select="'true'" />
    </xsl:apply-templates>
    },

    "<xsl:value-of select="$raceFieldName"/>" : {
    <xsl:apply-templates mode="buildAnalyticsTableRangeLevel" select="//detail/record[generate-id()=generate-id(key($raceFieldName, field[@name=$raceFieldName]))]">
        <xsl:with-param name="keyName" select="$raceFieldName"/>
        <xsl:with-param name="countField" select="'NUMOFRACE'"/>
        <xsl:with-param name="label" select="'Race'" />
        <xsl:with-param name="isGender" select="'true'" />
    </xsl:apply-templates>
    }

 </xsl:template>

 <xsl:template match="detail/record" mode="buildAnalyticsTableRangeLevel">
    <xsl:param name="keyName" />
    <xsl:param name="countField" />
    <xsl:param name="label" />
    <xsl:param name="isGender" />
    <xsl:variable name="value" >
        <xsl:call-template name="testForUnknown">
            <xsl:with-param name="name" select="field[@name=$keyName]"/>
        </xsl:call-template>
    </xsl:variable>
    <xsl:variable name="name">
        <xsl:call-template name="testForGender">
            <xsl:with-param name="isGender" select="$isGender"/>
            <xsl:with-param name="name" select="$value"/>
        </xsl:call-template>
    </xsl:variable>

    "<xsl:value-of select="$value"/>" : {
    "analyticsLabel" : "<xsl:value-of select="$label"/>",
    "analyticsName" : "<xsl:value-of select="$name"/>",
    <xsl:apply-templates mode="buildAnalyticsTableCountLevel"
    select="key($keyName, field[@name=$keyName])
              [generate-id()=generate-id(key(concat($keyName, '_merge'),
              concat((field[@name=$keyName]
                     |document('')/*/my:unknown[not(current()/field[@name='RACENAME'])]),
                     '|', field[@name=$ouIdFieldName])))]">
        <xsl:with-param name="countField" select="$countField"/>
    </xsl:apply-templates>
    },
 </xsl:template>

 <xsl:template match="detail/record" mode="buildAnalyticsTableCountLevel">
    <xsl:param name="countField" />
    "<xsl:value-of select="field[@name=$ouIdFieldName]"/>" : {
    "analyticsOUname" : "<xsl:value-of select="field[@name=$ouNameFieldName]"/>",
    "analyticsValue" : "<xsl:value-of select="field[@name=$countField]"/>"
    },
 </xsl:template>

 <xsl:template name="testForUnknown">
    <xsl:param name="name" />
    <xsl:choose>
        <xsl:when test="string-length($name) = 0">
            <xsl:value-of select="'Unknown'"/>
        </xsl:when>
        <xsl:otherwise>
            <xsl:value-of select="$name" />
        </xsl:otherwise>
    </xsl:choose>
 </xsl:template>

 <xsl:template name="testForGender">
    <xsl:param name="isGender" />
    <xsl:param name="name" />
    <xsl:choose>
        <xsl:when test="$isGender = 'true' and $name = 1">
            <xsl:value-of select="'male'" />
        </xsl:when>
        <xsl:when test="$isGender = 'true' and $name = 2">
            <xsl:value-of select="'female'" />
        </xsl:when>
        <xsl:otherwise>
            <xsl:value-of select="$name" />
        </xsl:otherwise>
    </xsl:choose>
 </xsl:template>
</xsl:stylesheet>

and when this transformation is applied on the provided XML document:
<cds>
    <sections>

            <detail name="">
                <record>
                    <field name="AGERANGEID">30-39</field>
                    <field name="NUMOFCOUNTAGE">1</field>
                    <field name="ORGUNITID">00001001</field>
                    <field name="PARENTORGUNITID">00000100</field>
                    <field name="ORGUNITNAME">Human Resources</field>
                </record>
                <record>
                    <field name="AGERANGEID">>=70</field>
                    <field name="NUMOFCOUNTAGE">5</field>
                    <field name="ORGUNITID">00001001</field>
                    <field name="PARENTORGUNITID">00000100</field>
                    <field name="ORGUNITNAME">Human Resources</field>
                </record>
            </detail>

            <detail name="">
                <record>
                    <field name="PARENTORGUNITID">00000100</field>
                    <field name="ORGUNITID">00001001</field>
                    <field name="ORGUNITNAME">Human Resources</field>
                    <field name="NUMOFGENDERCOUNT">5</field>
                    <field name="GENDER">2</field>
                </record>
                <record>
                    <field name="PARENTORGUNITID">00000100</field>
                    <field name="ORGUNITID">00001001</field>
                    <field name="ORGUNITNAME">Human Resources</field>
                    <field name="NUMOFGENDERCOUNT">7</field>
                    <field name="GENDER">1</field>
                </record>
            </detail>

            <detail name="">
                <record>
                    <field name="ORGUNITNAME">Human Resources</field>
                    <field name="PARENTORGUNITID">00000100</field>
                    <field name="ORGUNITID">00001001</field>
                    <field name="NUMOFRACE">10.0</field>
                    <field name="RACENAME" />
                </record>
                <record>
                    <field name="ORGUNITNAME">Human Resources</field>
                    <field name="PARENTORGUNITID">00000100</field>
                    <field name="ORGUNITID">00001001</field>
                    <field name="NUMOFRACE">1</field>
                    <field name="RACENAME">Asian</field>
                </record>
                <record>
                    <field name="ORGUNITNAME">Human Resources</field>
                    <field name="PARENTORGUNITID">00000100</field>
                    <field name="ORGUNITID">00001001</field>
                    <field name="NUMOFRACE">1</field>
                    <field name="RACENAME">American Indian</field>
                </record>
            </detail>

            <detail name="">
                <record>
                    <field name="AGERANGEID">40-49</field>
                    <field name="NUMOFCOUNTAGE">1</field>
                    <field name="ORGUNITID">50000013</field>
                    <field name="PARENTORGUNITID">00001001</field>
                    <field name="ORGUNITNAME">IT computer center (D)</field>
                </record>
                <record>
                    <field name="AGERANGEID">50-59</field>
                    <field name="NUMOFCOUNTAGE">2</field>
                    <field name="ORGUNITID">50000013</field>
                    <field name="PARENTORGUNITID">00001001</field>
                    <field name="ORGUNITNAME">IT computer center (D)</field>
                </record>
                <record>
                    <field name="AGERANGEID">>=70</field>
                    <field name="NUMOFCOUNTAGE">5</field>
                    <field name="ORGUNITID">50000013</field>
                    <field name="PARENTORGUNITID">00001001</field>
                    <field name="ORGUNITNAME">IT computer center (D)</field>
                </record>
            </detail>

            <detail name="">
                <record>
                    <field name="PARENTORGUNITID">00001001</field>
                    <field name="ORGUNITID">50000013</field>
                    <field name="ORGUNITNAME">IT computer center (D)</field>
                    <field name="NUMOFGENDERCOUNT">4</field>
                    <field name="GENDER">2</field>
                </record>
                <record>
                    <field name="PARENTORGUNITID">00001001</field>
                    <field name="ORGUNITID">50000147</field>
                    <field name="ORGUNITNAME">Personnel Administration (D)</field>
                    <field name="NUMOFGENDERCOUNT">3</field>
                    <field name="GENDER">1</field>
                </record>
                <record>
                    <field name="PARENTORGUNITID">00001001</field>
                    <field name="ORGUNITID">50000013</field>
                    <field name="ORGUNITNAME">IT computer center (D)</field>
                    <field name="NUMOFGENDERCOUNT">4</field>
                    <field name="GENDER">1</field>
                </record>
            </detail>

            <detail name="">
                <record>
                    <field name="PARENTORGUNITID">00001001</field>
                    <field name="ORGUNITID">50000013</field>
                    <field name="ORGUNITNAME">IT computer center (D)</field>
                    <field name="NUMOFGENDERCOUNT">4</field>
                    <field name="GENDER">2</field>
                </record>
                <record>
                    <field name="PARENTORGUNITID">00001001</field>
                    <field name="ORGUNITID">50000147</field>
                    <field name="ORGUNITNAME">Personnel Administration (D)</field>
                    <field name="NUMOFGENDERCOUNT">3</field>
                    <field name="GENDER">1</field>
                </record>
                <record>
                    <field name="PARENTORGUNITID">00001001</field>
                    <field name="ORGUNITID">50000013</field>
                    <field name="ORGUNITNAME">IT computer center (D)</field>
                    <field name="NUMOFGENDERCOUNT">4</field>
                    <field name="GENDER">1</field>
                </record>
            </detail>

            <detail name="">
                <record>
                    <field name="PARENTORGUNITID">00001001</field>
                    <field name="ORGUNITID">50000013</field>
                    <field name="ORGUNITNAME">IT computer center (D)</field>
                    <field name="NUMOFGENDERCOUNT">4</field>
                    <field name="GENDER">2</field>
                </record>
                <record>
                    <field name="PARENTORGUNITID">00001001</field>
                    <field name="ORGUNITID">50000147</field>
                    <field name="ORGUNITNAME">Personnel Administration (D)</field>
                    <field name="NUMOFGENDERCOUNT">3</field>
                    <field name="GENDER">1</field>
                </record>
            </detail>

    </sections>
</cds>

the wanted, correct result is produced:
    var analyticsMap = {

    "AGERANGEID" : {

    "30-39" : {
    "analyticsLabel" : "Age Range",
    "analyticsName" : "30-39",

    "00001001" : {
    "analyticsOUname" : "Human Resources",
    "analyticsValue" : "1"
    },

    },

    ">=70" : {
    "analyticsLabel" : "Age Range",
    "analyticsName" : ">=70",

    "00001001" : {
    "analyticsOUname" : "Human Resources",
    "analyticsValue" : "5"
    },

    "50000013" : {
    "analyticsOUname" : "IT computer center (D)",
    "analyticsValue" : "5"
    },

    },

    "40-49" : {
    "analyticsLabel" : "Age Range",
    "analyticsName" : "40-49",

    "50000013" : {
    "analyticsOUname" : "IT computer center (D)",
    "analyticsValue" : "1"
    },

    },

    "50-59" : {
    "analyticsLabel" : "Age Range",
    "analyticsName" : "50-59",

    "50000013" : {
    "analyticsOUname" : "IT computer center (D)",
    "analyticsValue" : "2"
    },

    },

    },

    "GENDER" : {

    "2" : {
    "analyticsLabel" : "Gender",
    "analyticsName" : "female",

    "00001001" : {
    "analyticsOUname" : "Human Resources",
    "analyticsValue" : "5"
    },

    "50000013" : {
    "analyticsOUname" : "IT computer center (D)",
    "analyticsValue" : "4"
    },

    },

    "1" : {
    "analyticsLabel" : "Gender",
    "analyticsName" : "male",

    "00001001" : {
    "analyticsOUname" : "Human Resources",
    "analyticsValue" : "7"
    },

    "50000147" : {
    "analyticsOUname" : "Personnel Administration (D)",
    "analyticsValue" : "3"
    },

    "50000013" : {
    "analyticsOUname" : "IT computer center (D)",
    "analyticsValue" : "4"
    },

    },

    },

    "RACENAME" : {

    "Unknown" : {
    "analyticsLabel" : "Race",
    "analyticsName" : "Unknown",

    "00001001" : {
    "analyticsOUname" : "Human Resources",
    "analyticsValue" : "10.0"
    },

    },

    "Asian" : {
    "analyticsLabel" : "Race",
    "analyticsName" : "Asian",

    "00001001" : {
    "analyticsOUname" : "Human Resources",
    "analyticsValue" : "1"
    },

    },

    "American Indian" : {
    "analyticsLabel" : "Race",
    "analyticsName" : "American Indian",

    "00001001" : {
    "analyticsOUname" : "Human Resources",
    "analyticsValue" : "1"
    },

    },

    }

 };


text:
Q: Google maps - embed a map by city name Is there a way to embed a map by using only the city name like the code below ?
<iframe src="https://www.google.com/maps/embed?pb=Paris,France" width="600" height="250" frameborder="0" style="border:0" allowfullscreen></iframe>

A: Please refer to the documentation for the Embed API.

Place mode
Place mode displays a map pin at a particular place or address, such as a landmark, business, geographic feature, or town.
https://www.google.com/maps/embed/v1/place
    ?key=YOUR_API_KEY
    &q=Eiffel+Tower,Paris+France
The following URL parameter is required:

*

*q defines the place to highlight on the map. It accepts a location as either a place name, address, or place ID. The string should be URL-escaped, so an address such as "City Hall, New York, NY" should be converted to City+Hall,New+York,NY. (The Google Maps Embed API supports both + and %20 when escaping spaces.) Place IDs should be prefixed with place_id:.

Example with Paris, France:
<iframe width="100%" height="600" frameborder="0" style="border:0"
src="https://www.google.com/maps/embed/v1/place?q=Paris, France&key=YOUR_API_KEY">
</iframe>

working example

A: you can use javascript or jQuery for google map api with click events like so..
                     $('...ELEMENT, CLASS, BUTTON....').click(function(){
                        $.ajax({
                            type:"GET",
                            url:"https://maps.googleapis.com/maps/api/geocode/xml?address=...CITY NAME...&key=...YOUR KEY GOES ERE...",
                            dataType:'xml',
                            success: function(xml){

                                    }
                                });
                            }
                        });
                    });

YOU CAN USE JSON IF U PREFERE
or if u dont want the click and ajax function just copy n paste the url with ur key and city name
you can create a key from here:
    https://console.developers.google.com/flows/enableapi?apiid=maps_backend,geocoding_backend,directions_backend,distance_matrix_backend,elevation_backend,places_backend&keyType=CLIENT_SIDE&reusekey=true&pli=1
hope that will help.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Typescript React Intl Redux form type mismatch I want to connect my form to Intl but I am struggling to understand the typescript error. If I change injectIntl<any>, the error disappears. Possibly, I need to pass something there but I don't know what. Could you please take a look what I am doing wrong, perhaps help me understand the error.
Thank you
Code:
import { injectIntl, InjectedIntlProps } from 'react-intl';
import { reduxForm, Field, InjectedFormProps } from 'redux-form';

interface PageProps extends InjectedIntlProps, InjectedFormProps {}

const Page = (props: PageProps): JSX.Element => {
  const { intl: { formatMessage } } = props;
  return (
    <div>
        <form>
             <Field
                    name="date"
                    type="text"
                    component="input"
                    id="date"
                    {...{
                        label: formatMessage({
                            id: '...',
                        }),
                    }}
                />
        </form>
    </div>
  );
};

export default injectIntl(
  reduxForm({
    form: "FormName",
  })(Page),
);

Error:

message: 'Argument of type 'DecoratedComponentClass<{},
  Partial>>' is not assignable to parameter of type
  'ComponentConstructor> &
  InjectedIntlProps>'. Type 'DecoratedComponentClass<{},
  Partial>>' is not assignable to type
  'StatelessComponent> &
  InjectedIntlProps>'. Type 'DecoratedComponentClass<{},
  Partial>>' provides no match for the signature
  '(props: Partial> & InjectedIntlProps & {
  children?: ReactNode; }, context?: any): ReactElement | null'.'

A: Try injectIntl on the Page.
export default reduxForm({
    form: "FormName",
})(injectIntl(Page));


text:
Q: Understanding the each jquery function - Unexpected output I am trying to wrap my head around the each function. In this fiddle here
I would like to iterate through the selected elements of the list box one by one.
Essentially I was expecting an output like this
found itemA
found itemB

However I get an output like this
found itemA,itemB

I would like to know why that is happening and how I can fix it.
This is the code I am using
HTML
<select multiple="multiple" size="5" id="test">
    <option>itemA</option>
    <option>itemB</option>
</select>

<button type="button" id="bid">test</button>

JQuery
$( "#bid" ).click(function() {
   $("#test").each(function () {
       console.log("found " + $(this).val());
   });
});

A: You are iterating over the select and not the options. The function you passed to each is getting called just once. Change your selector to #test > option and, like the comments on the question, change val() to text().
$( "#bid" ).click(function() {
   $("#test > option").each(function () {
       console.log("found " + $(this).text());
   });
});

A: *

*You have to specify the elements selector. Using only #test won't iterate over options because you didn't actually refer to it.

$("#bid").click(function() {
  $("#test option").each(function() {
    console.log("found " + $(this).val());
  });
});

<select multiple="multiple" size="5" id="test">
  <option>itemA</option>
  <option>itemB</option>
</select>

<button type="button" id="bid">test</button>

A: You'll want to use
$.each($("#test").prop("options"), function () {
    console.log("found " + this.value);
});

or
$("#test").children().each(function () {
    console.log("found " + this.value);
});

A: Here is an example that might explain it more: https://jsfiddle.net/Twisty/dr1tay6f/6/
HTML
<select multiple="multiple" size="5" id="test">
  <option value="a">Item A</option>
  <option value="b">Item B</option>
</select>

<button type="button" id="bid">test</button>

JavaScript
$(function() {
  $("#bid").click(function() {
    $("#test option").each(function(ind, el) {
      console.log("At Index " + ind +" found Option with Value: " + $(el).val() + " and Label of: " + $(el).html());
    });
  });
});

The $(selector).each(callback(index, element)); will iterate over each element in the selector, passing it's index and element to the function.


text:
Q: Suspension on invoking method jdbcTemplate.getDataSource() Hello everyone!
I have a application, which configured with spring 3 and hibernate 3. In application all requests to database with a JDBCTemplate and HibernateTemplate. In my case i have a method, which registers an array parameter:
protected void registerArrayParameter(PreparedStatement st, int num, Long[] mas) throws SQLException {
    Connection conn = jdbcTemplate.getDataSource().getConnection();
    OracleConnection ocon = (OracleConnection) ((DelegatingConnection) conn).getInnermostDelegate();
    ArrayDescriptor arrayDescriptor = ArrayDescriptor.createDescriptor("CCSYS.NUMBER_TABLE", ocon);
    java.sql.Array sqlArray = new oracle.sql.ARRAY(arrayDescriptor, ocon, mas);
    st.setArray(num, sqlArray);
}

Often application suspend (freezing) on jdbcTemplate.getDataSource().getConnection().
Could somebody know what it can be?
Thanks for any replies.

A: Solved!
In my case i have a class extends BasicDataSourse:
public class SomeSource extends BasicDataSource implements Serializable {
    public static final long serialVersionUID = 4467486478647684235L;
    public static SomeSource dataSource;

    public SomeSource(){
        super();
        /* implementation*/
        ....
        dataSource = this;
    }
}

I have modified method, which registers an array parameter:
protected void registerArrayParameter(PreparedStatement st, int num, Long[] mas) throws SQLException {
    Connection conn = jdbcTemplate.getDataSource().getConnection();
    OracleConnection ocon = (OracleConnection) ((DelegatingConnection) conn).getInnermostDelegate();
    ArrayDescriptor arrayDescriptor = ArrayDescriptor.createDescriptor("CCSYS.NUMBER_TABLE", ocon);
    java.sql.Array sqlArray = new oracle.sql.ARRAY(arrayDescriptor, ocon, mas);
    st.setArray(num, sqlArray);

    /*added*/
    conn.close();
    ocon.close();
    SomeSource.dataSource.close();
}

After that the application steel working without suspend/freezing...


text:
Q: The operation could not complete. (Alamofire.AFError error 9.) On a network request handled by Alamofire, I often get this error:

The operation could not complete. (Alamofire.AFError error 9.)

Has anyone a clue about what this error 9 is?
I suppose AFError being an enum and conforming to protocol Error, this error 9 could be the raw value of the createURLRequestFailed(error:) case (which is the 10th case in this enum).
AFError enumeration reference
I then implemented some delegate methods in EventMonitor, like
public func request(_ request: Request, didFailToCreateURLRequestWithError error: AFError)

public func request(_ request: Request, didCompleteTask task: URLSessionTask, with error: AFError?)

public func request(_ request: UploadRequest, didFailToCreateUploadableWithError error: AFError)

public func request(_ request: Request, didFailTask task: URLSessionTask, earlyWithError error: AFError)

but none of these seem to be triggered for this error (especially the first one, which seemed a good fit).
How can I debug this error and find the root cause of the issue?

A: I found this, where you can debug this by casting the AFError to an NSError or URLError and from there on debug what it is that actually went wrong.
https://github.com/Alamofire/Alamofire/issues/3068


text:
Q: Issue with Resampling and True/False being set to 1 or 0. Okay so I have this code:  That reads in this CSV file:
2004-02-27 00:00,7.7,167
2004-02-27 00:05,7.5,169
2004-02-27 00:10,7.2,173
2004-02-27 00:15,7,176
2004-02-27 00:20,6.5,176
2004-02-27 00:25,6,178
2004-02-27 00:30,5.6,184
2004-02-27 00:35,5.5,185
2004-02-27 00:40,5.8,182
2004-02-27 00:45,6.3,178
2004-02-27 00:50,6.6,179
2004-02-27 00:55,6.6,186
2004-02-27 01:00,6.6,189
2004-02-27 01:05,6.5,190
2004-02-27 01:10,6,192
2004-02-27 01:15,6.2,195
2004-02-27 01:20,6.4,197
2004-02-27 01:25,6.7,197
2004-02-27 01:30,7,198
2004-02-27 01:35,7.2,200
2004-02-27 01:40,7.5,202
2004-02-27 01:45,7.8,206
2004-02-27 01:50,8.1,206
2004-02-27 01:55,7.9,202
2004-02-27 02:00,7.5,196
2004-02-27 02:05,7.3,191
2004-02-27 02:10,7.7,189
2004-02-27 02:15,7.7,185
2004-02-27 02:20,7.4,173
2004-02-27 02:25,6.8,172
2004-02-27 02:30,6,183
2004-02-27 02:35,5.8,188
2004-02-27 02:40,5.8,186
2004-02-27 02:45,6,177
2004-02-27 02:50,6,174
2004-02-27 02:55,5.8,179
2004-02-27 03:00,5.4,183
2004-02-27 03:05,5.6,177
2004-02-27 03:10,5.8,174
2004-02-27 03:15,5.7,176
2004-02-27 03:20,5.7,176
2004-02-27 03:25,5.4,177
2004-02-27 03:30,4.9,174
2004-02-27 03:35,4.6,174
2004-02-27 03:40,4.4,175
2004-02-27 03:45,4.2,175
2004-02-27 03:50,3.9,170
2004-02-27 03:55,4,161
2004-02-27 04:00,4,157
2004-02-27 04:05,3.8,158
2004-02-27 04:10,3.7,158
2004-02-27 04:15,3.4,155
2004-02-27 04:20,3.5,153
2004-02-27 04:25,3.9,154
2004-02-27 04:30,4.2,152
2004-02-27 04:35,4.3,146
2004-02-27 04:40,4.1,139
2004-02-27 04:45,3.8,134
2004-02-27 04:50,3.9,132
2004-02-27 04:55,4.7,130
2004-02-27 05:00,5.6,125
2004-02-27 05:05,5.6,121
2004-02-27 05:10,5,119
2004-02-27 05:15,4.2,120
2004-02-27 05:20,3.8,120
2004-02-27 05:25,4.3,116
2004-02-27 05:30,5.1,112
2004-02-27 05:35,5.7,110
2004-02-27 05:40,6.3,106
2004-02-27 05:45,6.2,101
2004-02-27 05:50,5.7,95
2004-02-27 05:55,5.4,91
2004-02-27 06:00,4.5,90
2004-02-27 06:05,3.7,86
2004-02-27 06:10,3.2,83
2004-02-27 06:15,2.7,83
2004-02-27 06:20,2.5,78
2004-02-27 06:25,3,69
2004-02-27 06:30,4,69
2004-02-27 06:35,4.5,74
2004-02-27 06:40,4.1,70
2004-02-27 06:45,3.9,64
2004-02-27 06:50,3.9,62
2004-02-27 06:55,3.3,63
2004-02-27 07:00,3,72
2004-02-27 07:05,3.5,94
2004-02-27 07:10,3.7,110
2004-02-27 07:15,2.6,115
2004-02-27 07:20,1.7,118
2004-02-27 07:25,1.7,111
2004-02-27 07:30,1.5,104
2004-02-27 07:35,2.4,94
2004-02-27 07:40,3.8,87
2004-02-27 07:45,4.3,85
2004-02-27 07:50,4.4,89
2004-02-27 07:55,4.5,91
2004-02-27 08:00,5.2,91
2004-02-27 08:05,5.1,90
2004-02-27 08:10,4.3,79
2004-02-27 08:15,3.9,69
2004-02-27 08:20,4.1,58
2004-02-27 08:25,4.5,46
2004-02-27 08:30,5.1,31
2004-02-27 08:35,5.3,17
2004-02-27 08:40,4.7,8
2004-02-27 08:45,4.1,6
2004-02-27 08:50,3.1,11
2004-02-27 08:55,1.8,2
2004-02-27 09:00,1.2,349
2004-02-27 09:05,1.1,344
2004-02-27 09:10,1.4,350
2004-02-27 09:15,1.6,345
2004-02-27 09:20,1.7,322
2004-02-27 09:25,2.1,304
2004-02-27 09:30,2.4,296
2004-02-27 09:35,2.1,297
2004-02-27 09:40,1.8,309
2004-02-27 09:45,2,323
2004-02-27 09:50,2.6,326
2004-02-27 09:55,3,330
2004-02-27 10:00,2.8,342
2004-02-27 10:05,2.9,351
2004-02-27 10:10,3.5,348
2004-02-27 10:15,4.1,342
2004-02-27 10:20,4.7,333
2004-02-27 10:25,4.9,319
2004-02-27 10:30,5.1,309
2004-02-27 10:35,6,301
2004-02-27 10:40,6.6,299
2004-02-27 10:45,7.5,296
2004-02-27 10:50,6.9,288
2004-02-27 10:55,4.3,227
2004-02-27 11:00,2.5,184
2004-02-27 11:05,2.1,201
2004-02-27 11:10,2.4,222
2004-02-27 11:15,2.9,228
2004-02-27 11:20,2.9,226
2004-02-27 11:25,2.8,191
2004-02-27 11:30,2.8,168
2004-02-27 11:35,2.6,185
2004-02-27 11:40,3,203
2004-02-27 11:45,3.5,200
2004-02-27 11:50,3.9,174
2004-02-27 11:55,3.5,158
2004-02-27 12:00,2.4,187
2004-02-27 12:05,2.2,218
2004-02-27 12:10,1.7,218
2004-02-27 12:15,1.1,215
2004-02-27 12:20,1.1,204
2004-02-27 12:25,1.8,206
2004-02-27 12:30,2.4,226
2004-02-27 12:35,3.3,233
2004-02-27 12:40,3.9,226
2004-02-27 12:45,3.7,219
2004-02-27 12:50,3.9,214
2004-02-27 12:55,4.7,213
2004-02-27 13:00,5.1,214
2004-02-27 13:05,5.1,216
2004-02-27 13:10,5.3,217
2004-02-27 13:15,5.7,219
2004-02-27 13:20,6.1,225
2004-02-27 13:25,6.3,228
2004-02-27 13:30,6.3,225
2004-02-27 13:35,6.3,223
2004-02-27 13:40,6.2,224
2004-02-27 13:45,5.8,226
2004-02-27 13:50,5.9,231
2004-02-27 13:55,6.9,237
2004-02-27 14:00,7.7,241
2004-02-27 14:05,7.7,244
2004-02-27 14:10,7.8,244
2004-02-27 14:15,8.3,247
2004-02-27 14:20,8.6,248
2004-02-27 14:25,8.6,249
2004-02-27 14:30,9,251
2004-02-27 14:35,9.3,251
2004-02-27 14:40,9.1,250
2004-02-27 14:45,8.9,249
2004-02-27 14:50,8.7,246
2004-02-27 14:55,8.7,242
2004-02-27 15:00,8.7,243
2004-02-27 15:05,8.6,246
2004-02-27 15:10,8.9,249
2004-02-27 15:15,9.3,251
2004-02-27 15:20,9,253
2004-02-27 15:25,8.6,255
2004-02-27 15:30,8.3,257
2004-02-27 15:35,7.5,260
2004-02-27 15:40,6.9,267
2004-02-27 15:45,7.1,271
2004-02-27 15:50,7.2,270
2004-02-27 15:55,7.3,270
2004-02-27 16:00,7.7,271
2004-02-27 16:05,7.6,269
2004-02-27 16:10,7.2,265
2004-02-27 16:15,7,264
2004-02-27 16:20,7.1,266
2004-02-27 16:25,7.3,269
2004-02-27 16:30,7.6,272
2004-02-27 16:35,7.5,273
2004-02-27 16:40,7.4,273
2004-02-27 16:45,7.2,274
2004-02-27 16:50,6.6,273
2004-02-27 16:55,6,274
2004-02-27 17:00,5.6,275
2004-02-27 17:05,5.4,274
2004-02-27 17:10,5.5,269
2004-02-27 17:15,5.7,267
2004-02-27 17:20,5.6,265
2004-02-27 17:25,5.3,263
2004-02-27 17:30,5.4,261
2004-02-27 17:35,5.6,256
2004-02-27 17:40,5.4,255
2004-02-27 17:45,5,259
2004-02-27 17:50,5,264
2004-02-27 17:55,5.3,267
2004-02-27 18:00,6,266
2004-02-27 18:05,6.6,258
2004-02-27 18:10,6.6,249
2004-02-27 18:15,6.7,246
2004-02-27 18:20,6.6,244
2004-02-27 18:25,6.8,248
2004-02-27 18:30,6.5,254
2004-02-27 18:35,5.6,262
2004-02-27 18:40,6.7,267
2004-02-27 18:45,7.7,268
2004-02-27 18:50,6.5,269
2004-02-27 18:55,5.9,274
2004-02-27 19:00,6.6,270
2004-02-27 19:05,6.5,256
2004-02-27 19:10,5.6,252
2004-02-27 19:15,5.4,259
2004-02-27 19:20,4.8,255
2004-02-27 19:25,3.8,244
2004-02-27 19:30,4.1,242
2004-02-27 19:35,4.7,239
2004-02-27 19:40,5,236
2004-02-27 19:45,5.4,235
2004-02-27 19:50,6,237
2004-02-27 19:55,6.2,239
2004-02-27 20:00,6.5,240
2004-02-27 20:05,7.5,248
2004-02-27 20:10,7.8,246
2004-02-27 20:15,7.2,239
2004-02-27 20:20,7.5,244
2004-02-27 20:25,8.9,247
2004-02-27 20:30,10.5,248
2004-02-27 20:35,12.3,252
2004-02-27 20:40,12.8,252
2004-02-27 20:45,12.4,247
2004-02-27 20:50,12.6,247
2004-02-27 20:55,12.4,250
2004-02-27 21:00,11.9,252
2004-02-27 21:05,11.8,252
2004-02-27 21:10,11.7,252
2004-02-27 21:15,11.4,252
2004-02-27 21:20,10.8,252
2004-02-27 21:25,10.6,251
2004-02-27 21:30,10.6,251
2004-02-27 21:35,10.9,251
2004-02-27 21:40,11.6,250
2004-02-27 21:45,11.9,251
2004-02-27 21:50,11.4,254
2004-02-27 21:55,11.1,255
2004-02-27 22:00,11.5,256
2004-02-27 22:05,11.9,256
2004-02-27 22:10,11.9,255
2004-02-27 22:15,12,255
2004-02-27 22:20,12.2,257
2004-02-27 22:25,12.4,258
2004-02-27 22:30,12.5,257
2004-02-27 22:35,12.6,257
2004-02-27 22:40,12.7,258
2004-02-27 22:45,12.9,259
2004-02-27 22:50,13.6,259
2004-02-27 22:55,14.3,259
2004-02-27 23:00,14.2,262
2004-02-27 23:05,13.8,263
2004-02-27 23:10,14.1,263
2004-02-27 23:15,14.8,264
2004-02-27 23:20,14.7,263
2004-02-27 23:25,13.6,263
2004-02-27 23:30,12.9,263
2004-02-27 23:35,13.2,261
2004-02-27 23:40,12.4,261
2004-02-27 23:45,12.2,262
2004-02-27 23:50,12.9,261
2004-02-27 23:55,11.6,260
2004-02-28 00:00,10.8,259
2004-02-28 00:05,10.9,260
2004-02-28 00:10,10.6,262
2004-02-28 00:15,10.1,264
2004-02-28 00:20,9.3,264

What I want it to do, is for every data point, give it a flag (1 or 0) for the Wind Direction (first column) and if the Wind speed is less than 4 or greater than 4. And a middle one aswell.
Then I want it do take an average, sl that if there is one false data point (the average would be less than 1) and thus can turn that to a 0.
However, when going through line by line, its saved as an integer, but then is converted to an object.
My code is below:
import pandas as pd
names=['Date','Wind Speed','Wind Direction']
df_met = pd.read_csv('Met_Test.csv', index_col=0, names=names, parse_dates=[0])
df1=df_met
df1.insert(2,'Wind_direction_Flag','1')
df1.insert(3,'Wind_Speed_Less_than_4','0')
df1.insert(4,'Middle','0')
df1.insert(5,'Wind_Speed_Greater_than_10','0')

    for line in df1.iterrows():
            #print("**********")
            flag1=(line[1]['Wind Direction']>250)  & (line[1]['Wind Direction'] <345)
            #print (flag1)
            #flag1=flag1.astype(int)
            flag2=(line[1]['Wind Speed']<4)
            #flag2=flag2.astype(int)
            flag3=(line[1]['Wind Speed']>=4 ) & (line[1]['Wind Speed']<=10)
            #flag3=flag3.astype(int)
            flag4=(line[1]['Wind Speed']>10)
            #flag4=flag4.astype(int)
            print("JDKSJKDj",line[1]['Middle'])
    #%%

            line[1]['Wind_direction_Flag']=int(flag1)
            line[1]['Wind_Speed_Less_than_4']=int(flag2)
            line[1]['Middle']=int(flag3)
            line[1]['Wind_Speed_Greater_than_10']=int(flag4)

    print("JDKSJKDj",df1['Middle'])

    print(type(df1['Middle']))

    print(type(df1['Middle']))
    df1.to_csv("All_Met.csv")
    ####Takes an hour average
    df2=df1.resample('h').mean()
    df2.loc[df2['Wind_direction_Flag'] == 0, 'Wind_direction_Flag'] = -100
    df2.loc[df2['Wind_direction_Flag'] > 0, 'Wind_direction_Flag'] = 0
    df2.loc[df2['Wind_direction_Flag'] < 0, 'Wind_direction_Flag'] = 1

Thanks in advance!

A: I think this seems to work:
import pandas as pd
names=['Date','Wind Speed','Wind Direction']
df_met = pd.read_csv('Met_Test.csv', index_col=0, names=names, parse_dates=[0])
df1=df_met
df1.insert(2,'Wind_direction_Flag','1')
df1.insert(3,'Wind_Speed_Less_than_4','0')
df1.insert(4,'Middle','0')
df1.insert(5,'Wind_Speed_Greater_than_10','0')

flag1=(df1['Wind Direction']>290 ) & (df1['Wind Direction'] <345)
flag1=flag1.astype(int)

flag2=(df1['Wind Speed']<4)
flag2=flag2.astype(int)

flag3=(df1['Wind Speed']>=4 ) & (df1['Wind Speed']<=10)
flag3=flag3.astype(int)

flag4=(df1['Wind Speed']>20)
flag4=flag4.astype(int)

df1['Wind_direction_Flag']=flag1
df1['Wind_Speed_Less_than_4']=flag2
df1['Middle']=flag3
df1['Wind_Speed_Greater_than_10']=flag4
#%%
df1.to_csv("All_Met.csv")
####Takes an hour average
df2=df1.resample('h').mean()
df2.loc[df2['Wind_direction_Flag'] == 0, 'Wind_direction_Flag'] = -100
df2.loc[df2['Wind_direction_Flag'] > 0, 'Wind_direction_Flag'] = 0 #Win ddirection is the opposite flag as want 1's for good data
df2.loc[df2['Wind_direction_Flag'] < 0, 'Wind_direction_Flag'] = 1


text:
Q: The Negative Energy in the Harmonic Oscillator Potential! I'm self studying Quantum mechanics from Griffiths. Now I'm at the Harmonic oscillator potential. All my questions raised after defining the ladder operators $a_-$ and $a_+$.
If $\psi$ satisfies the time independent Schrodinger equation then too $a_-\psi$ with energy $(E-\hslash\omega)$ such that:
$H(a_-\psi)=(E-\hslash\omega)(a_-\psi)$
Applying the lowering operator repeatedly eventually I'm going to reach a state with energy less than zero, It's written that according to some problem (which says that the energy must exceed the minimum value of $V(x)$), and such state does not exist!
That's mean that he refutes that the potential can be less than zero. I don't get why is that? That was a the first question.
Now for the second question I have to write what was exactly written:
"We know that $(a_-\psi)$ is a new solution to the schrodinger equation, but there is no guarantee that it will be normalizable$-$it might be zero, or its square-integral might be infinite"
I get that so far, what I don't get:
"In practice it is the former: There occurs a "lowest rung" (call it $\psi_0$) such that
$(a_-\psi)$=0"
How? Or is it a must to enforce it?
That's all and thank you for your time anyway.

A: For the first doubt, there is a problem in the very same chapter in the initial section which asks you to prove the statement. It all boils down to normalization of the solution.
As a general statement, we want our $\hat{H}$ to be positive definite so that our system is unitary, it's used in QFT as well.
For the second one since our potential goes to infinite with $x$ and we're dealing with bound state as the $E$ are discrete so we won't be getting any not square-integrable function (bound state definition) what we're left with is $\psi_g=0$ where $\psi_g=a_-\psi$.
If you're still confused you can check Adam explanation in MIT OCW QP-I.

A: If we see the energy spectrum for a harmonic oscillator we get,
En = (n + 1/2) (h/2π) ω ..............(1)
Where En is the energy for n-th state.
Now, it's evident that;
En+1 - En = (h/2π) ω..........(2)
Which is in agreement with Planck's equidistant energy concept.
So as expected for bound states we see that the energy spectrum is discrete. Now if we are to consider the lowest energy of the spectrum we need to consider the zero point energy corresponding to the state n=0 which is;
E0 = (h/2π) ω/2.............(3)
So it's evident that the lowest possible energy in case of an harmonic oscillator is not zero rather it has a proper value which is in agreement with uncertainty principle.
So we must when we are considering the ground state energy state we are talking about |0> state and applying lowering operator on this state cannot provide any result and thus we must get;
a_ ψo = 0
I hope it was helpful. And sorry for the expressions, I'm using my mobile and can't get proper expressions.


text:
Q: How to store device id in web service in windows phone? this is my web service url
http://www.newsquizapp.com/webservice/get_question
Parameter :
1. device_id
2. quiz_type
Method: post
i already retrieve device_id & quiz_type
but my problem is how to send device_id & quiz_type so that the device id is store in web service.
    void SendPost()
    {
        var url = "http://www.newsquizapp.com/webservice/get_question";

        HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
        webRequest.Method = "POST";
        webRequest.ContentType = "application/x-www-form-urlencoded";

        webRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), webRequest);
    }
    void GetRequestStreamCallback(IAsyncResult callbackResult)
    {
        HttpWebRequest webRequest = (HttpWebRequest)callbackResult.AsyncState;
        Stream postStream = webRequest.EndGetRequestStream(callbackResult);
        // static device id
        string postData = "device_id=001&quiz_type=all";

        byte[] byteArray = Encoding.UTF8.GetBytes(postData);

        postStream.Write(byteArray, 0, byteArray.Length);
        postStream.Close();

        webRequest.BeginGetResponse(new AsyncCallback(GetResponseCallback), webRequest);
    }

    void GetResponseCallback(IAsyncResult callbackResult)
    {
        try
        {
            HttpWebRequest webRequest = (HttpWebRequest)callbackResult.AsyncState;
            HttpWebResponse response;
            response = (HttpWebResponse)webRequest.EndGetResponse(callbackResult);
            Stream streamResponse = response.GetResponseStream();
            StreamReader streamReader = new StreamReader(streamResponse);
            var Response = streamReader.ReadToEnd();
            streamResponse.Close();
            streamReader.Close();
            response.Close();

        }
        catch (WebException e)
        {
            // Error treatment
            // ...
        }
    }
    public void MainPage_Loaded(object sender, RoutedEventArgs e)
    {
        client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(download);
        client.DownloadStringAsync(new Uri("http://www.newsquizapp.com/webservice/get_question"));
    }

    public void download(object sender, DownloadStringCompletedEventArgs e)
    {
        var objMain = JsonConvert.DeserializeObject<Main>(e.Result);
        question = objMain.questions;
        DisplayQuestion();
    }
    protected void DisplayQuestion()
    {
        rb1.Visibility = Visibility.Visible;
        rb2.Visibility = Visibility.Visible;
        rb3.Visibility = Visibility.Visible;
        rb4.Visibility = Visibility.Visible;

        Question objQue = question[counter];
        txtquestion.Text = objQue.questionTitle;
        rb1.Content = objQue.answers[0].answer;
        rb2.Content = objQue.answers[1].answer;
        rb3.Content = objQue.answers[2].answer;

        if (objQue.answers.Count == 3)
        {
            rb4.Visibility = Visibility.Collapsed;
        }
        else
        {
            rb4.Visibility = Visibility.Visible;
            rb4.Content = objQue.answers[3].answer;
        }
    }
    protected void radio_checked(object sender, RoutedEventArgs e)
    {
        btnFinish.Visibility = Visibility.Collapsed;
        btnSubmit.Visibility = Visibility.Visible;
    }
    protected void btnsubmit_click(object sender, RoutedEventArgs e)
    {
        Question que = question[counter];

        var correctAnswerId = que.correctAnswerId;

        string answer = string.Empty;

        if (que.answers[0].answerId == correctAnswerId)
        {
            answer = que.answers[0].answer;
        }

        if (que.answers[1].answerId == correctAnswerId)
        {
            answer = que.answers[1].answer;
        }

        if (que.answers[2].answerId == correctAnswerId)
        {
            answer = que.answers[2].answer;
        }

        if (que.answers.Count == 3)
        {
            rb4.Visibility = Visibility.Collapsed;
        }

        else if (que.answers[3].answerId == correctAnswerId)
        {
            answer = que.answers[3].answer;
        }

        if (rb1.IsChecked == true && que.answers[0].answerId == correctAnswerId)
        {
            txtanswer.Text = que.answers[0].answer;
            rb1.Visibility = Visibility.Collapsed;
            rb2.Visibility = Visibility.Collapsed;
            rb3.Visibility = Visibility.Collapsed;
            rb4.Visibility = Visibility.Collapsed;

        }

        else if (rb1.IsChecked == true && que.answers[0].answerId != correctAnswerId)
        {
            rb1.Visibility = Visibility.Visible;
            rb2.Visibility = Visibility.Collapsed;
            rb3.Visibility = Visibility.Collapsed;
            rb4.Visibility = Visibility.Collapsed;
            txtanswer.Text = answer;

        }

        else if (rb2.IsChecked == true && que.answers[1].answerId == correctAnswerId)
        {
            txtanswer.Text = que.answers[1].answer;
            rb1.Visibility = Visibility.Collapsed;
            rb2.Visibility = Visibility.Collapsed;
            rb3.Visibility = Visibility.Collapsed;
            rb4.Visibility = Visibility.Collapsed;
        }
        else if (rb2.IsChecked == true && que.answers[1].answerId != correctAnswerId)
        {
            rb1.Visibility = Visibility.Collapsed;
            rb2.Visibility = Visibility.Visible;
            rb3.Visibility = Visibility.Collapsed;
            rb4.Visibility = Visibility.Collapsed;
            txtanswer.Text = answer;

        }

        else if (rb3.IsChecked == true && que.answers[2].answerId == correctAnswerId)
        {
            txtanswer.Text = que.answers[2].answer;
            rb1.Visibility = Visibility.Collapsed;
            rb2.Visibility = Visibility.Collapsed;
            rb3.Visibility = Visibility.Collapsed;
            rb4.Visibility = Visibility.Collapsed;
        }
        else if (rb3.IsChecked == true && que.answers[2].answerId != correctAnswerId)
        {
            rb1.Visibility = Visibility.Collapsed;
            rb2.Visibility = Visibility.Collapsed;
            rb3.Visibility = Visibility.Visible;
            rb4.Visibility = Visibility.Collapsed;
            txtanswer.Text = answer;

        }
        else if (que.answers.Count == 3)
        {
            rb4.Visibility = Visibility.Collapsed;
        }

        else if (rb4.IsChecked == true && que.answers[3].answerId == correctAnswerId)
        {
            txtanswer.Text = que.answers[3].answer;
            rb1.Visibility = Visibility.Collapsed;
            rb2.Visibility = Visibility.Collapsed;
            rb3.Visibility = Visibility.Collapsed;
            rb4.Visibility = Visibility.Collapsed;
        }
        else if (rb4.IsChecked == true && que.answers[3].answerId != correctAnswerId)
        {
            rb1.Visibility = Visibility.Collapsed;
            rb2.Visibility = Visibility.Collapsed;
            rb3.Visibility = Visibility.Collapsed;
            rb4.Visibility = Visibility.Visible;
            txtanswer.Text = answer;

        }
        btnNext.Visibility = Visibility.Visible;
    }

    protected void btnnext_click(object sender, RoutedEventArgs e)
    {
        counter++;
        if (counter >= question.Count)
        {
            txtanswer.Text = "no more question right now....";
        }
        else
        {
            DisplayQuestion();
        }
    }
}

once the user device id stores in database, they will not get the same question if user close the app & again open it...

A: Maybe a HTTPRequest is what you are looking for.
http://dotnet-snippets.de/snippet/simple-web-request-with-web-response/215

A: Http Post for Windows Phone 8
Check the answer from nemesisfixx.
I found it helpful.
If you have access to the webservice code, you can modify it to carry the Device_uid as a url parameter and thus avoid all the extra work. I did so.

A: If you just want to POST data to a web service you can use WebClient class. It is the simplest way to achieve what you are looking to do.
Example:
Uri uri = new Uri("http://www.newsquizapp.com/webservice/get_question");
string data = "device_id=123&quiz_type=all";
WebClient wc = new WebClient();
wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
wc.UploadStringAsync(uri, data);
wc.UploadStringCompleted += wc_UploadComplete;

public void wc_UploadComplete(object sender, UploadStringCompletedEventArgs e)
{
   string result = e.Result.ToString();
   MessageBox.Show(result);
}

Try this out. Hope it helps.


text:
Q: Type.GetEnumUnderlyingType() replacement for .net35 I'm looking for a way to replicate the functionality of Type.GetEnumUnderlyingType() which is missing in .net35.

A: Just use Enum.GetUnderlyingType instead:

Returns the underlying type of the specified enumeration.

A: Here's the implementation for GetEnumUnderlyingType from Type:
public virtual Type GetEnumUnderlyingType()
{
    if (!this.IsEnum)
        throw new ArgumentException(
            Environment.GetResourceString("Arg_MustBeEnum"), "enumType");
    FieldInfo[] fields = this.GetFields(
        BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
    if (fields == null || fields.Length != 1)
        throw new ArgumentException(
            Environment.GetResourceString("Argument_InvalidEnum"), "enumType");
    return fields[0].FieldType;
}


text:
Q: Load JSON data into a Bootstrap modal I want to load a JSON file that creates a list inside a Bootstrap Modal. I have it set where if you click on a person's picture, the modal pops up.

Kenneth Atkins

[Description here]

Here's an example of the JSON data:
    var florida_exoneration = [
  {
    "last_name":"Atkins",
    "first_name":"Kenneth",
    "age":16,
    "race":"Caucasian",
    "state":"FL",
    "crime":"Sexual Assault",
    "sentence":"10 years",
    "conviction":2004,
    "exonerated":2008,
    "dna":"",
    "mistaken witness identification":"",
    "false confession":"",
    "perjury/false accusation":"Y",
    "false evidence":"",
    "official misconduct":"",
    "inadequate legal defense":"",
    "compensation":""
  }
]

I'd like the modal to display something like this inside the box:
Title = "first_name + last_name"
Age = "age"
Race = "race"
State = "state"
""
""

I also want to make sure the data is tied to the picture so the modal doesn't get confused. I'm sorry if this is a bit confusing. I'll try and clarify if anyone has any questions.

A: Method 1: using Ajax
Every time a user clicks an image, you get the id from the clicked image and then you send an Ajax request to server in order to get the JSON object.
HTML

Kenneth Atkins

[Description here]

JavaScript
(function($) {
    var infoModal = $('#myModal');
    $('.thumbnail').on('click', function(){
        $.ajax({
          type: "GET",
          url: 'getJson.php?id='+$(this).data('id'),
          dataType: 'json',
          success: function(data){
            htmlData = '

title: '+data.first_name+'

age: '+data.age+'

';
            infoModal.find('.modal-body').html(htmlData);
            infoModal.modal('show');
          }
        });

        return false;
    });
})(jQuery);

Method 2: using hidden div
No need to any Ajax request, but you need to create a hidden div that contain all the information you want to display in the modal
HTML

Kenneth Atkins

[Description here]

title: Atkins Kenneth

Age: 16

JavaScript
(function($) {
    var infoModal = $('#myModal');
    $('.thumbnail').on('click', function(){
        htmlData = $(this).find('.profile').html();
        infoModal.find('.modal-body').html(htmlData);
        infoModal.modal('show');
        return false;
    });
})(jQuery);


text:
Q: Double Superscript Error with Macro Adding a Superscript I found a lots of questions asking how to add a superscript to a variable defined with a superscript but none for how to do it the other way around.
My macro is \newcommand{\trsp}[1]{#1^T} and I want to apply it to e.g. \trsp{M^{-1}}.
How do I avoid a Double Superscript error ?

A: Use \def\trsp#1{{#1}^T}. The key is to use {#1} instead #1 in the body of the macro. You can use \newcommand too, if you are using LaTeX.


text:
Q: SSRS Expression to extract all Names in an Name Field I have a query that pulls three fields, over 9000 rows (A-Z, names):

I am trying to extract by all "A" name Agencies, "B", and so on into Excel worksheets by each A,B,C,etc., once we render and save the report.
Can someone help with an Expression that will accomplish this?
Thanks,
jer

A: First create a calculated field in the dataset to get the first letter of each agency.
=Left(Fields!AgencyName.Value, 1)

Next, set up a table (aka tablix or matrix) with two row groups. The parent group should be sorted and grouped by the new FirstLetter column. In this group's properties, set it to break at the end of each group. Also set the PageName property to be the FirstLetter.
The child row group should be grouped by nothing so that it will show every detail row. Sort it by Agency name if desired.
What you should get now is a page for each letter and within each page a row for each agency. When you export to Excel it will create a sheet for each "page" and name them all accordingly.


text:
Q: Disable function in NodeJS for a while Is there any option to disable function call for a while? for example you can call this function only once per 5 seconds.
Here is my code I would like call max once per 5 seconds:
var rest =  require.main.require('./src/Core/WebService/RESTful');

module.exports = {

  updateTimetableData: function(config) {
    var url = 'http://' + config.pttIpAddress + ':' + config.pttServerPort + '/api/';
    var requestUrl = url + 'updatetimetabledata?ipAddress=' + config.pttIpAddress + '&macAddress=' + config.pttMacAddress + '&appVersion=' + config.appVersion;
    rest.getDataFromRESTWebService(requestUrl);
  }

}

This method can be called by client rest service and from server code also.

A: *

*Create a variable (outside the function).

*When the function is called, compare the time stored in the variable with the current time. If the difference is less than 5 seconds: immediately return.

*Store the current time in the variable


text:
Q: Database and SpringBoot in same Docker-Containter without password safe? I was wondering if it is safe to configure a DB without a password, when you deploy the SpringBootApp in the same container.
So that you dont have to expose the ports of the DB.
Roughly like this docker-compose.yml
version:'3'
service:
   myspringapp:
       ...
       dependson: 'mydb'
       ports:
         - 8080:8080
   mydb:
       ...

Now the DB should not be accessible for outstanding persons or am I missing something?


text:
Q: How to compare images using opencv in iOS (iPhone) I want to compare 2 images taken by iPhone camera in my project. I am using OpenCV for doing that. Is there any other better way to do that?
If i got the % similarity, It will be great.
I am using OpenCV following code for image comparison:
-(void)opencvImageCompare{
 NSMutableArray *valuesArray=[[NSMutableArray alloc]init];
 IplImage *img = [self CreateIplImageFromUIImage:imageView.image];
// always check camera image
 if(img == 0) {
   printf("Cannot load camera img");

}

IplImage  *res;
CvPoint   minloc, maxloc;
double    minval, maxval;
double values;

UIImage *imageTocompare = [UIImage imageNamed:@"MyImageName"];
IplImage *imageTocompareIpl = [self CreateIplImageFromUIImage:imageTocompare];
// always check server image
if(imageTocompareIpl == 0) {
    printf("Cannot load serverIplImageArray image");
}
if(img->width-imageTocompareIpl->width<=0 && img->height-imageTocompareIpl->height<=0){
    int balWidth=imageTocompareIpl->width-img->width;
    int balHeight=imageTocompareIpl->height-img->height;
    img->width=img->width+balWidth+100;
    img->height=img->height+balHeight+100;
}

CvSize size = cvSize(
                     img->width  - imageTocompareIpl->width  + 1,
                     img->height - imageTocompareIpl->height + 1
                     );

res = cvCreateImage(size, IPL_DEPTH_32F, 1);

// CV_TM_SQDIFF CV_TM_SQDIFF_NORMED
// CV_TM_CCORR  CV_TM_CCORR_NORMED
// CV_TM_CCOEFF CV_TM_CCOEFF_NORMED

cvMatchTemplate(img, imageTocompareIpl, res,CV_TM_CCOEFF);
cvMinMaxLoc(res, &minval, &maxval, &minloc, &maxloc, 0);
printf("\n value %f", maxval-minval);
values=maxval-minval;
NSString *valString=[NSString stringWithFormat:@"%f",values];
[valuesArray addObject:valString];
weedObject.values=[valString doubleValue];
printf("\n------------------------------");

cvReleaseImage(&imageTocompareIpl);

cvReleaseImage(&res);
}
cvReleaseImage(&img);

}

For the same image I am getting non zero result (14956...) and if I pass different image its crash.

A: try this code, It compares images bit by bit, ie 100%
UIImage *img1 = // Some photo;
UIImage *img2 = // Some photo;

NSData *imgdata1 = UIImagePNGRepresentation(img1);

NSData *imgdata2 = UIImagePNGRepresentation(img2);

if ([imgdata1 isEqualToData:imgdata2])
{
NSLog(@"Same Image");
}

A: Try this code - it compare images pixel by pixel
-(void)removeindicator :(UIImage *)image
{
    for (int i =0; i < [imageArray count]; i++)
    {
        CGFloat width =100.0f;
        CGFloat height=100.0f;

        CGSize newSize1 = CGSizeMake(width, height); //whaterver size
        UIGraphicsBeginImageContext(newSize1);
        [[UIImage imageNamed:[imageArray objectAtIndex:i]] drawInRect:CGRectMake(0, 0, newSize1.width, newSize1.height)];
         UIImage *newImage1 = UIGraphicsGetImageFromCurrentImageContext();
         UIGraphicsEndImageContext();

        UIImageView *imageview_camera=(UIImageView *)[self.view viewWithTag:-3];

        CGSize newSize2 = CGSizeMake(width, height); //whaterver size
        UIGraphicsBeginImageContext(newSize2);
        [[imageview_camera image] drawInRect:CGRectMake(0, 0, newSize2.width, newSize2.height)];
         UIImage *newImage2 = UIGraphicsGetImageFromCurrentImageContext();
         UIGraphicsEndImageContext();

       float numDifferences = 0.0f;
       float totalCompares = width * height;

       NSArray *img1RGB=[[NSArray alloc]init];
       NSArray *img2RGB=[[NSArray alloc]init];

      for (int yCoord = 0; yCoord < height; yCoord += 1)
      {
          for (int xCoord = 0; xCoord < width; xCoord += 1)
          {
              img1RGB = [self getRGBAsFromImage:newImage1 atX:xCoord andY:yCoord];
              img2RGB = [self getRGBAsFromImage:newImage2 atX:xCoord andY:yCoord];

              if (([[img1RGB objectAtIndex:0]floatValue] - [[img2RGB objectAtIndex:0]floatValue]) == 0 || ([[img1RGB objectAtIndex:1]floatValue] - [[img2RGB objectAtIndex:1]floatValue]) == 0 || ([[img1RGB objectAtIndex:2]floatValue] - [[img2RGB objectAtIndex:2]floatValue]) == 0)
              {
                 //one or more pixel components differs by 10% or more
                 numDifferences++;
              }
           }
       }

    // It will show result in percentage at last
      CGFloat percentage_similar=((numDifferences*100)/totalCompares);
      NSString *str=NULL;

      if (percentage_similar>=10.0f)
      {
          str=[[NSString alloc]initWithString:[NSString stringWithFormat:@"%i%@ Identical", (int)((numDifferences*100)/totalCompares),@"%"]];

              UIAlertView *alertview=[[UIAlertView alloc]initWithTitle:@"i-App" message:[NSString stringWithFormat:@"%@ Images are same",str] delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
              [alertview show];

            break;
       }
      else
      {
          str=[[NSString alloc]initWithString:[NSString stringWithFormat:@"Result: %i%@ Identical",(int)((numDifferences*100)/totalCompares),@"%"]];

          UIAlertView *alertview=[[UIAlertView alloc]initWithTitle:@"i-App" message:[NSString stringWithFormat:@"%@ Images are not same",str] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
          [alertview show];
      }
  }

}
-(NSArray*)getRGBAsFromImage:(UIImage*)image atX:(int)xx andY:(int)yy
{
    //NSArray *result = [[NSArray alloc]init];
    // First get the image into your data buffer
    CGImageRef imageRef = [image CGImage];
    NSUInteger width = CGImageGetWidth(imageRef);
    NSUInteger height = CGImageGetHeight(imageRef);
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    unsigned char *rawData = (unsigned char*) calloc(height * width * 4, sizeof(unsigned char));
    NSUInteger bytesPerPixel = 4;
    NSUInteger bytesPerRow = bytesPerPixel * width;
    NSUInteger bitsPerComponent = 8;
    CGContextRef context = CGBitmapContextCreate(rawData, width, height,
                                              bitsPerComponent, bytesPerRow, colorSpace,
                                             kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
   CGColorSpaceRelease(colorSpace);

   CGContextDrawImage(context, CGRectMake(0, 0, width, height), imageRef);
   CGContextRelease(context);

   // Now your rawData contains the image data in the RGBA8888 pixel format.
   int byteIndex = (bytesPerRow * yy) + xx * bytesPerPixel;
   //    for (int ii = 0 ; ii < count ; ++ii)
  //    {
   CGFloat red   = (rawData[byteIndex]     * 1.0) / 255.0;
   CGFloat green = (rawData[byteIndex + 1] * 1.0) / 255.0;
   CGFloat blue  = (rawData[byteIndex + 2] * 1.0) / 255.0;
   //CGFloat alpha = (rawData[byteIndex + 3] * 1.0) / 255.0;
   byteIndex += 4;

   // UIColor *acolor = [UIColor colorWithRed:red green:green blue:blue alpha:alpha];

   //}
   free(rawData);

   NSArray *result = [NSArray arrayWithObjects:
                   [NSNumber numberWithFloat:red],
                   [NSNumber numberWithFloat:green],
                   [NSNumber numberWithFloat:blue],nil];

   return result;
}


text:
Q: Where to find acpi mailing list? Was this mailing list dead:  Acpi-devel -- Defunct ACPI Development Discussion List
What other source can I utilize , just want to find the developers of acpid

A: Searching GMANE (a mailing list archive service) seems helpful, it yields (among others) gmane.linux.acpi.devel, the Linux ACPI Development Discussion List.  While I'm not sure if it's where you'll find the developers of acpid, it is mentioned there, so it might be worth a try.
Edit Looking at Debian's packages for the homepage of some project is often helpful, too.

A: The manpage of acpid (http://linux.die.net/man/8/acpid) lists
 Tim Hockin <thockin@hockin.org>

as author.


text:
Q: Kubernetes Service Account Signing Key I am looking for private key being used to sign service account tokens in my cluster. Is there a way I can find path to this key or print it somehow?
Documentation says what flag is used to provide the key during startup but there is no info about current key in use.

A: You can check the path passed to –service-account-private-key-file parameter to the kube controller manager component. This is the key used by token controller to sign the service accounts.
–service-account-private-key-file string
Filename containing a PEM-encoded private RSA or ECDSA key used to sign service account tokens.

In a cluster installed by kubeadm I could check the path by describing the pod kube-controller-manager-kind-control-plane(the pod name could be different in different cluster) in kube-system namespace
kubectl describe pod kube-controller-manager-kind-control-plane -n kube-system
Name:                 kube-controller-manager-kind-control-plane
Namespace:            kube-system
Priority:             2000000000
Priority Class Name:  system-cluster-critical
Node:                 kind-control-plane/172.17.0.2
Start Time:           Tue, 14 Apr 2020 14:13:18 +0530
Labels:               component=kube-controller-manager
                      tier=control-plane
Annotations:          kubernetes.io/config.hash: 15e79e27a50d92dc481a5aaaad4399d8
                      kubernetes.io/config.mirror: 15e79e27a50d92dc481a5aaaad4399d8
                      kubernetes.io/config.seen: 2020-04-14T08:43:15.2951468Z
                      kubernetes.io/config.source: file
Status:               Running
IP:                   172.17.0.2
IPs:
  IP:           172.17.0.2
Controlled By:  Node/kind-control-plane
Containers:
  kube-controller-manager:
    Container ID:  containerd://6423f4d70cf0af2be708315b1aa5d4cb038d73b00b63f3d759db60e75f1ebf56
    Image:         k8s.gcr.io/kube-controller-manager:v1.17.0
    Image ID:      sha256:7818d75a7d002a3c1bb6e9d8fe4416e75ee7df87b57585ab4f8ef01ccba1ddaa
    Port:          <none>
    Host Port:     <none>
    Command:
      kube-controller-manager
      --allocate-node-cidrs=true
      --authentication-kubeconfig=/etc/kubernetes/controller-manager.conf
      --authorization-kubeconfig=/etc/kubernetes/controller-manager.conf
      --bind-address=127.0.0.1
      --client-ca-file=/etc/kubernetes/pki/ca.crt
      --cluster-cidr=10.244.0.0/16
      --cluster-signing-cert-file=/etc/kubernetes/pki/ca.crt
      --cluster-signing-key-file=/etc/kubernetes/pki/ca.key
      --controllers=*,bootstrapsigner,tokencleaner
      --enable-hostpath-provisioner=true
      --kubeconfig=/etc/kubernetes/controller-manager.conf
      --leader-elect=true
      --node-cidr-mask-size=24
      --requestheader-client-ca-file=/etc/kubernetes/pki/front-proxy-ca.crt
      --root-ca-file=/etc/kubernetes/pki/ca.crt
      --service-account-private-key-file=/etc/kubernetes/pki/sa.key
      --service-cluster-ip-range=10.96.0.0/12
      --use-service-account-credentials=true

As it can be seen above in a cluster installed by kubeadm the key file is located in master nodes at /etc/kubernetes/pki/sa.key location
Since you are on EKS managed cluster you will not have access to master nodes.


text:
Q: How to Change a C++ Class member's Type Is it possible to be able to assign a "flexible" type to a class member? This would be somewhat like std::variant or std::any, except std::variant requires types to be stated in advance and std::any requires any_cast<Type> (which isn't a problem, except for saving the type information so I'd know what type to cast the std::any member to).
What I'm looking for is something that makes the following functionality possible:
class FlexType
{
    ChangeableType m_Value;

public:
    FlexType(SomeType init_value)
        : m_Value(init_value)
    {}

    void setValue(SomeOtherType new_value) { m_Value = new_value; }
    CurrentType getValue() const { return m_Value; }
};

Edit
I need the functionality for storing a return type of an std::function, where I want to be able to change the std::function's return type to any given type. This comes from a class that has a virtual void run() const method (call it "ParentClass" for convenience). I then have a child class that overrides the run() method and runs an std::function and saves the return value in another class member.
It looks something like this:
class ParentClass
{ // Example basic parent class
private:
    /* ... Class members ... */

public:
    ParentClass() = default;

    virtual void run() const { /* Do stuff w/ class members */ }
};

template<class FuncRetTy, class... FuncArgs>
class ChildClass : public ParentClass
{
private:
    using function_return_type = FuncRetTy;
    using function_arg_types = FuncArgs...;
    using function_args_container = std::tuple<function_arg_types>;
    std::function<function_return_type(function_args_container)>

    mutable function_return_type m_StoredValue;
    function_type m_Function;
    func_args_container m_Args;

public:
    FunctionMenu(
        function_return_type type_var, // Used to deduce return type
        function_type function,
        function_arg_types arguments)
        : m_Function(function)
        , m_Args(std::make_tuple(std::forward<FuncArgs>(arguments)...))
    {}

    void run() const override
    {
        m_StoredValue = m_Function(m_Args);
    }

    [[nodiscard]] function_return_type getStoredValue() const
    {
        return m_StoredValue;
    }

    // This is where my problem is...
    // I want to be able to set m_Function to another function,
    // but this means the return type can change, and so can
    // the tuple template parameters for m_Args.
    // The below code is just pseudocode
    template<class NewFuncRetTy, class... NewFuncArgs>
    void setFunction(
        NewFuncRetTy type_var,
        std::function<NewFuncRetTy(std::tuple<NewFuncArgs...>)> function
        NewFuncArgs... args)
    {
        // Change all class typedef's to new types
        // Reassign m_Function = function
        // Reassign m_Args = make_tuple(std::forward<NewFuncArgs>(args)...);
        // Delete whatever value m_StoredValue already has and
        //     change type of m_StoredValue to NewFuncRetTy so
        //     getStoredValue() knows what type to return
    }
};

I'm sorry about there being a lot of code, but I figured explaining in detail what exactly I'm asking for would help people understand the question better.


text:
Q: How to access the params variable in helper specs I am writing some specs for helpers that check for values in the params variable. Until now I have been doing:
helper.stub!(:params).and_return(:user => {:username => "jack"})

The problem is that while the actual params Hash has string/symbol-agnostic keys and params[:user] == params["user"], my implementation does not and produces various failures where it should not.
Is there a way to set the proper (key-type agnostic) params variable in helper specs?

A: THe easiest way to do this is to use with_indifferent_access.
In your case :
helper.stub!(:params).and_return({:user => {:username => "jack"}}.with_indifferent_access)


text:
Q: make_pipeline()f TypeError: All intermediate steps should be transformers and implement fit and transform or be the string 'passthrough' I am trying to make a stacked classifier that uses count vectorization, gradient boosting and then Naive baised. However, I get a type error for my make_pipeline function.
from sklearn.pipeline import make_pipeline
from sklearn.ensemble import StackingClassifier

estimators = [make_pipeline(('vec', CountVectorizer(min_df=1, stop_words= 'english', ngram_range=(1,2))),
                            ('gbc', GradientBoostingClassifier(learning_rate = 0.25, max_features = 'sqrt', n_estimators = 500)))]

clf = StackingClassifier(estimators=estimators, final_estimator=MultinomialNB(alpha=0.1))
clf.fit(x_train, y_train)

This is the error I get:
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_10224/3708809530.py in <module>
      7 estimators = [
      8                 ('gbc', GradientBoostingClassifier(learning_rate = 0.25, max_features = 'sqrt', n_estimators = 500)),
----> 9                 make_pipeline('vec', TfidfVectorizer(stop_words = 'english', ngram_range = (1, 2)),
     10                 ('gbc', GradientBoostingClassifier(learning_rate = 0.25, max_features = 'sqrt', n_estimators = 500)))]
     11

~\anaconda3\envs\comp4331\lib\site-packages\sklearn\pipeline.py in make_pipeline(memory, verbose, *steps)
    868                     ('gaussiannb', GaussianNB())])
    869     """
--> 870     return Pipeline(_name_estimators(steps), memory=memory, verbose=verbose)
    871
    872

~\anaconda3\envs\comp4331\lib\site-packages\sklearn\pipeline.py in __init__(self, steps, memory, verbose)
    146         self.memory = memory
    147         self.verbose = verbose
--> 148         self._validate_steps()
    149
    150     def get_params(self, deep=True):

~\anaconda3\envs\comp4331\lib\site-packages\sklearn\pipeline.py in _validate_steps(self)
    205                 t, "transform"
    206             ):
--> 207                 raise TypeError(
    208                     "All intermediate steps should be "
    209                     "transformers and implement fit and transform "

TypeError: All intermediate steps should be transformers and implement fit and transform or be the string 'passthrough' 'vec' (type <class 'str'>) doesn't

A: make_pipeline does not accept names for its steps, and the steps need to be provided as a tuple.  Either:
estimators = [make_pipeline((
    CountVectorizer(min_df=1, stop_words= 'english', ngram_range=(1,2)),
    GradientBoostingClassifier(learning_rate = 0.25, max_features = 'sqrt', n_estimators = 500),
))]

(in which case the names of the steps will be "countvectorizer" and "gradientboostingclassifier")
or
estimators = [Pipeline([
    ('vec', CountVectorizer(min_df=1, stop_words='english', ngram_range=(1,2))),
    ('gbc', GradientBoostingClassifier(learning_rate=0.25, max_features='sqrt', n_estimators=500)),
])]


text:
Q: Asp.net Mvc Form & KendoView Grid Save Toghter I have 2 different Tables in sql server,  Table 1 is part of asp.net mvc form & second table is part of kendo grid,  How can I save both tables once through single Button.
 ****Table 1 is part of asp.net mvc form as following****

 @using (Html.BeginForm())
 {
 @Html.TextBoxFor(m => m.CustomerID)
 }

 ****Table 2 is part of Kendo Grid****
 @(Html.Kendo().Grid<Accounting.DAL.InvoiceDetail>()
 .Name("Grid")
 .Columns(columns =>
 {

  }
  )

A: I think you're new to MVC. In MVC, every view represents a model(Domain logic class).
@using model Applciaton.Models.SomeViewmodel

//This will create a form tag. you can mention your target controller action here.
@using (Html.BeginForm())

// Form tag with action and post attribute.
@using(Html.BeginForm('action','controller',FormMethod.Post,new {id="formID"}))
{
  //your tables and kendo grid should be inside this form tag so you can post them to server.
  <input type="submit" value="save"/> //This will submit the form to controller action
}

So when your view submits data to server(controller), you can recieve it with model.
 [HttpPost] // Post Attribute.
 public ActionResult action(SomeViewmodel obj)//Viewmodel object from view.
 {
     //you have your kendo grid data posted from view.

     // you also have other table data and all the data you specified in model will be here.

     //Save it to db from model. call the repository from here and pass relevent data.

 }


text:
Q: iPlymouth Broke GRUB I followed the steps in this thread:
What happens if I disable and unistall Plymouth?
Now GRUB is broken. I'm running Ubuntu 12.04.4 without a GUI and when my server boots now, I get a screen showing what services are starting and then it says:
umount: /proc/fs/nfsd: device is busy.

When I press the arrow keys, it alternates from this screen and the purple Ubuntu splash screen.


text:
Q: Edit uploaded file (djangos FileField) using pre_save signal I want to edit an uploaded file on byte level (i.e. searching and removing a certain byte sequence) before saving it.
I have a pre_save signal set up in the following way:
class Snippet(models.Model):
    name = models.CharField(max_length=256, unique=True)
    audio_file = models.FileField(upload_to=generate_file_name, blank=True, null=True)

@receiver(models.signals.pre_save, sender=Snippet)
def prepare_save(sender, instance, **kwargs):
    if instance.audio_file:
        remove_headers(instance)

Now I have had problems implementing the remove_headers function in a way that I can edit the file while it is still in memory and have it stored afterwards. I tried among others the following:
def remove_headers(instance):
    byte_sequence = b'bytestoremove'
    f = instance.audio_file.read()
    file_in_hex = f.hex()
    file_in_hex = re.sub(byte_sequence.hex(), '', file_in_hex)

    x = b''
    x = x.fromhex(file_in_hex)

    tmp_file = TemporaryFile()
    tmp_file.write(x)
    tmp_file.flush()
    tmp_file.seek(0)
    instance.audio_file.save(instance.audio_file.name, tmp_file, save=True)

This first of all would result in an infinite loop. But this can be mitigated by e.g. only calling the remove_headers method on create or so. It did however not work, the file was unchanged. I also tried replacing the last line with:
instance.audio_file = File(tmp_file, name=instance.audio_file.name)

This however resulted in an empty file to be written/saved.
Curiously when writing a test, this method seems to work:
def test_header_removed(self):
    snippet = mommy.make(Snippet)
    snippet.audio_file.save('newname.mp3', ContentFile('contentbytestoremovecontent'))
    snippet.save()
    self.assertEqual(snippet.audio_file.read(), b'contentcontent')

This test does not fail, despite the file being zero bytes in the end.
What am I missing here?

A: The second solution was almost correct. The reason the files ended up being empty (actually this only happened to bigger files) was, that sometimes you have to seek to the beginning of the file after opening it. So the beginngni of remove_headers needs to be changed:
def remove_headers(instance):
    byte_sequence = b'bytestoremove'
    instance.audio_file.seek(0)
    f = instance.audio_file.read()
    file_in_hex = f.hex()


text:
Q: SQL Server Transaction Log VLF access Is there any way to access, and examine the contents of, the VLFs (virtual log files) that make up sql server's transaction log?  I need this for a project to examine SQL Server's internal working.

A: No, the behaviour of the VLFs is internalized within SQL Server's engine and there are no interfaces that expose their functionality or properties.


text:
Q: MySQL Multiple Joins from 3 Tables I need to select all records from assets_tbl (A). Included with these records I need to have any lightboxes (lightbox_name) that are linked to the
asset_id from assets_tbl where author = "scott@co.com" OR authorized_viewers includes "scott@co.com"
I think this is close to what I need but it returns multiple rows of the same record:
SELECT
  A.*,
  C.lightbox_name,
  C.author,
  C.authorized_viewers
FROM
  media_tbl A
  LEFT JOIN lightbox_assets_tbl B ON A.asset_id = B.asset_id
  LEFT JOIN lightboxes_tbl C
    ON B.lightbox_id = C.id
    AND C.author = "scott@co.com"
  LEFT JOIN lightboxes_tbl D ON D.authorized_viewers LIKE "scott@co.com"
ORDER BY A.id DESC

Here are the tables:
lightboxes_tbl
+-----+----------------+---------------+---------------------+
|id   |lightbox_name   |author         |authoried_viewers    |
+-----+----------------+---------------+---------------------+
|100  | aircraft-types |scott@co.com   |jon@co.com,aj@co.com |
|101  | maintenance    |nicole@co.com  |jon@co.com           |
|102  | ramp           |nicole@co.com  |scott@co.com         |
+-----+----------------+---------------+---------------------+

lightbox_assets_tbl
+-----+-------------+-------------+---------------+----------+
|id   |lightbox_id  |asset_name   |asset_path     | asset_id |
+-----+-------------+-------------+---------------+----------+
|1    |100          |a321.jpg     |project1/imgs/ | 3700     |
|2    |100          |b757.jpg     |project1/imgs/ | 3444     |
|3    |101          |FlyBy.swf    |project4/imgs/ | 1444     |
|4    |102          |Door_757.swf |project5/imgs/ | 3701     |
+-----+-------------+-------------+---------------+----------+

assets_tbl
+-----+---------------------+-------------------------------------+
|asset_id   |asset_name           | asset_location                |
+-----------+---------------------+-------------------------------+
|3700       |a321.jpg             |Libraries\Library_Media\Images |
|200        |757_Taxi.swf         |Libraries\Library_Media\Images |
|3444       |b757.jpg             |Libraries\Library_Media\Images |
|1444       |FlyBy.swf            |Libraries\Library_Media\Images |
|3701       |Door_757.swf         |Libraries\Library_Media\Images |
+----------+---------------------+--------------------------------+

Here are the expected RESULTS of the query:
+-----------+---------------------+-------------------------------+------------------+-------------+------------------------+
|asset_id   |asset_name           | asset_location                |lightbox_name     | author      | authorized_viewers     |
+-----------+---------------------+-------------------------------+------------------+-------------+------------------------+
|3700       |a321.jpg             |Libraries\Library_Media\Images |aircraft-types    |scott@co.com |jon@co.com,aj@co.com    |
+-----------+---------------------+-------------------------------+------------------+-------------+------------------------+
|200        |757_Taxi.swf         |Libraries\Library_Media\Images |NULL              |NULL         |NULL                    |
+-----------+---------------------+-------------------------------+------------------+-------------+------------------------+
|3444       |b757.jpg             |Libraries\Library_Media\Images |aircraft-types    |scott@co.com |jon@co.com,aj@co.com    |
+-----------+---------------------+-------------------------------+------------------+-------------+------------------------+
|1444       |FlyBy.swf            |Libraries\Library_Media\Images |NULL              |NULL         |NULL                    |
+-----------+---------------------+-------------------------------+------------------+-------------+------------------------+
|3701       |Door_757.swf         |Libraries\Library_Media\Images |ramp              |nicole@co.com|scott@co.com            |
+----------+---------------------+--------------------------------+------------------+-------------+------------------------+

SQL Fiddle
Thanks!

A: I'm wondering why you need two joins to the lightboxes_tbl table. It seems like the second reference to that table (alias D) is unnecessary. Seems like you could just use an OR.
As a demonstration, replicating the predicates in your query:
LEFT JOIN lightboxes_tbl C
       ON B.lightbox_id = C.id
      AND ( C.author = 'scott@co.com'
          OR C.authorized_viewers = 'scott@co.com'
          )

But given that authorized_user contains a comma separated list (ACCKKK!!!), I suspect you really want to look for an exact match to an item in the comma separated list.  The LIKE comparison that currently have is equivalent to an equals comparison (to the entire contents of authorized_viewers column). You could add '%' wildcard characters to search for the value as part of the string...
But that approach is will also match strings containing e.g. ebscott@co.com, which may not be what you really want.
You could use the FIND_IN_SET function to find an exact match within the comma separated list...
LEFT JOIN lightboxes_tbl C
       ON B.lightbox_id = C.id
      AND ( C.author = 'scott@co.com'
          OR FIND_IN_SET('scott@co.com',C.authorized_viewers)
          )

Storing comma separated lists is a SQL anti-pattern. I recommend Bill Karwin's book: SQL Anti-Patterns: Avoiding the Pitfalls of Database Programming
http://www.amazon.com/SQL-Antipatterns-Programming-Pragmatic-Programmers/dp/1934356557