问:
Response.Redirect Fails But then Works on Refresh IIS Express VS2013
I have an ASP.NET project in Visual Studio 2013, running locally in IIExpress (Version 8.08418.0) for testing.

The main page (adminDefault.aspx) redirects user to Login.aspx to authenticate (which is done silently based on userID that was passed to adminDefault.aspx as a url variable). The login page sends it back to adminDefault.aspx upon successful authentication. Default then loads data into a Gridview.

The whole process takes about 15 seconds.

When I run this from Visual Studio 2013, I get an error "This page can't be displayed" in about 4 seconds. But if I manually hit refresh, after working for a bit, everything comes in fine.

In my code, suspecting a timeout, I implicitly set this long enough to run through everything:

```<code> if (!this.IsPostBack)
            {

                Session.Timeout = 120;  // seconds before timeout
                try
                {
                    // OnUser should have been set from Login.asp. If it is null, send to Login
                    MembershipUser onUser = Membership.GetUser();
                    if (onUser == null)
                    {
                        Response.Redirect("/login.aspx", true);
                    }
                    else
                    {
                        String currentUserName = Membership.GetUser().UserName;
                        userRoles = Roles.GetRolesForUser(Membership.GetUser().UserName);
                    }
                }
</code>```

Even if the Session.Timeout is being ignored, the default is 20 Seconds, so I would expect it to work anyway.

So:
1) Why is the first run through failing?
2) Is there a way I can prevent it? Failing that can I catch the page not found, and refresh automatically?

EDIT: This has something to do with the trip to Login.aspx and back. If I remove Response.Redirect("/login.aspx", true);
Then this works as expected. The problem is, I need the Login.aspx for validation. Anyone have any thoughts as to why the trip to Login and back is not working... and then does upon refresh?

When I try to run this in Chrome, I don't get as far. Chrome shows me this:

Hitting the here just cycles for a moment and comes back to the screen.

The Developer Tool on IE are not helpful (at least that i can see) in this case. When I run my project in the debugger, it launches a new IE session. Before I can turn on developer tools and press "Play" to record events, the session has given me "Cannot display the page" error. Of course I can hit "play" in the tools and then refresh, but of course everything runs then without error. The refresh makes everything run right. I need to discover why it fails before then.

EDIT: This is the Login.aspx and Web.Security Code. I didn't write it, but it looks boilerplate:

```<code>  protected void Page_Load(object sender, EventArgs e)
    {
            string userName = "";
            bool authenticated = FormsAuthentication.Authenticate(ref userName);
            if (authenticated)
                {
                    FormsAuthentication.RedirectFromLoginPage(userName, false);
                }
     }
</code>```

And the Authentication code looks like this:

```<code>        /// <summary>
    /// Validates a user based on the  session id found in the ReturnURL against credentials stored in the ASP.NET membership.
    /// </summary>
    /// <param name="userName">The user name.</param>
    /// <returns>true if the user name and password are valid; otherwise, false.</returns>
    public static bool Authenticate(ref string userName)
    {
        bool Authenticated = Authenticate(ref userName, GetSessionId());
        return Authenticated;
    }

    /// <summary>
    /// Redirects an authenticated user back to the originally requested URL or the default URL using the specified cookie path for the forms-authentication cookie.
    /// </summary>
    /// <param name="userName">The authenticated user name. </param>
    /// <param name="createPersistentCookie">true to create a durable cookie (one that is saved across browser sessions); otherwise, false. </param>
    /// <param name="strCookiePath">The cookie path for the forms-authentication ticket. </param>
    public static void RedirectFromLoginPage(string userName, bool createPersistentCookie, string strCookiePath)
    {
        System.Web.Security.FormsAuthentication.SetAuthCookie(userName, false, strCookiePath);

        // Redirect back to request page.
        HttpContext.Current.Response.Redirect(GetRedirectUrl());
    }
</code>```

答:
Based on your application circumstance in the comments, you cannot manage the authentication/authorization via web.config. And, Membership class is usually accessed if you have your custom provider, it's not the default way of accessing logged in users. So do either one of those:

Check the logged in user in your if statement the following way:

```<code> if (User.Identity.IsAuthenticated)
 {
    Response.Redirect("/login.aspx", true);
 }
 else
 {
    String currentUserName = Use User.Identity.Name; // accessing the logged in uer
    userRoles = Roles.GetRolesForUser(currentUserName); // not sure about this step, have you added your roles to web.Config? or from where you get them
 }
</code>```

Depends on how your ERP integrates with your app (you should be using a custom provider), check where the users get authenticated. (ex. who is calling Membership.ValidateUser(strUsername,strPassword) . And make sure your login.aspx page is updating the session state.

Check this page for more information about implementing a custom provider

Body:
I have an ASP.NET project in Visual Studio 2013, running locally in IIExpress (Version 8.08418.0) for testing.

The main page (adminDefault.aspx) redirects user to Login.aspx to authenticate (which is done silently based on userID that was passed to adminDefault.aspx as a url variable). The login page sends it back to adminDefault.aspx upon successful authentication. Default then loads data into a Gridview.

The whole process takes about 15 seconds.

When I run this from Visual Studio 2013, I get an error "This page can't be displayed" in about 4 seconds. But if I manually hit refresh, after working for a bit, everything comes in fine.

In my code, suspecting a timeout, I implicitly set this long enough to run through everything:

 if (!this.IsPostBack)
            {

                Session.Timeout = 120;  // seconds before timeout
                try
                {
                    // OnUser should have been set from Login.asp. If it is null, send to Login
                    MembershipUser onUser = Membership.GetUser();
                    if (onUser == null)
                    {
                        Response.Redirect("/login.aspx", true);
                    }
                    else
                    {
                        String currentUserName = Membership.GetUser().UserName;
                        userRoles = Roles.GetRolesForUser(Membership.GetUser().UserName);
                    }
                }

Even if the Session.Timeout is being ignored, the default is 20 Seconds, so I would expect it to work anyway.

So:
1) Why is the first run through failing?
2) Is there a way I can prevent it? Failing that can I catch the page not found, and refresh automatically?

EDIT: This has something to do with the trip to Login.aspx and back. If I remove Response.Redirect("/login.aspx", true);
Then this works as expected. The problem is, I need the Login.aspx for validation. Anyone have any thoughts as to why the trip to Login and back is not working... and then does upon refresh?

When I try to run this in Chrome, I don't get as far. Chrome shows me this:

Hitting the here just cycles for a moment and comes back to the screen.

The Developer Tool on IE are not helpful (at least that i can see) in this case. When I run my project in the debugger, it launches a new IE session. Before I can turn on developer tools and press "Play" to record events, the session has given me "Cannot display the page" error. Of course I can hit "play" in the tools and then refresh, but of course everything runs then without error. The refresh makes everything run right. I need to discover why it fails before then.

EDIT: This is the Login.aspx and Web.Security Code. I didn't write it, but it looks boilerplate:

  protected void Page_Load(object sender, EventArgs e)
    {
            string userName = "";
            bool authenticated = FormsAuthentication.Authenticate(ref userName);
            if (authenticated)
                {
                    FormsAuthentication.RedirectFromLoginPage(userName, false);
                }
     }

And the Authentication code looks like this:

        ///
    /// Validates a user based on the  session id found in the ReturnURL against credentials stored in the ASP.NET membership.
    ///
    /// <param name="userName">The user name.</param>
    /// <returns>true if the user name and password are valid; otherwise, false.</returns>
    public static bool Authenticate(ref string userName)
    {
        bool Authenticated = Authenticate(ref userName, GetSessionId());
        return Authenticated;
    }

    ///
    /// Redirects an authenticated user back to the originally requested URL or the default URL using the specified cookie path for the forms-authentication cookie.
    ///
    /// <param name="userName">The authenticated user name. </param>
    /// <param name="createPersistentCookie">true to create a durable cookie (one that is saved across browser sessions); otherwise, false. </param>
    /// <param name="strCookiePath">The cookie path for the forms-authentication ticket. </param>
    public static void RedirectFromLoginPage(string userName, bool createPersistentCookie, string strCookiePath)
    {
        System.Web.Security.FormsAuthentication.SetAuthCookie(userName, false, strCookiePath);

        // Redirect back to request page.
        HttpContext.Current.Response.Redirect(GetRedirectUrl());
    }

Body:
Based on your application circumstance in the comments, you cannot manage the authentication/authorization via web.config. And, Membership class is usually accessed if you have your custom provider, it's not the default way of accessing logged in users. So do either one of those:

Check the logged in user in your if statement the following way:

 if (User.Identity.IsAuthenticated)
 {
    Response.Redirect("/login.aspx", true);
 }
 else
 {
    String currentUserName = Use User.Identity.Name; // accessing the logged in uer
    userRoles = Roles.GetRolesForUser(currentUserName); // not sure about this step, have you added your roles to web.Config? or from where you get them
 }

Depends on how your ERP integrates with your app (you should be using a custom provider), check where the users get authenticated. (ex. who is calling Membership.ValidateUser(strUsername,strPassword) . And make sure your login.aspx page is updating the session state.

Check this page for more information about implementing a custom provider


来源: stackexchange

问:
XML TO XML using XSL
I have trouble trying to convert this xml format

```<code><?xml version="1.0" standalone="yes"?>
<_InventoryProgram_0_1DataSet xmlns="http://tempuri.org/_InventoryProgram_0_1DataSet.xsd">
    <ΠΡΟΙΟΝΤΑ>
    <unique_id>test</unique_id>
    <title>test</title>
    <description>test</description>
    <category_id>test</category_id>
    <price>test</price>
    <make>test</make>
    <model>test</model>
    <yearfrom>test</yearfrom>
    <yearto>test</yearto>
  </ΠΡΟΙΟΝΤΑ>
  <ΠΡΟΙΟΝΤΑ>
    <unique_id>test</unique_id>
    <title>test</title>
    <description>test</description>
    <category_id>test</category_id>
    <price>test</price>
    <make>test</make>
    <model>test</model>
    <yearfrom>test</yearfrom>
    <yearto>test</yearto>
  </ΠΡΟΙΟΝΤΑ>
  <ΠΡΟΙΟΝΤΑ>
    <unique_id>test</unique_id>
    <title>test</title>
    <description>test</description>
    <category_id>test</category_id>
    <price>test</price>
    <make>test</make>
    <model>test</model>
    <yearfrom>test</yearfrom>
    <yearto>test</yearto>
    <photo>test</photo>
    <condition>test</condition>
    <update_interval>test</update_interval>
  </ΠΡΟΙΟΝΤΑ>
</_InventoryProgram_0_1DataSet>
</code>```

Into this xml format

```<code><?xml version="1.0" encoding="UTF-8"?>
<cardealer>
    <lastupdate>2017-12-05T22:03:05Z</lastupdate>
    <classifieds>
        <classified>
            <unique_id>test</unique_id>
            <title><![CDATA[test]]></title>
            <description><![test]]></description>
            <category_id>test</category_id>
            <price>test</price>
            <makemodels>
                <makemodel>
                    <make>test</make>
                    <model>test</model>
                    <yearfrom>test</yearfrom>
                    <yearto>test</yearto>
                </makemodel>
            </makemodels>
            <photos>
                <photo>
                    test
                </photo>
            </photos>
            <condition>test</condition>
            <update_interval>test</update_interval>
        </classified>
    </classifieds>
</cardealer>
</code>```

I have tried this with disasterus results... It just erases everything and gives me the raw data!

```<code><?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" >
    <xsl:output method="xml" encoding="UTF-8" indent="yes"/>
    <xsl:template match="/_InventoryProgram_0_1DataSet">
        <cardealer>
            <classifieds>
                <xsl:for-each select="ΠΡΟΙΟΝΤΑ">
                    <classified>
                        <xsl:for-each select="unique_id">
                            <unique_id>
                                <xsl:value-of select="."/>
                            </unique_id>
                        </xsl:for-each>
                        <xsl:for-each select="title">
                            <title>
                                <xsl:value-of select="."/>
                            </title>
                        </xsl:for-each>
                        <xsl:for-each select="description">
                            <description>
                                <xsl:value-of select="."/>
                            </description>
                        </xsl:for-each>
                        <xsl:for-each select="category_id">
                            <category_id>
                                <xsl:value-of select="."/>
                            </category_id>
                        </xsl:for-each>
                        <xsl:for-each select="price">
                            <price>
                                <xsl:value-of select="."/>
                            </price>
                        </xsl:for-each>
                        <makemodels>
                            <makemodel>
                                <xsl:for-each select="make">
                                    <make>
                                        <xsl:value-of select="."/>
                                    </make>
                                </xsl:for-each>
                                <xsl:for-each select="model">
                                    <model>
                                        <xsl:value-of select="."/>
                                    </model>
                                </xsl:for-each>
                                <xsl:for-each select="yearfrom">
                                    <yearfrom>
                                        <xsl:value-of select="."/>
                                    </yearfrom>
                                </xsl:for-each>
                                <xsl:for-each select="yearto">
                                    <yearto>
                                        <xsl:value-of select="."/>
                                    </yearto>
                                </xsl:for-each>
                            </makemodel>
                        </makemodels>
                    </classified>
                </xsl:for-each>
            </classifieds>
        </cardealer>
    </xsl:template>
</xsl:stylesheet>
</code>```

These xmls are just an example of the export(first) of a long output from a product data-table , and the second only an example of one product, but i wish this format could be applied to all the products of the first , no matter how many.

Is the XSL the correct way? Is this even possible or there is a better one? This is in a C# program Btw.

答:
Your input has a namespace and you didn't reference it... some of your xpaths were also wrong.

Stylesheet

```<code><?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0"
                xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                xmlns:ds="http://tempuri.org/_InventoryProgram_0_1DataSet.xsd"
                exclude-result-prefixes="ds xsl"
                >
  <xsl:output method="xml"
              encoding="UTF-8"
              indent="yes"/>
  <xsl:template match="/">
    <cardealer>
      <classifieds>
        <xsl:apply-templates select="//ds:ΠΡΟΙΟΝΤΑ" />
      </classifieds>
    </cardealer>
  </xsl:template>

  <xsl:template match="ds:ΠΡΟΙΟΝΤΑ">
    <classified>
      <unique_id>
        <xsl:value-of select="ds:unique_id"/>
      </unique_id>
      <title>
        <xsl:value-of select="ds:title"/>
      </title>
      <description>
        <xsl:value-of select="ds:description"/>
      </description>
      <category_id>
        <xsl:value-of select="ds:category_id"/>
      </category_id>
      <price>
        <xsl:value-of select="ds:price"/>
      </price>
      <makemodels>
        <makemodel>
          <make>
            <xsl:value-of select="ds:make"/>
          </make>
          <model>
            <xsl:value-of select="ds:model"/>
          </model>
          <yearfrom>
            <xsl:value-of select="ds:yearfrom"/>
          </yearfrom>
          <yearto>
            <xsl:value-of select="ds:yearto"/>
          </yearto>
        </makemodel>
      </makemodels>
    </classified>
  </xsl:template>
</xsl:stylesheet>
</code>```

Example

```<code><?xml version="1.0" encoding="utf-8"?>
<cardealer>
  <classifieds>
    <classified>
      <unique_id>test</unique_id>
      <title>test</title>
      <description>test</description>
      <category_id>test</category_id>
      <price>test</price>
      <makemodels>
        <makemodel>
          <make>test</make>
          <model>test</model>
          <yearfrom>test</yearfrom>
          <yearto>test</yearto>
        </makemodel>
      </makemodels>
    </classified>
    <classified>
      <unique_id>test</unique_id>
      <title>test</title>
      <description>test</description>
      <category_id>test</category_id>
      <price>test</price>
      <makemodels>
        <makemodel>
          <make>test</make>
          <model>test</model>
          <yearfrom>test</yearfrom>
          <yearto>test</yearto>
        </makemodel>
      </makemodels>
    </classified>
    <classified>
      <unique_id>test</unique_id>
      <title>test</title>
      <description>test</description>
      <category_id>test</category_id>
      <price>test</price>
      <makemodels>
        <makemodel>
          <make>test</make>
          <model>test</model>
          <yearfrom>test</yearfrom>
          <yearto>test</yearto>
        </makemodel>
      </makemodels>
    </classified>
  </classifieds>
</cardealer>
</code>```

ContentLicense: CC BY-SA 3.0

Title: XML TO XML using XSL

Body:
I have trouble trying to convert this xml format

<?xml version="1.0" standalone="yes"?>
<_InventoryProgram_0_1DataSet xmlns="http://tempuri.org/_InventoryProgram_0_1DataSet.xsd">
    <ΠΡΟΙΟΝΤΑ>
    <unique_id>test</unique_id>
    <title>test</title>
    <description>test</description>
    <category_id>test</category_id>
    <price>test</price>
    <make>test</make>
    <model>test</model>
    <yearfrom>test</yearfrom>
    <yearto>test</yearto>
  </ΠΡΟΙΟΝΤΑ>
  <ΠΡΟΙΟΝΤΑ>
    <unique_id>test</unique_id>
    <title>test</title>
    <description>test</description>
    <category_id>test</category_id>
    <price>test</price>
    <make>test</make>
    <model>test</model>
    <yearfrom>test</yearfrom>
    <yearto>test</yearto>
  </ΠΡΟΙΟΝΤΑ>
  <ΠΡΟΙΟΝΤΑ>
    <unique_id>test</unique_id>
    <title>test</title>
    <description>test</description>
    <category_id>test</category_id>
    <price>test</price>
    <make>test</make>
    <model>test</model>
    <yearfrom>test</yearfrom>
    <yearto>test</yearto>
    <photo>test</photo>
    <condition>test</condition>
    <update_interval>test</update_interval>
  </ΠΡΟΙΟΝΤΑ>
</_InventoryProgram_0_1DataSet>

Into this xml format

<?xml version="1.0" encoding="UTF-8"?>
<cardealer>
    <lastupdate>2017-12-05T22:03:05Z</lastupdate>
    <classifieds>
        <classified>
            <unique_id>test</unique_id>
            <title><![CDATA[test]]></title>
            <description><![test]]></description>
            <category_id>test</category_id>
            <price>test</price>
            <makemodels>
                <makemodel>
                    <make>test</make>
                    <model>test</model>
                    <yearfrom>test</yearfrom>
                    <yearto>test</yearto>
                </makemodel>
            </makemodels>
            <photos>
                <photo>
                    test
                </photo>
            </photos>
            <condition>test</condition>
            <update_interval>test</update_interval>
        </classified>
    </classifieds>
</cardealer>

I have tried this with disasterus results... It just erases everything and gives me the raw data!

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" >
    <xsl:output method="xml" encoding="UTF-8" indent="yes"/>
    <xsl:template match="/_InventoryProgram_0_1DataSet">
        <cardealer>
            <classifieds>
                <xsl:for-each select="ΠΡΟΙΟΝΤΑ">
                    <classified>
                        <xsl:for-each select="unique_id">
                            <unique_id>
                                <xsl:value-of select="."/>
                            </unique_id>
                        </xsl:for-each>
                        <xsl:for-each select="title">
                            <title>
                                <xsl:value-of select="."/>
                            </title>
                        </xsl:for-each>
                        <xsl:for-each select="description">
                            <description>
                                <xsl:value-of select="."/>
                            </description>
                        </xsl:for-each>
                        <xsl:for-each select="category_id">
                            <category_id>
                                <xsl:value-of select="."/>
                            </category_id>
                        </xsl:for-each>
                        <xsl:for-each select="price">
                            <price>
                                <xsl:value-of select="."/>
                            </price>
                        </xsl:for-each>
                        <makemodels>
                            <makemodel>
                                <xsl:for-each select="make">
                                    <make>
                                        <xsl:value-of select="."/>
                                    </make>
                                </xsl:for-each>
                                <xsl:for-each select="model">
                                    <model>
                                        <xsl:value-of select="."/>
                                    </model>
                                </xsl:for-each>
                                <xsl:for-each select="yearfrom">
                                    <yearfrom>
                                        <xsl:value-of select="."/>
                                    </yearfrom>
                                </xsl:for-each>
                                <xsl:for-each select="yearto">
                                    <yearto>
                                        <xsl:value-of select="."/>
                                    </yearto>
                                </xsl:for-each>
                            </makemodel>
                        </makemodels>
                    </classified>
                </xsl:for-each>
            </classifieds>
        </cardealer>
    </xsl:template>
</xsl:stylesheet>

These xmls are just an example of the export(first) of a long output from a product data-table , and the second only an example of one product, but i wish this format could be applied to all the products of the first , no matter how many.

Is the XSL the correct way? Is this even possible or there is a better one? This is in a C# program Btw.

Body:
Your input has a namespace and you didn't reference it... some of your xpaths were also wrong.

Stylesheet

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0"
                xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                xmlns:ds="http://tempuri.org/_InventoryProgram_0_1DataSet.xsd"
                exclude-result-prefixes="ds xsl"
                >
  <xsl:output method="xml"
              encoding="UTF-8"
              indent="yes"/>
  <xsl:template match="/">
    <cardealer>
      <classifieds>
        <xsl:apply-templates select="//ds:ΠΡΟΙΟΝΤΑ" />
      </classifieds>
    </cardealer>
  </xsl:template>

  <xsl:template match="ds:ΠΡΟΙΟΝΤΑ">
    <classified>
      <unique_id>
        <xsl:value-of select="ds:unique_id"/>
      </unique_id>
      <title>
        <xsl:value-of select="ds:title"/>
      </title>
      <description>
        <xsl:value-of select="ds:description"/>
      </description>
      <category_id>
        <xsl:value-of select="ds:category_id"/>
      </category_id>
      <price>
        <xsl:value-of select="ds:price"/>
      </price>
      <makemodels>
        <makemodel>
          <make>
            <xsl:value-of select="ds:make"/>
          </make>
          <model>
            <xsl:value-of select="ds:model"/>
          </model>
          <yearfrom>
            <xsl:value-of select="ds:yearfrom"/>
          </yearfrom>
          <yearto>
            <xsl:value-of select="ds:yearto"/>
          </yearto>
        </makemodel>
      </makemodels>
    </classified>
  </xsl:template>
</xsl:stylesheet>

Example

<?xml version="1.0" encoding="utf-8"?>
<cardealer>
  <classifieds>
    <classified>
      <unique_id>test</unique_id>
      <title>test</title>
      <description>test</description>
      <category_id>test</category_id>
      <price>test</price>
      <makemodels>
        <makemodel>
          <make>test</make>
          <model>test</model>
          <yearfrom>test</yearfrom>
          <yearto>test</yearto>
        </makemodel>
      </makemodels>
    </classified>
    <classified>
      <unique_id>test</unique_id>
      <title>test</title>
      <description>test</description>
      <category_id>test</category_id>
      <price>test</price>
      <makemodels>
        <makemodel>
          <make>test</make>
          <model>test</model>
          <yearfrom>test</yearfrom>
          <yearto>test</yearto>
        </makemodel>
      </makemodels>
    </classified>
    <classified>
      <unique_id>test</unique_id>
      <title>test</title>
      <description>test</description>
      <category_id>test</category_id>
      <price>test</price>
      <makemodels>
        <makemodel>
          <make>test</make>
          <model>test</model>
          <yearfrom>test</yearfrom>
          <yearto>test</yearto>
        </makemodel>
      </makemodels>
    </classified>
  </classifieds>
</cardealer>


问:
Compare end punctuation in columns A and B in Excel (VBA?)
I'm trying to catch and resolve instances in Excel where the end punctuation (in my case an empty line) in cells in column B doesn't match the end punctuation in cells in column A. For background, column A contains English text and column B contains translated version of the very same content. The problem is - in some cases the source text has empty/blank lines at the end of text in cells, while some translated text doesn't and I need to find and fix those instances.

So, I'm trying to:

1) Compare the last line of each cell in column A to the adjacent cell in the same row in column B.

2) If the cell in column A has a blank line at the end and corresponding cell in column B doesn't, add such blank line to the end of cell in column B.

Example:

```<code>         **Column A**    **Column B**
Row 1       Text X          Text Y
            \n
Row 2       Text X          Text Y
Row 3       Text X          Text Y
            \n
Row 4       Text X          Text Y
            \n              \n
</code>```

So, in the example above, I need to flag cells B1 and B3 because they don't have a line feed (\n) at the end, similar to their counterparts in cells A1 and A3.

Thank you in advance!

答:
Use column C to find line termination mismatches:

```<code>=(CODE(RIGHT(A1,1))=10)<>(CODE(RIGHT(B1,1))=10)
</code>```

Copy the formula down to all rows and filter on TRUE.

Body:
I'm trying to catch and resolve instances in Excel where the end punctuation (in my case an empty line) in cells in column B doesn't match the end punctuation in cells in column A. For background, column A contains English text and column B contains translated version of the very same content. The problem is - in some cases the source text has empty/blank lines at the end of text in cells, while some translated text doesn't and I need to find and fix those instances.

So, I'm trying to:

1) Compare the last line of each cell in column A to the adjacent cell in the same row in column B.

2) If the cell in column A has a blank line at the end and corresponding cell in column B doesn't, add such blank line to the end of cell in column B.

Example:

         **Column A**    **Column B**
Row 1       Text X          Text Y
            \n
Row 2       Text X          Text Y
Row 3       Text X          Text Y
            \n
Row 4       Text X          Text Y
            \n              \n

So, in the example above, I need to flag cells B1 and B3 because they don't have a line feed (\n) at the end, similar to their counterparts in cells A1 and A3.

Thank you in advance!

Body:
Use column C to find line termination mismatches:

=(CODE(RIGHT(A1,1))=10)<>(CODE(RIGHT(B1,1))=10)

Copy the formula down to all rows and filter on TRUE.


问:
How can I get a program working with missing references?
I've got the code for project written with a vb.net, .net Framework 2.0, Windows Form Application.  I'm trying to get it working in Visual Studio 2015.  When I open it up, I'm missing several references.  I try to compile (Clean/Rebuild) it, and get multiple errors.  I've looked up the files online, but all I can find are sites saying I need to reinstall them.  I don't have the dll's and don't have any idea what these do (except that they vaguely are Microsoft related).  Can someone tell me how to get the program working or how to find the files?

Here are the missing references:

AxInterop.MSDataGridLib

AxMSDataGridLib

DAO

Interop.MSDataGridLib

Microsoft.ReportVeiwer.WinForms

Microsoft.Vbe.Interop

MSDataGridLib

MSDataReportLib

MSDATASRC

Here is the error I get when I rebuild the solution:

1>------ Rebuild All started: Project: RTS, Configuration: Release Any CPU ------
1>C:\Program Files (x86)\MSBuild\14.0\bin\Microsoft.Common.CurrentVersion.targets(1819,5): warning MSB3245: Could not resolve this reference. Could not locate the assembly "AxInterop.MSDataGridLib". Check to make sure the assembly exists on disk. If this reference is required by your code, you may get compilation errors.
1>C:\Program Files (x86)\MSBuild\14.0\bin\Microsoft.Common.CurrentVersion.targets(1819,5): warning MSB3245: Could not resolve this reference. Could not locate the assembly "Interop.MSDataGridLib". Check to make sure the assembly exists on disk. If this reference is required by your code, you may get compilation errors.
1>C:\Program Files (x86)\MSBuild\14.0\bin\Microsoft.Common.CurrentVersion.targets(2398,5): warning MSB3284: Cannot get the file path for type library "cde57a40-8b86-11d0-b3c6-00a0c90aea82" version 1.0. Library not registered. (Exception from HRESULT: 0x8002801D (TYPE_E_LIBNOTREGISTERED))
1>C:\Program Files (x86)\MSBuild\14.0\bin\Microsoft.Common.CurrentVersion.targets(2398,5): warning MSB3284: Cannot get the file path for type library "00025e01-0000-0000-c000-000000000046" version 4.0. Library not registered. (Exception from HRESULT: 0x8002801D (TYPE_E_LIBNOTREGISTERED))
1>C:\Program Files (x86)\MSBuild\14.0\bin\Microsoft.Common.CurrentVersion.targets(2398,5): warning MSB3284: Cannot get the file path for type library "cde57a40-8b86-11d0-b3c6-00a0c90aea82" version 1.0. Library not registered. (Exception from HRESULT: 0x8002801D (TYPE_E_LIBNOTREGISTERED))
1>C:\Program Files (x86)\MSBuild\14.0\bin\Microsoft.Common.CurrentVersion.targets(2398,5): warning MSB3284: Cannot get the file path for type library "642ac760-aab4-11d0-8494-00a0c90dc8a9" version 1.0. Library not registered. (Exception from HRESULT: 0x8002801D (TYPE_E_LIBNOTREGISTERED))
1>C:\Program Files (x86)\MSBuild\14.0\bin\Microsoft.Common.CurrentVersion.targets(2398,5): warning MSB3283: Cannot find wrapper assembly for type library "MSDATASRC". Verify that (1) the COM component is registered correctly and (2) your target platform is the same as the bitness of the COM component. For example, if the COM component is 32-bit, your target platform must not be 64-bit.
========== Rebuild All: 0 succeeded, 1 failed, 0 skipped ==========

Here is the image showing broken references:

答: You will need the Microsoft Office Primary Interop Assemblies for Interop with MS Office. Which package depends on the version of Office you are running: Microsoft Office PIA Website</p>


问:
States not getting stored in database using city-state gem in ruby on rails
so I am using a gem called city-state gem in my web application to populate a dropdown list with the 50 states of US, but I am unable to save the selected value in the database,maybe I am missing something here, I have the following code:

```<code><%= form_for(resource, as: resource_name, :class=>'well form-horizontal' ,:style=>"margin-top:30px",url: registration_path(resource_name)) do |f| %>
  <select name="form[state]">
    <% CS.states(:us).each do |key, value| %>
      <option value="<%= key %>"><%= value %></option>
    <% end %>
  </select>
<% end %>
</code>```

I tried using

```<code><%= f.select :state, value %>
</code>```

but that would give me an empty dropdown list, any help appreciated.Thanks in advance.

```<code>Processing by Devise::RegistrationsController#create as HTML
Parameters: {"utf8"=>"✓","authenticity_token"=>"w1dXvna7zYZ96f9pNtCdm3ruIHu/J9+kXZ6rxoPy+7QJCqTDAs+Y1ZcOgUvRiJEEZpyJ3S0qpLEbfoKEr+15bw==", "user"=>{"firstname"=>"Han", "lastname"=>"Park", "gender"=>"Male", "dob(1i)"=>"1996", "dob(2i)"=>"12", "dob(3i)"=>"6", "ssn"=>"1432229824", "driver_license"=>"D768765764", "street_address"=>"1000 north", "city"=>"New York", "zip"=>"60098", "email"=>"han@gmail.com", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]", "tandc"=>"true"}, "state"=>"MD", "commit"=>"Sign Up"}
DEPRECATION WARNING: ssn is not an attribute known to Active Record. This
behavior is deprecated and will be removed in the next version of Rails. If
you'd like ssn to be managed by Active Record, add `attribute :ssn to your
class. (called from block in attr_encrypted at /Users/reynold/.rvm/gems/ruby-
2.2.2/gems/attr_encrypted-
3.0.3/lib/attr_encrypted/adapters/active_record.rb:75)
(0.3ms)  BEGIN
User Exists (0.8ms)  SELECT  1 AS one FROM "users" WHERE "users"."email" = $1
LIMIT $2  [["email", "han@saveup.com"], ["LIMIT", 1]]
SQL (6.2ms)  INSERT INTO "users" ("email", "encrypted_password", "created_at",
"updated_at", "firstname", "lastname", "gender", "encrypted_ssn",
"encrypted_ssn_iv", "street_address", "city", "zip", "driver_license",
"tandc", "dob") VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12,
$13, $14, $15) RETURNING "id"  [["email", "han@saveup.com"],
["encrypted_password",
"$2a$11$asC6.rG.aYUXJa8Ps.Gbeu3FzTFw64urmIB2KK9rxj94sH71gXaYm"],
["created_at", "2017-12-06 22:17:55.383121"], ["updated_at", "2017-12-06
22:17:55.383121"], ["firstname", "Han"], ["lastname", "Park"], ["gender",
"Male"], ["encrypted_ssn", "eWjL/lDpivR3T9cXx1w6rg==\n"], ["encrypted_ssn_iv",
"Rt/5Tl6PkwvqOjDC9nN1ng==\n"], ["street_address", "1000 north"], ["city",
"New York"], ["zip", "60098"], ["driver_license", "D768765764"], ["tandc",
"t"], ["dob", "1996-12-06"]]
(0.6ms)  COMMIT
(0.3ms)  BEGIN
SQL (2.4ms)  UPDATE "users" SET "sign_in_count" = $1, "current_sign_in_at" =
$2, "last_sign_in_at" = $3, "current_sign_in_ip" = $4, "last_sign_in_ip" = $5,
"updated_at" = $6 WHERE "users"."id" = $7  [["sign_in_count", 1],
["current_sign_in_at", "2017-12-06 22:17:55.397080"], ["last_sign_in_at",
"2017-12-06 22:17:55.397080"], ["current_sign_in_ip", "127.0.0.1/32"],
["last_sign_in_ip", "127.0.0.1/32"], ["updated_at", "2017-12-06
22:17:55.398231"], ["id", 18]]
(0.5ms)  COMMIT
Redirected to http://localhost:3000/
Completed 302 Found in 276ms (ActiveRecord: 11.1ms)

Started GET "/" for 127.0.0.1 at 2017-12-06 16:17:55 -0600
User Load (0.8ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1
ORDER BY "users"."id" ASC LIMIT $2  [["id", 18], ["LIMIT", 1]]
Processing by HomeController#roothome as HTML
Rendering home/roothome.html.erb within layouts/application
Rendered shared/_comparechart.html.erb (1.0ms)
Rendered shared/_disclaimer.html.erb (0.7ms)
Rendered home/roothome.html.erb within layouts/application (8.1ms)
Rendered _navbar.html.erb (4.6ms)
Completed 200 OK in 478ms (Views: 474.8ms | ActiveRecord: 0.0ms)
</code>```

答:
I'm guessing (since you didn't show us your controller code) that you expect state to be a part of the user params. But, as you can see, it is not:

```<code>{
  "utf8"=>"✓",
  "authenticity_token"=>"w1dXvna7zYZ96f9pNtCdm3ruIHu/J9+kXZ6rxoPy+7QJCqTDAs+Y1ZcOgUvRiJEEZpyJ3S0qpLEbfoKEr+15bw==",
  "user"=>{
    "firstname"=>"Han",
    "lastname"=>"Park",
    "gender"=>"Male",
    "dob(1i)"=>"1996",
    "dob(2i)"=>"12",
    "dob(3i)"=>"6",
    "ssn"=>"1432229824",
    "driver_license"=>"D768765764",
    "street_address"=>"1000 north",
    "city"=>"New York",
    "zip"=>"60098",
    "email"=>"han@gmail.com",
    "password"=>"[FILTERED]",
    "password_confirmation"=>"[FILTERED]",
    "tandc"=>"true"
  },
  "state"=>"MD",
  "commit"=>"Sign Up"
}
</code>```

I think it's because you do:

```<code><select name="form[state]">
</code>```

You probably want something like:

```<code><select name="user[state]">
</code>```

I'm not sure about that syntax, so you'll have to monkey with it.

Body:
so I am using a gem called city-state gem in my web application to populate a dropdown list with the 50 states of US, but I am unable to save the selected value in the database,maybe I am missing something here, I have the following code:

<%= form_for(resource, as: resource_name, :class=>'well form-horizontal' ,:style=>"margin-top:30px",url: registration_path(resource_name)) do |f| %>
  <select name="form[state]">
    <% CS.states(:us).each do |key, value| %>
      <option value="<%= key %>"><%= value %></option>
    <% end %>
  </select>
<% end %>

I tried using

<%= f.select :state, value %>

but that would give me an empty dropdown list, any help appreciated.Thanks in advance.

Processing by Devise::RegistrationsController#create as HTML
Parameters: {"utf8"=>"✓","authenticity_token"=>"w1dXvna7zYZ96f9pNtCdm3ruIHu/J9+kXZ6rxoPy+7QJCqTDAs+Y1ZcOgUvRiJEEZpyJ3S0qpLEbfoKEr+15bw==", "user"=>{"firstname"=>"Han", "lastname"=>"Park", "gender"=>"Male", "dob(1i)"=>"1996", "dob(2i)"=>"12", "dob(3i)"=>"6", "ssn"=>"1432229824", "driver_license"=>"D768765764", "street_address"=>"1000 north", "city"=>"New York", "zip"=>"60098", "email"=>"han@gmail.com", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]", "tandc"=>"true"}, "state"=>"MD", "commit"=>"Sign Up"}
DEPRECATION WARNING: ssn is not an attribute known to Active Record. This
behavior is deprecated and will be removed in the next version of Rails. If
you'd like ssn to be managed by Active Record, add `attribute :ssn to your
class. (called from block in attr_encrypted at /Users/reynold/.rvm/gems/ruby-
2.2.2/gems/attr_encrypted-
3.0.3/lib/attr_encrypted/adapters/active_record.rb:75)
(0.3ms)  BEGIN
User Exists (0.8ms)  SELECT  1 AS one FROM "users" WHERE "users"."email" = $1
LIMIT $2  [["email", "han@saveup.com"], ["LIMIT", 1]]
SQL (6.2ms)  INSERT INTO "users" ("email", "encrypted_password", "created_at",
"updated_at", "firstname", "lastname", "gender", "encrypted_ssn",
"encrypted_ssn_iv", "street_address", "city", "zip", "driver_license",
"tandc", "dob") VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12,
$13, $14, $15) RETURNING "id"  [["email", "han@saveup.com"],
["encrypted_password",
"$2a$11$asC6.rG.aYUXJa8Ps.Gbeu3FzTFw64urmIB2KK9rxj94sH71gXaYm"],
["created_at", "2017-12-06 22:17:55.383121"], ["updated_at", "2017-12-06
22:17:55.383121"], ["firstname", "Han"], ["lastname", "Park"], ["gender",
"Male"], ["encrypted_ssn", "eWjL/lDpivR3T9cXx1w6rg==\n"], ["encrypted_ssn_iv",
"Rt/5Tl6PkwvqOjDC9nN1ng==\n"], ["street_address", "1000 north"], ["city",
"New York"], ["zip", "60098"], ["driver_license", "D768765764"], ["tandc",
"t"], ["dob", "1996-12-06"]]
(0.6ms)  COMMIT
(0.3ms)  BEGIN
SQL (2.4ms)  UPDATE "users" SET "sign_in_count" = $1, "current_sign_in_at" =
$2, "last_sign_in_at" = $3, "current_sign_in_ip" = $4, "last_sign_in_ip" = $5,
"updated_at" = $6 WHERE "users"."id" = $7  [["sign_in_count", 1],
["current_sign_in_at", "2017-12-06 22:17:55.397080"], ["last_sign_in_at",
"2017-12-06 22:17:55.397080"], ["current_sign_in_ip", "127.0.0.1/32"],
["last_sign_in_ip", "127.0.0.1/32"], ["updated_at", "2017-12-06
22:17:55.398231"], ["id", 18]]
(0.5ms)  COMMIT
Redirected to http://localhost:3000/
Completed 302 Found in 276ms (ActiveRecord: 11.1ms)

Started GET "/" for 127.0.0.1 at 2017-12-06 16:17:55 -0600
User Load (0.8ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1
ORDER BY "users"."id" ASC LIMIT $2  [["id", 18], ["LIMIT", 1]]
Processing by HomeController#roothome as HTML
Rendering home/roothome.html.erb within layouts/application
Rendered shared/_comparechart.html.erb (1.0ms)
Rendered shared/_disclaimer.html.erb (0.7ms)
Rendered home/roothome.html.erb within layouts/application (8.1ms)
Rendered _navbar.html.erb (4.6ms)
Completed 200 OK in 478ms (Views: 474.8ms | ActiveRecord: 0.0ms)

Body:
I'm guessing (since you didn't show us your controller code) that you expect state to be a part of the user params. But, as you can see, it is not:

{
  "utf8"=>"✓",
  "authenticity_token"=>"w1dXvna7zYZ96f9pNtCdm3ruIHu/J9+kXZ6rxoPy+7QJCqTDAs+Y1ZcOgUvRiJEEZpyJ3S0qpLEbfoKEr+15bw==",
  "user"=>{
    "firstname"=>"Han",
    "lastname"=>"Park",
    "gender"=>"Male",
    "dob(1i)"=>"1996",
    "dob(2i)"=>"12",
    "dob(3i)"=>"6",
    "ssn"=>"1432229824",
    "driver_license"=>"D768765764",
    "street_address"=>"1000 north",
    "city"=>"New York",
    "zip"=>"60098",
    "email"=>"han@gmail.com",
    "password"=>"[FILTERED]",
    "password_confirmation"=>"[FILTERED]",
    "tandc"=>"true"
  },
  "state"=>"MD",
  "commit"=>"Sign Up"
}

I think it's because you do:

<select name="form[state]">

You probably want something like:

<select name="user[state]">

I'm not sure about that syntax, so you'll have to monkey with it.


问:
Is it possible to draw a boxplot given the percentile values instead of the original inputs?
From what I can see, boxplot() method expects a sequence of raw values (numbers) as input, from which it then computes percentiles to draw the boxplot(s).

I would like to have a method by which I could pass in the percentiles and get the corresponding boxplot.

For example:

Assume that I have run several benchmarks and for each benchmark I've measured latencies ( floating point values ). Now additionally, I have precomputed the percentiles for these values.

Hence for each benchmark, I have the 25th, 50th, 75th percentile along with the min and max.

Now given these data, I would like to draw the box plots for the benchmarks.

答:
Here is a bottom-up approach where the box_plot is build up using matplotlib's vline, Rectangle, and normal plot functions

```<code>def boxplot(df, ax=None, box_width=0.2, whisker_size=20, mean_size=10, median_size = 10 , line_width=1.5, xoffset=0,
                     color=0):
    """Plots a boxplot from existing percentiles.

    Parameters
    ----------
    df: pandas DataFrame
    ax: pandas AxesSubplot
        if to plot on en existing axes
    box_width: float
    whisker_size: float
        size of the bar at the end of each whisker
    mean_size: float
        size of the mean symbol
    color: int or rgb(list)
        If int particular color of property cycler is taken. Example of rgb: [1,0,0] (red)

    Returns
    -------
    f, a, boxes, vlines, whisker_tips, mean, median
    """

    if type(color) == int:
        color = plt.rcParams['axes.prop_cycle'].by_key()['color'][color]

    if ax:
        a = ax
        f = a.get_figure()
    else:
        f, a = plt.subplots()

    boxes = []
    vlines = []
    xn = []
    for row in df.iterrows():
        x = row[0] + xoffset
        xn.append(x)

        # box
        y = row[1][25]
        height = row[1][75] - row[1][25]
        box = plt.Rectangle((x - box_width / 2, y), box_width, height)
        a.add_patch(box)
        boxes.append(box)

        # whiskers
        y = (row[1][95] + row[1][5]) / 2
        vl = a.vlines(x, row[1][5], row[1][95])
        vlines.append(vl)

    for b in boxes:
        b.set_linewidth(line_width)
        b.set_facecolor([1, 1, 1, 1])
        b.set_edgecolor(color)
        b.set_zorder(2)

    for vl in vlines:
        vl.set_color(color)
        vl.set_linewidth(line_width)
        vl.set_zorder(1)

    whisker_tips = []
    if whisker_size:
        g, = a.plot(xn, df[5], ls='')
        whisker_tips.append(g)

        g, = a.plot(xn, df[95], ls='')
        whisker_tips.append(g)

    for wt in whisker_tips:
        wt.set_markeredgewidth(line_width)
        wt.set_color(color)
        wt.set_markersize(whisker_size)
        wt.set_marker('_')

    mean = None
    if mean_size:
        g, = a.plot(xn, df['mean'], ls='')
        g.set_marker('o')
        g.set_markersize(mean_size)
        g.set_zorder(20)
        g.set_markerfacecolor('None')
        g.set_markeredgewidth(line_width)
        g.set_markeredgecolor(color)
        mean = g

    median = None
    if median_size:
        g, = a.plot(xn, df['median'], ls='')
        g.set_marker('_')
        g.set_markersize(median_size)
        g.set_zorder(20)
        g.set_markeredgewidth(line_width)
        g.set_markeredgecolor(color)
        median = g

    a.set_ylim(np.nanmin(df), np.nanmax(df))
    return f, a, boxes, vlines, whisker_tips, mean, median
</code>```

This is how it looks in action:

```<code>import numpy as np
import pandas as pd
import matplotlib.pylab as plt

nopts = 12
df = pd.DataFrame()
df['mean'] = np.random.random(nopts) + 7
df['median'] = np.random.random(nopts) + 7
df[5] = np.random.random(nopts) + 4
df[25] = np.random.random(nopts) + 6
df[75] = np.random.random(nopts) + 8
df[95] = np.random.random(nopts) + 10
out = boxplot(df)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Here is a bottom-up approach where the box_plot is build up using matplotlib's vline, Rectangle, and normal plot functions

def boxplot(df, ax=None, box_width=0.2, whisker_size=20, mean_size=10, median_size = 10 , line_width=1.5, xoffset=0,
                     color=0):
    """Plots a boxplot from existing percentiles.

    Parameters
    ----------
    df: pandas DataFrame
    ax: pandas AxesSubplot
        if to plot on en existing axes
    box_width: float
    whisker_size: float
        size of the bar at the end of each whisker
    mean_size: float
        size of the mean symbol
    color: int or rgb(list)
        If int particular color of property cycler is taken. Example of rgb: [1,0,0] (red)

    Returns
    -------
    f, a, boxes, vlines, whisker_tips, mean, median
    """

    if type(color) == int:
        color = plt.rcParams['axes.prop_cycle'].by_key()['color'][color]

    if ax:
        a = ax
        f = a.get_figure()
    else:
        f, a = plt.subplots()

    boxes = []
    vlines = []
    xn = []
    for row in df.iterrows():
        x = row[0] + xoffset
        xn.append(x)

        # box
        y = row[1][25]
        height = row[1][75] - row[1][25]
        box = plt.Rectangle((x - box_width / 2, y), box_width, height)
        a.add_patch(box)
        boxes.append(box)

        # whiskers
        y = (row[1][95] + row[1][5]) / 2
        vl = a.vlines(x, row[1][5], row[1][95])
        vlines.append(vl)

    for b in boxes:
        b.set_linewidth(line_width)
        b.set_facecolor([1, 1, 1, 1])
        b.set_edgecolor(color)
        b.set_zorder(2)

    for vl in vlines:
        vl.set_color(color)
        vl.set_linewidth(line_width)
        vl.set_zorder(1)

    whisker_tips = []
    if whisker_size:
        g, = a.plot(xn, df[5], ls='')
        whisker_tips.append(g)

        g, = a.plot(xn, df[95], ls='')
        whisker_tips.append(g)

    for wt in whisker_tips:
        wt.set_markeredgewidth(line_width)
        wt.set_color(color)
        wt.set_markersize(whisker_size)
        wt.set_marker('_')

    mean = None
    if mean_size:
        g, = a.plot(xn, df['mean'], ls='')
        g.set_marker('o')
        g.set_markersize(mean_size)
        g.set_zorder(20)
        g.set_markerfacecolor('None')
        g.set_markeredgewidth(line_width)
        g.set_markeredgecolor(color)
        mean = g

    median = None
    if median_size:
        g, = a.plot(xn, df['median'], ls='')
        g.set_marker('_')
        g.set_markersize(median_size)
        g.set_zorder(20)
        g.set_markeredgewidth(line_width)
        g.set_markeredgecolor(color)
        median = g

    a.set_ylim(np.nanmin(df), np.nanmax(df))
    return f, a, boxes, vlines, whisker_tips, mean, median

This is how it looks in action:

import numpy as np
import pandas as pd
import matplotlib.pylab as plt

nopts = 12
df = pd.DataFrame()
df['mean'] = np.random.random(nopts) + 7
df['median'] = np.random.random(nopts) + 7
df[5] = np.random.random(nopts) + 4
df[25] = np.random.random(nopts) + 6
df[75] = np.random.random(nopts) + 8
df[95] = np.random.random(nopts) + 10
out = boxplot(df)


问:
MQTT Over Websockets in Android
I am using Paho Android Service for MQTT over web sockets.

https://www.hivemq.com/blog/mqtt-client-library-enyclopedia-paho-android-service

My question is how do I set the Broker WSS URI which has a query parameter in it.

For example: wss://test.amazon.com:80/mqtt?query1=value&query2=value

Edit

If we add the complete URL, the PAHO client library throws following exception:

```<code>MqttException (0) - java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.String.toLowerCase()' on a null object reference
W/System.err:     at org.eclipse.paho.client.mqttv3.internal.ExceptionHelper.createMqttException(ExceptionHelper.java:38)
W/System.err:     at org.eclipse.paho.client.mqttv3.internal.ClientComms$ConnectBG.run(ClientComms.java:664)
W/System.err:     at java.lang.Thread.run(Thread.java:761)
W/System.err: Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.String.toLowerCase()' on a null object reference
W/System.err:     at org.eclipse.paho.client.mqttv3.internal.websocket.WebSocketHandshake.receiveHandshakeResponse(WebSocketHandshake.java:133)
W/System.err:     at org.eclipse.paho.client.mqttv3.internal.websocket.WebSocketHandshake.execute(WebSocketHandshake.java:74)
W/System.err:     at org.eclipse.paho.client.mqttv3.internal.websocket.WebSocketSecureNetworkModule.start(WebSocketSecureNetworkModule.java:77)
W/System.err:     at org.eclipse.paho.client.mqttv3.internal.ClientComms$ConnectBG.run(ClientComms.java:650)
</code>```

Edit 2

```<code>CLIENT = new MqttAndroidClient(this, "wss://test.amazon.com:80/mqtt?query1=value&query2=value", clientId, new MemoryPersistence());
CLIENT.setCallback(this);

MQTT_CONNECTION_OPTIONS = new MqttConnectOptions();
MQTT_CONNECTION_OPTIONS.setCleanSession(true);

try {
    IMqttToken token = CLIENT.connect(MQTT_CONNECTION_OPTIONS);
    token.setActionCallback(new IMqttActionListener() {
        @Override
        public void onSuccess(IMqttToken asyncActionToken) {
            Log.v("tag", "onsuccess");
        }

        @Override
        public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
            exception.printStackTrace();
        }
    });

} catch (MqttException e) {
    e.printStackTrace();
}
</code>```

答:
Changing version from

compile 'org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.1.0'

to

compile 'org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.2.0'

resolved this issue. They have fixed this issue in v1.2.0

Title: MQTT Over Websockets in Android

Body:
I am using Paho Android Service for MQTT over web sockets.

https://www.hivemq.com/blog/mqtt-client-library-enyclopedia-paho-android-service

My question is how do I set the Broker WSS URI which has a query parameter in it.

For example: wss://test.amazon.com:80/mqtt?query1=value&query2=value

Edit

If we add the complete URL, the PAHO client library throws following exception:

MqttException (0) - java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.String.toLowerCase()' on a null object reference
W/System.err:     at org.eclipse.paho.client.mqttv3.internal.ExceptionHelper.createMqttException(ExceptionHelper.java:38)
W/System.err:     at org.eclipse.paho.client.mqttv3.internal.ClientComms$ConnectBG.run(ClientComms.java:664)
W/System.err:     at java.lang.Thread.run(Thread.java:761)
W/System.err: Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.String.toLowerCase()' on a null object reference
W/System.err:     at org.eclipse.paho.client.mqttv3.internal.websocket.WebSocketHandshake.receiveHandshakeResponse(WebSocketHandshake.java:133)
W/System.err:     at org.eclipse.paho.client.mqttv3.internal.websocket.WebSocketHandshake.execute(WebSocketHandshake.java:74)
W/System.err:     at org.eclipse.paho.client.mqttv3.internal.websocket.WebSocketSecureNetworkModule.start(WebSocketSecureNetworkModule.java:77)
W/System.err:     at org.eclipse.paho.client.mqttv3.internal.ClientComms$ConnectBG.run(ClientComms.java:650)

Edit 2

CLIENT = new MqttAndroidClient(this, "wss://test.amazon.com:80/mqtt?query1=value&query2=value", clientId, new MemoryPersistence());
CLIENT.setCallback(this);

MQTT_CONNECTION_OPTIONS = new MqttConnectOptions();
MQTT_CONNECTION_OPTIONS.setCleanSession(true);

try {
    IMqttToken token = CLIENT.connect(MQTT_CONNECTION_OPTIONS);
    token.setActionCallback(new IMqttActionListener() {
        @Override
        public void onSuccess(IMqttToken asyncActionToken) {
            Log.v("tag", "onsuccess");
        }

        @Override
        public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
            exception.printStackTrace();
        }
    });

} catch (MqttException e) {
    e.printStackTrace();
}


问:
AWS beanstalk wordpress
I was trying to setting up my AWS beanstalk by following the implementation guide provided by AWS.

But when I got to the "Launch an Elastic Beanstalk Environment" section, this message appeared which basically said the app is not created.

Here's the message:

[Instance: i-088472611e1ef4405] Command failed on instance. Return
  code: 1 Output: ln: failed to create symbolic link
  'wp-content/uploads': No such file or directory. container_command
  2link in wordpress-beanstalk/.ebextensions/efs-mount.config failed.
  For more detail, check /var/log/eb-activity.log using console or EB
  CLI.

Does anyone have the same problem or know how to resolve this?

答:
A bit late here so for anyone else having this issue, it's caused when that directory does not exist. Here are some reasons this might happen:

1). WP has not created it - Check manually that it exists.

2). .gitignore - When a .ebignore file is not present, EB uses your .gitignore instead. This can cause the directory to not be uploaded with the EB deploy command. If this is the case, make a .ebignore, EB will start ignoring the .gitignore

3). Document root - If you have modified the document root, to something like /src you have to modify the efs-mount.config file.

```<code>##############################################
#### Do not modify values below this line ####
##############################################
container_commands:
  1chown:
    command: "chown webapp:webapp /wpfiles"
  2link:
    command: "sudo -u webapp ln -s /wpfiles src/wp-content/uploads"
</code>```

Even though the file mentions not to modify it, you have to add your document root path in the 2link entry. Change wp-content/uploads to src/wp-content/uploads (replace src with your document root)

Finally, I would not include a command to automatically make this directory, as that only puts a band-aid on the problem.

Hope this helps

Title: AWS beanstalk wordpress

Body:
A bit late here so for anyone else having this issue, it's caused when that directory does not exist. Here are some reasons this might happen:

1). WP has not created it - Check manually that it exists.

2). .gitignore - When a .ebignore file is not present, EB uses your .gitignore instead. This can cause the directory to not be uploaded with the EB deploy command. If this is the case, make a .ebignore, EB will start ignoring the .gitignore

3). Document root - If you have modified the document root, to something like /src you have to modify the efs-mount.config file.

##############################################
#### Do not modify values below this line ####
##############################################
container_commands:
  1chown:
    command: "chown webapp:webapp /wpfiles"
  2link:
    command: "sudo -u webapp ln -s /wpfiles src/wp-content/uploads"

Even though the file mentions not to modify it, you have to add your document root path in the 2link entry. Change wp-content/uploads to src/wp-content/uploads (replace src with your document root)

Finally, I would not include a command to automatically make this directory, as that only puts a band-aid on the problem.

Hope this helps


问:
Where in the NetBeans 6.9.1 source code is the code for scanning Java files and finding all the methods, variables, imports etc
I'm looking for a sample or possibly even code I can use which scans Java files and tells me key pieces of information about each class, which i can then use much like the NetBeans refactoring and go to source features do.</p>

答:
Instead of reusing the Netbeans sources, you should probably just find a good library.

tells me key pieces of information about each class

Depending on your definition of "key pieces", I would recommend QDox:

http://qdox.codehaus.org/

QDox is a high speed, small footprint
  parser for extracting
  class/interface/method definitions
  from source files complete with
  JavaDoc @tags.

ContentLicense: CC BY-SA 2.5


问:
'Could not read path' build failed error on react-native
When I run react-native run-android, the first time I run it after doing cd android && gradlew clean, everything runs fine. If I stop the packager and run react-native run-android a second time, I get this error:

```<code>FAILURE: Build failed with an exception.

* What went wrong:
Could not read path 'C:\ig3\android\app\build\intermediates\incremental\mergeDebugResources\merged.dir\values-fr-rCA'.
> C:\ig3\android\app\build\intermediates\incremental\mergeDebugResources\merged.dir\values-fr-rCA

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

BUILD FAILED
</code>```

I can do cd android && gradlew clean then the build will run fine, but again the next time I run, I will get the same error. It is always the second time I run my build after doing gradlew clean, I get the same error. How can I fix this so I do not need to clean every time?

Any help would be much appreciated. Thanks!

答: After updating gradle to 3.0.1, gradle wrapper to 4.1, and build tools version to 26.0.2 I don't have this issue anymore.</p>

Body:
When I run react-native run-android, the first time I run it after doing cd android && gradlew clean, everything runs fine. If I stop the packager and run react-native run-android a second time, I get this error:

FAILURE: Build failed with an exception.

* What went wrong:
Could not read path 'C:\ig3\android\app\build\intermediates\incremental\mergeDebugResources\merged.dir\values-fr-rCA'.
> C:\ig3\android\app\build\intermediates\incremental\mergeDebugResources\merged.dir\values-fr-rCA

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

BUILD FAILED

I can do cd android && gradlew clean then the build will run fine, but again the next time I run, I will get the same error. It is always the second time I run my build after doing gradlew clean, I get the same error. How can I fix this so I do not need to clean every time?

Any help would be much appreciated. Thanks!


问:
What is the easiest way to privately distribute a jar and resolve it's dependencies?
I am an Android developer and my use case is very basic. I have a java library. I want to share the jar with my teammates as a re-usable piece of functionality.

So far I have tried,

Building a .jar from ./gradlew jar by following this guide. But when I include the same jar in Android Studio the jar's dependencies are not resolved.

I can't publish it on bintray or maven central. So I used maven-publish gradle plugin to publishToLocal by following these steps. This didn't help either. In fact, this didn't publish anything at all.

I used gradle shadow jar plugin. It made the jar "fat" i.e. increase the size from 25KB to 3MB.

All I want is to share a jar within my team. And also the transitive dependencies to be resolved.

Can anyone help?

答:
To have the dependencies resolved you need a POM file, which needs to be hosted on a maven repository.

On this blog post it's explained how to do it using bitbucket as your private maven: https://jeroenmols.com/blog/2016/02/05/wagongit/

The TL;DR from the post is:

Add this script to the module gradle:

```<code>apply from: 'https://raw.githubusercontent.com/JeroenMols/GitAsMaven/master/publish-bitbucket.gradle'
</code>```

Add these data to project gradle.properties

```<code>ARTIFACT_VERSION=<version_here>
ARTIFACT_NAME=<libraryname_here>
ARTIFACT_PACKAGE=<packagename_here>
ARTIFACT_PACKAGING=jar //You could also use aar

COMPANY=<bitbucket_team_company_here> //Username if not part of team
REPOSITORY_NAME=<bitbucket_reponame_here>
</code>```

Add these data to your computer global gradle.properties (on linux it's on ~/.gradle/gradle.properties (on mac/windows you'll have to figure out yourself)

```<code>USERNAME=<username_here>
PASSWORD=<password_here>
</code>```

Execute ./gradlew uploadArchives to send it to the private maven.

Add the new repo on your other project:

```<code>    maven {
        credentials {
            username USERNAME
            password PASSWORD
        }
        url "https://api.bitbucket.org/1.0/repositories/<your user name>/<the repo name>/raw/releases/"
</code>```

Body:
To have the dependencies resolved you need a POM file, which needs to be hosted on a maven repository.

On this blog post it's explained how to do it using bitbucket as your private maven: https://jeroenmols.com/blog/2016/02/05/wagongit/

The TL;DR from the post is:

Add this script to the module gradle:

apply from: 'https://raw.githubusercontent.com/JeroenMols/GitAsMaven/master/publish-bitbucket.gradle'

Add these data to project gradle.properties

ARTIFACT_VERSION=<version_here>
ARTIFACT_NAME=<libraryname_here>
ARTIFACT_PACKAGE=<packagename_here>
ARTIFACT_PACKAGING=jar //You could also use aar

COMPANY=<bitbucket_team_company_here> //Username if not part of team
REPOSITORY_NAME=<bitbucket_reponame_here>

Add these data to your computer global gradle.properties (on linux it's on ~/.gradle/gradle.properties (on mac/windows you'll have to figure out yourself)

USERNAME=<username_here>
PASSWORD=<password_here>

Execute ./gradlew uploadArchives to send it to the private maven.

Add the new repo on your other project:

    maven {
        credentials {
            username USERNAME
            password PASSWORD
        }
        url "https://api.bitbucket.org/1.0/repositories/<your user name>/<the repo name>/raw/releases/"


问:
Python split string at comma, ignore comma in numbers
If I'm given the string

```<code>"Today, I picked, a total, of, 1,000,000, apples"
</code>```

I want

```<code>[Today, I picked, a total, of, 1,000,000, apples]
</code>```

I tried using string.split(","), but that doesn't account for commas in numbers... Could you help me for this particular case? Thank you

Edit
I previously asked this question for javascript, can anyone provide any insights for python?

答: replace your string.split(",") by string.split(", ") with a space after the comma. This should be enough to avoid splitting the numbers.

Body:
If I'm given the string

"Today, I picked, a total, of, 1,000,000, apples"

I want

[Today, I picked, a total, of, 1,000,000, apples]

I tried using string.split(","), but that doesn't account for commas in numbers... Could you help me for this particular case? Thank you

Edit
I previously asked this question for javascript, can anyone provide any insights for python?


问:
What can't be done in CSS yet?
A while ago I was trying to figure out a way of doing this without using a table layout:

```<code><table>
  <tr><td rowspan="2">Left column</td></tr>
  <tr><td>Right Top</td><td>Right bottom</td></tr>
</table>
</code>```

Eventually I gave up and decided that it's impossible to do without tables (okay, CSS 3 might be able to, but waiting another 5-10 years isn't practical).

Has anyone got more examples like this? (Or even better, can you show me I was wrong?)

答: You might want to check out the answer to this question.  There was some interesting CSS code submitted for the answer - including a construct that solved the problem that I hadn't ever seen before.  Lots of very useful links as well.  </p>

Title: What can't be done in CSS yet?

Body:
A while ago I was trying to figure out a way of doing this without using a table layout:

Left column

Right Top	Right bottom

Eventually I gave up and decided that it's impossible to do without tables (okay, CSS 3 might be able to, but waiting another 5-10 years isn't practical).

Has anyone got more examples like this? (Or even better, can you show me I was wrong?)

OwnerDisplayName: Mark Brittingham


问:
how does array.fill.call() work in js?
Mozilla developer includes the following example for the function fill:

```<code>[].fill.call({ length: 3 }, 4);  // {0: 4, 1: 4, 2: 4, length: 3}
</code>```

I don't understand what do you need the call() for and how it gets to that output.

答:
Here is a glimpse of what fill implementation look like (for the sake of explaining):

```<code>Array.prototype.fill = function(value) {
    for(var i = 0; i < this.length; i++) {
        this[i] = value;
    }
}
</code>```

Now when we do fill.call( { length: 3 }, 4 ) we pass the object { length: 3 } as this and 4 as value. The rest is obvious.

fill is an array function. And to work, it should be called on an object that has a valid length property. fill then loops from 0 to length - 1 of that object, setting key-value properties on this object, where key is the current index of the loop (ie. i from the above pseudo code) and value is the value we pass to it.

But using call, we can, instead of passing an array, pass in an array-like object which is an object that looks like an array (have a valid length property). fill is tricked into believing that the object we called it on is an array. And does the same thing for it as it would do for a real array.

Title: how does array.fill.call() work in js?

Body:
Mozilla developer includes the following example for the function fill:

[].fill.call({ length: 3 }, 4);  // {0: 4, 1: 4, 2: 4, length: 3}

I don't understand what do you need the call() for and how it gets to that output.

Body:
Here is a glimpse of what fill implementation look like (for the sake of explaining):

Array.prototype.fill = function(value) {
    for(var i = 0; i < this.length; i++) {
        this[i] = value;
    }
}

Now when we do fill.call( { length: 3 }, 4 ) we pass the object { length: 3 } as this and 4 as value. The rest is obvious.

fill is an array function. And to work, it should be called on an object that has a valid length property. fill then loops from 0 to length - 1 of that object, setting key-value properties on this object, where key is the current index of the loop (ie. i from the above pseudo code) and value is the value we pass to it.

But using call, we can, instead of passing an array, pass in an array-like object which is an object that looks like an array (have a valid length property). fill is tricked into believing that the object we called it on is an array. And does the same thing for it as it would do for a real array.


问:
How to code for optional command line parameters in C
My program has to accept optional command line parameters where there will be either 1 or 3 parameters (executable, number of rows, number of columns). If argc is anything other than 3, we have to create a board that is 10x10 (I've already made a function to create the board).

I'm not sure how to account for this. One restriction on main.c is that we're only allowed to declare/assign variables and call functions, so I'm stuck on how I'm supposed to make this work. My initial idea was to write a function correctNumOfArgs to check if argc is 3, and then return true or false. I would then use that result in a different function to determine how to create the board, but that would still require me to pass argv[1] and argv[2] as parameters in the function and they might not even exist. How do I get around this? Note: I looked at other questions regarding optional command line parameters and they suggested solutions more advanced than what we have learned. Is there a more basic solution to this?

答:
It doesn't matter if the arguments don't exist for a code path you don't take.

What I mean:

```<code>if(3==argc)
make_board(argv[1], argv[2]);
else if(1==argc)
make_board("10", "10");
else
{
/*error*/
}
</code>```

If numArgs is not 3 then that path is not taken so the non-existent arguments aren't used and are never evaluated.

Body:
It doesn't matter if the arguments don't exist for a code path you don't take.

What I mean:

if(3==argc)
make_board(argv[1], argv[2]);
else if(1==argc)
make_board("10", "10");
else
{
/*error*/
}

If numArgs is not 3 then that path is not taken so the non-existent arguments aren't used and are never evaluated.


问:
BrowserStack Automate Test - Click action not work on Android
I have problem when run test on Android. Is look like click action not work, but works fine on iPhone and in Chrome on desktop (Windows).
I use CodeceptJS 1.1.0, WebDriverIO 4.9.9, Selenium-stanalone 6.11.0 and BrowserStack 1.5.0

BrowserStack configuration:

exports.config = {
 tests: ******,
 timeout: 10000,
 output: './output',
 helpers: {
  WebDriverIO: {
   user: ******,
   key: ******,
   url: ******,
   smartWait: 5000,
   browser: 'Android',
   commonCapabilities: [{
    'browserstack.debug': true,
    'browserstack.video': false
   }],
  },
  MyHelper: {
   require: "./MyHelper.js"
  }
 },
 include: {
  I: './hosts/helper.js'
 },
 bootstrap: false,
 mocha: {},
 name: 'js'
};```
</div>
</div>
</p>

<p><strong>Logs for iPhone:</strong></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>• I am on page "/"
• I see element "#registerMultiStepContainer"
• I see element "#registration-step-1 .next"
• I click "#registration-step-1 .next"
WARNING: the "touchClick" command will be deprecated soon. If you have further questions, reach out in the WebdriverIO Gitter support channel (https://gitter.im/webdriverio/webdriverio).
Note: This command is not part of the W3C WebDriver spec and won't be supported in future versions of the driver. It is recommended to use the touchAction command for this.

(You can disable this warning by setting `"deprecationWarnings": false` in your WebdriverIO config)
• I wait 5
• I see element "#registration-step-2"
✓ OK in 15109ms</code>```

Logs for Android:

• I am on page "/"
• I see element "#registerMultiStepContainer"
• I see element "#registration-step-1 .next"
• I click "#registration-step-1 .next"
WARNING: the "touchClick" command will be deprecated soon. If you have further questions, reach out in the WebdriverIO Gitter support channel (https://gitter.im/webdriverio/webdriverio).
Note: This command is not part of the W3C WebDriver spec and won't be supported in future versions of the driver. It is recommended to use the touchAction command for this.

(You can disable this warning by setting `"deprecationWarnings": false` in your WebdriverIO config)
• I wait 5
• I see element "#registration-step-2"
✖ FAILED in 17435ms

-- FAILURES:

  1) Login test: Login as testuser:

      expected elements of #registration-step-2 to be seen
      + expected - actual

      -false
      +true```
</div>
</div>
</p>

<p>I try with my custom step to make alternative for <code>click</code> and instead of using <code>Webdriver touchClick</code>, use something else, but then I got:</p>

```Not yet implemented. Please help us: http://appium.io/get-involved.html
```

<p>Can someone give me any information what can be problem and what is the problem between <code>Webdriver</code> and <code>Appium</code>?</p>

<p><strong>EDIT</strong></p>

<p>Code of test:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code> I.amOnPage('/');
 I.seeElement('#registerMultiStepContainer');
 I.seeElement('#registration-step-1 .next');
 I.wait(5);  // working same with and without this step
 I.click('#registration-step-1 .next');
 I.wait(5);
 I.seeElement('#registration-step-2');</code>```

My custom step:

tap(selector) {
  let browser = this.helpers['WebDriverIO'].browser;

  return browser.touchPerform([{
    action: 'tap',
    options: {
      element: selector,
      x: 5,
      y: 5,
      count: 1
    }
  }]);
}```
</div>
</div>
</p>

<p>Also try this and similar:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>tap(selector) {
  return this.helpers['WebDriverIO'].browser.touchAction(selector, 'tap');
}</code>```

答:
I still do not know what is the problem, Selenium/Webdriver/Browserstack incompatibility or wrong settings or some bug on Browserstack, but I fix this with simulation click event in my custom step.

If someone have better approach, please, let me know. Thanks.

module.exports = class MyHelper extends codecept_helper {

 _before() {
  let browser = this.helpers['WebDriverIO'].browser;

  browser.addCommand('jsClick', function(selector, cb) {
   browser.execute(function(cssSelector) {
    var clickEvent = document.createEvent("MouseEvent");
    clickEvent.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
    document.querySelector(cssSelector).dispatchEvent(clickEvent);
   }, selector, cb);
  });
 }

 jsClick(selector) {
  return this.helpers['WebDriverIO'].browser.jsClick(selector);
 }

}```

Body:
I have problem when run test on Android. Is look like click action not work, but works fine on iPhone and in Chrome on desktop (Windows).
I use CodeceptJS 1.1.0, WebDriverIO 4.9.9, Selenium-stanalone 6.11.0 and BrowserStack 1.5.0

BrowserStack configuration:

exports.config = {
 tests: ******,
 timeout: 10000,
 output: './output',
 helpers: {
  WebDriverIO: {
   user: ******,
   key: ******,
   url: ******,
   smartWait: 5000,
   browser: 'Android',
   commonCapabilities: [{
    'browserstack.debug': true,
    'browserstack.video': false
   }],
  },
  MyHelper: {
   require: "./MyHelper.js"
  }
 },
 include: {
  I: './hosts/helper.js'
 },
 bootstrap: false,
 mocha: {},
 name: 'js'
};

Logs for iPhone:

• I am on page "/"
• I see element "#registerMultiStepContainer"
• I see element "#registration-step-1 .next"
• I click "#registration-step-1 .next"
WARNING: the "touchClick" command will be deprecated soon. If you have further questions, reach out in the WebdriverIO Gitter support channel (https://gitter.im/webdriverio/webdriverio).
Note: This command is not part of the W3C WebDriver spec and won't be supported in future versions of the driver. It is recommended to use the touchAction command for this.

(You can disable this warning by setting `"deprecationWarnings": false` in your WebdriverIO config)
• I wait 5
• I see element "#registration-step-2"
✓ OK in 15109ms

Logs for Android:

• I am on page "/"
• I see element "#registerMultiStepContainer"
• I see element "#registration-step-1 .next"
• I click "#registration-step-1 .next"
WARNING: the "touchClick" command will be deprecated soon. If you have further questions, reach out in the WebdriverIO Gitter support channel (https://gitter.im/webdriverio/webdriverio).
Note: This command is not part of the W3C WebDriver spec and won't be supported in future versions of the driver. It is recommended to use the touchAction command for this.

(You can disable this warning by setting `"deprecationWarnings": false` in your WebdriverIO config)
• I wait 5
• I see element "#registration-step-2"
✖ FAILED in 17435ms

-- FAILURES:

  1) Login test: Login as testuser:

      expected elements of #registration-step-2 to be seen
      + expected - actual

      -false
      +true

I try with my custom step to make alternative for click and instead of using Webdriver touchClick, use something else, but then I got:

Not yet implemented. Please help us: http://appium.io/get-involved.html

Can someone give me any information what can be problem and what is the problem between Webdriver and Appium?

EDIT

Code of test:

 I.amOnPage('/');
 I.seeElement('#registerMultiStepContainer');
 I.seeElement('#registration-step-1 .next');
 I.wait(5);  // working same with and without this step
 I.click('#registration-step-1 .next');
 I.wait(5);
 I.seeElement('#registration-step-2');

My custom step:

tap(selector) {
  let browser = this.helpers['WebDriverIO'].browser;

  return browser.touchPerform([{
    action: 'tap',
    options: {
      element: selector,
      x: 5,
      y: 5,
      count: 1
    }
  }]);
}

Also try this and similar:

tap(selector) {
  return this.helpers['WebDriverIO'].browser.touchAction(selector, 'tap');
}


问:
Interrupt function execution from another function in Python
I have a function a doing some tasks and another function b being a callback to some events. Whenever an event happens, function b is called and I would like to make it able to interrupt the execution of function a. Both functions are declared inside the same class.

Function a is not supposed to call function b. Function b is totally independent, it is a callback to an external event like "user face detected" coming from ROS: robot operating system.

what I need is basically something like Ctrl+C that can be called from within Python and which only aborts a targeted function and not the whole program.

Can this be done in Python?

答:
It's generally recommended not to use exception calling for flow-control. Instead, look to python stdlib's threading.Event, even if you only plan on using a single thread (even the most basic Python program uses at least one thread).

This answer https://stackoverflow.com/a/46346184/914778 has a good explanation of how calling one function (function b) could interrupt another (function a).

Here's a few important parts, summarized from that other answer.

Set up your threading libraries:

```<code>from threading import Event
global exit
exit = Event()
</code>```

This is a good replacement for time.sleep(60), as it can be interrupt:

```<code>exit.wait(60)
</code>```

This code will execute, until you change exit to "set":

```<code>while not exit.is_set():
    do_a_thing()
</code>```

This will cause exit.wait(60) to stop waiting, and exit.is_set() will return True:

```<code>exit.set()
</code>```

This will enable execution again, and exit.is_set() will return False:

```<code>exit.clear()
</code>```

Body:
It's generally recommended not to use exception calling for flow-control. Instead, look to python stdlib's threading.Event, even if you only plan on using a single thread (even the most basic Python program uses at least one thread).

This answer https://stackoverflow.com/a/46346184/914778 has a good explanation of how calling one function (function b) could interrupt another (function a).

Here's a few important parts, summarized from that other answer.

Set up your threading libraries:

from threading import Event
global exit
exit = Event()

This is a good replacement for time.sleep(60), as it can be interrupt:

exit.wait(60)

This code will execute, until you change exit to "set":

while not exit.is_set():
    do_a_thing()

This will cause exit.wait(60) to stop waiting, and exit.is_set() will return True:

exit.set()

This will enable execution again, and exit.is_set() will return False:

exit.clear()


问:
Ways to apply an applicative functor multiple times
Hello fellow Haskellers.

Let's say I have an applicative functor (not an instance of monad) I
want to apply multiple times to a pure initial value. For example,

```<code>λ> Just (1+) <*> (Just (1+) <*> pure 0)
Just 2
</code>```

If I want to generalize this to any number of consecutive
applications, I can do it with a fold.

```<code>applyAppl :: Applicative f => f (a -> a) -> Int -> f a -> f a
applyAppl f n i = foldr (<*>) i $ replicate n f
</code>```

After this definition,

```<code>λ> applyAppl (Just (1+)) 10 $ pure 0
Just 10
</code>```

I have an awkward suspicion that the generalization could also be
done with one of the higher-order builtin applicative tools such as sequenceA or traverse. Can it?

(Edited to take into account the first two comments below.)

答:
Perhaps you are looking for the following variation of @David Young's answer:

```<code>foo :: Applicative f => f (a -> a) -> Int -> a -> f a
foo f n i = fmap (($ i) . iterateN n) f
   where iterateN n f = (!! n) . iterate f
</code>```

giving:

```<code>> foo (Just (1+)) 10 0
Just 10
>
</code>```

This uses the "applicative machinery" in the form of the Functor instance for applicatives to perform both the functional iteration and the application without explicit use of <*>.  I'm not sure what else you'd be hoping for here.

Body:
Hello fellow Haskellers.

Let's say I have an applicative functor (not an instance of monad) I
want to apply multiple times to a pure initial value. For example,

λ> Just (1+) <*> (Just (1+) <*> pure 0)
Just 2

If I want to generalize this to any number of consecutive
applications, I can do it with a fold.

applyAppl :: Applicative f => f (a -> a) -> Int -> f a -> f a
applyAppl f n i = foldr (<*>) i $ replicate n f

After this definition,

λ> applyAppl (Just (1+)) 10 $ pure 0
Just 10

I have an awkward suspicion that the generalization could also be
done with one of the higher-order builtin applicative tools such as sequenceA or traverse. Can it?

(Edited to take into account the first two comments below.)

Body:
Perhaps you are looking for the following variation of @David Young's answer:

foo :: Applicative f => f (a -> a) -> Int -> a -> f a
foo f n i = fmap (($ i) . iterateN n) f
   where iterateN n f = (!! n) . iterate f

giving:

> foo (Just (1+)) 10 0
Just 10
>

This uses the "applicative machinery" in the form of the Functor instance for applicatives to perform both the functional iteration and the application without explicit use of <*>.  I'm not sure what else you'd be hoping for here.


问:
aapt basename attribute
I upgraded my SDK to 2.3 and my build scripts start to fail. I am getting this error:

build.xml:363: aaptexec doesn't support the "basename" attribute

For the following line in my build script:

```<code><aapt executable="${aapt}" command="package" manifest="AndroidManifest.xml" resources="${resource.absolute.dir}" assets="${asset.absolute.dir}" androidjar="${android.jar}" outfolder="${out.absolute.dir}" basename="${ant.project.name}" />
</code>```

I do not know what changed in aapt but apparently basename is not there any more. Can you tell me what should I use instead?

答:
I had similar problems when upgrading from 2.1 to 2.3 with symbolic names changing in the built in 'rules' xmls. 2.1 seemed to use ant_rules_3.xml, now SDK 2.3 uses main_rules.xml as its starting point. If, like me, you had customised your build.xml based on the targets in the rules file, you will probably find it easier to start again by creating a sample project as described in : link text

then adapting you build.xml to override some or all of the targets that are listed in main_rules.xml. (This is in the sdk\tools\ant folder). I found this process to be reasonably quick, and for simple projects the generated files worked 'out of the box' with Ant. (I did have to change the build.xml a lot for a project which contained a second source folder containing .aidl files, as the main_rules.xml couldn't cope with it)

There are two targets which refer to aapt in the main_rules.xml, it's probably this one that you need to mimic:

```<code><target name="-package-resources">
    <echo>Packaging resources</echo>
    <aapt executable="${aapt}"
        command="package"
        versioncode="${version.code}"
        debug="${build.packaging.debug}"
        manifest="AndroidManifest.xml"
        assets="${asset.absolute.dir}"
        androidjar="${android.jar}"
        apkfolder="${out.absolute.dir}"
        resourcefilename="${resource.package.file.name}"
        resourcefilter="${aapt.resource.filter}">
    <res path="${resource.absolute.dir}" />
    <!-- <nocompress /> forces no compression on any files in assets or res/raw -->
    <!-- <nocompress extension="xml" /> forces no compression on specific file   extensions in assets and res/raw -->
    </aapt>
</target>
</code>```

I think the resourcefilename is the name of the generated apk. My build scripts generate the apks and put them in the bin directory OK, without my naming the resourcefilename explicitly.
My build.properties looks like:

```<code>#-----------------------------------------------
# The ONLY reference to the project's main base
#
projectname=MapProject1.2
#
#-----------------------------------------------

workspace.dir=/dev/projects/EclipseHelios/AndroidWorkspace
ant.project.name=${projectname}
outbasebase.dir=/dev/projects/AntBuilds
base.dir=${workspace.dir}/${projectname}
common_src=/dev/projects/CommonSource121210/GridSeviceAndUseGridService
source.dir=${base.dir}/src
outbase.dir=${outbasebase.dir}/${projectname}

out.dir=${outbase.dir}/bin
key.store=c:/users/me/my-release-key.keystore
key.alias=release_alias
key.store.password=*************
key.alias.password=*************
layout.dir=${base.dir}/res/layout
</code>```

(Apart from the passwords of course!)

I did comment out the projectname in the buid.xml, so that it would pick it up from the build.properties.

Title: aapt basename attribute

Body:
I upgraded my SDK to 2.3 and my build scripts start to fail. I am getting this error:

build.xml:363: aaptexec doesn't support the "basename" attribute

For the following line in my build script:

<aapt executable="${aapt}" command="package" manifest="AndroidManifest.xml" resources="${resource.absolute.dir}" assets="${asset.absolute.dir}" androidjar="${android.jar}" outfolder="${out.absolute.dir}" basename="${ant.project.name}" />

I do not know what changed in aapt but apparently basename is not there any more. Can you tell me what should I use instead?

Body:
I had similar problems when upgrading from 2.1 to 2.3 with symbolic names changing in the built in 'rules' xmls. 2.1 seemed to use ant_rules_3.xml, now SDK 2.3 uses main_rules.xml as its starting point. If, like me, you had customised your build.xml based on the targets in the rules file, you will probably find it easier to start again by creating a sample project as described in : link text

then adapting you build.xml to override some or all of the targets that are listed in main_rules.xml. (This is in the sdk\tools\ant folder). I found this process to be reasonably quick, and for simple projects the generated files worked 'out of the box' with Ant. (I did have to change the build.xml a lot for a project which contained a second source folder containing .aidl files, as the main_rules.xml couldn't cope with it)

There are two targets which refer to aapt in the main_rules.xml, it's probably this one that you need to mimic:

<target name="-package-resources">
    <echo>Packaging resources</echo>
    <aapt executable="${aapt}"
        command="package"
        versioncode="${version.code}"
        debug="${build.packaging.debug}"
        manifest="AndroidManifest.xml"
        assets="${asset.absolute.dir}"
        androidjar="${android.jar}"
        apkfolder="${out.absolute.dir}"
        resourcefilename="${resource.package.file.name}"
        resourcefilter="${aapt.resource.filter}">
    <res path="${resource.absolute.dir}" />
    <!-- <nocompress /> forces no compression on any files in assets or res/raw -->
    <!-- <nocompress extension="xml" /> forces no compression on specific file   extensions in assets and res/raw -->
    </aapt>
</target>

I think the resourcefilename is the name of the generated apk. My build scripts generate the apks and put them in the bin directory OK, without my naming the resourcefilename explicitly.
My build.properties looks like:

#-----------------------------------------------
# The ONLY reference to the project's main base
#
projectname=MapProject1.2
#
#-----------------------------------------------

workspace.dir=/dev/projects/EclipseHelios/AndroidWorkspace
ant.project.name=${projectname}
outbasebase.dir=/dev/projects/AntBuilds
base.dir=${workspace.dir}/${projectname}
common_src=/dev/projects/CommonSource121210/GridSeviceAndUseGridService
source.dir=${base.dir}/src
outbase.dir=${outbasebase.dir}/${projectname}

out.dir=${outbase.dir}/bin
key.store=c:/users/me/my-release-key.keystore
key.alias=release_alias
key.store.password=*************
key.alias.password=*************
layout.dir=${base.dir}/res/layout

(Apart from the passwords of course!)

I did comment out the projectname in the buid.xml, so that it would pick it up from the build.properties.


问:
Javascript : setInterval and ClearInterval on one click?
I'm trying to have the numbers 1-6 quickly flash on the screen when a button is clicked, then stop and display the random generated number. If I put clearInterval into the function it just displays the random Number and doesn't display the flashes up numbers before hand.

HTML

```<code><div id='dice'>
    <div id='number'>0</div>
</div>
<div id='button'>
    <button onclick='roll()'>Roll Dice</button>
</div>
</code>```

JAVASCRIPT

```<code>let rollButton = document.querySelector('button');
let diceNumber = document.getElementById ('number');

function roll(){
  diceSides = [1,2,3,4,5,6];
  var i = 0;
  let shuffleDice = setTimeout(function(){
    diceNumber.innerHTML = diceSides[i++];
    if(diceNumber == diceSides.length){
      i = 0;
    }
  }, 500);

  let random = Math.floor(Math.random() * 6);
    diceNumber.innerHTML = random;
}
</code>```

答:
Maybe this works for you

hint: you can use i as a counter variable OR use your approach (define an array with numbers and use index to find them and put them in number tag)

HTML:

```<code><div id='dice'>
    <div id='number'>0</div>
</div>
<div id='button'>
    <button onclick='roll()'>Roll Dice</button>
</div>
</code>```

JS:

```<code>let rollButton = document.querySelector('button');
let diceNumber = document.getElementById ('number');

function roll(){
    diceSides = [1,2,3,4,5,6];
    var i = 6;
    let shuffleDice = setInterval(function(){
        diceNumber.innerHTML = i;
        if(i == 0){
            clearInterval(shuffleDice);
            let random = Math.floor(Math.random() * 6);
            diceNumber.innerHTML = random;
        }
        i--;
    }, 1000);
}
</code>```

CodePen

clearInterval

setInterval

setTimeout

Body:
I'm trying to have the numbers 1-6 quickly flash on the screen when a button is clicked, then stop and display the random generated number. If I put clearInterval into the function it just displays the random Number and doesn't display the flashes up numbers before hand.

HTML

0

    <button onclick='roll()'>Roll Dice</button>

JAVASCRIPT

let rollButton = document.querySelector('button');
let diceNumber = document.getElementById ('number');

function roll(){
  diceSides = [1,2,3,4,5,6];
  var i = 0;
  let shuffleDice = setTimeout(function(){
    diceNumber.innerHTML = diceSides[i++];
    if(diceNumber == diceSides.length){
      i = 0;
    }
  }, 500);

  let random = Math.floor(Math.random() * 6);
    diceNumber.innerHTML = random;
}

Body:
Maybe this works for you

hint: you can use i as a counter variable OR use your approach (define an array with numbers and use index to find them and put them in number tag)

HTML:

<div id='dice'>
    <div id='number'>0</div>
</div>
<div id='button'>
    <button onclick='roll()'>Roll Dice</button>
</div>

JS:

let rollButton = document.querySelector('button');
let diceNumber = document.getElementById ('number');

function roll(){
    diceSides = [1,2,3,4,5,6];
    var i = 6;
    let shuffleDice = setInterval(function(){
        diceNumber.innerHTML = i;
        if(i == 0){
            clearInterval(shuffleDice);
            let random = Math.floor(Math.random() * 6);
            diceNumber.innerHTML = random;
        }
        i--;
    }, 1000);
}

CodePen

clearInterval

setInterval

setTimeout


答:
Let me re-write your code

```<code>var arr = [1];
arr.fill.call({ length: 3 }, 4); // {0: 4, 1: 4, 2: 4, length: 3}
</code>```

in above code if you don't use call, you see it return array with length 1

```<code>var arr = [1];
arr.fill(4); // {0: 4, length: 1}
</code>```

You see, using call function you can execute fill function on another array. first argument of call define functions scope (in your case, array with length 3), and other parameters will pass to function as its arguments

take a look to call DOC on MDN

Title: how does array.fill.call() work in js?

Body:
Let me re-write your code

var arr = [1];
arr.fill.call({ length: 3 }, 4); // {0: 4, 1: 4, 2: 4, length: 3}

in above code if you don't use call, you see it return array with length 1

var arr = [1];
arr.fill(4); // {0: 4, length: 1}

You see, using call function you can execute fill function on another array. first argument of call define functions scope (in your case, array with length 3), and other parameters will pass to function as its arguments

take a look to call DOC on MDN