问:
javascript or jquery keyboard event
i want to control the next and previous buttons also by clicking the keybord left and right buttons (37 and 39).

i tried by writing a javascript code to do it but it worked only for the first and second tab.

here is the full code without css

```<code><?php

      $nexticon = '<span style="font-size: 28px;"><i class="fi-arrow-right"></i></span>';
      $previousicon = '<span style="font-size: 28px;"><i class="fi-arrow-left"></i></span>';

     ?>

<div style="position: absolute; z-index: 7;">

     <!-- multistep form -->
<form id="msform" method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" autocomplete="off">

<!-- fieldsets -->
<fieldset>

 bla bla bla page 1

     <button class="next action-button-next" type="button" style=" position: absolute; top: 990px; left:380px; background-color: Transparent; background-repeat:no-repeat; border: none; cursor:pointer; overflow: hidden; outline:none; "> <?php echo $nexticon ?></i></button>

     </fieldset>

<fieldset>

    <form name="change">

 bla bla bla page 2

     <button class="previous action-button-previous" type="button" style=" position: absolute; top: 990px; left:135px; background-color: Transparent; background-repeat:no-repeat; border: none; cursor:pointer; overflow: hidden; outline:none; "> <?php echo $previousicon ?></button>
     <button class="next action-button-next" type="button" style=" position: absolute; top: 990px; left:380px; background-color: Transparent; background-repeat:no-repeat; border: none; cursor:pointer; overflow: hidden; outline:none; "> <?php echo $nexticon ?></button>
</fieldset>

<fieldset>

   bla bla bla page 3

     <button class="previous action-button-previous" type="button" style=" position: absolute; top: 990px; left:135px; background-color: Transparent; background-repeat:no-repeat; border: none; cursor:pointer; overflow: hidden; outline:none; "> <?php echo $previousicon ?></button>
     <button class="next action-button-next" type="button" style=" position: absolute; top: 990px; left:380px; background-color: Transparent; background-repeat:no-repeat; border: none; cursor:pointer; overflow: hidden; outline:none; "> <?php echo $nexticon ?></i></button>
</fieldset>

<fieldset>

    bla bla bla page 4

     <button class="previous action-button-previous" type="button" style=" position: absolute; top: 990px; left:135px; background-color: Transparent; background-repeat:no-repeat; border: none; cursor:pointer; overflow: hidden; outline:none; "> <?php echo $previousicon ?></button>
     <button class="next action-button-next" type="button" style=" position: absolute; top: 990px; left:380px; background-color: Transparent; background-repeat:no-repeat; border: none; cursor:pointer; overflow: hidden; outline:none; "> <?php echo $nexticon ?></i></button>
</fieldset>

<fieldset>

   bla bla bla page 5

     <button class="previous action-button-previous" type="button" style=" position: absolute; top: 990px; left:135px; background-color: Transparent; background-repeat:no-repeat; border: none; cursor:pointer; overflow: hidden; outline:none; "> <?php echo $previousicon ?></button>
     <button class="next action-button-next" type="button" style=" position: absolute; top: 990px; left:380px; background-color: Transparent; background-repeat:no-repeat; border: none; cursor:pointer; overflow: hidden; outline:none; "> <?php echo $nexticon ?></i></button>
</fieldset>

<fieldset>

    bla bla bla page 6

     <button class="previous action-button-previous" type="button" style=" position: absolute; top: 990px; left:135px; background-color: Transparent; background-repeat:no-repeat; border: none; cursor:pointer; overflow: hidden; outline:none; "> <?php echo $previousicon ?></button>
     <button class="next action-button-next" type="button" style=" position: absolute; top: 990px; left:380px; background-color: Transparent; background-repeat:no-repeat; border: none; cursor:pointer; overflow: hidden; outline:none; "> <?php echo $nexticon ?></i></button>
</fieldset>

<fieldset>

   bla bla bla page 7

     <button class="previous action-button-previous" type="button" style=" position: absolute; top: 990px; left:135px; background-color: Transparent; background-repeat:no-repeat; border: none; cursor:pointer; overflow: hidden; outline:none; "> <?php echo $previousicon ?></button>

</fieldset>
     <!-- progressbar -->
<ul id="progressbar">
<li class="active">1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>6</li>
<li>7</li>
</ul>
     </form>

<!-- jQuery easing plugin -->
        <script src="js/jquery.easing.min.js" type="text/javascript"></script>
        <script>
        $(function() {

        //jQuery time
        var current_fs, next_fs, previous_fs; //fieldsets
        var left, opacity, scale; //fieldset properties which we will animate
        var animating; //flag to prevent quick multi-click glitches

        $(".next").click(function(){
                if(animating) return false;
                animating = true;

                current_fs = $(this).parent();
                next_fs = $(this).parent().next();

                //activate next step on progressbar using the index of next_fs
                $("#progressbar li").eq($("fieldset").index(next_fs)).addClass("active");

                //show the next fieldset
                next_fs.show();
                //hide the current fieldset with style
                current_fs.animate({opacity: 0}, {
                        step: function(now, mx) {
                                //as the opacity of current_fs reduces to 0 - stored in "now"
                                //1. scale current_fs down to 80%
                                scale = 1 - (1 - now) * 0.2;
                                //2. bring next_fs from the right(50%)
                                left = (now * 50)+"%";
                                //3. increase opacity of next_fs to 1 as it moves in
                                opacity = 1 - now;
                                current_fs.css({'transform': 'scale('+scale+')'});
                                next_fs.css({'left': left, 'opacity': opacity});
                        },
                        duration: 800,
                        complete: function(){
                                current_fs.hide();
                                animating = false;
                        },
                        //this comes from the custom easing plugin
                        easing: 'easeInOutBack'
                });
        });

        $(".previous").click(function(){
                if(animating) return false;
                animating = true;

                current_fs = $(this).parent();
                previous_fs = $(this).parent().prev();

                //de-activate current step on progressbar
                $("#progressbar li").eq($("fieldset").index(current_fs)).removeClass("active");

                //show the previous fieldset
                previous_fs.show();
                //hide the current fieldset with style
                current_fs.animate({opacity: 0}, {
                        step: function(now, mx) {
                                //as the opacity of current_fs reduces to 0 - stored in "now"
                                //1. scale previous_fs from 80% to 100%
                                scale = 0.8 + (1 - now) * 0.2;
                                //2. take current_fs to the right(50%) - from 0%
                                left = ((1-now) * 50)+"%";
                                //3. increase opacity of previous_fs to 1 as it moves in
                                opacity = 1 - now;
                                current_fs.css({'left': left});
                                previous_fs.css({'transform': 'scale('+scale+')', 'opacity': opacity});
                        },
                        duration: 800,
                        complete: function(){
                                current_fs.hide();
                                animating = false;
                        },
                        //this comes from the custom easing plugin
                        easing: 'easeInOutBack'
                });
        });

        });
        </script>
</code>```

答:
Where do you place your handlers? I can't guess your perferred approach.

This is what would I do:

Since binding with individual instance may force the user focusing those fieldset containers, I would register a global event handler with the document. By checking the visibility of the current visible fieldset and its child nav buttons, it is able to perform corresponding action of showing your animation.

```<code>$(function() {
  $('#ctnFieldSets div').each(function( index ) {
    var fs = $(this);

    // hide buttons
    if (!fs.prev('div').length) fs.find('button.prev').hide();
    if (!fs.next('div').length) fs.find('button.next').hide();

    // hide pages
    if (index > 0) fs.hide();
  });

  // register handlers for buttons
  $('#ctnFieldSets div button.prev, #ctnFieldSets div button.next').bind({
    click: function(e) {
      var btn = $(this);
      var fs = $(btn.parent('div')[0]);

      fs.hide();
      if (btn.is('.prev')) {
        // animation here //
        $(fs.prev('div')[0]).show();
        return;
      }

      if (btn.is('.next')) {
        // animation here //
        $(fs.next('div')[0]).show();
        return;
      }
    }
  });

  // register global event handler for keydown. you may bind to other objects if
  // you don't want to be global event handler

  $(document).bind({
    keydown: function(e) {
      // you should check targets here. skips when target could input text
      if ($(e.target).is('input,textarea')) return;

      var fs = null;

      switch(e.keyCode) {
        case 37:
          fs = $($('#ctnFieldSets div:visible').first()[0]);
          if (!fs.find('button.prev:visible').length) return;

          // animation here //
          fs.hide();
          $(fs.prev('div')[0]).show();
          break;

        case 39:
          fs = $($('#ctnFieldSets div:visible').first()[0]);
          if (!fs.find('button.next:visible').length) return;

          // animation here //
          fs.hide();
          $(fs.next('div')[0]).show();
          break;

        default:
          return;
      }
    }
  });
});

<div id="ctnFieldSets">
  <div><button class='prev'>Prev</button>Div1<input><button class='next'>Next</button></div>
  <div><button class='prev'>Prev</button>Div2<input><button class='next'>Next</button></div>
  <div><button class='prev'>Prev</button>Div3<input><button class='next'>Next</button></div>
</div>
</code>```

Title: javascript or jquery keyboard event

Body:
i want to control the next and previous buttons also by clicking the keybord left and right buttons (37 and 39).

i tried by writing a javascript code to do it but it worked only for the first and second tab.

here is the full code without css

<?php

      $nexticon = '';
      $previousicon = '';

     ?>

<form id="msform" method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" autocomplete="off">

<fieldset>

 bla bla bla page 1

     <button class="next action-button-next" type="button" style=" position: absolute; top: 990px; left:380px; background-color: Transparent; background-repeat:no-repeat; border: none; cursor:pointer; overflow: hidden; outline:none; "> <?php echo $nexticon ?></button>

     </fieldset>

<fieldset>

    <form name="change">

 bla bla bla page 2

     <button class="previous action-button-previous" type="button" style=" position: absolute; top: 990px; left:135px; background-color: Transparent; background-repeat:no-repeat; border: none; cursor:pointer; overflow: hidden; outline:none; "> <?php echo $previousicon ?></button>
     <button class="next action-button-next" type="button" style=" position: absolute; top: 990px; left:380px; background-color: Transparent; background-repeat:no-repeat; border: none; cursor:pointer; overflow: hidden; outline:none; "> <?php echo $nexticon ?></button>
</fieldset>

<fieldset>

   bla bla bla page 3

     <button class="previous action-button-previous" type="button" style=" position: absolute; top: 990px; left:135px; background-color: Transparent; background-repeat:no-repeat; border: none; cursor:pointer; overflow: hidden; outline:none; "> <?php echo $previousicon ?></button>
     <button class="next action-button-next" type="button" style=" position: absolute; top: 990px; left:380px; background-color: Transparent; background-repeat:no-repeat; border: none; cursor:pointer; overflow: hidden; outline:none; "> <?php echo $nexticon ?></button>
</fieldset>

<fieldset>

    bla bla bla page 4

     <button class="previous action-button-previous" type="button" style=" position: absolute; top: 990px; left:135px; background-color: Transparent; background-repeat:no-repeat; border: none; cursor:pointer; overflow: hidden; outline:none; "> <?php echo $previousicon ?></button>
     <button class="next action-button-next" type="button" style=" position: absolute; top: 990px; left:380px; background-color: Transparent; background-repeat:no-repeat; border: none; cursor:pointer; overflow: hidden; outline:none; "> <?php echo $nexticon ?></button>
</fieldset>

<fieldset>

   bla bla bla page 5

     <button class="previous action-button-previous" type="button" style=" position: absolute; top: 990px; left:135px; background-color: Transparent; background-repeat:no-repeat; border: none; cursor:pointer; overflow: hidden; outline:none; "> <?php echo $previousicon ?></button>
     <button class="next action-button-next" type="button" style=" position: absolute; top: 990px; left:380px; background-color: Transparent; background-repeat:no-repeat; border: none; cursor:pointer; overflow: hidden; outline:none; "> <?php echo $nexticon ?></button>
</fieldset>

<fieldset>

    bla bla bla page 6

     <button class="previous action-button-previous" type="button" style=" position: absolute; top: 990px; left:135px; background-color: Transparent; background-repeat:no-repeat; border: none; cursor:pointer; overflow: hidden; outline:none; "> <?php echo $previousicon ?></button>
     <button class="next action-button-next" type="button" style=" position: absolute; top: 990px; left:380px; background-color: Transparent; background-repeat:no-repeat; border: none; cursor:pointer; overflow: hidden; outline:none; "> <?php echo $nexticon ?></button>
</fieldset>

<fieldset>

   bla bla bla page 7

     <button class="previous action-button-previous" type="button" style=" position: absolute; top: 990px; left:135px; background-color: Transparent; background-repeat:no-repeat; border: none; cursor:pointer; overflow: hidden; outline:none; "> <?php echo $previousicon ?></button>

</fieldset>

1

2

3

4

5

6

7

     </form>

Body:
Where do you place your handlers? I can't guess your perferred approach.

This is what would I do:

Since binding with individual instance may force the user focusing those fieldset containers, I would register a global event handler with the document. By checking the visibility of the current visible fieldset and its child nav buttons, it is able to perform corresponding action of showing your animation.

$(function() {
  $('#ctnFieldSets div').each(function( index ) {
    var fs = $(this);

    // hide buttons
    if (!fs.prev('div').length) fs.find('button.prev').hide();
    if (!fs.next('div').length) fs.find('button.next').hide();

    // hide pages
    if (index > 0) fs.hide();
  });

  // register handlers for buttons
  $('#ctnFieldSets div button.prev, #ctnFieldSets div button.next').bind({
    click: function(e) {
      var btn = $(this);
      var fs = $(btn.parent('div')[0]);

      fs.hide();
      if (btn.is('.prev')) {
        // animation here //
        $(fs.prev('div')[0]).show();
        return;
      }

      if (btn.is('.next')) {
        // animation here //
        $(fs.next('div')[0]).show();
        return;
      }
    }
  });

  // register global event handler for keydown. you may bind to other objects if
  // you don't want to be global event handler

  $(document).bind({
    keydown: function(e) {
      // you should check targets here. skips when target could input text
      if ($(e.target).is('input,textarea')) return;

      var fs = null;

      switch(e.keyCode) {
        case 37:
          fs = $($('#ctnFieldSets div:visible').first()[0]);
          if (!fs.find('button.prev:visible').length) return;

          // animation here //
          fs.hide();
          $(fs.prev('div')[0]).show();
          break;

        case 39:
          fs = $($('#ctnFieldSets div:visible').first()[0]);
          if (!fs.find('button.next:visible').length) return;

          // animation here //
          fs.hide();
          $(fs.next('div')[0]).show();
          break;

        default:
          return;
      }
    }
  });
});

<div id="ctnFieldSets">
  <div><button class='prev'>Prev</button>Div1<input><button class='next'>Next</button></div>
  <div><button class='prev'>Prev</button>Div2<input><button class='next'>Next</button></div>
  <div><button class='prev'>Prev</button>Div3<input><button class='next'>Next</button></div>
</div>


来源: stackexchange

问:
Regex pattern for HH:MM:SS time string
I want to parse a hh:mm:ss string.
A simple one is ([0-1]?\d|2[0-3]):([0-5]?\d):([0-5]?\d)  which expects 2:3:24 or 02:03:24 string.

I want to take it a step further and pass the validation even in cases like

if you enter just 56, it should be pass, as 56 can be considered as 56 secs  [SS]

if you enter 2:3 or 02:03 or 02:3 or 2:03  it should pass. 2 minutes and 3 seconds [MM:SS]

If you enter 20:30:12 pass with 20 hrs, 30 minutes and 12 secs [HH:MM:SS]

if you enter 78:12 , do not pass  78 minutes is wrong....

Basically, if one ":" is found, consider number before ":" as MM and number after ":" as SS
. If two ":" are found consider as HH:MM:SS

I came up with this pattern.

```<code>(^([0-1]?\d|2[0-3]):([0-5]?\d):([0-5]?\d)$)|(^([0-5]?\d):([0-5]?\d)$)|(^[0-5]?\d$)
</code>```

It seems to be working fine. I wanted to know any other simpler regular expression, that can do the job.

答:
@Tim Pietzcker covers the OP's requirement for a HH:MM:SS parser where SS was mandatory, i.e.

HH:MM:SS

MM:SS

SS

If you permit me to deviate from the OP's requirement for a bit, and consider a case where HH is mandatory, i.e.

HH

HH:MM

HH:MM:SS

The regex I came up with was:

```<code>^([0-1]?\d|2[0-3])(?::([0-5]?\d))?(?::([0-5]?\d))?$
</code>```

Let's break it down:

([0-1]?\d|2[0-3]) - matches for hours

(?::([0-5]?\d))? - optionally matches for minutes

(?::([0-5]?\d))? - optionally matches for seconds

ContentLicense: CC BY-SA 3.0

Title: Regex pattern for HH:MM:SS time string

Body:
I want to parse a hh:mm:ss string.
A simple one is ([0-1]?\d|2[0-3]):([0-5]?\d):([0-5]?\d)  which expects 2:3:24 or 02:03:24 string.

I want to take it a step further and pass the validation even in cases like

if you enter just 56, it should be pass, as 56 can be considered as 56 secs  [SS]

if you enter 2:3 or 02:03 or 02:3 or 2:03  it should pass. 2 minutes and 3 seconds [MM:SS]

If you enter 20:30:12 pass with 20 hrs, 30 minutes and 12 secs [HH:MM:SS]

if you enter 78:12 , do not pass  78 minutes is wrong....

Basically, if one ":" is found, consider number before ":" as MM and number after ":" as SS
. If two ":" are found consider as HH:MM:SS

I came up with this pattern.

(^([0-1]?\d|2[0-3]):([0-5]?\d):([0-5]?\d)$)|(^([0-5]?\d):([0-5]?\d)$)|(^[0-5]?\d$)

It seems to be working fine. I wanted to know any other simpler regular expression, that can do the job.

Body:
@Tim Pietzcker covers the OP's requirement for a HH:MM:SS parser where SS was mandatory, i.e.

HH:MM:SS

MM:SS

SS

If you permit me to deviate from the OP's requirement for a bit, and consider a case where HH is mandatory, i.e.

HH

HH:MM

HH:MM:SS

The regex I came up with was:

^([0-1]?\d|2[0-3])(?::([0-5]?\d))?(?::([0-5]?\d))?$

Let's break it down:

([0-1]?\d|2[0-3]) - matches for hours

(?::([0-5]?\d))? - optionally matches for minutes

(?::([0-5]?\d))? - optionally matches for seconds


问:
Hierarchical select module issue in drupal
i am using 'Hierarchical select' module in Drupal to create 2 drop down of States and cities and connecting the city ones to state in a way by changing the state,the list of cities changes too.(it is beside of CCK and taxonomy content module)

The problem is that by selecting the state and city for a new content,just the city shown.but i need both of them,State - city combination.

答: If you have all that data inside of one vocabulary and cities are children of states, once you select a city, it should display State >> City on the node. if you're displaying them with $terms; then it should display in such fashion.

ContentLicense: CC BY-SA 2.5


问:
Trying to list a JSON value using Javascript to my website
I have a rather large JSON file which contains rating, comments etc for different movies. The syntax is like this:

```<code>reviews_object={"2396": {"xyz001": {"reg_date": null, "object": 2396, "rating": 3, "mod_date": "2008-11-17", "comment": "", "username": "xyz001"}}, "1107": {"xyz001": {"reg_date": null, "object": 1107, "rating": 4, "mod_date": "2006-11-26", "comment": "", "username": "xyz001"}
</code>```

Javascript code

```<code>var ratingList = document.querySelector("rating");

function averageRating () {
var reviews = reviews_object;
var reviewList = []; // Array of reviews

for (var i in reviews) {
    reviewList.push(reviews[i])
    console.log(reviewList);
}
</code>```

}

```<code>function displayRating (reviewList) {
for (var i = 0; i < reviewList.length; i++) {
    var li = document.createElement("li")
    li.innerHTML = reviewList[i].rating;
    rating.appendChild(li);

}
</code>```

}

Obviously it doesn't work and I am kinda stuck about what do to next. This JSON file is only for ratings and comments, and I also have one which is about the movie itself (title, length etc). Both the JSON objects has the object ID as you can see in the JSON code i posted.
What I want to do is to parse through the JSON rating object and list out specifically the rating key and its value to its corresponding object ID from the other JSON file.

Probably a bad explanation of what I want do to, but ask if you wanna know more

答:
Some observations :

After pushing the reviews[i] into reviewList array. The reviewList array will be looking like this.

Hence, when you will try to access reviewList[i].rating in displayRating function it will return you undefined as reviewList[i].rating is not defined as per the reviewList structure.

You have to modify your code :

```<code>function displayRating(reviewList) {
    for (var i = 0; i < reviewList.length; i++) {
        console.log(reviewList[i].xyz001.rating);
    }
}
</code>```

Body:
I have a rather large JSON file which contains rating, comments etc for different movies. The syntax is like this:

reviews_object={"2396": {"xyz001": {"reg_date": null, "object": 2396, "rating": 3, "mod_date": "2008-11-17", "comment": "", "username": "xyz001"}}, "1107": {"xyz001": {"reg_date": null, "object": 1107, "rating": 4, "mod_date": "2006-11-26", "comment": "", "username": "xyz001"}

Javascript code

var ratingList = document.querySelector("rating");

function averageRating () {
var reviews = reviews_object;
var reviewList = []; // Array of reviews

for (var i in reviews) {
    reviewList.push(reviews[i])
    console.log(reviewList);
}

}

function displayRating (reviewList) {
for (var i = 0; i < reviewList.length; i++) {
    var li = document.createElement("li")
    li.innerHTML = reviewList[i].rating;
    rating.appendChild(li);

}

}

Obviously it doesn't work and I am kinda stuck about what do to next. This JSON file is only for ratings and comments, and I also have one which is about the movie itself (title, length etc). Both the JSON objects has the object ID as you can see in the JSON code i posted.
What I want to do is to parse through the JSON rating object and list out specifically the rating key and its value to its corresponding object ID from the other JSON file.

Probably a bad explanation of what I want do to, but ask if you wanna know more

Body:
Some observations :

After pushing the reviews[i] into reviewList array. The reviewList array will be looking like this.

Hence, when you will try to access reviewList[i].rating in displayRating function it will return you undefined as reviewList[i].rating is not defined as per the reviewList structure.

You have to modify your code :

function displayRating(reviewList) {
    for (var i = 0; i < reviewList.length; i++) {
        console.log(reviewList[i].xyz001.rating);
    }
}


问:
How to check the users currently using a powershell program?
So I have a basic program (incredibly buggy but we quite like it) that uses a shared folder that a couple of people at school have access to (Paths have been changed for ease of use). It is designed to work as a messaging application, with each user writing into the same Notepad file to send a message to a Poweshell script using the Get-Content and -Wait parameter. I have added a couple of commands using "/", but I want one (i.e. /online) that a user can type and see all of the other people currently using the program.

I have tried to set up a different text file that is updated every x seconds by each individual user with their own user name, while wiping the previous record:

```<code>while (1){
    Clear-Content -Path C:\users\Freddie\Desktop\ConvoOnline.txt
    Start-Sleep -Milliseconds 5000
    Add-Content -Path C:\users\Freddie\Desktop\ConvoOnline.txt $env:UserName
}
</code>```

So this can be called upon later:

```<code>elseif($_ -match "/online"){Get-Content -Path C:\users\Freddie\Desktop\ConvoOnline.txt}
</code>```

But this doesn't work, it won't sync up between users, so one user will wipe the current users and only that will apear as active, until the other users' cycle wipes THEIR name.

To avoid the XY Problem, I want a fairly simple way (still only using two files maximum) to determine which users are actively using (therefore updating) the Powershell script they are running.

Whole code:

```<code>Add-Type -AssemblyName System.speech
$speak = New-Object System.Speech.Synthesis.SpeechSynthesizer
$speak.Volume = 100
Write-Host "Type /helpp, save it, then hit backspace and save it again     for a guide and list of commands!"
Get-Content -Path C:\users\Freddie\Desktop\Convo.txt -Wait |
 %{$_ -replace "^", "$env:UserName  "} |
 %{if($_ -match "/cls"){cls} `
 elseif($_ -match "/online"){Get-Content -Path C:\users\Freddie\Desktop    \ConvoOnline.txt} `
 elseif(($_ -match "/afk") -and ($env:UserName -eq "Freddie")){Write-Host     "$env:UserName has gone afk"} `
 elseif(($_ -match "/say") -and ($env:UserName -eq "Freddie"))    {$speak.Speak($_.Substring(($_.length)-10))} `
elseif($_ -match "/whisper"){
 $array = @($_ -split "\s+")
 if($array[2] -eq "$env:UserName"){
 Write-Host $array[2]
 } `
 } `
 elseif($_ -match "/help"){
 Write-Host "Help: `
 1. Press Ctrl+S in Notepad to send your message `
 2. Make sure you delete it after it's been sent `
 3. If your message doesn't send properly, just hit backspace and all but     the last letter will be sent `
  `
 COMMANDS: `
  `
 /online - Lists all users currently in the chat `
 /cls - Clears you screen of all current and previous messages `
 /whisper [USERNAME] [MESSAGE] - This allows you to send a message     privately to a user"
 }
 else{Write-Host "$_"}}
#
#
#
#
#Add a command: elseif($_ -match "/[COMMAND]"){[FUNCTION]}
#
#Make it user-specific: elseif($_ -match "/[COMMAND]" -and $envUserName     -eq "[USERNAME]"){[FUNCTION]}
</code>```

答:
You can add time stamp with add-content and another ps1 file for clearing data written before 5 seconds (you can do this in the same ps1 file but another ps1 file is better)

Modified user online updation part :

```<code>while ($true){

    Add-Content -Path d:\ConvoOnline.txt "$($env:UserName);$(get-date)"
    Start-Sleep -Milliseconds 5000

}
</code>```

Another script which watches and clears content before 5 seconds ,so the online file is always updated

```<code> while($true){
    Start-Sleep -Milliseconds 5000
    $data = get-content -Path D:\ConvoOnline.txt
    clear-content -Path D:\ConvoOnline.txt
    if($data){
    $data | %{if(!([datetime]($_.split(";")[1]) -lt (get-date).addmilliseconds(-4500))){Add-Content -Path d:\ConvoOnline.txt $_}}
    }
    }
</code>```

Body:
So I have a basic program (incredibly buggy but we quite like it) that uses a shared folder that a couple of people at school have access to (Paths have been changed for ease of use). It is designed to work as a messaging application, with each user writing into the same Notepad file to send a message to a Poweshell script using the Get-Content and -Wait parameter. I have added a couple of commands using "/", but I want one (i.e. /online) that a user can type and see all of the other people currently using the program.

I have tried to set up a different text file that is updated every x seconds by each individual user with their own user name, while wiping the previous record:

while (1){
    Clear-Content -Path C:\users\Freddie\Desktop\ConvoOnline.txt
    Start-Sleep -Milliseconds 5000
    Add-Content -Path C:\users\Freddie\Desktop\ConvoOnline.txt $env:UserName
}

So this can be called upon later:

elseif($_ -match "/online"){Get-Content -Path C:\users\Freddie\Desktop\ConvoOnline.txt}

But this doesn't work, it won't sync up between users, so one user will wipe the current users and only that will apear as active, until the other users' cycle wipes THEIR name.

To avoid the XY Problem, I want a fairly simple way (still only using two files maximum) to determine which users are actively using (therefore updating) the Powershell script they are running.

Whole code:

Add-Type -AssemblyName System.speech
$speak = New-Object System.Speech.Synthesis.SpeechSynthesizer
$speak.Volume = 100
Write-Host "Type /helpp, save it, then hit backspace and save it again     for a guide and list of commands!"
Get-Content -Path C:\users\Freddie\Desktop\Convo.txt -Wait |
 %{$_ -replace "^", "$env:UserName  "} |
 %{if($_ -match "/cls"){cls} `
 elseif($_ -match "/online"){Get-Content -Path C:\users\Freddie\Desktop    \ConvoOnline.txt} `
 elseif(($_ -match "/afk") -and ($env:UserName -eq "Freddie")){Write-Host     "$env:UserName has gone afk"} `
 elseif(($_ -match "/say") -and ($env:UserName -eq "Freddie"))    {$speak.Speak($_.Substring(($_.length)-10))} `
elseif($_ -match "/whisper"){
 $array = @($_ -split "\s+")
 if($array[2] -eq "$env:UserName"){
 Write-Host $array[2]
 } `
 } `
 elseif($_ -match "/help"){
 Write-Host "Help: `
 1. Press Ctrl+S in Notepad to send your message `
 2. Make sure you delete it after it's been sent `
 3. If your message doesn't send properly, just hit backspace and all but     the last letter will be sent `
  `
 COMMANDS: `
  `
 /online - Lists all users currently in the chat `
 /cls - Clears you screen of all current and previous messages `
 /whisper [USERNAME] [MESSAGE] - This allows you to send a message     privately to a user"
 }
 else{Write-Host "$_"}}
#
#
#
#
#Add a command: elseif($_ -match "/[COMMAND]"){[FUNCTION]}
#
#Make it user-specific: elseif($_ -match "/[COMMAND]" -and $envUserName     -eq "[USERNAME]"){[FUNCTION]}

Body:
You can add time stamp with add-content and another ps1 file for clearing data written before 5 seconds (you can do this in the same ps1 file but another ps1 file is better)

Modified user online updation part :

while ($true){

    Add-Content -Path d:\ConvoOnline.txt "$($env:UserName);$(get-date)"
    Start-Sleep -Milliseconds 5000

}

Another script which watches and clears content before 5 seconds ,so the online file is always updated

 while($true){
    Start-Sleep -Milliseconds 5000
    $data = get-content -Path D:\ConvoOnline.txt
    clear-content -Path D:\ConvoOnline.txt
    if($data){
    $data | %{if(!([datetime]($_.split(";")[1]) -lt (get-date).addmilliseconds(-4500))){Add-Content -Path d:\ConvoOnline.txt $_}}
    }
    }


问:
ValueError: The shape of the input to "Flatten" is not fully defined (got (0, 3, 16)
When run the following model:

```<code>l0 = Input(shape=(1, height, width), name='l0')

l1 = Convolution2D(9, 5, 5, border_mode='same', activation='relu', name='l1')(l0)
l1_mp = MaxPooling2D(pool_size=(2, 2), name='l1_mp')(l1)

l2 = Convolution2D(9, 5, 5, border_mode='same', activation='relu', name='l2')(l1_mp)
l2_mp = MaxPooling2D(pool_size=(2, 2), name='l2_mp')(l2)

l3 = Convolution2D(16, 3, 3, border_mode='same', activation='relu', name='l3')(l2_mp)
l3_mp = MaxPooling2D(pool_size=(2, 2), name='l3_mp')(l3)

flat = Flatten(name='flat')(l3_mp)

l4 = Dense(25, activation='relu', name='l4')(flat)

l5 = Dense(n_classes, activation='softmax', name='l5')(l4)

model = Model(input=l0, output=l5)
model.summary()
</code>```

I get the following error:

/home/imad/anaconda2/lib/python2.7/site-packages/keras/legacy/interfaces.py:86: UserWarning: Update your Conv2D call to the Keras 2 API: Conv2D(9, (5, 5), padding="same", activation="relu", name="l1")
    '` call to the Keras 2 API: ' + signature)

Please help.

答:
With Keras 2.0 There are interfaces changes.
Please have a look at the below link for more details

https://github.com/fchollet/keras/wiki/Keras-2.0-release-notes

Body:
When run the following model:

l0 = Input(shape=(1, height, width), name='l0')

l1 = Convolution2D(9, 5, 5, border_mode='same', activation='relu', name='l1')(l0)
l1_mp = MaxPooling2D(pool_size=(2, 2), name='l1_mp')(l1)

l2 = Convolution2D(9, 5, 5, border_mode='same', activation='relu', name='l2')(l1_mp)
l2_mp = MaxPooling2D(pool_size=(2, 2), name='l2_mp')(l2)

l3 = Convolution2D(16, 3, 3, border_mode='same', activation='relu', name='l3')(l2_mp)
l3_mp = MaxPooling2D(pool_size=(2, 2), name='l3_mp')(l3)

flat = Flatten(name='flat')(l3_mp)

l4 = Dense(25, activation='relu', name='l4')(flat)

l5 = Dense(n_classes, activation='softmax', name='l5')(l4)

model = Model(input=l0, output=l5)
model.summary()

I get the following error:

/home/imad/anaconda2/lib/python2.7/site-packages/keras/legacy/interfaces.py:86: UserWarning: Update your Conv2D call to the Keras 2 API: Conv2D(9, (5, 5), padding="same", activation="relu", name="l1")
    '` call to the Keras 2 API: ' + signature)

Please help.


问:
Bitwise Operations to change 2 LSB
Suppose I have an list of numbers:

```<code>l = [30, 31, 32, 33]
</code>```

In binary this would the same as

```<code>l = [00011110, 00011111, 00100000, 00100001]
</code>```

Using binary operations I want to set the least 2 significant bits to any random value, but retain the 6 most significant bits. An example of this might be:

```<code>l_new = [00011111, 00011101, 00100010, 00100010]
</code>```

How can I do this, using the numpy library in python?

Title: Bitwise Operations to change 2 LSB

Body:
Suppose I have an list of numbers:

l = [30, 31, 32, 33]

In binary this would the same as

l = [00011110, 00011111, 00100000, 00100001]

Using binary operations I want to set the least 2 significant bits to any random value, but retain the 6 most significant bits. An example of this might be:

l_new = [00011111, 00011101, 00100010, 00100010]

How can I do this, using the numpy library in python?

Body:
You can use numpy.unpackbits

l = np.random.randint(16,size=(10,)).astype(np.uint8)
# [ 9 13  3 10 10]

bits = np.unpackbits(l[:,np.newaxis],axis=1)
# [[0 0 0 0 1 0 0 1]
#  [0 0 0 0 1 1 0 1]
#  [0 0 0 0 0 0 1 1]
#  [0 0 0 0 1 0 1 0]
#  [0 0 0 0 1 0 1 0]]

bits[:,-2:] = np.random.randint(0,2,size=(bits.shape[0],2))
# [[0 0 0 0 1 0 0 1]
#  [0 0 0 0 1 1 0 1]
#  [0 0 0 0 0 0 1 0]
#  [0 0 0 0 1 0 0 1]
#  [0 0 0 0 1 0 0 1]]

np.squeeze(np.packbits(bits,axis=1))
# [ 9 13  2  9  9]


问:
Vue.js - this.data not storing GET response
```<code><!DOCTYPE html>
<html>
<head>
  <title>Welcome to Vue</title>
  <script src="https://unpkg.com/vue/dist/vue.js"></script>
</head>
<body>
  <div id="app">
    <button v-on:click="sendTime">Load</button>
  <div v-for="user in users">
    <p>{{ user.username }}</p>
  </div>
</div>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.js"></script>
  <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
new Vue({
el: '#app',
data: {
  users: [
    { username: "billy" },
    { username: "ryan" }
  ],
},
methods: {
  sendTime : function () {
    axios.get('/api/users')
  .then(function (response) {
    console.log(response.data);
    this.users = response.data;
  })
  .catch(function (error) {
    console.log(error);
  });
  },
}
})
</script>

</body>
</html>
</code>```

console.log returns -

Array [ Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, 15 more… ]

For some reason I can't seem to get this Array to assign to 'this.data'? When ever the button is clicked the only change is a new console.log, but the two default users in data are displayed. Any help would be greatly appreciated!

答:
You can maintain a reference to the Vue object, then use that reference within the callback.</p>

```<code>methods: {
  sendTime : function () {
    var self = this;
    axios.get('/api/users')
  .then(function (response) {
    console.log(response.data);
    self.users = response.data;
  })
  .catch(function (error) {
    console.log(error);
  });
  },
}
</code>```

Body:
<!DOCTYPE html>

  <title>Welcome to Vue</title>

    <button v-on:click="sendTime">Load</button>

{{ user.username }}

console.log returns -

Array [ Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, 15 more… ]

For some reason I can't seem to get this Array to assign to 'this.data'? When ever the button is clicked the only change is a new console.log, but the two default users in data are displayed. Any help would be greatly appreciated!

Body:
You can maintain a reference to the Vue object, then use that reference within the callback.

methods: {
  sendTime : function () {
    var self = this;
    axios.get('/api/users')
  .then(function (response) {
    console.log(response.data);
    self.users = response.data;
  })
  .catch(function (error) {
    console.log(error);
  });
  },
}


问:
Select Top 1 In SQL Server
Please help me in select top 1

The data like this

```<code>Code    Amp      Price
-----------------------
00001   10       1000
00002   75-100   1500
00003   50-60    1200
00004   15       1100
</code>```

Note : datatype for column Amp is VarChar

I want to select with Amp 75 and I want get the price is 1500

So I use this statement:

```<code>SELECT TOP 1 *
FROM Cable
WHERE (Amp <= '75')
ORDER BY Amp DESC
</code>```

but the result price I get is 1200 is record with code : 00003 (wrong), actually I want the result is code : 00002 and the price is 1500

But if I want to select with Amp 76 the result is true with the syntax :

```<code>SELECT TOP 1 *
FROM Cable
WHERE (Amp <= '75')
ORDER BY Amp DESC
</code>```

What is the true select for my case? Please help me

答:
If you are using SQL Server 2008 and later, try something like this:

```<code>SELECT TOP 1 *
FROM Cable
WHERE isnumeric(left(Amp, 2)) = 1 and cast(left(Amp, 2) as int) <= 75
and Price = 1500
ORDER BY Amp DESC
</code>```

Note: This will work only if you have no records with Amp less than 10.

Title: Select Top 1 In SQL Server

Body:
Please help me in select top 1

The data like this

Code    Amp      Price
-----------------------
00001   10       1000
00002   75-100   1500
00003   50-60    1200
00004   15       1100

Note : datatype for column Amp is VarChar

I want to select with Amp 75 and I want get the price is 1500

So I use this statement:

SELECT TOP 1 *
FROM Cable
WHERE (Amp <= '75')
ORDER BY Amp DESC

but the result price I get is 1200 is record with code : 00003 (wrong), actually I want the result is code : 00002 and the price is 1500

But if I want to select with Amp 76 the result is true with the syntax :

SELECT TOP 1 *
FROM Cable
WHERE (Amp <= '75')
ORDER BY Amp DESC

What is the true select for my case? Please help me

Body:
If you are using SQL Server 2008 and later, try something like this:

SELECT TOP 1 *
FROM Cable
WHERE isnumeric(left(Amp, 2)) = 1 and cast(left(Amp, 2) as int) <= 75
and Price = 1500
ORDER BY Amp DESC

Note: This will work only if you have no records with Amp less than 10.


问:
having trouble with a specific plot using pdf()
I'm trying to create a pdf of a TukeyHSD post hoc test plot (through Sweave, but I've tried pdf(), too, yielding same result). While Document viewer (Ubuntu 10.04) and Acrobat Reader can't display the plot properly, Foxit reader has no problems.
Acrobat Reader displays an error that the image can't be displayed and DV prints this... "thing" (it should have horizontal confidence interval bars and a vertical dotted line).

This happens only for TukeyHSD post hoc test plots, all other figures print just fine (plot prints fine in the R's plotting device). Has anyone experienced this or something similar? What are my other options?

答:
Same thing happens on a Mac. Preview displays it properly but Acrobat Reader has no segments inside a properly drawn box with labels. Attempting to add a col="black argument to the call failed, but you can make the behavior go away by redefining plot.TukeyHSD with col="black" in the segment plotting calls  :</p>

```<code>plot.TukeyHSD2 <- function (x, ...) {
    for (i in seq_along(x)) {
        xi <- x[[i]][, -4, drop = FALSE]
        yvals <- nrow(xi):1
        plot(c(xi[, "lwr"], xi[, "upr"]), rep.int(yvals, 2),
            type = "n", axes = FALSE, xlab = "", ylab = "", ...)
        axis(1, ...)
        axis(2, at = nrow(xi):1, labels = dimnames(xi)[[1L]],
            srt = 0, ...)
        abline(h = yvals, lty = 1, lwd = 1, col = "lightgray")
        abline(v = 0, lty = 2, lwd = 1, ...)
        segments(xi[, "lwr"], yvals, xi[, "upr"], yvals, col="black", ...)
        segments(as.vector(xi), rep.int(yvals - 0.1, 3), as.vector(xi),
            rep.int(yvals + 0.1, 3), col="black", ...)
        title(main = paste(format(100 * attr(x, "conf.level"),
            2), "% family-wise confidence level\n", sep = ""),
            xlab = paste("Differences in mean levels of", names(x)[i]))
        box()
    }
}
</code>```

Body:
Same thing happens on a Mac. Preview displays it properly but Acrobat Reader has no segments inside a properly drawn box with labels. Attempting to add a col="black argument to the call failed, but you can make the behavior go away by redefining plot.TukeyHSD with col="black" in the segment plotting calls  :

plot.TukeyHSD2 <- function (x, ...) {
    for (i in seq_along(x)) {
        xi <- x[[i]][, -4, drop = FALSE]
        yvals <- nrow(xi):1
        plot(c(xi[, "lwr"], xi[, "upr"]), rep.int(yvals, 2),
            type = "n", axes = FALSE, xlab = "", ylab = "", ...)
        axis(1, ...)
        axis(2, at = nrow(xi):1, labels = dimnames(xi)[[1L]],
            srt = 0, ...)
        abline(h = yvals, lty = 1, lwd = 1, col = "lightgray")
        abline(v = 0, lty = 2, lwd = 1, ...)
        segments(xi[, "lwr"], yvals, xi[, "upr"], yvals, col="black", ...)
        segments(as.vector(xi), rep.int(yvals - 0.1, 3), as.vector(xi),
            rep.int(yvals + 0.1, 3), col="black", ...)
        title(main = paste(format(100 * attr(x, "conf.level"),
            2), "% family-wise confidence level\n", sep = ""),
            xlab = paste("Differences in mean levels of", names(x)[i]))
        box()
    }
}


问:
Icon sets showing trend and number in same cell
Know how to customize the icon set conditional formatting in excel?
Basically check for next month & show up down or neutral values??
This has to be done for say next 18 months

Desired output - same cell say A3 should have the number for the month and relevant arrow key (when compared to A2)

or can this be done in VBA??

答:
If you're always comparing to A2, then select the rest of the data, add Arrow Icon set as usual, then modify that conditional formatting:

Conditional Formatting > Manage Rules

Select the Icon Set and click Edit Rule

Then change the conditions to Formulas that compare to A2


问:
How to print all possible balanced parentheses for an expression?
For example, with elements a,b,c,d, there are 5 possible ways to take neighboring elements and reduce them into a single element, where exactly two elements must be combined at a time (below represented by parentheses):

```<code>(((ab)c)d), ((a(bc))d), ((ab)(cd)), (a((bc)d)) and (a(b(cd)))
</code>```

The first example multiplies a*b, then multiplies that product by c, then multiplies that product by d. The second example first multiplies b*c, then multiplies that product by a, then multiplies that product by d.

Any valid parenthesized expression of 2n elements will necessarily have n ( and n ) with the property that, reading from left to right, there are always at least as many ( as ).

I know that for n numbers, the number of ways is the (n-1)th Catalan number. But how does one accurately generate all the resulting groupings?

Thanks

(As an aside: There are over 160 equivalent formulations of this problem, all based on different combinatorial objects enumerated by the Catalan Numbers. For the most up to date list of these, see Richard Stanley's Catalan Addendum.)

答:
The initial left parenthesis has a unique matching right parenthesis such that what is between the two parentheses and what comes after are both valid expressions. This leads to a simple recursive solution here expressed in Scala.

```<code>def catalan(n: Int): List[String] =
    if (n == 0) List("")
    else
        for {
            k <- (0 to n - 1).toList
            first <- catalan(k)
            rest <- catalan(n - 1 - k)
        } yield "a" + first + "b" + rest
</code>```

Here I'm using "a" for left parenthesis and "b" for right parenthesis.

```<code>catalan(0)               List()
catalan(1)               List(ab)
catalan(2)               List(abab, aabb)
catalan(3)               List(ababab, abaabb, aabbab, aababb, aaabbb)
catalan(5).size          42
</code>```

Body:
For example, with elements a,b,c,d, there are 5 possible ways to take neighboring elements and reduce them into a single element, where exactly two elements must be combined at a time (below represented by parentheses):

(((ab)c)d), ((a(bc))d), ((ab)(cd)), (a((bc)d)) and (a(b(cd)))

The first example multiplies a*b, then multiplies that product by c, then multiplies that product by d. The second example first multiplies b*c, then multiplies that product by a, then multiplies that product by d.

Any valid parenthesized expression of 2n elements will necessarily have n ( and n ) with the property that, reading from left to right, there are always at least as many ( as ).

I know that for n numbers, the number of ways is the (n-1)th Catalan number. But how does one accurately generate all the resulting groupings?

Thanks

(As an aside: There are over 160 equivalent formulations of this problem, all based on different combinatorial objects enumerated by the Catalan Numbers. For the most up to date list of these, see Richard Stanley's Catalan Addendum.)

Body:
The initial left parenthesis has a unique matching right parenthesis such that what is between the two parentheses and what comes after are both valid expressions. This leads to a simple recursive solution here expressed in Scala.

def catalan(n: Int): List[String] =
    if (n == 0) List("")
    else
        for {
            k <- (0 to n - 1).toList
            first <- catalan(k)
            rest <- catalan(n - 1 - k)
        } yield "a" + first + "b" + rest

Here I'm using "a" for left parenthesis and "b" for right parenthesis.

catalan(0)               List()
catalan(1)               List(ab)
catalan(2)               List(abab, aabb)
catalan(3)               List(ababab, abaabb, aabbab, aababb, aaabbb)
catalan(5).size          42


问:
failing on unknown properties w/notification
If I disable failure on unknown properties:

new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)

is there a way to be notified when an unknown property is encountered? So that I can output a log message?

答:
Javadoc of DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES says:

Feature that determines whether encountering of unknown properties (ones that do not map to a property, and there is no "any setter" or handler that can handle it) should result in a failure (by throwing a JsonMappingException) or not.

The keyword here is "handler", so looking for handlers, you'll find method DeserializationConfig.withHandler(DeserializationProblemHandler h), and javadoc of DeserializationProblemHandler says:

This is the class that can be registered (via DeserializationConfig object owner by ObjectMapper) to get called when a potentially recoverable problem is encountered during deserialization process. Handlers can try to resolve the problem, throw an exception or do nothing.

In your case, you want to log the problem, then "do nothing".

So, a little research of the javadoc provided an answer to you question.


问:
Append cookies and sending to next request using cookie manager in jmeter
I am doing load test for my application. For login i am getting set-cookie in response headers. Is it possible to append all cookies using cookie manager and sending it in request header for another request</p>

答:
Add HTTP Cookie Manager to your Thread Group, it should handle cookies automatically.

If it doesn't pick up all the cookies, there should be an issue with one or more cookies, i.e. Domain or Path mismatch or expiration date is in the past or whatever. If this is the case and you still want JMeter to consider the invalid cookies you can try adding the next line to user.properties file (located in JMeter's "bin" folder)

```<code>CookieManager.check.cookies=false
</code>```

Given this property set to false JMeter won't check cookies before storing them and you should see "missing" ones, however I would recommend raising a defect against your application as the fact you are not seeing the cookies added by the HTTP Cookie Manager indicates that something is wrong with them

Body:
Add HTTP Cookie Manager to your Thread Group, it should handle cookies automatically.

If it doesn't pick up all the cookies, there should be an issue with one or more cookies, i.e. Domain or Path mismatch or expiration date is in the past or whatever. If this is the case and you still want JMeter to consider the invalid cookies you can try adding the next line to user.properties file (located in JMeter's "bin" folder)

CookieManager.check.cookies=false

Given this property set to false JMeter won't check cookies before storing them and you should see "missing" ones, however I would recommend raising a defect against your application as the fact you are not seeing the cookies added by the HTTP Cookie Manager indicates that something is wrong with them


答:
If you have to work with this existing datatype and table structure then below query may work for you.</p>

```<code>SELECT TOP 1 *
FROM Cable
WHERE (SUBSTRING(Amp,1,IIF((CHARINDEX('-',Amp)-1)>0,(CHARINDEX('-',Amp)-1),0 ) ) <=75)
ORDER BY Amp DESC
</code>```

Title: Select Top 1 In SQL Server

Body:
If you have to work with this existing datatype and table structure then below query may work for you.

SELECT TOP 1 *
FROM Cable
WHERE (SUBSTRING(Amp,1,IIF((CHARINDEX('-',Amp)-1)>0,(CHARINDEX('-',Amp)-1),0 ) ) <=75)
ORDER BY Amp DESC


问:
Delete a record in Ember data not working
I have a table (a component) and a delete button in each row. When the the delete button is clicked the specific row should be deleted.

Tried the following code:

MyComponent.js

```<code>  import Ember from 'ember';

   export default Ember.Component.extend({
   actions:{
    deleteCartRecord(cartDetails){
        debugger;
        this.sendAction('deleteRecord',cartDetails);
    }
 }

});
</code>```

In MyComponent.hbs

```<code>{{#each model.orderParts as |newCart|}}
  <div class="card-wrapper col-lg-12 col-md-12">
     <div class="col-lg-2 col-md-2">
        <div class="order-id">{{newCart.partNumber}}</div>
       {{#if (gte newCart.promiseQty newCart.quantity)}}
    <div class="order-status delivered">{{env.APP.StockAvailable}}</div>
    {{else}} {{#if (gt newCart.promiseQty '0'(and (lt newCart.promiseQty newCart.quantity)))}}
    <div class="order-status intransit">{{env.APP.LowInStock}}</div>
    {{else}} {{#if (eq newCart.promiseQty '0')}}
    <div class="order-status outofstock">{{env.APP.OutofStock}}</div>
    {{/if}} {{/if}} {{/if}}
</div>
<div class="col-lg-3 col-md-3">
    <div class="item-header">Delivery Date</div>
    <div class="item-data">{{newCart.deliveryDate}}</div>
</div>
<div class="col-lg-2 col-md-2">
    <div class="item-header">Required Qty.</div>
    <div class="item-data">
        {{increse-required-quantity incresedQuantity=newCart.quantity}}
    </div>
</div>
<div class="col-lg-2 col-md-2">
    <div class="item-header">Unit Price</div>
    <div class="item-data">{{newCart.unitPrice}}</div>
</div>
<div class="col-lg-2 col-md-2">
    <div class="item-header">Total Price</div>
    <div class="item-data">{{newCart.partTotalPrice}}</div>
</div>
<div class="col-lg-1 col-md-1 button-colum"><button type="button" class="btn btn-danger" {{action "deleteCartRecord" newCart}}>Delete</button>             </div>
  </div>
 {{/each}}
</code>```

My Controller

```<code>   import Ember from 'ember';
   export default Ember.Controller.extend({
     actions:{
        deleteRecord(data){
          debugger;
            let confirmation = confirm("are you sure to delete");
            if(confirmation)
            {
               debugger;
               data.deleteRecord();
               data.save();

            }
       }
  }
});
</code>```

The template file in which component is called

```<code>    <hr>
</div>

<div class="col-lg-12 col-md-12">
    <div class="checkout-summery-wrapper">
        <div class="total-label">Total</div>
        <div class="total">{{model.totalPrice}}</div>
        <!--<div class="tax-text">( Inclusive of all taxes )</div>-->
        <div class="place-order-button"><button type="button" class="btn siemens-btn">Place Order</button></div>
    </div>
</div>

<div class="col-lg-12 col-md-12">
    {{#if model.orderParts.isGeneric}}
    <div class="panel panel-default card-list-panel">
        <div class="panel-heading-cart col-lg-12 col-md-12">
            <div class="col-lg-11 col-md-11 heading">Generic Parts</div>
            <div class="col-lg-1 col-md-1"><a href='#' class="delete-all">Delete All</a></div>
        </div>
        <div class="panel-body">
            {{cart-record model = model}}
        </div>
    </div>
    {{/if}}
    {{#unless model.orderParts.isGeneric}}
    <div class="panel panel-default card-list-panel">
        <div class="panel-heading-cart col-lg-12 col-md-12">
            <div class="col-lg-11 col-md-11 heading">Hot Gas Path</div>
            <div class="col-lg-1 col-md-1"><a href='#' class="delete-all">Delete All</a></div>
        </div>
        <div class="panel-body">
            {{cart-record model = model deleteRecord=(action 'deleteRecord')}}
        </div>
    </div>
    {{/unless}}
</div>
</code>```

MyRoute

```<code> import Ember from 'ember';

  export default Ember.Route.extend({
     model: function()
     {
             return this.get('store').queryRecord('cart',{userId:1})
     }

  });
</code>```

My Serializer

```<code>  import DS from 'ember-data';

  export default DS.JSONSerializer.extend(DS.EmbeddedRecordsMixin, {
       primaryKey: 'totalPrice',

       attrs: {
        orderParts:
       {
           serialize: 'records',
           deserialize: 'records'
       }

    }

 });
</code>```

I have the following issues:

In MyComponent.hbs, will newCart being passed as a parameter delete all the records or the specific record I want deleted?

Any ideas on why MyController is not invoked from the component?

Is this the correct way of deleting a record in ember?

Thank you in advance.

答:
In MyComponent.hbs newCart is passed as a parameter will this delete all the record or the specific record i want?

It will delete the particular record alone. if you want to delete all the record then you can try unloadAll('model-name')

MyController is not invoked from the component why is that?

You need to send action upcon calling component, {{my-component deleteRecord=(action 'deleteRecords') }} . Actually real problem is, you are calling deleteRecord but in controller you got deleteRecords.

Is this the correct way of deleting a record in ember?

If you want to delete right away then you can use destroyRecord this will delete and save record immediately

Body:
I have a table (a component) and a delete button in each row. When the the delete button is clicked the specific row should be deleted.

Tried the following code:

MyComponent.js

  import Ember from 'ember';

   export default Ember.Component.extend({
   actions:{
    deleteCartRecord(cartDetails){
        debugger;
        this.sendAction('deleteRecord',cartDetails);
    }
 }

});

In MyComponent.hbs

{{#each model.orderParts as |newCart|}}

{{newCart.partNumber}}

       {{#if (gte newCart.promiseQty newCart.quantity)}}

{{env.APP.StockAvailable}}

    {{else}} {{#if (gt newCart.promiseQty '0'(and (lt newCart.promiseQty newCart.quantity)))}}

{{env.APP.LowInStock}}

    {{else}} {{#if (eq newCart.promiseQty '0')}}

{{env.APP.OutofStock}}

    {{/if}} {{/if}} {{/if}}

Delivery Date

{{newCart.deliveryDate}}

Required Qty.

        {{increse-required-quantity incresedQuantity=newCart.quantity}}

Unit Price

{{newCart.unitPrice}}

Total Price

{{newCart.partTotalPrice}}

<button type="button" class="btn btn-danger" {{action "deleteCartRecord" newCart}}>Delete</button>

 {{/each}}

My Controller

   import Ember from 'ember';
   export default Ember.Controller.extend({
     actions:{
        deleteRecord(data){
          debugger;
            let confirmation = confirm("are you sure to delete");
            if(confirmation)
            {
               debugger;
               data.deleteRecord();
               data.save();

            }
       }
  }
});

The template file in which component is called

Total

{{model.totalPrice}}

<button type="button" class="btn siemens-btn">Place Order</button>

    {{#if model.orderParts.isGeneric}}

Generic Parts

Delete All

            {{cart-record model = model}}

    {{/if}}
    {{#unless model.orderParts.isGeneric}}

Hot Gas Path

Delete All

            {{cart-record model = model deleteRecord=(action 'deleteRecord')}}

    {{/unless}}

MyRoute

 import Ember from 'ember';

  export default Ember.Route.extend({
     model: function()
     {
             return this.get('store').queryRecord('cart',{userId:1})
     }

  });

My Serializer

  import DS from 'ember-data';

  export default DS.JSONSerializer.extend(DS.EmbeddedRecordsMixin, {
       primaryKey: 'totalPrice',

       attrs: {
        orderParts:
       {
           serialize: 'records',
           deserialize: 'records'
       }

    }

 });

I have the following issues:

In MyComponent.hbs, will newCart being passed as a parameter delete all the records or the specific record I want deleted?

Any ideas on why MyController is not invoked from the component?

Is this the correct way of deleting a record in ember?

Thank you in advance.


问:
Canvas: Strange behavior when pressing key down
By default the rectangle of my canvas should move from left to right. When pressing the key down, it should start moving down.

var canvas = document.getElementById('canvas'),
    ctx = canvas.getContext('2d'),
    x = 0,
    y = 0;

function draw(x_move, y_move) {
  requestAnimationFrame(function() {
    draw(x_move, y_move);
  });
  ctx.beginPath();
  ctx.rect(x, y, 20, 20);
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.fillStyle = "#ffffff";
  ctx.fill();
  ctx.closePath();
  x = x + x_move;
  y = y + y_move;
}

draw(1, 0);

document.addEventListener('keydown', function(event) {
  //console.log(event.keyCode);
  if (event.keyCode == 40) {
    draw(0, 1);
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>canvas { background-color: red; }</code>```

<canvas id="canvas" width="600" height="400"></canvas>```

Using the code above, you may at least notice two issues:

When pressing key down, the rectangle moves down but also keeps moving to the right.

When you keep pressing the down key multiple times, the speed gets increased.

How can I fix those issues?

答:
keyboardEvent.keyCode is a depreciated property. You should use keyboardEvent.code or keyboardEvent.key they provided a named key which is much easier to manage than trying to remember key codes.

You can use fillRect rather than rect and you don't need to use beginPath and fill. You don't need to use closePath you only use it if you want to close a shape (ie add a line from the last point to the first) rect is already closed

You can set the callback directly as the argument for requestAnimationFrame

It pays to group related data together. In this case the square has a position x, y and a delta position (x_move, y_move) that are better off in a object. A good clue that you have related data is when you find yourself adding the same name to a set of variables. Objects can also include behaviour in the form of functions like draw and update

```<code>const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');

// list of named keys to record state of
const keys = {
   ArrowDown: false,
};
// create key event listeners
document.addEventListener('keydown', keyEvent);
document.addEventListener('keyup', keyEvent);

// define the square
const square = {
    x : 0,  // position
    y : 0,
    dx : 0, // delta pos
    dy : 0,
    draw () {  // function to render the square
        ctx.fillStyle = "#ffffff";
        ctx.fillRect(this.x, this.y, 20, 20);
    },
    update () { // function to update square
        if(keys.ArrowDown){
            this.dx = 0;
            this.dy = 1;
        }else {
            this.dx = 1;
            this.dy = 0;
        }
        this.x += this.dx;
        this.y += this.dy;
    }
}

// main animation update function called once per frame 1/60th second
function update () {
  requestAnimationFrame(update);
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  square.update();
  square.draw();
}

// key event records named key state (false up, true down)
function keyEvent (event) {
   if(keys[event.code] !== undefined){
      keys[event.code] = event.type === "keydown";
   }
}
</code>```

Body:
By default the rectangle of my canvas should move from left to right. When pressing the key down, it should start moving down.

var canvas = document.getElementById('canvas'),
    ctx = canvas.getContext('2d'),
    x = 0,
    y = 0;

function draw(x_move, y_move) {
  requestAnimationFrame(function() {
    draw(x_move, y_move);
  });
  ctx.beginPath();
  ctx.rect(x, y, 20, 20);
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.fillStyle = "#ffffff";
  ctx.fill();
  ctx.closePath();
  x = x + x_move;
  y = y + y_move;
}

draw(1, 0);

document.addEventListener('keydown', function(event) {
  //console.log(event.keyCode);
  if (event.keyCode == 40) {
    draw(0, 1);
  }
});

canvas { background-color: red; }

<canvas id="canvas" width="600" height="400"></canvas>

Using the code above, you may at least notice two issues:

When pressing key down, the rectangle moves down but also keeps moving to the right.

When you keep pressing the down key multiple times, the speed gets increased.

How can I fix those issues?

Body:
keyboardEvent.keyCode is a depreciated property. You should use keyboardEvent.code or keyboardEvent.key they provided a named key which is much easier to manage than trying to remember key codes.

You can use fillRect rather than rect and you don't need to use beginPath and fill. You don't need to use closePath you only use it if you want to close a shape (ie add a line from the last point to the first) rect is already closed

You can set the callback directly as the argument for requestAnimationFrame

It pays to group related data together. In this case the square has a position x, y and a delta position (x_move, y_move) that are better off in a object. A good clue that you have related data is when you find yourself adding the same name to a set of variables. Objects can also include behaviour in the form of functions like draw and update

const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');

// list of named keys to record state of
const keys = {
   ArrowDown: false,
};
// create key event listeners
document.addEventListener('keydown', keyEvent);
document.addEventListener('keyup', keyEvent);

// define the square
const square = {
    x : 0,  // position
    y : 0,
    dx : 0, // delta pos
    dy : 0,
    draw () {  // function to render the square
        ctx.fillStyle = "#ffffff";
        ctx.fillRect(this.x, this.y, 20, 20);
    },
    update () { // function to update square
        if(keys.ArrowDown){
            this.dx = 0;
            this.dy = 1;
        }else {
            this.dx = 1;
            this.dy = 0;
        }
        this.x += this.dx;
        this.y += this.dy;
    }
}

// main animation update function called once per frame 1/60th second
function update () {
  requestAnimationFrame(update);
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  square.update();
  square.draw();
}

// key event records named key state (false up, true down)
function keyEvent (event) {
   if(keys[event.code] !== undefined){
      keys[event.code] = event.type === "keydown";
   }
}


问:
Catch Change / Add / Delete Event for Blocks in Drupal
I need to add some functionality (flush some caches and such) when a Block in Drupal is added, moved, edited or deleted, is there ANY kind of hook for that (or another somewhat Drupal native way) like there is for nodes with hook_nodeapi?

I know there is hook_block but there $op is always list, so its not really any good.

答:
Unfortunately blocks don't have that kind of signalling mechanism. I would use the forms system to add submit callbacks wherever you need a signal for additional work.

```<code>/**
 * Implementation of hook_form_alter().
 */
function custom_form_alter(&$form, &$form_state, $form_id) {
  // Overview form.
  if ($form_id == 'block_admin_display_form') {
    $form['#submit'][] = 'custom_block_admin_display_form_submit';
  }
  // Individual block configuration form.
  elseif ($form_id == 'block_admin_configure') {
    $form['#submit'][] = 'custom_block_admin_configure_submit';
  }
}

/**
 * Submit handler for block overview form.
 */
function custom_block_admin_display_form_submit($form, &$form_state) {
  cache_clear_all();
}

/**
 * Submit handler for block configuration form.
 */
function custom_block_admin_configure_form_submit($form, &$form_state) {
  drupal_set_message(t('You have changed a block. Run for the hills!'));
}
</code>```

The one downside to this method is that any alternate approach to configuring blocks won't work. If someone builds a custom form outside the block module, or if you are using context or panels to move blocks around it won't help. Of course, since any of those alternate configuration points would also use a form, you can use hook_form_alter() to hack into their submit processes as well.

Body:
Unfortunately blocks don't have that kind of signalling mechanism. I would use the forms system to add submit callbacks wherever you need a signal for additional work.

/**
 * Implementation of hook_form_alter().
 */
function custom_form_alter(&$form, &$form_state, $form_id) {
  // Overview form.
  if ($form_id == 'block_admin_display_form') {
    $form['#submit'][] = 'custom_block_admin_display_form_submit';
  }
  // Individual block configuration form.
  elseif ($form_id == 'block_admin_configure') {
    $form['#submit'][] = 'custom_block_admin_configure_submit';
  }
}

/**
 * Submit handler for block overview form.
 */
function custom_block_admin_display_form_submit($form, &$form_state) {
  cache_clear_all();
}

/**
 * Submit handler for block configuration form.
 */
function custom_block_admin_configure_form_submit($form, &$form_state) {
  drupal_set_message(t('You have changed a block. Run for the hills!'));
}

The one downside to this method is that any alternate approach to configuring blocks won't work. If someone builds a custom form outside the block module, or if you are using context or panels to move blocks around it won't help. Of course, since any of those alternate configuration points would also use a form, you can use hook_form_alter() to hack into their submit processes as well.


问:
Align right side of a group of labels
I'm making an HTML page with a list of fields for filling out billing info.
Since the labels are in-line, their width is determined by the text contained in them, thus making them different widths which makes the input boxes unaligned. This makes a very ugly, unorganized look.

<fieldset>
    <legend>Billing Information</legend>

    Card Number: <input type="text">

    Expiration Month: <input type="number">

    Expiration Year: <input type="number">

    Name on Card: <input type="text">

    Address: <input type="text">

    City: <input type="text">

    State: <input type="text">

    Country: <input type="text">

    ZIP Code: <input type="number">

</fieldset>
```

What do I need to do to my HTML code to align the right side of the labels and the left side of the input boxes?

答:
You can use tables or use display: table-row & display: table-cell css to simulate table cell layouts as following:

fieldset {display: inline-block; padding: 10px 20px;} /* 'display: inline-block' is not necessary, just for appearance */

.row {display: table-row; }
.lbl {display: table-cell; text-align:right; padding: 8px 5px;}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><fieldset>
    <legend>Billing Information</legend>

    <div class="row"><span class="lbl">Card Number: </span><input type="text"></div>
    <div class="row"><span class="lbl">Expiration Month: </span><input type="number"></div>
    <div class="row"><span class="lbl">Expiration Year: </span><input type="number"></div>
    <!-- ... /-->
</fieldset><br></code>```

Title: Align right side of a group of labels

Body:
I'm making an HTML page with a list of fields for filling out billing info.
Since the labels are in-line, their width is determined by the text contained in them, thus making them different widths which makes the input boxes unaligned. This makes a very ugly, unorganized look.

<fieldset>
    <legend>Billing Information</legend>

    Card Number: <input type="text">

    Expiration Month: <input type="number">

    Expiration Year: <input type="number">

    Name on Card: <input type="text">

    Address: <input type="text">

    City: <input type="text">

    State: <input type="text">

    Country: <input type="text">

    ZIP Code: <input type="number">

</fieldset>

What do I need to do to my HTML code to align the right side of the labels and the left side of the input boxes?

Body:
You can use tables or use display: table-row & display: table-cell css to simulate table cell layouts as following:

fieldset {display: inline-block; padding: 10px 20px;} /* 'display: inline-block' is not necessary, just for appearance */

.row {display: table-row; }
.lbl {display: table-cell; text-align:right; padding: 8px 5px;}

<fieldset>
    <legend>Billing Information</legend>

    <div class="row"><span class="lbl">Card Number: </span><input type="text"></div>
    <div class="row"><span class="lbl">Expiration Month: </span><input type="number"></div>
    <div class="row"><span class="lbl">Expiration Year: </span><input type="number"></div>
    <!-- ... /-->
</fieldset><br>


问:
limit is not working in subquery
I have saved vehicle types in 'vehicle_types_locales', drivers in 'drivers' and driver's current location in 'drivercurrentlocation' table.

Logic : I am trying to get all vehicle types from main query then trying to select 5 drivers for each category from driver's tables which satisfying conditions as implemented. If records are less than 5 for all categories then it's working fine else it returns all driver's exist in category.(seems limit not working)

My query is :

```<code>SELECT vtl.vehicle_type_id as id ,vtl.name, (
    SELECT GROUP_CONCAT(concat(
        drv.id,'----', drv.firstname, '----', ifnull(drv.lastname,''), '----',
        dll.latitude, '----', dll.longitude) SEPARATOR '--++--')
    FROM drivercurrentlocation as dll LEFT JOIN drivers as drv ON
    (dll.driverid = drv.id) WHERE drv.active_vehicle_id > 0 AND
    current_duty_status='F' and drv.status='A' and drv.onduty='Y' AND
    drv.vehicle_type_id= vtl.vehicle_type_id AND latitude > '".
    $latLongData['minLat']."' AND latitude < '". $latLongData['maxLat'] ."'
    AND longitude > '". $latLongData['minLng'] ."' AND longitude < '".
    $latLongData['maxLng']."' limit 5)
as ddata FROM vehicle_types_locales
WHERE vtl.status  = 'A' AND vtl.language_id = '$languageid'";
</code>```

Please help me to resolve this limit issue.

Thanks in advance

答:
After investing lots of hours, I have found a solution.

```<code>SELECT vtl.vehicle_type_id as id ,vtl.name, (
    SELECT substring_index(GROUP_CONCAT(concat(drv.id,'----
    ',drv.firstname, '----', ifnull(drv.lastname,''), '----', dll.latitude,
    '----', dll.longitude) SEPARATOR '--++--'),'--++--',$no_of_drivers)
    FROM drivercurrentlocation as dll LEFT JOIN drivers as drv ON
    (dll.driverid = drv.id) WHERE drv.active_vehicle_id > 0 AND
    current_duty_status='F' and drv.status='A' and drv.onduty='Y' AND
    drv.vehicle_type_id= vtl.vehicle_type_id AND latitude > '".
    $latLongData['minLat']."' AND latitude < '". $latLongData['maxLat']
    ."' AND longitude > '". $latLongData['minLng'] ."' AND longitude < '".
    $latLongData['maxLng']."' )
as ddata FROM vehicle_types_locales as vtl
WHERE vtl.status  = 'A' AND vtl.language_id = '$languageid'";
</code>```

with this query I have found desired output.

Thanks for your answers.

Title: limit is not working in subquery

Body:
I have saved vehicle types in 'vehicle_types_locales', drivers in 'drivers' and driver's current location in 'drivercurrentlocation' table.

Logic : I am trying to get all vehicle types from main query then trying to select 5 drivers for each category from driver's tables which satisfying conditions as implemented. If records are less than 5 for all categories then it's working fine else it returns all driver's exist in category.(seems limit not working)

My query is :

SELECT vtl.vehicle_type_id as id ,vtl.name, (
    SELECT GROUP_CONCAT(concat(
        drv.id,'----', drv.firstname, '----', ifnull(drv.lastname,''), '----',
        dll.latitude, '----', dll.longitude) SEPARATOR '--++--')
    FROM drivercurrentlocation as dll LEFT JOIN drivers as drv ON
    (dll.driverid = drv.id) WHERE drv.active_vehicle_id > 0 AND
    current_duty_status='F' and drv.status='A' and drv.onduty='Y' AND
    drv.vehicle_type_id= vtl.vehicle_type_id AND latitude > '".
    $latLongData['minLat']."' AND latitude < '". $latLongData['maxLat'] ."'
    AND longitude > '". $latLongData['minLng'] ."' AND longitude < '".
    $latLongData['maxLng']."' limit 5)
as ddata FROM vehicle_types_locales
WHERE vtl.status  = 'A' AND vtl.language_id = '$languageid'";

Please help me to resolve this limit issue.

Thanks in advance

Body:
After investing lots of hours, I have found a solution.

SELECT vtl.vehicle_type_id as id ,vtl.name, (
    SELECT substring_index(GROUP_CONCAT(concat(drv.id,'----
    ',drv.firstname, '----', ifnull(drv.lastname,''), '----', dll.latitude,
    '----', dll.longitude) SEPARATOR '--++--'),'--++--',$no_of_drivers)
    FROM drivercurrentlocation as dll LEFT JOIN drivers as drv ON
    (dll.driverid = drv.id) WHERE drv.active_vehicle_id > 0 AND
    current_duty_status='F' and drv.status='A' and drv.onduty='Y' AND
    drv.vehicle_type_id= vtl.vehicle_type_id AND latitude > '".
    $latLongData['minLat']."' AND latitude < '". $latLongData['maxLat']
    ."' AND longitude > '". $latLongData['minLng'] ."' AND longitude < '".
    $latLongData['maxLng']."' )
as ddata FROM vehicle_types_locales as vtl
WHERE vtl.status  = 'A' AND vtl.language_id = '$languageid'";

with this query I have found desired output.

Thanks for your answers.


问:
Event keypress jquery when match a special character
I'm trying to processing code when user type @ like facebook tag. When user type @abc, then event is processed. This is my code:

```<code>$("#content").keypress(function(e) {
          var tmp = $("#content").val();
          if(tmp =="@")
          {
            console.log("It working");
          }
        });
</code>```

UPDATING

Code like this:

```<code>$("#content").keypress(function(event) {
          var tmp  = $("#content").val();
          if(tmp.indexOf('@') !== -1)
          {
            console.log("It's working");
          }
        });
</code>```

It's working when i'm typing @ with anything charater, but when i type  (space), it also working, i try to stop event when user type (space) after @anything.

答:
Here is updated working codepen .
You need to use valuestring.charAt(0) every time.

Body:
I'm trying to processing code when user type @ like facebook tag. When user type @abc, then event is processed. This is my code:

$("#content").keypress(function(e) {
          var tmp = $("#content").val();
          if(tmp =="@")
          {
            console.log("It working");
          }
        });

UPDATING

Code like this:

$("#content").keypress(function(event) {
          var tmp  = $("#content").val();
          if(tmp.indexOf('@') !== -1)
          {
            console.log("It's working");
          }
        });

It's working when i'm typing @ with anything charater, but when i type  (space), it also working, i try to stop event when user type (space) after @anything.


问:
Changing the stroke color of map overlay on tap
I have a map view and I am generating a bunch of mkcircle overlays. These have a stroke width and fill color.

I also have a tap gesture set up that determines if the tap is on one of the mkcircles. What I would like to do now is change the stroke width and fill color so the user knows which mkcircle was tapped and then change it back on any other tap.

The code I have is below.

```<code>func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
    let circleRenderer = MKCircleRenderer(overlay: overlay)
    circleRenderer.fillColor = UIColor.blue.withAlphaComponent(0.1)
    circleRenderer.strokeColor = UIColor.blue
    circleRenderer.lineWidth = 2
    return circleRenderer
}

func handleMapTap(_ gestureReconizer: UITapGestureRecognizer) {
    let tapPoint = gestureReconizer.location(in: mapView)
    let tapCoordinate = mapView.convert(tapPoint, toCoordinateFrom: mapView)
    let point = MKMapPointForCoordinate(tapCoordinate)
    if mapView.overlays.count > 0 {
        for overlay: MKOverlay in polygonArray {
            if (overlay is MKCircle) {
                let circle = overlay
                let circleRenderer = (mapView.renderer(for: circle) as! MKCircleRenderer)
                let datapoint = circleRenderer.point(for: point)
                circleRenderer.invalidatePath()

                if circleRenderer.path.contains(datapoint) {

                    let circleIndex = polygonArray.index{$0 === circle}!
                    print(circleIndex)
                }
            }
        }
    }
}
</code>```

I have done some searching but I have not been able to find a solution yet. I am able to get the circleIndex of the tapped circle.

Any guidance is appreciated.

答:
Just in case anyone else comes across this here is the answer which was actually pretty easy in the end.</p>

```<code>func handleMapTap(_ gestureReconizer: UITapGestureRecognizer) {
    let tapPoint = gestureReconizer.location(in: mapView)
    let tapCoordinate = mapView.convert(tapPoint, toCoordinateFrom: mapView)
    let point = MKMapPointForCoordinate(tapCoordinate)
    if mapView.overlays.count > 0 {
        for overlay: MKOverlay in polygonArray {
            if (overlay is MKCircle) {
                let circle = overlay
                let circleRenderer = (mapView.renderer(for: circle) as! MKCircleRenderer)
                let datapoint = circleRenderer.point(for: point)
                circleRenderer.invalidatePath()

                circleRenderer.fillColor = UIColor.blue.withAlphaComponent(0.1)
                circleRenderer.strokeColor = UIColor.blue

                if circleRenderer.path.contains(datapoint) {

                    circleRenderer.fillColor = UIColor.black
                    circleRenderer.strokeColor = UIColor.black
                    let circleIndex = polygonArray.index{$0 === circle}!
                    print(circleIndex)
                }
            }
        }
    }
}
</code>```

Body:
I have a map view and I am generating a bunch of mkcircle overlays. These have a stroke width and fill color.

I also have a tap gesture set up that determines if the tap is on one of the mkcircles. What I would like to do now is change the stroke width and fill color so the user knows which mkcircle was tapped and then change it back on any other tap.

The code I have is below.

func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
    let circleRenderer = MKCircleRenderer(overlay: overlay)
    circleRenderer.fillColor = UIColor.blue.withAlphaComponent(0.1)
    circleRenderer.strokeColor = UIColor.blue
    circleRenderer.lineWidth = 2
    return circleRenderer
}

func handleMapTap(_ gestureReconizer: UITapGestureRecognizer) {
    let tapPoint = gestureReconizer.location(in: mapView)
    let tapCoordinate = mapView.convert(tapPoint, toCoordinateFrom: mapView)
    let point = MKMapPointForCoordinate(tapCoordinate)
    if mapView.overlays.count > 0 {
        for overlay: MKOverlay in polygonArray {
            if (overlay is MKCircle) {
                let circle = overlay
                let circleRenderer = (mapView.renderer(for: circle) as! MKCircleRenderer)
                let datapoint = circleRenderer.point(for: point)
                circleRenderer.invalidatePath()

                if circleRenderer.path.contains(datapoint) {

                    let circleIndex = polygonArray.index{$0 === circle}!
                    print(circleIndex)
                }
            }
        }
    }
}

I have done some searching but I have not been able to find a solution yet. I am able to get the circleIndex of the tapped circle.

Any guidance is appreciated.

Body:
Just in case anyone else comes across this here is the answer which was actually pretty easy in the end.

func handleMapTap(_ gestureReconizer: UITapGestureRecognizer) {
    let tapPoint = gestureReconizer.location(in: mapView)
    let tapCoordinate = mapView.convert(tapPoint, toCoordinateFrom: mapView)
    let point = MKMapPointForCoordinate(tapCoordinate)
    if mapView.overlays.count > 0 {
        for overlay: MKOverlay in polygonArray {
            if (overlay is MKCircle) {
                let circle = overlay
                let circleRenderer = (mapView.renderer(for: circle) as! MKCircleRenderer)
                let datapoint = circleRenderer.point(for: point)
                circleRenderer.invalidatePath()

                circleRenderer.fillColor = UIColor.blue.withAlphaComponent(0.1)
                circleRenderer.strokeColor = UIColor.blue

                if circleRenderer.path.contains(datapoint) {

                    circleRenderer.fillColor = UIColor.black
                    circleRenderer.strokeColor = UIColor.black
                    let circleIndex = polygonArray.index{$0 === circle}!
                    print(circleIndex)
                }
            }
        }
    }
}


问:
NPM Unmet peer dependency
I have a project with installed React@15.4.1

Now I want to add this package, but this error appears:

```<code>-- UNMET PERR DEPENDENCY react@>=0.12.0 || ^15.0.0-0
npm WARN react-swipeable@3.9.2 requires a peer of react@>=0.12.0 || ^15.0.0-0
but none was installed
</code>```

If I understand right, this package has React 0.12-15.0 versions in its peer dependencies, but my project uses higher version and that;s why I can't add this package to my project. So what is possible solution?

答:
Two are two things that can be done from your side,

You can make use of React@15.0.0 instead of React@15.4.1 in your package.json

Remove the entry for React@15.4.1 and delete the node_modules. After that run the command

```<code>npm install
</code>```

to install React@15.0.0 run command

```<code>npm install -S react@15.0.0
</code>```

The second thing that you can do is to look for another npm module that is compatible with your version of React.

Title: NPM Unmet peer dependency

Body:
I have a project with installed React@15.4.1

Now I want to add this package, but this error appears:

-- UNMET PERR DEPENDENCY react@>=0.12.0 || ^15.0.0-0
npm WARN react-swipeable@3.9.2 requires a peer of react@>=0.12.0 || ^15.0.0-0
but none was installed

If I understand right, this package has React 0.12-15.0 versions in its peer dependencies, but my project uses higher version and that;s why I can't add this package to my project. So what is possible solution?

Body:
Two are two things that can be done from your side,

You can make use of React@15.0.0 instead of React@15.4.1 in your package.json

Remove the entry for React@15.4.1 and delete the node_modules. After that run the command

npm install

to install React@15.0.0 run command

npm install -S react@15.0.0

The second thing that you can do is to look for another npm module that is compatible with your version of React.


问:
C++ Two dimensional array multiplication table
I am using C++ and want to do a 2-dimensional array. 10 rows and 3 columns. First column is(1 through 10).  For Second column, user enters his/her choice of a number from (1-10) resulting in a times table displaying the results as follows: In this example the user's choice is '4':

```<code>1x4=4
2x4=8
3x4=12
4x4=16
5x4=20
6x4=24
7x4=28
8x4=32
9x4=36
10x4=40
</code>```

I can't get the user's input to calculate correctly when using the for loop.

答:
Well you can try this to get that output

```<code>#include<iostream>
using namespace std;
int main()
{
int n;      //To take input
int table[10][3]; // Table
cout << "Input a number: ";
cin >> n;
// Generating Output
for (int i = 0; i < 10; i++)
{
    table[i][0] = i + 1;
    table[i][1] = n;
    table[i][2] = table[i][0] * table[i][1];
}

for (int i = 0; i < 10; i++)
{
    cout << table[i][0] << " * " << table[i][1] << " = " << table[i][2]<<endl;
}
return 0;
}
</code>```

Output

Body:
I am using C++ and want to do a 2-dimensional array. 10 rows and 3 columns. First column is(1 through 10).  For Second column, user enters his/her choice of a number from (1-10) resulting in a times table displaying the results as follows: In this example the user's choice is '4':

1x4=4
2x4=8
3x4=12
4x4=16
5x4=20
6x4=24
7x4=28
8x4=32
9x4=36
10x4=40

I can't get the user's input to calculate correctly when using the for loop.

Body:
Well you can try this to get that output

#include<iostream>
using namespace std;
int main()
{
int n;      //To take input
int table[10][3]; // Table
cout << "Input a number: ";
cin >> n;
// Generating Output
for (int i = 0; i < 10; i++)
{
    table[i][0] = i + 1;
    table[i][1] = n;
    table[i][2] = table[i][0] * table[i][1];
}

for (int i = 0; i < 10; i++)
{
    cout << table[i][0] << " * " << table[i][1] << " = " << table[i][2]<<endl;
}
return 0;
}

Output


问:
How to intercept an authentication request in ASP.net webform
I have user's who are losing their data because they sit on a page too long, then are asked to log back in.  I want to do the following:

1) Instead of redirecting them to a login page, I want to cancel the current request and give the user a popup dialog box to login with.

2) When the login is successful, I want the user to be sent back to their form, with all data intact.  (Even better if the request could go through without sending them back to that form, but this is optional).

How can I intercept these authentication requests, and present the user with a popup login?

I am using ASP.net forms authentication.

答: Are you using a master page?  You could redirect to there when login is required, not a separate login page.  In the login code in the master page you then decided whether to redirect to a proper, standalone login page, or make a login div visible as a popup.  </p>


问:
Haskell zip lists with type Int
I'm having the following issue in Haskell.

I try to zip a list and numbers in order to number the list
i.e. zip [1..] mylist.

However, the type for this is [(Integer, [String])].

Is there any way to get Int instead of Integer in this case?

答:
The literal 1 is overloaded, i.e.

```<code>1 :: Num a => a
</code>```

and will either be Integer or Int, depending on the context. So if you use zip [1..] mylist in a context that expects a type [(Int, [String])], then this will work.

You can also be explicit, by writing zip [1::Int..] mylist instead.

Title: Haskell zip lists with type Int

Body:
The literal 1 is overloaded, i.e.

1 :: Num a => a

and will either be Integer or Int, depending on the context. So if you use zip [1..] mylist in a context that expects a type [(Int, [String])], then this will work.

You can also be explicit, by writing zip [1::Int..] mylist instead.


问:
How to install tshark on Docker?
I want to install tshark on ubuntu17.04 on Docker for Mac with Dockerfile.
I am using docker-compose

In apt install tshark, there is a following prompt.

The prompt stopping install despite I typed yes.

How to install tshark in Dockerfile?

```<code>Dumpcap can be installed in a way that allows members of the "wireshark" system
group to capture packets. This is recommended over the alternative of running
Wireshark/Tshark directly as root, because less of the code will run with
elevated privileges.

For more detailed information please see
/usr/share/doc/wireshark-common/README.Debian.

Enabling this feature may be a security risk, so it is disabled by default. If
in doubt, it is suggested to leave it disabled.

Should non-superusers be able to capture packets? [yes/no] yes
</code>```

答:
First, you generally have (to avoid having to type 'yes'):

```<code>RUN apt install -yq xxx
</code>```

Second:

you can check out this tshark image, which does install dumcap; by compiling wireshark, which produced dumpcap.

the alternative (no compilation, only install) is this image

The install command becomes in that last case:

```<code># Install build wireshark, need to run as root RUN apt-get update && \
    apt-get install -y wireshark && \
    groupadd wireshark && \
    usermod -aG wireshark developer && \
    setcap 'CAP_NET_RAW+eip CAP_NET_ADMIN+eip' /usr/bin/dumpcap && \
    chgrp wireshark /usr/bin/dumpcap && \
    chmod 750 /usr/bin/dumpcap
</code>```

Title: How to install tshark on Docker?

Body:
I want to install tshark on ubuntu17.04 on Docker for Mac with Dockerfile.
I am using docker-compose

In apt install tshark, there is a following prompt.

The prompt stopping install despite I typed yes.

How to install tshark in Dockerfile?

Dumpcap can be installed in a way that allows members of the "wireshark" system
group to capture packets. This is recommended over the alternative of running
Wireshark/Tshark directly as root, because less of the code will run with
elevated privileges.

For more detailed information please see
/usr/share/doc/wireshark-common/README.Debian.

Enabling this feature may be a security risk, so it is disabled by default. If
in doubt, it is suggested to leave it disabled.

Should non-superusers be able to capture packets? [yes/no] yes

Body:
First, you generally have (to avoid having to type 'yes'):

RUN apt install -yq xxx

Second:

you can check out this tshark image, which does install dumcap; by compiling wireshark, which produced dumpcap.

the alternative (no compilation, only install) is this image

The install command becomes in that last case:

# Install build wireshark, need to run as root RUN apt-get update && \
    apt-get install -y wireshark && \
    groupadd wireshark && \
    usermod -aG wireshark developer && \
    setcap 'CAP_NET_RAW+eip CAP_NET_ADMIN+eip' /usr/bin/dumpcap && \
    chgrp wireshark /usr/bin/dumpcap && \
    chmod 750 /usr/bin/dumpcap


问:
Select Top 1 In SQL Server
Please help me in select top 1

The data like this

```<code>Code    Amp      Price
-----------------------
00001   10       1000
00002   75-100   1500
00003   50-60    1200
00004   15       1100
</code>```

Note : datatype for column Amp is VarChar

I want to select with Amp 75 and I want get the price is 1500

So I use this statement:

```<code>SELECT TOP 1 *
FROM Cable
WHERE (Amp <= '75')
ORDER BY Amp DESC
</code>```

but the result price I get is 1200 is record with code : 00003 (wrong), actually I want the result is code : 00002 and the price is 1500

But if I want to select with Amp 76 the result is true with the syntax :

```<code>SELECT TOP 1 *
FROM Cable
WHERE (Amp <= '75')
ORDER BY Amp DESC
</code>```

What is the true select for my case? Please help me

答:
Just about any parse/split function will do, and combined with a Cross Apply, it becomes a small matter

-- Easy to do without a parse function

```<code>Declare @Cable table (Code varchar(25),Amp varchar(50),Price int)
Insert Into @Cable values
('00001','10',    1000),
('00002','75-100',1500),
('00003','50-60', 1200),
('00004','15',    1100)

Select Top 1 A.*
 From  @Cable A
 Cross Apply [dbo].[udf-Str-Parse](A.Amp,'-') B
 Where RetVal<=76              --<< Notice we are testing for 76
 Order By Price Desc
</code>```

Returns

```<code>Code    Amp     Price
00002   75-100  1500
</code>```

The UDF if interested

```<code>CREATE FUNCTION [dbo].[udf-Str-Parse] (@String varchar(max),@Delimiter varchar(25))
Returns Table
As
Return (
    with   cte1(N)   As (Select 1 From (Values(1),(1),(1),(1),(1),(1),(1),(1),(1),(1)) N(N)),
           cte2(N)   As (Select Top (IsNull(DataLength(@String),0)) Row_Number() over (Order By (Select NULL)) From (Select N=1 From cte1 a,cte1 b,cte1 c,cte1 d) A ),
           cte3(N)   As (Select 1 Union All Select t.N+DataLength(@Delimiter) From cte2 t Where Substring(@String,t.N,DataLength(@Delimiter)) = @Delimiter),
           cte4(N,L) As (Select S.N,IsNull(NullIf(CharIndex(@Delimiter,@String,s.N),0)-S.N,8000) From cte3 S)

    Select RetSeq = Row_Number() over (Order By A.N)
          ,RetVal = LTrim(RTrim(Substring(@String, A.N, A.L)))
    From   cte4 A
);
--Orginal Source http://www.sqlservercentral.com/articles/Tally+Table/72993/
--Much faster than str-Parse, but limited to 8K
--Select * from [dbo].[udf-Str-Parse-8K]('Dog,Cat,House,Car',',')
--Select * from [dbo].[udf-Str-Parse-8K]('John||Cappelletti||was||here','||')
</code>```

Title: Select Top 1 In SQL Server

Body:
Please help me in select top 1

The data like this

Code    Amp      Price
-----------------------
00001   10       1000
00002   75-100   1500
00003   50-60    1200
00004   15       1100

Note : datatype for column Amp is VarChar

I want to select with Amp 75 and I want get the price is 1500

So I use this statement:

SELECT TOP 1 *
FROM Cable
WHERE (Amp <= '75')
ORDER BY Amp DESC

but the result price I get is 1200 is record with code : 00003 (wrong), actually I want the result is code : 00002 and the price is 1500

But if I want to select with Amp 76 the result is true with the syntax :

SELECT TOP 1 *
FROM Cable
WHERE (Amp <= '75')
ORDER BY Amp DESC

What is the true select for my case? Please help me

Body:
Just about any parse/split function will do, and combined with a Cross Apply, it becomes a small matter

-- Easy to do without a parse function

Declare @Cable table (Code varchar(25),Amp varchar(50),Price int)
Insert Into @Cable values
('00001','10',    1000),
('00002','75-100',1500),
('00003','50-60', 1200),
('00004','15',    1100)

Select Top 1 A.*
 From  @Cable A
 Cross Apply [dbo].[udf-Str-Parse](A.Amp,'-') B
 Where RetVal<=76              --<< Notice we are testing for 76
 Order By Price Desc

Returns

Code    Amp     Price
00002   75-100  1500

The UDF if interested

CREATE FUNCTION [dbo].[udf-Str-Parse] (@String varchar(max),@Delimiter varchar(25))
Returns Table
As
Return (
    with   cte1(N)   As (Select 1 From (Values(1),(1),(1),(1),(1),(1),(1),(1),(1),(1)) N(N)),
           cte2(N)   As (Select Top (IsNull(DataLength(@String),0)) Row_Number() over (Order By (Select NULL)) From (Select N=1 From cte1 a,cte1 b,cte1 c,cte1 d) A ),
           cte3(N)   As (Select 1 Union All Select t.N+DataLength(@Delimiter) From cte2 t Where Substring(@String,t.N,DataLength(@Delimiter)) = @Delimiter),
           cte4(N,L) As (Select S.N,IsNull(NullIf(CharIndex(@Delimiter,@String,s.N),0)-S.N,8000) From cte3 S)

    Select RetSeq = Row_Number() over (Order By A.N)
          ,RetVal = LTrim(RTrim(Substring(@String, A.N, A.L)))
    From   cte4 A
);
--Orginal Source http://www.sqlservercentral.com/articles/Tally+Table/72993/
--Much faster than str-Parse, but limited to 8K
--Select * from [dbo].[udf-Str-Parse-8K]('Dog,Cat,House,Car',',')
--Select * from [dbo].[udf-Str-Parse-8K]('John||Cappelletti||was||here','||')