问:
Data validation issues in HTML
I have an HTML data entry code with some data validation. After I enter the customer no and select 'Find' to look for the customer details, it is still asking for the 'customer title'.

How do I resolve this issue?

<link rel='stylesheet' href='input-style.css' type='text/css' />
<form method="post" action="customers.php">

<colgroup>
    <col span="4"  style="background-color:cyan">
  </colgroup>

     Customer Details

  Customer No.:

  <input  type="text" name="cust_no" maxlength="10" size="10" required>
<input type="submit"  formaction="/find_customers.php" value="Find">

  Customer Title

  <input  type="text" name="cust_title" maxlength="10" size="10" required>

  Surname

  <input  type="text" name="surname" maxlength="20" size="20" required>

  First Name

  <input  type="text" name="fstname" maxlength="50" size="30" required>

  Middle Name

  <input  type="text" name="midname" maxlength="50" size="30">

  Sex

  <select name="sex">
    <option value="Female">Female</option>
    <option value="Male">Male</option>
  </select>

 Date of Birth
<input  type="date" name="dob" maxlength="10" size="10" required>

  Profession

  <input  type="text" name="profession" maxlength="30" size="30">

  Customer Type

 <select name="cust_type">
    <option value="Individual">Individual</option>
    <option value="Group">Group</option>
   <option value="Company">Company</option>
  </select>

  Postal Address

  <input  type="text" name="p_addr1" maxlength="20" size="20">
  <input  type="text" name="p_addr2" maxlength="20" size="20">

  Location Address

  <input  type="text" name="l_addr1" maxlength="20" size="20">
 <input  type="text" name="l_addr2" maxlength="20" size="20">

  Phone No.

  <input  type="text" name="phone_no" maxlength="20" size="20" required>

  ID Type

 <select name="id_type ">
    <option value="Driver's License">Driver's License</option>
    <option value="Passport">Passport</option>
    <option value="National ID">National ID</option>
  </select>

  ID No.
  <input  type="text" name="id_no " maxlength="20" size="20" required>

  Monthly Basic Salary

  <input  type="number" name="mon_basic" maxlength="5" size="5"  min="0"  step = "any" value="0.00" required>

  Annual Basic Salary

  <input  type="number" name="year_basic" maxlength="5" size="5" min="0"  step = "any" value="0.00" required>
  Customer Status
   <select name="cust_status">
    <option value="Active">Active</option>
    <option value="Dormant">Dormant</option>
    <option value="Closed">Closed</option>
  </select>

  Employer

  <input  type="text" name="employer" maxlength="30" size="30">

  Employer Address

  <input  type="text" name="emp_addr1" maxlength="20" size="20">
 <input  type="text" name="emp_addr1" maxlength="20" size="20">

  Employer Phone

  <input  type="text" name="emp_phone" maxlength="20" size="20">

     <input type="submit"  formaction="/update_customers.php" value="Update">
<input type="submit" value="Save">

  Main Menu

</form>
```

答:
This is a possible solution using vanilla javascript.

var findSubmit = document.querySelector('input[value="Find"]');

findSubmit.addEventListener('click', function() {
  document.querySelector('input[name="cust_title"]').removeAttribute('required');
  document.querySelector('input[name="surname"]').removeAttribute('required');
  document.querySelector('input[name="fstname"]').removeAttribute('required');
  document.querySelector('input[name="dob"]').removeAttribute('required');
  document.querySelector('input[name="phone_no"]').removeAttribute('required');
  document.querySelector('input[name="id_no"]').removeAttribute('required');

  // This two are not necessary, because have a default value
  document.querySelector('input[name="mon_basic"]').removeAttribute('required');
  document.querySelector('input[name="year_basic"]').removeAttribute('required');
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form method="post" action="customers.php">
    <table width="550px" align = "center">
    <colgroup>
        <col span="4"  style="background-color:cyan">
      </colgroup>

    <thead>
      <tr>
         <th>Customer Details</th>
      </tr>
     </thead>

    <tr>
     <td valign="top">
     </td>
     <td valign="top">
     </td>
    </tr>

    <tr>
     <td valign="top">
      <label for="cust_no">Customer No.: </label>
     </td>
     <td valign="top">
      <input  type="text" name="cust_no" maxlength="10" size="10" required>
    <input type="submit"  formaction="/find_customers.php" value="Find">
     </td>
    </tr>

    <tr>
     <td valign="top">
      <label for="cust_title">Customer Title</label>
     </td>
     <td valign="top">
      <input  type="text" name="cust_title" maxlength="10" size="10" required>
     </td>
    </tr>

    <tr>
     <td valign="top">
      <label for="surname">Surname </label>
     </td>
     <td valign="top">
      <input  type="text" name="surname" maxlength="20" size="20" required>
     </td>
    </tr>

    <tr>
     <td valign="top">
      <label for="fstname">First Name</label>
     </td>
     <td valign="top">
      <input  type="text" name="fstname" maxlength="50" size="30" required>
     </td>
    </tr>

    <tr>
     <td valign="top">
      <label for="midname">Middle Name</label>
     </td>
     <td valign="top">
      <input  type="text" name="midname" maxlength="50" size="30">
     </td>
    </tr>

    <tr>
     <td valign="top">
      <label for="sex">Sex</label>
     </td>
     <td valign="top">
      <select name="sex">
        <option value="Female">Female</option>
        <option value="Male">Male</option>
      </select>

     <label for="dob">Date of Birth</label>
    <input  type="date" name="dob" maxlength="10" size="10" required>
    </tr>

    <tr>
    <td valign="top">
      <label for="profession">Profession</label>
     </td>
     <td valign="top">
      <input  type="text" name="profession" maxlength="30" size="30">
     </td>
    </tr>

    <tr>
    <td valign="top">
      <label for="cust_type">Customer Type</label>
     </td>
     <td valign="top">
     <select name="cust_type">
        <option value="Individual">Individual</option>
        <option value="Group">Group</option>
       <option value="Company">Company</option>
      </select>
     </td>
    </tr>

    <tr>
    <td valign="top">
      <label for="p_addr1">Postal Address</label>
     </td>
     <td valign="top">
      <input  type="text" name="p_addr1" maxlength="20" size="20">
      <input  type="text" name="p_addr2" maxlength="20" size="20">
    </tr>

    <tr>
    <td valign="top">
      <label for="l_addr1">Location Address</label>
     </td>
     <td valign="top">
      <input  type="text" name="l_addr1" maxlength="20" size="20">
     <input  type="text" name="l_addr2" maxlength="20" size="20">
    </tr>

    <tr>
    <td valign="top">
      <label for="phone_no">Phone No.</label>
     </td>
     <td valign="top">
      <input  type="text" name="phone_no" maxlength="20" size="20" required>
     </td>
    </tr>

    <tr>
    <td valign="top">
      <label for="id_type ">ID Type</label>
     </td>
     <td valign="top">
     <select name="id_type ">
        <option value="Driver's License">Driver's License</option>
        <option value="Passport">Passport</option>
        <option value="National ID">National ID</option>
      </select>

      <label for="id_no ">ID No.</label>
      <input  type="text" name="id_no" maxlength="20" size="20" required>
    </tr>

    <tr>
     <td valign="top">
      <label for="mon_basic">Monthly Basic Salary</label>
     </td>
     <td valign="top">
      <input  type="number" name="mon_basic" maxlength="5" size="5"  min="0"  step = "any" value="0.00" required>
     </td>
    </tr>

    <tr>
     <td valign="top">
      <label for="year_basic">Annual Basic Salary</label>
     </td>
     <td valign="top">
      <input  type="number" name="year_basic" maxlength="5" size="5" min="0"  step = "any" value="0.00" required>
      <label for="cust_status ">Customer Status</label>
       <select name="cust_status">
        <option value="Active">Active</option>
        <option value="Dormant">Dormant</option>
        <option value="Closed">Closed</option>
      </select>
    </tr>

    <tr>
    <td valign="top">
      <label for="employer">Employer</label>
     </td>
     <td valign="top">
      <input  type="text" name="employer" maxlength="30" size="30">
     </td>
    </tr>

    <tr>
    <td valign="top">
      <label for="emp_addr1">Employer Address</label>
     </td>
     <td valign="top">
      <input  type="text" name="emp_addr1" maxlength="20" size="20">
     <input  type="text" name="emp_addr1" maxlength="20" size="20">
    </tr>

    <tr>
    <td valign="top">
      <label for="emp_phone">Employer Phone</label>
     </td>
     <td valign="top">
      <input  type="text" name="emp_phone" maxlength="20" size="20">
     </td>
    </tr>

    <tr>
     <td colspan="2" style="text-align:center">
         <input type="submit"  formaction="/update_customers.php" value="Update">
    <input type="submit" value="Save">
    </tr>

    <tr>
     <td colspan="2" style="text-align:center">
      Main Menu
     </td>
    </tr>
    </table>
    </form></code>```

Title: Data validation issues in HTML

Body:
This is a possible solution using vanilla javascript.

var findSubmit = document.querySelector('input[value="Find"]');

findSubmit.addEventListener('click', function() {
  document.querySelector('input[name="cust_title"]').removeAttribute('required');
  document.querySelector('input[name="surname"]').removeAttribute('required');
  document.querySelector('input[name="fstname"]').removeAttribute('required');
  document.querySelector('input[name="dob"]').removeAttribute('required');
  document.querySelector('input[name="phone_no"]').removeAttribute('required');
  document.querySelector('input[name="id_no"]').removeAttribute('required');

  // This two are not necessary, because have a default value
  document.querySelector('input[name="mon_basic"]').removeAttribute('required');
  document.querySelector('input[name="year_basic"]').removeAttribute('required');
});

<form method="post" action="customers.php">
    <table width="550px" align = "center">
    <colgroup>
        <col span="4"  style="background-color:cyan">
      </colgroup>

    <thead>
      <tr>
         <th>Customer Details</th>
      </tr>
     </thead>

    <tr>
     <td valign="top">
     </td>
     <td valign="top">
     </td>
    </tr>

    <tr>
     <td valign="top">
      <label for="cust_no">Customer No.: </label>
     </td>
     <td valign="top">
      <input  type="text" name="cust_no" maxlength="10" size="10" required>
    <input type="submit"  formaction="/find_customers.php" value="Find">
     </td>
    </tr>

    <tr>
     <td valign="top">
      <label for="cust_title">Customer Title</label>
     </td>
     <td valign="top">
      <input  type="text" name="cust_title" maxlength="10" size="10" required>
     </td>
    </tr>

    <tr>
     <td valign="top">
      <label for="surname">Surname </label>
     </td>
     <td valign="top">
      <input  type="text" name="surname" maxlength="20" size="20" required>
     </td>
    </tr>

    <tr>
     <td valign="top">
      <label for="fstname">First Name</label>
     </td>
     <td valign="top">
      <input  type="text" name="fstname" maxlength="50" size="30" required>
     </td>
    </tr>

    <tr>
     <td valign="top">
      <label for="midname">Middle Name</label>
     </td>
     <td valign="top">
      <input  type="text" name="midname" maxlength="50" size="30">
     </td>
    </tr>

    <tr>
     <td valign="top">
      <label for="sex">Sex</label>
     </td>
     <td valign="top">
      <select name="sex">
        <option value="Female">Female</option>
        <option value="Male">Male</option>
      </select>

     <label for="dob">Date of Birth</label>
    <input  type="date" name="dob" maxlength="10" size="10" required>
    </tr>

    <tr>
    <td valign="top">
      <label for="profession">Profession</label>
     </td>
     <td valign="top">
      <input  type="text" name="profession" maxlength="30" size="30">
     </td>
    </tr>

    <tr>
    <td valign="top">
      <label for="cust_type">Customer Type</label>
     </td>
     <td valign="top">
     <select name="cust_type">
        <option value="Individual">Individual</option>
        <option value="Group">Group</option>
       <option value="Company">Company</option>
      </select>
     </td>
    </tr>

    <tr>
    <td valign="top">
      <label for="p_addr1">Postal Address</label>
     </td>
     <td valign="top">
      <input  type="text" name="p_addr1" maxlength="20" size="20">
      <input  type="text" name="p_addr2" maxlength="20" size="20">
    </tr>

    <tr>
    <td valign="top">
      <label for="l_addr1">Location Address</label>
     </td>
     <td valign="top">
      <input  type="text" name="l_addr1" maxlength="20" size="20">
     <input  type="text" name="l_addr2" maxlength="20" size="20">
    </tr>

    <tr>
    <td valign="top">
      <label for="phone_no">Phone No.</label>
     </td>
     <td valign="top">
      <input  type="text" name="phone_no" maxlength="20" size="20" required>
     </td>
    </tr>

    <tr>
    <td valign="top">
      <label for="id_type ">ID Type</label>
     </td>
     <td valign="top">
     <select name="id_type ">
        <option value="Driver's License">Driver's License</option>
        <option value="Passport">Passport</option>
        <option value="National ID">National ID</option>
      </select>

      <label for="id_no ">ID No.</label>
      <input  type="text" name="id_no" maxlength="20" size="20" required>
    </tr>

    <tr>
     <td valign="top">
      <label for="mon_basic">Monthly Basic Salary</label>
     </td>
     <td valign="top">
      <input  type="number" name="mon_basic" maxlength="5" size="5"  min="0"  step = "any" value="0.00" required>
     </td>
    </tr>

    <tr>
     <td valign="top">
      <label for="year_basic">Annual Basic Salary</label>
     </td>
     <td valign="top">
      <input  type="number" name="year_basic" maxlength="5" size="5" min="0"  step = "any" value="0.00" required>
      <label for="cust_status ">Customer Status</label>
       <select name="cust_status">
        <option value="Active">Active</option>
        <option value="Dormant">Dormant</option>
        <option value="Closed">Closed</option>
      </select>
    </tr>

    <tr>
    <td valign="top">
      <label for="employer">Employer</label>
     </td>
     <td valign="top">
      <input  type="text" name="employer" maxlength="30" size="30">
     </td>
    </tr>

    <tr>
    <td valign="top">
      <label for="emp_addr1">Employer Address</label>
     </td>
     <td valign="top">
      <input  type="text" name="emp_addr1" maxlength="20" size="20">
     <input  type="text" name="emp_addr1" maxlength="20" size="20">
    </tr>

    <tr>
    <td valign="top">
      <label for="emp_phone">Employer Phone</label>
     </td>
     <td valign="top">
      <input  type="text" name="emp_phone" maxlength="20" size="20">
     </td>
    </tr>

    <tr>
     <td colspan="2" style="text-align:center">
         <input type="submit"  formaction="/update_customers.php" value="Update">
    <input type="submit" value="Save">
    </tr>

    <tr>
     <td colspan="2" style="text-align:center">
      <a href= "loanmgr.html">Main Menu</a>
     </td>
    </tr>
    </table>
    </form>


来源: stackexchange

问:
How to limit the scope of ancestor search in XSLT?
Example input:

```<code><body>
  <ul>
     <li>
       <p>Some text with <b><i><span style="color:red">formatting</span></i></b></p>
   </li>
</ul>
</body>
</code>```

The 'inline' elements are b, i, or span

Suppose the context node is the nested span element in the example.

How do I get all ancestor inline elements, without the search going past the containing p element?

The expression ancestor-or-self::*[self::b | self::i | self::span] should actually work, as there can't be ancestor inline elements containing 'block' level elements such as p, ul, etc.

But, I wonder if there is some performance cost that could be avoided, as I think the search will continue past the containing p element.  Is there a way to avoid that?

Edit

This is what I've come up with so far:

```<code><xsl:function name="my:getInlineSeq" as="element() *">
    <xsl:param name="pElem" as="element()" />
    <xsl:if test="$pElem[self::b | self::i | self::span]">
        <xsl:sequence select="my:getInlineSeq($pElem/parent::*)" />
        <xsl:sequence select="$pElem" />
    </xsl:if>
</xsl:function>
</code>```

But, I'm unsure if there is an better or 'standard' way of solving this problem.

Note: the $pElem/parent::* in the code will always return an element as inline items must have a block element container such as p, h1, etc.  Also, the assumption is the $pElem parameter provided initially is always an inline element.

答:
Using

```<code><xsl:function name="mf:block" as="element()">
    <xsl:param name="inline" as="element()"/>
    <xsl:sequence select="$inline/ancestor::*[self::h1 | self::h2 | self::h3 | self::h4 | self::h5 | self::h6 | self::li | self::p][1]"/>
</xsl:function>
</code>```

and your assumption about block and inline elements you could rewrite ancestor-or-self::*[self::b | self::i | self::span] in the context of match="span | b | i" to

```<code>for $block in mf:block(.) return ancestor-or-self::*[. >> $block]
</code>```

I think (or assuming you use <xsl:variable name="block" select="mf:block(.)"/> to ancestor-or-self::*[. >> $block]. I have no idea whether that performs any better than your attempt.

Tried to test the expression at http://xsltransform.net/3MvmrzK where

```<code><xsl:template match="span | b | i">
    <xsl:copy>
        <xsl:apply-templates select="@*"/>
        <xsl:attribute name="inline-ancestor" select="ancestor-or-self::*[self::b | self::i | self::span]/name()"/>
        <xsl:attribute name="test-block" select="for $block in mf:block(.) return ancestor-or-self::*[. >> $block]/name()"/>
        <xsl:apply-templates/>
    </xsl:copy>
</xsl:template>
</code>```

gives the same result for the inline elements with

```<code>   <p>Some text with <b inline-ancestor="b" test-block="b"><i inline-ancestor="b i" test-block="b i"><span style="color:red" inline-ancestor="b i span" test-block="b i span">formatting</span></i></b></p>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Example input:

Some text with formatting

The 'inline' elements are b, i, or span

Suppose the context node is the nested span element in the example.

How do I get all ancestor inline elements, without the search going past the containing p element?

The expression ancestor-or-self::*[self::b | self::i | self::span] should actually work, as there can't be ancestor inline elements containing 'block' level elements such as p, ul, etc.

But, I wonder if there is some performance cost that could be avoided, as I think the search will continue past the containing p element.  Is there a way to avoid that?

Edit

This is what I've come up with so far:

<xsl:function name="my:getInlineSeq" as="element() *">
    <xsl:param name="pElem" as="element()" />
    <xsl:if test="$pElem[self::b | self::i | self::span]">
        <xsl:sequence select="my:getInlineSeq($pElem/parent::*)" />
        <xsl:sequence select="$pElem" />
    </xsl:if>
</xsl:function>

But, I'm unsure if there is an better or 'standard' way of solving this problem.

Note: the $pElem/parent::* in the code will always return an element as inline items must have a block element container such as p, h1, etc.  Also, the assumption is the $pElem parameter provided initially is always an inline element.

Body:
Using

<xsl:function name="mf:block" as="element()">
    <xsl:param name="inline" as="element()"/>
    <xsl:sequence select="$inline/ancestor::*[self::h1 | self::h2 | self::h3 | self::h4 | self::h5 | self::h6 | self::li | self::p][1]"/>
</xsl:function>

and your assumption about block and inline elements you could rewrite ancestor-or-self::*[self::b | self::i | self::span] in the context of match="span | b | i" to

for $block in mf:block(.) return ancestor-or-self::*[. >> $block]

I think (or assuming you use <xsl:variable name="block" select="mf:block(.)"/> to ancestor-or-self::*[. >> $block]. I have no idea whether that performs any better than your attempt.

Tried to test the expression at http://xsltransform.net/3MvmrzK where

<xsl:template match="span | b | i">
    <xsl:copy>
        <xsl:apply-templates select="@*"/>
        <xsl:attribute name="inline-ancestor" select="ancestor-or-self::*[self::b | self::i | self::span]/name()"/>
        <xsl:attribute name="test-block" select="for $block in mf:block(.) return ancestor-or-self::*[. >> $block]/name()"/>
        <xsl:apply-templates/>
    </xsl:copy>
</xsl:template>

gives the same result for the inline elements with

   <p>Some text with <b inline-ancestor="b" test-block="b"><i inline-ancestor="b i" test-block="b i"><span style="color:red" inline-ancestor="b i span" test-block="b i span">formatting</span></i></b></p>


问:
"open/close" SqlConnection or keep open?
I have my business-logic implemented in simple static classes with static methods. Each of these methods opens/closes SQL connection when called:

```<code>public static void DoSomething()
{
    using (SqlConnection connection = new SqlConnection("..."))
    {
        connection.Open();

        // ...

        connection.Close();
    }
}
</code>```

But I think passing the connection object around and avoiding opening and closing a connection saves performance. I made some tests long time ago with OleDbConnection class (not sure about SqlConnection), and it definitely helped to work like this (as far as I remember):

```<code>//pass around the connection object into the method
public static void DoSomething(SqlConnection connection)
{
    bool openConn = (connection.State == ConnectionState.Open);
    if (!openConn)
    {
        connection.Open();
    }

    // ....

    if (openConn)
    {
        connection.Close();
    }
}
</code>```

So the question is - should I choose the method (a) or method (b) ? I read in another stackoverflow question that connection pooling saved performance for me, I don't have to bother at all...

PS. It's an ASP.NET app - connections exist only during a web-request. Not a win-app or service.

答:
Stick to option a.

The connection pooling is your friend.

ContentLicense: CC BY-SA 4.0

Body:
I have my business-logic implemented in simple static classes with static methods. Each of these methods opens/closes SQL connection when called:

public static void DoSomething()
{
    using (SqlConnection connection = new SqlConnection("..."))
    {
        connection.Open();

        // ...

        connection.Close();
    }
}

But I think passing the connection object around and avoiding opening and closing a connection saves performance. I made some tests long time ago with OleDbConnection class (not sure about SqlConnection), and it definitely helped to work like this (as far as I remember):

//pass around the connection object into the method
public static void DoSomething(SqlConnection connection)
{
    bool openConn = (connection.State == ConnectionState.Open);
    if (!openConn)
    {
        connection.Open();
    }

    // ....

    if (openConn)
    {
        connection.Close();
    }
}

So the question is - should I choose the method (a) or method (b) ? I read in another stackoverflow question that connection pooling saved performance for me, I don't have to bother at all...

PS. It's an ASP.NET app - connections exist only during a web-request. Not a win-app or service.

ContentLicense: CC BY-SA 2.5


问:
Concat multiple C++ strings at once?
I'm new to C++ strings. Is there a way to concatenate more than two strings at once? Or I have to concat two strings at the time? My concern is that it probably needs to allocate memory on each operation, instead of only once for the final result.

Remember something like that in java, wonder if there is a method for that somewhere in std. Actually, std::stringstream might be it, but I don't know how exactly it works.

答:
If you are using the c-style strings (ie char*), then you can allocate once and cat a number of times.  The strcat function takes a pointer to a destination address as a first argument.  Thus if you make your destination string large enough, there will only be one alloc.  Thus

```<code>char* dest = new char[100];
dest[0] = 0; //Zero length string to start
strcat(dest, str1);
strcat(dest, str2);
strcat(dest, str3);
</code>```

If on the other hand you use std::string then + can be chained string1 + string2 + string3.

Title: Concat multiple C++ strings at once?

Body:
If you are using the c-style strings (ie char*), then you can allocate once and cat a number of times.  The strcat function takes a pointer to a destination address as a first argument.  Thus if you make your destination string large enough, there will only be one alloc.  Thus

char* dest = new char[100];
dest[0] = 0; //Zero length string to start
strcat(dest, str1);
strcat(dest, str2);
strcat(dest, str3);

If on the other hand you use std::string then + can be chained string1 + string2 + string3.


问:
Promise not resolved correctly when routing
So basically I am using resolve in $routeProvider in order to get my current user's information before I instantiate the controller.
This is how I do it:

```<code>userMan.config(['$routeProvider', function ($routeProvider) {
    $routeProvider.when('/userManagement', {
        templateUrl: 'userManagement/userManagement.html',
        controller: 'userManCtrl',
        resolve: {
            myUser:function($http){
                console.log("I am about to make the call");
                $http.get("/irods-cloud-backend/searchByMetadata/getCurrentUser").then( function( result ) {
                    console.log(result.data);
                    return result.data;
                },
                function( result ) {
                    alert("Unable to find any users! Please try again...");
                })
            }
        }
    });
}]);
</code>```

My controller also looks something like this:

```<code>userMan.controller('userManCtrl', ['$scope', '$log', '$http', '$location', 'myUser',
function($scope, $log, $http, $location, myUser){

    var currUser = myUser;
</code>```

Basically my error is that currUser is undefined. This prevents me to check the user's permissions and such.
I have also used:

```<code>    $scope.$on('$routeChangeSuccess',function(event, current){
        alert("loaded!!");
    });
</code>```

To see when this promise is resolved, but I see the alert message as soon as I load into the tab.
I then tried to use a dummy return object simply like

```<code>return { someAttr: 'val'};
</code>```

This functions just fine.. I know its not a promise but did that for sanity purposes..

Any clues for the error?

答:
You don't return from the myUser method, so there's nothing to wait for but undefined. As @JoelCDoyle commented:

Your resolve method must return a promise. $http method returns a promise.

```<code>resolve: {
        myUser:function($http){
            // return here!
            return $http.get("/irods-cloud-backend/searchByMetadata/getCurrentUser").then( function( result ) {
                console.log(result.data);
                return result.data;
            }
</code>```

Body:
So basically I am using resolve in $routeProvider in order to get my current user's information before I instantiate the controller.
This is how I do it:

userMan.config(['$routeProvider', function ($routeProvider) {
    $routeProvider.when('/userManagement', {
        templateUrl: 'userManagement/userManagement.html',
        controller: 'userManCtrl',
        resolve: {
            myUser:function($http){
                console.log("I am about to make the call");
                $http.get("/irods-cloud-backend/searchByMetadata/getCurrentUser").then( function( result ) {
                    console.log(result.data);
                    return result.data;
                },
                function( result ) {
                    alert("Unable to find any users! Please try again...");
                })
            }
        }
    });
}]);

My controller also looks something like this:

userMan.controller('userManCtrl', ['$scope', '$log', '$http', '$location', 'myUser',
function($scope, $log, $http, $location, myUser){

    var currUser = myUser;

Basically my error is that currUser is undefined. This prevents me to check the user's permissions and such.
I have also used:

    $scope.$on('$routeChangeSuccess',function(event, current){
        alert("loaded!!");
    });

To see when this promise is resolved, but I see the alert message as soon as I load into the tab.
I then tried to use a dummy return object simply like

return { someAttr: 'val'};

This functions just fine.. I know its not a promise but did that for sanity purposes..

Any clues for the error?

Body:
You don't return from the myUser method, so there's nothing to wait for but undefined. As @JoelCDoyle commented:

Your resolve method must return a promise. $http method returns a promise.

resolve: {
        myUser:function($http){
            // return here!
            return $http.get("/irods-cloud-backend/searchByMetadata/getCurrentUser").then( function( result ) {
                console.log(result.data);
                return result.data;
            }


问:
How to find docker.socket file after change of docker root folder ?
Docker service is correctly setting up.

Before long, I change the root directory of Docker from /var/lib/docker to /opt/docker.

I can't find the docker.socket file, in order to share it with another container (Docker In Docker, DIND).

Docker info does not display any information about the location of the socker ?, How can I find it ?

答:
Please specify your OS.
For example, on Ubuntu 14.04 it's /var/run/docker.sock

I believe that Docker socket file is not expected to appear at /var/lib/docker on any default setup

Also, if you are on CentOS of Fedora, take a look on http://www.projectatomic.io/blog/2015/08/why-we-dont-let-non-root-users-run-docker-in-centos-fedora-or-rhel/


问:
CSS: element should get max-width before breaking words
There are CSS tooltips (codepen is given below). They have min-width and max-width. They contain sometimes short phrases, sometimes very long words without breaks. This is what happens if there is white-space: nowrap => Short tooltips are rendered perfectly, but long ones, obviously, are not wrapped and are not fully visible:

This is what happens when I add white-space: normal and word-break: break-word => Now short ones and long ones get wrapped long before getting to the max-width:

What I would like to achieve is:
Tooltips don't wrap before getting to the max-width. And start wrapping only if they don't get into the max-width. Like here:

Is it possible to get this behaviour just with CSS (no javascript)?

Here is the codepen: https://codepen.io/anon/pen/bWXobM
(Uncomment lines 58-59 to change the behaviour.)

I didn't manage to achieve this with any of the found solutions. If you know how to apply them in this case, please share!

Update: apparently some kind of solution to this problem has just been added to the wg draft: https://github.com/w3c/csswg-drafts/issues/1171. It is still interesting if someone found a workaround for now.

答:
I made some changed in the css code.I have commented on the lines which i have changed.(eg. //changed).Actually you already made the half solution by using

```<code>word-break: break-word;
</code>```

The only thing i changed is min-width and max-width to achieve the required results.

Here is the updated link

https://codepen.io/anon/pen/ZyGpaL

Body:
I made some changed in the css code.I have commented on the lines which i have changed.(eg. //changed).Actually you already made the half solution by using

word-break: break-word;

The only thing i changed is min-width and max-width to achieve the required results.

Here is the updated link

https://codepen.io/anon/pen/ZyGpaL


问:
How to scroll softly not rapidly at once
I am begginer in html and want to ask how to move to an id in html which is targeted by an anchor tag for example:

When I run this code, it rapidly goes to targeted id although I want to go with animations. How can I do this?

答:
Let's say your HTML is:

```<code><a href = "#start-heading">Jump to start of content</a>
<div id = "table-of-contents">...</div>
<h1 id = "start-heading">Chapter 1</h1>
</code>```

Then add this javascript:

```<code>document.querySelector("#start-heading").onclick = e=>{
  this.scrollIntoView({
    behavior: 'smooth'
  });
  e.preventDefault();
  return false;
};
</code>```

document.querySelector("#start-heading").onclick = e=>{
  document.querySelector(this.href).scrollIntoView({
    behavior: 'smooth'
  });
  e.preventDefault();
  return false;
};```
<pre class="snippet-code-html lang-html prettyprint-override"><code>Jump to start of content
<div id = "table-of-contents">
  Bacon ipsum dolor amet flank shank meatloaf tri-tip picanha beef ribs sirloin strip steak fatback. Tenderloin boudin ground round biltong pig pancetta bacon tail porchetta strip steak leberkas fatback chicken venison tongue. Boudin short loin andouille drumstick prosciutto brisket, ham hock pork belly kevin jowl. Picanha turkey tenderloin shank, sirloin alcatra frankfurter tri-tip biltong drumstick filet mignon bresaola tongue ham hock. Boudin tri-tip ribeye salami. Kielbasa shankle cow ham hock landjaeger biltong shoulder turkey chuck pig chicken filet mignon. Ham drumstick pancetta, jerky spare ribs prosciutto frankfurter.

Boudin tail t-bone burgdoggen shank short ribs meatball. Salami andouille sausage porchetta. Sausage boudin jowl meatloaf, fatback drumstick kevin prosciutto turkey kielbasa sirloin biltong pig swine andouille. Kevin capicola picanha, tri-tip filet mignon ham pig jowl hamburger biltong brisket doner ground round.

Meatball boudin landjaeger alcatra ground round pancetta flank shank chuck bacon jerky jowl cupim. Ribeye pastrami tongue ham ground round shankle strip steak tenderloin, boudin ball tip hamburger. Brisket bacon hamburger, rump turducken jowl pig tongue venison tail kielbasa cow filet mignon ham. Tongue chicken ribeye porchetta t-bone. Corned beef flank turkey porchetta landjaeger. Pork loin tri-tip andouille, spare ribs jowl picanha pig ham pancetta cupim chuck filet mignon biltong sausage. Ground round pork belly biltong filet mignon t-bone, andouille bacon leberkas shoulder venison sausage tri-tip shank.

Doner ball tip frankfurter, pancetta chuck kielbasa bresaola meatloaf cupim. Cupim rump pork ham frankfurter burgdoggen kevin beef ribs ribeye porchetta shoulder swine beef filet mignon capicola. Tongue sausage strip steak short loin kevin doner beef ribs kielbasa chicken shank capicola bacon pastrami pork loin andouille. Burgdoggen alcatra frankfurter, spare ribs cupim biltong shoulder pig flank brisket.
</div>
<h1 id = "start-heading">Chapter 1</h1>
<p>
Bacon ipsum dolor amet rump ground round leberkas bresaola shoulder doner capicola shankle tri-tip beef ribs pork belly. Pork chop flank alcatra shoulder kielbasa cow ball tip venison turkey jerky hamburger. Kielbasa fatback sausage, drumstick tri-tip flank frankfurter pork chop pastrami. Jowl filet mignon flank ball tip short ribs turducken beef tail ribeye bacon t-bone sirloin tri-tip. Flank pork loin pork chop, fatback pancetta capicola alcatra doner t-bone meatball.

Kielbasa t-bone burgdoggen andouille pig venison turducken ground round short loin tenderloin strip steak pork chop corned beef porchetta. Rump short ribs meatloaf bacon shankle biltong tail hamburger salami flank chuck jowl pancetta pork loin filet mignon. Pig beef ribs venison alcatra rump cow cupim swine, salami drumstick boudin. Flank tri-tip picanha turkey pig corned beef. Turducken prosciutto andouille kevin cow chuck filet mignon landjaeger. Chuck turducken chicken brisket spare ribs. Porchetta cupim chuck, fatback biltong tail rump ground round sausage picanha.

Spare ribs shank drumstick meatball pork chop prosciutto pork belly sausage jerky andouille. Chicken hamburger pork belly ground round kevin leberkas pork loin rump ham picanha ribeye jerky alcatra andouille swine. Tenderloin ham pancetta beef ribs turducken ball tip. Kielbasa spare ribs capicola doner sirloin corned beef bresaola beef ribs pork chop. Pork belly prosciutto short ribs, kielbasa kevin alcatra short loin tongue sirloin meatloaf. Pork loin meatloaf t-bone sausage jerky chicken, ground round pig.

Meatloaf shankle ribeye jowl, chicken cow picanha turkey pork belly rump leberkas alcatra kielbasa tri-tip fatback. Bacon filet mignon cupim prosciutto pork belly. Corned beef hamburger ham hock, short ribs ham turkey cow fatback venison pastrami filet mignon jerky shankle chicken beef ribs. Prosciutto turducken turkey meatball, short loin kielbasa beef ribs tenderloin biltong venison ground round pork loin. Short loin filet mignon biltong jowl pig rump pork jerky drumstick strip steak swine ham hock beef bresaola ball tip. Pancetta tenderloin swine, meatloaf ham drumstick shank kevin salami.

Pork venison beef ribs rump hamburger. T-bone jerky prosciutto picanha kevin. Frankfurter ribeye shank tri-tip porchetta biltong tail filet mignon beef landjaeger sirloin leberkas jowl. Hamburger ham hock beef ribs shoulder biltong tenderloin sirloin burgdoggen. Cow cupim venison, biltong corned beef shankle meatloaf kevin ribeye capicola short loin ball tip ham hock. Strip steak spare ribs doner shoulder sausage tongue bacon boudin pork loin. Porchetta filet mignon pig jowl, pastrami doner kielbasa ham hock pork chop bacon chicken short ribs meatloaf.

Beef ribs pork meatball, drumstick pig burgdoggen prosciutto spare ribs porchetta alcatra chicken jowl venison frankfurter. Tongue sausage drumstick picanha beef pig jerky, meatball ham. Ribeye cow meatloaf, ham spare ribs pancetta tri-tip capicola kevin bresaola shank. Cupim pork loin capicola prosciutto, ham beef t-bone tail biltong jerky filet mignon flank pastrami bresaola turducken.

Bacon cow venison doner short ribs. Strip steak salami landjaeger capicola. Ground round turducken chicken strip steak flank, sausage bacon shank. Short ribs jerky leberkas corned beef tenderloin t-bone beef ribs tongue chicken pancetta kevin flank fatback sausage. Shoulder beef ribs fatback bacon, tongue venison burgdoggen meatloaf t-bone ham hock doner chicken kevin. Drumstick andouille cow shankle. Short loin corned beef bresaola meatball cupim, strip steak t-bone.
</p>

<script>/*
 * smoothscroll polyfill - v0.3.5
 * https://iamdustan.github.io/smoothscroll
 * 2016 (c) Dustan Kasten, Jeremias Menichelli - MIT License
 */

(function(w, d, undefined) {
  'use strict';

  /*
   * aliases
   * w: window global object
   * d: document
   * undefined: undefined
   */

  // polyfill
  function polyfill() {
    // return when scrollBehavior interface is supported
    if ('scrollBehavior' in d.documentElement.style) {
      return;
    }

    /*
     * globals
     */
    var Element = w.HTMLElement || w.Element;
    var SCROLL_TIME = 468;

    /*
     * object gathering original scroll methods
     */
    var original = {
      scroll: w.scroll || w.scrollTo,
      scrollBy: w.scrollBy,
      elScroll: Element.prototype.scroll || scrollElement,
      scrollIntoView: Element.prototype.scrollIntoView
    };

    /*
     * define timing method
     */
    var now = w.performance && w.performance.now
      ? w.performance.now.bind(w.performance) : Date.now;

    /**
     * changes scroll position inside an element
     * @method scrollElement
     * @param {Number} x
     * @param {Number} y
     */
    function scrollElement(x, y) {
      this.scrollLeft = x;
      this.scrollTop = y;
    }

    /**
     * returns result of applying ease math function to a number
     * @method ease
     * @param {Number} k
     * @returns {Number}
     */
    function ease(k) {
      return 0.5 * (1 - Math.cos(Math.PI * k));
    }

    /**
     * indicates if a smooth behavior should be applied
     * @method shouldBailOut
     * @param {Number|Object} x
     * @returns {Boolean}
     */
    function shouldBailOut(x) {
      if (typeof x !== 'object'
            || x === null
            || x.behavior === undefined
            || x.behavior === 'auto'
            || x.behavior === 'instant') {
        // first arg not an object/null
        // or behavior is auto, instant or undefined
        return true;
      }

      if (typeof x === 'object'
            && x.behavior === 'smooth') {
        // first argument is an object and behavior is smooth
        return false;
      }

      // throw error when behavior is not supported
      throw new TypeError('behavior not valid');
    }

    /**
     * finds scrollable parent of an element
     * @method findScrollableParent
     * @param {Node} el
     * @returns {Node} el
     */
    function findScrollableParent(el) {
      var isBody;
      var hasScrollableSpace;
      var hasVisibleOverflow;

      do {
        el = el.parentNode;

        // set condition variables
        isBody = el === d.body;
        hasScrollableSpace =
          el.clientHeight < el.scrollHeight ||
          el.clientWidth < el.scrollWidth;
        hasVisibleOverflow =
          w.getComputedStyle(el, null).overflow === 'visible';
      } while (!isBody && !(hasScrollableSpace && !hasVisibleOverflow));

      isBody = hasScrollableSpace = hasVisibleOverflow = null;

      return el;
    }

    /**
     * self invoked function that, given a context, steps through scrolling
     * @method step
     * @param {Object} context
     */
    function step(context) {
      var time = now();
      var value;
      var currentX;
      var currentY;
      var elapsed = (time - context.startTime) / SCROLL_TIME;

      // avoid elapsed times higher than one
      elapsed = elapsed > 1 ? 1 : elapsed;

      // apply easing to elapsed time
      value = ease(elapsed);

      currentX = context.startX + (context.x - context.startX) * value;
      currentY = context.startY + (context.y - context.startY) * value;

      context.method.call(context.scrollable, currentX, currentY);

      // scroll more if we have not reached our destination
      if (currentX !== context.x || currentY !== context.y) {
        w.requestAnimationFrame(step.bind(w, context));
      }
    }

    /**
     * scrolls window with a smooth behavior
     * @method smoothScroll
     * @param {Object|Node} el
     * @param {Number} x
     * @param {Number} y
     */
    function smoothScroll(el, x, y) {
      var scrollable;
      var startX;
      var startY;
      var method;
      var startTime = now();

      // define scroll context
      if (el === d.body) {
        scrollable = w;
        startX = w.scrollX || w.pageXOffset;
        startY = w.scrollY || w.pageYOffset;
        method = original.scroll;
      } else {
        scrollable = el;
        startX = el.scrollLeft;
        startY = el.scrollTop;
        method = scrollElement;
      }

      // scroll looping over a frame
      step({
        scrollable: scrollable,
        method: method,
        startTime: startTime,
        startX: startX,
        startY: startY,
        x: x,
        y: y
      });
    }

    /*
     * ORIGINAL METHODS OVERRIDES
     */

    // w.scroll and w.scrollTo
    w.scroll = w.scrollTo = function() {
      // avoid smooth behavior if not required
      if (shouldBailOut(arguments[0])) {
        original.scroll.call(
          w,
          arguments[0].left || arguments[0],
          arguments[0].top || arguments[1]
        );
        return;
      }

      // LET THE SMOOTHNESS BEGIN!
      smoothScroll.call(
        w,
        d.body,
        ~~arguments[0].left,
        ~~arguments[0].top
      );
    };

    // w.scrollBy
    w.scrollBy = function() {
      // avoid smooth behavior if not required
      if (shouldBailOut(arguments[0])) {
        original.scrollBy.call(
          w,
          arguments[0].left || arguments[0],
          arguments[0].top || arguments[1]
        );
        return;
      }

      // LET THE SMOOTHNESS BEGIN!
      smoothScroll.call(
        w,
        d.body,
        ~~arguments[0].left + (w.scrollX || w.pageXOffset),
        ~~arguments[0].top + (w.scrollY || w.pageYOffset)
      );
    };

    // Element.prototype.scroll and Element.prototype.scrollTo
    Element.prototype.scroll = Element.prototype.scrollTo = function() {
      // avoid smooth behavior if not required
      if (shouldBailOut(arguments[0])) {
        original.elScroll.call(
            this,
            arguments[0].left || arguments[0],
            arguments[0].top || arguments[1]
        );
        return;
      }

      // LET THE SMOOTHNESS BEGIN!
      smoothScroll.call(
          this,
          this,
          arguments[0].left,
          arguments[0].top
      );
    };

    // Element.prototype.scrollBy
    Element.prototype.scrollBy = function() {
      var arg0 = arguments[0];

      if (typeof arg0 === 'object') {
        this.scroll({
          left: arg0.left + this.scrollLeft,
          top: arg0.top + this.scrollTop,
          behavior: arg0.behavior
        });
      } else {
        this.scroll(
          this.scrollLeft + arg0,
          this.scrollTop + arguments[1]
        );
      }
    };

    // Element.prototype.scrollIntoView
    Element.prototype.scrollIntoView = function() {
      // avoid smooth behavior if not required
      if (shouldBailOut(arguments[0])) {
        original.scrollIntoView.call(this, arguments[0] || true);
        return;
      }

      // LET THE SMOOTHNESS BEGIN!
      var scrollableParent = findScrollableParent(this);
      var parentRects = scrollableParent.getBoundingClientRect();
      var clientRects = this.getBoundingClientRect();

      if (scrollableParent !== d.body) {
        // reveal element inside parent
        smoothScroll.call(
          this,
          scrollableParent,
          scrollableParent.scrollLeft + clientRects.left - parentRects.left,
          scrollableParent.scrollTop + clientRects.top - parentRects.top
        );
        // reveal parent in viewport
        w.scrollBy({
          left: parentRects.left,
          top: parentRects.top,
          behavior: 'smooth'
        });
      } else {
        // reveal element in viewport
        w.scrollBy({
          left: clientRects.left,
          top: clientRects.top,
          behavior: 'smooth'
        });
      }
    };
  }

  if (typeof exports === 'object') {
    // commonjs
    module.exports = { polyfill: polyfill };
  } else {
    // global
    polyfill();
  }
})(window, document);</script></code>```

Body:
Let's say your HTML is:

<a href = "#start-heading">Jump to start of content</a>
<div id = "table-of-contents">...</div>
<h1 id = "start-heading">Chapter 1</h1>

Then add this javascript:

document.querySelector("#start-heading").onclick = e=>{
  this.scrollIntoView({
    behavior: 'smooth'
  });
  e.preventDefault();
  return false;
};

document.querySelector("#start-heading").onclick = e=>{
  document.querySelector(this.href).scrollIntoView({
    behavior: 'smooth'
  });
  e.preventDefault();
  return false;
};

<a href = "#start-heading">Jump to start of content</a>
<div id = "table-of-contents">
  Bacon ipsum dolor amet flank shank meatloaf tri-tip picanha beef ribs sirloin strip steak fatback. Tenderloin boudin ground round biltong pig pancetta bacon tail porchetta strip steak leberkas fatback chicken venison tongue. Boudin short loin andouille drumstick prosciutto brisket, ham hock pork belly kevin jowl. Picanha turkey tenderloin shank, sirloin alcatra frankfurter tri-tip biltong drumstick filet mignon bresaola tongue ham hock. Boudin tri-tip ribeye salami. Kielbasa shankle cow ham hock landjaeger biltong shoulder turkey chuck pig chicken filet mignon. Ham drumstick pancetta, jerky spare ribs prosciutto frankfurter.

Boudin tail t-bone burgdoggen shank short ribs meatball. Salami andouille sausage porchetta. Sausage boudin jowl meatloaf, fatback drumstick kevin prosciutto turkey kielbasa sirloin biltong pig swine andouille. Kevin capicola picanha, tri-tip filet mignon ham pig jowl hamburger biltong brisket doner ground round.

Meatball boudin landjaeger alcatra ground round pancetta flank shank chuck bacon jerky jowl cupim. Ribeye pastrami tongue ham ground round shankle strip steak tenderloin, boudin ball tip hamburger. Brisket bacon hamburger, rump turducken jowl pig tongue venison tail kielbasa cow filet mignon ham. Tongue chicken ribeye porchetta t-bone. Corned beef flank turkey porchetta landjaeger. Pork loin tri-tip andouille, spare ribs jowl picanha pig ham pancetta cupim chuck filet mignon biltong sausage. Ground round pork belly biltong filet mignon t-bone, andouille bacon leberkas shoulder venison sausage tri-tip shank.

Doner ball tip frankfurter, pancetta chuck kielbasa bresaola meatloaf cupim. Cupim rump pork ham frankfurter burgdoggen kevin beef ribs ribeye porchetta shoulder swine beef filet mignon capicola. Tongue sausage strip steak short loin kevin doner beef ribs kielbasa chicken shank capicola bacon pastrami pork loin andouille. Burgdoggen alcatra frankfurter, spare ribs cupim biltong shoulder pig flank brisket.
</div>
<h1 id = "start-heading">Chapter 1</h1>
<p>
Bacon ipsum dolor amet rump ground round leberkas bresaola shoulder doner capicola shankle tri-tip beef ribs pork belly. Pork chop flank alcatra shoulder kielbasa cow ball tip venison turkey jerky hamburger. Kielbasa fatback sausage, drumstick tri-tip flank frankfurter pork chop pastrami. Jowl filet mignon flank ball tip short ribs turducken beef tail ribeye bacon t-bone sirloin tri-tip. Flank pork loin pork chop, fatback pancetta capicola alcatra doner t-bone meatball.

Kielbasa t-bone burgdoggen andouille pig venison turducken ground round short loin tenderloin strip steak pork chop corned beef porchetta. Rump short ribs meatloaf bacon shankle biltong tail hamburger salami flank chuck jowl pancetta pork loin filet mignon. Pig beef ribs venison alcatra rump cow cupim swine, salami drumstick boudin. Flank tri-tip picanha turkey pig corned beef. Turducken prosciutto andouille kevin cow chuck filet mignon landjaeger. Chuck turducken chicken brisket spare ribs. Porchetta cupim chuck, fatback biltong tail rump ground round sausage picanha.

Spare ribs shank drumstick meatball pork chop prosciutto pork belly sausage jerky andouille. Chicken hamburger pork belly ground round kevin leberkas pork loin rump ham picanha ribeye jerky alcatra andouille swine. Tenderloin ham pancetta beef ribs turducken ball tip. Kielbasa spare ribs capicola doner sirloin corned beef bresaola beef ribs pork chop. Pork belly prosciutto short ribs, kielbasa kevin alcatra short loin tongue sirloin meatloaf. Pork loin meatloaf t-bone sausage jerky chicken, ground round pig.

Meatloaf shankle ribeye jowl, chicken cow picanha turkey pork belly rump leberkas alcatra kielbasa tri-tip fatback. Bacon filet mignon cupim prosciutto pork belly. Corned beef hamburger ham hock, short ribs ham turkey cow fatback venison pastrami filet mignon jerky shankle chicken beef ribs. Prosciutto turducken turkey meatball, short loin kielbasa beef ribs tenderloin biltong venison ground round pork loin. Short loin filet mignon biltong jowl pig rump pork jerky drumstick strip steak swine ham hock beef bresaola ball tip. Pancetta tenderloin swine, meatloaf ham drumstick shank kevin salami.

Pork venison beef ribs rump hamburger. T-bone jerky prosciutto picanha kevin. Frankfurter ribeye shank tri-tip porchetta biltong tail filet mignon beef landjaeger sirloin leberkas jowl. Hamburger ham hock beef ribs shoulder biltong tenderloin sirloin burgdoggen. Cow cupim venison, biltong corned beef shankle meatloaf kevin ribeye capicola short loin ball tip ham hock. Strip steak spare ribs doner shoulder sausage tongue bacon boudin pork loin. Porchetta filet mignon pig jowl, pastrami doner kielbasa ham hock pork chop bacon chicken short ribs meatloaf.

Beef ribs pork meatball, drumstick pig burgdoggen prosciutto spare ribs porchetta alcatra chicken jowl venison frankfurter. Tongue sausage drumstick picanha beef pig jerky, meatball ham. Ribeye cow meatloaf, ham spare ribs pancetta tri-tip capicola kevin bresaola shank. Cupim pork loin capicola prosciutto, ham beef t-bone tail biltong jerky filet mignon flank pastrami bresaola turducken.

Bacon cow venison doner short ribs. Strip steak salami landjaeger capicola. Ground round turducken chicken strip steak flank, sausage bacon shank. Short ribs jerky leberkas corned beef tenderloin t-bone beef ribs tongue chicken pancetta kevin flank fatback sausage. Shoulder beef ribs fatback bacon, tongue venison burgdoggen meatloaf t-bone ham hock doner chicken kevin. Drumstick andouille cow shankle. Short loin corned beef bresaola meatball cupim, strip steak t-bone.
</p>

<script>/*
 * smoothscroll polyfill - v0.3.5
 * https://iamdustan.github.io/smoothscroll
 * 2016 (c) Dustan Kasten, Jeremias Menichelli - MIT License
 */

(function(w, d, undefined) {
  'use strict';

  /*
   * aliases
   * w: window global object
   * d: document
   * undefined: undefined
   */

  // polyfill
  function polyfill() {
    // return when scrollBehavior interface is supported
    if ('scrollBehavior' in d.documentElement.style) {
      return;
    }

    /*
     * globals
     */
    var Element = w.HTMLElement || w.Element;
    var SCROLL_TIME = 468;

    /*
     * object gathering original scroll methods
     */
    var original = {
      scroll: w.scroll || w.scrollTo,
      scrollBy: w.scrollBy,
      elScroll: Element.prototype.scroll || scrollElement,
      scrollIntoView: Element.prototype.scrollIntoView
    };

    /*
     * define timing method
     */
    var now = w.performance && w.performance.now
      ? w.performance.now.bind(w.performance) : Date.now;

    /**
     * changes scroll position inside an element
     * @method scrollElement
     * @param {Number} x
     * @param {Number} y
     */
    function scrollElement(x, y) {
      this.scrollLeft = x;
      this.scrollTop = y;
    }

    /**
     * returns result of applying ease math function to a number
     * @method ease
     * @param {Number} k
     * @returns {Number}
     */
    function ease(k) {
      return 0.5 * (1 - Math.cos(Math.PI * k));
    }

    /**
     * indicates if a smooth behavior should be applied
     * @method shouldBailOut
     * @param {Number|Object} x
     * @returns {Boolean}
     */
    function shouldBailOut(x) {
      if (typeof x !== 'object'
            || x === null
            || x.behavior === undefined
            || x.behavior === 'auto'
            || x.behavior === 'instant') {
        // first arg not an object/null
        // or behavior is auto, instant or undefined
        return true;
      }

      if (typeof x === 'object'
            && x.behavior === 'smooth') {
        // first argument is an object and behavior is smooth
        return false;
      }

      // throw error when behavior is not supported
      throw new TypeError('behavior not valid');
    }

    /**
     * finds scrollable parent of an element
     * @method findScrollableParent
     * @param {Node} el
     * @returns {Node} el
     */
    function findScrollableParent(el) {
      var isBody;
      var hasScrollableSpace;
      var hasVisibleOverflow;

      do {
        el = el.parentNode;

        // set condition variables
        isBody = el === d.body;
        hasScrollableSpace =
          el.clientHeight < el.scrollHeight ||
          el.clientWidth < el.scrollWidth;
        hasVisibleOverflow =
          w.getComputedStyle(el, null).overflow === 'visible';
      } while (!isBody && !(hasScrollableSpace && !hasVisibleOverflow));

      isBody = hasScrollableSpace = hasVisibleOverflow = null;

      return el;
    }

    /**
     * self invoked function that, given a context, steps through scrolling
     * @method step
     * @param {Object} context
     */
    function step(context) {
      var time = now();
      var value;
      var currentX;
      var currentY;
      var elapsed = (time - context.startTime) / SCROLL_TIME;

      // avoid elapsed times higher than one
      elapsed = elapsed > 1 ? 1 : elapsed;

      // apply easing to elapsed time
      value = ease(elapsed);

      currentX = context.startX + (context.x - context.startX) * value;
      currentY = context.startY + (context.y - context.startY) * value;

      context.method.call(context.scrollable, currentX, currentY);

      // scroll more if we have not reached our destination
      if (currentX !== context.x || currentY !== context.y) {
        w.requestAnimationFrame(step.bind(w, context));
      }
    }

    /**
     * scrolls window with a smooth behavior
     * @method smoothScroll
     * @param {Object|Node} el
     * @param {Number} x
     * @param {Number} y
     */
    function smoothScroll(el, x, y) {
      var scrollable;
      var startX;
      var startY;
      var method;
      var startTime = now();

      // define scroll context
      if (el === d.body) {
        scrollable = w;
        startX = w.scrollX || w.pageXOffset;
        startY = w.scrollY || w.pageYOffset;
        method = original.scroll;
      } else {
        scrollable = el;
        startX = el.scrollLeft;
        startY = el.scrollTop;
        method = scrollElement;
      }

      // scroll looping over a frame
      step({
        scrollable: scrollable,
        method: method,
        startTime: startTime,
        startX: startX,
        startY: startY,
        x: x,
        y: y
      });
    }

    /*
     * ORIGINAL METHODS OVERRIDES
     */

    // w.scroll and w.scrollTo
    w.scroll = w.scrollTo = function() {
      // avoid smooth behavior if not required
      if (shouldBailOut(arguments[0])) {
        original.scroll.call(
          w,
          arguments[0].left || arguments[0],
          arguments[0].top || arguments[1]
        );
        return;
      }

      // LET THE SMOOTHNESS BEGIN!
      smoothScroll.call(
        w,
        d.body,
        ~~arguments[0].left,
        ~~arguments[0].top
      );
    };

    // w.scrollBy
    w.scrollBy = function() {
      // avoid smooth behavior if not required
      if (shouldBailOut(arguments[0])) {
        original.scrollBy.call(
          w,
          arguments[0].left || arguments[0],
          arguments[0].top || arguments[1]
        );
        return;
      }

      // LET THE SMOOTHNESS BEGIN!
      smoothScroll.call(
        w,
        d.body,
        ~~arguments[0].left + (w.scrollX || w.pageXOffset),
        ~~arguments[0].top + (w.scrollY || w.pageYOffset)
      );
    };

    // Element.prototype.scroll and Element.prototype.scrollTo
    Element.prototype.scroll = Element.prototype.scrollTo = function() {
      // avoid smooth behavior if not required
      if (shouldBailOut(arguments[0])) {
        original.elScroll.call(
            this,
            arguments[0].left || arguments[0],
            arguments[0].top || arguments[1]
        );
        return;
      }

      // LET THE SMOOTHNESS BEGIN!
      smoothScroll.call(
          this,
          this,
          arguments[0].left,
          arguments[0].top
      );
    };

    // Element.prototype.scrollBy
    Element.prototype.scrollBy = function() {
      var arg0 = arguments[0];

      if (typeof arg0 === 'object') {
        this.scroll({
          left: arg0.left + this.scrollLeft,
          top: arg0.top + this.scrollTop,
          behavior: arg0.behavior
        });
      } else {
        this.scroll(
          this.scrollLeft + arg0,
          this.scrollTop + arguments[1]
        );
      }
    };

    // Element.prototype.scrollIntoView
    Element.prototype.scrollIntoView = function() {
      // avoid smooth behavior if not required
      if (shouldBailOut(arguments[0])) {
        original.scrollIntoView.call(this, arguments[0] || true);
        return;
      }

      // LET THE SMOOTHNESS BEGIN!
      var scrollableParent = findScrollableParent(this);
      var parentRects = scrollableParent.getBoundingClientRect();
      var clientRects = this.getBoundingClientRect();

      if (scrollableParent !== d.body) {
        // reveal element inside parent
        smoothScroll.call(
          this,
          scrollableParent,
          scrollableParent.scrollLeft + clientRects.left - parentRects.left,
          scrollableParent.scrollTop + clientRects.top - parentRects.top
        );
        // reveal parent in viewport
        w.scrollBy({
          left: parentRects.left,
          top: parentRects.top,
          behavior: 'smooth'
        });
      } else {
        // reveal element in viewport
        w.scrollBy({
          left: clientRects.left,
          top: clientRects.top,
          behavior: 'smooth'
        });
      }
    };
  }

  if (typeof exports === 'object') {
    // commonjs
    module.exports = { polyfill: polyfill };
  } else {
    // global
    polyfill();
  }
})(window, document);</script>


问:
jQuery DataTable Not a Function
I've done a lot of searching and everyone says it is caused by including the DataTable script before jQuery, or double-including jQuery.

However, this is not the case for my code.

I keep getting $(...).DataTable is not a function.

```<code><!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Example of Employee Table with twitter bootstrap</title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>

    <script type="text/javascript">
        $(document).ready(function(){
            $('#myTable').DataTable();
        });
    </script>
</head>
<body style="margin:20px auto">
    <table id="myTable" class="table table-striped" >
        <thead>
          <tr>
            <th>ENO</th>
            <th>EMPName</th>
            <th>Country</th>
            <th>Salary</th>
          </tr>
        </thead>
        <tbody>
          <tr>
            <td>001</td>
            <td>Anusha</td>
            <td>India</td>
            <td>10000</td>
          </tr>
          <tr>
        <td>002</td>
        <td>Charles</td>
        <td>United Kingdom</td>
        <td>28000</td>
      </tr>
      <tr>
        <td>003</td>
        <td>Sravani</td>
        <td>Australia</td>
        <td>7000</td>
      </tr>
       <tr>
        <td>004</td>
        <td>Amar</td>
        <td>India</td>
        <td>18000</td>
      </tr>
      <tr>
        <td>005</td>
        <td>Lakshmi</td>
        <td>India</td>
        <td>12000</td>
      </tr>
      <tr>
        <td>006</td>
        <td>James</td>
        <td>Canada</td>
        <td>50000</td>
      </tr>

       <tr>
        <td>007</td>
        <td>Ronald</td>
        <td>US</td>
        <td>75000</td>
      </tr>
      <tr>
        <td>008</td>
        <td>Mike</td>
        <td>Belgium</td>
        <td>100000</td>
      </tr>
    </tbody>
  </table>
  </div>
</body>

</html>
</code>```

答: @Philip Tenn, I have checked the code with and without https. But I have no any issue with your code, its working fine.</p>

Title: jQuery DataTable Not a Function

Body:
I've done a lot of searching and everyone says it is caused by including the DataTable script before jQuery, or double-including jQuery.

However, this is not the case for my code.

I keep getting $(...).DataTable is not a function.

<!DOCTYPE html>

  <meta charset="utf-8">
  <title>Example of Employee Table with twitter bootstrap</title>

            ENO
            EMPName
            Country
            Salary

            001
            Anusha
            India
            10000

        002
        Charles
        United Kingdom
        28000

        003
        Sravani
        Australia
        7000

        004
        Amar
        India
        18000

        005
        Lakshmi
        India
        12000

        006
        James
        Canada
        50000

        007
        Ronald
        US
        75000

        008
        Mike
        Belgium
        100000


问:
Excel Time to SQL Time
I am having some trouble inserting time into SQLServer

The data type in SQLServer is time(0). I have the time in excel as 10:29:42. (It is in 24-hour format)When I insert it into SQL the actual value being inserted is 0.4372917

I get an error and the insert fails.Is there any way in VBA to have the actual value as `10:29:42'? This is my current code I use to copy from one sheet to another:

```<code>Test Time
Dim tt As String
tt = raw.Range("A7")
master.Range("F2") = tt
</code>```

My insert Code is such:

```<code>Insert into Date_t( Date) Values(ActiveSheet.Range("F2"))
</code>```

答:
0.4372917 - part of day that have passed, multiply it with total seconds count in day to receive how many seconds passed since midnight

you should add seconds quantity to zero time:

```<code>Insert into Date_t( Date) Values(DATEADD(SECOND, ActiveSheet.Range("F2") * 24 * 60 * 60, CAST('00:00' AS TIME)))
</code>```

P.S. it's better to use parametrized queries.

Title: Excel Time to SQL Time

Body:
I am having some trouble inserting time into SQLServer

The data type in SQLServer is time(0). I have the time in excel as 10:29:42. (It is in 24-hour format)When I insert it into SQL the actual value being inserted is 0.4372917

I get an error and the insert fails.Is there any way in VBA to have the actual value as `10:29:42'? This is my current code I use to copy from one sheet to another:

Test Time
Dim tt As String
tt = raw.Range("A7")
master.Range("F2") = tt

My insert Code is such:

Insert into Date_t( Date) Values(ActiveSheet.Range("F2"))

Body:
0.4372917 - part of day that have passed, multiply it with total seconds count in day to receive how many seconds passed since midnight

you should add seconds quantity to zero time:

Insert into Date_t( Date) Values(DATEADD(SECOND, ActiveSheet.Range("F2") * 24 * 60 * 60, CAST('00:00' AS TIME)))

P.S. it's better to use parametrized queries.


问:
Regex Splitting with Negative Lookbehind
The string I am trying to split:

string1, string2, string\,3, string4

I want to split the above string on each comma, except when the comma is escaped with a backslash.

I am unable to utilize negative lookbehind in my JavaScript.

My attempt:

var splits = "string1, string2, string\,3, string4".split("(?<!\\\\),");

None of the commas are being recognized.

Potential solutions: after research, I stumbled across this SO question.  However, I don't understand the workarounds well enough to change the above code to the replace the use case.

答:
You may use

```<code>s.match(/(?:[^,\\]|\\.)+/g)
</code>```

See the regex demo. It will match 1 or more chars other than comma and backslash, or any char that is escaped with a literal backslash.

Note that the string literal should have a double backslash to define a literal backslash.

var splits = "string1, string2, string\\,3, string4".match(/(?:[^,\\]|\\.)+/g);
console.log(splits);```

Body:
You may use

s.match(/(?:[^,\\]|\\.)+/g)

See the regex demo. It will match 1 or more chars other than comma and backslash, or any char that is escaped with a literal backslash.

Note that the string literal should have a double backslash to define a literal backslash.

var splits = "string1, string2, string\\,3, string4".match(/(?:[^,\\]|\\.)+/g);
console.log(splits);


问:
How to read current db version number in dexie?
In Dexie, when you need to upgrade your schemas or table architectures, you use db.version(X) method.

The library will then check whether the user's browser has a previous version cached and do the appropriate upgrade steps.

But I cannot find how to read the current user's db version manually.

So for example if write this purposefully breaking code:

<s>db.version(1).stores(/* my schema */)</s> // remove this code

db.version(2).stores(/* my schema */)

The library will politely throw an error saying that the version the user currently has (obviously, 1) has no schema.

But is there a way to read what version exactly the user has?

It could be useful for debugging!

答:
It is possible to skip the whole version() thing if you only want to inspect the database. For instance, I'm able to print the version number of my database by using this code.

```<code>new Dexie("myDB").open().then((db) => console.log(db.verno))
</code>```

Note that (as stated in the documentation), Dexie multiples the version number set through .version() by 10 so if you inspect the database in your browser's debugger you will see a number which is 10 times the number you get from using the verno field.

Body:
It is possible to skip the whole version() thing if you only want to inspect the database. For instance, I'm able to print the version number of my database by using this code.

new Dexie("myDB").open().then((db) => console.log(db.verno))

Note that (as stated in the documentation), Dexie multiples the version number set through .version() by 10 so if you inspect the database in your browser's debugger you will see a number which is 10 times the number you get from using the verno field.


问:
XML serialization and inheritance
```<code>class A : IXmlSerializable
{     ...
}

class B : A
{
   public string X;
}
</code>```

When i serialize object of type B, only A is serialized. How can I include X with minimum effort?

答:
The fact you're implementing IXmlSerializable makes it a bit harder...

What you could do is make WriteXml and ReadXml virtual, and override them in your derived class:

```<code>public class A : IXmlSerializable
{
    public virtual void WriteXml (XmlWriter writer)
    {
        // Serialize A members
    }

    public virtual void ReadXml (XmlReader reader)
    {
        // Deserialize A members
    }

    public XmlSchema GetSchema()
    {
        return(null);
    }

}

public class B : A
{
    public override void WriteXml (XmlWriter writer)
    {
        base.WriteXml(writer);

        // Serialize B members
    }

    public virtual void ReadXml (XmlReader reader)
    {
        base.ReadXml(reader);

        // Deserialize B members
    }
}
</code>```

Title: XML serialization and inheritance

Body:
class A : IXmlSerializable
{     ...
}

class B : A
{
   public string X;
}

When i serialize object of type B, only A is serialized. How can I include X with minimum effort?

Body:
The fact you're implementing IXmlSerializable makes it a bit harder...

What you could do is make WriteXml and ReadXml virtual, and override them in your derived class:

public class A : IXmlSerializable
{
    public virtual void WriteXml (XmlWriter writer)
    {
        // Serialize A members
    }

    public virtual void ReadXml (XmlReader reader)
    {
        // Deserialize A members
    }

    public XmlSchema GetSchema()
    {
        return(null);
    }

}

public class B : A
{
    public override void WriteXml (XmlWriter writer)
    {
        base.WriteXml(writer);

        // Serialize B members
    }

    public virtual void ReadXml (XmlReader reader)
    {
        base.ReadXml(reader);

        // Deserialize B members
    }
}


问:
How to setup MariaDB datasource in Wildfly with CLI
I'm really new to Wildfly and probably this is a dumb question. I'm trying to configurate the MariaDB datasource with the CLI. The script I'm using is:

```<code>module add --name=org.mariadb.jdbc --resources=mariadb-java-client-1.5.5.jar --dependencies=javax.api.javax.transaction.api

/subsystem=datasources/jdbc-driver=org.mariadb.jdbc.Driver:add(driver-name=org.mariadb.jdbc.Driver,driver-module-name=org.mariadb.jdbc)

data-source add --jndi-name=java:/datasources/MariaDBS --name=MariaDBPool --connection-url=jdbc:mariadb://localhost:3306/exampledb --driver-name=org.mariadb.jdbc --user-name=root --password=root
</code>```

The error I'm getting is:

```<code>{
    "outcome" => "failed",
    "failure-description" => "WFLYJCA0041: Failed to load module for driver [org.mariadb.jdbc]",
    "rolled-back" => true
}
</code>```

The code is similar to MySQL setting I have found in the internet. I tried to modified it to use MariaDB instead. Any help will be appreciate. Also my original jar is in /bin and I'm using Wildfly 10.1.0

答:
Please change:

--dependencies=javax.api.javax.transaction.api to --dependencies=javax.api,javax.transaction.api

--driver-name=org.mariadb.jdbc to --driver-name=org.mariadb.jdbc.Driver

Body:
I'm really new to Wildfly and probably this is a dumb question. I'm trying to configurate the MariaDB datasource with the CLI. The script I'm using is:

module add --name=org.mariadb.jdbc --resources=mariadb-java-client-1.5.5.jar --dependencies=javax.api.javax.transaction.api

/subsystem=datasources/jdbc-driver=org.mariadb.jdbc.Driver:add(driver-name=org.mariadb.jdbc.Driver,driver-module-name=org.mariadb.jdbc)

data-source add --jndi-name=java:/datasources/MariaDBS --name=MariaDBPool --connection-url=jdbc:mariadb://localhost:3306/exampledb --driver-name=org.mariadb.jdbc --user-name=root --password=root

The error I'm getting is:

{
    "outcome" => "failed",
    "failure-description" => "WFLYJCA0041: Failed to load module for driver [org.mariadb.jdbc]",
    "rolled-back" => true
}

The code is similar to MySQL setting I have found in the internet. I tried to modified it to use MariaDB instead. Any help will be appreciate. Also my original jar is in /bin and I'm using Wildfly 10.1.0


问:
Selecting rows that contain subset characters in any order
I have a table containing a list of English words from which I am trying to select all the words which can be made with a given string "hand" (as in the game scrabble)

```<code>+--------+
|  word  |
+--------+
| test   |
| father |
| woman  |
| zebra  |
+--------+
</code>```

The query I have so far will only check that any of the characters in the hand are present in the word.

```<code>SELECT * FROM words WHERE word SIMILAR to '%e%|%z%|%h%';
/* returns test, father and zebra as they all contain either e,z or h */
</code>```

However this does not take into account whether a word contains a character more times than the hand does, the code I am using in python to check whether a word is valid

```<code>def isValidWord(word, hand):
    """Return true or false can the word be made using the characters in the hand"""
    for i in word: # for each character in word
        if hand.count(i)<word.count(i): # is the character in the hand enough times
            return False
    return True # if every character in the word is present in the hand
</code>```

My question is how can I build a query that checks each character in a word and making sure that the number of appearances of that character is not greater than the number of appearances in a string?
Or is this not a job for a database?

Thanks in advance.

答:
That's not the job of a (relational) database, to be completely frank.

Since the couple thousand words in English, even if you blow them up to all thinkable declinations, won't exceed a rough 100k words, I really don't see why you'd use a database for that, either. Just write it in python with an in-memory word list that you simply go through linearly.

There's several ways to make searching that amount of data faster, but a relational database can't apply any of them. Also, the speed gain should be negligible, considering letters are single bytes of data.

If you're worried about performance: yes, doing this in python does have a significant runtime overhead, because counting letters is very fast and can be highly optimized, but python itself is a complex language and executing it sets some limits.

Considering the amount of data to be handled to be rather small, my approach would be:

Prepare a wordlist: sort the letters of each word in your dictionary alphabetically, and use the sorted strings as keys for the actual words. You'll find that one sorted string can map to multiple words.

Sort the letters of your hand

For every key in your word list, check whether it's a subset of your hand. That should be really fast, because the previous sorting allows you to avoid redundant checks (i.e. if your at the beginning of your wordlist, the first word starts with an a, but your lowest hand letter is e, skip to the first word that starts with an e).

Tree structures of any kind could, algorithmically, be faster, but on most PC-style processors, nicely written C code will compile to very fast SIMD'ed string comparisons.

Body:
I have a table containing a list of English words from which I am trying to select all the words which can be made with a given string "hand" (as in the game scrabble)

+--------+
|  word  |
+--------+
| test   |
| father |
| woman  |
| zebra  |
+--------+

The query I have so far will only check that any of the characters in the hand are present in the word.

SELECT * FROM words WHERE word SIMILAR to '%e%|%z%|%h%';
/* returns test, father and zebra as they all contain either e,z or h */

However this does not take into account whether a word contains a character more times than the hand does, the code I am using in python to check whether a word is valid

def isValidWord(word, hand):
    """Return true or false can the word be made using the characters in the hand"""
    for i in word: # for each character in word
        if hand.count(i)<word.count(i): # is the character in the hand enough times
            return False
    return True # if every character in the word is present in the hand

My question is how can I build a query that checks each character in a word and making sure that the number of appearances of that character is not greater than the number of appearances in a string?
Or is this not a job for a database?

Thanks in advance.


问:
Is it possible to make this query using CodeIgniter's Query Builder?
Query:

```<code>select (exists (select 1 from table1 where url = 'fajne-to-jest')) as in_table1,
       (exists (select 1 from table2 where url = 'fajne-to-jest')) as in_table2;
</code>```

I don't see function like exist.

I don't think it is possible but maybe I am wrong.

So question is, is it possible to create this complex query with only CodeIgniter's query builder?

答:
Probably not as well optimized as your example. The easiest solution is to not use Querybuilder and write the statement directly for use in query().

```<code>$sql = "select (exists (select 1 from table1 where url = 'fajne-to-jest')) as in_table1,
               (exists (select 1 from table2 where url = 'fajne-to-jest')) as in_table2";
$query = $this->db->query($sql);
</code>```

Querybuilder (QB) is a great tool but it is often (perhaps more often than not) completely unnecessary. The primary task of QB is to build a query statement. Why execute a whole lot of code to create easily written queries?

QB is great in situations where you need to conditionally alter the query statement. For example adding where clauses, changing sort order etc.

Body:
Query:

select (exists (select 1 from table1 where url = 'fajne-to-jest')) as in_table1,
       (exists (select 1 from table2 where url = 'fajne-to-jest')) as in_table2;

I don't see function like exist.

I don't think it is possible but maybe I am wrong.

So question is, is it possible to create this complex query with only CodeIgniter's query builder?

Body:
Probably not as well optimized as your example. The easiest solution is to not use Querybuilder and write the statement directly for use in query().

$sql = "select (exists (select 1 from table1 where url = 'fajne-to-jest')) as in_table1,
               (exists (select 1 from table2 where url = 'fajne-to-jest')) as in_table2";
$query = $this->db->query($sql);

Querybuilder (QB) is a great tool but it is often (perhaps more often than not) completely unnecessary. The primary task of QB is to build a query statement. Why execute a whole lot of code to create easily written queries?

QB is great in situations where you need to conditionally alter the query statement. For example adding where clauses, changing sort order etc.


问:
Login to WebForm using Powershell
I've been trying for a while to Login to a site, navigate through it and download file at conditions. I've tried with PhantomJs but failed miserably.

Now I'm trying with a Powershell approach and I've been looking around to how get the first step, logging into the the form to get to the next page.

The last site I've followed the hints was PowerShell Getting Started the very last topic "Logging In To Web Sites"

The site which I'm trying to log in: ACSMAMGA

It's seems a very easy login form, so I setp up the powershell code like this:

```<code>#Input User and Password - Set UserAgent - Store the WebRequest

 $credential = Get-Credential
 $uaString   = [Microsoft.PowerShell.Commands.PSUserAgent]::FireFox
 $webRequest = Invoke-WebRequest -Uri 'http://portal.reti.acsm-agam.it/Portal/Index.aspx?m=200G&area=B2B' -SessionVariable webSession -UserAgent $uaString

#Store the form with id 'form1' into variable - Set fields of the form with the credential inputted before

 $loginForm= $webRequest.Forms | Where-Object {$_.Id -eq 'form1'}
 $loginForm.Fields.twsTemplate_Content1_twsModule_txtUser   = $credential.UserName
 $loginForm.Fields.twsTemplate_Content1_twsModule_txtPSW = $credential.GetNetworkCredential().Password

#Set New Request with new data, I change the -uri $loginform.action to the actual site because it actually set it to Index.aspx?m=200G&area=B2B which is just the last part of the actual site "http://portal.reti.acsm-agam.it/Portal/Index.aspx?m=200G&area=B2B" and it will raise an error

 $webRequest = Invoke-WebRequest -Uri $loginForm.Action -Method $loginForm.Method -Body $loginForm.Fields -WebSession $webSession -UserAgent $uaString

#Check if login has been successfuf,changed the Where-Object statment to an actual element that can be found in page that get showed after loggin in.

if ($webRequest.Links | Where-Object {$_.id -like ('*' + "twsTemplate_Header1_LogOff1_LnkLOF" + '*')}) {

    Write-Host "Login verified!"

} else {

    Write-Host 'Login unsuccessful!' -ForegroundColor Red -BackgroundColor DarkBlue

}
</code>```

Ofcourse the If Statement return "Login unsuccessful".

There might be something else in the login page that get involved after sending the request.
I've noted there are some input fields that are hidden (I guess they are some token, dunno how those things work) and 3 javascript running in background but dunno what they do and I read they are wrapper for function or such).

Would be great if anyone can take down this. It's long time i've been trying to automate the access to those type of sites.
Thank you

Edit:08.06.2017
HI've been doing some more test.
It seems that the problemi that it's blocking me to get to next page after the login is how the inputfields are passed.
Actually usgin:

```<code> $loginForm.Fields.twsTemplate_Content1_twsModule_txtUser   = $credential.UserName
 $loginForm.Fields.twsTemplate_Content1_twsModule_txtPSW = $credential.GetNetworkCredential().Password
</code>```

Dont' work, instead passing the same value but like

```<code>$loginForm.Fields['twsTemplate$Content1$twsModule$txtUser']= $credential.UserName
     $loginForm.Fields['twsTemplate$Content1$twsModule$txtPSW'] = $credential.GetNetworkCredential().Password
</code>```

get the work done (note the "$" instead of "_" and the "'" that wrap the name or the $ would be treated as variable.
I even had to add "twsTemplate_Content1_twsModule_btnLogin Login" which is already setted in the page but still I have to convert the "_" with "$" and set the value as above.

I don't get why this work but actually worked ...

edit 17.07.2017
I should have know before but I get on the programmin subject only in spare time as it not my work. Those field with the "$" work as in the post method you have to pass the name attribute of the field, which in my case are those with the $.

答:
So this uses the post information and signs in if you have the correct login.
It also brings back a Session so you can keep interacting with the site.</p>

```<code>function Login([string]$Address,[pscredential]$credential){
    if(!$credential){
        $credential = Get-Credential
    }
    $post = "__EVENTTARGET=&__EVENTARGUMENT=&__VIEWSTATE=%2FwEPDwUJNzY0OTc5NDQ5D2QWAgIDD2QWBAIBDw8WAh4HVmlzaWJsZWhkFgICAQ9kFgICAQ8PZBYCHgdvbmNsaWNrBZIBamF2YXNjcmlwdDp3aW5kb3cub3BlbignaW5mb0Nvb2tpZS5hc3B4JywnR3VpZGEnLCAnd2lkdGg9ODAwLGhlaWdodD02MDAsbGVmdD02MDAsdG9wPTEwMCwgc2Nyb2xsYmFycz15ZXMsIG1lbnViYXI9bm8sIHRvb2xiYXI9bm8sIHJlc2l6YWJsZT15ZXMnKTtkAgUPZBYCZg9kFgYCAQ9kFgJmD2QWAmYPFgIfAGhkAgMPZBYCZg9kFgRmD2QWAmYPZBYCAgEPFgIfAGhkAgEPZBYCAgEPDxYCHgRUZXh0BTVWZXJpZmljYSBkaSBhdmVyZSBpbnNlcml0byBjb3JyZXR0YW1lbnRlIGkgdHVvaSBkYXRpLmRkAgUPZBYCZg9kFgICAQ8PFgIfAgUQUmVsLiAyLjAuMDk0KDAzKWRkZP4%2BMa9cyFCJx8l%2BEYykopVYA0gwPUz3FbFyI0NAU1WC&__VIEWSTATEGENERATOR=DF200D8E&__EVENTVALIDATION=%2FwEWBAK8z%2BQMAsaPwpsGAqnL470LAq%2F5qKcIp5vlm7cytSxOzkYL2ESDraZWLoQRji0OxUOW9t%2FXBRI%3D&smRetiWeb=&twsTemplate%24Content1%24twsModule%24txtUser=$($credential.GetNetworkCredential().UserName)&twsTemplate%24Content1%24twsModule%24txtPSW=$($credential.GetNetworkCredential().Password)&twsTemplate%24Content1%24twsModule%24btnLogin=Login"
    $Information = Invoke-WebRequest -Uri $Address -Method POST -Body $Post -SessionVariable WebSession
    return $WebSession
}

login -Address "http://portal.reti.acsm-agam.it/Portal/Index.aspx?idn=0005&area=B2B"
</code>```

Title: Login to WebForm using Powershell

Body:
I've been trying for a while to Login to a site, navigate through it and download file at conditions. I've tried with PhantomJs but failed miserably.

Now I'm trying with a Powershell approach and I've been looking around to how get the first step, logging into the the form to get to the next page.

The last site I've followed the hints was PowerShell Getting Started the very last topic "Logging In To Web Sites"

The site which I'm trying to log in: ACSMAMGA

It's seems a very easy login form, so I setp up the powershell code like this:

#Input User and Password - Set UserAgent - Store the WebRequest

 $credential = Get-Credential
 $uaString   = [Microsoft.PowerShell.Commands.PSUserAgent]::FireFox
 $webRequest = Invoke-WebRequest -Uri 'http://portal.reti.acsm-agam.it/Portal/Index.aspx?m=200G&area=B2B' -SessionVariable webSession -UserAgent $uaString

#Store the form with id 'form1' into variable - Set fields of the form with the credential inputted before

 $loginForm= $webRequest.Forms | Where-Object {$_.Id -eq 'form1'}
 $loginForm.Fields.twsTemplate_Content1_twsModule_txtUser   = $credential.UserName
 $loginForm.Fields.twsTemplate_Content1_twsModule_txtPSW = $credential.GetNetworkCredential().Password

#Set New Request with new data, I change the -uri $loginform.action to the actual site because it actually set it to Index.aspx?m=200G&area=B2B which is just the last part of the actual site "http://portal.reti.acsm-agam.it/Portal/Index.aspx?m=200G&area=B2B" and it will raise an error

 $webRequest = Invoke-WebRequest -Uri $loginForm.Action -Method $loginForm.Method -Body $loginForm.Fields -WebSession $webSession -UserAgent $uaString

#Check if login has been successfuf,changed the Where-Object statment to an actual element that can be found in page that get showed after loggin in.

if ($webRequest.Links | Where-Object {$_.id -like ('*' + "twsTemplate_Header1_LogOff1_LnkLOF" + '*')}) {

    Write-Host "Login verified!"

} else {

    Write-Host 'Login unsuccessful!' -ForegroundColor Red -BackgroundColor DarkBlue

}

Ofcourse the If Statement return "Login unsuccessful".

There might be something else in the login page that get involved after sending the request.
I've noted there are some input fields that are hidden (I guess they are some token, dunno how those things work) and 3 javascript running in background but dunno what they do and I read they are wrapper for function or such).

Would be great if anyone can take down this. It's long time i've been trying to automate the access to those type of sites.
Thank you

Edit:08.06.2017
HI've been doing some more test.
It seems that the problemi that it's blocking me to get to next page after the login is how the inputfields are passed.
Actually usgin:

 $loginForm.Fields.twsTemplate_Content1_twsModule_txtUser   = $credential.UserName
 $loginForm.Fields.twsTemplate_Content1_twsModule_txtPSW = $credential.GetNetworkCredential().Password

Dont' work, instead passing the same value but like

$loginForm.Fields['twsTemplate$Content1$twsModule$txtUser']= $credential.UserName
     $loginForm.Fields['twsTemplate$Content1$twsModule$txtPSW'] = $credential.GetNetworkCredential().Password

get the work done (note the "$" instead of "_" and the "'" that wrap the name or the $ would be treated as variable.
I even had to add "twsTemplate_Content1_twsModule_btnLogin Login" which is already setted in the page but still I have to convert the "_" with "$" and set the value as above.

I don't get why this work but actually worked ...

edit 17.07.2017
I should have know before but I get on the programmin subject only in spare time as it not my work. Those field with the "$" work as in the post method you have to pass the name attribute of the field, which in my case are those with the $.

Body:
So this uses the post information and signs in if you have the correct login.
It also brings back a Session so you can keep interacting with the site.

function Login([string]$Address,[pscredential]$credential){
    if(!$credential){
        $credential = Get-Credential
    }
    $post = "__EVENTTARGET=&__EVENTARGUMENT=&__VIEWSTATE=%2FwEPDwUJNzY0OTc5NDQ5D2QWAgIDD2QWBAIBDw8WAh4HVmlzaWJsZWhkFgICAQ9kFgICAQ8PZBYCHgdvbmNsaWNrBZIBamF2YXNjcmlwdDp3aW5kb3cub3BlbignaW5mb0Nvb2tpZS5hc3B4JywnR3VpZGEnLCAnd2lkdGg9ODAwLGhlaWdodD02MDAsbGVmdD02MDAsdG9wPTEwMCwgc2Nyb2xsYmFycz15ZXMsIG1lbnViYXI9bm8sIHRvb2xiYXI9bm8sIHJlc2l6YWJsZT15ZXMnKTtkAgUPZBYCZg9kFgYCAQ9kFgJmD2QWAmYPFgIfAGhkAgMPZBYCZg9kFgRmD2QWAmYPZBYCAgEPFgIfAGhkAgEPZBYCAgEPDxYCHgRUZXh0BTVWZXJpZmljYSBkaSBhdmVyZSBpbnNlcml0byBjb3JyZXR0YW1lbnRlIGkgdHVvaSBkYXRpLmRkAgUPZBYCZg9kFgICAQ8PFgIfAgUQUmVsLiAyLjAuMDk0KDAzKWRkZP4%2BMa9cyFCJx8l%2BEYykopVYA0gwPUz3FbFyI0NAU1WC&__VIEWSTATEGENERATOR=DF200D8E&__EVENTVALIDATION=%2FwEWBAK8z%2BQMAsaPwpsGAqnL470LAq%2F5qKcIp5vlm7cytSxOzkYL2ESDraZWLoQRji0OxUOW9t%2FXBRI%3D&smRetiWeb=&twsTemplate%24Content1%24twsModule%24txtUser=$($credential.GetNetworkCredential().UserName)&twsTemplate%24Content1%24twsModule%24txtPSW=$($credential.GetNetworkCredential().Password)&twsTemplate%24Content1%24twsModule%24btnLogin=Login"
    $Information = Invoke-WebRequest -Uri $Address -Method POST -Body $Post -SessionVariable WebSession
    return $WebSession
}

login -Address "http://portal.reti.acsm-agam.it/Portal/Index.aspx?idn=0005&area=B2B"


问:
Convert html anchor tag to mvc action link
I have this basic anchor tag inhtml

```<code><a href="signup.html" class="signup-button">CREER UN COMPTE</a>
</code>```

how can i convert it to mvc action link along with the css class.

答:
Try this guy:

```<code>@Html.ActionLink("CREER UN COMPTE", "MyAction", "MyController", null, null, "MyAnchor", null, new {@class="signup-button"})
</code>```

Reference to extension method here: https://msdn.microsoft.com/en-us/library/dd460522.aspx

```<code>public static MvcHtmlString ActionLink(
 this HtmlHelper htmlHelper,
 string linkText,
 string actionName,
 string controllerName,
 string protocol,
 string hostName,
 string fragment,
 Object routeValues,
 Object htmlAttributes
)
</code>```

Body:
I have this basic anchor tag inhtml

CREER UN COMPTE

how can i convert it to mvc action link along with the css class.

Body:
Try this guy:

@Html.ActionLink("CREER UN COMPTE", "MyAction", "MyController", null, null, "MyAnchor", null, new {@class="signup-button"})

Reference to extension method here: https://msdn.microsoft.com/en-us/library/dd460522.aspx

public static MvcHtmlString ActionLink(
 this HtmlHelper htmlHelper,
 string linkText,
 string actionName,
 string controllerName,
 string protocol,
 string hostName,
 string fragment,
 Object routeValues,
 Object htmlAttributes
)


问:
Simple email forwarding server
I need to forward emails for a several domains to other email addresses. Previously I have used hMailServer on my Windows server to perform this forwarding function, but I am looking for something simpler that I can interface with from a .NET application.

Is there a simple email forwarding server I can easily manage from .NET? Spam filtering or email storage is not required.

答:
I've never used hMailServer but according to the documentation there's a COM API that looks like it would be automation compatible (since they've got VBScript samples) so you should be able to access this from .Net.

I'd suggest looking at the Rule object or the forum

Title: Simple email forwarding server


问:
Android "?colorPrimary" vs "?attr/colorPrimary"?
I can't find any information about the differences between:

```<code>android:textColor="?attr/colorPrimary"
</code>```

vs

```<code>android:textColor="?colorPrimary"
</code>```

I have read that "?attr" means attribute value specified in the current theme, but without "attr" it gives the same result (=color defined in my theme). It behaves similar with other attributes?

For example:

Does android:background="?attr/selectableItemBackground"
equals android:background="?selectableItemBackground" ?

Here it's told that it differs.

Thanks very much.

答:
Ok, I have finally found in the docs:

Because the system resource tool knows that an attribute resource is expected in this context, you do not need to explicitly state the type (which would be ?android:attr/textColorSecondary)—you can exclude the attr type.

So, I deducted it's like this: the AppCompat library attributes are treated as custom attributes and as a result we point them by a question mark without "android" keyword. And "attr" is type of resource which is optional for both platform and custom attributes (from docs).
Android documentation

Body:
I can't find any information about the differences between:

android:textColor="?attr/colorPrimary"

vs

android:textColor="?colorPrimary"

I have read that "?attr" means attribute value specified in the current theme, but without "attr" it gives the same result (=color defined in my theme). It behaves similar with other attributes?

For example:

Does android:background="?attr/selectableItemBackground"
equals android:background="?selectableItemBackground" ?

Here it's told that it differs.

Thanks very much.