问:
After hitting send button the form submits but how do I redirect to new page in rails?
Here's my form code. After hitting send I'd like to see a confirmation message or redirect to a different page.

```<code><%= flash[:notice]

<%= form_with(url: "/static_pages/thank_you") do |form| %>
  <div class="row">
    <div class="col-md-4">
      <div class="form-group">
        <%= form.label :name %>
        <%= form.text_field :name, class: "form-control", placeholder: "Enter Name" %>
      </div>
      <div class="form-group">
        <%= form.label :email, "Email Address" %>
        <%= form.text_field :email, class: "form-control", placeholder: "Enter Email" %>
      </div>
      <div class="form-group">
        <%= form.label :message %>
        <%= form.text_area :message, class: "form-control", placeholder: "Enter Message" %>
      </div>
    </div>
  </div>
  <%= form.submit "Send" %>
<% end %>
</code>```

Here is my controller code or at least the start of it. I'm suspecting I'm missing something on the page below.

```<code>class StaticPagesController < ApplicationController

    def index
    #@products = Product.all
    end

  def landing_page
    @products = Product.limit(4)
    end

    def contact
    end

    def about
    end

    def thank_you
    @name = params[:name]
        @email = params[:email]
    @message = params[:message]
    UserMailer.contact_form(@email, @name, @message).deliver_now
    end

end
</code>```

答:
```<code>def thank_you
  @name = params[:name]
  @email = params[:email]
  @message = params[:message]
  UserMailer.contact_form(@email, @name, @message).deliver_now
  flash[:notice] = "Mail sent successfully!"
  redirect_to root_path
end
</code>```

Body:
Here's my form code. After hitting send I'd like to see a confirmation message or redirect to a different page.

<%= flash[:notice]

<%= form_with(url: "/static_pages/thank_you") do |form| %>

        <%= form.label :name %>
        <%= form.text_field :name, class: "form-control", placeholder: "Enter Name" %>

        <%= form.label :email, "Email Address" %>
        <%= form.text_field :email, class: "form-control", placeholder: "Enter Email" %>

        <%= form.label :message %>
        <%= form.text_area :message, class: "form-control", placeholder: "Enter Message" %>

  <%= form.submit "Send" %>
<% end %>

Here is my controller code or at least the start of it. I'm suspecting I'm missing something on the page below.

class StaticPagesController < ApplicationController

    def index
    #@products = Product.all
    end

  def landing_page
    @products = Product.limit(4)
    end

    def contact
    end

    def about
    end

    def thank_you
    @name = params[:name]
        @email = params[:email]
    @message = params[:message]
    UserMailer.contact_form(@email, @name, @message).deliver_now
    end

end


来源: stackexchange

问:
How to create 1-100 in 10 rows?
I'm trying to get the following exercise:

"Write a program containing a pair of neste while loops that displays the integer values 1-100, ten numbers per row, with the columns alignes as below.

```<code> 1  2  3  4  5  6  7  8  9 10
11 12 13 14 15 16 17 18 19 20
</code>```

So far I've come up with this:

```<code>lijst = list(range(1, 101))
i = 0

while i < 100:
    print(lijst[i],"\t", end=" ".format(">"))
    i = i+1
    if i % 10 == 0:
        print("")
</code>```

Although it produces the things I need, the tabs aren't working. whenever I try to add spaces instead of a tab, things move way too much on the second and further rows.
Furthermore I can't seem to find out why the .format(">") doesn't work. I've tried to apply .format(">3") but that didn't do anything at all.

ContentLicense: CC BY-SA 3.0

Title: How to create 1-100 in 10 rows?

Body:
I'm trying to get the following exercise:

"Write a program containing a pair of neste while loops that displays the integer values 1-100, ten numbers per row, with the columns alignes as below.

 1  2  3  4  5  6  7  8  9 10
11 12 13 14 15 16 17 18 19 20

So far I've come up with this:

lijst = list(range(1, 101))
i = 0

while i < 100:
    print(lijst[i],"\t", end=" ".format(">"))
    i = i+1
    if i % 10 == 0:
        print("")

Although it produces the things I need, the tabs aren't working. whenever I try to add spaces instead of a tab, things move way too much on the second and further rows.
Furthermore I can't seem to find out why the .format(">") doesn't work. I've tried to apply .format(">3") but that didn't do anything at all.

Body:
You can use the {:>5d} format style to right align integers 5 spaces

lijst = list(range(1, 101))
i = 0

while i < 100:
    print("{:>5d}".format(lijst[i]), end=" ")
    i = i+1
    if i % 10 == 0:
        print("")

Output:

    1     2     3     4     5     6     7     8     9    10
   11    12    13    14    15    16    17    18    19    20
   21    22    23    24    25    26    27    28    29    30
   31    32    33    34    35    36    37    38    39    40
   41    42    43    44    45    46    47    48    49    50
   51    52    53    54    55    56    57    58    59    60
   61    62    63    64    65    66    67    68    69    70
   71    72    73    74    75    76    77    78    79    80
   81    82    83    84    85    86    87    88    89    90
   91    92    93    94    95    96    97    98    99   100


问:
Why can't I import and use my class in TypeScript?
My class is defined as follows:

```<code>export class Log {
    email: string;

    constructor(email: string) {
        this.email = email;
    }
}
</code>```

In a separate file, I import my class as follows:

```<code>import * as Log from "../models/Log";
</code>```

But then, when I try to use my class eg:

```<code>function log(log: Log, callback: Function) {

}
</code>```

I get an error 'cannot find name Log'.

What am I doing wrong?

答:
You can use {} to specify which class to import from the file. So...

```<code>import { Log } from "../models/Log";
</code>```

imports the class Log from the file ../models/Log

Body:
My class is defined as follows:

export class Log {
    email: string;

    constructor(email: string) {
        this.email = email;
    }
}

In a separate file, I import my class as follows:

import * as Log from "../models/Log";

But then, when I try to use my class eg:

function log(log: Log, callback: Function) {

}

I get an error 'cannot find name Log'.

What am I doing wrong?

Body:
You can use {} to specify which class to import from the file. So...

import { Log } from "../models/Log";

imports the class Log from the file ../models/Log


问:
Add
 every 2 images from mysql in a variable
I'm trying to make this code insert a line break after 2 images when there are a total of 4 images. The Code listed below adds the line break after all images are displayed instead of after 2 images. Could someone please help me with this?

```<code>$images = "";
$i = 0;
while ($info = mysqli_fetch_array($imglist)) {
  $style = $info['Style'];
  $imgpath = $info['ImgPath'];
  $standardimg = $info['StandardImg'];
  $colorname = $info['ColorName'];
  $smallimgwidth = $info['SmallImgWidth'];

  $images = $images.
  "<img src='$imgpath/$standardimg-Small.jpg'
  alt = '$mill $style - $colorname'
  title = '$mill $style - $colorname'
  style = 'min-width:35px; max-width:$smallimgwidthpx;' / > ";

  if (mysqli_num_rows($imglist) == 4) {
    if ($i != 0 && $i % 2 == 1) {
      echo '<br />';
    }
  }
  $i++;
}
</code>```

答:
**Problem **

You are constructing the  tags dynamically but in the process you are adding
 tags separately.

Solution

Add
 tag to your  tags string being generated.

Code

```<code>$images = $images . '<br />';
</code>```

In place of

```<code>echo '<br />';
</code>```

Title: Add <br /> every 2 images from mysql in a variable

Body:
I'm trying to make this code insert a line break after 2 images when there are a total of 4 images. The Code listed below adds the line break after all images are displayed instead of after 2 images. Could someone please help me with this?

$images = "";
$i = 0;
while ($info = mysqli_fetch_array($imglist)) {
  $style = $info['Style'];
  $imgpath = $info['ImgPath'];
  $standardimg = $info['StandardImg'];
  $colorname = $info['ColorName'];
  $smallimgwidth = $info['SmallImgWidth'];

  $images = $images.
  " ";

  if (mysqli_num_rows($imglist) == 4) {
    if ($i != 0 && $i % 2 == 1) {
      echo '
';
    }
  }
  $i++;
}

Body:
**Problem **

You are constructing the  tags dynamically but in the process you are adding
 tags separately.

Solution

Add
 tag to your  tags string being generated.

Code

$images = $images . '<br />';

In place of

echo '<br />';


问:
redirect to error on exceeding fileupload size
I am trying to direct user to a error page when maximum fileupload size excedds.For this iam doing the following thing:

```<code>public void Init(HttpApplication application)
    {
        application.BeginRequest += new EventHandler(application_BeginRequest);
    }

    void application_BeginRequest(object sender, EventArgs e)
    {
        HttpApplication application = (HttpApplication)sender;
        HttpContext context = application.Context;
        if (context.Request.ContentLength > 4096000)
        {
            context.Response.Redirect("~/Error.aspx");
        }
    }
    public void Dispose()
    {
    }
</code>```

But on uploading file with size more than the max filesize it is showing "connection reset" error.
How should i do this.

答:
Following the post the reason can be just a redirection to local site:

It doesn't seem to work when the
  server is local (either through using
  localhost, local ip or
  http://machinename/). The browser just
  reacts like the server completely
  dropped the connection - connection
  reset by peer / connection was reset
  (FF) / cannot display web page (IE).

ContentLicense: CC BY-SA 2.5

Body:
I am trying to direct user to a error page when maximum fileupload size excedds.For this iam doing the following thing:

public void Init(HttpApplication application)
    {
        application.BeginRequest += new EventHandler(application_BeginRequest);
    }

    void application_BeginRequest(object sender, EventArgs e)
    {
        HttpApplication application = (HttpApplication)sender;
        HttpContext context = application.Context;
        if (context.Request.ContentLength > 4096000)
        {
            context.Response.Redirect("~/Error.aspx");
        }
    }
    public void Dispose()
    {
    }

But on uploading file with size more than the max filesize it is showing "connection reset" error.
How should i do this.


问:
How can I get the percentage of utilization for each cpu?
I wrote a script to get the percentage of utilization for each cpu based on a script that I have found that gave the average percentage of utilization. The script that I have found works great, the percentage changes every second. Unfortunately the percentages displayed by the script I wrote don't change at all. Do you have an idea of what I did wrong or if you have a better idea to get the percentage of utilization for each cpu ?

EDIT

The working part is the "GET THE MEAN USAGE OF THE CPU" part, the non working part is the "GET THE MAX USAGE BETWEEN ALL THE CPUS"

Here is my script, it displays the avg cpu usage and the cpu that is used the most :

```<code>#!/bin/bash

PREV_TOTAL=0
PREV_IDLE=0

while true; do

# GET THE MEAN USAGE OF THE CPU
# -----------------------------
  # we get the mean of the cpu usage
  CPU=(`cat /proc/stat | grep '^cpu '`) # Get the total CPU statistics.
  unset CPU[0]                          # Discard the "cpu" prefix.
  IDLE=${CPU[4]}
  # Calculate the total CPU time.
  TOTAL=0
  for VALUE in "${CPU[@]:0:4}"; do
    let "TOTAL=$TOTAL+$VALUE"
  done

  # Calculate the CPU usage since we last checked.
  let "DIFF_IDLE=$IDLE-$PREV_IDLE"
  let "DIFF_TOTAL=$TOTAL-$PREV_TOTAL"
  let "DIFF_USAGE=(1000*($DIFF_TOTAL-$DIFF_IDLE)/$DIFF_TOTAL+5)/10"

  # Remember the total and idle CPU times for the next check.
  PREV_TOTAL="$TOTAL"
  PREV_IDLE="$IDLE"

# GET THE MAX USAGE BETWEEN ALL THE CPUS
# --------------------------------------

  # here we get an array with all the cpus
  CPUS=(`cat /proc/stat | grep '^cpu[0-9]'`)
  lengthArray=${#CPUS[@]}
  numberOfCpus=$((lengthArray/11))
  i=0
  numberOfCpus=$((lengthArray/11))
  TOTALS=()
  IDLES=()
  PERCENTAGES=()
  PREV_TOTALS=()
  PREV_IDLES=()
  # we instenciate the arrays and set their values to 0
  while [ $i -lt $numberOfCpus ]; do
    TOTALS+=(0)
    IDLES+=(0)
    PERCENTAGES+=(0)
    PREV_TOTALS+=(0)
    PREV_IDLES+=(0)
    i=$((i+1))
  done

  i=0
  index=1
  limit=$((index+4))
  # we loop through the array to get each total for each cpu
  while [ $i -lt $numberOfCpus ]; do
    IDLES[$i]=${CPUS[$index+3]}
    # since we only want the first four numbers for each cpu, we have to loop in a strange way
    while [ $index -lt $limit ]; do
        TOTALS[$i]=$((TOTALS[$i]+CPUS[$index]))
        index=$((index+1))
    done
    # 7 is the number of array element before the next series of number that we want
    index=$((limit+7))
    # we set the limit to four+the index because we only want the four numbers after the index
    limit=$((index+4))
    i=$((i+1))
  done

  # now we calculate the percentage of usage for every cpu so we can get the max percentage
  i=0

  # we calculate the percentage for each cpu
  while [ $i -lt $numberOfCpus ]; do
    let "DIFF_IDLE_i=${IDLES[$i]}-${PREV_IDLES[$i]}"
    let "DIFF_TOTAL_i=${TOTALS[$i]}-${PREV_TOTALS[$i]}"
    let "DIFF_USAGE_i=(1000*($DIFF_TOTAL_i-$DIFF_IDLE_i)/$DIFF_TOTAL_i+5)/10"
    PERCENTAGES[$i]=$DIFF_USAGE_i
    PREV_TOTALS[$i]=${TOTALS[$i]}
    PREV_IDLES[$i]=${IDLES[$i]}
    i=$((i+1))
  done

  MAX=${PERCENTAGES[0]}
  cpu=0
  i=0
  # here we look for the max
  for percent in ${PERCENTAGES[@]}; do
    if [ $percent -gt $MAX ]; then
        cpu=$i
        MAX=$percent
    fi
    i=$((i+1))
  done

  echo -en "\rCPU: $DIFF_USAGE%   CPU$cpu: $MAX%  \b\b"

  # Wait before checking again.
  sleep 1
done
</code>```

答:
I have finally found my problem, I initialized my arrays in the loop, and it needed to be initialized outside the loop. I managed to make the script work, if anyone is interested, here is the final script:

```<code>#!/bin/bash

# this function is used to get the infos about the cpu
getCpuScores() {
    CPU=(`cat /proc/stat | grep ^cpu$1`)
}

# this function is used to get the percentage of utilization of a cpu
getPercentageOfCpu() {
    unset CPU[0]
    local idle=${CPU[4]}
    local total=0
    for val in "${CPU[@]:0:4}"; do
        let "total=$total+$val"
    done

    let "diff_idle=$idle-${PREV_IDLES[$1]}"
    let "diff_total=$total-${PREV_TOTALS[$1]}"
    let "diff_usage=(1000*($diff_total-$diff_idle)/$diff_total+5)/10"

    PERCENTAGES[$1]=$diff_usage
    PREV_IDLES[$1]=$idle
    PREV_TOTALS[$1]=$total
}

# first we initialize all the needed variables
PREV_TOTAL=0
PREV_IDLE=0
# this is to get the number of cpu
CPUS=(`cat /proc/stat | grep '^cpu[0-9]'`)
lengthArray=${#CPUS[@]}
numberOfCpus=$((lengthArray/11))
i=0
PREV_TOTALS=()
PREV_IDLES=()
PERCENTAGES=()
# we instenciate the arrays and set their values to 0
while [ $i -lt $numberOfCpus ]; do
    PREV_TOTALS+=(0)
    PREV_IDLES+=(0)
    PERCENTAGES+=(0)
    i=$((i+1))
done

# MAIN LOOP

while true; do

# GET THE MEAN USAGE OF THE CPU
# -----------------------------
  # we get the mean of the cpu usage
  CPU=(`cat /proc/stat | grep '^cpu '`) # Get the total CPU statistics.
  unset CPU[0]                          # Discard the "cpu" prefix.
  IDLE=${CPU[4]}
  # Calculate the total CPU time.
  TOTAL=0
  for VALUE in "${CPU[@]:0:4}"; do
    let "TOTAL=$TOTAL+$VALUE"
  done

  # Calculate the CPU usage since we last checked.
  let "DIFF_IDLE=$IDLE-$PREV_IDLE"
  let "DIFF_TOTAL=$TOTAL-$PREV_TOTAL"
  let "DIFF_USAGE=(1000*($DIFF_TOTAL-$DIFF_IDLE)/$DIFF_TOTAL+5)/10"

  # Remember the total and idle CPU times for the next check.
  PREV_TOTAL="$TOTAL"
  PREV_IDLE="$IDLE"

# GET THE MAX USAGE BETWEEN ALL THE CPUS
# ------------------------
  # first we get the percentage of utilization for each cpu
  i=0
  while [ $i -lt $numberOfCpus ]; do
    # we get the cpu score to be able to calculate the percentage of utilization
    getCpuScores $i
    # then we calculate the percentage of the cpu and put it in an array
    getPercentageOfCpu $i

    i=$((i+1))

  done

  # then we get the max
  MAX=${PERCENTAGES[0]}
  cpu=0
  i=0

  while [ $i -lt $numberOfCpus ]; do
    if [ ${PERCENTAGES[$i]} -gt $MAX ]; then
        MAX=${PERCENTAGES[$i]}
        cpu=$i
    fi
    i=$((i+1))
  done

  # finally we display the avg cpu usage and the max cpu usage
  echo -en "\rCPU: $DIFF_USAGE%  CPU$cpu: $MAX% \b\b"

  # Wait before checking again.
  sleep 1
done
</code>```

The script displays the percentage of the average cpu usage and the percentage of usage of the cpu that is used the most.

Body:
I wrote a script to get the percentage of utilization for each cpu based on a script that I have found that gave the average percentage of utilization. The script that I have found works great, the percentage changes every second. Unfortunately the percentages displayed by the script I wrote don't change at all. Do you have an idea of what I did wrong or if you have a better idea to get the percentage of utilization for each cpu ?

EDIT

The working part is the "GET THE MEAN USAGE OF THE CPU" part, the non working part is the "GET THE MAX USAGE BETWEEN ALL THE CPUS"

Here is my script, it displays the avg cpu usage and the cpu that is used the most :

#!/bin/bash

PREV_TOTAL=0
PREV_IDLE=0

while true; do

# GET THE MEAN USAGE OF THE CPU
# -----------------------------
  # we get the mean of the cpu usage
  CPU=(`cat /proc/stat | grep '^cpu '`) # Get the total CPU statistics.
  unset CPU[0]                          # Discard the "cpu" prefix.
  IDLE=${CPU[4]}
  # Calculate the total CPU time.
  TOTAL=0
  for VALUE in "${CPU[@]:0:4}"; do
    let "TOTAL=$TOTAL+$VALUE"
  done

  # Calculate the CPU usage since we last checked.
  let "DIFF_IDLE=$IDLE-$PREV_IDLE"
  let "DIFF_TOTAL=$TOTAL-$PREV_TOTAL"
  let "DIFF_USAGE=(1000*($DIFF_TOTAL-$DIFF_IDLE)/$DIFF_TOTAL+5)/10"

  # Remember the total and idle CPU times for the next check.
  PREV_TOTAL="$TOTAL"
  PREV_IDLE="$IDLE"

# GET THE MAX USAGE BETWEEN ALL THE CPUS
# --------------------------------------

  # here we get an array with all the cpus
  CPUS=(`cat /proc/stat | grep '^cpu[0-9]'`)
  lengthArray=${#CPUS[@]}
  numberOfCpus=$((lengthArray/11))
  i=0
  numberOfCpus=$((lengthArray/11))
  TOTALS=()
  IDLES=()
  PERCENTAGES=()
  PREV_TOTALS=()
  PREV_IDLES=()
  # we instenciate the arrays and set their values to 0
  while [ $i -lt $numberOfCpus ]; do
    TOTALS+=(0)
    IDLES+=(0)
    PERCENTAGES+=(0)
    PREV_TOTALS+=(0)
    PREV_IDLES+=(0)
    i=$((i+1))
  done

  i=0
  index=1
  limit=$((index+4))
  # we loop through the array to get each total for each cpu
  while [ $i -lt $numberOfCpus ]; do
    IDLES[$i]=${CPUS[$index+3]}
    # since we only want the first four numbers for each cpu, we have to loop in a strange way
    while [ $index -lt $limit ]; do
        TOTALS[$i]=$((TOTALS[$i]+CPUS[$index]))
        index=$((index+1))
    done
    # 7 is the number of array element before the next series of number that we want
    index=$((limit+7))
    # we set the limit to four+the index because we only want the four numbers after the index
    limit=$((index+4))
    i=$((i+1))
  done

  # now we calculate the percentage of usage for every cpu so we can get the max percentage
  i=0

  # we calculate the percentage for each cpu
  while [ $i -lt $numberOfCpus ]; do
    let "DIFF_IDLE_i=${IDLES[$i]}-${PREV_IDLES[$i]}"
    let "DIFF_TOTAL_i=${TOTALS[$i]}-${PREV_TOTALS[$i]}"
    let "DIFF_USAGE_i=(1000*($DIFF_TOTAL_i-$DIFF_IDLE_i)/$DIFF_TOTAL_i+5)/10"
    PERCENTAGES[$i]=$DIFF_USAGE_i
    PREV_TOTALS[$i]=${TOTALS[$i]}
    PREV_IDLES[$i]=${IDLES[$i]}
    i=$((i+1))
  done

  MAX=${PERCENTAGES[0]}
  cpu=0
  i=0
  # here we look for the max
  for percent in ${PERCENTAGES[@]}; do
    if [ $percent -gt $MAX ]; then
        cpu=$i
        MAX=$percent
    fi
    i=$((i+1))
  done

  echo -en "\rCPU: $DIFF_USAGE%   CPU$cpu: $MAX%  \b\b"

  # Wait before checking again.
  sleep 1
done

Body:
I have finally found my problem, I initialized my arrays in the loop, and it needed to be initialized outside the loop. I managed to make the script work, if anyone is interested, here is the final script:

#!/bin/bash

# this function is used to get the infos about the cpu
getCpuScores() {
    CPU=(`cat /proc/stat | grep ^cpu$1`)
}

# this function is used to get the percentage of utilization of a cpu
getPercentageOfCpu() {
    unset CPU[0]
    local idle=${CPU[4]}
    local total=0
    for val in "${CPU[@]:0:4}"; do
        let "total=$total+$val"
    done

    let "diff_idle=$idle-${PREV_IDLES[$1]}"
    let "diff_total=$total-${PREV_TOTALS[$1]}"
    let "diff_usage=(1000*($diff_total-$diff_idle)/$diff_total+5)/10"

    PERCENTAGES[$1]=$diff_usage
    PREV_IDLES[$1]=$idle
    PREV_TOTALS[$1]=$total
}

# first we initialize all the needed variables
PREV_TOTAL=0
PREV_IDLE=0
# this is to get the number of cpu
CPUS=(`cat /proc/stat | grep '^cpu[0-9]'`)
lengthArray=${#CPUS[@]}
numberOfCpus=$((lengthArray/11))
i=0
PREV_TOTALS=()
PREV_IDLES=()
PERCENTAGES=()
# we instenciate the arrays and set their values to 0
while [ $i -lt $numberOfCpus ]; do
    PREV_TOTALS+=(0)
    PREV_IDLES+=(0)
    PERCENTAGES+=(0)
    i=$((i+1))
done

# MAIN LOOP

while true; do

# GET THE MEAN USAGE OF THE CPU
# -----------------------------
  # we get the mean of the cpu usage
  CPU=(`cat /proc/stat | grep '^cpu '`) # Get the total CPU statistics.
  unset CPU[0]                          # Discard the "cpu" prefix.
  IDLE=${CPU[4]}
  # Calculate the total CPU time.
  TOTAL=0
  for VALUE in "${CPU[@]:0:4}"; do
    let "TOTAL=$TOTAL+$VALUE"
  done

  # Calculate the CPU usage since we last checked.
  let "DIFF_IDLE=$IDLE-$PREV_IDLE"
  let "DIFF_TOTAL=$TOTAL-$PREV_TOTAL"
  let "DIFF_USAGE=(1000*($DIFF_TOTAL-$DIFF_IDLE)/$DIFF_TOTAL+5)/10"

  # Remember the total and idle CPU times for the next check.
  PREV_TOTAL="$TOTAL"
  PREV_IDLE="$IDLE"

# GET THE MAX USAGE BETWEEN ALL THE CPUS
# ------------------------
  # first we get the percentage of utilization for each cpu
  i=0
  while [ $i -lt $numberOfCpus ]; do
    # we get the cpu score to be able to calculate the percentage of utilization
    getCpuScores $i
    # then we calculate the percentage of the cpu and put it in an array
    getPercentageOfCpu $i

    i=$((i+1))

  done

  # then we get the max
  MAX=${PERCENTAGES[0]}
  cpu=0
  i=0

  while [ $i -lt $numberOfCpus ]; do
    if [ ${PERCENTAGES[$i]} -gt $MAX ]; then
        MAX=${PERCENTAGES[$i]}
        cpu=$i
    fi
    i=$((i+1))
  done

  # finally we display the avg cpu usage and the max cpu usage
  echo -en "\rCPU: $DIFF_USAGE%  CPU$cpu: $MAX% \b\b"

  # Wait before checking again.
  sleep 1
done

The script displays the percentage of the average cpu usage and the percentage of usage of the cpu that is used the most.


问:
How to wait for return value and subscribe to it in Angular2?
I've encountered a problem while developing app in Ionic. I'm executing a query on the database using database provider and it is fine but it is probably called asynchronous because I get undefined.

After some checks and other logic I'm returning value from the database:

```<code>this.databaseProvider.getValueFor(saved.id)
    .then(data => {
           return data;
    });
</code>```

Is there any way to return data to Observable and subscribe to it? I'm quite new to Angular2 and don't know all concepts.

答:
You can use [**Observable.fromPromise**][1] method to convert promise to Observable & then subscribe to Observable to retrieve data from it.

```<code>SomeMethod(){
   return Observable.fromPromise(this.databaseProvider.getValueFor(saved.id))
}

//Usage
this.SomeMethod().subscribe(data => {
   console.log("data", data)
})
</code>```

Body:
I've encountered a problem while developing app in Ionic. I'm executing a query on the database using database provider and it is fine but it is probably called asynchronous because I get undefined.

After some checks and other logic I'm returning value from the database:

this.databaseProvider.getValueFor(saved.id)
    .then(data => {
           return data;
    });

Is there any way to return data to Observable and subscribe to it? I'm quite new to Angular2 and don't know all concepts.

Body:
You can use [**Observable.fromPromise**][1] method to convert promise to Observable & then subscribe to Observable to retrieve data from it.

SomeMethod(){
   return Observable.fromPromise(this.databaseProvider.getValueFor(saved.id))
}

//Usage
this.SomeMethod().subscribe(data => {
   console.log("data", data)
})


问:
Convert array-like String to ArrayList in Java
I've been trying to convert a String like this: "[1,2,3]" to an ArrayList in Java.
What I tried so far is to use GSon library to convert the String mentioned above to List using:

Gson - convert from Json to a typed ArrayList<T>

Convert Gson Array to Arraylist

Parsing JSON array into java.util.List with Gson

but it ends with an exception (I can provide more details if needed). The first question should be actually if it's a good approach to achieve such a transformation?

答:
A non-regex method would be to remove the brackets from the string and then split on the commas. Then convert to an ArrayList.</p>

```<code>String s = "[1, 2, 3]";
String[] splits =  s.replace("[","").replace("]","").split(",");
ArrayList<String> arrayList = new ArrayList<>(Arrays.asList(splits));
</code>```

Body:
A non-regex method would be to remove the brackets from the string and then split on the commas. Then convert to an ArrayList.

String s = "[1, 2, 3]";
String[] splits =  s.replace("[","").replace("]","").split(",");
ArrayList<String> arrayList = new ArrayList<>(Arrays.asList(splits));


问:
RSpec how to use a_collection_containing_exactly matcher with an array?
I'd really like to use the a_collection_containing_exactly matcher but with an array in parameters instead of writing values directly, like this

contract_ids_subset = order_summaries_subset.map {|c| c.contract_id.to_i}.compact

allow(Shipping::Owner::Api::Helper).to receive(:order_summaries_by_contract_ids_and_delivery_date).with(
a_collection_containing_exactly(contract_ids_subset),
delivery_date) {
          order_summaries_subset
        }

( assume that contract_ids_subset = [11111, 22222, 99999] )

This work if I hardcode
a_collection_containing_exactly(11111, 22222, 99999)

But I cant figure out how to use an array [11111, 22222, 99999] with the same results ???

答:
You're looking for the splat operator in ruby to deconstruct the array. It'll basically take the single argument of the array and deconstruct it such that each value becomes an argument.

So you'd do something like:

```<code>a_collection_containing_exactly(*contact_ids_subset)
</code>```

Body:
You're looking for the splat operator in ruby to deconstruct the array. It'll basically take the single argument of the array and deconstruct it such that each value becomes an argument.

So you'd do something like:

a_collection_containing_exactly(*contact_ids_subset)


问:
Is it possible to have multiple STDIN streams?
I'm hoping to connect two USB barcode scanners to a single computer, allowing two people to scan ticket barcodes simultaneously.  If both people scan at the same time, however, the input from STDIN will get messy.

Is there a way to set up different STDIN streams, each tied to a specific USB port?  The console script is in Ruby, though pointers in any language would be much appreciated.

答:
What if you use a Mutex to synchronize them so only one scan can be processed at a time?

Here's a tutorial on working with threads in Ruby

http://ruby-doc.org/docs/ProgrammingRuby/html/tut_threads.html


问:
What is the difference between using virsh and qemu to create virtual machines?
I think there are two ways of creating a virtual machine.

1.Use virsh command(or GUI,virt-manager) to create a virtual machine.

2.Use qemu command (like qemu-system-x86_64)to create a virtual machine.

What is the difference between the two ways?

答:
Virsh is the command that interact with the libvirtd in order to manage "any" hypervisor.
qemu is a Quick Emulator. This is actually the application that will provide the hardware abstraction layer for the guest VMs</p>


问:
Visual Studio 2015: Visualization of std::vector doesn't show information in debug
I installed a new update of visual studio 2015 and have now the version 14.0.25424.00 with update 3.
After installing the update the visualization of std::vectors while debugging changed. Usually when I debugged a program I could see the size and the items of a std::vector.

After the update I only can see the raw view of the std::vector.

Here is the code which I used to for this example:

```<code>int main()
{
   int a = 1;
   std::vector<int> vecOfInt;
   vecOfInt.push_back(1);
   vecOfInt.push_back(2);
   vecOfInt.push_back(3);

   return 0;
}
</code>```

I think that maybe during the update some settings in visual studio changed but I can't find out what is different...
Does anyone has an idea what I could try to fix this besides reinstalling visual studio?

EDIT:
Here the requested debug settings:

答:
I had the same issue. Win7 x64, VS2015 Update3 (ver 14.0.25431.01).

I tried repair Update 3 as described in WinterMute's answer (incl. reboot) - it didn't help.

I tried reset my setting in VS as described in Jack's answer:

TOOLS->Import and Export Settings Wizard->Reset all settings->select “No, just reset settings, overwriting my current settings”-> I chose a "General" collection. (+ restart VS)

It helped. And I noticed 1 change in Options > Debugging > General: Use Managed Compatibility Mode is unchecked now. (I have also Use Native Compatibility Mode unchecked but it was before too).

Both std::vector and std::stack are shown nice in debug mode.

Body:
I installed a new update of visual studio 2015 and have now the version 14.0.25424.00 with update 3.
After installing the update the visualization of std::vectors while debugging changed. Usually when I debugged a program I could see the size and the items of a std::vector.

After the update I only can see the raw view of the std::vector.

Here is the code which I used to for this example:

int main()
{
   int a = 1;
   std::vector<int> vecOfInt;
   vecOfInt.push_back(1);
   vecOfInt.push_back(2);
   vecOfInt.push_back(3);

   return 0;
}

I think that maybe during the update some settings in visual studio changed but I can't find out what is different...
Does anyone has an idea what I could try to fix this besides reinstalling visual studio?

EDIT:
Here the requested debug settings:


问:
React - Sort players on scoreboard by highest score if their score changes
I have built a React app that is a scoreboard.  You can add and remove points from a player's score using the + and - symbols on the right side. Currently, the players are sorted by their id.  I would like to figure out a way to sort my players based on their current score.

For instance, if one player gets a higher score than another player above them, that player would move up to the row they are ranked at.  I have made a Codepen displaying my project.  If anyone has any idea how to sort the players after the onScoreChange function is run I would really appreciate it!

CodePen

```<code><div id="container"></div>
body {
  background: #d5d5d5;
  font-family: arial;
  color: #FAFAFA;
  text-transform: uppercase;
}

.scoreboard {
  background: #333;
  width: 700px;
  margin: 70px auto;
  box-shadow: 0 4px 0px #333;
  border-radius: 15px;

}

.header {
  padding: 5px 10px;
  text-align: center;
  display: flex;
  align-items: center;
  background-color: #222;
  border-radius: 15px 15px 0 0;
  border-bottom: solid 2px #444;
}

.header h1 {
  flex-grow: 1;
  font-size: 1.5em;
  letter-spacing: 3px;
  font-weight: normal;
}

.player {
  display: flex;
  font-size: 1.2em;
  border-bottom: solid 2px #444;
  letter-spacing: 2px;
}

  .remove-player {
    visibility: hidden;
    margin-right: 10px;
    color: #e57373;
    cursor: pointer;
  }

  .player-name:hover .remove-player {
    visibility: visible;
  }

  .player-name {
    flex-grow: 1;
    padding: 20px 10px 10px 10px;
  }

  .player-score {
    width: 190px;
    background: blue;
  }

  .counter {
    display: flex;
  }

  .counter-action {
    border: none;
    font-weight: bold;
    color: #FAFAFA;
    display: block;
    padding: 20px 20px;
    cursor: pointer;
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
  }

  .counter-action.increment {
    background: #66BB6A;
  }

  .counter-action.increment:hover {
    background: #549d59;
    cursor: pointer;
  }

  .counter-action.decrement {
    background: #ef5350;
  }

  .counter-action.decrement:hover {
    background: #c44442;
    cursor: pointer;
  }

  .counter-score {
    flex-grow: 1;
    background: #2b2b2b;
    color: #FAFAFA;
    text-align: center;
    font-family: monospace;
    padding: 10px;
    font-size: 2em;
  }

.add-player-form form {
  display: flex;
  background-color: #222;
  border-radius: 0 0 20px 20px
}

  .add-player-form input[type=text] {
    flex-grow: 1;
    border-width: 0 0 1px 0;
    margin: 15px 10px 15px 15px;
    padding: 10px;
    border-radius: 5px;
    background-color: #333;
    border-style: none;
    text-shadow: none;
    text-transform: uppercase;
    color: #999;
    letter-spacing: 2px;
    outline: none;
  }

  .add-player-form input[type=text]::-webkit-input-placeholder{
    color: #666;
    letter-spacing: 2px;
  }

  .add-player-form input[type=text]:focus{
    background-color: #444;
  }

  .add-player-form input[type=submit] {
    display: block;
    font-size: .6em;
    margin: 15px 15px 15px 0;
    padding: 10px;
    background-color: #333;
    border-radius: 5px;
    border: none;
    color: #999;
    letter-spacing: 2px;
    font-weight: bold;
    text-shadow: none;
    text-transform: uppercase;
  }

  .add-player-form input[type=submit]:hover{
    background: #4b71b5;
    color: #fafafa;
    cursor: pointer;
  }

var PLAYERS = [
  {
    name: "Mary Miller",
    score: 22,
    id: 1,
  },
  {
    name: "Ellie Grace",
    score: 20,
    id: 2,
  },
  {
    name: "Ben Pine",
    score: 18,
    id: 3,
  },
  {
    name: "Rachel Slater",
    score: 17,
    id: 4,
  },
  {
    name: "Lisette Ven",
    score: 10,
    id: 5,
  },
];

var nextId = 6;

var AddPlayerForm = React.createClass({
  propTypes: {
    onAdd: React.PropTypes.func.isRequired,
  },

  getInitialState: function() {
    return {
      name: "",
    };
  },

  onNameChange: function(e) {
    this.setState({name: e.target.value});
  },

  onSubmit: function(e) {
    e.preventDefault();

    this.props.onAdd(this.state.name);
    this.setState({name: ""});
  },

  render: function() {
    return (
      <div className="add-player-form">
        <form onSubmit={this.onSubmit}>
          <input type="text" value={this.state.name} onChange={this.onNameChange} />
          <input type="submit" value="Add Player" />
        </form>
      </div>
    );
  }
});

function Header(props) {
  return (
    <div className="header">
      <h1>{props.title}</h1>
    </div>
  );
}

Header.propTypes = {
  title: React.PropTypes.string.isRequired,
  players: React.PropTypes.array.isRequired,
};

function Counter(props) {
  return (
    <div className="counter">
      <button className="counter-action decrement" onClick={function() {props.onChange(-1);}} > - </button>
      <div className="counter-score"> {props.score} </div>
      <button className="counter-action increment" onClick={function() {props.onChange(1);}}> + </button>
    </div>
  );
}

Counter.propTypes = {
  score: React.PropTypes.number.isRequired,
  onChange: React.PropTypes.func.isRequired,
}

function Player(props) {
  return (
    <div className="player">
      <div className="player-name">
        <a className="remove-player" onClick={props.onRemove}>✖</a>
        {props.name}
      </div>
      <div className="player-score">
        <Counter score={props.score} onChange={props.onScoreChange} />
      </div>
    </div>
  );
}

Player.propTypes = {
  name: React.PropTypes.string.isRequired,
  score: React.PropTypes.number.isRequired,
  onScoreChange: React.PropTypes.func.isRequired,
  onRemove: React.PropTypes.func.isRequired,
};

var Application = React.createClass({
  propTypes: {
    title: React.PropTypes.string,
    initialPlayers: React.PropTypes.arrayOf(React.PropTypes.shape({
      name: React.PropTypes.string.isRequired,
      score: React.PropTypes.number.isRequired,
      id: React.PropTypes.number.isRequired,
    })).isRequired,
  },

  getDefaultProps: function() {
    return {
      title: "Foosball Scoreboard",
    }
  },

  getInitialState: function() {
    return {
      players: this.props.initialPlayers,
    };
  },

  onScoreChange: function(index, delta) {
    this.state.players[index].score += delta;
    this.setState(this.state);
  },

  onPlayerAdd: function(name) {
    this.state.players.push({
      name: name,
      score: 0,
      id: nextId,
    });
    this.setState(this.state);
    nextId += 1;
  },

  onRemovePlayer: function(index) {
    this.state.players.splice(index, 1);
    this.setState(this.state);
  },

  // reorderPlayers

  render: function() {
    return (
      <div className="scoreboard">
        <Header title={this.props.title} players={this.state.players} />

        <div className="players">
          {this.state.players.map(function(player, index) {
            return (
              <Player
                onScoreChange={function(delta) {this.onScoreChange(index ,delta)}.bind(this)}
                onRemove={function() {this.onRemovePlayer(index)}.bind(this)}
                name={player.name}
                score={player.score}
                key={player.id} />
            );
          }.bind(this))}
        </div>
        <AddPlayerForm onAdd={this.onPlayerAdd} />
      </div>
    );
  }
});

ReactDOM.render(<Application initialPlayers={PLAYERS}/>, document.getElementById('container'));
</code>```

答:
Just use Array.sort function in the onScoreChange function to sort the array everytime score is changed like this

```<code>onScoreChange: function(index, delta) {
    let players = [...this.state.players]

    players[index] = Object.assign({},players[index])
    // Or if you can use object spread then: players[index] = {...players[index]}
    players[index].score += delta;

    // Use Array.sort function like this
    players.sort((a,b) => b.score - a.score)
    this.setState({players});
  },
</code>```

Body:
I have built a React app that is a scoreboard.  You can add and remove points from a player's score using the + and - symbols on the right side. Currently, the players are sorted by their id.  I would like to figure out a way to sort my players based on their current score.

For instance, if one player gets a higher score than another player above them, that player would move up to the row they are ranked at.  I have made a Codepen displaying my project.  If anyone has any idea how to sort the players after the onScoreChange function is run I would really appreciate it!

CodePen

body {
  background: #d5d5d5;
  font-family: arial;
  color: #FAFAFA;
  text-transform: uppercase;
}

.scoreboard {
  background: #333;
  width: 700px;
  margin: 70px auto;
  box-shadow: 0 4px 0px #333;
  border-radius: 15px;

}

.header {
  padding: 5px 10px;
  text-align: center;
  display: flex;
  align-items: center;
  background-color: #222;
  border-radius: 15px 15px 0 0;
  border-bottom: solid 2px #444;
}

.header h1 {
  flex-grow: 1;
  font-size: 1.5em;
  letter-spacing: 3px;
  font-weight: normal;
}

.player {
  display: flex;
  font-size: 1.2em;
  border-bottom: solid 2px #444;
  letter-spacing: 2px;
}

  .remove-player {
    visibility: hidden;
    margin-right: 10px;
    color: #e57373;
    cursor: pointer;
  }

  .player-name:hover .remove-player {
    visibility: visible;
  }

  .player-name {
    flex-grow: 1;
    padding: 20px 10px 10px 10px;
  }

  .player-score {
    width: 190px;
    background: blue;
  }

  .counter {
    display: flex;
  }

  .counter-action {
    border: none;
    font-weight: bold;
    color: #FAFAFA;
    display: block;
    padding: 20px 20px;
    cursor: pointer;
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
  }

  .counter-action.increment {
    background: #66BB6A;
  }

  .counter-action.increment:hover {
    background: #549d59;
    cursor: pointer;
  }

  .counter-action.decrement {
    background: #ef5350;
  }

  .counter-action.decrement:hover {
    background: #c44442;
    cursor: pointer;
  }

  .counter-score {
    flex-grow: 1;
    background: #2b2b2b;
    color: #FAFAFA;
    text-align: center;
    font-family: monospace;
    padding: 10px;
    font-size: 2em;
  }

.add-player-form form {
  display: flex;
  background-color: #222;
  border-radius: 0 0 20px 20px
}

  .add-player-form input[type=text] {
    flex-grow: 1;
    border-width: 0 0 1px 0;
    margin: 15px 10px 15px 15px;
    padding: 10px;
    border-radius: 5px;
    background-color: #333;
    border-style: none;
    text-shadow: none;
    text-transform: uppercase;
    color: #999;
    letter-spacing: 2px;
    outline: none;
  }

  .add-player-form input[type=text]::-webkit-input-placeholder{
    color: #666;
    letter-spacing: 2px;
  }

  .add-player-form input[type=text]:focus{
    background-color: #444;
  }

  .add-player-form input[type=submit] {
    display: block;
    font-size: .6em;
    margin: 15px 15px 15px 0;
    padding: 10px;
    background-color: #333;
    border-radius: 5px;
    border: none;
    color: #999;
    letter-spacing: 2px;
    font-weight: bold;
    text-shadow: none;
    text-transform: uppercase;
  }

  .add-player-form input[type=submit]:hover{
    background: #4b71b5;
    color: #fafafa;
    cursor: pointer;
  }

var PLAYERS = [
  {
    name: "Mary Miller",
    score: 22,
    id: 1,
  },
  {
    name: "Ellie Grace",
    score: 20,
    id: 2,
  },
  {
    name: "Ben Pine",
    score: 18,
    id: 3,
  },
  {
    name: "Rachel Slater",
    score: 17,
    id: 4,
  },
  {
    name: "Lisette Ven",
    score: 10,
    id: 5,
  },
];

var nextId = 6;

var AddPlayerForm = React.createClass({
  propTypes: {
    onAdd: React.PropTypes.func.isRequired,
  },

  getInitialState: function() {
    return {
      name: "",
    };
  },

  onNameChange: function(e) {
    this.setState({name: e.target.value});
  },

  onSubmit: function(e) {
    e.preventDefault();

    this.props.onAdd(this.state.name);
    this.setState({name: ""});
  },

  render: function() {
    return (

        <form onSubmit={this.onSubmit}>
          <input type="text" value={this.state.name} onChange={this.onNameChange} />
          <input type="submit" value="Add Player" />
        </form>

    );
  }
});

function Header(props) {
  return (

{props.title}

  );
}

Header.propTypes = {
  title: React.PropTypes.string.isRequired,
  players: React.PropTypes.array.isRequired,
};

function Counter(props) {
  return (

      <button className="counter-action decrement" onClick={function() {props.onChange(-1);}} > - </button>

 {props.score}

      <button className="counter-action increment" onClick={function() {props.onChange(1);}}> + </button>

  );
}

Counter.propTypes = {
  score: React.PropTypes.number.isRequired,
  onChange: React.PropTypes.func.isRequired,
}

function Player(props) {
  return (

        ✖
        {props.name}

        <Counter score={props.score} onChange={props.onScoreChange} />

  );
}

Player.propTypes = {
  name: React.PropTypes.string.isRequired,
  score: React.PropTypes.number.isRequired,
  onScoreChange: React.PropTypes.func.isRequired,
  onRemove: React.PropTypes.func.isRequired,
};

var Application = React.createClass({
  propTypes: {
    title: React.PropTypes.string,
    initialPlayers: React.PropTypes.arrayOf(React.PropTypes.shape({
      name: React.PropTypes.string.isRequired,
      score: React.PropTypes.number.isRequired,
      id: React.PropTypes.number.isRequired,
    })).isRequired,
  },

  getDefaultProps: function() {
    return {
      title: "Foosball Scoreboard",
    }
  },

  getInitialState: function() {
    return {
      players: this.props.initialPlayers,
    };
  },

  onScoreChange: function(index, delta) {
    this.state.players[index].score += delta;
    this.setState(this.state);
  },

  onPlayerAdd: function(name) {
    this.state.players.push({
      name: name,
      score: 0,
      id: nextId,
    });
    this.setState(this.state);
    nextId += 1;
  },

  onRemovePlayer: function(index) {
    this.state.players.splice(index, 1);
    this.setState(this.state);
  },

  // reorderPlayers

  render: function() {
    return (

          {this.state.players.map(function(player, index) {
            return (
              <Player
                onScoreChange={function(delta) {this.onScoreChange(index ,delta)}.bind(this)}
                onRemove={function() {this.onRemovePlayer(index)}.bind(this)}
                name={player.name}
                score={player.score}
                key={player.id} />
            );
          }.bind(this))}

        <AddPlayerForm onAdd={this.onPlayerAdd} />

    );
  }
});

ReactDOM.render(<Application initialPlayers={PLAYERS}/>, document.getElementById('container'));

Body:
Just use Array.sort function in the onScoreChange function to sort the array everytime score is changed like this

onScoreChange: function(index, delta) {
    let players = [...this.state.players]

    players[index] = Object.assign({},players[index])
    // Or if you can use object spread then: players[index] = {...players[index]}
    players[index].score += delta;

    // Use Array.sort function like this
    players.sort((a,b) => b.score - a.score)
    this.setState({players});
  },


问:
jQuery - unbind and rebind hover on click
I want to unbind and rebind the hover styling when an item is clicked.

```<code>$('.merc-list img').mouseover(function(){
    if ($(this).hasClass('with-grayscale')){
        $(this).removeClass('with-grayscale');
    }
    $(this).css('transform', 'scale(' + 1.3 + ')');
    $('.merc-list img').not(this).each(function(){
        $(this).addClass('with-grayscale');
        $(this).css('transform', 'scale(' + 0.9 + ')');
    });
});

$('.merc-list img').mouseleave(function(){
    if ($(this).hasClass('with-grayscale')){
        $(this).removeClass('with-grayscale');
    }
    $(this).css('transform', 'scale(' + 1.0 + ')');
    $('.merc-list img').not(this).each(function(){
        if ($(this).hasClass('with-grayscale')){
            $(this).removeClass('with-grayscale');
        }
        $(this).css('transform', 'scale(' + 1.0 + ')');
    });
});

$('.merc-list img').on('click', function(){
    if ($(this).hasClass('selected')){
        $(this).bind('mouseover mouseleave'); // rebind for clicked image
        $(this).removeClass('selected');
        $(this).css('transform', 'scale(' + 1.0 + ')');
        $('.merc-list img').not(this).each(function(){
            $(this).bind('mouseover mouseleave'); // rebind for every other image except clicked image
            $(this).removeClass('with-grayscale');
            $(this).css('transform', 'scale(' + 1.0 + ')');
        });
    }else{
        $(this).unbind('mouseover mouseleave'); // unbind for clicked image
        if ($(this).hasClass('with-grayscale')){
            $(this).removeClass('with-grayscale');
        }
        $(this).addClass('selected');
        $(this).css('transform', 'scale(' + 1.3 + ')');
        $('.merc-list img').not(this).each(function(){
            $(this).unbind('mouseover mouseleave'); // unbind for every other image except clicked image
            $(this).addClass('with-grayscale');
            if ($(this).hasClass('selected')){
                $(this).removeClass('selected');
            }
            $(this).css('transform', 'scale(' + 0.9 + ')');
        });
    }
});
</code>```

So when there is no hover or click event, this is how it originally looks like:

When I hover over it, all the other images shrink and become gray and the element that is hovered over becomes larger and has no grayscale (in this example I'm hovering over Phantom)

Now when I click Phantom, I want to freeze every mouseover and mouseleave on each of these mercs. However, when I unclick Phantom, for example, I want to unfreeze everything and go back to its original hover animation.

As you can see in my code, I am unbinding and rebinding the mouseover and mouseenter functionalities, but it's not rebinding (it does not go back to its original hover animations).

Thanks for any help!

答:
Instead of binding and rebinding, I'd use a flag.  A flag is just a boolean that tells your program whether or not to do a certain thing.  So, in this case we will have a flag that will indicate whether or not the mouseenter and mouseleave events should work.

Example:

var shouldHover = true;

$('div').mouseenter(function () {
  if (shouldHover) {
    $(this).css({'background':'#4286f4'})
  }
});

$('div').mouseleave(function () {
  if (shouldHover) {
    $(this).css({'background':'#e3ffad'})
  }
});

$('div').click(function () {
  shouldHover = false;
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>div {
  display:inline-block;
  width:100px;
  height:100px;
  background:#e3ffad;
  text-align:center;
  line-height:100px;
  font-weight:bold;
  font-size:100px;
  cursor:pointer;
}</code>```

1

2

3
```

Body:
I want to unbind and rebind the hover styling when an item is clicked.

$('.merc-list img').mouseover(function(){
    if ($(this).hasClass('with-grayscale')){
        $(this).removeClass('with-grayscale');
    }
    $(this).css('transform', 'scale(' + 1.3 + ')');
    $('.merc-list img').not(this).each(function(){
        $(this).addClass('with-grayscale');
        $(this).css('transform', 'scale(' + 0.9 + ')');
    });
});

$('.merc-list img').mouseleave(function(){
    if ($(this).hasClass('with-grayscale')){
        $(this).removeClass('with-grayscale');
    }
    $(this).css('transform', 'scale(' + 1.0 + ')');
    $('.merc-list img').not(this).each(function(){
        if ($(this).hasClass('with-grayscale')){
            $(this).removeClass('with-grayscale');
        }
        $(this).css('transform', 'scale(' + 1.0 + ')');
    });
});

$('.merc-list img').on('click', function(){
    if ($(this).hasClass('selected')){
        $(this).bind('mouseover mouseleave'); // rebind for clicked image
        $(this).removeClass('selected');
        $(this).css('transform', 'scale(' + 1.0 + ')');
        $('.merc-list img').not(this).each(function(){
            $(this).bind('mouseover mouseleave'); // rebind for every other image except clicked image
            $(this).removeClass('with-grayscale');
            $(this).css('transform', 'scale(' + 1.0 + ')');
        });
    }else{
        $(this).unbind('mouseover mouseleave'); // unbind for clicked image
        if ($(this).hasClass('with-grayscale')){
            $(this).removeClass('with-grayscale');
        }
        $(this).addClass('selected');
        $(this).css('transform', 'scale(' + 1.3 + ')');
        $('.merc-list img').not(this).each(function(){
            $(this).unbind('mouseover mouseleave'); // unbind for every other image except clicked image
            $(this).addClass('with-grayscale');
            if ($(this).hasClass('selected')){
                $(this).removeClass('selected');
            }
            $(this).css('transform', 'scale(' + 0.9 + ')');
        });
    }
});

So when there is no hover or click event, this is how it originally looks like:

When I hover over it, all the other images shrink and become gray and the element that is hovered over becomes larger and has no grayscale (in this example I'm hovering over Phantom)

Now when I click Phantom, I want to freeze every mouseover and mouseleave on each of these mercs. However, when I unclick Phantom, for example, I want to unfreeze everything and go back to its original hover animation.

As you can see in my code, I am unbinding and rebinding the mouseover and mouseenter functionalities, but it's not rebinding (it does not go back to its original hover animations).

Thanks for any help!

Body:
Instead of binding and rebinding, I'd use a flag.  A flag is just a boolean that tells your program whether or not to do a certain thing.  So, in this case we will have a flag that will indicate whether or not the mouseenter and mouseleave events should work.

Example:

var shouldHover = true;

$('div').mouseenter(function () {
  if (shouldHover) {
    $(this).css({'background':'#4286f4'})
  }
});

$('div').mouseleave(function () {
  if (shouldHover) {
    $(this).css({'background':'#e3ffad'})
  }
});

$('div').click(function () {
  shouldHover = false;
});

div {
  display:inline-block;
  width:100px;
  height:100px;
  background:#e3ffad;
  text-align:center;
  line-height:100px;
  font-weight:bold;
  font-size:100px;
  cursor:pointer;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div>1</div>
<div>2</div>
<div>3</div>


问:
Collect all values from nested array row of specific key
Need to create a list that consists of all values stored in the array row of a specific key (product_id). Currently, doing a print_r of my $bestsellers variable produces the following array:

```<code>Array
  (
    [0] => stdClass Object
        (
            [product_id] => 178
            [order_item_qty] => 9
        )

    [1] => stdClass Object
        (
            [product_id] => 233
            [order_item_qty] => 4
        )

    [2] => stdClass Object
        (
            [product_id] => 179
            [order_item_qty] => 1
        )
  )
</code>```

Other SO answers led me to try:

```<code>$ids = array_column($bestsellers, 'product_id');
</code>```

...but that produced an empty array, I guess because the row I’m trying to grab is nested in there? With that in mind I tried

```<code>foreach($bestsellers as $bestseller) {
    $ids = array_column($bestsellers, 'product_id');
}
</code>```

...which produced no result at all.
Hopefully someone can help clue me in as to where I’m going wrong. Thanks!

答:
The nested values are objects, not arrays (can't you see stdClass Object in the output?). array_column is for 2-dimensional arrays. You need to access the properties using object syntax.

```<code>$ids = array_map(function($x) { return $x->product_id; }, $bestsellers);
</code>```

Body:
Need to create a list that consists of all values stored in the array row of a specific key (product_id). Currently, doing a print_r of my $bestsellers variable produces the following array:

Array
  (
    [0] => stdClass Object
        (
            [product_id] => 178
            [order_item_qty] => 9
        )

    [1] => stdClass Object
        (
            [product_id] => 233
            [order_item_qty] => 4
        )

    [2] => stdClass Object
        (
            [product_id] => 179
            [order_item_qty] => 1
        )
  )

Other SO answers led me to try:

$ids = array_column($bestsellers, 'product_id');

...but that produced an empty array, I guess because the row I’m trying to grab is nested in there? With that in mind I tried

foreach($bestsellers as $bestseller) {
    $ids = array_column($bestsellers, 'product_id');
}

...which produced no result at all.
Hopefully someone can help clue me in as to where I’m going wrong. Thanks!

Body:
The nested values are objects, not arrays (can't you see stdClass Object in the output?). array_column is for 2-dimensional arrays. You need to access the properties using object syntax.

$ids = array_map(function($x) { return $x->product_id; }, $bestsellers);


问:
Add the multiple regression equation to a segmented graph
I found this example helpful from RDocumentation and I'd like to explore it further. The code below was adapted from https://www.rdocumentation.org/packages/segmented/versions/0.5-2.1/topics/plot.segmented

```<code>GDD<- c(221.2765957446810000,
    309.2198581560280000,
    431.2056737588650000,
    483.6879432624110000,
    553.1914893617020000)

biom<-c(0.0000000001000000,
        0.8510638297872340,
        5.9574468085106400,
        15.3191489361702000,
        22.1276595744681000)
o<- glm(biom~GDD, family = gaussian); o
o.seg<-segmented(o, ~GDD) #single segmented covariate and one breakpoint:'psi' can be omitted
par(mfrow=c(2,1))
plot(o.seg, conf.level=0.95, shade=TRUE)
points(o.seg, link=FALSE, col=2)
</code>```

I would like to find the equation that created the black segmented line and to find the joint point (red). Please see how I can do that. Any help is much appreciated.

答:
o.seg tells you everything you want to know. "Estimated Break-Point(s):" tells you the x-value (GDD value) of the breakpoint (red point). It is psi1.GDD = 391.3.

o.seg$coefficients tells you the line equation, which is roughly -2.14 + 0.0097*GDD*(GDD < psi1.GDD) + 0.12*GDD*(GDD >= psi1.GDD).

Body:
I found this example helpful from RDocumentation and I'd like to explore it further. The code below was adapted from https://www.rdocumentation.org/packages/segmented/versions/0.5-2.1/topics/plot.segmented

GDD<- c(221.2765957446810000,
    309.2198581560280000,
    431.2056737588650000,
    483.6879432624110000,
    553.1914893617020000)

biom<-c(0.0000000001000000,
        0.8510638297872340,
        5.9574468085106400,
        15.3191489361702000,
        22.1276595744681000)
o<- glm(biom~GDD, family = gaussian); o
o.seg<-segmented(o, ~GDD) #single segmented covariate and one breakpoint:'psi' can be omitted
par(mfrow=c(2,1))
plot(o.seg, conf.level=0.95, shade=TRUE)
points(o.seg, link=FALSE, col=2)

I would like to find the equation that created the black segmented line and to find the joint point (red). Please see how I can do that. Any help is much appreciated.


问:
How to transfer time from one view controller to another?
in my current project I have implemented a timer on one view.
When I click the button that leads to the next view, I want it to show the time the previous view had at the end.

This is my current code:

```<code>import UIKit

class ViewController2: UIViewController, UITableViewDataSource, UITableViewDelegate {

@IBOutlet weak var myTableView: UITableView!

@IBOutlet weak var labelMinute: UILabel!
@IBOutlet weak var labelHour: UILabel!
@IBOutlet weak var labelSecond: UILabel!

weak var timer: Timer?
var startTime: Double = 0
var time: Double = 0
var elapsed: Double = 0
var status: Bool = false

var psgTextField: UITextField?
var emTextField: UITextField?

public var passengers2 = [""]

public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return passengers2.count
}

public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell2 = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "cell2")
    cell2.textLabel?.text = passengers2[indexPath.row]

    return (cell2)
}

@objc func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath){

    if editingStyle == UITableViewCellEditingStyle.delete {

        let alertController = UIAlertController(title: "Do you really want to leave?",
                                                message: nil,
                                                preferredStyle: .alert)

        alertController.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))

        alertController.addAction(UIAlertAction(title: "Leave", style: .default, handler: { action in self.passengers2.remove(at: indexPath.row)
            self.myTableView.deleteRows(at: [indexPath], with: .automatic)
        } ))

        self.present(alertController, animated: true)

    }
}

override func viewDidLoad() {
    super.viewDidLoad()

    startTime = Date().timeIntervalSinceReferenceDate - elapsed
    timer = Timer.scheduledTimer(timeInterval: 0.01, target: self, selector: #selector(updateCounter), userInfo: nil, repeats: true)

    status = true

}

@objc func updateCounter() {

    // Calculate total time since timer started in seconds
    time = Date().timeIntervalSinceReferenceDate - startTime

    // Calculate minutes
    let minutes = UInt8(time / 60.0)
    time -= (TimeInterval(minutes) * 60)

    // Calculate seconds
    let hours = UInt8(time / 3600)
    time -= TimeInterval(hours)

    let seconds = UInt8(time)
    time -= TimeInterval(seconds)

    // Format time vars with leading zero
    let strMinutes = String(format: "%02d", minutes)
    let strHour = String(format: "%02d", hours)
    let strSecond = String(format: "%02d", seconds)

    // Add time vars to relevant labels
    labelMinute.text = strMinutes
    labelHour.text = strHour
    labelSecond.text = strSecond

}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    let thirdController = segue.destination as! ViewController3
    thirdController.timeHour.text = labelHour.text

    let fourthController = segue.destination as! ViewController3
    fourthController.timeMinute.text = labelMinute.text
}
}
</code>```

Without the last "override" function, the timer on my first view works perfectly, but for some reason it won't transfer the time to the labels on my second view ("timeHour", "timeMinute").

Xcode gives me the errorThread 1: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0), but the cases I found in the internet were different from mine.

Does someone know where the problem is?

答:
Here is my thought:
1. Did you setup your segue correctly?
2. Passing data with segue, requiring you to pass the data and handle it correcly in the view event.

Some example code might look like this:

```<code>override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.

        if (segue.identifier == "YourSegueIdentifier") {
            let destinationVC = segue.destination as! YourSegueViewController;

            destinationVC.passedData = "some-data-to-pass";
        }
    }
</code>```

While on you receiving view controller, handle it on your viewDidLoad function, e.g

```<code>var passedData: String!;

func viewDidLoad() {
    self.txtName.text = passedData;
}
</code>```

Body:
in my current project I have implemented a timer on one view.
When I click the button that leads to the next view, I want it to show the time the previous view had at the end.

This is my current code:

import UIKit

class ViewController2: UIViewController, UITableViewDataSource, UITableViewDelegate {

@IBOutlet weak var myTableView: UITableView!

@IBOutlet weak var labelMinute: UILabel!
@IBOutlet weak var labelHour: UILabel!
@IBOutlet weak var labelSecond: UILabel!

weak var timer: Timer?
var startTime: Double = 0
var time: Double = 0
var elapsed: Double = 0
var status: Bool = false

var psgTextField: UITextField?
var emTextField: UITextField?

public var passengers2 = [""]

public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return passengers2.count
}

public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell2 = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "cell2")
    cell2.textLabel?.text = passengers2[indexPath.row]

    return (cell2)
}

@objc func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath){

    if editingStyle == UITableViewCellEditingStyle.delete {

        let alertController = UIAlertController(title: "Do you really want to leave?",
                                                message: nil,
                                                preferredStyle: .alert)

        alertController.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))

        alertController.addAction(UIAlertAction(title: "Leave", style: .default, handler: { action in self.passengers2.remove(at: indexPath.row)
            self.myTableView.deleteRows(at: [indexPath], with: .automatic)
        } ))

        self.present(alertController, animated: true)

    }
}

override func viewDidLoad() {
    super.viewDidLoad()

    startTime = Date().timeIntervalSinceReferenceDate - elapsed
    timer = Timer.scheduledTimer(timeInterval: 0.01, target: self, selector: #selector(updateCounter), userInfo: nil, repeats: true)

    status = true

}

@objc func updateCounter() {

    // Calculate total time since timer started in seconds
    time = Date().timeIntervalSinceReferenceDate - startTime

    // Calculate minutes
    let minutes = UInt8(time / 60.0)
    time -= (TimeInterval(minutes) * 60)

    // Calculate seconds
    let hours = UInt8(time / 3600)
    time -= TimeInterval(hours)

    let seconds = UInt8(time)
    time -= TimeInterval(seconds)

    // Format time vars with leading zero
    let strMinutes = String(format: "%02d", minutes)
    let strHour = String(format: "%02d", hours)
    let strSecond = String(format: "%02d", seconds)

    // Add time vars to relevant labels
    labelMinute.text = strMinutes
    labelHour.text = strHour
    labelSecond.text = strSecond

}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    let thirdController = segue.destination as! ViewController3
    thirdController.timeHour.text = labelHour.text

    let fourthController = segue.destination as! ViewController3
    fourthController.timeMinute.text = labelMinute.text
}
}

Without the last "override" function, the timer on my first view works perfectly, but for some reason it won't transfer the time to the labels on my second view ("timeHour", "timeMinute").

Xcode gives me the errorThread 1: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0), but the cases I found in the internet were different from mine.

Does someone know where the problem is?

Body:
Here is my thought:
1. Did you setup your segue correctly?
2. Passing data with segue, requiring you to pass the data and handle it correcly in the view event.

Some example code might look like this:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.

        if (segue.identifier == "YourSegueIdentifier") {
            let destinationVC = segue.destination as! YourSegueViewController;

            destinationVC.passedData = "some-data-to-pass";
        }
    }

While on you receiving view controller, handle it on your viewDidLoad function, e.g

var passedData: String!;

func viewDidLoad() {
    self.txtName.text = passedData;
}


问:
Create table in c# with values from database
I am creating an application for my coursework but there is one thing I cannot figure out how to complete. This is I need to create a table in winforms with data from a database.

The table needs to have days of week on columns and times on rows. I wan't to get the data from a database and fill in the table. This table is for patient appointments in a doctors surgery.

答:
It sounds like you need to focus on your SQL Server database first, then your C# form second.

Setup your table so it has a form similar to this:

```<code> select
 getdate() as Curr_Date
,datename(dw,getdate()) as Weekday_Name
,datepart(dw,getdate()) as Weekday_Number
,case when datepart(dw,getdate()) = 1 then 'Your Column Value Goes Here' end as Sunday
,case when datepart(dw,getdate()) = 2 then 'Your Column Value Goes Here' end as Monday
,case when datepart(dw,getdate()) = 3 then 'Your Column Value Goes Here' end as Tuesday
,case when datepart(dw,getdate()) = 4 then 'Your Column Value Goes Here' end as Wednesday
,case when datepart(dw,getdate()) = 5 then 'Your Column Value Goes Here' end as Thursday
,case when datepart(dw,getdate()) = 6 then 'Your Column Value Goes Here' end as Friday
,case when datepart(dw,getdate()) = 7 then 'Your Column Value Goes Here' end as Saturday
</code>```

You will replace getdate() with the actual timestamp of your true data.
You will replace 'Your Column Value Goes Here' with the actual value of your data.

Lastly, you will want your C# form to capture the specific cells.

I just read your post again.  It looks like you want the time in the row?  If so, try something like this:

```<code> select
 getdate() as Curr_Date
,datename(dw,getdate()) as Weekday_Name
,datepart(dw,getdate()) as Weekday_Number
,case when datepart(dw,getdate()) = 1 then cast(getdate() as time) end as Sunday
,case when datepart(dw,getdate()) = 2 then cast(getdate() as time) end as Monday
,case when datepart(dw,getdate()) = 3 then cast(getdate() as time) end as Tuesday
,case when datepart(dw,getdate()) = 4 then cast(getdate() as time) end as Wednesday
,case when datepart(dw,getdate()) = 5 then cast(getdate() as time) end as Thursday
,case when datepart(dw,getdate()) = 6 then cast(getdate() as time) end as Friday
,case when datepart(dw,getdate()) = 7 then cast(getdate() as time) end as Saturday
</code>```

Because I'm feeling generous and actually enjoy writing SQL...

```<code>create table Schedule
(
 Person varchar(15)
,Appointment datetime
)
;
insert into Schedule values
('John Doe','2017-11-20 9:25:00'),
('Jane Doe','2017-11-22 9:15:00'),
('Michael','2017-11-24 9:25:00'),
('Sam','2017-11-26 9:15:00')
;

create table Time_Table
(
Start_Time time,
End_Time time,
Time_Name Varchar(20)
)
;
insert into Time_Table values
 ('9:00' , '9:10'  , '9:10 - 9:10'  )
,('9:10' , '9:20'  , '9:10 - 9:20'  )
,('9:20' , '9:30'  , '9:20 - 9:30'  )
,('9:30' , '9:40'  , '9:30 - 9:40'  )
,('9:40' , '9:50'  , '9:40 - 9:50'  )
,('9:50' , '10:00' , '9:50 - 10:00' )
;

 select
 a.Time_Name
,max(case when datepart(dw,b.Appointment) = 1 then b.Person end) as Sunday
,max(case when datepart(dw,b.Appointment) = 2 then b.Person end) as Monday
,max(case when datepart(dw,b.Appointment) = 3 then b.Person end) as Tuesday
,max(case when datepart(dw,b.Appointment) = 4 then b.Person end) as Wednesday
,max(case when datepart(dw,b.Appointment) = 5 then b.Person end) as Thursday
,max(case when datepart(dw,b.Appointment) = 6 then b.Person end) as Friday
,max(case when datepart(dw,b.Appointment) = 7 then b.Person end) as Saturday
from Time_Table a
LEFT JOIN Schedule b ON cast(b.Appointment as time) between a.Start_Time and a.End_Time
group by
a.Time_Name
order by a.Time_Name
</code>```

This is the SQL Server version of your assignment.  The point of your assignment clearly has more to do with learning the fundamentals of interacting with databases.  I am not going to build a CRUD app for you on here, but this should at least give you a very solid foundation to start from.

Body:
It sounds like you need to focus on your SQL Server database first, then your C# form second.

Setup your table so it has a form similar to this:

 select
 getdate() as Curr_Date
,datename(dw,getdate()) as Weekday_Name
,datepart(dw,getdate()) as Weekday_Number
,case when datepart(dw,getdate()) = 1 then 'Your Column Value Goes Here' end as Sunday
,case when datepart(dw,getdate()) = 2 then 'Your Column Value Goes Here' end as Monday
,case when datepart(dw,getdate()) = 3 then 'Your Column Value Goes Here' end as Tuesday
,case when datepart(dw,getdate()) = 4 then 'Your Column Value Goes Here' end as Wednesday
,case when datepart(dw,getdate()) = 5 then 'Your Column Value Goes Here' end as Thursday
,case when datepart(dw,getdate()) = 6 then 'Your Column Value Goes Here' end as Friday
,case when datepart(dw,getdate()) = 7 then 'Your Column Value Goes Here' end as Saturday

You will replace getdate() with the actual timestamp of your true data.
You will replace 'Your Column Value Goes Here' with the actual value of your data.

Lastly, you will want your C# form to capture the specific cells.

I just read your post again.  It looks like you want the time in the row?  If so, try something like this:

 select
 getdate() as Curr_Date
,datename(dw,getdate()) as Weekday_Name
,datepart(dw,getdate()) as Weekday_Number
,case when datepart(dw,getdate()) = 1 then cast(getdate() as time) end as Sunday
,case when datepart(dw,getdate()) = 2 then cast(getdate() as time) end as Monday
,case when datepart(dw,getdate()) = 3 then cast(getdate() as time) end as Tuesday
,case when datepart(dw,getdate()) = 4 then cast(getdate() as time) end as Wednesday
,case when datepart(dw,getdate()) = 5 then cast(getdate() as time) end as Thursday
,case when datepart(dw,getdate()) = 6 then cast(getdate() as time) end as Friday
,case when datepart(dw,getdate()) = 7 then cast(getdate() as time) end as Saturday

Because I'm feeling generous and actually enjoy writing SQL...

create table Schedule
(
 Person varchar(15)
,Appointment datetime
)
;
insert into Schedule values
('John Doe','2017-11-20 9:25:00'),
('Jane Doe','2017-11-22 9:15:00'),
('Michael','2017-11-24 9:25:00'),
('Sam','2017-11-26 9:15:00')
;

create table Time_Table
(
Start_Time time,
End_Time time,
Time_Name Varchar(20)
)
;
insert into Time_Table values
 ('9:00' , '9:10'  , '9:10 - 9:10'  )
,('9:10' , '9:20'  , '9:10 - 9:20'  )
,('9:20' , '9:30'  , '9:20 - 9:30'  )
,('9:30' , '9:40'  , '9:30 - 9:40'  )
,('9:40' , '9:50'  , '9:40 - 9:50'  )
,('9:50' , '10:00' , '9:50 - 10:00' )
;

 select
 a.Time_Name
,max(case when datepart(dw,b.Appointment) = 1 then b.Person end) as Sunday
,max(case when datepart(dw,b.Appointment) = 2 then b.Person end) as Monday
,max(case when datepart(dw,b.Appointment) = 3 then b.Person end) as Tuesday
,max(case when datepart(dw,b.Appointment) = 4 then b.Person end) as Wednesday
,max(case when datepart(dw,b.Appointment) = 5 then b.Person end) as Thursday
,max(case when datepart(dw,b.Appointment) = 6 then b.Person end) as Friday
,max(case when datepart(dw,b.Appointment) = 7 then b.Person end) as Saturday
from Time_Table a
LEFT JOIN Schedule b ON cast(b.Appointment as time) between a.Start_Time and a.End_Time
group by
a.Time_Name
order by a.Time_Name

This is the SQL Server version of your assignment.  The point of your assignment clearly has more to do with learning the fundamentals of interacting with databases.  I am not going to build a CRUD app for you on here, but this should at least give you a very solid foundation to start from.


问:
FileNotFoundException in onActivityResult
I am trying to browse only two file-types: images or pdf.

Here is the source:

```<code>String[] permissions = new String[]{Manifest.permission.READ_EXTERNAL_STORAGE};
            myPermissions =new MyPermissions(TestDialog.this, 0, permissions);
            MyPermissions.EventHandler permHandler = new MyPermissions.EventHandler() {
                @Override
                public void handle() {

                    Intent intent = new Intent();
                    intent.setAction(Intent.ACTION_GET_CONTENT);
                    intent.setType("application/pdf");
                    intent.setType("image/jpeg");
                    startActivityForResult(intent, 0);
                }
            };

            myPermissions.doIfHasPermissions(permHandler);
</code>```

Here is a my onActivityResult source:

```<code> @Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == RESULT_OK) {
        String url = data.getData().getPath();
        File myFile = new File(url);
        Log.e("base64 ", getStringFile(myFile));

    }
    super.onActivityResult(requestCode, resultCode, data);
}

public String getStringFile(File f) {
    InputStream inputStream = null;
    String encodedFile = "", lastVal;
    try {
        inputStream = new FileInputStream(f.getAbsolutePath());

        byte[] buffer = new byte[10240];//specify the size to allow
        int bytesRead;
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        Base64OutputStream output64 = new Base64OutputStream(output, Base64.DEFAULT);

        while ((bytesRead = inputStream.read(buffer)) != -1) {
            output64.write(buffer, 0, bytesRead);
        }
        output64.close();
        encodedFile = output.toString();
    } catch (FileNotFoundException e1) {
        e1.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    lastVal = encodedFile;
    return lastVal;
}
</code>```

I would like to convert the selected file to Base64, but I get a FileNotFoundException. Does anyone have any idea what am I doing wrong?

答:
I try to browse only two type files,images or pdf

Your code has nothing much to do with files. It uses ACTION_GET_CONTENT, which allows the user to choose a piece of content.

```<code>String url = data.getData().getPath();
</code>```

This line is useless, unless the Uri has a scheme of file. Most likely, it has a scheme of content.

Stop using File and FileInputStream. Instead, get an InputStream from a ContentResolver (from getContentResolver()) and its openInputStream() method. You can pass in the Uri, and you will get an InputStream regardless of whether the Uri scheme is file or content.

Also note that your app is likely to crash with an OutOfMemoryError, except for fairly small files, as you will not have enough heap space to perform this conversion.

Body:
I am trying to browse only two file-types: images or pdf.

Here is the source:

String[] permissions = new String[]{Manifest.permission.READ_EXTERNAL_STORAGE};
            myPermissions =new MyPermissions(TestDialog.this, 0, permissions);
            MyPermissions.EventHandler permHandler = new MyPermissions.EventHandler() {
                @Override
                public void handle() {

                    Intent intent = new Intent();
                    intent.setAction(Intent.ACTION_GET_CONTENT);
                    intent.setType("application/pdf");
                    intent.setType("image/jpeg");
                    startActivityForResult(intent, 0);
                }
            };

            myPermissions.doIfHasPermissions(permHandler);

Here is a my onActivityResult source:

 @Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == RESULT_OK) {
        String url = data.getData().getPath();
        File myFile = new File(url);
        Log.e("base64 ", getStringFile(myFile));

    }
    super.onActivityResult(requestCode, resultCode, data);
}

public String getStringFile(File f) {
    InputStream inputStream = null;
    String encodedFile = "", lastVal;
    try {
        inputStream = new FileInputStream(f.getAbsolutePath());

        byte[] buffer = new byte[10240];//specify the size to allow
        int bytesRead;
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        Base64OutputStream output64 = new Base64OutputStream(output, Base64.DEFAULT);

        while ((bytesRead = inputStream.read(buffer)) != -1) {
            output64.write(buffer, 0, bytesRead);
        }
        output64.close();
        encodedFile = output.toString();
    } catch (FileNotFoundException e1) {
        e1.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    lastVal = encodedFile;
    return lastVal;
}

I would like to convert the selected file to Base64, but I get a FileNotFoundException. Does anyone have any idea what am I doing wrong?

Body:
I try to browse only two type files,images or pdf

Your code has nothing much to do with files. It uses ACTION_GET_CONTENT, which allows the user to choose a piece of content.

String url = data.getData().getPath();

This line is useless, unless the Uri has a scheme of file. Most likely, it has a scheme of content.

Stop using File and FileInputStream. Instead, get an InputStream from a ContentResolver (from getContentResolver()) and its openInputStream() method. You can pass in the Uri, and you will get an InputStream regardless of whether the Uri scheme is file or content.

Also note that your app is likely to crash with an OutOfMemoryError, except for fairly small files, as you will not have enough heap space to perform this conversion.


答:
Have a look at

```<code>Uri uri = data.getData();
</code>```

Then try to log the value of uri.toString().

You will see that it starts with "content//....".

Do not try to find a file.

Instead of a FileInputStream use an InputStream.

```<code>InputStream inputStream = getContentResolver().openInputStream(uri);
</code>```

Title: FileNotFoundException in onActivityResult

Body:
Have a look at

Uri uri = data.getData();

Then try to log the value of uri.toString().

You will see that it starts with "content//....".

Do not try to find a file.

Instead of a FileInputStream use an InputStream.

InputStream inputStream = getContentResolver().openInputStream(uri);


问:
How to handle an exception inside a with block
So I was reading up on how to properly use the with keyword in python, and I could not figure out the best way to handle an exception that might occur within a with statement.  So I am writing a very simple script to write a value to a file.

```<code>json = loads(response.read())
try:
  with open(args.file, 'w') as t:
    try:
      t.write(json[TOKEN])
      print "Wrote token to {file!s}".format(file=args.file)
    except KeyError:
      print "Unable to find {token!s} in response".format(token=TOKEN)
except IOError as bad:
  print "Ran into an error while trying to open file {file!s}".format(file=args.file)
  print "{err!s}".format(bad.message)
</code>```

I want to be certain that if the KeyError is caught that the file will still close properly.

答:
I found the answer in the following document https://www.python.org/dev/peps/pep-0343/ that was in a link that was provided in the comments.

According to the link here is what happens when you use the with keyword.  In order to use the with keyword your expression must have an __enter__(self) and an __exit__(self, type, value, traceback) method.  Python will attempt to call the__enter__() method, followed by your block of code, and then run a finally with the __exit(self, type, value, traceback) method.  This will insure that that set up and tear down all get accomplished accordingly.  At least that is my understanding of the keyword.

Body:
So I was reading up on how to properly use the with keyword in python, and I could not figure out the best way to handle an exception that might occur within a with statement.  So I am writing a very simple script to write a value to a file.

json = loads(response.read())
try:
  with open(args.file, 'w') as t:
    try:
      t.write(json[TOKEN])
      print "Wrote token to {file!s}".format(file=args.file)
    except KeyError:
      print "Unable to find {token!s} in response".format(token=TOKEN)
except IOError as bad:
  print "Ran into an error while trying to open file {file!s}".format(file=args.file)
  print "{err!s}".format(bad.message)

I want to be certain that if the KeyError is caught that the file will still close properly.


问:
What is a NullReferenceException, and how do I fix it?
I have some code and when it executes, it throws a NullReferenceException, saying:

Object reference not set to an instance of an object.

What does this mean, and what can I do to fix this error?

答:
Literally the easiest way to fix a NullReferenceExeption has two ways.

If you have a GameObject for example with a script attached and a variable named rb (rigidbody) this variable will start with null when you start your game.
This is why you get a NullReferenceExeption because the computer does not have data stored in that variable.

I'll be using a RigidBody variable as an example.
We can add data really easily actually in a few ways:

Add a RigidBody to your object with AddComponent > Physics > Rigidbody
Then go into your script and type rb = GetComponent<Rigidbody>();
This line of code works best under your Start() or Awake() functions.

You can add a component programmatically and assign the variable at the same time with one line of code: rb = AddComponent<RigidBody>();

Further Notes: If you want Unity to add a component to your object and you might have forgotten to add one, you can type [RequireComponent(typeof(RigidBody))] above your class declaration (the space below all of your usings).

Enjoy and have fun making games!

ContentLicense: CC BY-SA 4.0


问:
Why is array_pop() returning the last item of the array instead of deleting it?
array_pop() is returning the last item of the array instead of deleting the last item of the array. Why is this happening?

```<code>$blam = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
$blam = explode("/", $blam);
$blam = array_pop($blam);
print_r($blam);
</code>```

You can test out the php here.

答:
Problem

You are doing the pop operation correctly, but immediately you are assigning the currently removed element to the variable $blam. So it iffectively makes that variable hold the value i.e the element that was popped.

Solution

Don't assign the value returned by pop function to the variable.

Code

```<code>$blam = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
$blam = explode("/", $blam);
array_pop($blam);
print_r($blam);
</code>```

Body:
array_pop() is returning the last item of the array instead of deleting the last item of the array. Why is this happening?

$blam = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
$blam = explode("/", $blam);
$blam = array_pop($blam);
print_r($blam);

You can test out the php here.

Body:
Problem

You are doing the pop operation correctly, but immediately you are assigning the currently removed element to the variable $blam. So it iffectively makes that variable hold the value i.e the element that was popped.

Solution

Don't assign the value returned by pop function to the variable.

Code

$blam = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
$blam = explode("/", $blam);
array_pop($blam);
print_r($blam);


问:
Python dict question. How to group similar strings?
```<code>for i in names:
    dict[i] = {'firstname': name[i]['firstname'],
               'lastname': name[i]['lastname']}
    print dict[0]['firstname'] # John
    print dict[0]['lastname'] # Doe

    # group similar lastnames, along with their firstnames
    # ...
return render_to_response('index.html', dict)
</code>```

I want to group names that end with similar last-names.
For example, the output should be:

```<code><html>
  <body>
    <h1> Doe </h1>
    <p> John, Jason, Peter </p>

    <h1> Avery </h1>
    <p> Kelly, Brittany </p>
  </body>
</html>
</code>```

The 'h1' tags are supposed to contain the last-names and the 'p' tags the first-names.

How should I do this?

答: You may also use groupby after you have sorted the names. You can see it here: http://docs.python.org/library/itertools.html#itertools.groupby</p>

Body:
for i in names:
    dict[i] = {'firstname': name[i]['firstname'],
               'lastname': name[i]['lastname']}
    print dict[0]['firstname'] # John
    print dict[0]['lastname'] # Doe

    # group similar lastnames, along with their firstnames
    # ...
return render_to_response('index.html', dict)

I want to group names that end with similar last-names.
For example, the output should be:

 Doe

 John, Jason, Peter

 Avery

 Kelly, Brittany

The 'h1' tags are supposed to contain the last-names and the 'p' tags the first-names.

How should I do this?


问:
Dictionary<string, double>get key from value (error)
I have a dictionary (Dictionary) and I want to get key value from (value) for instance:

suppose the dic contains:

```<code>"som": 12.2345
"roy": 2.677
"toy": 1.67445666777
</code>```

I want to get the roy key from searching about 2.677

I tried:

```<code>var keys = from entry in dic
                           where entry.Value == 2.677
                           select entry.Key;
</code>```

and also :

```<code>var myKey =dic.FirstOrDefault(x => x.Value.Contains(2.677)).Key;
</code>```

in each case I got the same error which is :
Error:  'double' does not contain a definition for 'Value' and no extension method 'Value' accepting a first argument of type 'double' could be found (are you missing a using directive or an assembly reference?)

any help would be appreciated

答:
You don't need Contains. Try this:

```<code>var myKey = dic.FirstOrDefault(item => item.Value == 2.677).Key;
</code>```

Note that FirstOrDefault method will return the exact first key or null if it doesn't find anything that matches the expression. Many keys can have the same Value property.

Body:
I have a dictionary (Dictionary) and I want to get key value from (value) for instance:

suppose the dic contains:

"som": 12.2345
"roy": 2.677
"toy": 1.67445666777

I want to get the roy key from searching about 2.677

I tried:

var keys = from entry in dic
                           where entry.Value == 2.677
                           select entry.Key;

and also :

var myKey =dic.FirstOrDefault(x => x.Value.Contains(2.677)).Key;

in each case I got the same error which is :
Error:  'double' does not contain a definition for 'Value' and no extension method 'Value' accepting a first argument of type 'double' could be found (are you missing a using directive or an assembly reference?)

any help would be appreciated

Body:
You don't need Contains. Try this:

var myKey = dic.FirstOrDefault(item => item.Value == 2.677).Key;

Note that FirstOrDefault method will return the exact first key or null if it doesn't find anything that matches the expression. Many keys can have the same Value property.


问:
I am getting errors trying to use INSERT INTO using VBA in Access, and can't fix it
With the following code I get

error 3061 (Too few parameters.  Expected 2)

```<code>Option Compare Database

Private Sub Command0_Click()
    Dim xls     As Excel.Application
    Dim wkb     As Excel.Workbook
    Dim wks     As Excel.Worksheet

    Set xls = New Excel.Application

    xls.Visible = True
    xls.UserControl = True

    Set wkb = xls.Workbooks.Open("link\Reliability Projects v5.xlsm", ReadOnly:=True, UpdateLinks:=False)
    Set wks = wkb.Worksheets("Projects")

    Dim RWPTitle As String 'there may be a better type to use here
    RWPTitle = wks.Range("E10").Value
    Text1.Value = RWPTitle
    Dim EstimatedCapital As Currency 'there may be a better type to use here
    EstimatedCapital = wks.Range("J10").Value
    CurrentDb.Execute "INSERT INTO Table1 (PlanTitle, EstimatedCapitalCost) Values (RWPTitle, EstimatedCapital)"

    wkb.Close False 'Close workbook.  False is so that it doesn't save

    Set wks = Nothing
    Set wkb = Nothing

    xls.Quit

    Set xls = Nothing
End Sub
</code>```

*When I try to use the INSERT INTO directly (No CurrentDb.EXECUTE) I get a

Compile Error - Expected:end of statement

and it highlights the Table name used.

Any ideas as to why this is happening to me?

Additionally, I am very new to VBA & Access.  Any good references for functions / calls used to deal with databse and with excel files / info?

答:
First thing I see is that your INSERT is going to fail because you are using your variables like they are parameters. - It should look like this, with the string in single quotes, and the currency not:</p>

```<code>    CurrentDb.Execute "INSERT INTO Table1 (PlanTitle, EstimatedCapitalCost)
                      Values ('" & RWPTitle & "', " & EstimatedCapital & ")"
</code>```

Body:
With the following code I get

error 3061 (Too few parameters.  Expected 2)

Option Compare Database

Private Sub Command0_Click()
    Dim xls     As Excel.Application
    Dim wkb     As Excel.Workbook
    Dim wks     As Excel.Worksheet

    Set xls = New Excel.Application

    xls.Visible = True
    xls.UserControl = True

    Set wkb = xls.Workbooks.Open("link\Reliability Projects v5.xlsm", ReadOnly:=True, UpdateLinks:=False)
    Set wks = wkb.Worksheets("Projects")

    Dim RWPTitle As String 'there may be a better type to use here
    RWPTitle = wks.Range("E10").Value
    Text1.Value = RWPTitle
    Dim EstimatedCapital As Currency 'there may be a better type to use here
    EstimatedCapital = wks.Range("J10").Value
    CurrentDb.Execute "INSERT INTO Table1 (PlanTitle, EstimatedCapitalCost) Values (RWPTitle, EstimatedCapital)"

    wkb.Close False 'Close workbook.  False is so that it doesn't save

    Set wks = Nothing
    Set wkb = Nothing

    xls.Quit

    Set xls = Nothing
End Sub

*When I try to use the INSERT INTO directly (No CurrentDb.EXECUTE) I get a

Compile Error - Expected:end of statement

and it highlights the Table name used.

Any ideas as to why this is happening to me?

Additionally, I am very new to VBA & Access.  Any good references for functions / calls used to deal with databse and with excel files / info?

Body:
First thing I see is that your INSERT is going to fail because you are using your variables like they are parameters. - It should look like this, with the string in single quotes, and the currency not:

    CurrentDb.Execute "INSERT INTO Table1 (PlanTitle, EstimatedCapitalCost)
                      Values ('" & RWPTitle & "', " & EstimatedCapital & ")"


问:
Preg_Split is not keeping the delimeter
I'm trying to parse the attributes out of a shortcode tag that I have.  The string that I'm starting with looks like this.

```<code>href="https://example.com" class="bootstrap class names"
</code>```

I'm using this expression, which gets me ALMOST there.

```<code>$attribute_dna = '/"\s/';
$attributes = preg_split($attribute_dna, $attributes_string, null, PREG_SPLIT_DELIM_CAPTURE|PREG_SPLIT_NO_EMPTY);
</code>```

the output I get is this...

```<code>string(27) "href="https://example.com"  <--Problem is right here (missing a quote)
string(17) "class="bootstrap class names""
</code>```

You can see above if i had the ending quote on the href just like the second one it would be perfect.  But it's not capturing the delimeter.

I'd appreciate any and all help I can get.  Thanks in advance.

答:
Isn't this much more beautiful?

```<code><?php

$html = <<<DATA
<div>
    <a href="https://example.com" class="bootstrap class names">Some link here</a>
</div>
DATA;

# set up the DOM
$dom = new DOMDocument();
$dom->loadHTML($html, LIBXML_HTML_NODEFDTD | LIBXML_HTML_NOIMPLIED);

# set up the xpath
$xpath = new DOMXPath($dom);

foreach ($xpath->query("//a") as $link) {
    foreach ($link->attributes as $attr) {
        $name = $attr->nodeName;
        $value = $attr->nodeValue;
        echo "Attribute '$name': '$value'\n";
    }
}
?>
</code>```

Which yields

```<code>Attribute 'href': 'https://example.com'
Attribute 'class': 'bootstrap class names'
</code>```

Title: Preg_Split is not keeping the delimeter

Body:
I'm trying to parse the attributes out of a shortcode tag that I have.  The string that I'm starting with looks like this.

href="https://example.com" class="bootstrap class names"

I'm using this expression, which gets me ALMOST there.

$attribute_dna = '/"\s/';
$attributes = preg_split($attribute_dna, $attributes_string, null, PREG_SPLIT_DELIM_CAPTURE|PREG_SPLIT_NO_EMPTY);

the output I get is this...

string(27) "href="https://example.com"  <--Problem is right here (missing a quote)
string(17) "class="bootstrap class names""

You can see above if i had the ending quote on the href just like the second one it would be perfect.  But it's not capturing the delimeter.

I'd appreciate any and all help I can get.  Thanks in advance.

Body:
Isn't this much more beautiful?

<?php

$html = <<<DATA
<div>
    <a href="https://example.com" class="bootstrap class names">Some link here</a>
</div>
DATA;

# set up the DOM
$dom = new DOMDocument();
$dom->loadHTML($html, LIBXML_HTML_NODEFDTD | LIBXML_HTML_NOIMPLIED);

# set up the xpath
$xpath = new DOMXPath($dom);

foreach ($xpath->query("//a") as $link) {
    foreach ($link->attributes as $attr) {
        $name = $attr->nodeName;
        $value = $attr->nodeValue;
        echo "Attribute '$name': '$value'\n";
    }
}
?>

Which yields

Attribute 'href': 'https://example.com'
Attribute 'class': 'bootstrap class names'


问:
Variable within a variable to replace a string
So what Im trying to do is take a file(s) which have the following parameter in it which I need to change globally:

```<code>level value="something"
</code>```

which I need to change all of them to:

```<code>level value="somethingelse"
</code>```

Im having trouble with my loop and sed script - lets say I have values of the such in the file:

```<code>level value="ABC"
level value="DEF"
level value="GHI"
level value="I DONT KNOW"
</code>```

I need all of them to become:

```<code>level value="XYZ"
</code>```

The thing is I dont know what all of the level values are, they could be anything. Hence why I am trying to standardize them to one level value. Is there a way of doing this with a loop and sed? I appreciate any help thanks!

答:
Try this:

```<code>sed 's/\(level value="\)[^"]*/\1XYZ/' file
</code>```

level value=" is captured when followed by non " characters. Using backreference, captured string is output followed by the new value XYZ.

Body:
So what Im trying to do is take a file(s) which have the following parameter in it which I need to change globally:

level value="something"

which I need to change all of them to:

level value="somethingelse"

Im having trouble with my loop and sed script - lets say I have values of the such in the file:

level value="ABC"
level value="DEF"
level value="GHI"
level value="I DONT KNOW"

I need all of them to become:

level value="XYZ"

The thing is I dont know what all of the level values are, they could be anything. Hence why I am trying to standardize them to one level value. Is there a way of doing this with a loop and sed? I appreciate any help thanks!

Body:
Try this:

sed 's/\(level value="\)[^"]*/\1XYZ/' file

level value=" is captured when followed by non " characters. Using backreference, captured string is output followed by the new value XYZ.