问:
linux perf: how to interpret and find hotspots
I tried out linux' perf utility today and am having trouble in interpreting its results. I'm used to valgrind's callgrind which is of course a totally different approach to the sampling based method of perf.

What I did:

```<code>perf record -g -p $(pidof someapp)
perf report -g -n
</code>```

Now I see something like this:

```
+     16.92%  kdevelop  libsqlite3.so.0.8.6               [.] 0x3fe57                                                                                ↑
+     10.61%  kdevelop  libQtGui.so.4.7.3                 [.] 0x81e344                                                                                ▮
+      7.09%  kdevelop  libc-2.14.so                      [.] 0x85804                                                                                ▒
+      4.96%  kdevelop  libQtGui.so.4.7.3                 [.] 0x265b69                                                                                ▒
+      3.50%  kdevelop  libQtCore.so.4.7.3                [.] 0x18608d                                                                                ▒
+      2.68%  kdevelop  libc-2.14.so                      [.] memcpy                                                                                ▒
+      1.15%  kdevelop  [kernel.kallsyms]                 [k] copy_user_generic_string                                                                                ▒
+      0.90%  kdevelop  libQtGui.so.4.7.3                 [.] QTransform::translate(double, double)                                                                                ▒
+      0.88%  kdevelop  libc-2.14.so                      [.] __libc_malloc                                                                                ▒
+      0.85%  kdevelop  libc-2.14.so                      [.] memcpy
...
```

Ok, these functions might be slow, but how do I find out where they are getting called from? As all these hotspots lie in external libraries I see no way to optimize my code.

Basically I am looking for some kind of callgraph annotated with accumulated cost, where my functions have a higher inclusive sampling cost than the library functions I call.

Is this possible with perf? If so - how?

Note: I found out that "E" unwraps the callgraph and gives somewhat more information. But the callgraph is often not deep enough and/or terminates randomly without giving information about how much info was spent where. Example:

```
-     10.26%  kate  libkatepartinterfaces.so.4.6.0  [.] Kate::TextLoader::readLine(int&...
     Kate::TextLoader::readLine(int&, int&)
     Kate::TextBuffer::load(QString const&, bool&, bool&)
     KateBuffer::openFile(QString const&)
     KateDocument::openFile()
     0x7fe37a81121c
```

Could it be an issue that I'm running on 64 bit? See also: http://lists.fedoraproject.org/pipermail/devel/2010-November/144952.html (I'm not using fedora but seems to apply to all 64bit systems).

答:
You should give hotspot a try:
https://www.kdab.com/hotspot-gui-linux-perf-profiler/

It's available on github: https://github.com/KDAB/hotspot

It is for example able to generate flamegraphs for you.

Body:
I tried out linux' perf utility today and am having trouble in interpreting its results. I'm used to valgrind's callgrind which is of course a totally different approach to the sampling based method of perf.

What I did:

perf record -g -p $(pidof someapp)
perf report -g -n

Now I see something like this:

+     16.92%  kdevelop  libsqlite3.so.0.8.6               [.] 0x3fe57                                                                                ↑
+     10.61%  kdevelop  libQtGui.so.4.7.3                 [.] 0x81e344                                                                                ▮
+      7.09%  kdevelop  libc-2.14.so                      [.] 0x85804                                                                                ▒
+      4.96%  kdevelop  libQtGui.so.4.7.3                 [.] 0x265b69                                                                                ▒
+      3.50%  kdevelop  libQtCore.so.4.7.3                [.] 0x18608d                                                                                ▒
+      2.68%  kdevelop  libc-2.14.so                      [.] memcpy                                                                                ▒
+      1.15%  kdevelop  [kernel.kallsyms]                 [k] copy_user_generic_string                                                                                ▒
+      0.90%  kdevelop  libQtGui.so.4.7.3                 [.] QTransform::translate(double, double)                                                                                ▒
+      0.88%  kdevelop  libc-2.14.so                      [.] __libc_malloc                                                                                ▒
+      0.85%  kdevelop  libc-2.14.so                      [.] memcpy
...

Ok, these functions might be slow, but how do I find out where they are getting called from? As all these hotspots lie in external libraries I see no way to optimize my code.

Basically I am looking for some kind of callgraph annotated with accumulated cost, where my functions have a higher inclusive sampling cost than the library functions I call.

Is this possible with perf? If so - how?

Note: I found out that "E" unwraps the callgraph and gives somewhat more information. But the callgraph is often not deep enough and/or terminates randomly without giving information about how much info was spent where. Example:

-     10.26%  kate  libkatepartinterfaces.so.4.6.0  [.] Kate::TextLoader::readLine(int&...
     Kate::TextLoader::readLine(int&, int&)
     Kate::TextBuffer::load(QString const&, bool&, bool&)
     KateBuffer::openFile(QString const&)
     KateDocument::openFile()
     0x7fe37a81121c

Could it be an issue that I'm running on 64 bit? See also: http://lists.fedoraproject.org/pipermail/devel/2010-November/144952.html (I'm not using fedora but seems to apply to all 64bit systems).


来源: stackexchange

问:
Changing the site root in plone.app.testing/Plone 4
Is there a way to change the PLONE_SITE_ID from its default at plone.app.testing.interfaces without modifying the source code?

I'm using Plone 4 with several custom products, and plone.app.testing (4.0.2) with relative success. In my custom products, there are several instances where there are hardcoded physical paths to locate objects when performing catalog searches (e.g., my site root is 'mySiteID', so several custom queries use path=/mySiteID/folder1/etc.. to do catalog searches).

The problem is that the site root in the Plone instance that plone.app.testing configures (PLONE_FIXTURE) is PLONE_SITE_ID = 'plone'. Therefore, any objects that I add in my tests always have /plone as the root rather than /mySiteID and my tests break. I can fix this problem by changing the defined value in the interface but this seems like an ugly hack.

答:
Martijn is correct. Though, his answer does not fully do the trick. You need to monkey patch multiple plone.app.testing imports to make this actually work:</p>

```<code>[test]
...

initialization =
    import plone.app.testing.helpers
    plone.app.testing.helpers.PLONE_SITE_ID = 'Plone'
    import plone.app.testing.interfaces
    plone.app.testing.interfaces.PLONE_SITE_ID = 'Plone'
    import plone.app.testing.layers
    plone.app.testing.layers.PLONE_SITE_ID = 'Plone'
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Martijn is correct. Though, his answer does not fully do the trick. You need to monkey patch multiple plone.app.testing imports to make this actually work:

[test]
...

initialization =
    import plone.app.testing.helpers
    plone.app.testing.helpers.PLONE_SITE_ID = 'Plone'
    import plone.app.testing.interfaces
    plone.app.testing.interfaces.PLONE_SITE_ID = 'Plone'
    import plone.app.testing.layers
    plone.app.testing.layers.PLONE_SITE_ID = 'Plone'


问:
For loop within a foreach loop java
So i have this code segment. searchStudentWith2RUCode() returns an Arraylist of Student objects. Student objects have various attributes such as forename, lastname, cprnumber, gpa etc.

```<code> public void assignStudents() throws ClassNotFoundException, SQLException {
     ArrayList<Student> notYetAssignedStudents = searchStudentsWith2RUCode();
     ArrayList<Student> assignedStudents = new ArrayList<>()
          for (Education edu : eduList) {

               for (int i = 0; i < edu.getAmountOfFreeSpacesInEdu(); i++) {
                  assignedStudents.add(notAssignedStudents.get(i));
                  setAssignedStudentsAdmitted(assignedStudents.get(i).getCPR, assignedStudents.get(i).getPrio, assignedStudents.get(i).eduNumber)
        }
    }
}
</code>```

setAssignedStudentsAdmitted updates my database and should set the field "sagsbehandling" in my table "students" as "Optaget" at each admitted student. However this doesnt work.
Im suspecting my for loops, but Im lost, i can't figure out why it doesn't work.

Here is my setAssignedStudentsAdmitted method:

```<code> public void setAssignedStudentsAdmitted(String CPR, int prio, int eduNumber) throws ClassNotFoundException, SQLException {

    //Declare a UPDATE statement
    String updateStmt
            = "UPDATE Students SET sagsbehandling='Optaget' WHERE cprnr ='" + CPR + "' AND prio='" + prio + "' AND eduNumber='" + eduNumber + "';";

    //Execute UPDATE operation
    try {
        DatabaseController.dbExecuteUpdate(updateStmt);
    } catch (SQLException e) {
        System.out.print("Error occurred while DELETE Operation: " + e);
        throw e;
    }
}
</code>```

}

And here is my dbExecuteUpdate method that is called in setAssignedStudentsAdmitted

```<code>    public static void dbExecuteUpdate(String sqlStmt) throws SQLException, ClassNotFoundException {
    //Declare statement as null
    Statement stmt = null;
    try {
        //Connect to DB (Establish Postgres Connection)
        databaseConnect();
        //Create Statement
        stmt = conn.createStatement();
        //Run executeUpdate operation with given sql statement
        stmt.executeUpdate(sqlStmt);
    } catch (SQLException e) {
        System.out.println("Problem occurred at executeUpdate operation : " + e);
        throw e;
    } finally {
        if (stmt != null) {
            //Close statement
            stmt.close();
        }
        //Close connection
        databaseDisconnect();
    }
}
</code>```

It builds succesfully, but changes nothing in my Database.

答: May be you have autoCommit set to false? Make sure on your databaseConnect(), or for a quick test perform a Commit at the end.</p>

Title: For loop within a foreach loop java

Body:
So i have this code segment. searchStudentWith2RUCode() returns an Arraylist of Student objects. Student objects have various attributes such as forename, lastname, cprnumber, gpa etc.

 public void assignStudents() throws ClassNotFoundException, SQLException {
     ArrayList<Student> notYetAssignedStudents = searchStudentsWith2RUCode();
     ArrayList<Student> assignedStudents = new ArrayList<>()
          for (Education edu : eduList) {

               for (int i = 0; i < edu.getAmountOfFreeSpacesInEdu(); i++) {
                  assignedStudents.add(notAssignedStudents.get(i));
                  setAssignedStudentsAdmitted(assignedStudents.get(i).getCPR, assignedStudents.get(i).getPrio, assignedStudents.get(i).eduNumber)
        }
    }
}

setAssignedStudentsAdmitted updates my database and should set the field "sagsbehandling" in my table "students" as "Optaget" at each admitted student. However this doesnt work.
Im suspecting my for loops, but Im lost, i can't figure out why it doesn't work.

Here is my setAssignedStudentsAdmitted method:

 public void setAssignedStudentsAdmitted(String CPR, int prio, int eduNumber) throws ClassNotFoundException, SQLException {

    //Declare a UPDATE statement
    String updateStmt
            = "UPDATE Students SET sagsbehandling='Optaget' WHERE cprnr ='" + CPR + "' AND prio='" + prio + "' AND eduNumber='" + eduNumber + "';";

    //Execute UPDATE operation
    try {
        DatabaseController.dbExecuteUpdate(updateStmt);
    } catch (SQLException e) {
        System.out.print("Error occurred while DELETE Operation: " + e);
        throw e;
    }
}

}

And here is my dbExecuteUpdate method that is called in setAssignedStudentsAdmitted

    public static void dbExecuteUpdate(String sqlStmt) throws SQLException, ClassNotFoundException {
    //Declare statement as null
    Statement stmt = null;
    try {
        //Connect to DB (Establish Postgres Connection)
        databaseConnect();
        //Create Statement
        stmt = conn.createStatement();
        //Run executeUpdate operation with given sql statement
        stmt.executeUpdate(sqlStmt);
    } catch (SQLException e) {
        System.out.println("Problem occurred at executeUpdate operation : " + e);
        throw e;
    } finally {
        if (stmt != null) {
            //Close statement
            stmt.close();
        }
        //Close connection
        databaseDisconnect();
    }
}

It builds succesfully, but changes nothing in my Database.


问:
How to complete Akka Http response with Stream and Custom Status Code
I've got an akka-http application that uses akka-streams for data processing. So, it makes some sense to complete the request with Source[Result, _] to get backpressure across HTTP boundary for free.

Versions:

akka-http 10.0.7

akka-streams 2.5.2

akka 2.5.2

This is the simplified version of the code, and it works just fine.

```<code>pathEnd { post { entity(asSourceOf[Request]) { _ =>
    complete {
        Source.single("ok")
    }
}}}
</code>```

Since this enpoint is supposed to create and entity, instead of returning 200 OK to the requester I'd like to return 204 CREATED status code. However, I wasn't able to find a way to do that:

complete { Created -> source.single("ok") } fails compilation with Type mismatch, expected: ToResponseMarshallable, actual: (StatusCodes.Success, Source[String, NotUsed])

complete { source.single((Created, "ok")) } fails with Type mismatch, expected: ToResponseMarshallable, actual: Source[(StatusCodes.Success, String), NotUsed]

complete(Created) { Source.single("ok") } fails with Type mismatch, expected: RequestContext, actual: Source[String,NotUsed]

complete(Created, Source.signle("ok") fails with too many arguments for method complete(m: => ToResponseMarshallable)

It looks like custom marshaller might be a way to achieve that, but it'll basically mean I'll need one unmarshaller per endpoint, which isn't quite convenient or clear.

So, the question is, are there a (more convenient than custom unmarshaller) way to complete the request with Source[_,_] while also providing status code.

答:
From the documentation:

```<code>complete(Created -> "bar")
</code>```

If you want to provide some Source of data then construct the HttpResponse and pass it to complete:

```<code>import akka.http.scaladsl.model.HttpEntity.Chunked
import akka.http.scaladsl.model.ContentTypes
import akka.http.scaladsl.model.HttpEntity.ChunkStreamPart

complete {

  val entity =
    Chunked(ContentTypes.`text/plain(UTF-8)`,
            Source.single("ok").map(ChunkStreamPart.apply))

  HttpResponse(status = Created, entity=entity)
}
</code>```

Body:
I've got an akka-http application that uses akka-streams for data processing. So, it makes some sense to complete the request with Source[Result, _] to get backpressure across HTTP boundary for free.

Versions:

akka-http 10.0.7

akka-streams 2.5.2

akka 2.5.2

This is the simplified version of the code, and it works just fine.

pathEnd { post { entity(asSourceOf[Request]) { _ =>
    complete {
        Source.single("ok")
    }
}}}

Since this enpoint is supposed to create and entity, instead of returning 200 OK to the requester I'd like to return 204 CREATED status code. However, I wasn't able to find a way to do that:

complete { Created -> source.single("ok") } fails compilation with Type mismatch, expected: ToResponseMarshallable, actual: (StatusCodes.Success, Source[String, NotUsed])

complete { source.single((Created, "ok")) } fails with Type mismatch, expected: ToResponseMarshallable, actual: Source[(StatusCodes.Success, String), NotUsed]

complete(Created) { Source.single("ok") } fails with Type mismatch, expected: RequestContext, actual: Source[String,NotUsed]

complete(Created, Source.signle("ok") fails with too many arguments for method complete(m: => ToResponseMarshallable)

It looks like custom marshaller might be a way to achieve that, but it'll basically mean I'll need one unmarshaller per endpoint, which isn't quite convenient or clear.

So, the question is, are there a (more convenient than custom unmarshaller) way to complete the request with Source[_,_] while also providing status code.

Body:
From the documentation:

complete(Created -> "bar")

If you want to provide some Source of data then construct the HttpResponse and pass it to complete:

import akka.http.scaladsl.model.HttpEntity.Chunked
import akka.http.scaladsl.model.ContentTypes
import akka.http.scaladsl.model.HttpEntity.ChunkStreamPart

complete {

  val entity =
    Chunked(ContentTypes.`text/plain(UTF-8)`,
            Source.single("ok").map(ChunkStreamPart.apply))

  HttpResponse(status = Created, entity=entity)
}


问:
Chrome malforms li > a > ul > li > a HTML
Chrome is changing the structure of my HTML for seemingly no reason, removing the second level anchor tag generates the expected html and replacing it with a div or any other tag also works fine. Fiddle

Written code:

```<code><ul>
  <li>
    <a href="/">
      Whatup
      <ul>
        <li>
          <a href="/test/">Yo</a>
        </li>
      </ul>
    </a>
  </li>
</ul>
</code>```

Interpreted code:

```<code><ul>
  <li>
    <a href="/">
      Whatup
    </a>
    <ul>
      <a href="/"></a>
      <li>
        <a href="/"></a>
        <a href="/test/">Yo</a>
      </li>
    </ul>
  </li>
</ul>
</code>```

Example working code:

```<code><ul>
  <li>
    <a href="/">
      Whatup
      <ul>
        <li>
          <div>Yo</div>
        </li>
      </ul>
    </a>
  </li>
</ul>
</code>```

答:
You have another a in the inner list. This is what's causing the inner ul to break out of the outer a, since you cannot have an a within another a (otherwise, the browser doesn't know how to handle clicking the inner a).

In other words, it's not Chrome that's malforming your HTML — your HTML is malformed to begin with.

Body:
Chrome is changing the structure of my HTML for seemingly no reason, removing the second level anchor tag generates the expected html and replacing it with a div or any other tag also works fine. Fiddle

Written code:

      Whatup

          Yo

Interpreted code:

      Whatup

        Yo

Example working code:

      Whatup

Yo


问:
Query related posts, Wrap in Row every 3 posts
I'm trying to query some related posts and wrap them in a row div every 3 posts. I've checked all the questions regarding this but still my query renders a mess.
This is what I have so far:

```<code><?php
$related = get_posts( array(
'category__in' => wp_get_post_categories($post->ID),
'numberposts' => 6,
'post__not_in' => array($post->ID) ) );
$counter=0;
if( $related ) foreach( $related as $post ) {
setup_postdata($post); $counter++;
 ?>

<div class="row">
    <article class="third-width">
        <a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>" class="third-link">
            <?php  the_post_thumbnail('post-parrilla'); ?>
        </a>
<?php exclude_post_categories("8"); ?>
<div class="clear"></div>
    <a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>" class="third-link">
        <div class="post-title">
        <span><?php the_title(); ?></span>
        </div>
    </a>
    </article>

<?php if ($counter%3==0):?>
    </div><div class="row">
<?php endif;?>
<?php } wp_reset_postdata(); ?>
</code>```

Thank you in advance

答:
Use below code </p>

```<code> <?php
$related = get_posts( array(
'category__in' => wp_get_post_categories($post->ID),
'numberposts' => 6,
'post__not_in' => array($post->ID) ) );

if( $related )
{
    $counter = 0;
    ?>
    <div class="row">
    <?php
    foreach( $related as $post ) {
    setup_postdata($post);

     if ($counter%3==0){
     ?>
        </div><div class="row">
       <?php
     }
    ?>

        <article class="third-width">
            <a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>" class="third-link">
                <?php  the_post_thumbnail('post-parrilla'); ?>
            </a>
    <?php exclude_post_categories("8"); ?>
    <div class="clear"></div>
        <a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>" class="third-link">
            <div class="post-title">
            <span><?php the_title(); ?></span>
            </div>
        </a>
        </article>

     <?php
     $counter++;
    }
    ?>
    </div>
    <?php
}
wp_reset_postdata();
?>
</code>```

Body:
I'm trying to query some related posts and wrap them in a row div every 3 posts. I've checked all the questions regarding this but still my query renders a mess.
This is what I have so far:

<?php
$related = get_posts( array(
'category__in' => wp_get_post_categories($post->ID),
'numberposts' => 6,
'post__not_in' => array($post->ID) ) );
$counter=0;
if( $related ) foreach( $related as $post ) {
setup_postdata($post); $counter++;
 ?>

        <a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>" class="third-link">
            <?php  the_post_thumbnail('post-parrilla'); ?>

<?php exclude_post_categories("8"); ?>

    <a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>" class="third-link">

        <?php the_title(); ?>

<?php if ($counter%3==0):?>

<?php endif;?>
<?php } wp_reset_postdata(); ?>

Thank you in advance

Body:
Use below code

 <?php
$related = get_posts( array(
'category__in' => wp_get_post_categories($post->ID),
'numberposts' => 6,
'post__not_in' => array($post->ID) ) );

if( $related )
{
    $counter = 0;
    ?>
    <div class="row">
    <?php
    foreach( $related as $post ) {
    setup_postdata($post);

     if ($counter%3==0){
     ?>
        </div><div class="row">
       <?php
     }
    ?>

        <article class="third-width">
            <a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>" class="third-link">
                <?php  the_post_thumbnail('post-parrilla'); ?>
            </a>
    <?php exclude_post_categories("8"); ?>
    <div class="clear"></div>
        <a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>" class="third-link">
            <div class="post-title">
            <span><?php the_title(); ?></span>
            </div>
        </a>
        </article>

     <?php
     $counter++;
    }
    ?>
    </div>
    <?php
}
wp_reset_postdata();
?>


问:
How to avoid duplicate "using" code
I have a wcf api and wish to wrap all requests inside a transaction

Currently my code looks like this in each endpoint

```<code>public MyCompleteList ReadOrganisations()
    {
        MyCompleteList resp = new MyCompleteList ();
        try
        {
            using (TransactionScope scope = new TransactionScope())
            {
                if (HttpContext.Current.User.Identity.IsAuthenticated)
                {
                    DC_Base browser_request = new DC_Base(PROJECT);
                    browser_request.cmd_user_id = coreDb.GetUserIDFromLoginName(PROJECT,
                        HttpContext.Current.User.Identity.Name);
                    resp =
                        new MyCompleteList (coreSc.User_Read_All_Organisations(browser_request, utils,
                            validation, coreSc, coreDb));
                    scope.Complete();
                }
                else
                {
                    resp.SetResponseNotLoggedIn();
                }

            }
        }
        catch (TransactionAbortedException ex)
        {
            resp.SetResponseServerError();
        }
        catch (ApplicationException ex)
        {
            resp.SetResponseServerError();
        }
        return resp;
    }
</code>```

As you can see if I am to use the "using" transaction scope part in every endpoint (approx 300) its going to be a lot of duplicated code.

is there anyway to reduce the amount of duplication?

答:
You can write a helper method, that handles the transaction logic while calling your actual code as a lambda.

```<code>    public static T Execute<T>(Func<T> func, TransactionExecutionOptions options = null)
    {
        options = options ?? TransactionExecutionOptions.Default;

        T res;
        using (var tx = new TransactionScope(options))
        {
            res = func();
            tx.Complete();
        }

        return res;
    }
</code>```

Depending on your needs you can provide additional arguments to the Func argument; for example, the Execute method could also open a database connection and pass that to the func (then having Func<IDbConnection, T> as parameter type). YMMV.

For your example:

```<code>public MyCompleteList ReadOrganisations()
{
    MyCompleteList resp = new MyCompleteList ();
    try
    {
        resp = Execute(() => {
            if (HttpContext.Current.User.Identity.IsAuthenticated)
            {
                DC_Base browser_request = new DC_Base(PROJECT);
                browser_request.cmd_user_id = coreDb.GetUserIDFromLoginName(PROJECT,
                    HttpContext.Current.User.Identity.Name);
                resp =
                    new MyCompleteList (coreSc.User_Read_All_Organisations(browser_request, utils,
                        validation, coreSc, coreDb));
                scope.Complete();
            }
            else
            {
                resp.SetResponseNotLoggedIn();
            }
       });
    }
    catch (TransactionAbortedException ex)
    {
        resp.SetResponseServerError();
    }
    catch (ApplicationException ex)
    {
        resp.SetResponseServerError();
    }
    return resp;
}
</code>```

If possible, you can also factor the SetResponse*() methods out into a base class or interface (say IMyResponse), thus making it possible to handle this aspect inside the Execute method as well.

```<code>    public static T Execute<T>(Func<T> func, TransactionExecutionOptions options = null) where T : IMyResponse
    {
        options = options ?? TransactionExecutionOptions.Default;

        T res;
        try
        {
            using (var tx = new TransactionScope(options))
            {
                res = func();
                tx.Complete();
            }
        }
        catch (TransactionAbortedException ex)
        {
            res.SetResponseServerError();
        }
        catch (ApplicationException ex)
        {
            res.SetResponseServerError();
        }
        return res;
    }
</code>```

Title: How to avoid duplicate "using" code

Body:
I have a wcf api and wish to wrap all requests inside a transaction

Currently my code looks like this in each endpoint

public MyCompleteList ReadOrganisations()
    {
        MyCompleteList resp = new MyCompleteList ();
        try
        {
            using (TransactionScope scope = new TransactionScope())
            {
                if (HttpContext.Current.User.Identity.IsAuthenticated)
                {
                    DC_Base browser_request = new DC_Base(PROJECT);
                    browser_request.cmd_user_id = coreDb.GetUserIDFromLoginName(PROJECT,
                        HttpContext.Current.User.Identity.Name);
                    resp =
                        new MyCompleteList (coreSc.User_Read_All_Organisations(browser_request, utils,
                            validation, coreSc, coreDb));
                    scope.Complete();
                }
                else
                {
                    resp.SetResponseNotLoggedIn();
                }

            }
        }
        catch (TransactionAbortedException ex)
        {
            resp.SetResponseServerError();
        }
        catch (ApplicationException ex)
        {
            resp.SetResponseServerError();
        }
        return resp;
    }

As you can see if I am to use the "using" transaction scope part in every endpoint (approx 300) its going to be a lot of duplicated code.

is there anyway to reduce the amount of duplication?

Body:
You can write a helper method, that handles the transaction logic while calling your actual code as a lambda.

    public static T Execute<T>(Func<T> func, TransactionExecutionOptions options = null)
    {
        options = options ?? TransactionExecutionOptions.Default;

        T res;
        using (var tx = new TransactionScope(options))
        {
            res = func();
            tx.Complete();
        }

        return res;
    }

Depending on your needs you can provide additional arguments to the Func argument; for example, the Execute method could also open a database connection and pass that to the func (then having Func<IDbConnection, T> as parameter type). YMMV.

For your example:

public MyCompleteList ReadOrganisations()
{
    MyCompleteList resp = new MyCompleteList ();
    try
    {
        resp = Execute(() => {
            if (HttpContext.Current.User.Identity.IsAuthenticated)
            {
                DC_Base browser_request = new DC_Base(PROJECT);
                browser_request.cmd_user_id = coreDb.GetUserIDFromLoginName(PROJECT,
                    HttpContext.Current.User.Identity.Name);
                resp =
                    new MyCompleteList (coreSc.User_Read_All_Organisations(browser_request, utils,
                        validation, coreSc, coreDb));
                scope.Complete();
            }
            else
            {
                resp.SetResponseNotLoggedIn();
            }
       });
    }
    catch (TransactionAbortedException ex)
    {
        resp.SetResponseServerError();
    }
    catch (ApplicationException ex)
    {
        resp.SetResponseServerError();
    }
    return resp;
}

If possible, you can also factor the SetResponse*() methods out into a base class or interface (say IMyResponse), thus making it possible to handle this aspect inside the Execute method as well.

    public static T Execute<T>(Func<T> func, TransactionExecutionOptions options = null) where T : IMyResponse
    {
        options = options ?? TransactionExecutionOptions.Default;

        T res;
        try
        {
            using (var tx = new TransactionScope(options))
            {
                res = func();
                tx.Complete();
            }
        }
        catch (TransactionAbortedException ex)
        {
            res.SetResponseServerError();
        }
        catch (ApplicationException ex)
        {
            res.SetResponseServerError();
        }
        return res;
    }


答:
Your HTML is invalid. You should use a validator.

From the specification for the a element:

Content model: Transparent, but there must be no interactive content descendant.

Links are interactive content (people are expected to click on them to load a new page).

The browser is attempting to recover from your error.

Title: Chrome malforms li > a > ul > li > a HTML


问:
using jquery.noConflict()
I have two files. HTML and .js files. in code.js, I have written jquery code and in HTML file, I am including code.js as following:

```<code><script src="jquery-1.4.2.js"></script>
<script src="jquery.interval.js"></script>
<script src="code.js">
jQuery.noConflict();
var $jcode = jQuery;
</script>
</code>```

in code.js, I have written following:

```<code>jcode(document).ready(function() {
     jcode.interval(checkForms, 2000);
});
</code>```

When I run it, it gives me error as can not read property of interval undefined.
I think there is something wrong with my usage of noConflict. Can you please help?

Thanks

答:
You are mixing internal and external JavScript, which is a bad practice in the least and may even fail.

Replace the code in code.js with:

```<code>jQuery(document).ready(function() {
     jQuery.interval(checkForms, 2000);
});
</code>```

In your page, write the script part as follows:

```<code><!-- no JavaScript before this line -->
<script src="jquery-1.4.2.js"></script>
<script src="jquery.interval.js"></script>
<script src="code.js"></script>
<script>jQuery.noConflict()</script>
<!-- load or insert other JavaScript here -->
</code>```

This is assuming you actually need noConflict(), since your example shows no other libraries. I'm assuming you left them out of this question.

If you still get errors, this may be due to jquery.interval.js not being coded properly.

ContentLicense: CC BY-SA 2.5

Title: using jquery.noConflict()

Body:
I have two files. HTML and .js files. in code.js, I have written jquery code and in HTML file, I am including code.js as following:

in code.js, I have written following:

jcode(document).ready(function() {
     jcode.interval(checkForms, 2000);
});

When I run it, it gives me error as can not read property of interval undefined.
I think there is something wrong with my usage of noConflict. Can you please help?

Thanks

Body:
You are mixing internal and external JavScript, which is a bad practice in the least and may even fail.

Replace the code in code.js with:

jQuery(document).ready(function() {
     jQuery.interval(checkForms, 2000);
});

In your page, write the script part as follows:

<!-- no JavaScript before this line -->
<script src="jquery-1.4.2.js"></script>
<script src="jquery.interval.js"></script>
<script src="code.js"></script>
<script>jQuery.noConflict()</script>
<!-- load or insert other JavaScript here -->

This is assuming you actually need noConflict(), since your example shows no other libraries. I'm assuming you left them out of this question.

If you still get errors, this may be due to jquery.interval.js not being coded properly.


问:
ChromeDriver has started to create blank screenshots?
I am using ChromeDriver to create automated browser tests. This stopped working today, taking a look at the screenshots that are saved in the database, they are all blank pixels.

Why?

Version

ChromeDriver 2.29.0

Screenshot

Hexdump

Code (c#)

```<code>foreach (var testStep in testSteps.ToList())
{
    var testStepRun = new TestStepRun();
    repo.createTestStepRun(testStepRun);

    /* I omit this function in my posting but will include it if needed */
    RunTestStep(testStep);

    try
    {
        testStepRun.ScreenshotPNG = driver.GetScreenshot().AsByteArray;
    }
    catch(UnhandledAlertException)
    {
    }

    repo.SaveChanges();
}
</code>```

答:
It can be related to current ChromeDriver version and Chrome version we use. I`m facing the same issue. I have tried some variants of ChromeDriver/Chrome version to find working one. You can also have a look at the existing issue:
https://github.com/SeleniumHQ/selenium/issues/3700</p>

Body:
I am using ChromeDriver to create automated browser tests. This stopped working today, taking a look at the screenshots that are saved in the database, they are all blank pixels.

Why?

Version

ChromeDriver 2.29.0

Screenshot

Hexdump

Code (c#)

foreach (var testStep in testSteps.ToList())
{
    var testStepRun = new TestStepRun();
    repo.createTestStepRun(testStepRun);

    /* I omit this function in my posting but will include it if needed */
    RunTestStep(testStep);

    try
    {
        testStepRun.ScreenshotPNG = driver.GetScreenshot().AsByteArray;
    }
    catch(UnhandledAlertException)
    {
    }

    repo.SaveChanges();
}


问:
LocalStorage TextBox's in JSON
Weave: https://codepen.io/anon/pen/BZVdaM?editors=0010

I'm using LocalStorage to remember the states of input[type=text] elements. I was able to push to a JSON fine

```<code>{"website": "value","behance": "value","dribbble": "value"}
</code>```

However, my problem now is I'm having difficulty populating the saved data on back in the inputs for page load.

On first run the string returned shouldn't have the quote outside of it; in addition, I noticed after 2nd run it wouldn't show any of the saved data.

Here's the result from Chrome Dev Tools (this is after the 2nd run adding text to another textbox)

Thus what am I doing wrong?

var arr = localStorage.getItem("socialValues") || {};
if ( localStorage.getItem("socialValues")) {
  var savedArrData = JSON.parse(arr);
  $.each(savedArrData, function(key, value) {
    $("[data-social=links] input#" + key).val(value);
  });
}
$("[data-social=links] input").on("change keyup", function() {
  var id = this.id;
  arr[id] = (this.value ? '"' + this.value + '"' : "");
  localStorage.removeItem("socialValues");
  localStorage.setItem("socialValues", JSON.stringify(arr));
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<ul class="uk-nav uk-nav-default" data-social="links">
  <li>

      <span class="uk-margin-small-right" uk-icon="icon: world"></span>
      <input id="website" class="socialbox" type="text" placeholder="http://yoursite.com/" value="hello world">

  </li>
  <li>

      <span class="uk-margin-small-right" uk-icon="icon: behance"></span>
      <input id="behance" class="socialbox" type="text" placeholder="Your behance page">

  </li>
  <li>

      <span class="uk-margin-small-right" uk-icon="icon: dribbble"></span>
      <input id="dribbble" class="socialbox" type="text" placeholder="Your dribbble page">

  </li>
</ul></code>```

答:
You just need to change the arr[id] = (this.value ? '"' + this.value + '"' : ""); to arr[id] = (this.value ? this.value   : "");.

```<code>$("[data-social=links] input").on("change keyup", function() {
  var id = this.id;
  arr[id] = (this.value ? this.value   : "");
  localStorage.removeItem("socialValues");
  localStorage.setItem("socialValues", JSON.stringify(arr));
});
</code>```

Since, you are converting your stored object to string localStorage.setItem("socialValues", JSON.stringify(savedArrData));, you don't need to convert while inserting into local storage.

Title: LocalStorage TextBox's in JSON

Body:
Weave: https://codepen.io/anon/pen/BZVdaM?editors=0010

I'm using LocalStorage to remember the states of input[type=text] elements. I was able to push to a JSON fine

{"website": "value","behance": "value","dribbble": "value"}

However, my problem now is I'm having difficulty populating the saved data on back in the inputs for page load.

On first run the string returned shouldn't have the quote outside of it; in addition, I noticed after 2nd run it wouldn't show any of the saved data.

Here's the result from Chrome Dev Tools (this is after the 2nd run adding text to another textbox)

Thus what am I doing wrong?

var arr = localStorage.getItem("socialValues") || {};
if ( localStorage.getItem("socialValues")) {
  var savedArrData = JSON.parse(arr);
  $.each(savedArrData, function(key, value) {
    $("[data-social=links] input#" + key).val(value);
  });
}
$("[data-social=links] input").on("change keyup", function() {
  var id = this.id;
  arr[id] = (this.value ? '"' + this.value + '"' : "");
  localStorage.removeItem("socialValues");
  localStorage.setItem("socialValues", JSON.stringify(arr));
});

      <input id="website" class="socialbox" type="text" placeholder="http://yoursite.com/" value="hello world">

      <input id="behance" class="socialbox" type="text" placeholder="Your behance page">

      <input id="dribbble" class="socialbox" type="text" placeholder="Your dribbble page">

Body:
You just need to change the arr[id] = (this.value ? '"' + this.value + '"' : ""); to arr[id] = (this.value ? this.value   : "");.

$("[data-social=links] input").on("change keyup", function() {
  var id = this.id;
  arr[id] = (this.value ? this.value   : "");
  localStorage.removeItem("socialValues");
  localStorage.setItem("socialValues", JSON.stringify(arr));
});

Since, you are converting your stored object to string localStorage.setItem("socialValues", JSON.stringify(savedArrData));, you don't need to convert while inserting into local storage.


问:
Are functions faster than commands in Neovim?
dein uses functions instead of commands even for functionality that's exposed to the user, which adds a little bit of extra typing when you work on your init.vim. Is there a reason for that? Are functions faster than commands?

答:
As most custom commands invoke one (or more) user-defined functions, there is a tiny performance benefit to functions, but that doesn't matter at all.

Commands more than make up for this by being quicker to type, allowing (custom) completion, being more discoverable, etc. All caveats about premature optimization (don't do it) apply here.

You refer to the dein package manager. I would guess that interaction with it is only (mostly) needed during startup, by invoking it in your ~/.vimrc. By using (autoload) functions, you don't need to :runtime plugin/dein.vim to define the custom commands; just having dein in the 'runtimepath' is enough to invoke its functions.

Also, this avoids polluting the commands namespace with commands that are not / rarely used interactively. Some plugin authors also just have their own, idiosyncratic style. For a definite answer, you'd have to ask the author :-)


问:
How to hide overlay on mouse hover
Here is my code, what i want is to hide overlay after mouse hover, and what is happening is its staying active until i remove mouse hover on the image. is there any one can solve this problem

.upper {position: absolute; top: 50%; bottom: 0; left: 50%; transform: translate(-50%, -50%); width: 0; height: 0; overflow: hidden; background: #ddd; opacity: 0.5; transition: .2s ease; border-radius: 100%;}
.maine:hover .upper {width: 150%; height: 150%;}
.maine {position: relative; overflow: hidden;}
.upper:after {width 0; height: 0;}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="col-md-2">
  <div class="maine">
    <img src="https://www.w3schools.com/howto/img_avatar.png" alt="Avatar" class="img-responsive">
    <div class="upper"> heading </div>
</div>
</div></code>```

答:
Either use keyframe or this solution:</p>

```<code>.maine:hover .upper:active,
.maine:hover .upper:focus,
.maine:hover .upper:hover {
  opacity: 0;
}
</code>```

Title: How to hide overlay on mouse hover

Body:
Here is my code, what i want is to hide overlay after mouse hover, and what is happening is its staying active until i remove mouse hover on the image. is there any one can solve this problem

.upper {position: absolute; top: 50%; bottom: 0; left: 50%; transform: translate(-50%, -50%); width: 0; height: 0; overflow: hidden; background: #ddd; opacity: 0.5; transition: .2s ease; border-radius: 100%;}
.maine:hover .upper {width: 150%; height: 150%;}
.maine {position: relative; overflow: hidden;}
.upper:after {width 0; height: 0;}

 heading

Body:
Either use keyframe or this solution:

.maine:hover .upper:active,
.maine:hover .upper:focus,
.maine:hover .upper:hover {
  opacity: 0;
}


问:
After upgrading application from MVC3 to MVC4, telerik extension grid throwing null reference error
I have upgraded MVC3 application to MVC4 application and changed target framework to 4.0. no build errors. But at run time System couldn't load a page where telerik extension grid was present.

I do get below error

Index Out Of Range Exception in GridBuilder

So, I have changed telerik extension grid to kendo grid but do get below error.

at
  System.ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument
  argument, ExceptionResource resource)    at
  System.Collections.ObjectModel.Collection1.set_Item(Int32 index, T
  value)    at System.Web.Mvc.ControllerContext.get_RequestContext()

  at Kendo.Mvc.UI.NavigatableExtensions.GenerateUrl(INavigatable
  navigatable, ViewContext viewContext, IUrlGenerator urlGenerator)

  at Kendo.Mvc.UI.Fluent.CrudOperationBuilderBase1.SetUrl()    at
  Kendo.Mvc.UI.Fluent.CrudOperationBuilderBase1.Action(String
  actionName, String controllerName, Object routeValues)    at
  Kendo.Mvc.UI.Fluent.CrudOperationBuilderBase1.Action(String
  actionName, String controllerName)

答:
Telerik extensions for ASP.Net MVC is supported MVC versions 1,2 and 3 only.

[http://docs.telerik.com/help/aspnet-mvc/getting-started-installation-instructions.html#Installing][1]

When you upgrade legacy application from MVC3 to MVC4, need to tell compiler to compile third party DLL like telerik extension using version 3 by modifying root web.config file.

```<code><dependentAssembly>
    <assemblyIdentity name="System.Web.Mvc"
         publicKeyToken="31bf3856ad364e35" />
    <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="4.0.0.0"/>
  </dependentAssembly>
</code>```

Body:
Telerik extensions for ASP.Net MVC is supported MVC versions 1,2 and 3 only.

[http://docs.telerik.com/help/aspnet-mvc/getting-started-installation-instructions.html#Installing][1]

When you upgrade legacy application from MVC3 to MVC4, need to tell compiler to compile third party DLL like telerik extension using version 3 by modifying root web.config file.

<dependentAssembly>
    <assemblyIdentity name="System.Web.Mvc"
         publicKeyToken="31bf3856ad364e35" />
    <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="4.0.0.0"/>
  </dependentAssembly>


问:
Pandas: How to find a particular pattern in a dataframe column?
I'd like to find a particular pattern in a pandas dataframe column, and return the corresponding index values in order to subset the dataframe.

Here's a sample dataframe with a possible pattern:

Snippet to produce dataframe:

```<code>import pandas as pd
import numpy as np

Observations = 10
Columns = 2
np.random.seed(123)
df = pd.DataFrame(np.random.randint(90,110,size=(Observations, Columns)),
                  columns = ['ColA','ColB'])
datelist = pd.date_range(pd.datetime(2017, 7, 7).strftime('%Y-%m-%d'),
                         periods=Observations).tolist()
df['Dates'] = datelist
df = df.set_index(['Dates'])

pattern = [100,90,105]
print(df)
</code>```

Dataframe:

```<code>            ColA  ColB
Dates
2017-07-07   103    92
2017-07-08    92    96
2017-07-09   107   109
2017-07-10   100    91
2017-07-11    90   107
2017-07-12   105    99
2017-07-13    90   104
2017-07-14    90   105
2017-07-15   109   104
2017-07-16    94    90
</code>```

Here, the pattern of interest occurs in Column A on the dates 2017-07-10 to 2017-07-12, and that's what I'd like to end up with:

Desired output:

```<code>2017-07-10   100    91
2017-07-11    90   107
2017-07-12   105    99
</code>```

If the same pattern occurs several times, I would like to subset the dataframe the same way, and also count how many times the pattern occurs, but I hope that's more straight forward as long as I get the first step sorted out.

Thank you for any suggestions!

答:
Here is a solution:

Check if the pattern was found in any of the columns using rolling.
This will give you the last index of the group matching the pattern

```<code>matched = df.rolling(len(pattern)).apply(lambda x: all(np.equal(x, pattern)))
matched = matched.sum(axis = 1).astype(bool)   #Sum to perform boolean OR

matched
Out[129]:
Dates
2017-07-07    False
2017-07-08    False
2017-07-09    False
2017-07-10    False
2017-07-11    False
2017-07-12     True
2017-07-13    False
2017-07-14    False
2017-07-15    False
2017-07-16    False
dtype: bool
</code>```

For each match, add the indexes of the complete pattern:

```<code>idx_matched = np.where(matched)[0]
subset = [range(match-len(pattern)+1, match+1) for match in idx_matched]
</code>```

Get all the patterns:

```<code>result = pd.concat([df.iloc[subs,:] for subs in subset], axis = 0)

result
Out[128]:
            ColA  ColB
Dates
2017-07-10   100    91
2017-07-11    90   107
2017-07-12   105    99
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'd like to find a particular pattern in a pandas dataframe column, and return the corresponding index values in order to subset the dataframe.

Here's a sample dataframe with a possible pattern:

Snippet to produce dataframe:

import pandas as pd
import numpy as np

Observations = 10
Columns = 2
np.random.seed(123)
df = pd.DataFrame(np.random.randint(90,110,size=(Observations, Columns)),
                  columns = ['ColA','ColB'])
datelist = pd.date_range(pd.datetime(2017, 7, 7).strftime('%Y-%m-%d'),
                         periods=Observations).tolist()
df['Dates'] = datelist
df = df.set_index(['Dates'])

pattern = [100,90,105]
print(df)

Dataframe:

            ColA  ColB
Dates
2017-07-07   103    92
2017-07-08    92    96
2017-07-09   107   109
2017-07-10   100    91
2017-07-11    90   107
2017-07-12   105    99
2017-07-13    90   104
2017-07-14    90   105
2017-07-15   109   104
2017-07-16    94    90

Here, the pattern of interest occurs in Column A on the dates 2017-07-10 to 2017-07-12, and that's what I'd like to end up with:

Desired output:

2017-07-10   100    91
2017-07-11    90   107
2017-07-12   105    99

If the same pattern occurs several times, I would like to subset the dataframe the same way, and also count how many times the pattern occurs, but I hope that's more straight forward as long as I get the first step sorted out.

Thank you for any suggestions!

Body:
Here is a solution:

Check if the pattern was found in any of the columns using rolling.
This will give you the last index of the group matching the pattern

matched = df.rolling(len(pattern)).apply(lambda x: all(np.equal(x, pattern)))
matched = matched.sum(axis = 1).astype(bool)   #Sum to perform boolean OR

matched
Out[129]:
Dates
2017-07-07    False
2017-07-08    False
2017-07-09    False
2017-07-10    False
2017-07-11    False
2017-07-12     True
2017-07-13    False
2017-07-14    False
2017-07-15    False
2017-07-16    False
dtype: bool

For each match, add the indexes of the complete pattern:

idx_matched = np.where(matched)[0]
subset = [range(match-len(pattern)+1, match+1) for match in idx_matched]

Get all the patterns:

result = pd.concat([df.iloc[subs,:] for subs in subset], axis = 0)

result
Out[128]:
            ColA  ColB
Dates
2017-07-10   100    91
2017-07-11    90   107
2017-07-12   105    99


问:
Move up cache bar from down to header
I'm trying to move up the cache bar at the webpage: http://www.skandicinkasso.de/ -  cant move the element because it is at the bottom of the "DOM"

I have been trying remove that positioning, and put the element inline where i wanted it, but i cant do that way.

i want to move the bar to here: http://prntscr.com/fsqb5d

答:
In the CSS : From .ginger_container.bottom remove position:fixed; and all other position attributes(left,right,bottom).

In the HTML : Move the entire
 and its contents into the header and palce it just above the closing header tag .

Output: Its fixed and stays close below the navigation bar.

Title: Move up cache bar from down to header

Body:
In the CSS : From .ginger_container.bottom remove position:fixed; and all other position attributes(left,right,bottom).

In the HTML : Move the entire <div class="ginger_banner-wrapper"> and its contents into the header and palce it just above the closing header tag </header>.

Output: Its fixed and stays close below the navigation bar.


问:
How to select rows from db where the given date range falls?
The table structure:

```<code>ID   VersionID   ShiftType   Duration(Hr)   FromDate       ToDate
**********************************************************************
1    1           WORKING     12             20150702        20170528
2    1           WORKING     12             20150702        20170528
3    2           NOTWORKING  06             20170529        20170531
4    2           WORKING     06             20170529        20170531
5    2           NOTWORKING  06             20170529        20170531
6    2           WORKING     06             20170529        20170531
7    3           WORKING     08             20170601        0
8    3           NOTWORKING  08             20170601        0
9    3           WORKING     08             20170601        0
</code>```

Here you can see I have 3 version's(1,2,3) of shift(like day-shifts for 10 days and night-shifts for next 20 days etc).

The present followed shift will not have the end time(Row 7,8 and 9).

For example from 20150702 to 20170528 I followed version 1 which is of total 24 hours(1 day) working with two shifts and from 20170529 to 20170531 followed version 2 with four shifts two working and two nonworking of total 24 hours(1 day).

Now if user provides date range I should get the shift followed on that date range.

Provided date range: From 20170528 To 20170614.

Expected result: All Rows.

Working with below query:

```<code>SELECT * FROM SHIFTS
WHERE (FFROMDATE >= 20170528 AND FFROMDATE <= 20170614) OR (FTODATE >= 20170528 AND FTODATE <= 20170614)
</code>```

But doesn't work for: From 20170502 To 20170514.

Expected result: Rows 1,2(But none selected).

But doesn't work for: From 20170604 To 20170714.

Expected result: Rows 7,8,9(But none selected).

Thank you.

答:
We have 3 distinct things we're looking for:

"Find all shifts that are entirely encompassed within my date range":

```<code>(FFROMDATE <= @StartDate AND FTODATE >= @EndDate)
</code>```

Find all shifts that overlap with the start

```<code>(FFROMDATE >= @StartDate AND FFROMDATE <= @EndDate)
</code>```

Find all shifts that overlap with the end

```<code>(FTODATE >= @StartDate AND FTODATE <= @EndDate)
</code>```

Then combine them all together into one query.

```<code>SELECT * FROM SHIFTS
WHERE
(FFROMDATE < @StartDate AND FTODATE > @EndDate) OR
(FFROMDATE >= @StartDate AND FFROMDATE <= @EndDate) OR
(FTODATE >= @StartDate AND FTODATE <= @EndDate)
</code>```

Make sure you test this with boundary values and remove = to suit your exact requirements.

Body:
The table structure:

ID   VersionID   ShiftType   Duration(Hr)   FromDate       ToDate
**********************************************************************
1    1           WORKING     12             20150702        20170528
2    1           WORKING     12             20150702        20170528
3    2           NOTWORKING  06             20170529        20170531
4    2           WORKING     06             20170529        20170531
5    2           NOTWORKING  06             20170529        20170531
6    2           WORKING     06             20170529        20170531
7    3           WORKING     08             20170601        0
8    3           NOTWORKING  08             20170601        0
9    3           WORKING     08             20170601        0

Here you can see I have 3 version's(1,2,3) of shift(like day-shifts for 10 days and night-shifts for next 20 days etc).

The present followed shift will not have the end time(Row 7,8 and 9).

For example from 20150702 to 20170528 I followed version 1 which is of total 24 hours(1 day) working with two shifts and from 20170529 to 20170531 followed version 2 with four shifts two working and two nonworking of total 24 hours(1 day).

Now if user provides date range I should get the shift followed on that date range.

Provided date range: From 20170528 To 20170614.

Expected result: All Rows.

Working with below query:

SELECT * FROM SHIFTS
WHERE (FFROMDATE >= 20170528 AND FFROMDATE <= 20170614) OR (FTODATE >= 20170528 AND FTODATE <= 20170614)

But doesn't work for: From 20170502 To 20170514.

Expected result: Rows 1,2(But none selected).

But doesn't work for: From 20170604 To 20170714.

Expected result: Rows 7,8,9(But none selected).

Thank you.

Body:
We have 3 distinct things we're looking for:

"Find all shifts that are entirely encompassed within my date range":

(FFROMDATE <= @StartDate AND FTODATE >= @EndDate)

Find all shifts that overlap with the start

(FFROMDATE >= @StartDate AND FFROMDATE <= @EndDate)

Find all shifts that overlap with the end

(FTODATE >= @StartDate AND FTODATE <= @EndDate)

Then combine them all together into one query.

SELECT * FROM SHIFTS
WHERE
(FFROMDATE < @StartDate AND FTODATE > @EndDate) OR
(FFROMDATE >= @StartDate AND FFROMDATE <= @EndDate) OR
(FTODATE >= @StartDate AND FTODATE <= @EndDate)

Make sure you test this with boundary values and remove = to suit your exact requirements.


问:
Styling input buttons for iPad and iPhone
I'm using CSS to style the input buttons on my website, but on IOS devices the styling is replaced by Mac's default buttons. Is there a way to style buttons for iOS, or a way to maybe make a hyperlink that behaves like a submit button?</p>

答:
-webkit-appearance: none;

Note : use bootstrap to style a button.Its common for responsive.


问:
How to insert spaces in front of selected lines?
Is there any way to add space or tab(4 spaces) in front of several selected lines?
Because now if change the code I hava to press command + click select each line.

Thanks.

答:
First set your TAB(4 spaces) width by selecting

```<code>View > Indentation > Tab Width: 4
</code>```

then select the number of lines(text blocks) that you wanna shift towards RIGHT.

Finally Hit(On MAC)

```<code>Command + Tab    OR
Command + [
</code>```

and Hit (On Windows)

```<code>Ctrl + Tab       OR
Ctrl + [
</code>```

Body:
First set your TAB(4 spaces) width by selecting

View > Indentation > Tab Width: 4

then select the number of lines(text blocks) that you wanna shift towards RIGHT.

Finally Hit(On MAC)

Command + Tab    OR
Command + [

and Hit (On Windows)

Ctrl + Tab       OR
Ctrl + [


问:
Palindrom check of linkedlist
Here is the code i wrote to check if a singly linked list of integers is a palindrome or not.

```<code>#include<stdio.h>
#include<stdlib.h>
struct list
{
int data;
struct list *next;
};
struct list *insert(int data,struct list *node)
{
 if(node==NULL)
 {
    node=(struct list *)malloc(sizeof(struct list));
    node->data=data;
    node->next=NULL;
}
else
{
    struct list *newnode=(struct list *)malloc(sizeof(struct list));
    newnode->data=data;
    newnode->next=node;
    node=newnode;
}
return node;
 }

int palindrome(struct list *node,int n)
{
int i=0;int j=0;
   int arr1[n],arr2[n];
   struct list *current;
   current=node;
 while(current!=NULL)
 {
    arr1[i]=current->data;
    i++;
    current=current->next;
}
i=0;j=0;
  for(i=n-1;i>=0;i--)
  {
    arr2[j]=arr1[i];
    j++;
}
for(i=0;i<n;i++)
{
    if(arr1[i]!=arr2[i])
    {
        return 0;
    }
}
return 1;
}
 void main()
{
 int n;
 scanf("%d",&n);
 struct list *node=NULL;
 int i=1;int value;
 for(i=1;i<=n;i++)
 {
    scanf("%d",&value);
     insert(value,node);
 }
 int status=palindrome(node,n);
 printf("%d",status);
 }
</code>```

But the code returns 0 even in case of valid palindrome inputs like "121" and also in non - palindrome inputs like "154". Please help. Thanks

答:
You need to write

```<code>node = insert(value,node);
</code>```

in main. Otherwise the head node is not changed because the function insert deals with a copy of the node.

Title: Palindrom check of linkedlist

Body:
Here is the code i wrote to check if a singly linked list of integers is a palindrome or not.

#include<stdio.h>
#include<stdlib.h>
struct list
{
int data;
struct list *next;
};
struct list *insert(int data,struct list *node)
{
 if(node==NULL)
 {
    node=(struct list *)malloc(sizeof(struct list));
    node->data=data;
    node->next=NULL;
}
else
{
    struct list *newnode=(struct list *)malloc(sizeof(struct list));
    newnode->data=data;
    newnode->next=node;
    node=newnode;
}
return node;
 }

int palindrome(struct list *node,int n)
{
int i=0;int j=0;
   int arr1[n],arr2[n];
   struct list *current;
   current=node;
 while(current!=NULL)
 {
    arr1[i]=current->data;
    i++;
    current=current->next;
}
i=0;j=0;
  for(i=n-1;i>=0;i--)
  {
    arr2[j]=arr1[i];
    j++;
}
for(i=0;i<n;i++)
{
    if(arr1[i]!=arr2[i])
    {
        return 0;
    }
}
return 1;
}
 void main()
{
 int n;
 scanf("%d",&n);
 struct list *node=NULL;
 int i=1;int value;
 for(i=1;i<=n;i++)
 {
    scanf("%d",&value);
     insert(value,node);
 }
 int status=palindrome(node,n);
 printf("%d",status);
 }

But the code returns 0 even in case of valid palindrome inputs like "121" and also in non - palindrome inputs like "154". Please help. Thanks

Body:
You need to write

node = insert(value,node);

in main. Otherwise the head node is not changed because the function insert deals with a copy of the node.


问:
How can I denote decimal floating point in swagger specs?
I would like to denote decimal with 2 places and decimal with 1 place in my api documentation. I'm using swagger 2.0, Is there inbuilt defined type or any other 'round' parameter in the specs, or my only option is to use 'x-' extension? </p>

答:
OpenAPI (fka Swagger) Specification uses a subset of JSON Schema to describe the data types.

If the parameter is passed as a number, you can try using multipleOf as suggested in this Q&A:

type: number
multipleOf: 0.1     # up to 1 decimal place,  e.g. 4.2
# multipleOf: 0.01  # up to 2 decimal places, e.g. 4.25
```

<p>Hovewer, <code>multipleOf</code> validation against floating-point numbers can be unreliable due to floating-point math specifics.</p>

<p><br/>
If your number if passed as a string, you can specify a regex <code>pattern</code> for the desired number format:</p>

<pre class="lang-yaml prettyprint-override"><code>type: string
pattern: your_regex
</code>```

In any case, you can also document any restrictions verbally in the description.

Body:
OpenAPI (fka Swagger) Specification uses a subset of JSON Schema to describe the data types.

If the parameter is passed as a number, you can try using multipleOf as suggested in this Q&A:

type: number
multipleOf: 0.1     # up to 1 decimal place,  e.g. 4.2
# multipleOf: 0.01  # up to 2 decimal places, e.g. 4.25

Hovewer, multipleOf validation against floating-point numbers can be unreliable due to floating-point math specifics.

If your number if passed as a string, you can specify a regex pattern for the desired number format:

type: string
pattern: your_regex

In any case, you can also document any restrictions verbally in the description.


问:
Hiding Empty Cells
I'm currently working on a code that hides empty cells ,but the problem is i want it to start hiding at a certain range ("A9:A12") not at the beginning of the sheet.
here is my program :

```<code>Sub EmptyRow()
'Dim s As String
po = Range("A9:A12").Count
Range("A8").Activate

For i = 1 To po
 s = i & ":" & i
 If IsEmpty(Cells(i, 1).Value) Then
     Rows(s).Select
     Selection.EntireRow.Hidden = True
End If
Next

End Sub
</code>```

The program keeps on hiding cells from the beginning, how do I set it up so it deletes from the range i want it to. Please help.

答:
You can get rid of bits like select

```<code>Sub EmptyRow()
    For i = 9 To 12
        If IsEmpty(Cells(i, 1).Value) Then
            Cells(i, 1).EntireRow.Hidden = True
        End If
    Next i
End Sub
</code>```

Title: Hiding Empty Cells

Body:
I'm currently working on a code that hides empty cells ,but the problem is i want it to start hiding at a certain range ("A9:A12") not at the beginning of the sheet.
here is my program :

Sub EmptyRow()
'Dim s As String
po = Range("A9:A12").Count
Range("A8").Activate

For i = 1 To po
 s = i & ":" & i
 If IsEmpty(Cells(i, 1).Value) Then
     Rows(s).Select
     Selection.EntireRow.Hidden = True
End If
Next

End Sub

The program keeps on hiding cells from the beginning, how do I set it up so it deletes from the range i want it to. Please help.

Body:
You can get rid of bits like select

Sub EmptyRow()
    For i = 9 To 12
        If IsEmpty(Cells(i, 1).Value) Then
            Cells(i, 1).EntireRow.Hidden = True
        End If
    Next i
End Sub


问:
Android eclipse ERROR: Unknown option '--auto-add-overlay'
I had an abnormal shutdown of my mac and when it came back up, Eclipse would no longer compile my project correctly.</p>

答: Gone through this link1 and link2</p>

Body: Gone through this link1 and link2


答:
The shortest way is finding the index at which the pattern starts. Then you just need to select the three following rows.

In order to find these indexes, a one-liner is enough:

```<code>indexes=df[(df.ColA==pattern[0])&(df["ColA"].shift(-1)==pattern[1])&(df["ColA"].shift(-2)==pattern[2])].index
</code>```

Then do as the other answer says to get the subsets that you want.

Title: Pandas: How to find a particular pattern in a dataframe column?

Body:
The shortest way is finding the index at which the pattern starts. Then you just need to select the three following rows.

In order to find these indexes, a one-liner is enough:

indexes=df[(df.ColA==pattern[0])&(df["ColA"].shift(-1)==pattern[1])&(df["ColA"].shift(-2)==pattern[2])].index

Then do as the other answer says to get the subsets that you want.


问:
R Shiny DataTable selected row color
I am trying to set the highlight color for a selected row in a DataTable in my shiny app. Basically I want the color of selected rows to be say red rather than blue. However, I am not at all familiar with JavaScript so I am struggling to write the appropriate callback (at least I think that is the problem). Here is what I've tried so far:

```<code># ui.R
library(shiny)

fluidPage(
  title = 'DataTables Test',
  DT::dataTableOutput('table')
)

# server.R
library(shiny)
library(DT)

# render the table
output$table = renderDataTable(datatable(head(iris, 20),
options = list(
    initComplete = JS(
      "function(settings, json) {",
      "var rows = $(this.api().table().rows());",
      "for (var i = 0; i < rows.length; i++){ ",
      "var row = rows[i];",
      "row.css({'background-color': '#000', 'color': '#f00'})",
      "}",
      "}")
  )))

})
</code>```

As you can see, so far I am just trying to figure out how to change the row colors. Once I had figured this out I was going to try and change the css to something like:

```<code>"tr.selected td, table.dataTable td.selected { background-color: #f00}"
</code>```

But I haven't gotten there yet - unfortunately the code above doesn't do anything to the background color. If anyone could help me with the whole solution that would be great.

答:
This should do the job:

```<code>#rm(list = ls())
library(shiny)
library(DT)

ui <- basicPage(
  tags$style(HTML('table.dataTable tr.selected td, table.dataTable td.selected {background-color: pink !important;}')),
  mainPanel(DT::dataTableOutput('mytable'))
)

server <- function(input, output,session) {

  output$mytable = DT::renderDataTable(
    datatable(mtcars)
  )
}
runApp(list(ui = ui, server = server))
</code>```

Title: R Shiny DataTable selected row color

Body:
I am trying to set the highlight color for a selected row in a DataTable in my shiny app. Basically I want the color of selected rows to be say red rather than blue. However, I am not at all familiar with JavaScript so I am struggling to write the appropriate callback (at least I think that is the problem). Here is what I've tried so far:

# ui.R
library(shiny)

fluidPage(
  title = 'DataTables Test',
  DT::dataTableOutput('table')
)

# server.R
library(shiny)
library(DT)

# render the table
output$table = renderDataTable(datatable(head(iris, 20),
options = list(
    initComplete = JS(
      "function(settings, json) {",
      "var rows = $(this.api().table().rows());",
      "for (var i = 0; i < rows.length; i++){ ",
      "var row = rows[i];",
      "row.css({'background-color': '#000', 'color': '#f00'})",
      "}",
      "}")
  )))

})

As you can see, so far I am just trying to figure out how to change the row colors. Once I had figured this out I was going to try and change the css to something like:

"tr.selected td, table.dataTable td.selected { background-color: #f00}"

But I haven't gotten there yet - unfortunately the code above doesn't do anything to the background color. If anyone could help me with the whole solution that would be great.

Body:
This should do the job:

#rm(list = ls())
library(shiny)
library(DT)

ui <- basicPage(
  tags$style(HTML('table.dataTable tr.selected td, table.dataTable td.selected {background-color: pink !important;}')),
  mainPanel(DT::dataTableOutput('mytable'))
)

server <- function(input, output,session) {

  output$mytable = DT::renderDataTable(
    datatable(mtcars)
  )
}
runApp(list(ui = ui, server = server))


问:
MS SQL Split a column value using delimiters and update in other field
Ex,  I have a table like this,

```<code>ID Name
1  Apple,banana
2  Grape,Orange
3  Papaya,Jackfruit
</code>```

I need to split (,) and save like this in SQL

```<code>ID Name    Name2
1  Apple   banana
2  Grape   Orange
3  Papaya  Jackfruit
</code>```

答:
We get the Result by using Lead and Lag Function along with Split String And insert the Result set in to your table as You Required

```<code>IF OBJECT_ID('tempdb..#InsertTable') IS NOT NULL
DROP TABLE #InsertTable
DECLARE @table TABLE (ID INT, Name VARCHAR(50))

CREATE TABLE #InsertTable (ID INT,Name1 VARCHAR(100),Name2 VARCHAR(100))

INSERT INTO @table
SELECT 1,'Apple,Banana'  UNION ALL
SELECT 2,'Grape,Orange'  UNION ALL
SELECT 3,'Papaya,Jackfruit'

INSERT INTO #InsertTable(ID,Name1,Name2)
SELECT  DISTINCT ID,
        ISNULL(Name1,LagName1) AS Name1 ,
        ISNULL(Name2,LeadName2) AS Name2

FROM
(
SELECT ID,
Name1,
LAG(NAme1,1)OVER(ORDER BY ID) LagName1,
Name2,
LEAD(Name2,1)OVER(ORDER BY ID)LeadName2
FROM
(
SELECT ID,   CASE WHEN Seq%2=1 THEN Name END AS Name1,
             CASE WHEN Seq%2=0 THEN Name END AS Name2
 FROM
(
SELECT Row_NUmber ()OVER(ORDER BY ID )AS Seq,ID, Split.a.value('.', 'VARCHAR(1000)') AS Name
            FROM  (
                SELECT ID,  CAST('<S>' + REPLACE(Name, ',', '</S><S>') + '</S>' AS XML) AS Name
                FROM @table
                ) AS A
            CROSS APPLY Name.nodes('/S') AS Split(a)

)Dt
)DT2
)Final

SELECT * FROM #InsertTable
</code>```

Result

```<code>ID  Name1   Name2
----------------------
1   Apple   Banana
2   Grape   Orange
3   Papaya  Jackfruit
</code>```

Body:
Ex,  I have a table like this,

ID Name
1  Apple,banana
2  Grape,Orange
3  Papaya,Jackfruit

I need to split (,) and save like this in SQL

ID Name    Name2
1  Apple   banana
2  Grape   Orange
3  Papaya  Jackfruit

Body:
We get the Result by using Lead and Lag Function along with Split String And insert the Result set in to your table as You Required

IF OBJECT_ID('tempdb..#InsertTable') IS NOT NULL
DROP TABLE #InsertTable
DECLARE @table TABLE (ID INT, Name VARCHAR(50))

CREATE TABLE #InsertTable (ID INT,Name1 VARCHAR(100),Name2 VARCHAR(100))

INSERT INTO @table
SELECT 1,'Apple,Banana'  UNION ALL
SELECT 2,'Grape,Orange'  UNION ALL
SELECT 3,'Papaya,Jackfruit'

INSERT INTO #InsertTable(ID,Name1,Name2)
SELECT  DISTINCT ID,
        ISNULL(Name1,LagName1) AS Name1 ,
        ISNULL(Name2,LeadName2) AS Name2

FROM
(
SELECT ID,
Name1,
LAG(NAme1,1)OVER(ORDER BY ID) LagName1,
Name2,
LEAD(Name2,1)OVER(ORDER BY ID)LeadName2
FROM
(
SELECT ID,   CASE WHEN Seq%2=1 THEN Name END AS Name1,
             CASE WHEN Seq%2=0 THEN Name END AS Name2
 FROM
(
SELECT Row_NUmber ()OVER(ORDER BY ID )AS Seq,ID, Split.a.value('.', 'VARCHAR(1000)') AS Name
            FROM  (
                SELECT ID,  CAST('<S>' + REPLACE(Name, ',', '</S><S>') + '</S>' AS XML) AS Name
                FROM @table
                ) AS A
            CROSS APPLY Name.nodes('/S') AS Split(a)

)Dt
)DT2
)Final

SELECT * FROM #InsertTable

Result

ID  Name1   Name2
----------------------
1   Apple   Banana
2   Grape   Orange
3   Papaya  Jackfruit


问:
How can I monkey-patch an instance method in Perl?
I'm trying to monkey-patch (duck-punch :-) a LWP::UserAgent instance, like so:

```<code>sub _user_agent_get_basic_credentials_patch {
  return ($username, $password);
}

my $agent = LWP::UserAgent->new();
$agent->get_basic_credentials = _user_agent_get_basic_credentials_patch;
</code>```

This isn't the right syntax -- it yields:

Can't modify non-lvalue subroutine
  call at [module] line [lineno].

As I recall (from Programming Perl), dispatch lookup is performed dynamically based on the blessed package (ref($agent), I believe), so I'm not sure how instance monkey patching would even work without affecting the blessed package.

I know that I can subclass the UserAgent, but I would prefer the more concise monkey-patched approach. Consenting adults and what have you. ;-)

答: Perl thinks you're trying to call the subroutine on the left of the assignment, which is why it's complaining. I think you may be able to whack the Perl symbol table directly (using *LWP::UserAgent::get_basic_credentials or something), but I lack the Perl-fu to correctly make that incantation.

OwnerDisplayName: cdleary

Body:
I'm trying to monkey-patch (duck-punch :-) a LWP::UserAgent instance, like so:

sub _user_agent_get_basic_credentials_patch {
  return ($username, $password);
}

my $agent = LWP::UserAgent->new();
$agent->get_basic_credentials = _user_agent_get_basic_credentials_patch;

This isn't the right syntax -- it yields:

Can't modify non-lvalue subroutine
  call at [module] line [lineno].

As I recall (from Programming Perl), dispatch lookup is performed dynamically based on the blessed package (ref($agent), I believe), so I'm not sure how instance monkey patching would even work without affecting the blessed package.

I know that I can subclass the UserAgent, but I would prefer the more concise monkey-patched approach. Consenting adults and what have you. ;-)

LastEditorDisplayName: cdleary

OwnerDisplayName: Greg Hewgill


答:
```<code>select * from log_customer
left join
(select max(log_id) as max_id from log_customer where customer_id=2)
  as log_customer2
on log_customer.log_id=log_customer2.max_id
where log_customer.customer_id=2;
</code>```

oh damn...

```<code>select * from log_customer where customer_id=2 order by log_id desc limit 1;
</code>```

Title: what will be the simple mysql query for this

Body:
I want to get the customer info where customer id should be 2 and the log_id should be maximum value
i tried below query but it is fetching first record found.

What will be the simple query

mysql> select * from log_customer where customer_id =2 group by customer_id having max(log_id);
+--------+------------+-------------+---------------------+-----------+----------+
| log_id | visitor_id | customer_id | login_at            | logout_at | store_id |
+--------+------------+-------------+---------------------+-----------+----------+
|      2 |         56 |           2 | 2010-02-19 19:34:45 | NULL      |        1 |
+--------+------------+-------------+---------------------+-----------+----------+
1 row in set (0.00 sec)

mysql> select * from log_customer where customer_id =2 limit 5;
+--------+------------+-------------+---------------------+---------------------+----------+
| log_id | visitor_id | customer_id | login_at            | logout_at           | store_id |
+--------+------------+-------------+---------------------+---------------------+----------+
|      2 |         56 |           2 | 2010-02-19 19:34:45 | NULL                |        1 |
|      3 |        114 |           2 | 2010-02-23 17:31:55 | NULL                |        1 |
|     31 |       1854 |           2 | 2010-03-08 18:31:28 | 2010-03-08 18:56:49 |        1 |
|     32 |       1992 |           2 | 2010-03-09 01:12:43 | NULL                |        1 |
|     33 |       2304 |           2 | 2010-03-09 14:42:39 | NULL                |        1 |
+--------+------------+-------------+---------------------+---------------------+----------+

Please do not suggest order by log_id desc I don't want to get in this way

Body:
select * from log_customer
left join
(select max(log_id) as max_id from log_customer where customer_id=2)
  as log_customer2
on log_customer.log_id=log_customer2.max_id
where log_customer.customer_id=2;

oh damn...

select * from log_customer where customer_id=2 order by log_id desc limit 1;


问:
Using Page Name or URL Properties for Handlebar If Statements in Big Commerce templates
I'm currently working on a BigCommerce theme using their Stencil framework. It leverages Handlebars.js for some logic already and I'm trying to use it to show specific html on specific pages.

Looking at the documentation I can see there is a "pages" object and that I should be able to name or URL to do what I need to do.

I cannot figure out the syntax to get the page name or url to run the iff against. I can succesfully get it to do what I want by testing if it's a page content type, but not any of the type properties.

```<code>{{#if pages }}
 ... do foo here
{{/if}}
</code>```

What I want to do is something like

```<code>{{#if pages.url '===' 'about' }}
 ... do foo here
{{/if}}

{{#if pages.url '===' 'service' }}
 ... do foo different here
{{/if}}
</code>```

答:
It looks like you are actually using the wrong Object Model for the data that you are trying to pull. The first word of your handlebars object should be "page" and not "pages". This will pull any content or data from the static pages that you build in the back office. (AKA the WYSIWYG)

Here is a link to the docs of the model that you want.  https://stencil.bigcommerce.com/docs/page-content-object

For Example:

```<code>{{{page.title}}}
{{{page.content}}}
</code>```

Note that I am using 3 handlebar on each side to escape the HTML on the WYSIWYG. Let me know if you need any other help.

Body:
I'm currently working on a BigCommerce theme using their Stencil framework. It leverages Handlebars.js for some logic already and I'm trying to use it to show specific html on specific pages.

Looking at the documentation I can see there is a "pages" object and that I should be able to name or URL to do what I need to do.

I cannot figure out the syntax to get the page name or url to run the iff against. I can succesfully get it to do what I want by testing if it's a page content type, but not any of the type properties.

{{#if pages }}
 ... do foo here
{{/if}}

What I want to do is something like

{{#if pages.url '===' 'about' }}
 ... do foo here
{{/if}}

{{#if pages.url '===' 'service' }}
 ... do foo different here
{{/if}}

Body:
It looks like you are actually using the wrong Object Model for the data that you are trying to pull. The first word of your handlebars object should be "page" and not "pages". This will pull any content or data from the static pages that you build in the back office. (AKA the WYSIWYG)

Here is a link to the docs of the model that you want.  https://stencil.bigcommerce.com/docs/page-content-object

For Example:

{{{page.title}}}
{{{page.content}}}

Note that I am using 3 handlebar on each side to escape the HTML on the WYSIWYG. Let me know if you need any other help.


问:
Running script even with no page loaded
Please understand that the following question is more of an academic one as I am trying to understand the logic behind the issue I am going to describe.

Many times I've seen websites (especially about upcoming movie films) that have a countdown timer. This tells the page visitor about the film's date release in theaters.

My question is how do they code this in order to run even when no one has visited the page? For example JavaScript code works only when the page is loaded. This would make a countdown timer to reset every time. I am really confused how people visit these websites and the countdown timer is already working.

I just need the logic and not some specific coding. Thank you all in advance.

答:
JS counter is running only when user is viewing page. What happens here:

PHP (back-end) has event start time. He calculates how much time is left

Outputting this left time to JS like var timeLeft = "<?php echo getTimeLeft($eventId); ?>";

Now JS just decrements this time with setInterval()

So basically yes, JS counter is reset all time you re-enter page. But it's start time is always different.

There is another option, when you need to do periodical actions without human interaction (e.g. send emails at 00:00 every night for subscribers).

Then we use Cron Job (search for crontab linux). You provide path to file that must be executed and server calls that file when time comes.

Title: Running script even with no page loaded


问:
WPF Binding Issue - UI Updates, Object Does Not
I'm having yet another WPF binding issue.  Just when I think I've got this stuff figured out, I run into more problems...  :S

Anyway... I've created a custom user control for selecting files.  It's a simple textbox followed by a button contained within a grid.  The property of the control with which I am working is called FilePath and the TextBox on this control is bound to that property.  When the button is clicked, a SaveFileDialog is opened and the user selects a file.  The UI correctly updates after the user selects the file.

The problem I seem to be having is that when I bind an object to the control (in this instance I have an object with a DocumentFilePath property) the object doesn't update when a new file is selected.

Here's the relevant code within my user control:

```<code>public static readonly DependencyProperty FilePathProperty = DependencyProperty.Register("FilePath", typeof(string), typeof(FileSave), new UIPropertyMetadata(string.Empty, OnFilePathChanged));

public string FilePath
{
    get
    {
        return this.GetValue(FilePathProperty) as string;
    }
    set
    {
        this.SetValue(FilePathProperty, value);
        this.OnPropertyChanged("FilePath");
    }
}

private void OnPropertyChanged(string propName)
{
    if (PropertyChanged != null)
    {
       PropertyChanged(this, new PropertyChangedEventArgs(propName));
    }
}

private static void OnFilePathChanged(object sender, DependencyPropertyChangedEventArgs e)
{
    ((FileSave)sender).OnPropertyChanged("FilePath");
}
</code>```

And the user control is added into my Window programatically by using reflection on my object:

```<code>private void AddFileSave(PropertyInfo pi)
{
     FileSave fs = new FileSave();
     Binding b = new Binding(pi.Name);

     fs.SetBinding(FileSave.FilePathProperty, b);
     this.AddToGrid(fs); //adds the control into my window's grid in the correct row and column; nothing fancy here
}
</code>```

It may be worth noting that if I load the window with an existing object, my user control displays properly but still won't register any changes within the object to which it is bound.

Please let me know if you guys need any more info.

Thanks in advance,

Sonny

EDIT:  I've found a way around the problem, but this probably isn't a good solution.  By watching the debugger carefully I found that when I set the FilePath property within my control, the object was being unbound.  If anyone can shed some light on that, I would be most appreciative.  In the mean time, I've changed the code that opens my SaveFileDialog to look like this:

```<code>private void Button_Click(object sender, RoutedEventArgs e)
{
    Microsoft.Win32.OpenFileDialog ofd = new Microsoft.Win32.OpenFileDialog();

    ofd.Multiselect = false;
    ofd.Title = "Select document to import...";
    ofd.ValidateNames = true;

    ofd.ShowDialog();

    if (this.GetBindingExpression(FilePathProperty) == null)
    {
        this.FilePath = ofd.FileName;
    }
    else //set value on bound object (THIS IS THE NEW PORTION I JUST ADDED)
    {
        BindingExpression be = this.GetBindingExpression(FilePathProperty);
        string propName = be.ParentBinding.Path.Path;
        object entity = be.DataItem;
        System.Reflection.PropertyInfo pi = entity.GetType().GetProperty(propName);

        pi.SetValue(entity, ofd.FileName, null);
    }

    if (!string.IsNullOrWhiteSpace(this.FilePath))
    {
        _fileContents = new MemoryStream();
        using (StreamReader sr = new StreamReader(this.FilePath))
        {
            _fileContents = new MemoryStream(System.Text.ASCIIEncoding.ASCII.GetBytes(sr.ReadToEnd()));
        }
    }
    else
    {
        _fileContents = null;
    }
}
</code>```

答:
You're not specifying anywhere in your code that the FilePath property should be TwoWay so updates of the DP value won't get pushed to the bound source object's property. You can use either:

```<code>Binding b = new Binding(pi.Name){ Mode = BindingMode.TwoWay };
</code>```

or you can set up your Dependency Property to use a default of TwoWay:

```<code>public static readonly DependencyProperty FilePathProperty = DependencyProperty.Register(
"FilePath", typeof(string), typeof(FileSave),
new FrameworkPropertyMetadata(string.Empty, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, OnFilePathChanged));
</code>```

You should also follow Robert's suggestion of removing the manual PropertyChange event, and also don't EVER add any code other than GetValue and SetValue in your DP wrapper property. XAML calls GetValue and SetValue directly so will skip over anything else you add there - which can lead to very nasty bugs.

Body:
I'm having yet another WPF binding issue.  Just when I think I've got this stuff figured out, I run into more problems...  :S

Anyway... I've created a custom user control for selecting files.  It's a simple textbox followed by a button contained within a grid.  The property of the control with which I am working is called FilePath and the TextBox on this control is bound to that property.  When the button is clicked, a SaveFileDialog is opened and the user selects a file.  The UI correctly updates after the user selects the file.

The problem I seem to be having is that when I bind an object to the control (in this instance I have an object with a DocumentFilePath property) the object doesn't update when a new file is selected.

Here's the relevant code within my user control:

public static readonly DependencyProperty FilePathProperty = DependencyProperty.Register("FilePath", typeof(string), typeof(FileSave), new UIPropertyMetadata(string.Empty, OnFilePathChanged));

public string FilePath
{
    get
    {
        return this.GetValue(FilePathProperty) as string;
    }
    set
    {
        this.SetValue(FilePathProperty, value);
        this.OnPropertyChanged("FilePath");
    }
}

private void OnPropertyChanged(string propName)
{
    if (PropertyChanged != null)
    {
       PropertyChanged(this, new PropertyChangedEventArgs(propName));
    }
}

private static void OnFilePathChanged(object sender, DependencyPropertyChangedEventArgs e)
{
    ((FileSave)sender).OnPropertyChanged("FilePath");
}

And the user control is added into my Window programatically by using reflection on my object:

private void AddFileSave(PropertyInfo pi)
{
     FileSave fs = new FileSave();
     Binding b = new Binding(pi.Name);

     fs.SetBinding(FileSave.FilePathProperty, b);
     this.AddToGrid(fs); //adds the control into my window's grid in the correct row and column; nothing fancy here
}

It may be worth noting that if I load the window with an existing object, my user control displays properly but still won't register any changes within the object to which it is bound.

Please let me know if you guys need any more info.

Thanks in advance,

Sonny

EDIT:  I've found a way around the problem, but this probably isn't a good solution.  By watching the debugger carefully I found that when I set the FilePath property within my control, the object was being unbound.  If anyone can shed some light on that, I would be most appreciative.  In the mean time, I've changed the code that opens my SaveFileDialog to look like this:

private void Button_Click(object sender, RoutedEventArgs e)
{
    Microsoft.Win32.OpenFileDialog ofd = new Microsoft.Win32.OpenFileDialog();

    ofd.Multiselect = false;
    ofd.Title = "Select document to import...";
    ofd.ValidateNames = true;

    ofd.ShowDialog();

    if (this.GetBindingExpression(FilePathProperty) == null)
    {
        this.FilePath = ofd.FileName;
    }
    else //set value on bound object (THIS IS THE NEW PORTION I JUST ADDED)
    {
        BindingExpression be = this.GetBindingExpression(FilePathProperty);
        string propName = be.ParentBinding.Path.Path;
        object entity = be.DataItem;
        System.Reflection.PropertyInfo pi = entity.GetType().GetProperty(propName);

        pi.SetValue(entity, ofd.FileName, null);
    }

    if (!string.IsNullOrWhiteSpace(this.FilePath))
    {
        _fileContents = new MemoryStream();
        using (StreamReader sr = new StreamReader(this.FilePath))
        {
            _fileContents = new MemoryStream(System.Text.ASCIIEncoding.ASCII.GetBytes(sr.ReadToEnd()));
        }
    }
    else
    {
        _fileContents = null;
    }
}

Body:
You're not specifying anywhere in your code that the FilePath property should be TwoWay so updates of the DP value won't get pushed to the bound source object's property. You can use either:

Binding b = new Binding(pi.Name){ Mode = BindingMode.TwoWay };

or you can set up your Dependency Property to use a default of TwoWay:

public static readonly DependencyProperty FilePathProperty = DependencyProperty.Register(
"FilePath", typeof(string), typeof(FileSave),
new FrameworkPropertyMetadata(string.Empty, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, OnFilePathChanged));

You should also follow Robert's suggestion of removing the manual PropertyChange event, and also don't EVER add any code other than GetValue and SetValue in your DP wrapper property. XAML calls GetValue and SetValue directly so will skip over anything else you add there - which can lead to very nasty bugs.


问:
SQL Command query
```<code>    System.Data.SqlClient.SqlException occurred
  HResult=0x80131904
  Message=Invalid object name 'Drivers.DriversDetailTable'.
  Source=.Net SqlClient Data Provider
  StackTrace:
<Cannot evaluate the exception stack trace>
</code>```

Keep getting the above error everytime i try and copy stuff from one database table to another, heres my code.

```<code>SqlConnection connect = new SqlConnection($@"Data Source = Computer\SQLEXPRESS;Initial Catalog = Drivers;Trusted_Connection=True;");
            connect.Open();
            SqlCommand cmd = new SqlCommand($@"SELECT * INTO BackUpDatabase.DriversDetailTable FROM Drivers.DriversDetailTable", connect);
            cmd.ExecuteNonQuery();
            connect.Close();
</code>```

答:
Looks like your database name is Drivers not schema name

SELECT *
INTO BackUpDatabase.DriversDetailTable
FROM Drivers.DriversDetailTable --here schema name is missing
```

<p>When you use two part identifer then it will be parsed as</p>

<blockquote>
  <p>schemaname.tablename</p>
</blockquote>

<p>So <code>Drivers</code> and <code>BackUpDatabase</code> is considered as schema names instead of database. </p>

<p>It should be</p>

<pre class="lang-sql prettyprint-override"><code>SELECT *
INTO BackUpDatabase.dbo.DriversDetailTable
FROM Drivers.schemaname.DriversDetailTable --here replace schemaname with dbo or whatever schema name
</code>```

Note : When you use INTO clause it creates a new table. When you run second time you may get a error stating table already exist. Better to create table in prior in backup database use INSERT INTO..select to copy the rows

```<code>Insert into BackUpDatabase.dbo.DriversDetailTable (col1,col2,..)
select col1,col2,..FROM Drivers.schemaname.DriversDetailTable
</code>```

Title: SQL Command query

Body:
    System.Data.SqlClient.SqlException occurred
  HResult=0x80131904
  Message=Invalid object name 'Drivers.DriversDetailTable'.
  Source=.Net SqlClient Data Provider
  StackTrace:
<Cannot evaluate the exception stack trace>

Keep getting the above error everytime i try and copy stuff from one database table to another, heres my code.

SqlConnection connect = new SqlConnection($@"Data Source = Computer\SQLEXPRESS;Initial Catalog = Drivers;Trusted_Connection=True;");
            connect.Open();
            SqlCommand cmd = new SqlCommand($@"SELECT * INTO BackUpDatabase.DriversDetailTable FROM Drivers.DriversDetailTable", connect);
            cmd.ExecuteNonQuery();
            connect.Close();

Body:
Looks like your database name is Drivers not schema name

SELECT *
INTO BackUpDatabase.DriversDetailTable
FROM Drivers.DriversDetailTable --here schema name is missing

When you use two part identifer then it will be parsed as

schemaname.tablename

So Drivers and BackUpDatabase is considered as schema names instead of database.

It should be

SELECT *
INTO BackUpDatabase.dbo.DriversDetailTable
FROM Drivers.schemaname.DriversDetailTable --here replace schemaname with dbo or whatever schema name

Note : When you use INTO clause it creates a new table. When you run second time you may get a error stating table already exist. Better to create table in prior in backup database use INSERT INTO..select to copy the rows

Insert into BackUpDatabase.dbo.DriversDetailTable (col1,col2,..)
select col1,col2,..FROM Drivers.schemaname.DriversDetailTable


问:
How to hide overlay on mouse hover
Here is my code, what i want is to hide overlay after mouse hover, and what is happening is its staying active until i remove mouse hover on the image. is there any one can solve this problem

.upper {position: absolute; top: 50%; bottom: 0; left: 50%; transform: translate(-50%, -50%); width: 0; height: 0; overflow: hidden; background: #ddd; opacity: 0.5; transition: .2s ease; border-radius: 100%;}
.maine:hover .upper {width: 150%; height: 150%;}
.maine {position: relative; overflow: hidden;}
.upper:after {width 0; height: 0;}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="col-md-2">
  <div class="maine">
    <img src="https://www.w3schools.com/howto/img_avatar.png" alt="Avatar" class="img-responsive">
    <div class="upper"> heading </div>
</div>
</div></code>```

答:
I think the easiest solution will be switch to an animation.

.upper {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  overflow: hidden;
}

.upper-background {
  position: absolute;
  width: 0%;
  height: 0%;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  transform-origin: 50% 50%;
  border-radius: 100%;
  background-color: rgba(251, 251, 251, 0.5);
}

.upper-inner {
  position: absolute;
  transform: translate(-50%, -50%);
  top: 50%;
  left: 50%;
  opacity: 0;
}

.maine:hover .upper-background {
  animation: expand 0.6s ease;
  animation-fill-mode: forwards;
  animation-iteration-count: 1;
}

.maine:hover .upper-inner {
  animation: showText 0.3s ease;
  animation-fill-mode: forwards;
  animation-iteration-count: 1;
}

.maine {
  position: relative;
  display: inline-block;
  overflow: hidden;
}

@keyframes showText {
  0% {
    opacity: 0;
  }
  30% {
    opacity: 0;
  }
  100% {
    opacity: 1;
  }
}

@keyframes expand {
  0% {
    width: 0%;
    height: 0%;
  }
  95% {
    width: 150%;
    height: 150%;
  }
  100% {
    width: 150%;
    height: 150%;
    opacity: 0;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="col-md-2">
  <div class="maine">
    <img src="https://www.w3schools.com/howto/img_avatar.png" alt="Avatar" class="img-responsive">
    <div class="upper">
      <div class="upper-background"></div>
      <div class="upper-inner">NAME</div>
    </div>
  </div>
</div></code>```

Title: How to hide overlay on mouse hover

Body:
Here is my code, what i want is to hide overlay after mouse hover, and what is happening is its staying active until i remove mouse hover on the image. is there any one can solve this problem

.upper {position: absolute; top: 50%; bottom: 0; left: 50%; transform: translate(-50%, -50%); width: 0; height: 0; overflow: hidden; background: #ddd; opacity: 0.5; transition: .2s ease; border-radius: 100%;}
.maine:hover .upper {width: 150%; height: 150%;}
.maine {position: relative; overflow: hidden;}
.upper:after {width 0; height: 0;}

 heading

Body:
I think the easiest solution will be switch to an animation.

.upper {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  overflow: hidden;
}

.upper-background {
  position: absolute;
  width: 0%;
  height: 0%;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  transform-origin: 50% 50%;
  border-radius: 100%;
  background-color: rgba(251, 251, 251, 0.5);
}

.upper-inner {
  position: absolute;
  transform: translate(-50%, -50%);
  top: 50%;
  left: 50%;
  opacity: 0;
}

.maine:hover .upper-background {
  animation: expand 0.6s ease;
  animation-fill-mode: forwards;
  animation-iteration-count: 1;
}

.maine:hover .upper-inner {
  animation: showText 0.3s ease;
  animation-fill-mode: forwards;
  animation-iteration-count: 1;
}

.maine {
  position: relative;
  display: inline-block;
  overflow: hidden;
}

@keyframes showText {
  0% {
    opacity: 0;
  }
  30% {
    opacity: 0;
  }
  100% {
    opacity: 1;
  }
}

@keyframes expand {
  0% {
    width: 0%;
    height: 0%;
  }
  95% {
    width: 150%;
    height: 150%;
  }
  100% {
    width: 150%;
    height: 150%;
    opacity: 0;
  }
}

<div class="col-md-2">
  <div class="maine">
    <img src="https://www.w3schools.com/howto/img_avatar.png" alt="Avatar" class="img-responsive">
    <div class="upper">
      <div class="upper-background"></div>
      <div class="upper-inner">NAME</div>
    </div>
  </div>
</div>


问:
How to implement a memory heap
Wasn't exactly sure how to phrase the title, but the question is:

I've heard of programmers allocating a large section of contiguous memory at the start of a program and then dealing it out as necessary. This is, in contrast to simply going to the OS every time memory is needed.
I've heard that this would be faster because it would avoid the cost of asking the OS for contiguous blocks of memory constantly.

I believe the JVM does just this, maintaining its own section of memory and then allocating objects from that.

My question is, how would one actually implement this?

答:
Yes, both stdlib heap and OS heap / virtual memory are pretty troublesome.
OS calls are really slow, and stdlib is faster, but still has some "unnecessary"
locks and checks, and adds a significant overhead to allocated blocks
(ie some memory is used for management, in addition to what you allocate).

In many cases its possible to avoid dynamic allocation completely,
by using static structures instead. For example, sometimes its better (safer etc) to define a 64k
static buffer for unicode filename, than define a pointer/std:string and dynamically
allocate it.

When the program has to allocate a lot of instances of the same structure, its
much faster to allocate large memory blocks and then just store the instances there
(sequentially or using a linked list of free nodes) - C++ has a "placement new" for that.

In many cases, when working with varible-size objects, the set of possible sizes
is actually very limited (eg. something like 4+2*(1..256)), so its possible to use
a few pools like [3] without having to collect garbage, fill the gaps etc.

Its common for a custom allocator for specific task to be much faster than one(s)
from standard library, and even faster than speed-optimized, but too universal implementations.

Modern CPUs/OSes support "large pages", which can significantly improve the memory
access speed when you explicitly work with large blocks - see http://7-max.com/

Title: How to implement a memory heap