问:
How to identify particular descendant element found under first-or-second descendant of another element
Please suggest to identify the MFENCED, which is having MFRAC as descendant of MSUB or not.

Here some scenarios mentioned as below to stretch the MFENCED (inserting one attribute):

If MFRAC found and which is not under MSUB, then attribute STRETCH

required for MFENCED.

If MFRAC found as descendant to MFENCED and
under FIRST-CHILD-DESCENDANT of MSUB, then STRETCH required.

In third MATH from input xml, 2nd MFENCED required STRETCH, even that MFRAC descendant of 2nd child descendant of MSUB, but with within that MFENCED, MFRAC is not having MSUB as its ancestor.

Newly added further explanations:

If MFENCED under (descendant from (this) present MFENCED) any MFRAC found, then that MFENCED can stretch, where MFENCE/ancestor should not, because, with respect to main MFENCE, FRAC found under subs 2nd child-descendant. If not clear, i will give further explanations.

Input XML:

```<code><article>

<math>
    <mrow>
        <mfenced open="(" close=")">
            <!--stretch required -->
            <mrow>
                <mrow><mn>99999</mn></mrow>
                    <mrow>
                            <mrow><mn>9999</mn></mrow>
                            <mrow>
                                <mfenced open="(" close=")">
                                    <!--stretch required -->
                                    <mrow>
                                        <mfrac><mi>a</mi><mi>b</mi></mfrac>
                                    </mrow>
                                </mfenced>
                            </mrow>
                    </mrow>
                </mrow>
        </mfenced>
    </mrow>
</math>

<math>
    <mrow>
        <mfenced open="(" close=")"><!--Stretch  required, bcs descendant Frac, found as first child of msub, if descendant mfrac, found under (descendant) second child of MSUB, then no need to stretch-->
            <mrow>
                <mrow><mn>99999</mn></mrow>
                    <mrow>
                        <msub>
                            <mrow>
                                <mfenced open="(" close=")"><!--Stretch required, because under this mfen, 'mfrac' found under first child of 'msub' -->
                                    <mrow>
                                        <mfrac><mi>a</mi><mi>b</mi></mfrac>
                                    </mrow>
                                </mfenced>
                            </mrow>
                            <mrow><mn>9999</mn></mrow>
                        </msub>
                    </mrow>
                </mrow>
        </mfenced>
    </mrow>
</math>

<math>
    <mrow>
        <mfenced open="(" close=")"><!-- this mfence, no need to stretch, because, descendant MFRAC found under second child-descendant of MSUB -->
            <mrow>
                <mrow><mn>99999</mn></mrow>
                    <mrow>
                        <msub>
                            <mrow><mn>9999</mn></mrow>
                            <mrow>
                                <mfenced open="(" close=")"><!--Stretch required, because under this mfen, 'mfrac' found (even MFRAC under 2nd child-descendant of MSUB, but under existing MFENCE, MFRAC is not having ancestor MSUB -->
                                    <mrow>
                                        <mfrac><mi>a</mi><mi>b</mi></mfrac>
                                    </mrow>
                                </mfenced>
                            </mrow>
                        </msub>
                    </mrow>
                </mrow>
        </mfenced>
    </mrow>
</math>
</article>
</code>```

XSLT 2.0:

```<code><xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output indent="yes"/>
<xsl:strip-space elements="*"/>

<xsl:template match="@*|node()">
    <xsl:copy><xsl:apply-templates select="@*|node()"/></xsl:copy>
</xsl:template>

<xsl:template match="mfenced">
    <xsl:variable name="varFrac">
        <xsl:for-each select="descendant::mfenced">
            <xsl:for-each select="descendant::*[name()='mfrac']">
                <xsl:choose>
                    <xsl:when  test="not(ancestor::*[matches(name(), '^(msubsup|msub|msup|munder|munderover|mover|msqrt|mroot)$')]
                        [generate-id(ancestor::mmlmfenced[1])=generate-id(current()/ancestor::mmlmfenced[1])])">Yes2</xsl:when>
                    <xsl:when  test="(ancestor-or-self::*/parent::*[not(preceding-sibling::*)]/parent::*[matches(name(), '^(msubsup|msub|msup|munder|munderover|mover|msqrt|mroot)$')]
                        [generate-id(ancestor::mmlmfenced[1])=generate-id(current()/ancestor::mmlmfenced[1])])">Yes21</xsl:when>
                </xsl:choose>
            </xsl:for-each>
        </xsl:for-each>

        <xsl:for-each select="descendant::*[name()='mfrac']">
            <xsl:choose>
                <xsl:when  test="not(ancestor::*[matches(name(), '^(msubsup|msub|msup|munder|munderover|mover|msqrt|mroot)$')])">Yes1a</xsl:when>
                <xsl:when  test="(ancestor-or-self::*/parent::*[not(preceding-sibling::*)]/parent::*[matches(name(), '^(msubsup|msub|msup|munder|munderover|mover|msqrt|mroot)$')])">Yes11a</xsl:when>
            </xsl:choose>
        </xsl:for-each>
    </xsl:variable>

        <xsl:choose>
            <xsl:when test="contains($varFrac, 'Yes')">
                <xsl:copy>
                    <xsl:apply-templates select="@*"/>
                    <xsl:attribute name="stretchy">true</xsl:attribute>
                    <xsl:apply-templates select="node()"/>
                </xsl:copy>
            </xsl:when>
            <xsl:otherwise>
                <xsl:copy><xsl:apply-templates select="@*|node()"/></xsl:copy>
            </xsl:otherwise>
        </xsl:choose>
</xsl:template>

</xsl:stylesheet>
</code>```

Required result:

```<code><article>
<math>
  <mrow>
     <mfenced open="(" close=")" stretchy="true">
          <mrow>
           <mrow>
              <mn>99999</mn>
           </mrow>
           <mrow>
              <mrow>
                 <mn>9999</mn>
              </mrow>
              <mrow>
                 <mfenced open="(" close=")" stretchy="true">
                    <mrow>
                       <mfrac>
                          <mi>a</mi>
                          <mi>b</mi>
                       </mfrac>
                    </mrow>
                 </mfenced>
              </mrow>
           </mrow>
        </mrow>
     </mfenced>
  </mrow>
</math>

<math>
  <mrow>
     <mfenced open="(" close=")" stretchy="true">
        <mrow>
           <mrow>
              <mn>99999</mn>
           </mrow>
           <mrow>
              <msub>
                 <mrow>
                    <mfenced open="(" close=")" stretchy="true">
                        <mrow>
                          <mfrac>
                             <mi>a</mi>
                             <mi>b</mi>
                          </mfrac>
                       </mrow>
                    </mfenced>
                 </mrow>
                 <mrow>
                    <mn>9999</mn>
                 </mrow>
              </msub>
           </mrow>
        </mrow>
     </mfenced>
  </mrow>
</math>

<math>
  <mrow>
     <mfenced open="(" close=")">
        <mrow>
           <mrow>
              <mn>99999</mn>
           </mrow>
           <mrow>
              <msub>
                 <mrow>
                    <mn>9999</mn>
                 </mrow>
                 <mrow>
                    <mfenced open="(" close=")" stretchy="true"><!-- Here stretch required -->
                        <mrow>
                          <mfrac>
                             <mi>a</mi>
                             <mi>b</mi>
                          </mfrac>
                       </mrow>
                    </mfenced>
                 </mrow>
              </msub>
           </mrow>
        </mrow>
     </mfenced>
  </mrow>
</math>
</article>
</code>```

答:
New XSLT:

```<code><xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output indent="yes"/>
<xsl:strip-space elements="*"/>

<xsl:template match="@*|node()">
    <xsl:copy><xsl:apply-templates select="@*|node()"/></xsl:copy>
</xsl:template>

<xsl:template match="mfenced">

    <xsl:variable name="varFrac">
        <xsl:choose><!--to check only within MFENCED descendant is MFRAC -->
            <xsl:when test="descendant-or-self::*[matches(name(), '^(msubsup|msub|msup|munder|munderover|mover|msqrt|mroot)$')]/*[not(preceding-sibling::*)]/descendant::mfrac">Yes1</xsl:when>
            <xsl:when test="descendant-or-self::*[matches(name(), '^(msubsup|msub|msup|munder|munderover|mover|msqrt|mroot)$')]/*[(preceding-sibling::*)]/descendant::mfrac">No1</xsl:when>
            <xsl:when test="descendant-or-self::mfrac">Yes2</xsl:when>
        </xsl:choose>
        <!-- to check MFRAC found as online (first child-descendant of msub). -->
        <xsl:for-each select="descendant::*[name()='mfrac']">
            <xsl:choose>
                <xsl:when  test="not(ancestor::*[matches(name(), '^(msubsup|msub|msup|munder|munderover|mover|msqrt|mroot)$')])">Yes1a</xsl:when>
                <xsl:when  test="(ancestor-or-self::*/parent::*[not(preceding-sibling::*)]/parent::*[matches(name(), '^(msubsup|msub|msup|munder|munderover|mover|msqrt|mroot)$')])">Yes11a</xsl:when>
            </xsl:choose>
        </xsl:for-each>
    </xsl:variable>

    <xsl:choose>
        <xsl:when test="contains($varFrac, 'Yes')">
            <xsl:copy>
                <xsl:apply-templates select="@*"/>
                <xsl:attribute name="stretchy">true</xsl:attribute>
                <xsl:apply-templates select="node()"/>
            </xsl:copy>
        </xsl:when>
        <xsl:otherwise>
            <xsl:copy><xsl:apply-templates select="@*|node()"/></xsl:copy>
        </xsl:otherwise>
    </xsl:choose>
</xsl:template>
</xsl:stylesheet>
</code>```

Body:
Please suggest to identify the MFENCED, which is having MFRAC as descendant of MSUB or not.

Here some scenarios mentioned as below to stretch the MFENCED (inserting one attribute):

If MFRAC found and which is not under MSUB, then attribute STRETCH

required for MFENCED.

If MFRAC found as descendant to MFENCED and
under FIRST-CHILD-DESCENDANT of MSUB, then STRETCH required.

In third MATH from input xml, 2nd MFENCED required STRETCH, even that MFRAC descendant of 2nd child descendant of MSUB, but with within that MFENCED, MFRAC is not having MSUB as its ancestor.

Newly added further explanations:

If MFENCED under (descendant from (this) present MFENCED) any MFRAC found, then that MFENCED can stretch, where MFENCE/ancestor should not, because, with respect to main MFENCE, FRAC found under subs 2nd child-descendant. If not clear, i will give further explanations.

Input XML:

<math>
    <mrow>
        <mfenced open="(" close=")">

            <mrow>
                <mrow><mn>99999</mn></mrow>
                    <mrow>
                            <mrow><mn>9999</mn></mrow>
                            <mrow>
                                <mfenced open="(" close=")">

                                    <mrow>
                                        <mfrac><mi>a</mi><mi>b</mi></mfrac>
                                    </mrow>
                                </mfenced>
                            </mrow>
                    </mrow>
                </mrow>
        </mfenced>
    </mrow>
</math>

<math>
    <mrow>
        <mfenced open="(" close=")">
            <mrow>
                <mrow><mn>99999</mn></mrow>
                    <mrow>
                        <msub>
                            <mrow>
                                <mfenced open="(" close=")">
                                    <mrow>
                                        <mfrac><mi>a</mi><mi>b</mi></mfrac>
                                    </mrow>
                                </mfenced>
                            </mrow>
                            <mrow><mn>9999</mn></mrow>
                        </msub>
                    </mrow>
                </mrow>
        </mfenced>
    </mrow>
</math>

<math>
    <mrow>
        <mfenced open="(" close=")">
            <mrow>
                <mrow><mn>99999</mn></mrow>
                    <mrow>
                        <msub>
                            <mrow><mn>9999</mn></mrow>
                            <mrow>
                                <mfenced open="(" close=")">
                                    <mrow>
                                        <mfrac><mi>a</mi><mi>b</mi></mfrac>
                                    </mrow>
                                </mfenced>
                            </mrow>
                        </msub>
                    </mrow>
                </mrow>
        </mfenced>
    </mrow>
</math>

XSLT 2.0:

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output indent="yes"/>
<xsl:strip-space elements="*"/>

<xsl:template match="@*|node()">
    <xsl:copy><xsl:apply-templates select="@*|node()"/></xsl:copy>
</xsl:template>

<xsl:template match="mfenced">
    <xsl:variable name="varFrac">
        <xsl:for-each select="descendant::mfenced">
            <xsl:for-each select="descendant::*[name()='mfrac']">
                <xsl:choose>
                    <xsl:when  test="not(ancestor::*[matches(name(), '^(msubsup|msub|msup|munder|munderover|mover|msqrt|mroot)$')]
                        [generate-id(ancestor::mmlmfenced[1])=generate-id(current()/ancestor::mmlmfenced[1])])">Yes2</xsl:when>
                    <xsl:when  test="(ancestor-or-self::*/parent::*[not(preceding-sibling::*)]/parent::*[matches(name(), '^(msubsup|msub|msup|munder|munderover|mover|msqrt|mroot)$')]
                        [generate-id(ancestor::mmlmfenced[1])=generate-id(current()/ancestor::mmlmfenced[1])])">Yes21</xsl:when>
                </xsl:choose>
            </xsl:for-each>
        </xsl:for-each>

        <xsl:for-each select="descendant::*[name()='mfrac']">
            <xsl:choose>
                <xsl:when  test="not(ancestor::*[matches(name(), '^(msubsup|msub|msup|munder|munderover|mover|msqrt|mroot)$')])">Yes1a</xsl:when>
                <xsl:when  test="(ancestor-or-self::*/parent::*[not(preceding-sibling::*)]/parent::*[matches(name(), '^(msubsup|msub|msup|munder|munderover|mover|msqrt|mroot)$')])">Yes11a</xsl:when>
            </xsl:choose>
        </xsl:for-each>
    </xsl:variable>

        <xsl:choose>
            <xsl:when test="contains($varFrac, 'Yes')">
                <xsl:copy>
                    <xsl:apply-templates select="@*"/>
                    <xsl:attribute name="stretchy">true</xsl:attribute>
                    <xsl:apply-templates select="node()"/>
                </xsl:copy>
            </xsl:when>
            <xsl:otherwise>
                <xsl:copy><xsl:apply-templates select="@*|node()"/></xsl:copy>
            </xsl:otherwise>
        </xsl:choose>
</xsl:template>

</xsl:stylesheet>

Required result:

<math>
  <mrow>
     <mfenced open="(" close=")" stretchy="true">
          <mrow>
           <mrow>
              <mn>99999</mn>
           </mrow>
           <mrow>
              <mrow>
                 <mn>9999</mn>
              </mrow>
              <mrow>
                 <mfenced open="(" close=")" stretchy="true">
                    <mrow>
                       <mfrac>
                          <mi>a</mi>
                          <mi>b</mi>
                       </mfrac>
                    </mrow>
                 </mfenced>
              </mrow>
           </mrow>
        </mrow>
     </mfenced>
  </mrow>
</math>

<math>
  <mrow>
     <mfenced open="(" close=")" stretchy="true">
        <mrow>
           <mrow>
              <mn>99999</mn>
           </mrow>
           <mrow>
              <msub>
                 <mrow>
                    <mfenced open="(" close=")" stretchy="true">
                        <mrow>
                          <mfrac>
                             <mi>a</mi>
                             <mi>b</mi>
                          </mfrac>
                       </mrow>
                    </mfenced>
                 </mrow>
                 <mrow>
                    <mn>9999</mn>
                 </mrow>
              </msub>
           </mrow>
        </mrow>
     </mfenced>
  </mrow>
</math>

<math>
  <mrow>
     <mfenced open="(" close=")">
        <mrow>
           <mrow>
              <mn>99999</mn>
           </mrow>
           <mrow>
              <msub>
                 <mrow>
                    <mn>9999</mn>
                 </mrow>
                 <mrow>
                    <mfenced open="(" close=")" stretchy="true">
                        <mrow>
                          <mfrac>
                             <mi>a</mi>
                             <mi>b</mi>
                          </mfrac>
                       </mrow>
                    </mfenced>
                 </mrow>
              </msub>
           </mrow>
        </mrow>
     </mfenced>
  </mrow>
</math>

Body:
New XSLT:

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output indent="yes"/>
<xsl:strip-space elements="*"/>

<xsl:template match="@*|node()">
    <xsl:copy><xsl:apply-templates select="@*|node()"/></xsl:copy>
</xsl:template>

<xsl:template match="mfenced">

    <xsl:variable name="varFrac">
        <xsl:choose><!--to check only within MFENCED descendant is MFRAC -->
            <xsl:when test="descendant-or-self::*[matches(name(), '^(msubsup|msub|msup|munder|munderover|mover|msqrt|mroot)$')]/*[not(preceding-sibling::*)]/descendant::mfrac">Yes1</xsl:when>
            <xsl:when test="descendant-or-self::*[matches(name(), '^(msubsup|msub|msup|munder|munderover|mover|msqrt|mroot)$')]/*[(preceding-sibling::*)]/descendant::mfrac">No1</xsl:when>
            <xsl:when test="descendant-or-self::mfrac">Yes2</xsl:when>
        </xsl:choose>
        <!-- to check MFRAC found as online (first child-descendant of msub). -->
        <xsl:for-each select="descendant::*[name()='mfrac']">
            <xsl:choose>
                <xsl:when  test="not(ancestor::*[matches(name(), '^(msubsup|msub|msup|munder|munderover|mover|msqrt|mroot)$')])">Yes1a</xsl:when>
                <xsl:when  test="(ancestor-or-self::*/parent::*[not(preceding-sibling::*)]/parent::*[matches(name(), '^(msubsup|msub|msup|munder|munderover|mover|msqrt|mroot)$')])">Yes11a</xsl:when>
            </xsl:choose>
        </xsl:for-each>
    </xsl:variable>

    <xsl:choose>
        <xsl:when test="contains($varFrac, 'Yes')">
            <xsl:copy>
                <xsl:apply-templates select="@*"/>
                <xsl:attribute name="stretchy">true</xsl:attribute>
                <xsl:apply-templates select="node()"/>
            </xsl:copy>
        </xsl:when>
        <xsl:otherwise>
            <xsl:copy><xsl:apply-templates select="@*|node()"/></xsl:copy>
        </xsl:otherwise>
    </xsl:choose>
</xsl:template>
</xsl:stylesheet>


来源: stackexchange

问:
Running appium programatically in mac terminal using Java
I want to start appium server programatically in mac using Java.

Can any one help me how to write the code to start appium.

Thanks..

答:
You can launch appium server programmatically with below piece of code.

```<code>appium = AppiumDriverLocalService.buildService(new AppiumServiceBuilder()
            .withAppiumJS(new File("/usr/local/lib/node_modules/appium/build/lib/main.js"))
            .usingPort(4723).withIPAddress("127.0.0.1"));
appium.start();
</code>```

If you want to launch from terminal you can run below command

```<code>/Applications/Appium.app/Contents/Resources/node/bin/node /Applications/Appium.app/Contents/Resources/node_modules/appium/bin/appium.js
</code>```

If you want to specify the simulator and app details etc you can run below command.

```<code>node /Applications/Appium.app/Contents/Resources/node_modules/appium/bin/appium.js --address 127.0.0.1 --port 4723 --full-reset
--device-name "iPhone 6"
--platform-name iOS
--platform-version "8.3"
--app "/My.app"
--browser-name iOS
</code>```

For this the node executable should be added to the path.

For starting appium 1.5.3 go through below link.

starting appium 1.5.3 programmatically

ContentLicense: CC BY-SA 3.0

Body:
You can launch appium server programmatically with below piece of code.

appium = AppiumDriverLocalService.buildService(new AppiumServiceBuilder()
            .withAppiumJS(new File("/usr/local/lib/node_modules/appium/build/lib/main.js"))
            .usingPort(4723).withIPAddress("127.0.0.1"));
appium.start();

If you want to launch from terminal you can run below command

/Applications/Appium.app/Contents/Resources/node/bin/node /Applications/Appium.app/Contents/Resources/node_modules/appium/bin/appium.js

If you want to specify the simulator and app details etc you can run below command.

node /Applications/Appium.app/Contents/Resources/node_modules/appium/bin/appium.js --address 127.0.0.1 --port 4723 --full-reset
--device-name "iPhone 6"
--platform-name iOS
--platform-version "8.3"
--app "/My.app"
--browser-name iOS

For this the node executable should be added to the path.

For starting appium 1.5.3 go through below link.

starting appium 1.5.3 programmatically


问:
How to run a query asynchronously from MySQL Workbench
Say you have a query you want to run on your database, but you know that query is going to take a long time to complete, and you don't have direct access to the machine where MySQL is running, or to some other endpoint which has a stable connection with that machine. What do you do?</p>

答:
Well, you create a one time event that performs the necessary query.

Something like this:

```<code>CREATE EVENT <event_name>
ON SCHEDULE
AT CURRENT_TIMESTAMP + INTERVAL 10 SECOND
ENABLE DO
BEGIN
    -- log the event started
    INSERT INTO EventLogs (`Name`, `Start`, `Query`)
    VALUES (<event_name>, CURRENT_TIMESTAMP, <query_string>);
    -- run the query
    ....
    ...    <query>
    ....
    -- log the event done
    UPDATE EventLogs
    SET `Done` = CURRENT_TIMESTAMP
    WHERE `Name` = <event_name>;
END
</code>```

The above template can handle any arbitrary query.

Body:
Well, you create a one time event that performs the necessary query.

Something like this:

CREATE EVENT <event_name>
ON SCHEDULE
AT CURRENT_TIMESTAMP + INTERVAL 10 SECOND
ENABLE DO
BEGIN
    -- log the event started
    INSERT INTO EventLogs (`Name`, `Start`, `Query`)
    VALUES (<event_name>, CURRENT_TIMESTAMP, <query_string>);
    -- run the query
    ....
    ...    <query>
    ....
    -- log the event done
    UPDATE EventLogs
    SET `Done` = CURRENT_TIMESTAMP
    WHERE `Name` = <event_name>;
END

The above template can handle any arbitrary query.


问:
discretization in R with arules package
I am using arules package to discretize my continuous variables in data frame.
I am using this particular line

discretize(data1,categories = 3)

but its giving me an error

Error in cut.default(x,k2) : k2 must be numeric

I am just trying to convert my continuous variables from "data1" data frame to 3 bins discrete variables.
Any help would be appreciated...thanks in advance

答:
This worked for me to discretize all columns:</p>

```<code>data1.Disc <- as.data.frame(lapply(data1,
                                   function(x) discretize(x, categories=5)
                                   )
                           )
</code>```

Title: discretization in R with arules package

Body:
This worked for me to discretize all columns:

data1.Disc <- as.data.frame(lapply(data1,
                                   function(x) discretize(x, categories=5)
                                   )
                           )

ContentLicense: CC BY-SA 4.0


问:
Selenium | Java | Can anyone suggest how to select this element?
Need help to select an element that has the following attributes</p>

```<code><a href="" tabindex="-1" ng-bind-html="match.label uibTypeaheadHighlight:query" class="ng-binding ng-scope"><strong>Lantus</strong> 100 iu (Insulin)</a>
</code>```

答:
WebElement link = driver.findElement(By.xpath("//a[@class='ng-binding ng-scope']"));
// do whatever you need with the link

Body:
Need help to select an element that has the following attributes

Lantus 100 iu (Insulin)


问:
Any way for executing code to know it's running in the eclipse debugger?
I have some Pax Exam tests.  To execute the test normally, I just run the JUnit class in Eclipse.  If I want to step through the code in the Eclipse debugger, I have to make it set the debug options, including the flag to make it wait for the debugger connection, which is a separate process I have to run.  I'm presently having this code check for a "debug" system property to enable this, but that's sort of annoying.

It would be really nice if the @Configuration method can look at a system property or some other condition that will always be true if the code is executing in the debugger, so I could use that as a trigger to enable those flags, instead of a manually set "debug" system property.

I've already tried setting a breakpoint at the top of this method and inspecting all the system properties for something that might be set while in the debugger, but I didn't see anything.

Update:

Just to be clear, I need to point out some details about how Pax Exam tests work, to better explain why I'm looking for a way to improve this process.  When the test runs, it forks a Karaf container to run the test in.  In order to run a test in the debugger, you have to force the code that runs in the container to set the "suspend=y" flag, which will wait for a debugger connection.  You definitely don't want to do that if you're not debugging.

After starting the pax exam test running, you then have to run another debug configuration, to make a remote connection to the karaf container.  Technically, the run configuration for the unit test itself doesn't need to be a debug configuration.

So, the easiest way to make this happen is to have the the code that initiates the container check for a "debug" system property (or whatever you want to call it), and when that is set, to set the debugger port and the "suspend=y" flag.  If the property is not set, it doesn't do that.

So, if you're running the test without debug, you have to make sure that system property is not set.  If you're debugging, you have to make sure it's set.  It's an annoyance to have to edit the run configuration each time you need to go back and forth.

So, what I was intending was to start the unit test run configuration as a debug configuration (even though it doesn't need to be), and for the code that starts the karaf container to detect that it's being run as a debug configuration, and set the "suspend=y" flag in that case.

I've concluded that there is no way for the code itself to detect this, but I'll detail in my own answer how I get the debugger to help me a bit.

答:
If you are debugging eclipse application there is a way, you can use Platform.isDebug() to check whether your application is using debug or run lanuch configuration.

In your case i.e checking in Junit test run, I am not aware of how to detect whether we are using run/debug launch config. But strongly believe that there must a way to find it out with code like what you suggested using System Class.

Why can't you pass your own argument/environment variable in Junit debug launch config(With -D= in Arguments tab or in Environment tab? and use it in the test code to detect?


问:
How to get time difference in hours between two dates (Django)
I am trying to subtract two dates stored in a database to get difference in hours.
However these values are in query sets, so I am unable to subtract them.

For example:

```<code>date1 = table.objects.values_list('field1').filter(id=1))
date2 = table.objects.values_list('field1').filter(id=2))
timediff = date1-date2
</code>```

How to do this?

答:
To get time difference, use strptime method from datetime.

```<code>FMT = '%H:%M:%S'
timedelta = datetime.strptime(table.objects.values_list('field1', flat=True).filter(id=1))[0], FMT) - datetime.strptime(table.objects.values_list('field1', flat=True).filter(id=2))[0], FMT)
</code>```

it will return a timedelta

Body:
I am trying to subtract two dates stored in a database to get difference in hours.
However these values are in query sets, so I am unable to subtract them.

For example:

date1 = table.objects.values_list('field1').filter(id=1))
date2 = table.objects.values_list('field1').filter(id=2))
timediff = date1-date2

How to do this?

Body:
To get time difference, use strptime method from datetime.

FMT = '%H:%M:%S'
timedelta = datetime.strptime(table.objects.values_list('field1', flat=True).filter(id=1))[0], FMT) - datetime.strptime(table.objects.values_list('field1', flat=True).filter(id=2))[0], FMT)

it will return a timedelta


Title: SQL query to compare time difference

Body:
I've used the code below to query and got the output shown. Now, I would like to query as describe below. How should I do it?

Find code 2, check if code 1 comes after code 2 within the same ItemID. If yes, compare the time difference. If time difference is less than 10 seconds, display the two compared rows.

    SELECT [Date]
      ,[Code]
      ,[ItemId]
      ,[ItemName]
  FROM [dbo].[Log] as t
join Item as d
on t.ItemId = d.Id
  where ([Code] = 2 or [Code] = 1) and ([ItemId] > 97 and [ItemId] < 100)
  order by [ItemId], [Date]

Output from the above query

         Date           Code  ItemName  ItemID
2017-01-06 11:00:49.000  2       B      98
2017-01-06 11:00:49.000  1       A      98
2017-01-06 11:00:55.000  2       B      98
2017-01-06 12:01:56.000  1       A      98
2017-01-06 12:02:37.000  2       B      98
2017-01-06 12:03:49.000  1       A      98
2017-01-06 12:05:44.000  2       B      98
2017-01-06 20:24:32.000  1       A      98
2017-01-06 20:24:55.000  2       B      98
2017-03-14 16:37:42.000  2       B      99
2017-03-14 17:40:24.000  1       A      99
2017-03-14 17:40:25.000  2       B      99
2017-03-14 21:28:46.000  1       A      99
2017-03-15 08:03:07.000  2       B      99
2017-03-15 10:43:00.000  1       A      99
2017-03-15 12:01:17.000  2       B      99
2017-03-15 14:18:19.000  2       B      99

Expected Result

         Date           Code  ItemName  ItemID
2017-01-06 11:00:49.000  2       B      98
2017-01-06 11:00:49.000  1       A      98

Body:
create table results ([Date] datetime, Code int, ItemName char(1), ItemID int);
insert into results values
('2017-01-06 11:00:49',  2,       'B',      98),
('2017-01-06 11:00:49',  1,       'A',      98),
('2017-01-06 11:00:55',  2,       'B',      98),
('2017-01-06 12:01:56',  1,       'A',      98),
('2017-01-06 12:01:58',  1,       'A',      98),
('2017-01-06 12:02:37',  2,       'B',      98),
('2017-01-06 12:03:49',  1,       'A',      98),
('2017-01-06 12:05:44',  2,       'B',      98),
('2017-01-06 20:24:32',  1,       'A',      98),
('2017-01-06 20:24:55',  2,       'B',      98),
('2017-03-07 00:02:27',  1,       'A',      91),
('2017-03-07 00:02:27',  1,       'A',      58),
('2017-03-14 16:37:42',  2,       'B',      99),
('2017-03-14 17:40:24',  1,       'A',      99),
('2017-03-14 17:40:38',  2,       'B',      99),
('2017-03-14 21:28:46',  1,       'A',      99),
('2017-03-15 08:03:07',  2,       'B',      99),
('2017-03-15 10:43:00',  1,       'A',      99),
('2017-03-15 12:01:17',  2,       'B',      99),
('2017-03-15 14:18:19',  1,       'A',      99);

--= set a reset point when ItemId changes, or there is no correlative (2,1) couples
--= keep in mind this solution assumes that first Code must be 2
--
WITH SetReset AS
(
    SELECT [Date], Code, ItemName, ItemId,
           CASE WHEN LAG([ItemId]) OVER (PARTITION BY ItemId ORDER BY [Date]) IS NULL
                     OR ([Code] = 2)
                     OR ([Code] = COALESCE(LAG([Code]) OVER (PARTITION BY ItemId ORDER BY [Date]), [Code]))
                THEN 1 END is_reset
    FROM   results

)
--
--= set groups according to reset points
--
, SetGroup AS
   (
        SELECT [Date], Code, ItemName, ItemId,
               COUNT(is_reset) OVER (ORDER BY [ItemId], [Date]) grp
        FROM   SetReset
    )
    --
    --= calcs diff date for each group
    , CalcSeconds AS
    (
        SELECT [Date], Code, ItemName, ItemId,
               DATEDIFF(SECOND, MIN([Date]) OVER (PARTITION BY grp), MAX([Date]) OVER (PARTITION BY grp)) dif_sec,
               COUNT(*) OVER (PARTITION BY grp) num_items
        FROM   SetGroup
    )
    --
    --= selects those rows with 2 items by group and date diff less than 10 sec
    SELECT [Date], Code, ItemName, ItemId
    FROM   CalcSeconds
    WHERE  dif_sec < 10
    AND    num_items = 2
;
GO

Date                | Code | ItemName | ItemId
:------------------ | ---: | :------- | -----:
06/01/2017 11:00:49 |    2 | B        |     98
06/01/2017 11:00:49 |    1 | A        |     98

Warning: Null value is eliminated by an aggregate or other SET operation.

dbfiddle here


问:
Xcode 8 shows error that provisioning profile doesn't include signing certificate
Xcode 8 shows error that provisioning profile doesn't include signing certificate.

This issue is with Xcode-8 only with Xcode 7, same provisioning profile showing related identified certificate.

答:
For those who should keep using not auotamatic for some reason

Open keyChain Access to see whether there are two same Certifications ,If there's two or more,Just Delete to one and it will work :)


问:
If any input field value entered zero then disable else enable
I am trying to implement code in that if any of input value entered is zero then disable button otherwise enable. Its working fine when input value entered is zero but after I entered value other then zero it still disabled not enabling I am using counter and I have total nearly 40 text field to check so I am using input type with each statement.

following is fiddle which is I am implemented.

答:
You need to initialize count value every time ,because you want to check that value is the statement of having 0 value or not.Put it that setting value in .change() function

```<code>$(document).ready(function() {
   $('input').change(function()  {
      var count = 0;
      $("input").each(function() {
         if($(this).val() == "0")
         {
          count = 1;
         }
       });

       if(count == 0)
            {

          $("#submitBtn").removeAttr("disabled","disabled");

            }
        else
            {
          $("#submitBtn").attr("disabled","disabled");
            }
      });
   });
</code>```

Body:
You need to initialize count value every time ,because you want to check that value is the statement of having 0 value or not.Put it that setting value in .change() function

$(document).ready(function() {
   $('input').change(function()  {
      var count = 0;
      $("input").each(function() {
         if($(this).val() == "0")
         {
          count = 1;
         }
       });

       if(count == 0)
            {

          $("#submitBtn").removeAttr("disabled","disabled");

            }
        else
            {
          $("#submitBtn").attr("disabled","disabled");
            }
      });
   });


问:
Move Activity to Fragment

Help, how to pass this code (Activity) to code (Fragment), how it should be?

```<code>public class SelectProfileActivity extends AppCompatActivity implements ProfileAdapter.ProfileAdapterItemCallBack {

    private List<Profile> Profiles;
    private RecyclerView morral;
    private GridLayoutManager correa;
    private ProfileAdapter adapter;
    private SharedPreferencesController spc;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }
    public void crearPerfil(View view){
        Intent inten=new Intent(this,RegistrarPerfil.class);
        startActivity(inten);
    }
    @Override
    protected void onResume() {
        super.onResume();
        spc = new SharedPreferencesController(this);
        setContentView(R.layout.activity_select_profile);
        //la lista donde se agregaran los perfiles
        Profiles = new ArrayList<Profile>();
        //Consulta para obtener todos los perfiles
        Profiles=App.getProfFromUser(spc.getPrefUID());
        adapter = new ProfileAdapter(Profiles, this);
        if (Profiles.isEmpty()){
            App.showMessage("No se encontraron Perfiles",this);
        }
        else
        {
            //RecyclerView donde se van a mostrar los elementos
            morral = (RecyclerView)findViewById(R.id.rv_all_profiles);
            correa = new GridLayoutManager(this,3);
            morral.setLayoutManager(correa);
            morral.setAdapter(adapter);
        }

    }

    @Override
    public void onProfileItemSelected(Profile perfil) {
        spc.saveProfile(perfil);
        Intent inte = new Intent(this, CategoryActivity.class);
        startActivity(inte);
        finish();
    }
}
</code>```

答:
There are so many things going wrong in your code.

Don't do such things in your onResume(). setContentView(..) should be done in Activity onCreate(..) callback. In some special scenarios, setContentView(..) can be done based on different conditions.

May be its good to start with Android resources, there are many samples by Google. Google samples for Android

Please read android docs Android Docs

Title: Move Activity to Fragment

Body:
Help, how to pass this code (Activity) to code (Fragment), how it should be?

public class SelectProfileActivity extends AppCompatActivity implements ProfileAdapter.ProfileAdapterItemCallBack {

    private List<Profile> Profiles;
    private RecyclerView morral;
    private GridLayoutManager correa;
    private ProfileAdapter adapter;
    private SharedPreferencesController spc;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }
    public void crearPerfil(View view){
        Intent inten=new Intent(this,RegistrarPerfil.class);
        startActivity(inten);
    }
    @Override
    protected void onResume() {
        super.onResume();
        spc = new SharedPreferencesController(this);
        setContentView(R.layout.activity_select_profile);
        //la lista donde se agregaran los perfiles
        Profiles = new ArrayList<Profile>();
        //Consulta para obtener todos los perfiles
        Profiles=App.getProfFromUser(spc.getPrefUID());
        adapter = new ProfileAdapter(Profiles, this);
        if (Profiles.isEmpty()){
            App.showMessage("No se encontraron Perfiles",this);
        }
        else
        {
            //RecyclerView donde se van a mostrar los elementos
            morral = (RecyclerView)findViewById(R.id.rv_all_profiles);
            correa = new GridLayoutManager(this,3);
            morral.setLayoutManager(correa);
            morral.setAdapter(adapter);
        }

    }

    @Override
    public void onProfileItemSelected(Profile perfil) {
        spc.saveProfile(perfil);
        Intent inte = new Intent(this, CategoryActivity.class);
        startActivity(inte);
        finish();
    }
}


问:
Mysql connecting issue in django 1.9
I am getting the following error when trying to connect mysql db

```<code>[Fri Mar 31 09:04:54.154874 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314] mod_wsgi (pid=16451): Target WSGI script '/home/abhadran/network_python3/netmap/netmap/wsgi.py' cannot be loaded as Python module.
[Fri Mar 31 09:04:54.154920 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314] mod_wsgi (pid=16451): Exception occurred processing WSGI script '/home/abhadran/network_python3/netmap/netmap/wsgi.py'.
[Fri Mar 31 09:04:54.154942 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314] Traceback (most recent call last):
[Fri Mar 31 09:04:54.154960 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]   File "/home/abhadran/network_python3/netmap/netmap/wsgi.py", line 21, in <module>
[Fri Mar 31 09:04:54.156034 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]     application = get_wsgi_application()
[Fri Mar 31 09:04:54.156062 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]   File "/home/webdev01/pythonev3/lib/python3.5/site-packages/django/core/wsgi.py", line 13, in get_wsgi_application
[Fri Mar 31 09:04:54.156125 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]     django.setup()
[Fri Mar 31 09:04:54.156140 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]   File "/home/webdev01/pythonev3/lib/python3.5/site-packages/django/__init__.py", line 18, in setup
[Fri Mar 31 09:04:54.156170 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]     apps.populate(settings.INSTALLED_APPS)
[Fri Mar 31 09:04:54.156182 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]   File "/home/webdev01/pythonev3/lib/python3.5/site-packages/django/apps/registry.py", line 108, in populate
[Fri Mar 31 09:04:54.156290 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]     app_config.import_models(all_models)
[Fri Mar 31 09:04:54.156310 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]   File "/home/webdev01/pythonev3/lib/python3.5/site-packages/django/apps/config.py", line 202, in import_models
[Fri Mar 31 09:04:54.156373 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]     self.models_module = import_module(models_module_name)
[Fri Mar 31 09:04:54.156392 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]   File "/usr/lib64/python2.7/importlib/__init__.py", line 37, in import_module
[Fri Mar 31 09:04:54.156462 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]     __import__(name)
[Fri Mar 31 09:04:54.156478 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]   File "/home/webdev01/pythonev3/lib/python3.5/site-packages/django/contrib/auth/models.py", line 4, in <module>
[Fri Mar 31 09:04:54.156614 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]     from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
[Fri Mar 31 09:04:54.156636 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]   File "/home/webdev01/pythonev3/lib/python3.5/site-packages/django/contrib/auth/base_user.py", line 49, in <module>
[Fri Mar 31 09:04:54.156715 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]     class AbstractBaseUser(models.Model):
[Fri Mar 31 09:04:54.156732 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]   File "/home/webdev01/pythonev3/lib/python3.5/site-packages/django/db/models/base.py", line 108, in __new__
[Fri Mar 31 09:04:54.157044 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]     new_class.add_to_class('_meta', Options(meta, app_label))
[Fri Mar 31 09:04:54.157061 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]   File "/home/webdev01/pythonev3/lib/python3.5/site-packages/django/db/models/base.py", line 307, in add_to_class
[Fri Mar 31 09:04:54.157078 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]     value.contribute_to_class(cls, name)
[Fri Mar 31 09:04:54.157098 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]   File "/home/webdev01/pythonev3/lib/python3.5/site-packages/django/db/models/options.py", line 263, in contribute_to_class
[Fri Mar 31 09:04:54.157316 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]     self.db_table = truncate_name(self.db_table, connection.ops.max_name_length())
[Fri Mar 31 09:04:54.157335 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]   File "/home/webdev01/pythonev3/lib/python3.5/site-packages/django/db/__init__.py", line 36, in __getattr__
[Fri Mar 31 09:04:54.157383 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]     return getattr(connections[DEFAULT_DB_ALIAS], item)
[Fri Mar 31 09:04:54.157398 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]   File "/home/webdev01/pythonev3/lib/python3.5/site-packages/django/db/utils.py", line 212, in __getitem__
[Fri Mar 31 09:04:54.157479 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]     backend = load_backend(db['ENGINE'])
[Fri Mar 31 09:04:54.157492 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]   File "/home/webdev01/pythonev3/lib/python3.5/site-packages/django/db/utils.py", line 116, in load_backend
[Fri Mar 31 09:04:54.157505 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]     return import_module('%s.base' % backend_name)
[Fri Mar 31 09:04:54.157513 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]   File "/usr/lib64/python2.7/importlib/__init__.py", line 37, in import_module
[Fri Mar 31 09:04:54.157523 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]     __import__(name)
[Fri Mar 31 09:04:54.157529 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]   File "/home/webdev01/pythonev3/lib/python3.5/site-packages/django/db/backends/mysql/base.py", line 28, in <module>
[Fri Mar 31 09:04:54.157625 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]     raise ImproperlyConfigured("Error loading MySQLdb module: %s" % e)
[Fri Mar 31 09:04:54.157650 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314] ImproperlyConfigured: Error loading MySQLdb module: this is MySQLdb version (1, 3, 10, 'final', 0), but _mysql is version (1, 2, 3, 'final', 0)
</code>```

I am using django 1.9 version with python3.5.3. I have python installtion manually . Is this problem because of that??. Even after unistalling mysql client I am getting the above error.

pip freeze

```<code>configparser2==4.0.0
Django==1.9.12
django-tastypie==0.13.3
mod-wsgi==4.5.15
python-dateutil==2.6.0
python-mimeparse==1.6.0
requests==2.13.0
six==1.10.0
</code>```

答:
```<code>import PyMySQL
</code>```

PyMySQL is the interface for python to connect to mysql.
can be downloaded using

```<code>pip install PyMySQL
</code>```

Also mysqlclient can be used.

```<code>pip install mysqlclient.
</code>```

Title: Mysql connecting issue in django 1.9

Body:
I am getting the following error when trying to connect mysql db

[Fri Mar 31 09:04:54.154874 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314] mod_wsgi (pid=16451): Target WSGI script '/home/abhadran/network_python3/netmap/netmap/wsgi.py' cannot be loaded as Python module.
[Fri Mar 31 09:04:54.154920 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314] mod_wsgi (pid=16451): Exception occurred processing WSGI script '/home/abhadran/network_python3/netmap/netmap/wsgi.py'.
[Fri Mar 31 09:04:54.154942 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314] Traceback (most recent call last):
[Fri Mar 31 09:04:54.154960 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]   File "/home/abhadran/network_python3/netmap/netmap/wsgi.py", line 21, in <module>
[Fri Mar 31 09:04:54.156034 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]     application = get_wsgi_application()
[Fri Mar 31 09:04:54.156062 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]   File "/home/webdev01/pythonev3/lib/python3.5/site-packages/django/core/wsgi.py", line 13, in get_wsgi_application
[Fri Mar 31 09:04:54.156125 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]     django.setup()
[Fri Mar 31 09:04:54.156140 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]   File "/home/webdev01/pythonev3/lib/python3.5/site-packages/django/__init__.py", line 18, in setup
[Fri Mar 31 09:04:54.156170 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]     apps.populate(settings.INSTALLED_APPS)
[Fri Mar 31 09:04:54.156182 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]   File "/home/webdev01/pythonev3/lib/python3.5/site-packages/django/apps/registry.py", line 108, in populate
[Fri Mar 31 09:04:54.156290 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]     app_config.import_models(all_models)
[Fri Mar 31 09:04:54.156310 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]   File "/home/webdev01/pythonev3/lib/python3.5/site-packages/django/apps/config.py", line 202, in import_models
[Fri Mar 31 09:04:54.156373 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]     self.models_module = import_module(models_module_name)
[Fri Mar 31 09:04:54.156392 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]   File "/usr/lib64/python2.7/importlib/__init__.py", line 37, in import_module
[Fri Mar 31 09:04:54.156462 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]     __import__(name)
[Fri Mar 31 09:04:54.156478 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]   File "/home/webdev01/pythonev3/lib/python3.5/site-packages/django/contrib/auth/models.py", line 4, in <module>
[Fri Mar 31 09:04:54.156614 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]     from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
[Fri Mar 31 09:04:54.156636 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]   File "/home/webdev01/pythonev3/lib/python3.5/site-packages/django/contrib/auth/base_user.py", line 49, in <module>
[Fri Mar 31 09:04:54.156715 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]     class AbstractBaseUser(models.Model):
[Fri Mar 31 09:04:54.156732 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]   File "/home/webdev01/pythonev3/lib/python3.5/site-packages/django/db/models/base.py", line 108, in __new__
[Fri Mar 31 09:04:54.157044 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]     new_class.add_to_class('_meta', Options(meta, app_label))
[Fri Mar 31 09:04:54.157061 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]   File "/home/webdev01/pythonev3/lib/python3.5/site-packages/django/db/models/base.py", line 307, in add_to_class
[Fri Mar 31 09:04:54.157078 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]     value.contribute_to_class(cls, name)
[Fri Mar 31 09:04:54.157098 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]   File "/home/webdev01/pythonev3/lib/python3.5/site-packages/django/db/models/options.py", line 263, in contribute_to_class
[Fri Mar 31 09:04:54.157316 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]     self.db_table = truncate_name(self.db_table, connection.ops.max_name_length())
[Fri Mar 31 09:04:54.157335 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]   File "/home/webdev01/pythonev3/lib/python3.5/site-packages/django/db/__init__.py", line 36, in __getattr__
[Fri Mar 31 09:04:54.157383 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]     return getattr(connections[DEFAULT_DB_ALIAS], item)
[Fri Mar 31 09:04:54.157398 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]   File "/home/webdev01/pythonev3/lib/python3.5/site-packages/django/db/utils.py", line 212, in __getitem__
[Fri Mar 31 09:04:54.157479 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]     backend = load_backend(db['ENGINE'])
[Fri Mar 31 09:04:54.157492 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]   File "/home/webdev01/pythonev3/lib/python3.5/site-packages/django/db/utils.py", line 116, in load_backend
[Fri Mar 31 09:04:54.157505 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]     return import_module('%s.base' % backend_name)
[Fri Mar 31 09:04:54.157513 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]   File "/usr/lib64/python2.7/importlib/__init__.py", line 37, in import_module
[Fri Mar 31 09:04:54.157523 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]     __import__(name)
[Fri Mar 31 09:04:54.157529 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]   File "/home/webdev01/pythonev3/lib/python3.5/site-packages/django/db/backends/mysql/base.py", line 28, in <module>
[Fri Mar 31 09:04:54.157625 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]     raise ImproperlyConfigured("Error loading MySQLdb module: %s" % e)
[Fri Mar 31 09:04:54.157650 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314] ImproperlyConfigured: Error loading MySQLdb module: this is MySQLdb version (1, 3, 10, 'final', 0), but _mysql is version (1, 2, 3, 'final', 0)

I am using django 1.9 version with python3.5.3. I have python installtion manually . Is this problem because of that??. Even after unistalling mysql client I am getting the above error.

pip freeze

configparser2==4.0.0
Django==1.9.12
django-tastypie==0.13.3
mod-wsgi==4.5.15
python-dateutil==2.6.0
python-mimeparse==1.6.0
requests==2.13.0
six==1.10.0

Body:
import PyMySQL

PyMySQL is the interface for python to connect to mysql.
can be downloaded using

pip install PyMySQL

Also mysqlclient can be used.

pip install mysqlclient.


问:
change the connection string values the app.config
I am trying to change the connection String values

connectionString="Data Source=localhost;Initial Catalog=Tracker;Persist Security Info=false;User ID=sa;Password=p@ssw0rd"

from my user interface. Could any one help to change the settings from the user interface in the windows application?

答:
User below method to change connection string using C# :

```<code>public void SaveConnectionString(DbInfo dbinfo, string path,string appConfigFile)
    {
        try
        {
            string configFile = Path.Combine(path, appConfigFile);
            var doc = new XmlDocument();
            doc.Load(configFile);
            XmlNodeList endpoints = doc.GetElementsByTagName("connectionStrings");
            foreach (XmlNode item in endpoints)
            {
                if (item.HasChildNodes)
                {
                    foreach (var c in item.ChildNodes)
                    {
                        if (((XmlNode)c).NodeType == XmlNodeType.Element)
                        {

                            var adressAttribute = ((XmlNode)c).Attributes["name"];
                            if (adressAttribute.Value.Contains("YourConStrName"))
                            {
                                if (dbinfo.dbType == dataBaseType.Embedded)
                                {
                                    ((XmlNode)c).Attributes["connectionString"].Value = SetupConstants.DbEmbededConnectionString;
                                    ((XmlNode)c).Attributes["providerName"].Value = SetupConstants.DbEmbededConnectionProvider;
                                }
                                else if (dbinfo.dbType == dataBaseType.Microsoft_SQL_Server)
                                {
                                    if (dbinfo.sqlServerAuthType == SqlServerAuthenticationType.SQL_Server_Authentication)
                                    {
                                       // ((XmlNode)c).Attributes["connectionString"].Value = string.Format(SetupConstants.dbConnStringwithDb, dbinfo.databaseAdress, SetupConstants.SqlDbName, dbinfo.userId, dbinfo.password) + "MultipleActiveResultSets=true;";
                                        ((XmlNode)c).Attributes["connectionString"].Value = string.Format(SetupConstants.dbConnStringwithDb, dbinfo.databaseAdress, dbinfo.DatabaseName, dbinfo.userId, dbinfo.password) + "MultipleActiveResultSets=true;";

                                    }
                                    else if (dbinfo.sqlServerAuthType == SqlServerAuthenticationType.Windows_Authentication)
                                    {
                                        //((XmlNode)c).Attributes["connectionString"].Value = string.Format("Data Source={0};Initial Catalog={1};Integrated Security=True;MultipleActiveResultSets=true;", dbinfo.databaseAdress, SetupConstants.SqlDbName);
                                        ((XmlNode)c).Attributes["connectionString"].Value = string.Format("Data Source={0};Initial Catalog={1};Integrated Security=True;MultipleActiveResultSets=true;", dbinfo.databaseAdress, dbinfo.DatabaseName);
                                    }
                                    ((XmlNode)c).Attributes["providerName"].Value = SetupConstants.DbSqlConnectionProvider;
                                }
                            }
                        }
                    }
                }

            }
            doc.Save(configFile);
            string exePath = Path.Combine(path, "EDC.Service.exe");
            InstallerHelper.EncryptConnectionString(true, exePath);
        }
        catch (Exception ex)
        {
            //TODO://log here exception
            Helper.WriteLog(ex.Message + "\n" + ex.StackTrace);
            throw;
        }
    }
</code>```

Add bellow class DBinfo

```<code>public class DbInfo
{
    public DataBaseType dbType { get; set; }
    public SqlServerAuthenticationType sqlServerAuthType { get; set; }
    public string ConnectionString { get; set; }
    public string databaseAdress { get; set; }
    public string userId { get; set; }
    public string password { get; set; }
    public string Port { get; set; }
    public string DatabaseName { get; set; }
}

public enum DataBaseType
{
    Unknown = 0,
    Embedded = 1,
    Microsoft_SQL_Server =2,
}

public enum SqlServerAuthenticationType
{
    Windows_Authentication = 0 ,
    SQL_Server_Authentication =1
}
</code>```

Body:
User below method to change connection string using C# :

public void SaveConnectionString(DbInfo dbinfo, string path,string appConfigFile)
    {
        try
        {
            string configFile = Path.Combine(path, appConfigFile);
            var doc = new XmlDocument();
            doc.Load(configFile);
            XmlNodeList endpoints = doc.GetElementsByTagName("connectionStrings");
            foreach (XmlNode item in endpoints)
            {
                if (item.HasChildNodes)
                {
                    foreach (var c in item.ChildNodes)
                    {
                        if (((XmlNode)c).NodeType == XmlNodeType.Element)
                        {

                            var adressAttribute = ((XmlNode)c).Attributes["name"];
                            if (adressAttribute.Value.Contains("YourConStrName"))
                            {
                                if (dbinfo.dbType == dataBaseType.Embedded)
                                {
                                    ((XmlNode)c).Attributes["connectionString"].Value = SetupConstants.DbEmbededConnectionString;
                                    ((XmlNode)c).Attributes["providerName"].Value = SetupConstants.DbEmbededConnectionProvider;
                                }
                                else if (dbinfo.dbType == dataBaseType.Microsoft_SQL_Server)
                                {
                                    if (dbinfo.sqlServerAuthType == SqlServerAuthenticationType.SQL_Server_Authentication)
                                    {
                                       // ((XmlNode)c).Attributes["connectionString"].Value = string.Format(SetupConstants.dbConnStringwithDb, dbinfo.databaseAdress, SetupConstants.SqlDbName, dbinfo.userId, dbinfo.password) + "MultipleActiveResultSets=true;";
                                        ((XmlNode)c).Attributes["connectionString"].Value = string.Format(SetupConstants.dbConnStringwithDb, dbinfo.databaseAdress, dbinfo.DatabaseName, dbinfo.userId, dbinfo.password) + "MultipleActiveResultSets=true;";

                                    }
                                    else if (dbinfo.sqlServerAuthType == SqlServerAuthenticationType.Windows_Authentication)
                                    {
                                        //((XmlNode)c).Attributes["connectionString"].Value = string.Format("Data Source={0};Initial Catalog={1};Integrated Security=True;MultipleActiveResultSets=true;", dbinfo.databaseAdress, SetupConstants.SqlDbName);
                                        ((XmlNode)c).Attributes["connectionString"].Value = string.Format("Data Source={0};Initial Catalog={1};Integrated Security=True;MultipleActiveResultSets=true;", dbinfo.databaseAdress, dbinfo.DatabaseName);
                                    }
                                    ((XmlNode)c).Attributes["providerName"].Value = SetupConstants.DbSqlConnectionProvider;
                                }
                            }
                        }
                    }
                }

            }
            doc.Save(configFile);
            string exePath = Path.Combine(path, "EDC.Service.exe");
            InstallerHelper.EncryptConnectionString(true, exePath);
        }
        catch (Exception ex)
        {
            //TODO://log here exception
            Helper.WriteLog(ex.Message + "\n" + ex.StackTrace);
            throw;
        }
    }

Add bellow class DBinfo

public class DbInfo
{
    public DataBaseType dbType { get; set; }
    public SqlServerAuthenticationType sqlServerAuthType { get; set; }
    public string ConnectionString { get; set; }
    public string databaseAdress { get; set; }
    public string userId { get; set; }
    public string password { get; set; }
    public string Port { get; set; }
    public string DatabaseName { get; set; }
}

public enum DataBaseType
{
    Unknown = 0,
    Embedded = 1,
    Microsoft_SQL_Server =2,
}

public enum SqlServerAuthenticationType
{
    Windows_Authentication = 0 ,
    SQL_Server_Authentication =1
}


问:
Adding Different DataGridView Cell Types to a Column

Goal

My datagridview has two columns ([Question], [Answer]). Depending on the known question type (Yes/No Checkbox, Text Textbox, FileUpload Button) I want the column cell to have the respective control.

Example

Datagridview Rows:

[Question] Do you smoke? [Answer] (YesNo Checkbox)

[Question] How old are you? [Answer] (Text Textbox)

[Question] Document upload [Answer] (FileUpload Button)

Work

I programmatically create my datagridviews.

```<code>Private Sub FormatQuestionDgv(ByVal dgv As DataGridView)
    Dim ColQ As New DataGridViewTextBoxColumn
    Dim ColA As New DataGridViewColumn

    'Header text
    ColQ.HeaderText = "Question"
    ColA.HeaderText = "Answer"

    'Name
    ColQ.Name = "ColQ"
    ColA.Name = "ColA"

    'Widths
    ColQ.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill
    ColA.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill

    'Add columns
    With dgv.Columns
        .Add(ColQ)
        .Add(ColA)
    End With
End Sub
</code>```

Problem

As you can see in my work, the answer column is of DataGridViewColumn type. I do not know the question type at that moment. Therefore I declare it as a normal column instead of DataGridViewCheckBoxColumn, DataGridViewTextBoxColumn, DataGridViewButtonColumn...

Since those are not the same type as DataGridViewColumn, I get the following error:

How do I go about adding different control types in 1 DataGridViewColumn? Is it even possible?

答:
The other answers are way to difficult and error prone.
It is way easier to add the required cell type upon request.

Example:

Using the designer, create a form with a DataGridView, and two columns: one for the question and one for the answer.

```<code>private DataGridView dataGridView3;
private DataGridViewTextBoxColumn columnQuestion;
private DataGridViewTextBoxColumn columnAnswer;
</code>```

In my class, I created the enum for the answer type

```<code>public enum AnswerType
{
    Text,
    YesNo,
    LoadFile,
    Combo,
};
</code>```

I create two methods: one to create a cell that contains a question, and one to create the proper cell type for the answer.

The method to create a question cell is simple:

```<code>private DataGridViewCell CreateQuestionCell(string question)
{
    return new DataGridViewTextBoxCell()
    {
        ValueType = typeof(string),
        Value = question,
        ReadOnly = true,       // questions can't be edited
    };
}
</code>```

The method to create an answer cell has a parameter indicating the desired answer type:

```<code>private DataGridViewCell CreateAnswerCell(AnswerType answerType)
{
    // type of column depends on rowIndex
    DataGridViewCell cell;
    switch (answerType)
    {
        case AnswerType.YesNo: // Create a checkbox cell
            cell = new DataGridViewCheckBoxCell()
            {
                ValueType = typeof(bool),
                Value = false,
            };
            break;
        case AnswerType.LoadFile: // Create a Button cell
            cell = new DataGridViewButtonCell()
            {
                ValueType = typeof(string),
                Value = "Load!",
            };
            break;
        case AnswerType.Combo: // Create a Combo Cell
            var selectableValues = Enumerable.Range(0, 4);
            var comboItems = Enumerable.Range(0, 100);
            cell = new DataGridViewComboBoxCell()
            {
                DataSource = new BindingList<int>(comboItems.ToList()),
            };
            break;
        default: // Create a Text cell
            cell = new DataGridViewTextBoxCell()
            {
                ValueType = typeof(string),
                Value = "<please enter name>",
            };
            break;
    }
    return cell;
}
</code>```

Upon request add a Row, containing a question cell and an answer cell:

```<code>private void AddRow(string question, AnswerType answerType)
{
    DataGridViewRow row = new DataGridViewRow();
    row.Cells.Add(this.CreateQuestionCell(question));
    row.Cells.Add(this.CreateAnswerCell(answerType));
    this.dataGridView1.Rows.Add(row);
}
</code>```

To test I created four buttons and handlers to add rows:

```<code>private Button buttonCheckbox;
private Button buttonAction;
private Button buttonCombo;
private Button buttonText;

private void OnButtonCheckbox(object sender, EventArgs e)
{
    this.AddRow("Do you smoke", AnswerType.YesNo);
}

private void OnButtonText(object sender, EventArgs e)
{
    this.AddRow("Name", AnswerType.Text);
}

private void OnButtonCombo(object sender, EventArgs e)
{
    this.AddRow("Age?", AnswerType.Combo);
}

private void OnButtonAction(object sender, EventArgs e)
{
    this.AddRow("Document upload", AnswerType.LoadFile);
}
</code>```

Et voilà, ça marche! Simple comme bonjour!

Body:
Goal

My datagridview has two columns ([Question], [Answer]). Depending on the known question type (Yes/No Checkbox, Text Textbox, FileUpload Button) I want the column cell to have the respective control.

Example

Datagridview Rows:

[Question] Do you smoke? [Answer] (YesNo Checkbox)

[Question] How old are you? [Answer] (Text Textbox)

[Question] Document upload [Answer] (FileUpload Button)

Work

I programmatically create my datagridviews.

Private Sub FormatQuestionDgv(ByVal dgv As DataGridView)
    Dim ColQ As New DataGridViewTextBoxColumn
    Dim ColA As New DataGridViewColumn

    'Header text
    ColQ.HeaderText = "Question"
    ColA.HeaderText = "Answer"

    'Name
    ColQ.Name = "ColQ"
    ColA.Name = "ColA"

    'Widths
    ColQ.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill
    ColA.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill

    'Add columns
    With dgv.Columns
        .Add(ColQ)
        .Add(ColA)
    End With
End Sub

Problem

As you can see in my work, the answer column is of DataGridViewColumn type. I do not know the question type at that moment. Therefore I declare it as a normal column instead of DataGridViewCheckBoxColumn, DataGridViewTextBoxColumn, DataGridViewButtonColumn...

Since those are not the same type as DataGridViewColumn, I get the following error:

How do I go about adding different control types in 1 DataGridViewColumn? Is it even possible?

Body:
The other answers are way to difficult and error prone.
It is way easier to add the required cell type upon request.

Example:

Using the designer, create a form with a DataGridView, and two columns: one for the question and one for the answer.

private DataGridView dataGridView3;
private DataGridViewTextBoxColumn columnQuestion;
private DataGridViewTextBoxColumn columnAnswer;

In my class, I created the enum for the answer type

public enum AnswerType
{
    Text,
    YesNo,
    LoadFile,
    Combo,
};

I create two methods: one to create a cell that contains a question, and one to create the proper cell type for the answer.

The method to create a question cell is simple:

private DataGridViewCell CreateQuestionCell(string question)
{
    return new DataGridViewTextBoxCell()
    {
        ValueType = typeof(string),
        Value = question,
        ReadOnly = true,       // questions can't be edited
    };
}

The method to create an answer cell has a parameter indicating the desired answer type:

private DataGridViewCell CreateAnswerCell(AnswerType answerType)
{
    // type of column depends on rowIndex
    DataGridViewCell cell;
    switch (answerType)
    {
        case AnswerType.YesNo: // Create a checkbox cell
            cell = new DataGridViewCheckBoxCell()
            {
                ValueType = typeof(bool),
                Value = false,
            };
            break;
        case AnswerType.LoadFile: // Create a Button cell
            cell = new DataGridViewButtonCell()
            {
                ValueType = typeof(string),
                Value = "Load!",
            };
            break;
        case AnswerType.Combo: // Create a Combo Cell
            var selectableValues = Enumerable.Range(0, 4);
            var comboItems = Enumerable.Range(0, 100);
            cell = new DataGridViewComboBoxCell()
            {
                DataSource = new BindingList<int>(comboItems.ToList()),
            };
            break;
        default: // Create a Text cell
            cell = new DataGridViewTextBoxCell()
            {
                ValueType = typeof(string),
                Value = "<please enter name>",
            };
            break;
    }
    return cell;
}

Upon request add a Row, containing a question cell and an answer cell:

private void AddRow(string question, AnswerType answerType)
{
    DataGridViewRow row = new DataGridViewRow();
    row.Cells.Add(this.CreateQuestionCell(question));
    row.Cells.Add(this.CreateAnswerCell(answerType));
    this.dataGridView1.Rows.Add(row);
}

To test I created four buttons and handlers to add rows:

private Button buttonCheckbox;
private Button buttonAction;
private Button buttonCombo;
private Button buttonText;

private void OnButtonCheckbox(object sender, EventArgs e)
{
    this.AddRow("Do you smoke", AnswerType.YesNo);
}

private void OnButtonText(object sender, EventArgs e)
{
    this.AddRow("Name", AnswerType.Text);
}

private void OnButtonCombo(object sender, EventArgs e)
{
    this.AddRow("Age?", AnswerType.Combo);
}

private void OnButtonAction(object sender, EventArgs e)
{
    this.AddRow("Document upload", AnswerType.LoadFile);
}

Et voilà, ça marche! Simple comme bonjour!


答:
You can simply get the value from queryset in this way:

```<code>date1 = table.objects.values_list('field1', flat=True).filter(id=1))[0]
date2 = table.objects.values_list('field1', flat=True).filter(id=2))[0]
timediff = date2 - date1
</code>```

Please note also that the timediff is date2 - date1 and not viceversa.

Title: How to get time difference in hours between two dates (Django)

Body:
You can simply get the value from queryset in this way:

date1 = table.objects.values_list('field1', flat=True).filter(id=1))[0]
date2 = table.objects.values_list('field1', flat=True).filter(id=2))[0]
timediff = date2 - date1

Please note also that the timediff is date2 - date1 and not viceversa.


问:
Converting string to byte array in C# (CSV)
I wrote a function to convert byte[] to string, and I add ";" after each byte. Now I want to convert this string to byte[] by splitting the string (similar to a CSV string).

```<code>public string ByteArrayToString(byte[] byteArray,string s)
{
    for (int i = 0; i < byteArray.Length; i++)
    {
        s += byteArray[i].ToString() + ";";
    }
    s = s.Substring(0, s.Length - 1);
    return s;
}
</code>```

How could I write a function to convert this string to that byte array again?

答:
StringBuilder will be useful instead of String (Performance wise).

With StringBuilder:

```<code>byte[] buffer = System.Text.Encoding.UTF8.GetBytes(objStringBuilder.ToString());
</code>```

with String:

```<code>byte[] buffer = System.Text.Encoding.UTF8.GetBytes(objString);
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I wrote a function to convert byte[] to string, and I add ";" after each byte. Now I want to convert this string to byte[] by splitting the string (similar to a CSV string).

public string ByteArrayToString(byte[] byteArray,string s)
{
    for (int i = 0; i < byteArray.Length; i++)
    {
        s += byteArray[i].ToString() + ";";
    }
    s = s.Substring(0, s.Length - 1);
    return s;
}

How could I write a function to convert this string to that byte array again?

Body:
StringBuilder will be useful instead of String (Performance wise).

With StringBuilder:

byte[] buffer = System.Text.Encoding.UTF8.GetBytes(objStringBuilder.ToString());

with String:

byte[] buffer = System.Text.Encoding.UTF8.GetBytes(objString);


问:
How can I search for an object property value in an array if I only know a different property?
In this array I would like to find the id of the object by querying on the property name. Given I know the name is NV, how can I get the id?

I already tried different loops and other thing like GetObject, but it gives no return.

```<code>{
  "items": [
    {
      "id": 1,
      "name": "BV",
    },
    {
      "id": 2,
      "name": "NV"
    }
  ],
}
</code>```

答:
You can use Array filter() method :

var jsonObj = {
  "items": [
    {
      "id": 1,
      "name": "BV",
    },
    {
      "id": 2,
      "name": "NV"
    }
  ]
};

var res = jsonObj.items.filter(function(item) {
    return item.name == "NV";
});

console.log(res[0].id);```

Body:
In this array I would like to find the id of the object by querying on the property name. Given I know the name is NV, how can I get the id?

I already tried different loops and other thing like GetObject, but it gives no return.

{
  "items": [
    {
      "id": 1,
      "name": "BV",
    },
    {
      "id": 2,
      "name": "NV"
    }
  ],
}


问:
Remove Installed Directory after uninstallation of Windows Application
I have created setup file(msi) for my windows application using install shield. The problem is when i uninstall the application from control panel,except 2 files remaining files got removed from installed directory. But i want to have the whole installed directory to be removed. Any help is appreciated.</p>

答:
Those files are created by application.It is just bin files of
  winforms.

Windows installer automatically removes files on uninstall only if it has installed them before. It won't automatically remove other files because these might be user files.

The solution is to explicitly tell Windows Installer to remove the left-over files on uninstall. I can't tell you exactly how to do that using InstallShield but I'm fairly certain that it has a feature for that. The WiX toolset for example has the RemoveFile element which writes entries to the underlying RemoveFile table of Window Installer.

Explicitly removing the directory should not be necessary as Windows installer will do that if the directory is empty (after all files have been removed). If you still see an empty directory left over (your application may have created), there should be a feature of InstallShield where you can define directories to delete on uninstall. For example the WiX toolset has the RemoveFolder element which writes entries to the underlying RemoveFile table of Window Installer.


问:
Prometheus with multi-container pod on kubernetes
I have a multi-container pod in my kubernetes deployment:

java

redis

nginx

For every of those containers, there's a container with Prometheus exporter as well.

The question is how can I expose those ports to Prometheus if annotations section supports only one port per pod?

```<code>annotations:
  prometheus.io/scrape: 'true'
  prometheus.io/port: 'xxxx'
</code>```

but I need something like this:

```<code>annotations:
  prometheus.io/scrape: 'true'
  prometheus.io/port_1: 'xxxx'
  prometheus.io/port_2: 'yyyy'
  prometheus.io/port_3: 'zzzz'
</code>```

Maybe there's some other method to scrape all metrics from my multi-container pods? Thanks in advance for any kind of help.

答: The annotations you propose should work. Create one scrape_config per port annotation, keeping only targets matching the corresponding annotation port name.</p>

Body:
I have a multi-container pod in my kubernetes deployment:

java

redis

nginx

For every of those containers, there's a container with Prometheus exporter as well.

The question is how can I expose those ports to Prometheus if annotations section supports only one port per pod?

annotations:
  prometheus.io/scrape: 'true'
  prometheus.io/port: 'xxxx'

but I need something like this:

annotations:
  prometheus.io/scrape: 'true'
  prometheus.io/port_1: 'xxxx'
  prometheus.io/port_2: 'yyyy'
  prometheus.io/port_3: 'zzzz'

Maybe there's some other method to scrape all metrics from my multi-container pods? Thanks in advance for any kind of help.


问:
Override animation-duration with a CSS class
I would like to design my CSS file in this way:

```<code><h1 class="bounce">Bouncing Text</h1>
<h1 class="bounce fast">Faster Bouncing Text</h1>
</code>```

I have CSS code that looks like this, but it doesn't seem to be working:

```<code>.fast {
    -webkit-animation-duration: 1s !important;
    animation-duration: 1s !important;
}
.bounce {
    -webkit-animation-name: bounce-animation;
    animation-name: bounce-animation;
    -webkit-animation-duration: 2s;
    animation-duration: 2s;
    -webkit-animation-timing-function: linear;
    animation-timing-function: linear;
    -webkit-animation-iteration-count: infinite;
    animation-iteration-count: infinite;
}
</code>```

The 'fast' class does not seem to actually change the animation-duration at all. The two elements bounce at the same speed.
Is there anyway to make this design work? Thanks

答: display: block; will fix the problem. :)

Body:
I would like to design my CSS file in this way:

Bouncing Text

Faster Bouncing Text

I have CSS code that looks like this, but it doesn't seem to be working:

.fast {
    -webkit-animation-duration: 1s !important;
    animation-duration: 1s !important;
}
.bounce {
    -webkit-animation-name: bounce-animation;
    animation-name: bounce-animation;
    -webkit-animation-duration: 2s;
    animation-duration: 2s;
    -webkit-animation-timing-function: linear;
    animation-timing-function: linear;
    -webkit-animation-iteration-count: infinite;
    animation-iteration-count: infinite;
}

The 'fast' class does not seem to actually change the animation-duration at all. The two elements bounce at the same speed.
Is there anyway to make this design work? Thanks


问:
javascript: how to judge a function name exists?
Is it possible to judge if a function names exists before calling it?</p>

答:
depends pretty much on the scope you're in.

But in general if( 'function_name_to_check' in this) would return true if there is a property in the global or local scope which has that name.

This check must be followed by an additional check for the type:

```<code>if( typeof this.function_name_to_check === 'function') { }
</code>```

to be sure that this IS a function.

Body:
depends pretty much on the scope you're in.

But in general if( 'function_name_to_check' in this) would return true if there is a property in the global or local scope which has that name.

This check must be followed by an additional check for the type:

if( typeof this.function_name_to_check === 'function') { }

to be sure that this IS a function.


问:
Powershell to List Azure VMs with storage account name
I need help with listing all Azure Virutal Machines in a subscription with their associated storage account name.

I have tried the below command but am not getting the expected output:

```<code>Get-Azurermvm | Ft vmname,storageaccount,location
</code>```

答:
Below script will give you the VM Name along with Resource group Name, Subscription name ,disk name, disk type and the storage account associated with it.</p>

```<code>Login-AzureRmAccount

$subscription=Get-AzureRmSubscription | select SubscriptionName -ExpandProperty SubscriptionName

foreach($sub in $subscription)
{

Select-AzureRmSubscription -SubscriptionName $sub

$StroageAccDetail = Get-AzureRmStorageAccount

$vmstatus=Get-AzurermVM -Status

foreach ($vmdetails in $vmstatus)
{
$ResourceGroupName=$vmdetails.ResourceGroupName
$VMName=$vmdetails.name
$storage=$vmdetails.StorageProfile.OsDisk.Vhd.Uri
$DataDiks=$vmdetails.StorageProfile.OsDisk.Name
$ss=$storage.split('/')[2]

$OSStorageAccountName=$ss.split('.')[0]
$DiskType="OSDisk"
$StroageAccountLocation=($StroageAccDetail | where  {$_.StorageAccountName -eq $OSStorageAccountName }).location
$StorageAccountType=($StroageAccDetail | where  {$_.StorageAccountName -eq $OSStorageAccountName }).AccountType
"$sub,$ResourceGroupName,$VMName,$DataDiks,$DiskType,$OSStorageAccountName" | Out-File $OutFile -Append
$vmdatadisks=$vmdetails.StorageProfile.DataDisks

if($vmdatadisks -ne $null){
foreach($vmDatadsik in $vmdatadisks)
{
$vmDatadsikss=$vmDatadsik.vhd.uri
$DiskType="DataDisk"
$ss=$vmDatadsikss.split('/')[2]
$DataDiks=$vmDatadsik.Name
$dataStorageAccountName=$ss.split('.')[0]
"$sub,$ResourceGroupName,$VMName,$DataDiks,$DiskType,$dataStorageAccountName" | Out-File $OutFile -Append
}
}
}
}
</code>```

Body:
I need help with listing all Azure Virutal Machines in a subscription with their associated storage account name.

I have tried the below command but am not getting the expected output:

Get-Azurermvm | Ft vmname,storageaccount,location

Body:
Below script will give you the VM Name along with Resource group Name, Subscription name ,disk name, disk type and the storage account associated with it.

Login-AzureRmAccount

$subscription=Get-AzureRmSubscription | select SubscriptionName -ExpandProperty SubscriptionName

foreach($sub in $subscription)
{

Select-AzureRmSubscription -SubscriptionName $sub

$StroageAccDetail = Get-AzureRmStorageAccount

$vmstatus=Get-AzurermVM -Status

foreach ($vmdetails in $vmstatus)
{
$ResourceGroupName=$vmdetails.ResourceGroupName
$VMName=$vmdetails.name
$storage=$vmdetails.StorageProfile.OsDisk.Vhd.Uri
$DataDiks=$vmdetails.StorageProfile.OsDisk.Name
$ss=$storage.split('/')[2]

$OSStorageAccountName=$ss.split('.')[0]
$DiskType="OSDisk"
$StroageAccountLocation=($StroageAccDetail | where  {$_.StorageAccountName -eq $OSStorageAccountName }).location
$StorageAccountType=($StroageAccDetail | where  {$_.StorageAccountName -eq $OSStorageAccountName }).AccountType
"$sub,$ResourceGroupName,$VMName,$DataDiks,$DiskType,$OSStorageAccountName" | Out-File $OutFile -Append
$vmdatadisks=$vmdetails.StorageProfile.DataDisks

if($vmdatadisks -ne $null){
foreach($vmDatadsik in $vmdatadisks)
{
$vmDatadsikss=$vmDatadsik.vhd.uri
$DiskType="DataDisk"
$ss=$vmDatadsikss.split('/')[2]
$DataDiks=$vmDatadsik.Name
$dataStorageAccountName=$ss.split('.')[0]
"$sub,$ResourceGroupName,$VMName,$DataDiks,$DiskType,$dataStorageAccountName" | Out-File $OutFile -Append
}
}
}
}


问:
Abstract constants in PHP - Force a child class to define a constant
I noticed that you can't have abstract constants in PHP.

Is there a way I can force a child class to define a constant (which I need to use in one of the abstract class internal methods) ?

答:
This may be a bit of a ‘hack’, but does the job with very little effort, but just with a different error message if the constant is not declared in the child class.

A self-referential constant declaration is syntactically correct and parses without problem, only throwing an error if that declaration is actually executed at runtime, so a self-referential declaration in the abstract class must be overridden in a child class else there will be fatal error: Cannot declare self-referencing constant.

In this example, the abstract, parent class Foo forces all its children to declare the variable NAME. This code runs fine, outputting Donald. However, if the child class Fooling did not declare the variable, the fatal error would be triggered.

```<code><?php

abstract class Foo {

    // Self-referential 'abstract' declaration
    const NAME = self::NAME;

}

class Fooling extends Foo {

    // Overrides definition from parent class
    // Without this declaration, an error will be triggered
    const NAME = 'Donald';

}

$fooling = new Fooling();

echo $fooling::NAME;
</code>```

Body:
This may be a bit of a ‘hack’, but does the job with very little effort, but just with a different error message if the constant is not declared in the child class.

A self-referential constant declaration is syntactically correct and parses without problem, only throwing an error if that declaration is actually executed at runtime, so a self-referential declaration in the abstract class must be overridden in a child class else there will be fatal error: Cannot declare self-referencing constant.

In this example, the abstract, parent class Foo forces all its children to declare the variable NAME. This code runs fine, outputting Donald. However, if the child class Fooling did not declare the variable, the fatal error would be triggered.

<?php

abstract class Foo {

    // Self-referential 'abstract' declaration
    const NAME = self::NAME;

}

class Fooling extends Foo {

    // Overrides definition from parent class
    // Without this declaration, an error will be triggered
    const NAME = 'Donald';

}

$fooling = new Fooling();

echo $fooling::NAME;


问:
Dynamic form on symfony for choicetype
I am trying to do a dynamic Form on two choiceList and i've tried to follow the documentation about SYmfony: http://symfony.com/doc/current/form/dynamic_form_modification.html#dynamic-generation-for-submitted-forms but the are using two entities and i have to work with choiceList Can anyone help me about that here is my UserTYpe:

$

```<code>builder
    ->add('at', ChoiceType::class, array(
        'label' => ' ',
        'choices' =>array(
            "42consulting.fr" => "42consulting.fr",
            "42consulting.lu" => "42consulting.lu",
            "42mediatvcom.fr" => "42mediatvcom.fr",
            "42consulting.ma" => "42consulting.ma",
            "42consulting.nl" => "42consulting.nl",
        ),
        'attr' => array(
            'class' => 'form-control',
            'placeholder' => 'service',
        ),
    )
);

$formModifier = function (FormInterface $form, User $at= null) {
    $services = null === $at ? array() :$at->getService();

    $form->add('service', ChoiceType::class, array(
                'label' => 'Service',
                'choices' => array(
                    "42Consulting Paris" => "Saint-Mandé",
                    "42Consulting Lux" => "Luxembourg",
                    "42MediaTelecom" => "Issy-Les-Moulineaux",
                    "42Consulting Maroc" => "Casablanca"
                ),
                'attr' => array(
                    'class' => 'form-control service',
                    'placeholder' => 'service',
                ),
            )
    );

};

$builder->addEventListener(
    FormEvents::PRE_SET_DATA,
    function (FormEvent $event) use ($formModifier) {
        $data = $event->getData();

        $formModifier($event->getForm(), $data->getAt());
    }
);

$builder->get('at')->addEventListener(
    FormEvents::POST_SUBMIT,
    function (FormEvent $event) use ($formModifier) {
        $at = $event->getForm()->getData();

        $formModifier($event->getForm()->getParent(), $at);
    }
);
</code>```

and the error that i'm getting is : Type error: Argument 2 passed to BackBundle\Form\UserType::BackBundle\Form{closure}() must be an instance of BackBundle\Entity\User, string given, called in /home/work/Sites/backoffice-ad/src/BackBundle/Form/UserType.php on line 263 (on this line:  $formModifier($event->getForm()->getParent(), $at);)

答:
On the line

```<code>$formModifier = function (FormInterface $form, User $at= null) {
</code>```

Your $at, as declare, this parameter must be an instance of User entity. But when you call this function, you passed a string:

```<code>$builder->addEventListener(
    FormEvents::PRE_SET_DATA,
    function (FormEvent $event) use ($formModifier) {
        $data = $event->getData();
        $formModifier($event->getForm(), $data->getAt());
    }
);
</code>```

Have you tried:

```<code>$formModifier($event->getForm(), $data);
</code>```

I'm not sure, but I think this is the problem when you call getAt(), this method return string. And $data variable is probably an instance of User entity.

Title: Dynamic form on symfony for choicetype

Body:
I am trying to do a dynamic Form on two choiceList and i've tried to follow the documentation about SYmfony: http://symfony.com/doc/current/form/dynamic_form_modification.html#dynamic-generation-for-submitted-forms but the are using two entities and i have to work with choiceList Can anyone help me about that here is my UserTYpe:

$

builder
    ->add('at', ChoiceType::class, array(
        'label' => ' ',
        'choices' =>array(
            "42consulting.fr" => "42consulting.fr",
            "42consulting.lu" => "42consulting.lu",
            "42mediatvcom.fr" => "42mediatvcom.fr",
            "42consulting.ma" => "42consulting.ma",
            "42consulting.nl" => "42consulting.nl",
        ),
        'attr' => array(
            'class' => 'form-control',
            'placeholder' => 'service',
        ),
    )
);

$formModifier = function (FormInterface $form, User $at= null) {
    $services = null === $at ? array() :$at->getService();

    $form->add('service', ChoiceType::class, array(
                'label' => 'Service',
                'choices' => array(
                    "42Consulting Paris" => "Saint-Mandé",
                    "42Consulting Lux" => "Luxembourg",
                    "42MediaTelecom" => "Issy-Les-Moulineaux",
                    "42Consulting Maroc" => "Casablanca"
                ),
                'attr' => array(
                    'class' => 'form-control service',
                    'placeholder' => 'service',
                ),
            )
    );

};

$builder->addEventListener(
    FormEvents::PRE_SET_DATA,
    function (FormEvent $event) use ($formModifier) {
        $data = $event->getData();

        $formModifier($event->getForm(), $data->getAt());
    }
);

$builder->get('at')->addEventListener(
    FormEvents::POST_SUBMIT,
    function (FormEvent $event) use ($formModifier) {
        $at = $event->getForm()->getData();

        $formModifier($event->getForm()->getParent(), $at);
    }
);

and the error that i'm getting is : Type error: Argument 2 passed to BackBundle\Form\UserType::BackBundle\Form{closure}() must be an instance of BackBundle\Entity\User, string given, called in /home/work/Sites/backoffice-ad/src/BackBundle/Form/UserType.php on line 263 (on this line:  $formModifier($event->getForm()->getParent(), $at);)

Body:
On the line

$formModifier = function (FormInterface $form, User $at= null) {

Your $at, as declare, this parameter must be an instance of User entity. But when you call this function, you passed a string:

$builder->addEventListener(
    FormEvents::PRE_SET_DATA,
    function (FormEvent $event) use ($formModifier) {
        $data = $event->getData();
        $formModifier($event->getForm(), $data->getAt());
    }
);

Have you tried:

$formModifier($event->getForm(), $data);

I'm not sure, but I think this is the problem when you call getAt(), this method return string. And $data variable is probably an instance of User entity.


问:
How to change document by terms dataframe into a dataframe which records the documents where a word appears
I have a

I want to change the dataframe into the format like

Could you tell me how to code with pandas, is there any built-in function in pandas which can be used to do it.

```<code>doc_term_frame=pd.DataFrame(data={'doc_id':[1,2,3,4],'words':[['w1','w2'],['w2','w3'],['w4','w5'],['w4','w6']]}).set_index('doc_id')
desired_frame=pd.DataFrame(data={'word':['w1','w2','w3','w4','w5','w6'],'doc_ids':[[1],[1,2],[2],[3,4],[3],[4]]}).set_index('word')
</code>```

答:
You can use DataFrame constructor for creating convert lists to rows, then reshape by stack, create columns from index by reseting index, groupby and create list. Last convert Series to DataFrame by to_frame:

```<code>df1 = pd.DataFrame(doc_term_frame['words'].values.tolist(), index=doc_term_frame.index)
        .stack()
        .reset_index(name='word')
        .groupby('word')['doc_id']
        .apply(list)
        .to_frame(name='doc_ids')
print (df1)

     doc_ids
word
w1       [1]
w2    [1, 2]
w3       [2]
w4    [3, 4]
w5       [3]
w6       [4]
</code>```

Body:
I have a

I want to change the dataframe into the format like

Could you tell me how to code with pandas, is there any built-in function in pandas which can be used to do it.

doc_term_frame=pd.DataFrame(data={'doc_id':[1,2,3,4],'words':[['w1','w2'],['w2','w3'],['w4','w5'],['w4','w6']]}).set_index('doc_id')
desired_frame=pd.DataFrame(data={'word':['w1','w2','w3','w4','w5','w6'],'doc_ids':[[1],[1,2],[2],[3,4],[3],[4]]}).set_index('word')

Body:
You can use DataFrame constructor for creating convert lists to rows, then reshape by stack, create columns from index by reseting index, groupby and create list. Last convert Series to DataFrame by to_frame:

df1 = pd.DataFrame(doc_term_frame['words'].values.tolist(), index=doc_term_frame.index)
        .stack()
        .reset_index(name='word')
        .groupby('word')['doc_id']
        .apply(list)
        .to_frame(name='doc_ids')
print (df1)

     doc_ids
word
w1       [1]
w2    [1, 2]
w3       [2]
w4    [3, 4]
w5       [3]
w6       [4]


问:
Bind Param with array of parameters
I have a function that does this:

```<code>function registerUser($firstName, $lastName, $address, $postcode, $email, $password)
{
    $params = array($firstName, $lastName, $address, $postcode, $email, $password);
    $result = $this->db->bind("INSERT INTO Users VALUES (?, ?, ?, ?, ?, ?)", 'ssssss', $params);
}
</code>```

Which sends off to my database class, which does this:

```<code>public function bind($query, $type, $params)
{
    $this->query = $query;
    $stmt = $this->mysqli->prepare($this->query);
    $stmt->bind_param($type, $param);
    $stmt->execute;
}
</code>```

The problem is this doesn't work.

What I was hoping to do, was to take the $params list and have it list them after the $type, so that the query would resemble:

```<code>$stmt->bind_param('ssssss', $firstName, $lastName, $address, $postcode, $email, $password);
</code>```

But obviously I'm going about it the wrong way.

is there a way to make the array...transform as it were, into a list to be printed out at the bind_param query stage?

答:
As of PHP 5.6 you can utilize argument unpacking as an alternative to call_user_func_array, and is often 3 to 4 times faster.

```<code><?php
function foo ($a, $b) {
     return $a + $b;
}

$func = 'foo';
$values = array(1, 2);
call_user_func_array($func, $values);
//returns 3

$func(...$values);
//returns 3
?>
</code>```

Taken from here.

So your code should look something like this:

```<code>public function bind($query, $type, $params)
        {

            $this->query = $query;
            $stmt = $this->mysqli->prepare($this->query);
            $stmt->bind_param($type, ...$params);
            $stmt->execute;
        }
</code>```

Title: Bind Param with array of parameters

Body:
I have a function that does this:

function registerUser($firstName, $lastName, $address, $postcode, $email, $password)
{
    $params = array($firstName, $lastName, $address, $postcode, $email, $password);
    $result = $this->db->bind("INSERT INTO Users VALUES (?, ?, ?, ?, ?, ?)", 'ssssss', $params);
}

Which sends off to my database class, which does this:

public function bind($query, $type, $params)
{
    $this->query = $query;
    $stmt = $this->mysqli->prepare($this->query);
    $stmt->bind_param($type, $param);
    $stmt->execute;
}

The problem is this doesn't work.

What I was hoping to do, was to take the $params list and have it list them after the $type, so that the query would resemble:

$stmt->bind_param('ssssss', $firstName, $lastName, $address, $postcode, $email, $password);

But obviously I'm going about it the wrong way.

is there a way to make the array...transform as it were, into a list to be printed out at the bind_param query stage?

Body:
As of PHP 5.6 you can utilize argument unpacking as an alternative to call_user_func_array, and is often 3 to 4 times faster.

<?php
function foo ($a, $b) {
     return $a + $b;
}

$func = 'foo';
$values = array(1, 2);
call_user_func_array($func, $values);
//returns 3

$func(...$values);
//returns 3
?>

Taken from here.

So your code should look something like this:

public function bind($query, $type, $params)
        {

            $this->query = $query;
            $stmt = $this->mysqli->prepare($this->query);
            $stmt->bind_param($type, ...$params);
            $stmt->execute;
        }


问:
Remove number from large string in specific position [PHP RegEx]
I have a large string (multiple lines) I need to find numbers in with regex. The position the number I need is always proceeded/follow by an exact order of characters so I can use non-capturing matches to pinpoint the exact number I need. I put together a regex to get this number but it refuses to work and I can't figure it out!

Below is a small bit of php code that I can't get to work showing the basic format of what i need

```<code>$sTestData = 'lak sjdhfklsjaf<?kjnsdfh461uihrfkjsn+%5Bmlknsadlfjncas dlk';

$sNumberStripRE = '/.*?(?:sjdhfklsjaf<\\?kjnsdfh)(\\d+)(?:uihrfkjsn\\+%5Bmlknsadlfjncas).*?/gim';

if (preg_match_all($sNumberStripRE, $sTestData, $aMatches))
{
    var_dump($aMatches);
}
</code>```

the number I need is 461 and the characters before/after the spaces on either side of this number are always the same

any help getting the above regex working would be great!

This link RegExr: My Reg Ex (to an online regex genereator and my regex) shows that it should work!

答:
g is an invalid modifier, drop it.

Ideone Link

Body:
I have a large string (multiple lines) I need to find numbers in with regex. The position the number I need is always proceeded/follow by an exact order of characters so I can use non-capturing matches to pinpoint the exact number I need. I put together a regex to get this number but it refuses to work and I can't figure it out!

Below is a small bit of php code that I can't get to work showing the basic format of what i need

$sTestData = 'lak sjdhfklsjaf<?kjnsdfh461uihrfkjsn+%5Bmlknsadlfjncas dlk';

$sNumberStripRE = '/.*?(?:sjdhfklsjaf<\\?kjnsdfh)(\\d+)(?:uihrfkjsn\\+%5Bmlknsadlfjncas).*?/gim';

if (preg_match_all($sNumberStripRE, $sTestData, $aMatches))
{
    var_dump($aMatches);
}

the number I need is 461 and the characters before/after the spaces on either side of this number are always the same

any help getting the above regex working would be great!

This link RegExr: My Reg Ex (to an online regex genereator and my regex) shows that it should work!