问:
PHP: game loop (threads or the sort)
I am writing PHP code to be a game client. It uses socket; socket_create followed by socket_connect and then socket_read. It works fine, but the issue is that the server can send a packet at any time which means socket_read needs to be happening constantly in a "game loop". So something like this:

```<code><?php
$reply = "";
do {
     $recv = "";
     $recv = socket_read($socket, '1400');
     if($recv != "") {
         $reply .= $recv;
     }
} while($recv != "");

echo($reply);
?>
</code>```

Doesn't work because it's stuck in the loop (server doesn't terminate connection until game is quit by client) and the PHP code needs to handle the packet stuff as it comes in.

So PHP doesn't really have threading. What's the best way of handling this?

答:
TCP implementations tend to fragment and join messages; there's no telling how much data or how many message fragments a socket receive will return. You need to know where a message ends and a new one begins (which may happen multiple times in data returned by a single read). Some simple solutions:

Use some kind of delimiter. End each message by '\0'.

Send the message size along with the message. Start each message with "Content-length: 42\n" or two size bytes (0x00 0x42).

Use XML. <message> starts and </message> ends a message.

PHP's XML parser doesn't like incomplete XMLs, though so the third option is out unless you want to match the start and end tags manually. Use the first option if the protocol is based on ASCII, second if it's binary, third if it's already XML.

Now, remember you can get any number of messages per packet. In the most complex case, you might have the end of an earlier message followed by a number of full messages and the beginning of yet another message in a single packet.

A full solution would be along these lines:

```<code>while (connected) {
    while (messages in buffer < 1) {
        read from socket;
        add to buffer;
    }

    while (messages in buffer > 0) {
        extract message from buffer;
        process message;
    }
}
</code>```

...though this is an asynchronous message loop. I'll leave the "if there's a message available, return it; else, wait for one" synchronous implementation as an exercise. (Hint: You'll need a class to build and buffer messages.)

Title: PHP: game loop (threads or the sort)

Body:
I am writing PHP code to be a game client. It uses socket; socket_create followed by socket_connect and then socket_read. It works fine, but the issue is that the server can send a packet at any time which means socket_read needs to be happening constantly in a "game loop". So something like this:

<?php
$reply = "";
do {
     $recv = "";
     $recv = socket_read($socket, '1400');
     if($recv != "") {
         $reply .= $recv;
     }
} while($recv != "");

echo($reply);
?>

Doesn't work because it's stuck in the loop (server doesn't terminate connection until game is quit by client) and the PHP code needs to handle the packet stuff as it comes in.

So PHP doesn't really have threading. What's the best way of handling this?

Body:
TCP implementations tend to fragment and join messages; there's no telling how much data or how many message fragments a socket receive will return. You need to know where a message ends and a new one begins (which may happen multiple times in data returned by a single read). Some simple solutions:

Use some kind of delimiter. End each message by '\0'.

Send the message size along with the message. Start each message with "Content-length: 42\n" or two size bytes (0x00 0x42).

Use XML. <message> starts and </message> ends a message.

PHP's XML parser doesn't like incomplete XMLs, though so the third option is out unless you want to match the start and end tags manually. Use the first option if the protocol is based on ASCII, second if it's binary, third if it's already XML.

Now, remember you can get any number of messages per packet. In the most complex case, you might have the end of an earlier message followed by a number of full messages and the beginning of yet another message in a single packet.

A full solution would be along these lines:

while (connected) {
    while (messages in buffer < 1) {
        read from socket;
        add to buffer;
    }

    while (messages in buffer > 0) {
        extract message from buffer;
        process message;
    }
}

...though this is an asynchronous message loop. I'll leave the "if there's a message available, return it; else, wait for one" synchronous implementation as an exercise. (Hint: You'll need a class to build and buffer messages.)


来源: stackexchange

问:
How can I import bulk data from a CSV file into DynamoDB?
I am trying to import a CSV file data into AWS DynamoDB.

Here's what my CSV file looks like:

```<code>first_name  last_name
sri ram
Rahul   Dravid
JetPay  Underwriter
Anil Kumar  Gurram
</code>```

答: You can use AWS Data Pipeline which is for things like this.  You can upload your csv file to S3 and then use Data Pipeline to retrieve and populate a DynamoDB table. They have a step-by-step tutorial.

ContentLicense: CC BY-SA 4.0

Body:
I am trying to import a CSV file data into AWS DynamoDB.

Here's what my CSV file looks like:

first_name  last_name
sri ram
Rahul   Dravid
JetPay  Underwriter
Anil Kumar  Gurram

ContentLicense: CC BY-SA 3.0


问:
Uploading using FTP but website not adapting to changes (not cache)
I am developing a Wordpress theme for a blog I want to start.

I am using Dreamweaver to upload my files to the server using FTP. It appears that the FTP is working perfectly. I have edited files, uploaded, then checked on the server and the changes are being made.

The problem is the changed are not showing up on my website. They are showing up maybe 5 - 10 minutes after, if at all. The strange thing is .css files work and update perfectly, but the .php files do not.

The issue does not appear to be the cache. I am clearing cache, doing hard-refreshes and using incognito to develop.

答:
You can press ctrl+r for refresh your page and check it . if still out put not come check then follow my suggestion.
1.check your file permission
2.wordpress disabled cache.
3.check htacces </p>


问:
How to update JSON using JQ and get the updated value
I have some data in JSON which I want to edit using JQ.

It's a list of persons.

Each person can have one or more mobile.

Each mobile has a number (which is obviously unique) and no. of calls made.

Also person keep track of total calls (sum of calls for each mobile they have)

I have tried to use self explanatory variables here. Please let me know if the data is not clear enough.

[
  {
    "name": "Person1",
    "mobiles": [{
      "number": "11111",
      "calls": 2
    },{
      "number": "22222",
      "calls": 3
    }],
    "total": 5
  },
  {
    "name": "Person2",
    "mobiles": [{
      "number": "33333",
      "calls": 1
    },{
      "number": "44444",
      "calls": 2
    },{
      "number": "55555",
      "calls": 1
    }],
    "total": 4
  }
]
```

<p>What I want is, given a mobile number and no. of calls made for that mobile on a particular day, update the json (update both the individual counter and the total)</p>

<p>Eg. Let's say for number <code>444444</code> calls made are 5, then the final json should be</p>

<pre class="lang-js prettyprint-override"><code>[
  {
    "name": "Person1",
    "mobiles": [{
      "number": "11111",
      "calls": 2
    },{
      "number": "22222",
      "calls": 3
    }],
    "total": 5
  },
  {
    "name": "Person2",
    "mobiles": [{
      "number": "33333",
      "calls": 1
    },{
      "number": "44444",
      "calls": 7 // previous value was 2, added 5 more
    },{
      "number": "55555",
      "calls": 1
    }],
    "total": 9 // previous total was 4, added 5 more
  }
]
</code>```

What I have tried so far

I am able to update the total calls but not the individual calls for the given number

map(select(.mobiles[].number == "44444").total = .total + 5) gives

[
  {
    "name": "Person1",
    "mobiles": [
      {
        "number": "11111",
        "calls": 2
      },
      {
        "number": "22222",
        "calls": 3
      }
    ],
    "total": 5
  },
  {
    "name": "Person2",
    "mobiles": [
      {
        "number": "33333",
        "calls": 1
      },
      {
        "number": "44444",
        "calls": 2 // How do I update this
      },
      {
        "number": "55555",
        "calls": 1
      }
    ],
    "total": 9 // This is correct
  }
]
```

答:
To update the relevant "calls" along the lines you were exploring:

```<code>map( (.mobiles[] | select(.number == $number) | .calls) += $incr)
</code>```

where the values of $number and $incr can (for example) be specified on the command line, e.g.

```<code>jq --arg number 44444 --argjson incr 5 -f update.jq input.json
</code>```

To update the relevant "total", you could use any/2:

```<code>map( if any(.mobiles[]; .number == $number)
     then .total += $incr
     else .
     end)
</code>```

You could chain these two together, either literally, or (presumably more efficiently) by combining the two filters into a single map.  For readability and maintainability, you might also want to define helper functions (i.e., using def).

Body:
I have some data in JSON which I want to edit using JQ.

It's a list of persons.

Each person can have one or more mobile.

Each mobile has a number (which is obviously unique) and no. of calls made.

Also person keep track of total calls (sum of calls for each mobile they have)

I have tried to use self explanatory variables here. Please let me know if the data is not clear enough.

[
  {
    "name": "Person1",
    "mobiles": [{
      "number": "11111",
      "calls": 2
    },{
      "number": "22222",
      "calls": 3
    }],
    "total": 5
  },
  {
    "name": "Person2",
    "mobiles": [{
      "number": "33333",
      "calls": 1
    },{
      "number": "44444",
      "calls": 2
    },{
      "number": "55555",
      "calls": 1
    }],
    "total": 4
  }
]

What I want is, given a mobile number and no. of calls made for that mobile on a particular day, update the json (update both the individual counter and the total)

Eg. Let's say for number 444444 calls made are 5, then the final json should be

[
  {
    "name": "Person1",
    "mobiles": [{
      "number": "11111",
      "calls": 2
    },{
      "number": "22222",
      "calls": 3
    }],
    "total": 5
  },
  {
    "name": "Person2",
    "mobiles": [{
      "number": "33333",
      "calls": 1
    },{
      "number": "44444",
      "calls": 7 // previous value was 2, added 5 more
    },{
      "number": "55555",
      "calls": 1
    }],
    "total": 9 // previous total was 4, added 5 more
  }
]

What I have tried so far

I am able to update the total calls but not the individual calls for the given number

map(select(.mobiles[].number == "44444").total = .total + 5) gives

[
  {
    "name": "Person1",
    "mobiles": [
      {
        "number": "11111",
        "calls": 2
      },
      {
        "number": "22222",
        "calls": 3
      }
    ],
    "total": 5
  },
  {
    "name": "Person2",
    "mobiles": [
      {
        "number": "33333",
        "calls": 1
      },
      {
        "number": "44444",
        "calls": 2 // How do I update this
      },
      {
        "number": "55555",
        "calls": 1
      }
    ],
    "total": 9 // This is correct
  }
]

Body:
To update the relevant "calls" along the lines you were exploring:

map( (.mobiles[] | select(.number == $number) | .calls) += $incr)

where the values of $number and $incr can (for example) be specified on the command line, e.g.

jq --arg number 44444 --argjson incr 5 -f update.jq input.json

To update the relevant "total", you could use any/2:

map( if any(.mobiles[]; .number == $number)
     then .total += $incr
     else .
     end)

You could chain these two together, either literally, or (presumably more efficiently) by combining the two filters into a single map.  For readability and maintainability, you might also want to define helper functions (i.e., using def).


问:
Is ConsoleColor available for .NET Standard?
I'm creating a class library that targets .NET Standard. I can't seem to find ConsoleColor (or Console, for that matter). Are Console-related APIs available for .NET Standard at all?

答:
Console (and related functionality) can be found in (surprise surprise) System.Console.

While I did try adding that before I asked the question, Console could not be found because I was targeting .NET Standard 1.2, whereas System.Console is only available for .NET Standard 1.3+.


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

答:
Two things:

In a Visual Studio setup project (that doesn't offer support for the RemoveFile functionality) you'd need to run an uninstall custom action to remove those files. That may be trickier than you expect because you'll need to remember that actual install folder - Windows doesn't do it for you - and then remove the *.bin files.

If these are temporary files that are left behind from running the app and you don't really need them, then create them in the standard Temp folder, because:

a) The program files folders are not really intended for data storage, and locating them in Temp will solve your problem.

b) The Temp folder files typically get removed periodically by the user cleaning disk, by automatic cleanup etc. In other words nobody really cares if you leave behind small files in Temp.


问:
MySQL query becomes extremely slow when using Order By
I have a messages table with 15 million rows.

Below query returns about 5 million(But limited in 15 rows) records in less than 1 second :

```<code>SELECT messages.* FROM messages
INNER JOIN gateways ON
messages.gateway_id=gateways.id
INNER JOIN orders ON
gateways.order_id=orders.id
WHERE orders.user_id=6500 AND messages.deleted=0
AND messages.type='Out' LIMIT 15;
</code>```

But when I adding an Order ByidDESC to the end of it, it becomes extremely slow about ~40 seconds :

```<code>SELECT messages.* FROM messages
INNER JOIN gateways ON
messages.gateway_id=gateways.id
INNER JOIN orders ON
gateways.order_id=orders.id
WHERE orders.user_id=6500 AND messages.deleted=0
AND messages.type='Out' ORDER BY messages.id DESC LIMIT 15;
</code>```

Any help would be great appreciated.

答:
I assume that

each order belongs to one user

each gateway belongs to one order

Therefore, this:

```<code>INNER JOIN gateways ON messages.gateway_id=gateways.id
INNER JOIN orders   ON gateways.order_id=orders.id
WHERE orders.user_id=6500 AND messages.deleted=0
</code>```

can be rephrased into English as:

"Get the gateways which belong to the orders which belong to this user".

Now, to get the most recent messages related to this user, the problem is we will likely have many different gateway_id's (about 143 according to your EXPLAIN), so we can't use an index to skip the sort.

Well, we could, as O. Jones demonstrated, but there is a catch. Here is the simplified version of the query:

```<code>SELECT ... FROM messages
WHERE gateway_id IN (1,2) ORDER BY id DESC LIMIT 10
</code>```

If we have an index on (id,gateway_id) then MySQL will most likely decide to scan it in descending order. If it quickly finds 10 messages having "gateway_id IN (1,2)" then it will be fast. However, it could need to scan the entire index if these gateway_ids have very old messages, or no messages at all.

If the PK relationships are as I described, I would materialize a user_id column inside the messages table, which would then allow an index on (user_id,message_id) which would give query timings well under a millisecond.

Body:
I have a messages table with 15 million rows.

Below query returns about 5 million(But limited in 15 rows) records in less than 1 second :

SELECT messages.* FROM messages
INNER JOIN gateways ON
messages.gateway_id=gateways.id
INNER JOIN orders ON
gateways.order_id=orders.id
WHERE orders.user_id=6500 AND messages.deleted=0
AND messages.type='Out' LIMIT 15;

But when I adding an Order ByidDESC to the end of it, it becomes extremely slow about ~40 seconds :

SELECT messages.* FROM messages
INNER JOIN gateways ON
messages.gateway_id=gateways.id
INNER JOIN orders ON
gateways.order_id=orders.id
WHERE orders.user_id=6500 AND messages.deleted=0
AND messages.type='Out' ORDER BY messages.id DESC LIMIT 15;

Any help would be great appreciated.

Body:
I assume that

each order belongs to one user

each gateway belongs to one order

Therefore, this:

INNER JOIN gateways ON messages.gateway_id=gateways.id
INNER JOIN orders   ON gateways.order_id=orders.id
WHERE orders.user_id=6500 AND messages.deleted=0

can be rephrased into English as:

"Get the gateways which belong to the orders which belong to this user".

Now, to get the most recent messages related to this user, the problem is we will likely have many different gateway_id's (about 143 according to your EXPLAIN), so we can't use an index to skip the sort.

Well, we could, as O. Jones demonstrated, but there is a catch. Here is the simplified version of the query:

SELECT ... FROM messages
WHERE gateway_id IN (1,2) ORDER BY id DESC LIMIT 10

If we have an index on (id,gateway_id) then MySQL will most likely decide to scan it in descending order. If it quickly finds 10 messages having "gateway_id IN (1,2)" then it will be fast. However, it could need to scan the entire index if these gateway_ids have very old messages, or no messages at all.

If the PK relationships are as I described, I would materialize a user_id column inside the messages table, which would then allow an index on (user_id,message_id) which would give query timings well under a millisecond.


问:
show the error and resume the stream
I have a real-time search, but if for some reason the forkJoin fails, everything stops working. Any new words I try to look for after the error do not work. How can I show the error and resume the stream normally so that I can search for other words?</p>

```<code>this.search$
  .distinctUntilChanged()
  .switchMap((query) => Rx.Observable.forkJoin(sources)) // If this fails the search stops working
  .subscribe((results) => console.log(results));
</code>```

答:
Try this:

this.search$
  .distinctUntilChanged()
  .switchMap((query) => Rx.Observable.forkJoin(sources)
    // return empty results object, I used an empty array...
    .catch(error => Observable.of([])))
  .subscribe((results) => console.log(results));
```

Notice that catch() is on forkJoin(), not on switchMap()...

Title: show the error and resume the stream

Body:
I have a real-time search, but if for some reason the forkJoin fails, everything stops working. Any new words I try to look for after the error do not work. How can I show the error and resume the stream normally so that I can search for other words?

this.search$
  .distinctUntilChanged()
  .switchMap((query) => Rx.Observable.forkJoin(sources)) // If this fails the search stops working
  .subscribe((results) => console.log(results));

Body:
Try this:

this.search$
  .distinctUntilChanged()
  .switchMap((query) => Rx.Observable.forkJoin(sources)
    // return empty results object, I used an empty array...
    .catch(error => Observable.of([])))
  .subscribe((results) => console.log(results));

Notice that catch() is on forkJoin(), not on switchMap()...


问:
No connected between view and controller
I'm a newbie and I tried finding a solution of this error message:

"The model item passed into the
  dictionary is of type
  'NerdDinner.Controllers.DinnerFormViewModel',
  but this dictionary requires a model
  item of type
  'NerdDinner.Models.Dinner'"

There are similiar problem error but not the same context problem.
I believe that the problem is located in the edit.aspx and still i can't solve it.

DinnersController:

```<code>//
// GET: /Dinners/Create

public ActionResult Create()
{

    Dinner dinner = new Dinner()
    {
        EventDate = DateTime.Now.AddDays(7)
    };

    return View(new DinnerFormViewModel(dinner));
}
</code>```

Models:

```<code>namespace NerdDinner.Models
{
    [MetadataType(typeof(Dinner_Validation))]
    public partial class Dinner
    {

    }

    public class Dinner_Validation
    {
        [Required(ErrorMessage = "Title is required")]
        [StringLength(50, ErrorMessage = "Title may not be longer than 50 characters")]
        public string Title { get; set; }

        [Required(ErrorMessage = "Description is required")]
        [StringLength(265, ErrorMessage =
          "Description must be 256 characters or less")]
        public string Description { get; set; }

        [Required(ErrorMessage = "Address is required")]
        public string Address { get; set; }

        [Required(ErrorMessage = "Country is required")]
        public string Country { get; set; }

        [Required(ErrorMessage = "Phone# is required")]
        public string ContactPhone { get; set; }
    }
}

namespace NerdDinner.Controllers
{
    public class DinnerFormViewModel
    {

        private static string[] _countries = new[]
        {
            "USA",
            "Afghanistan",
            "Akrotiri",
            "Albania",
            //... omitted for brevity
            "Zimbabwe"
        };

        // Properties
        public Dinner Dinner { get; private set; }
        public SelectList Countries { get; private set; }

        // Constructor
        public DinnerFormViewModel(Dinner dinner)
        {
            Dinner = dinner;

            Countries = new SelectList(_countries, dinner.Country);
        }
    }
}
</code>```

Edit.aspx:

```<code><%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<NerdDinner.Controllers.DinnerFormViewModel>" %>

<asp:Content ID="Title" ContentPlaceHolderID="TitleContent" runat="server">
   Edit: <%: Model.Dinner.Title %>
</asp:Content>

<asp:Content ID="Main" ContentPlaceHolderID="MainContent" runat="server">

   <h2>Edit Dinner</h2>
   <% using (Html.BeginForm()) { %>
       <%: Html.ValidationSummary("Please correct the errors and try again.") %>
       <fieldset>
          <legend>Fields</legend>
           <div class="editor-label">
               <%: Html.LabelFor(m => m.Dinner.Title) %>
           </div>
           <div class="editor-field">
               <%: Html.TextBoxFor(m => m.Dinner.Title)%>
               <%: Html.ValidationMessageFor(m => m.Dinner.Title, "*")%>
           </div>
           <div class="editor-label">
               <%: Html.LabelFor(m => m.Dinner.EventDate) %>
           </div>
           <div class="editor-field">
               <%: Html.TextBoxFor(m => m.Dinner.EventDate)%>
               <%: Html.ValidationMessageFor(m => m.Dinner.EventDate, "*")%>
           </div>
           <div class="editor-label">
               <%: Html.LabelFor(m => m.Dinner.Description) %>
           </div>
           <div class="editor-field">
               <%: Html.TextAreaFor(m => m.Dinner.Description) %>
               <%: Html.ValidationMessageFor(m => m.Dinner.Description, "*") %>
           </div>
           <div class="editor-label">
               <%: Html.LabelFor(m => m.Dinner.Address) %>
           </div>
           <div class="editor-field">
               <%: Html.TextBoxFor(m => m.Dinner.Address) %>
               <%: Html.ValidationMessageFor(m => m.Dinner.Address, "*") %>
           </div>
<%: Html.LabelFor(m => m.Dinner.Country) %>
<%: Html.DropDownListFor(m => m.Dinner.Country, Model.Countries) %>
<%: Html.ValidationMessageFor(m => m.Dinner.Country, "*") %>
           <div class="editor-label">
               <%: Html.LabelFor(m => m.Dinner.ContactPhone)%>
           </div>
           <div class="editor-field">
               <%: Html.TextBoxFor(m => m.Dinner.ContactPhone)%>
               <%: Html.ValidationMessageFor(m => Model.Dinner.ContactPhone, "*") %>
           </div>
           <div class="editor-label">
               <%: Html.LabelFor(m => m.Dinner.Latitude)%>
           </div>
           <div class="editor-field">
               <%: Html.TextBoxFor(m => m.Dinner.Latitude)%>
               <%: Html.ValidationMessageFor(m => Model.Dinner.Latitude, "*") %>
           </div>
           <div class="editor-label">
               <%: Html.LabelFor(m => m.Dinner.Longitude)%>
           </div>
           <div class="editor-field">
               <%: Html.TextBoxFor(m => m.Dinner.Longitude)%>
               <%: Html.ValidationMessageFor(m => m.Dinner.Longitude, "*")%>
           </div>
           <p>
               <input type="submit" value="Save" />
           </p>
       </fieldset>

   <% } %>

</asp:Content>
</code>```

答: Your 'Create' action is going to load "Create.aspx" not "Edit.aspx", I suspect that is still pointing to Dinner as the model.</p>

ContentLicense: CC BY-SA 2.5

Body:
I'm a newbie and I tried finding a solution of this error message:

"The model item passed into the
  dictionary is of type
  'NerdDinner.Controllers.DinnerFormViewModel',
  but this dictionary requires a model
  item of type
  'NerdDinner.Models.Dinner'"

There are similiar problem error but not the same context problem.
I believe that the problem is located in the edit.aspx and still i can't solve it.

DinnersController:

//
// GET: /Dinners/Create

public ActionResult Create()
{

    Dinner dinner = new Dinner()
    {
        EventDate = DateTime.Now.AddDays(7)
    };

    return View(new DinnerFormViewModel(dinner));
}

Models:

namespace NerdDinner.Models
{
    [MetadataType(typeof(Dinner_Validation))]
    public partial class Dinner
    {

    }

    public class Dinner_Validation
    {
        [Required(ErrorMessage = "Title is required")]
        [StringLength(50, ErrorMessage = "Title may not be longer than 50 characters")]
        public string Title { get; set; }

        [Required(ErrorMessage = "Description is required")]
        [StringLength(265, ErrorMessage =
          "Description must be 256 characters or less")]
        public string Description { get; set; }

        [Required(ErrorMessage = "Address is required")]
        public string Address { get; set; }

        [Required(ErrorMessage = "Country is required")]
        public string Country { get; set; }

        [Required(ErrorMessage = "Phone# is required")]
        public string ContactPhone { get; set; }
    }
}

namespace NerdDinner.Controllers
{
    public class DinnerFormViewModel
    {

        private static string[] _countries = new[]
        {
            "USA",
            "Afghanistan",
            "Akrotiri",
            "Albania",
            //... omitted for brevity
            "Zimbabwe"
        };

        // Properties
        public Dinner Dinner { get; private set; }
        public SelectList Countries { get; private set; }

        // Constructor
        public DinnerFormViewModel(Dinner dinner)
        {
            Dinner = dinner;

            Countries = new SelectList(_countries, dinner.Country);
        }
    }
}

Edit.aspx:

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<NerdDinner.Controllers.DinnerFormViewModel>" %>

<asp:Content ID="Title" ContentPlaceHolderID="TitleContent" runat="server">
   Edit: <%: Model.Dinner.Title %>
</asp:Content>

<asp:Content ID="Main" ContentPlaceHolderID="MainContent" runat="server">

Edit Dinner

   <% using (Html.BeginForm()) { %>
       <%: Html.ValidationSummary("Please correct the errors and try again.") %>
       <fieldset>
          <legend>Fields</legend>

               <%: Html.LabelFor(m => m.Dinner.Title) %>

               <%: Html.TextBoxFor(m => m.Dinner.Title)%>
               <%: Html.ValidationMessageFor(m => m.Dinner.Title, "*")%>

               <%: Html.LabelFor(m => m.Dinner.EventDate) %>

               <%: Html.TextBoxFor(m => m.Dinner.EventDate)%>
               <%: Html.ValidationMessageFor(m => m.Dinner.EventDate, "*")%>

               <%: Html.LabelFor(m => m.Dinner.Description) %>

               <%: Html.TextAreaFor(m => m.Dinner.Description) %>
               <%: Html.ValidationMessageFor(m => m.Dinner.Description, "*") %>

               <%: Html.LabelFor(m => m.Dinner.Address) %>

               <%: Html.TextBoxFor(m => m.Dinner.Address) %>
               <%: Html.ValidationMessageFor(m => m.Dinner.Address, "*") %>

<%: Html.LabelFor(m => m.Dinner.Country) %>
<%: Html.DropDownListFor(m => m.Dinner.Country, Model.Countries) %>
<%: Html.ValidationMessageFor(m => m.Dinner.Country, "*") %>

               <%: Html.LabelFor(m => m.Dinner.ContactPhone)%>

               <%: Html.TextBoxFor(m => m.Dinner.ContactPhone)%>
               <%: Html.ValidationMessageFor(m => Model.Dinner.ContactPhone, "*") %>

               <%: Html.LabelFor(m => m.Dinner.Latitude)%>

               <%: Html.TextBoxFor(m => m.Dinner.Latitude)%>
               <%: Html.ValidationMessageFor(m => Model.Dinner.Latitude, "*") %>

               <%: Html.LabelFor(m => m.Dinner.Longitude)%>

               <%: Html.TextBoxFor(m => m.Dinner.Longitude)%>
               <%: Html.ValidationMessageFor(m => m.Dinner.Longitude, "*")%>

               <input type="submit" value="Save" />

       </fieldset>

   <% } %>

</asp:Content>


问:
Accessing min and max value within JSON array in JavaScript/HTML
I have the following code that gets data from a database and plots a graph using HTML and the FusionCharts library. I'm just having some trouble with the graph formatting. I want the yAxisMin to be 10 values below the minimum value in the data array and the yAxisMax value to be 10 values above.

```<code>function createJSON(name, data){
    return(
        {
            "chart": {
                "caption": String(name),
                "subCaption": "15-Day Prices",
                "xAxisName": "Day",
                "yAxisName": "Price (USD)",
                "anchorRadius": "1",
                "showValues": "0",
                "borderThickness": "3",
                "yAxisMinValue": data.value.min() - 10,
                "yAxisMaxValue": data.value.max() + 10,
                "theme": "fint"
            },
            "data": data,
        }
    );
}

//I'm including this for context. This is the function that returns the data array
var getHistory = function(req,res,next){

    var data = [];
    History.findOne({"Symbol": String(req.params.sym)}, function(err, foundHistory){
        if(foundHistory){
            (foundHistory.Historical).forEach(function(day){
                data.push({
                    "label": day.Date,
                    "value": day.Close
                });
            });
            res.json(createJSON(foundHistory.Name, data));
            next();
        }
        else{
            next();
        }
    });
};

module.exports = getHistory;
</code>```

Everything else works fine. I just need help with the two lines of code:

```<code>"yAxisMinValue": data.value.min() - 10,
"yAxisMaxValue": data.value.max() + 10,
</code>```

How would I do this? This was my attempt but it does not compile.

答:
How about this? Since your code sample is incomplete, I cannot test it myself.</p>

```<code>function createJSON(name, data){
  var min = Number.MAX_SAFE_INTEGER;
  var max = Number.MIN_SAFE_INTEGER;
  for(var i = 0; i < data.length; i++) {
    if(data[i].value < min) min = data[i].value;
    if(data[i].value > max) max = data[i].value;
  }
  ...
      "yAxisMinValue": min - 10,
      "yAxisMaxValue": max + 10,
  ...
</code>```

Body:
I have the following code that gets data from a database and plots a graph using HTML and the FusionCharts library. I'm just having some trouble with the graph formatting. I want the yAxisMin to be 10 values below the minimum value in the data array and the yAxisMax value to be 10 values above.

function createJSON(name, data){
    return(
        {
            "chart": {
                "caption": String(name),
                "subCaption": "15-Day Prices",
                "xAxisName": "Day",
                "yAxisName": "Price (USD)",
                "anchorRadius": "1",
                "showValues": "0",
                "borderThickness": "3",
                "yAxisMinValue": data.value.min() - 10,
                "yAxisMaxValue": data.value.max() + 10,
                "theme": "fint"
            },
            "data": data,
        }
    );
}

//I'm including this for context. This is the function that returns the data array
var getHistory = function(req,res,next){

    var data = [];
    History.findOne({"Symbol": String(req.params.sym)}, function(err, foundHistory){
        if(foundHistory){
            (foundHistory.Historical).forEach(function(day){
                data.push({
                    "label": day.Date,
                    "value": day.Close
                });
            });
            res.json(createJSON(foundHistory.Name, data));
            next();
        }
        else{
            next();
        }
    });
};

module.exports = getHistory;

Everything else works fine. I just need help with the two lines of code:

"yAxisMinValue": data.value.min() - 10,
"yAxisMaxValue": data.value.max() + 10,

How would I do this? This was my attempt but it does not compile.

Body:
How about this? Since your code sample is incomplete, I cannot test it myself.

function createJSON(name, data){
  var min = Number.MAX_SAFE_INTEGER;
  var max = Number.MIN_SAFE_INTEGER;
  for(var i = 0; i < data.length; i++) {
    if(data[i].value < min) min = data[i].value;
    if(data[i].value > max) max = data[i].value;
  }
  ...
      "yAxisMinValue": min - 10,
      "yAxisMaxValue": max + 10,
  ...


问:
email validation in javascript
I am using razor view in my application.
I am trying to validate my mailID.
I got email pattern format like,

```<code> function validateEmail(mail) {
  var emailPattern =  var emailPattern = /^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
     if (emailPattern.test(mail) == false) {
           $("#emailvalidation").text("Email is not in correct format");
       }
       else if (emailPattern.test(mail) == true) {
        }
     }
</code>```

but If I give this in my function,It is displaying error at the "@" symbol.
can any one help me,how to fix this.

答:
```<code>I am trying to restrict the user not to insert more than two domain after the '@'.

/^[\w-_$\.]+@[\w]+((\.)((\w){2,4})){1,2}$/
</code>```

Title: email validation in javascript

Body:
I am using razor view in my application.
I am trying to validate my mailID.
I got email pattern format like,

 function validateEmail(mail) {
  var emailPattern =  var emailPattern = /^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
     if (emailPattern.test(mail) == false) {
           $("#emailvalidation").text("Email is not in correct format");
       }
       else if (emailPattern.test(mail) == true) {
        }
     }

but If I give this in my function,It is displaying error at the "@" symbol.
can any one help me,how to fix this.


问:
Android Studio - How can I create a Card View?
I am having trouble creating a card view in Android Studio, I am creating an App on Nexus 7.  Please help me with a step-by-step guide to create a working card view :)

A

答:
It is very simple to create card view in android :

very first you have to add dependency in gradle:

compile 'com.android.support:cardview-v7:+'

and you have too add card view in XML:

```<code> <android.support.v7.widget.CardView
    android:id="@+id/card_viewspOffer"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginLeft="2dp"
    android:layout_marginRight="2dp"
    app:cardElevation="5dp"
    app:cardCornerRadius="0.5dp"
    app:cardPreventCornerOverlap="false"
    app:cardUseCompatPadding="true"
  >

<TextView
     android:id="@+id/test"
     android:layout_width="match_parent"
     android:layout_weight="1"
     android:maxLines="5"
     android:padding="10dp"
    android:text="TEST" />
  </android.support.v7.widget.CardView>
</code>```

Inspite of textview you can put all the android components or layouts as per your design need

Body:
It is very simple to create card view in android :

very first you have to add dependency in gradle:

compile 'com.android.support:cardview-v7:+'

and you have too add card view in XML:

 <android.support.v7.widget.CardView
    android:id="@+id/card_viewspOffer"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginLeft="2dp"
    android:layout_marginRight="2dp"
    app:cardElevation="5dp"
    app:cardCornerRadius="0.5dp"
    app:cardPreventCornerOverlap="false"
    app:cardUseCompatPadding="true"
  >

<TextView
     android:id="@+id/test"
     android:layout_width="match_parent"
     android:layout_weight="1"
     android:maxLines="5"
     android:padding="10dp"
    android:text="TEST" />
  </android.support.v7.widget.CardView>

Inspite of textview you can put all the android components or layouts as per your design need


问:
How to create an array from two columns in pandas
suppose I have a DataFrame similar to this:

```<code>d = {'col1': [0, 2, 4], 'col2': [1, 3, 5], 'col3': [2, 4, 8]}
df = pd.DataFrame(d)

   col1  col2  col3
0     0     1     2
1     2     3     4
2     4     5     8
</code>```

How can I select col1 and col2 and turn them into this array?

```<code>array([[0, 1],
       [2, 3],
       [4, 5]])
</code>```

答:
You can access the underlying numpy array via the to_numpy method:

```<code>df[['col1', 'col2']].to_numpy()
Out:
array([[0, 1],
       [2, 3],
       [4, 5]])
</code>```

.values attribute will do the same if you are on an earlier version (before v0.24).

Body:
suppose I have a DataFrame similar to this:

d = {'col1': [0, 2, 4], 'col2': [1, 3, 5], 'col3': [2, 4, 8]}
df = pd.DataFrame(d)

   col1  col2  col3
0     0     1     2
1     2     3     4
2     4     5     8

How can I select col1 and col2 and turn them into this array?

array([[0, 1],
       [2, 3],
       [4, 5]])

Body:
You can access the underlying numpy array via the to_numpy method:

df[['col1', 'col2']].to_numpy()
Out:
array([[0, 1],
       [2, 3],
       [4, 5]])

.values attribute will do the same if you are on an earlier version (before v0.24).


问:
How to convert latitude and longitude into (x,y) coordinates using d3.js
I am making my country's map using d3.js. I use the google maps url to  extract the longitude and latitude values of some points. In order to show a point using d3, I need to convert it into an (x,y) value in pixels and store it in an array of cities. I know this issue is about projection but I couldn't manage to solve it.

This is part of my code.

```<code>var projection = d3.geoMercator().fitSize([width, height], json);
var path = d3.geoPath().projection(projection);

var URL =  "https://www.google.com.tr/maps/place/Ankara/@39.9035553,32.6223376,11z/data=!3m1!4b1!4m5!3m4!1s0x14d347d520732db1:0xbdc57b0c0842b8d!8m2!3d39.9333635!4d32.8597419?hl=tr";

var splitUrl = URL.split('@');
var coords = splitUrl[1].split(',');

console.log(coords[0]);
console.log(coords[1]);

cities.push([coords[0], coords[1]]);
</code>```

答:
You don't need to convert your data to (x,y) pairs in pixels. When you use d3.geoPath.projection(projection) you've set your d3.geoPath() path generator to use the specified projection to automatically convert (latitude, longitude) pairs to (x,y) pairs.

What you need to do is take your (lat, long) pairs and use them to generate a GeoJSON object, which you can then feed to your d3.geoPath generator. You'll probably want a GeoJSON point.

So your code should probably look like:

```<code>var projection = d3.geoMercator().fitSize([width, height], json);
var pathGenerator = d3.geoPath(projection);

var URL =  "https://www.google.com.tr/maps/place/Ankara/@39.9035553,32.6223376,11z/data=!3m1!4b1!4m5!3m4!1s0x14d347d520732db1:0xbdc57b0c0842b8d!8m2!3d39.9333635!4d32.8597419?hl=tr";

var splitUrl = URL.split('@');
var coords = splitUrl[1].split(',');

var geoJsonPoint = {
    type: "Point",
    coordinates: coords,
}

pathGenerator.path(geoJsonPoint);
</code>```

Body:
I am making my country's map using d3.js. I use the google maps url to  extract the longitude and latitude values of some points. In order to show a point using d3, I need to convert it into an (x,y) value in pixels and store it in an array of cities. I know this issue is about projection but I couldn't manage to solve it.

This is part of my code.

var projection = d3.geoMercator().fitSize([width, height], json);
var path = d3.geoPath().projection(projection);

var URL =  "https://www.google.com.tr/maps/place/Ankara/@39.9035553,32.6223376,11z/data=!3m1!4b1!4m5!3m4!1s0x14d347d520732db1:0xbdc57b0c0842b8d!8m2!3d39.9333635!4d32.8597419?hl=tr";

var splitUrl = URL.split('@');
var coords = splitUrl[1].split(',');

console.log(coords[0]);
console.log(coords[1]);

cities.push([coords[0], coords[1]]);

Body:
You don't need to convert your data to (x,y) pairs in pixels. When you use d3.geoPath.projection(projection) you've set your d3.geoPath() path generator to use the specified projection to automatically convert (latitude, longitude) pairs to (x,y) pairs.

What you need to do is take your (lat, long) pairs and use them to generate a GeoJSON object, which you can then feed to your d3.geoPath generator. You'll probably want a GeoJSON point.

So your code should probably look like:

var projection = d3.geoMercator().fitSize([width, height], json);
var pathGenerator = d3.geoPath(projection);

var URL =  "https://www.google.com.tr/maps/place/Ankara/@39.9035553,32.6223376,11z/data=!3m1!4b1!4m5!3m4!1s0x14d347d520732db1:0xbdc57b0c0842b8d!8m2!3d39.9333635!4d32.8597419?hl=tr";

var splitUrl = URL.split('@');
var coords = splitUrl[1].split(',');

var geoJsonPoint = {
    type: "Point",
    coordinates: coords,
}

pathGenerator.path(geoJsonPoint);


问:
'npm' is not recognized as an internal or external command, operable program or batch file, but it's in my env path
I'm trying to launch on Windows a node.js module that I have written on Linux.

I have set the env path to nodejs, i have installed my dependencies, when i use npm alone it's working. But when I npm start my module, it's telling me this :

Here is my package.json's scripts :

Can someone explain to me what's wrong ?

Thanks in advance.

答:
Your issue has to do with how cmd PowerShell and other Windows terminals treats single quoted strings, which in turn will get incorrectly parsed into process.argv in node.js.

This is indicative in the error message:

'npm is not recognized (...)

which shows a leading ' in front of the expected command npm

As a workaround, try using escaped double quotes instead of the single quote in your start script in package.json:

```<code>"start": "nodemon lib/index.js --exec \"npm run lint && babel-node --presets es2015,stage-2\" "
</code>```

Body:
Your issue has to do with how cmd PowerShell and other Windows terminals treats single quoted strings, which in turn will get incorrectly parsed into process.argv in node.js.

This is indicative in the error message:

'npm is not recognized (...)

which shows a leading ' in front of the expected command npm

As a workaround, try using escaped double quotes instead of the single quote in your start script in package.json:

"start": "nodemon lib/index.js --exec \"npm run lint && babel-node --presets es2015,stage-2\" "


问:
Jquery toggle event is messing with checkbox value
I'm using Jquery's toggle event to do some stuff when a user clicks a checkbox, like this:

```<code>$('input#myId').toggle(
function(){
//do stuff
},
function(){
//do other stuff
}
);
</code>```

The problem is that the checkbox isn't being ticked when I click on the checkbox. (All the stuff I've put into the toggle event is working properly.)

I've tried the following:

```<code>$('input#myId').attr('checked', 'checked');
</code>```

and

```<code>$(this).attr('checked', 'checked');
</code>```

and even simply

```<code>return true;
</code>```

But nothing is working. Can anyone tell me where I'm going wrong?

Edit - thanks to all who replied. Dreas' answer very nearly worked for me, except for the part that checked the attribute. This works perfectly (although it's a bit hacky)

```<code>$('input#myInput').change(function ()
{
    if(!$(this).hasClass("checked"))
    {
        //do stuff if the checkbox isn't checked
        $(this).addClass("checked");
        return;
    }

    //do stuff if the checkbox isn't checked
    $(this).removeClass('checked');
});
</code>```

Thanks again to all who replied.

答:
While using the change event handler suggested by Dreas Grech is appropriate, it doesn't work well in IE 6 & 7, which doesn't fire the change event until the focus is blurred (that is, until you click outside the area of the checkbox). As QuirksMode say, "it's a serious bug".

You might want to use the click event handler, but that won't work with keyboard navigation. You need to register a keyup handler too...

See also this related question.

I haven't yet found a good cross-browser solution that supports both mouse clicks and keyboard activation of the checkboxes (and doesn't fire too many events).

Regarding your solution for checking whether the checkbox is checked or not, instead of adding your own checked class, you may use HTML's checked attribute:

```<code>$('input#myInput').change(function () {
    if ($(this).attr("checked")) {
        //do stuff if the checkbox is checked
    } else {
        //do stuff if the checkbox isn't checked
    }
});
</code>```

Any browser sets the checked attribute of an input element to the value "checked" if the checkbox is checked, and sets it to null (or deletes the attribute) if the checkbox is not checked.

OwnerDisplayName: John McCollum

Body:
I'm using Jquery's toggle event to do some stuff when a user clicks a checkbox, like this:

$('input#myId').toggle(
function(){
//do stuff
},
function(){
//do other stuff
}
);

The problem is that the checkbox isn't being ticked when I click on the checkbox. (All the stuff I've put into the toggle event is working properly.)

I've tried the following:

$('input#myId').attr('checked', 'checked');

and

$(this).attr('checked', 'checked');

and even simply

return true;

But nothing is working. Can anyone tell me where I'm going wrong?

Edit - thanks to all who replied. Dreas' answer very nearly worked for me, except for the part that checked the attribute. This works perfectly (although it's a bit hacky)

$('input#myInput').change(function ()
{
    if(!$(this).hasClass("checked"))
    {
        //do stuff if the checkbox isn't checked
        $(this).addClass("checked");
        return;
    }

    //do stuff if the checkbox isn't checked
    $(this).removeClass('checked');
});

Thanks again to all who replied.

LastEditorDisplayName: John McCollum

Body:
While using the change event handler suggested by Dreas Grech is appropriate, it doesn't work well in IE 6 & 7, which doesn't fire the change event until the focus is blurred (that is, until you click outside the area of the checkbox). As QuirksMode say, "it's a serious bug".

You might want to use the click event handler, but that won't work with keyboard navigation. You need to register a keyup handler too...

See also this related question.

I haven't yet found a good cross-browser solution that supports both mouse clicks and keyboard activation of the checkboxes (and doesn't fire too many events).

Regarding your solution for checking whether the checkbox is checked or not, instead of adding your own checked class, you may use HTML's checked attribute:

$('input#myInput').change(function () {
    if ($(this).attr("checked")) {
        //do stuff if the checkbox is checked
    } else {
        //do stuff if the checkbox isn't checked
    }
});

Any browser sets the checked attribute of an input element to the value "checked" if the checkbox is checked, and sets it to null (or deletes the attribute) if the checkbox is not checked.

OwnerDisplayName: dubek

LastEditorDisplayName: dubek


问:
Is there a way to deploy a jar without restarting in Tomcat 9?
I know this question has came up before here, however this is in regards to tomcat 9.

Is there anything that has changed in latest tomcat releases that allows to deploy a jar file without restarting tomcat ? We have been using tomcat 7 in our development and all developers restarting tomcat has been time consuming. Its application that has 700 java files that gets built in to a .jar file and about 1000 jsp files that rely on those .jar file, we are not using war. Can WatchedResource be used for this ?

答:
If you are using Eclipse IDE, then you can simply use FileSync plugin to hot deploy the .class files into tomcat WEB-INF/classes folder.

Basically, you need to map YOUR_PROJECT/target/classes folder to WEB-INF/classes so that they will always be in sync.

This is what we do in our project to avoid the restarts of Tomcat because of source file changes.


问:
Python Module Consisting Only of a Single String
It seems to be legal Python code to have a file consisting only of a single quote-enclosed string. The Python interpreter will not complain about the following:

```<code>#!/usr/bin/python

"somevalue"
</code>```

If I wanted to keep some one-off value (say an API key) isolated from other configuration settings, is it possible to import a file like this into another script as a module and use the string?

The default string representation of the imported module will be something like <module x from y-path>. Can the string value contained within that module be somehow accessed?

(To preemptively cut off tangents, I understand I could just read the file as text or assign the value to variable and from module import variable in another script. There are more conventional ways to accomplish related goals. I am asking out of a desire to better understand the language's design and capabilities.)

答:
You can also retrieve your string by using inspect. Which is almost the same as __doc__ except that it also got "cleaned up" by inspect.cleandoc()

```<code>import inspect
value = inspect.getdoc(__import__('filename'))
</code>```

Body:
It seems to be legal Python code to have a file consisting only of a single quote-enclosed string. The Python interpreter will not complain about the following:

#!/usr/bin/python

"somevalue"

If I wanted to keep some one-off value (say an API key) isolated from other configuration settings, is it possible to import a file like this into another script as a module and use the string?

The default string representation of the imported module will be something like <module x from y-path>. Can the string value contained within that module be somehow accessed?

(To preemptively cut off tangents, I understand I could just read the file as text or assign the value to variable and from module import variable in another script. There are more conventional ways to accomplish related goals. I am asking out of a desire to better understand the language's design and capabilities.)

Body:
You can also retrieve your string by using inspect. Which is almost the same as __doc__ except that it also got "cleaned up" by inspect.cleandoc()

import inspect
value = inspect.getdoc(__import__('filename'))


问:
LoadError: cannot load such file — bcrypt_ext
I have tried to deploy devise authentication on my rails app.

I am getting this issue

"cannot load such file -- bcrypt_ext"

I see it is a common issue amongst windows based computers but the answers to other questions have not helped me yet.

I am running Windows 8 x64 with x86 ruby and devkit

答:
This worked for me:
https://github.com/codahale/bcrypt-ruby/issues/142

-Uninstall all bcrypt versions: gem uninstall bcrypt

select option 3 (uninstall all)

-Uninstall all bcrypt-ruby versions: gem uninstall bcrypt-ruby

select option 3 (uninstall all)

replace the line in your gemfile by:

to add this line to the gemfile:
gem 'bcrypt', platforms: :ruby

did not work for me though but to point the gemfile to the git repository did:

gem 'bcrypt', git: 'https://github.com/codahale/bcrypt-ruby.git', :require => 'bcrypt'

bundle install

and you should be good to go


问:
Rails Custom Validation Across multiple attributes
I have a rails app with the following user models:

Truck
User

A truck belongs to a user with the following association:

```<code>class Unit < ActiveRecord::Base
  belongs_to :primary_crew_member, :foreign_key => :primary_crew_member_id, :class_name => 'User'
  belongs_to :secondary_crew_member, :foreign_key => :secondary_crew_member_id, :class_name => 'User'
end
</code>```

On the Truck model i have validations in place to ensure that the primary_crew_member_id and secondary_crew_member_id is always present as a Truck cannot have no users/crew.

What I want to be able to do is the following:

validate that the primary or secondary crew member (user) is not assigned to any other truck

expanding on that validation I need to make sure if John Doe on Truck A is the Primary crew member he cannot be assigned to a Primary or Secondary slot on any other truck.

expanding further John Doe should not be able to take both the Primary and Secondary slot on a given truck (dual rostering)

I've googled and have come up with a validation that validates the primary slot like so:

validate :primary_multiple_assignment

```<code>  def primary_multiple_assignment
      if Truck.has_primary(primary_crew_member_id)
        errors.add(:base, "User has already been assigned to another truck.")
      end
  end

  def self.has_primary(primary_crew_member_id)
      primary = Truck.where(primary_crew_member_id: primary_crew_member_id).first
      !primary.nil?
  end
</code>```

This seems to work and I can make sure that no user is assigned to a primary slot in any truck besides a single one.  However I need to be able to meet my validation requirements as noted above.  So basically I'm trying to validate multiple columns in one single method but I'm not sure how that would work.

I've read the Rails custom validation guide and am pretty much stuck.  Any information you might have to help would be greatly appreciated.  In the meantime I will keep tinkering and googling to find a solution.

答:
You may do it by using two kinds of validations:</p>

```<code># validate that the primary or secondary crew member (user) is not assigned to
# any other truck
validates :primary_crew_member, uniqueness: true
validates :secondary_crew_member, uniqueness: true

# validate that the primary crew member can't be secondary crew member on any
# truck (including current one)
validate :primary_not_to_be_secondary

# validate that the secondary crew member can't be primary crew member on any
# truck (including current one)
validate :secondary_not_to_be_primary

def primary_not_to_be_secondary
  if Truck.where(secondary_crew_member_id: primary_crew_member_id).present?
      errors.add(:base, "Primary crew member already assigned as secondary crew member.")
  end
end

def secondary_not_to_be_primary
  if Truck.where(primary_crew_member_id: secondary_crew_member_id).present?
      errors.add(:base, "Secondary crew member already assigned as primary crew member.")
  end
end
</code>```

Body:
I have a rails app with the following user models:

Truck
User

A truck belongs to a user with the following association:

class Unit < ActiveRecord::Base
  belongs_to :primary_crew_member, :foreign_key => :primary_crew_member_id, :class_name => 'User'
  belongs_to :secondary_crew_member, :foreign_key => :secondary_crew_member_id, :class_name => 'User'
end

On the Truck model i have validations in place to ensure that the primary_crew_member_id and secondary_crew_member_id is always present as a Truck cannot have no users/crew.

What I want to be able to do is the following:

validate that the primary or secondary crew member (user) is not assigned to any other truck

expanding on that validation I need to make sure if John Doe on Truck A is the Primary crew member he cannot be assigned to a Primary or Secondary slot on any other truck.

expanding further John Doe should not be able to take both the Primary and Secondary slot on a given truck (dual rostering)

I've googled and have come up with a validation that validates the primary slot like so:

validate :primary_multiple_assignment

  def primary_multiple_assignment
      if Truck.has_primary(primary_crew_member_id)
        errors.add(:base, "User has already been assigned to another truck.")
      end
  end

  def self.has_primary(primary_crew_member_id)
      primary = Truck.where(primary_crew_member_id: primary_crew_member_id).first
      !primary.nil?
  end

This seems to work and I can make sure that no user is assigned to a primary slot in any truck besides a single one.  However I need to be able to meet my validation requirements as noted above.  So basically I'm trying to validate multiple columns in one single method but I'm not sure how that would work.

I've read the Rails custom validation guide and am pretty much stuck.  Any information you might have to help would be greatly appreciated.  In the meantime I will keep tinkering and googling to find a solution.

Body:
You may do it by using two kinds of validations:

# validate that the primary or secondary crew member (user) is not assigned to
# any other truck
validates :primary_crew_member, uniqueness: true
validates :secondary_crew_member, uniqueness: true

# validate that the primary crew member can't be secondary crew member on any
# truck (including current one)
validate :primary_not_to_be_secondary

# validate that the secondary crew member can't be primary crew member on any
# truck (including current one)
validate :secondary_not_to_be_primary

def primary_not_to_be_secondary
  if Truck.where(secondary_crew_member_id: primary_crew_member_id).present?
      errors.add(:base, "Primary crew member already assigned as secondary crew member.")
  end
end

def secondary_not_to_be_primary
  if Truck.where(primary_crew_member_id: secondary_crew_member_id).present?
      errors.add(:base, "Secondary crew member already assigned as primary crew member.")
  end
end


问:
Get a HTML5 video to play once on page load and then fade out
I am trying to get a HTML5 clip to play only once on first arrival/pageload to the home page and then not play again. Also I would like the video to fadeout and disappear after it's played. I know you can do this with JQuery once and fadeout, but I'm a beginner and I am struggling with the syntax. Can a more experienced coder help me adjust my code so this works please? Here's what I have so far!

```<code><!DOCTYPE html>
<html>
<head>
<script src="jquery-3.2.0.min.js"></script>
<script>
$(document).ready(function(){
$("#video").one("load", function(){
$('#video').get(0).play()
});

</script>

</head>
<body>

<h2>This is a website</h2>

<video id="video">
<source src="clip.mp4" type="video/mp4">

Your browser does not support HTML5 video.
</video>
</body>
</html>
</code>```

答:
UPDATE

OP requests that the state of the video is persistent. I suggested cookies or localStorage. The following update is hosted on PLUNKER but not on the Snippet because there's strict security measures that are inhibiting the use of localStorage.

There's a basic flow to the demonstration you should adhere to initially:

Upon initial page load, the video plays and the console says:

Cache set to: played

After the video has ended and faded out, reload the page. Notice that the video is no longer present nor is it playing. The console now says:

Cache is: played

Reload the page several times and it will not change.

Should you have the need to revert the page back to it's original state, I have added a Delete Cache button that deletes that specific key that stores the information responsible for keeping the page at the state of post video playback.

Once the Delete Cache button is clicked, the console should say:

undefined

This means that the cache was successfully deleted. Details are commented within the PLUNKER

Create a <video> dynamically and remove it from the DOM on the ended event. Details commented in Snippet.

SNIPPET

// Create and reference video element
var vid = document.createElement('video');

// Add class for styling
vid.classList.add('playing');

// Add a src to .vid
vid.src = 'http://media6000.dropshots.com/photos/1381926/20170326/023642.mp4';

// Load .vid
vid.load();

// Add .vid to body
document.body.appendChild(vid);

// Play video
vid.play();

/* Register ended event to vid
|| After video has ended...
*/
vid.addEventListener('ended', function(e) {

  // Pause vid
  vid.pause()

  /* Reset time played. This method used
  || along with .pause() is equivelant to "stop"
  */
  vid.currentTime = 0;

  // Simulate a `non-playing state`
  vid.classList.remove('playing');

  /* Delay the call to remove vid in order
  || to preserve the fade ouyt effect.
  */
  setTimeout(function() {
    document.body.removeChild(vid);
  }, 2000);
}, false);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>video.playing {
  opacity: 1;
  transition: opacity 3s ease;
}

video {
  opacity: 0;
  transition: opacity 3s ease;
}</code>```

Body:
I am trying to get a HTML5 clip to play only once on first arrival/pageload to the home page and then not play again. Also I would like the video to fadeout and disappear after it's played. I know you can do this with JQuery once and fadeout, but I'm a beginner and I am struggling with the syntax. Can a more experienced coder help me adjust my code so this works please? Here's what I have so far!

<!DOCTYPE html>

This is a website

<video id="video">
<source src="clip.mp4" type="video/mp4">

Your browser does not support HTML5 video.
</video>

Body:
UPDATE

OP requests that the state of the video is persistent. I suggested cookies or localStorage. The following update is hosted on PLUNKER but not on the Snippet because there's strict security measures that are inhibiting the use of localStorage.

There's a basic flow to the demonstration you should adhere to initially:

Upon initial page load, the video plays and the console says:

Cache set to: played

After the video has ended and faded out, reload the page. Notice that the video is no longer present nor is it playing. The console now says:

Cache is: played

Reload the page several times and it will not change.

Should you have the need to revert the page back to it's original state, I have added a Delete Cache button that deletes that specific key that stores the information responsible for keeping the page at the state of post video playback.

Once the Delete Cache button is clicked, the console should say:

undefined

This means that the cache was successfully deleted. Details are commented within the PLUNKER

Create a <video> dynamically and remove it from the DOM on the ended event. Details commented in Snippet.

SNIPPET

// Create and reference video element
var vid = document.createElement('video');

// Add class for styling
vid.classList.add('playing');

// Add a src to .vid
vid.src = 'http://media6000.dropshots.com/photos/1381926/20170326/023642.mp4';

// Load .vid
vid.load();

// Add .vid to body
document.body.appendChild(vid);

// Play video
vid.play();

/* Register ended event to vid
|| After video has ended...
*/
vid.addEventListener('ended', function(e) {

  // Pause vid
  vid.pause()

  /* Reset time played. This method used
  || along with .pause() is equivelant to "stop"
  */
  vid.currentTime = 0;

  // Simulate a `non-playing state`
  vid.classList.remove('playing');

  /* Delay the call to remove vid in order
  || to preserve the fade ouyt effect.
  */
  setTimeout(function() {
    document.body.removeChild(vid);
  }, 2000);
}, false);

video.playing {
  opacity: 1;
  transition: opacity 3s ease;
}

video {
  opacity: 0;
  transition: opacity 3s ease;
}


问:
Getting accuracy of registration from matches
I have a normal ORB application. Since there is no way to find out the accuracy of my homography, I am trying to get to find out the accuracy of my matches, which is the right way to do so? In my code apparently the matches after removing outliers are in raw_matches. I want after I perform the ratio test, to get the good matches and find the accuracy of them.

Code:

```<code>detector = cv2.ORB_create(FEATURESCOUNT)
kp1, desc1 = detector.detectAndCompute(img1, None)
kp2, desc2 = detector.detectAndCompute(img2, None)

flann_params= dict(algorithm = FLANN_INDEX_LSH, table_number = 6, key_size = 12, bmulti_probe_level = 1)
matcher = cv2.FlannBasedMatcher(flann_params, {})
raw_matches = matcher.knnMatch(desc1, trainDescriptors = desc2, k = 2)

ratio = 0.9
mkp1, mkp2 = [], []

for m in raw_matches:
    if len(m) == 2 and m[0].distance < m[1].distance * ratio:
        m = m[0]
        mkp1.append( kp1[m.queryIdx] )
        mkp2.append( kp2[m.trainIdx] )

print max(distmax)
distall = sum(i for i in distmax)
print distall/len(distmax)

p1 = np.float32([kp.pt for kp in mkp1])
p2 = np.float32([kp.pt for kp in mkp2])

comps =[]
res = []

kp_pairs = zip(mkp1, mkp2)

if len(p1) >= 4:
    H, status = cv2.findHomography(p1, p2, cv2.RANSAC, 5.0)
    comps = getComponents(H)
    print (comps)
    print('%d / %d  inliers/matched' % (np.sum(status), len(status)))
else:
    H, status = None, None
    print('%d matches found, not enough for homography estimation' % len(p1))
</code>```

答:
One common measure for the quality of the homography (under the assumption that errors exist in both images) is the reprojection error. When the error of each point correspondence is gaussian, then a minimal reprojection error is equivalent to the maximum likelihood estimate. It is calculated as follows, where (x_i, x_i') are the correspondences, H is the homography and d is the geometric distance in the image, that means on the inhomogenous image points.

findHomography internally already tries to optimize the reprojection error. If a homography cannot be found (based on the passed max reprojection error), then the function should return None.

If results are plain wrong I would change ORB to AKAZE features and reduce the maximum reprojection error for inlier classification in the RANSAC scheme.
If the homography is a good coarse estimate which should be further optimized, you could use the homography to find more matches on all interest points by mapping each point with the homography and find the nearest interest point in a local neighbourhood. Afterwards you could compute findHomography again.

Body:
I have a normal ORB application. Since there is no way to find out the accuracy of my homography, I am trying to get to find out the accuracy of my matches, which is the right way to do so? In my code apparently the matches after removing outliers are in raw_matches. I want after I perform the ratio test, to get the good matches and find the accuracy of them.

Code:

detector = cv2.ORB_create(FEATURESCOUNT)
kp1, desc1 = detector.detectAndCompute(img1, None)
kp2, desc2 = detector.detectAndCompute(img2, None)

flann_params= dict(algorithm = FLANN_INDEX_LSH, table_number = 6, key_size = 12, bmulti_probe_level = 1)
matcher = cv2.FlannBasedMatcher(flann_params, {})
raw_matches = matcher.knnMatch(desc1, trainDescriptors = desc2, k = 2)

ratio = 0.9
mkp1, mkp2 = [], []

for m in raw_matches:
    if len(m) == 2 and m[0].distance < m[1].distance * ratio:
        m = m[0]
        mkp1.append( kp1[m.queryIdx] )
        mkp2.append( kp2[m.trainIdx] )

print max(distmax)
distall = sum(i for i in distmax)
print distall/len(distmax)

p1 = np.float32([kp.pt for kp in mkp1])
p2 = np.float32([kp.pt for kp in mkp2])

comps =[]
res = []

kp_pairs = zip(mkp1, mkp2)

if len(p1) >= 4:
    H, status = cv2.findHomography(p1, p2, cv2.RANSAC, 5.0)
    comps = getComponents(H)
    print (comps)
    print('%d / %d  inliers/matched' % (np.sum(status), len(status)))
else:
    H, status = None, None
    print('%d matches found, not enough for homography estimation' % len(p1))


问:
Get column data in JavaDB via foreign key
Outset: I am building a page in JSP / EJB (Java EE 8) that displays 2 tables: 1 for every user registerd in the database with their name and score and another one that displays all pending challenges to rock-paper-scisors for the currently logged in user.

Databases: So far I have 2 tables in that can be access via the "LOCALHOST." prefix: Usercredentials and Pending_Challenges. Both were created using the following code:

Database: JavaDB

Usercredentials:

```<code>CREATE TABLE USERCREDENTIALS (

    username varchar(10) primary key,
    password varchar(10) not null

);
</code>```

Yes, yes I know these are not the best fields to use but I blame my team mate! :)

Pending_Challenges:

```<code>CREATE TABLE PENDING_CHALLENGES (

    challenge_id integer primary key,
    from_user varchar(10) references Usercredentials(username),
    to_user varchar(10) references Usercredentials(username),

);
</code>```

The tables hold the following data so far:

```<code>Username | Password | Score
---------------------------
tom      | tom      | 5
mo       | mo       | 2
jon      | jon      | 0

Challenge_ID | From_User | To_User
----------------------------------
1            | tom       | mo
2            | jon       | tom
</code>```

I call on these tables in a file named ListUserServlet.java where I run 2 queries. Each one is to create a different set of results (code below ofc) to be printed in 2 different tables.

```<code>{... working Java code...}

    System.out.println("Creating EMF query for userList");
    String query = "SELECT U FROM Usercredentials U ORDER BY U.score DESC";
    List users = em.createQuery(query).getResultList();
    request.setAttribute("userList", users");

{... working Java code...}
</code>```

In my .jsp file that then displays the table, I get the following (don't mind the ID tags, we're changing that):

```<code><h3>Current rankings:</h3>

    <form id="challengeUserForm" action="ChallengeUser" method="POST">
    <table id="userListTable" border="3">
        <tr >
            <th>Username</th>
            <th>Challenge others</th>
            <th>Score</th>
        </tr>
        <c:forEach var="user" begin="0" items="${requestScope.userList}">
            <tr>
                <td>${user.username}  </td>
                <td><input type="submit" id="${user.username}" value="Challenge!"></td>
                <td>${user.score}</td>
            </tr>
        </c:forEach>
    </table>
</code>```

Using this approach, I also managed to print out ALL of the currently held challenges in that table by using:

```<code>{... working Java code...}

    query = "SELECT P FROM PendingChallenges P";
    List chall = em.createQuery(query).getResultList();
    request.setAttribute("pendingList", chall);

{... working Java code...}
</code>```

Now, using the same logic, this is how I print the table:

```<code><h3>Pending challenges:</h3>

<form id="acceptChallengeForm" action="AcceptChallenge" method="POST">
    <table id="pendingTable" border="3">
        <tr>
            <th>Username</th>
            <th>Accept challenge</th>
        </tr>
        <c:forEach var="pending" begin="0" items="${requestScope.pendingList}">
            <tr>
                <td>${pending.fromUser.username}   </td>
                <td><input type="submit" id="${pending.fromUser.username} " value="Accept!"></td>
            </tr>
        </c:forEach>
    </table>
</form>
</code>```

I need to get every row from column "from_user" that is NOT the currently logged in user (session variable is in place already). My simple thinking was to include a "NOT LIKE" statement in the Pending query:

```<code>query = "SELECT P.fromUser FROM PendingChallenges P WHERE P.fromUser NOT LIKE '" + current_user + "'";
</code>```

"current_user" is that EJB session String I mentioned.

However, every time I run it, I either get errors saying that either "P.fromUser" is not a String, "P.fromUser.username" does not belong to "entity[Usercredentials]" or the like OR the keyword "LIKE" has not been recognised -> Something along the lines of SQLException Error Code 30000.

答:
I would read about "SQL joins".

The query should be something like this to get the fields from the user credentials table:

```<code>SELECT * FROM PendingChallenges P
   INNER JOIN UserCredentials U ON P.fromUser = U.username
   WHERE P.fromUser != '" + current_user + "'"
</code>```

Body:
Outset: I am building a page in JSP / EJB (Java EE 8) that displays 2 tables: 1 for every user registerd in the database with their name and score and another one that displays all pending challenges to rock-paper-scisors for the currently logged in user.

Databases: So far I have 2 tables in that can be access via the "LOCALHOST." prefix: Usercredentials and Pending_Challenges. Both were created using the following code:

Database: JavaDB

Usercredentials:

CREATE TABLE USERCREDENTIALS (

    username varchar(10) primary key,
    password varchar(10) not null

);

Yes, yes I know these are not the best fields to use but I blame my team mate! :)

Pending_Challenges:

CREATE TABLE PENDING_CHALLENGES (

    challenge_id integer primary key,
    from_user varchar(10) references Usercredentials(username),
    to_user varchar(10) references Usercredentials(username),

);

The tables hold the following data so far:

Username | Password | Score
---------------------------
tom      | tom      | 5
mo       | mo       | 2
jon      | jon      | 0

Challenge_ID | From_User | To_User
----------------------------------
1            | tom       | mo
2            | jon       | tom

I call on these tables in a file named ListUserServlet.java where I run 2 queries. Each one is to create a different set of results (code below ofc) to be printed in 2 different tables.

{... working Java code...}

    System.out.println("Creating EMF query for userList");
    String query = "SELECT U FROM Usercredentials U ORDER BY U.score DESC";
    List users = em.createQuery(query).getResultList();
    request.setAttribute("userList", users");

{... working Java code...}

In my .jsp file that then displays the table, I get the following (don't mind the ID tags, we're changing that):

Current rankings:

    <form id="challengeUserForm" action="ChallengeUser" method="POST">

            Username
            Challenge others
            Score

        <c:forEach var="user" begin="0" items="${requestScope.userList}">

                ${user.username}
                <input type="submit" id="${user.username}" value="Challenge!">
                ${user.score}

        </c:forEach>

Using this approach, I also managed to print out ALL of the currently held challenges in that table by using:

{... working Java code...}

    query = "SELECT P FROM PendingChallenges P";
    List chall = em.createQuery(query).getResultList();
    request.setAttribute("pendingList", chall);

{... working Java code...}

Now, using the same logic, this is how I print the table:

Pending challenges:

<form id="acceptChallengeForm" action="AcceptChallenge" method="POST">

            Username
            Accept challenge

        <c:forEach var="pending" begin="0" items="${requestScope.pendingList}">

                ${pending.fromUser.username}
                <input type="submit" id="${pending.fromUser.username} " value="Accept!">

        </c:forEach>

</form>

I need to get every row from column "from_user" that is NOT the currently logged in user (session variable is in place already). My simple thinking was to include a "NOT LIKE" statement in the Pending query:

query = "SELECT P.fromUser FROM PendingChallenges P WHERE P.fromUser NOT LIKE '" + current_user + "'";

"current_user" is that EJB session String I mentioned.

However, every time I run it, I either get errors saying that either "P.fromUser" is not a String, "P.fromUser.username" does not belong to "entity[Usercredentials]" or the like OR the keyword "LIKE" has not been recognised -> Something along the lines of SQLException Error Code 30000.

Body:
I would read about "SQL joins".

The query should be something like this to get the fields from the user credentials table:

SELECT * FROM PendingChallenges P
   INNER JOIN UserCredentials U ON P.fromUser = U.username
   WHERE P.fromUser != '" + current_user + "'"


问:
Why my carousel disappear when click on menu?
can anybody tell me why my bootstrap carousel disappear when i click on nav menu btn..

I want to smooth scroll to div on same page...
Can any body sole this weird problem.

here is a fiddle---------------
https://jsfiddle.net/vo1npqdx/502/

$(document).ready(function() {
  // Add smooth scrolling to all links
  $("#siteoverview_btn").on('click', function(event) {

    // Make sure this.hash has a value before overriding default behavior

    $(".active").removeClass("active");

    // Prevent default anchor click behavior
    event.preventDefault();

    // Using jQuery's animate() method to add smooth page scroll
    // The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area
    $('html, body').animate({
      scrollTop: $("#siteoverview_content").offset().top
    }, 800, function() {

      // Add hash (#) to URL when done scrolling (default click behavior)
    });
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <!-- nav here -->
  <nav class="navbar navbar-default roboto normal menu" role="navigation">
    <div class="container">
      <div class="navbar-header">
      </div>
      <ul class="nav navbar-nav nav_bar_block">
        <li class="border_right">SITE OVERVIEW</li>
      </ul>
    </div>
  </nav>

  <!-- nav here -->

  <div class="banner">
    <div class="notification_bar">
      <div class="container">
        <div class="content">
        </div>
      </div>
    </div>

    <div id="carousel-example-generic" class="carousel slide" data-ride="carousel">
      <!-- Indicators -->
      <ol class="carousel-indicators">
        <li data-target="#carousel-example-generic" data-slide-to="0" class="active"></li>
        <li data-target="#carousel-example-generic" data-slide-to="1"></li>
        <li data-target="#carousel-example-generic" data-slide-to="2"></li>
      </ol>

      <!-- Wrapper for slides -->
      <div class="carousel-inner" role="listbox">
        <div class="item active">
          <img src="http://www.777a7.com/img65/vxxrimfdyqtwewgfynzp.jpg" alt="...">
          <div class="carousel-caption">
            ...
          </div>
        </div>
        <div class="item">
          <img src="http://www.777a7.com/img65/vxxrimfdyqtwewgfynzp.jpg" alt="...">
          <div class="carousel-caption">
            ...
          </div>
        </div>
        <div class="item">
          <img src="http://www.777a7.com/img65/vxxrimfdyqtwewgfynzp.jpg" alt="...">
          <div class="carousel-caption">
            ...
          </div>
        </div>
      </div>

      <!-- Controls -->

        <span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span>
        <span class="sr-only">Previous</span>

        <span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span>
        <span class="sr-only">Next</span>

    </div>
  </div>

  <div class="main_body">
    <div class="container">
      <div class="body_content">
        <h3 class="body_head">AUCTION CENTRE</h3>
        <div class="row">
          <div class="col-sm-8">

            <p>There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don't look even slightly believable. If you are going to use a passage of
              Lorem Ipsum, you need to be sure there isn't anything embarrassing hidden in the middle of text. All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary, making this the first true generator on the Internet.
              It uses a dictionary of over 200 Latin words, combined with a handful of model sentence structures, to generate Lorem Ipsum which looks reasonable. The generated Lorem Ipsum is therefore always free from repetition, injected humour, or non-characteristic
              words etc.</p>

            <br>
            <div class="row content_points">
              <div class="col-sm-6">
                <h4>LATEST NEWS</h4>
                <hr class="underline">
                <ul>
                  <li><b>LAST UPDATED ON: MARCH 17, 2017</b></li>
                  <li>Lorem Ipsum is simply dummy text of the printing and typesetting industry.</li>
                  <li>Many desktop publishing packages and web page editors</li>
                  <li>All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary</li>
                  <li>The standard chunk of Lorem Ipsum used since the 1500s is reproduced below</li>
                  <li>Many desktop publishing packages and web page editors</li>
                </ul>
              </div>
              <div id="siteoverview_content" class="col-sm-6">
                <h4>SITE OVERVIEW</h4>
                <hr class="underline">
                <ul>
                  <li>AWR Upload</li>
                  <li>AWR Report</li>
                  <li>Statistical Info</li>
                  <li>Gatepass Entry</li>
                  <li>Customised Reports</li>
                  <li>Other Info</li>
                  <li>Other Info 1</li>
                  <li>Other Info 2</li>
                </ul>
              </div>
            </div>

          </div>
        </div>
      </div>
    </div>

  </div>

  <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
  <!-- <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> -->
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
  <!-- Include all compiled plugins (below), or include individual files as needed -->
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</body></code>```

答:
```<code>$( ".active" ).removeClass( "active" );
</code>```

<p>using this line you are remove all the active class including carousel item active class. Because bootstrap by default has display:none; for .carousel-inner>.item and .carousel-inner>.active class has display block. So that's why when you remove active class, your carousel item disappear. So either you can remove that line or use this. Live on fiddle </p>

```<code>$(".active").not('.item.active').removeClass("active");
</code>```

Body:
can anybody tell me why my bootstrap carousel disappear when i click on nav menu btn..

I want to smooth scroll to div on same page...
Can any body sole this weird problem.

here is a fiddle---------------
https://jsfiddle.net/vo1npqdx/502/

$(document).ready(function() {
  // Add smooth scrolling to all links
  $("#siteoverview_btn").on('click', function(event) {

    // Make sure this.hash has a value before overriding default behavior

    $(".active").removeClass("active");

    // Prevent default anchor click behavior
    event.preventDefault();

    // Using jQuery's animate() method to add smooth page scroll
    // The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area
    $('html, body').animate({
      scrollTop: $("#siteoverview_content").offset().top
    }, 800, function() {

      // Add hash (#) to URL when done scrolling (default click behavior)
    });
  });
});

  <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

SITE OVERVIEW

            ...

            ...

            ...

        Previous

        Next

AUCTION CENTRE

There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don't look even slightly believable. If you are going to use a passage of
              Lorem Ipsum, you need to be sure there isn't anything embarrassing hidden in the middle of text. All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary, making this the first true generator on the Internet.
              It uses a dictionary of over 200 Latin words, combined with a handful of model sentence structures, to generate Lorem Ipsum which looks reasonable. The generated Lorem Ipsum is therefore always free from repetition, injected humour, or non-characteristic
              words etc.

LATEST NEWS

LAST UPDATED ON: MARCH 17, 2017

Lorem Ipsum is simply dummy text of the printing and typesetting industry.

Many desktop publishing packages and web page editors

All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary

The standard chunk of Lorem Ipsum used since the 1500s is reproduced below

Many desktop publishing packages and web page editors

SITE OVERVIEW

AWR Upload

AWR Report

Statistical Info

Gatepass Entry

Customised Reports

Other Info

Other Info 1

Other Info 2

Body:
$( ".active" ).removeClass( "active" );

using this line you are remove all the active class including carousel item active class. Because bootstrap by default has display:none; for .carousel-inner>.item and .carousel-inner>.active class has display block. So that's why when you remove active class, your carousel item disappear. So either you can remove that line or use this. Live on fiddle

$(".active").not('.item.active').removeClass("active");


问:
method references count statistics in Android project
For projects reasons I need to find out which methods of a class are referenced (used) and how many times. Lint gives me ability to find which are unused but I cannot find any tool to precise how many times methods are referenced. It could be an Android Studio plugin or a library (or any other way that prepares these statistics)

thanks in advance for your support

答:
You have to first step back and and clarify your requirements.

To determine how often a method is used within other pieces of code is trivial; any decent IDE allows you search your project/workspace for usage of methods.

But you are asking about count statistics. That is a **completely* different thing. An easy solution is to simply put static counters into your classes manually. But such self-grown solutions can turn pretty complex quickly; as people start asking for all kinds of solutions. Thus you might rather looking into profiling tools, such as those for java in general, or specifically for Android: look here.


问:
How to use Navigation Keys as Input in Windows Forms
I am trying to use navigation keys to get input command from user. For Example:- When the user presses Right navigation key, a method should be called to perform some task. Below is the piece of code i tried to use for this purpose:

```<code>private void MainForm_Load(object sender, EventArgs e)
{
    KeyPreview = true;
    this.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.MainForm_KeyPress);
}

private void MainForm_KeyPress(object sender, KeyPressEventArgs e)
{
    switch (e.KeyChar)
    {
        case (char)Keys.Right:
            NextMenuItem_Click(sender, EventArgs.Empty);
            break;
    }
}
</code>```

Note that this worked fine for other keys like Alphabets, Numeric-Keys and Even enter key. But somehow not working for Left, Right, Up, Down navigation keys.

Please guide me. I shall be glad and thankful to you :-)
Your Response will be appreciated !
 (I am using Visual Studio 2017)

答:
Use that instead of your switch and handle the KeyDown event instead of the KeyPress event:

```<code>switch (e.KeyCode)
{
    case Keys.Right:
        NextMenuItem_Click(sender, EventArgs.Empty);
        e.Handled = true;
        e.Suppressed = true;
        break;
}
</code>```

And I don't think that you need to set the KeyPreview option.
The problem with your code is that you try to parse the Right key to a char, which doesn't work as expected.

Body:
I am trying to use navigation keys to get input command from user. For Example:- When the user presses Right navigation key, a method should be called to perform some task. Below is the piece of code i tried to use for this purpose:

private void MainForm_Load(object sender, EventArgs e)
{
    KeyPreview = true;
    this.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.MainForm_KeyPress);
}

private void MainForm_KeyPress(object sender, KeyPressEventArgs e)
{
    switch (e.KeyChar)
    {
        case (char)Keys.Right:
            NextMenuItem_Click(sender, EventArgs.Empty);
            break;
    }
}

Note that this worked fine for other keys like Alphabets, Numeric-Keys and Even enter key. But somehow not working for Left, Right, Up, Down navigation keys.

Please guide me. I shall be glad and thankful to you :-)
Your Response will be appreciated !
 (I am using Visual Studio 2017)

Body:
Use that instead of your switch and handle the KeyDown event instead of the KeyPress event:

switch (e.KeyCode)
{
    case Keys.Right:
        NextMenuItem_Click(sender, EventArgs.Empty);
        e.Handled = true;
        e.Suppressed = true;
        break;
}

And I don't think that you need to set the KeyPreview option.
The problem with your code is that you try to parse the Right key to a char, which doesn't work as expected.


问:
Why does the WPF listbox change selection on mouse button down rather than button up?
I had never noticed this before, but the WPF ListBox seems to change its SelectedItem when the  Mouse is down, but has not yet been released. As a quick example, just create a simple ListBox with several ListBoxItems, like so:

```<code><ListBox>
  <ListBoxItem>Hello</ListBoxItem>
  <ListBoxItem>World</ListBoxItem>
  <ListBoxItem>ListBox</ListBoxItem>
  <ListBoxItem>Test</ListBoxItem>
</ListBox>
</code>```

fire up your application, press the mouse button (don't release it!) and move the mouse around. The SelectedItem will change as the mouse moves. This illustrates the larger problem (for me, at least), that a ListBox's SelectedItem will be set as soon as you mouse down, not when mouse up occurs. Usually that isn't a problem, but in my case I'd like to enable drag & drop on the items in my ListBox, without the items explicitly becoming selected.

I imagine my only recourse is to build a custom ItemsControl or Selector with selection-style semantics similar to ListBox, so really my question is more, why does ListBox work this way? Does anyone have any insight into this?

答:
I personally prefer MVVM and attached properties to tweak the behavior of elements.

Furthermore the solution proposed by Tomas Kosar doesn't seem to work when the ItemsSource property is bound.

Here's what I currently use (C# 7 syntax)

```<code>public static class SelectorBehavior
{
    #region bool ShouldSelectItemOnMouseUp

    public static readonly DependencyProperty ShouldSelectItemOnMouseUpProperty =
        DependencyProperty.RegisterAttached(
            "ShouldSelectItemOnMouseUp", typeof(bool), typeof(SelectorBehavior),
            new PropertyMetadata(default(bool), HandleShouldSelectItemOnMouseUpChange));

    public static void SetShouldSelectItemOnMouseUp(DependencyObject element, bool value)
    {
        element.SetValue(ShouldSelectItemOnMouseUpProperty, value);
    }

    public static bool GetShouldSelectItemOnMouseUp(DependencyObject element)
    {
        return (bool)element.GetValue(ShouldSelectItemOnMouseUpProperty);
    }

    private static void HandleShouldSelectItemOnMouseUpChange(
        DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        if (d is Selector selector)
        {
            selector.PreviewMouseDown -= HandleSelectPreviewMouseDown;
            selector.MouseUp -= HandleSelectMouseUp;

            if (Equals(e.NewValue, true))
            {
                selector.PreviewMouseDown += HandleSelectPreviewMouseDown;
                selector.MouseUp += HandleSelectMouseUp;
            }
        }
    }

    private static void HandleSelectMouseUp(object sender, MouseButtonEventArgs e)
    {
        var selector = (Selector)sender;

        if (e.ChangedButton == MouseButton.Left && e.OriginalSource is Visual source)
        {
            var container = selector.ContainerFromElement(source);
            if (container != null)
            {
                var index = selector.ItemContainerGenerator.IndexFromContainer(container);
                if (index >= 0)
                {
                    selector.SelectedIndex = index;
                }
            }
        }
    }

    private static void HandleSelectPreviewMouseDown(object sender, MouseButtonEventArgs e)
    {
        e.Handled = e.ChangedButton == MouseButton.Left;
    }

    #endregion

}
</code>```

Now you can apply this to any ListBox (or Selector-derived class), e.g.

```<code><ListBox ItemsSource="{Binding ViewModelItems}"
    SelectedItem="{Binding SelectedViewModelItem}"
    ui:SelectorBehavior.ShouldSelectItemOnMouseUp="True" />
</code>```

Body:
I had never noticed this before, but the WPF ListBox seems to change its SelectedItem when the  Mouse is down, but has not yet been released. As a quick example, just create a simple ListBox with several ListBoxItems, like so:

<ListBox>
  <ListBoxItem>Hello</ListBoxItem>
  <ListBoxItem>World</ListBoxItem>
  <ListBoxItem>ListBox</ListBoxItem>
  <ListBoxItem>Test</ListBoxItem>
</ListBox>

fire up your application, press the mouse button (don't release it!) and move the mouse around. The SelectedItem will change as the mouse moves. This illustrates the larger problem (for me, at least), that a ListBox's SelectedItem will be set as soon as you mouse down, not when mouse up occurs. Usually that isn't a problem, but in my case I'd like to enable drag & drop on the items in my ListBox, without the items explicitly becoming selected.

I imagine my only recourse is to build a custom ItemsControl or Selector with selection-style semantics similar to ListBox, so really my question is more, why does ListBox work this way? Does anyone have any insight into this?

Body:
I personally prefer MVVM and attached properties to tweak the behavior of elements.

Furthermore the solution proposed by Tomas Kosar doesn't seem to work when the ItemsSource property is bound.

Here's what I currently use (C# 7 syntax)

public static class SelectorBehavior
{
    #region bool ShouldSelectItemOnMouseUp

    public static readonly DependencyProperty ShouldSelectItemOnMouseUpProperty =
        DependencyProperty.RegisterAttached(
            "ShouldSelectItemOnMouseUp", typeof(bool), typeof(SelectorBehavior),
            new PropertyMetadata(default(bool), HandleShouldSelectItemOnMouseUpChange));

    public static void SetShouldSelectItemOnMouseUp(DependencyObject element, bool value)
    {
        element.SetValue(ShouldSelectItemOnMouseUpProperty, value);
    }

    public static bool GetShouldSelectItemOnMouseUp(DependencyObject element)
    {
        return (bool)element.GetValue(ShouldSelectItemOnMouseUpProperty);
    }

    private static void HandleShouldSelectItemOnMouseUpChange(
        DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        if (d is Selector selector)
        {
            selector.PreviewMouseDown -= HandleSelectPreviewMouseDown;
            selector.MouseUp -= HandleSelectMouseUp;

            if (Equals(e.NewValue, true))
            {
                selector.PreviewMouseDown += HandleSelectPreviewMouseDown;
                selector.MouseUp += HandleSelectMouseUp;
            }
        }
    }

    private static void HandleSelectMouseUp(object sender, MouseButtonEventArgs e)
    {
        var selector = (Selector)sender;

        if (e.ChangedButton == MouseButton.Left && e.OriginalSource is Visual source)
        {
            var container = selector.ContainerFromElement(source);
            if (container != null)
            {
                var index = selector.ItemContainerGenerator.IndexFromContainer(container);
                if (index >= 0)
                {
                    selector.SelectedIndex = index;
                }
            }
        }
    }

    private static void HandleSelectPreviewMouseDown(object sender, MouseButtonEventArgs e)
    {
        e.Handled = e.ChangedButton == MouseButton.Left;
    }

    #endregion

}

Now you can apply this to any ListBox (or Selector-derived class), e.g.

<ListBox ItemsSource="{Binding ViewModelItems}"
    SelectedItem="{Binding SelectedViewModelItem}"
    ui:SelectorBehavior.ShouldSelectItemOnMouseUp="True" />


答:
You may only access other keys next to the letters and numbers when handling the KeyDown event instead of KeyPressed.
Then you may utilize the Keys enum.

```<code>private void Mainform_KeyDown(object sender, KeyEventArgs e)
{
    switch (e.KeyCode)
    {
        case Keys.Right:
            e.Handled = true;
            e.Suppressed = true;
            NextMenuItem_Click(sender, EventArgs.Empty);
            break;
    }
}
</code>```

Title: How to use Navigation Keys as Input in Windows Forms

Body:
You may only access other keys next to the letters and numbers when handling the KeyDown event instead of KeyPressed.
Then you may utilize the Keys enum.

private void Mainform_KeyDown(object sender, KeyEventArgs e)
{
    switch (e.KeyCode)
    {
        case Keys.Right:
            e.Handled = true;
            e.Suppressed = true;
            NextMenuItem_Click(sender, EventArgs.Empty);
            break;
    }
}