问:
SQL: order by calculated rate between two tables
I might be confusing syntax from other languages with SQL and that's why this isn't working, my subquery is definitely incorrect.

Having the following 2 tables:

```<code>TEST_RESULTS
Student_ID Test_ID Test_Result
    A1       234       90
    B2       234       80
    C3       345       85
    D4       234       95
    A1       345       95
    C3       456       95

TEST_DESCRIPTION
Test_ID  Test_Description Passing_Score
  234         Test A            85
  345         Test B            90
  456         Test C            95
</code>```

I want to calculate the rate of passing for each test and sort by it.

The output I am looking for:

```<code>Test_ID   Test_Description  students_taking students_passing   rate
456             Test C         1                1               1
234             Test A         3                2               0.666666667
345             Test B         2                1               0.5
</code>```

This is my query

```<code>SELECT td.Test_ID, td.Test_Description, COUNT(tr.Student_ID) as
students_taking, students_passing, students_passing/students_taking as rate
FROM
(SELECT td.Test_ID, td.Test_Description, COUNT(tr.Student_ID) as
students_passing
FROM TEST_RESULTS tr
JOIN TEST_DESCRIPTION td
on tr.Test_ID = td.Test_ID
WHERE tr.Test_Result > td.)
GROUP BY td.Test_ID, td.Test_Description
ORDER BY rate DESC, td.Test_ID, td.Test_Description
</code>```

My select from select is wrong, because I am getting no results for this query.

答:
Please check below query-</p>

```<code>SELECT TD.TEST_ID,
TD.TEST_DESCRIPTION,
STUDENT_TAKING,
STUDENT_PASSING,
RATE
FROM TEST_DESCRIPTION TD,
  (SELECT TR.TEST_ID,COUNT(TR.STUDENT_ID) "STUDENT_TAKING",
  COUNT(CASE WHEN TEST_RESULT>=PASSING_SCORE THEN STUDENT_ID END) STUDENT_PASSING,
  TO_NUMBER(TO_CHAR(COUNT(CASE WHEN TEST_RESULT>=PASSING_SCORE THEN STUDENT_ID END)/COUNT(TR.STUDENT_ID),'9999.99')) RATE
  FROM TEST_RESULTS TR,TEST_DESCRIPTION TD
  WHERE TR.TEST_ID=TD.TEST_ID
  GROUP  BY TR.TEST_ID)SUB
  WHERE SUB.TEST_ID=TD.TEST_ID ORDER BY RATE DESC;
</code>```

Body:
I might be confusing syntax from other languages with SQL and that's why this isn't working, my subquery is definitely incorrect.

Having the following 2 tables:

TEST_RESULTS
Student_ID Test_ID Test_Result
    A1       234       90
    B2       234       80
    C3       345       85
    D4       234       95
    A1       345       95
    C3       456       95

TEST_DESCRIPTION
Test_ID  Test_Description Passing_Score
  234         Test A            85
  345         Test B            90
  456         Test C            95

I want to calculate the rate of passing for each test and sort by it.

The output I am looking for:

Test_ID   Test_Description  students_taking students_passing   rate
456             Test C         1                1               1
234             Test A         3                2               0.666666667
345             Test B         2                1               0.5

This is my query

SELECT td.Test_ID, td.Test_Description, COUNT(tr.Student_ID) as
students_taking, students_passing, students_passing/students_taking as rate
FROM
(SELECT td.Test_ID, td.Test_Description, COUNT(tr.Student_ID) as
students_passing
FROM TEST_RESULTS tr
JOIN TEST_DESCRIPTION td
on tr.Test_ID = td.Test_ID
WHERE tr.Test_Result > td.)
GROUP BY td.Test_ID, td.Test_Description
ORDER BY rate DESC, td.Test_ID, td.Test_Description

My select from select is wrong, because I am getting no results for this query.

Body:
Please check below query-

SELECT TD.TEST_ID,
TD.TEST_DESCRIPTION,
STUDENT_TAKING,
STUDENT_PASSING,
RATE
FROM TEST_DESCRIPTION TD,
  (SELECT TR.TEST_ID,COUNT(TR.STUDENT_ID) "STUDENT_TAKING",
  COUNT(CASE WHEN TEST_RESULT>=PASSING_SCORE THEN STUDENT_ID END) STUDENT_PASSING,
  TO_NUMBER(TO_CHAR(COUNT(CASE WHEN TEST_RESULT>=PASSING_SCORE THEN STUDENT_ID END)/COUNT(TR.STUDENT_ID),'9999.99')) RATE
  FROM TEST_RESULTS TR,TEST_DESCRIPTION TD
  WHERE TR.TEST_ID=TD.TEST_ID
  GROUP  BY TR.TEST_ID)SUB
  WHERE SUB.TEST_ID=TD.TEST_ID ORDER BY RATE DESC;


来源: stackexchange

问:
Nodejs - Global or local initialisation of libraries
I am a bit confused as to which of the below is the better practice and why? In the first, we initialise the library globally and in the second case, its done inside a function.

Code 1

```<code>var twilio_client = require('twilio')(
  process.env.TWILIO_ACCOUNT_SID,
  process.env.TWILIO_AUTH_TOKEN
);

function_sendSMS(from, to){
   twilio_client.messages.create({
     from: from,
     to: to,
     body: "You just sent an SMS from Node.js using Twilio!"
     }, function(err, message) {
     if(err) {
      console.error(err.message);
     }
  });
}
</code>```

Code 2

```<code>function_sendSMS(from, to){

   var twilio_client = require('twilio')(
     process.env.TWILIO_ACCOUNT_SID,
     process.env.TWILIO_AUTH_TOKEN
   );

   twilio_client.messages.create({
     from: from,
     to: to,
     body: "You just sent an SMS from Node.js using Twilio!"
     }, function(err, message) {
     if(err) {
      console.error(err.message);
     }
  });
}
</code>```

答:
Stylistically this is really a matter of opinion.

However from a performance point of view, the first code example will be more efficient because it's cheaper to reference a variable in a parent scope than it is to go through any of node's module machinery, even when the module is cached after the first require(). I should also point out that in node v8.x, require() performance when loading a cached module has improved significantly (also require() for non-cached modules has improved slightly as well). You can see the difference in this graph as of this writing.

ContentLicense: CC BY-SA 3.0

Body:
I am a bit confused as to which of the below is the better practice and why? In the first, we initialise the library globally and in the second case, its done inside a function.

Code 1

var twilio_client = require('twilio')(
  process.env.TWILIO_ACCOUNT_SID,
  process.env.TWILIO_AUTH_TOKEN
);

function_sendSMS(from, to){
   twilio_client.messages.create({
     from: from,
     to: to,
     body: "You just sent an SMS from Node.js using Twilio!"
     }, function(err, message) {
     if(err) {
      console.error(err.message);
     }
  });
}

Code 2

function_sendSMS(from, to){

   var twilio_client = require('twilio')(
     process.env.TWILIO_ACCOUNT_SID,
     process.env.TWILIO_AUTH_TOKEN
   );

   twilio_client.messages.create({
     from: from,
     to: to,
     body: "You just sent an SMS from Node.js using Twilio!"
     }, function(err, message) {
     if(err) {
      console.error(err.message);
     }
  });
}


问:
Format a tbl within a dplyr chain
I am trying to add commas for thousands in my data e.g. 10,000 along with dollars e.g. $10,000.

I'm using several dplyr commands along with tidyr gather and spread functions. Here's what I tried:

Cut n paste this code block to generate the random data "dataset" I'm working with:

```<code>library(dplyr)
library(tidyr)
library(lubridate)

## Generate some data
channels <- c("Facebook", "Youtube", "SEM", "Organic", "Direct", "Email")
last_month <- Sys.Date() %m+% months(-1) %>% floor_date("month")
mts <- seq(from = last_month %m+% months(-23), to = last_month, by = "1 month") %>% as.Date()
dimvars <- expand.grid(Month = mts, Channel = channels, stringsAsFactors = FALSE)

# metrics
rws <- nrow(dimvars)
set.seed(42)

# generates variablility in the random data
randwalk <- function(initial_val, ...){
  initial_val + cumsum(rnorm(...))
}
Sessions <- ceiling(randwalk(3000, n = rws, mean = 8, sd = 1500)) %>% abs()
Revenue <- ceiling(randwalk(10000, n = rws, mean = 0, sd = 3500)) %>% abs()

# make primary df
dataset <- cbind(dimvars, Revenue)
</code>```

Which looks like:

```<code>> tbl_df(dataset)
# A tibble: 144 × 3
        Month  Channel Revenue
       <date>    <chr>   <dbl>
1  2015-06-01 Facebook    8552
2  2015-07-01 Facebook   12449
3  2015-08-01 Facebook   10765
4  2015-09-01 Facebook    9249
5  2015-10-01 Facebook   11688
6  2015-11-01 Facebook    7991
7  2015-12-01 Facebook    7849
8  2016-01-01 Facebook    2418
9  2016-02-01 Facebook    6503
10 2016-03-01 Facebook    5545
# ... with 134 more rows
</code>```

Now I want to spread the months into columns to show revenue trend by channel, month over month. I can do that like so:

```<code>revenueTable <- dataset %>% select(Month, Channel, Revenue) %>%
  group_by(Month, Channel) %>%
  summarise(Revenue = sum(Revenue)) %>%
  #mutate(Revenue = paste0("$", format(Revenue, big.interval = ","))) %>%
  gather(Key, Value, -Channel, -Month) %>%
  spread(Month, Value) %>%
  select(-Key)
</code>```

And it looks almost exactly as I want:

```<code>> revenueTable
# A tibble: 6 × 25
   Channel `2015-06-01` `2015-07-01` `2015-08-01` `2015-09-01` `2015-10-01` `2015-11-01` `2015-12-01` `2016-01-01` `2016-02-01` `2016-03-01` `2016-04-01`
*    <chr>        <dbl>        <dbl>        <dbl>        <dbl>        <dbl>        <dbl>        <dbl>        <dbl>        <dbl>        <dbl>        <dbl>
1   Direct        11910         8417         4012          359         4473         2702         6261         6167         8630         5230         1394
2    Email         7244         3517          671         1339        10788        10575         8567         8406         7856         6345         7733
3 Facebook         8552        12449        10765         9249        11688         7991         7849         2418         6503         5545         3908
4  Organic         4191          978          219         4274         2924         4155         5981         9719         8220         8829         7024
5      SEM         2344         6873        10230         6429         5016         2964         3390         3841         3163         1994         2105
6  Youtube          186         2949         2144         5073         1035         4878         7905         7377         2305         4556         6247
# ... with 13 more variables: `2016-05-01` <dbl>, `2016-06-01` <dbl>, `2016-07-01` <dbl>, `2016-08-01` <dbl>, `2016-09-01` <dbl>, `2016-10-01` <dbl>,
#   `2016-11-01` <dbl>, `2016-12-01` <dbl>, `2017-01-01` <dbl>, `2017-02-01` <dbl>, `2017-03-01` <dbl>, `2017-04-01` <dbl>, `2017-05-01` <dbl>
</code>```

Now the part I'm struggling with. I would like to format the data as currency. I tried adding this inbetween summarise() and gather() within the chain:

```<code>mutate(Revenue = paste0("$", format(Revenue, big.interval = ","))) %>%
</code>```

This half works. The dollar sign is prepended but the comma separators do not show. I tried removing the paste0("$" part to see if I could get the comma formatting to work with no success.

How can I format my tbl as a currency with dollars and commas, rounded to nearest whole dollars (no $1.99, just $2)?

Title: Format a tbl within a dplyr chain

Body:
I am trying to add commas for thousands in my data e.g. 10,000 along with dollars e.g. $10,000.

I'm using several dplyr commands along with tidyr gather and spread functions. Here's what I tried:

Cut n paste this code block to generate the random data "dataset" I'm working with:

library(dplyr)
library(tidyr)
library(lubridate)

## Generate some data
channels <- c("Facebook", "Youtube", "SEM", "Organic", "Direct", "Email")
last_month <- Sys.Date() %m+% months(-1) %>% floor_date("month")
mts <- seq(from = last_month %m+% months(-23), to = last_month, by = "1 month") %>% as.Date()
dimvars <- expand.grid(Month = mts, Channel = channels, stringsAsFactors = FALSE)

# metrics
rws <- nrow(dimvars)
set.seed(42)

# generates variablility in the random data
randwalk <- function(initial_val, ...){
  initial_val + cumsum(rnorm(...))
}
Sessions <- ceiling(randwalk(3000, n = rws, mean = 8, sd = 1500)) %>% abs()
Revenue <- ceiling(randwalk(10000, n = rws, mean = 0, sd = 3500)) %>% abs()

# make primary df
dataset <- cbind(dimvars, Revenue)

Which looks like:

> tbl_df(dataset)
# A tibble: 144 × 3
        Month  Channel Revenue
       <date>    <chr>   <dbl>
1  2015-06-01 Facebook    8552
2  2015-07-01 Facebook   12449
3  2015-08-01 Facebook   10765
4  2015-09-01 Facebook    9249
5  2015-10-01 Facebook   11688
6  2015-11-01 Facebook    7991
7  2015-12-01 Facebook    7849
8  2016-01-01 Facebook    2418
9  2016-02-01 Facebook    6503
10 2016-03-01 Facebook    5545
# ... with 134 more rows

Now I want to spread the months into columns to show revenue trend by channel, month over month. I can do that like so:

revenueTable <- dataset %>% select(Month, Channel, Revenue) %>%
  group_by(Month, Channel) %>%
  summarise(Revenue = sum(Revenue)) %>%
  #mutate(Revenue = paste0("$", format(Revenue, big.interval = ","))) %>%
  gather(Key, Value, -Channel, -Month) %>%
  spread(Month, Value) %>%
  select(-Key)

And it looks almost exactly as I want:

> revenueTable
# A tibble: 6 × 25
   Channel `2015-06-01` `2015-07-01` `2015-08-01` `2015-09-01` `2015-10-01` `2015-11-01` `2015-12-01` `2016-01-01` `2016-02-01` `2016-03-01` `2016-04-01`
*    <chr>        <dbl>        <dbl>        <dbl>        <dbl>        <dbl>        <dbl>        <dbl>        <dbl>        <dbl>        <dbl>        <dbl>
1   Direct        11910         8417         4012          359         4473         2702         6261         6167         8630         5230         1394
2    Email         7244         3517          671         1339        10788        10575         8567         8406         7856         6345         7733
3 Facebook         8552        12449        10765         9249        11688         7991         7849         2418         6503         5545         3908
4  Organic         4191          978          219         4274         2924         4155         5981         9719         8220         8829         7024
5      SEM         2344         6873        10230         6429         5016         2964         3390         3841         3163         1994         2105
6  Youtube          186         2949         2144         5073         1035         4878         7905         7377         2305         4556         6247
# ... with 13 more variables: `2016-05-01` <dbl>, `2016-06-01` <dbl>, `2016-07-01` <dbl>, `2016-08-01` <dbl>, `2016-09-01` <dbl>, `2016-10-01` <dbl>,
#   `2016-11-01` <dbl>, `2016-12-01` <dbl>, `2017-01-01` <dbl>, `2017-02-01` <dbl>, `2017-03-01` <dbl>, `2017-04-01` <dbl>, `2017-05-01` <dbl>

Now the part I'm struggling with. I would like to format the data as currency. I tried adding this inbetween summarise() and gather() within the chain:

mutate(Revenue = paste0("$", format(Revenue, big.interval = ","))) %>%

This half works. The dollar sign is prepended but the comma separators do not show. I tried removing the paste0("$" part to see if I could get the comma formatting to work with no success.

How can I format my tbl as a currency with dollars and commas, rounded to nearest whole dollars (no $1.99, just $2)?

Body:
I think you can just do this at the end with dplyr::mutate_at().

revenueTable %>% mutate_at(vars(-Channel), funs(. %>% round(0) %>% scales::dollar()))

#> # A tibble: 6 x 25
#>    Channel `2015-06-01` `2015-07-01` `2015-08-01` `2015-09-01`
#>      <chr>        <chr>        <chr>        <chr>        <chr>
#> 1   Direct      $11,910       $8,417       $4,012         $359
#> 2    Email       $7,244       $3,517         $671       $1,339
#> 3 Facebook       $8,552      $12,449      $10,765       $9,249
#> 4  Organic       $4,191         $978         $219       $4,274
#> 5      SEM       $2,344       $6,873      $10,230       $6,429
#> 6  Youtube         $186       $2,949       $2,144       $5,073
#> # ... with 20 more variables: `2015-10-01` <chr>, `2015-11-01` <chr>,
#> #   `2015-12-01` <chr>, `2016-01-01` <chr>, `2016-02-01` <chr>,
#> #   `2016-03-01` <chr>, `2016-04-01` <chr>, `2016-05-01` <chr>,
#> #   `2016-06-01` <chr>, `2016-07-01` <chr>, `2016-08-01` <chr>,
#> #   `2016-09-01` <chr>, `2016-10-01` <chr>, `2016-11-01` <chr>,
#> #   `2016-12-01` <chr>, `2017-01-01` <chr>, `2017-02-01` <chr>,
#> #   `2017-03-01` <chr>, `2017-04-01` <chr>, `2017-05-01` <chr>


问:
How to pop up a three button dialog without using jquery?
I am currently trying to pop up a dialog with three buttons not using jquery? I know js can only have two button dialog (confirm). But wondering if there is a work-around? If yes, how? Thanks in advance.</p>

答:
You would need to use a Modal Dialog.  This can be created with vanilla JS.  I borrowed some code from w3schools (https://www.w3schools.com/howto/howto_css_modals.asp) -- pretty much all of it -- for my example.  Their example provides the code for a modal window.  I've modified it to have 3 buttons and added an 'onclick' event handler that triggers an alert box showing the value.

// Get the modal
var modal = document.getElementById('myModal');
// Get the button that opens the modal
var btn = document.getElementById("myBtn");
// Get the  element that closes the modal
var span = document.getElementsByClassName("close")[0];
// When the user clicks on the button, open the modal
btn.onclick = function() {
  modal.style.display = "block";
}
// When the user clicks on  (x), close the modal
span.onclick = function() {
  modal.style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
    if (event.target == modal) {
      modal.style.display = "none";
    }
  } <
  /script>

  <
  script >
  // Add an 'onclick' handler to alert the value of the button clicked.
  document.querySelectorAll('.option_button').forEach(function(optionButton) {
    optionButton.onclick = function() {
      window.alert(optionButton.value)
    }
  });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>/* The Modal (background) */

.modal {
  display: none;
  /* Hidden by default */
  position: fixed;
  /* Stay in place */
  z-index: 1;
  /* Sit on top */
  left: 0;
  top: 0;
  width: 100%;
  /* Full width */
  height: 100%;
  /* Full height */
  overflow: auto;
  /* Enable scroll if needed */
  background-color: rgb(0, 0, 0);
  /* Fallback color */
  background-color: rgba(0, 0, 0, 0.4);
  /* Black w/ opacity */
}

/* Modal Content/Box */

.modal-content {
  background-color: #fefefe;
  margin: 15% auto;
  /* 15% from the top and centered */
  padding: 20px;
  border: 1px solid #888;
  width: 50%;
  text-align: center;
  /* Could be more or less, depending on screen size */
}

/* The Close Button */

.close {
  color: #aaa;
  float: right;
  font-size: 28px;
  font-weight: bold;
}

.close:hover,
.close:focus {
  color: black;
  text-decoration: none;
  cursor: pointer;
}</code>```

  <button id="myBtn">Open Modal</button>

      ×

Click a button...

      <button value=1 class="option_button">Option 1</button>
      <button value=2 class="option_button">Option 2</button>
      <button value=3 class="option_button">Option 3</button>

```

Body:
You would need to use a Modal Dialog.  This can be created with vanilla JS.  I borrowed some code from w3schools (https://www.w3schools.com/howto/howto_css_modals.asp) -- pretty much all of it -- for my example.  Their example provides the code for a modal window.  I've modified it to have 3 buttons and added an 'onclick' event handler that triggers an alert box showing the value.

// Get the modal
var modal = document.getElementById('myModal');
// Get the button that opens the modal
var btn = document.getElementById("myBtn");
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];
// When the user clicks on the button, open the modal
btn.onclick = function() {
  modal.style.display = "block";
}
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
  modal.style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
    if (event.target == modal) {
      modal.style.display = "none";
    }
  } <
  /script>

  <
  script >
  // Add an 'onclick' handler to alert the value of the button clicked.
  document.querySelectorAll('.option_button').forEach(function(optionButton) {
    optionButton.onclick = function() {
      window.alert(optionButton.value)
    }
  });

/* The Modal (background) */

.modal {
  display: none;
  /* Hidden by default */
  position: fixed;
  /* Stay in place */
  z-index: 1;
  /* Sit on top */
  left: 0;
  top: 0;
  width: 100%;
  /* Full width */
  height: 100%;
  /* Full height */
  overflow: auto;
  /* Enable scroll if needed */
  background-color: rgb(0, 0, 0);
  /* Fallback color */
  background-color: rgba(0, 0, 0, 0.4);
  /* Black w/ opacity */
}

/* Modal Content/Box */

.modal-content {
  background-color: #fefefe;
  margin: 15% auto;
  /* 15% from the top and centered */
  padding: 20px;
  border: 1px solid #888;
  width: 50%;
  text-align: center;
  /* Could be more or less, depending on screen size */
}

/* The Close Button */

.close {
  color: #aaa;
  float: right;
  font-size: 28px;
  font-weight: bold;
}

.close:hover,
.close:focus {
  color: black;
  text-decoration: none;
  cursor: pointer;
}

<body>

  <!-- Trigger/Open The Modal -->
  <button id="myBtn">Open Modal</button>

  <!-- The Modal -->
  <div id="myModal" class="modal">

    <!-- Modal content -->
    <div class="modal-content">
      <span class="close">&times;</span>
      <p>Click a button...</p>
      <button value=1 class="option_button">Option 1</button>
      <button value=2 class="option_button">Option 2</button>
      <button value=3 class="option_button">Option 3</button>
    </div>

  </div>

</body>

ContentLicense: CC BY-SA 4.0


问:
A list of plotting functions in base R?
Each time I encounter a new plotting function in Base R (e.g., dotchart(), smoothScatter(). matplot()), I wish there was a list of plotting functions in Base R which I could refer to for various plotting cases.

Question:

I was wondering if any our colleagues might be aware of a list of plotting functions in Base R which I could refer to for various plotting cases?

答:
You could use

```<code> library(help = "graphics")
</code>```

that will display the list of plotting functions e.g.:

```<code>...
barplot                 Bar Plots
box                     Draw a Box around a Plot
boxplot                 Box Plots
boxplot.matrix          Draw a Boxplot for each Column (Row) of a
                        Matrix
bxp                     Draw Box Plots from Summaries
cdplot                  Conditional Density Plots
clip                    Set Clipping Region
contour                 Display Contours
coplot                  Conditioning Plots
</code>```

Title: A list of plotting functions in base R?

Body:
You could use

 library(help = "graphics")

that will display the list of plotting functions e.g.:

...
barplot                 Bar Plots
box                     Draw a Box around a Plot
boxplot                 Box Plots
boxplot.matrix          Draw a Boxplot for each Column (Row) of a
                        Matrix
bxp                     Draw Box Plots from Summaries
cdplot                  Conditional Density Plots
clip                    Set Clipping Region
contour                 Display Contours
coplot                  Conditioning Plots


问:
Keep background active state as hover?
I have an unordered list and inside an LI and under that is the dropdown menu.

Dropdown uses JQ/JS for the hide/show states. When hovered over a list item as it drops down how can i have a background-color/image stay on that item (main LI) like i would with active states, until the cursor has moved out of the Dropdown area.

Would this require creating another DIV block to contain all the elements? (Menu,Submenu,JS) And if so another few lines of JS if thats the case?

or is there a simpler way to achieve this with css.. as i cannot think of a way.
Hope my question is clear and please disregard all the unnecessary HTML and CSS code,

Thanks.

JS

```<code>$(function () {
$('.dropdown, .dropdown2, .dropdown3').each(function () {
$(this).parent().eq(0).hover(function () {
$('.dropdown, .dropdown2, .dropdown3:eq(0)', this).show();
}, function () {
$('.dropdown, .dropdown2, .dropdown3:eq(0)', this).hide();
});
});
});
</code>```

HTML

```<code><ul id="nav-container">
    <li><a href="#"><span>Home</span></a>
    <ul class="dropdown">
    <li><a href="#"><span class="subtxt">Menu item 2</span></a></li>
    <li><a href="#"><span class="subtxt">Menu item 2</span></a></li>
    <li><a href="#"><span class="subtxt">Menu item 2</span></a></li>
    <li><a href="#"><span class="subtxt">Menu item 2</span></a></li>
    <li><a href="#"><span class="subtxt">Menu item 2</span></a></li>
    <li><a href="#"><span class="subtxt">Menu item 2</span></a></li>
    <li><a href="#"><span class="subtxt">Menu item 2</span></a></li>
    </ul>
    </li>

    <li><a href="#"><span>Services</span></a>
    <ul class="dropdown2">
    <li><a href="#"><span class="subtxt">Menu item 2</span></a></li>
    <li><a href="#"><span class="subtxt">Menu item 2</span></a></li>
    <li><a href="#"><span class="subtxt">Menu item 2</span></a></li>
    <li><a href="#"><span class="subtxt">Menu item 2</span></a></li>
    <li><a href="#"><span class="subtxt">Menu item 2</span></a></li>
    <li><a href="#"><span class="subtxt">Menu item 2</span></a></li>
    <li><a href="#"><span class="subtxt">Menu item 2</span></a></li>
    </ul>
    </li>

    <li><a href="#"><span>Contact</span></a>
    <ul class="dropdown3">
    <li><a href="#"><span class="subtxt">Menu item 2</span></a></li>
    <li><a href="#"><span class="subtxt">Menu item 2</span></a></li>
    <li><a href="#"><span class="subtxt">Menu item 2</span></a></li>
    <li><a href="#"><span class="subtxt">Menu item 2</span></a></li>
    <li><a href="#"><span class="subtxt">Menu item 2</span></a></li>
    <li><a href="#"><span class="subtxt">Menu item 2</span></a></li>
    <li><a href="#"><span class="subtxt">Menu item 2</span></a></li>
    </ul>
    </li>
</ul><!--nav-container-->
</code>```

MENU CSS

```<code>#nav-container  {
 display: block;
 width: 900px;
 float: right;
 position: relative;
 left: 120px;
}
#nav-container li a span {
 display: inline;
 height: 36px;
 padding-top: 12px;
 padding-left: 13px;
 padding-right: 14px;
 float: left;
}
#nav-container .active-link span   {
 background-image: url(../img/navlist_bg2.gif);
 background-repeat: repeat-x;
 display: block;
 color: #000;

}

#nav-container li a:hover span {
 display: block;
 background-image: url(../img/navlist_bg2.gif);
 background-repeat: repeat-x;
}
#nav-container .active {
 background-image: url(../img/navlist_bg2.gif);
 background-repeat: repeat-x;
}

#nav-container li  {
 list-style-type: none;
 display: inline;
}
</code>```

SUB MENU CSS (dropdown2, dropdown3 are the same just made for positioning)

```<code>ul.dropdown
{
 margin: 0;
 padding: 0;
 display: block;
 position: absolute;
 z-index: 999;
 top: 100%;
 width: 300px;
 display: none;
 left: 80px;
 font-size: 11px;
 height: 90px;
}

ul.dropdown ul.dropdown
{
 top: 0;
 left: 95%;
}

ul.dropdown li
{
 margin: 0;
 padding: 0;
 float: none;
 position: relative;
 list-style: none;
 display: block;
 color: #3C3C3C;
}

ul.dropdown li a
{
 display: block;
 color: #3C3C3C;
 font-size: 11px;
}
ul.dropdown li a span {
 font-size: 11px;
 color: #3C3C3C;
}
</code>```

答:
JS:

```<code>$(function () {
$('.menu1').hover(function () {
$('.link').addClass('active');
$('.dropdown1').show;
}, function () {
$('.dropdown1').hide;
$('.link').removeClass('active');
});
});
});
</code>```

HTML:

```<code><li class="menu1"><a class="link" href="#"><span>Home</span></a>
<ul class="dropdown1">
<li><a href="#"><span class="subtxt">Menu item 2</span></a></li>
<li><a href="#"><span class="subtxt">Menu item 2</span></a></li>
</ul>
</li>
</code>```

repeat this for all base menu items (hover1, 2, 3, etc)

ContentLicense: CC BY-SA 2.5

Title: Keep background active state as hover?

Body:
I have an unordered list and inside an LI and under that is the dropdown menu.

Dropdown uses JQ/JS for the hide/show states. When hovered over a list item as it drops down how can i have a background-color/image stay on that item (main LI) like i would with active states, until the cursor has moved out of the Dropdown area.

Would this require creating another DIV block to contain all the elements? (Menu,Submenu,JS) And if so another few lines of JS if thats the case?

or is there a simpler way to achieve this with css.. as i cannot think of a way.
Hope my question is clear and please disregard all the unnecessary HTML and CSS code,

Thanks.

JS

$(function () {
$('.dropdown, .dropdown2, .dropdown3').each(function () {
$(this).parent().eq(0).hover(function () {
$('.dropdown, .dropdown2, .dropdown3:eq(0)', this).show();
}, function () {
$('.dropdown, .dropdown2, .dropdown3:eq(0)', this).hide();
});
});
});

HTML

Home

Menu item 2

Menu item 2

Menu item 2

Menu item 2

Menu item 2

Menu item 2

Menu item 2

Services

Menu item 2

Menu item 2

Menu item 2

Menu item 2

Menu item 2

Menu item 2

Menu item 2

Contact

Menu item 2

Menu item 2

Menu item 2

Menu item 2

Menu item 2

Menu item 2

Menu item 2

MENU CSS

#nav-container  {
 display: block;
 width: 900px;
 float: right;
 position: relative;
 left: 120px;
}
#nav-container li a span {
 display: inline;
 height: 36px;
 padding-top: 12px;
 padding-left: 13px;
 padding-right: 14px;
 float: left;
}
#nav-container .active-link span   {
 background-image: url(../img/navlist_bg2.gif);
 background-repeat: repeat-x;
 display: block;
 color: #000;

}

#nav-container li a:hover span {
 display: block;
 background-image: url(../img/navlist_bg2.gif);
 background-repeat: repeat-x;
}
#nav-container .active {
 background-image: url(../img/navlist_bg2.gif);
 background-repeat: repeat-x;
}

#nav-container li  {
 list-style-type: none;
 display: inline;
}

SUB MENU CSS (dropdown2, dropdown3 are the same just made for positioning)

ul.dropdown
{
 margin: 0;
 padding: 0;
 display: block;
 position: absolute;
 z-index: 999;
 top: 100%;
 width: 300px;
 display: none;
 left: 80px;
 font-size: 11px;
 height: 90px;
}

ul.dropdown ul.dropdown
{
 top: 0;
 left: 95%;
}

ul.dropdown li
{
 margin: 0;
 padding: 0;
 float: none;
 position: relative;
 list-style: none;
 display: block;
 color: #3C3C3C;
}

ul.dropdown li a
{
 display: block;
 color: #3C3C3C;
 font-size: 11px;
}
ul.dropdown li a span {
 font-size: 11px;
 color: #3C3C3C;
}

Body:
JS:

$(function () {
$('.menu1').hover(function () {
$('.link').addClass('active');
$('.dropdown1').show;
}, function () {
$('.dropdown1').hide;
$('.link').removeClass('active');
});
});
});

HTML:

<li class="menu1"><a class="link" href="#"><span>Home</span></a>
<ul class="dropdown1">
<li><a href="#"><span class="subtxt">Menu item 2</span></a></li>
<li><a href="#"><span class="subtxt">Menu item 2</span></a></li>
</ul>
</li>

repeat this for all base menu items (hover1, 2, 3, etc)


问:
Mongoose populate either ObjectId reference or String
Is there a way to specify a heterogeneous array as a schema property where it can contain both ObjectIds and strings? I'd like to have something like the following:

```<code>var GameSchema = new mongoose.schema({
    players: {
        type: [<UserModel reference|IP address/socket ID/what have you>]
    }
</code>```

Is the only option a Mixed type that I manage myself? I've run across discriminators, which look somewhat promising, but it looks like it only works for subdocuments and not references to other schemas. Of course, I could just have a UserModel reference and create a UserModel that just stores the IP address or whatever I'm using to identify them, but that seems like it could quickly get hugely out of control in terms of space (having a model for every IP I come across sounds bad).

EDIT:

Example:

A game has one logged in user, three anonymous users, the document should look something like this:

```<code>{ players: [ ObjectId("5fd88ea85...."), "192.0.0.1", "192.1.1.1", "192.2.2.1"] }
</code>```

Ideally this would be populated to:

```<code>{ players: [ UserModel(id: ..., name: ...),  "192.0.0.1", "192.1.1.1", "192.2.2.1"] }
</code>```

EDIT:

I've decided to go a different route: instead of mixing types, I'm differentiating with different properties. Something like this:

```<code>players: [
    {
        user: <object reference>,
        sessionID: <string>,
        color: {
           type: String
        },
        ...other properties...
    }
]
</code>```

I have a validator that ensures only one of user or sessionID are populated for a given entry. In some ways this is more complex, but it does obviate the need to do this kind of conditional populating and figuring out what type each entry is when iterating over them. I haven't tried any of the answers, but they look promising.

答:
If you are content to go with using Mixed or at least some scheme that will not work with .populate() then you can shift the "join" responsibility to the "server" instead using the $lookup functionality of MongoDB and a little fancy matching.

For me if I have a "games" collection document like this:

```<code>{
        "_id" : ObjectId("5933723c886d193061b99459"),
        "players" : [
                ObjectId("5933723c886d193061b99458"),
                "10.1.1.1",
                "10.1.1.2"
        ],
        "__v" : 0
}
</code>```

Then I send the statement to the server to "join" with the "users" collection data where an ObjectId is present like this:

```<code>Game.aggregate([
  { "$addFields": {
    "users": {
      "$filter": {
        "input": "$players",
        "as": "p",
        "cond": { "$gt": [ "$$p", {} ] }
      }
    }
  }},
  { "$lookup": {
    "from": "users",
    "localField": "users",
    "foreignField": "_id",
    "as": "users"
  }},
  { "$project": {
    "players": {
      "$map": {
        "input": "$players",
        "as": "p",
        "in": {
          "$cond": {
            "if": { "$gt": [ "$$p", {} ] },
            "then": {
              "$arrayElemAt": [
                { "$filter": {
                  "input": "$users",
                  "as": "u",
                  "cond": { "$eq": [ "$$u._id", "$$p" ] }
                }},
                0
              ]
            },
            "else": "$$p"
          }
        }
      }
    }
  }}
])
</code>```

Which gives the result when joined to the users object as:

```<code>{
        "_id" : ObjectId("5933723c886d193061b99459"),
        "players" : [
                {
                        "_id" : ObjectId("5933723c886d193061b99458"),
                        "name" : "Bill",
                        "__v" : 0
                },
                "10.1.1.1",
                "10.1.1.2"
        ]
}
</code>```

So the "fancy" part really relies on this logical statement when considering the entries in the "players" array:

```<code>  "$filter": {
    "input": "$players",
    "as": "p",
    "cond": { "$gt": [ "$$p", {} ] }
  }
</code>```

How this works is that to MongoDB, an ObjectId and actually all BSON types have a specific sort precedence. In this case where the data is "Mixed" between ObjectId and String then  the "string" values are considered "less than" the value of a "BSON Object", and the ObjectId values are "greater than".

This allows you to separate the ObjectId values from the source array into their own list. Given that list, you $lookup to perform the "join" at get the objects from the other collection.

In order to put them back, I'm using $map to "transpose" each element of the original "players" where the matched ObjectId was found with the related object. An alternate approach would be to "split" the two types, do the $lookup and $concatArrays between the Users and the "strings". But that would not maintain the original array order, so $map may be a better fit.

I will add of note that the same basic process can be applied in a "client" operation by similarly filtering the content of the "players" array to contain just the ObjectId values and then calling the "model" form of .populate() from "inside" the response of the initial query. The documentation shows an example of that form of usage, as do some answers on this site before it was possible to do a "nested populate" with mongoose.

The other point of mind here is that .populate() itself existed as a mongoose method long before the $lookup aggregation pipeline operator came about, and was a solution for a time when MongoDB itself was incapable of performing a "join" of any sort. So the operations are indeed "client" side as an emulation and really only perform additional queries that you do not need to be aware of in issuing the statements yourself.

Therefore it should generally be desirable in a modern scenario to use the "server" features, and avoid the overhead involved with multiple queries in order to get the result.

Body:
Is there a way to specify a heterogeneous array as a schema property where it can contain both ObjectIds and strings? I'd like to have something like the following:

var GameSchema = new mongoose.schema({
    players: {
        type: [<UserModel reference|IP address/socket ID/what have you>]
    }

Is the only option a Mixed type that I manage myself? I've run across discriminators, which look somewhat promising, but it looks like it only works for subdocuments and not references to other schemas. Of course, I could just have a UserModel reference and create a UserModel that just stores the IP address or whatever I'm using to identify them, but that seems like it could quickly get hugely out of control in terms of space (having a model for every IP I come across sounds bad).

EDIT:

Example:

A game has one logged in user, three anonymous users, the document should look something like this:

{ players: [ ObjectId("5fd88ea85...."), "192.0.0.1", "192.1.1.1", "192.2.2.1"] }

Ideally this would be populated to:

{ players: [ UserModel(id: ..., name: ...),  "192.0.0.1", "192.1.1.1", "192.2.2.1"] }

EDIT:

I've decided to go a different route: instead of mixing types, I'm differentiating with different properties. Something like this:

players: [
    {
        user: <object reference>,
        sessionID: <string>,
        color: {
           type: String
        },
        ...other properties...
    }
]

I have a validator that ensures only one of user or sessionID are populated for a given entry. In some ways this is more complex, but it does obviate the need to do this kind of conditional populating and figuring out what type each entry is when iterating over them. I haven't tried any of the answers, but they look promising.

Body:
If you are content to go with using Mixed or at least some scheme that will not work with .populate() then you can shift the "join" responsibility to the "server" instead using the $lookup functionality of MongoDB and a little fancy matching.

For me if I have a "games" collection document like this:

{
        "_id" : ObjectId("5933723c886d193061b99459"),
        "players" : [
                ObjectId("5933723c886d193061b99458"),
                "10.1.1.1",
                "10.1.1.2"
        ],
        "__v" : 0
}

Then I send the statement to the server to "join" with the "users" collection data where an ObjectId is present like this:

Game.aggregate([
  { "$addFields": {
    "users": {
      "$filter": {
        "input": "$players",
        "as": "p",
        "cond": { "$gt": [ "$$p", {} ] }
      }
    }
  }},
  { "$lookup": {
    "from": "users",
    "localField": "users",
    "foreignField": "_id",
    "as": "users"
  }},
  { "$project": {
    "players": {
      "$map": {
        "input": "$players",
        "as": "p",
        "in": {
          "$cond": {
            "if": { "$gt": [ "$$p", {} ] },
            "then": {
              "$arrayElemAt": [
                { "$filter": {
                  "input": "$users",
                  "as": "u",
                  "cond": { "$eq": [ "$$u._id", "$$p" ] }
                }},
                0
              ]
            },
            "else": "$$p"
          }
        }
      }
    }
  }}
])

Which gives the result when joined to the users object as:

{
        "_id" : ObjectId("5933723c886d193061b99459"),
        "players" : [
                {
                        "_id" : ObjectId("5933723c886d193061b99458"),
                        "name" : "Bill",
                        "__v" : 0
                },
                "10.1.1.1",
                "10.1.1.2"
        ]
}

So the "fancy" part really relies on this logical statement when considering the entries in the "players" array:

  "$filter": {
    "input": "$players",
    "as": "p",
    "cond": { "$gt": [ "$$p", {} ] }
  }

How this works is that to MongoDB, an ObjectId and actually all BSON types have a specific sort precedence. In this case where the data is "Mixed" between ObjectId and String then  the "string" values are considered "less than" the value of a "BSON Object", and the ObjectId values are "greater than".

This allows you to separate the ObjectId values from the source array into their own list. Given that list, you $lookup to perform the "join" at get the objects from the other collection.

In order to put them back, I'm using $map to "transpose" each element of the original "players" where the matched ObjectId was found with the related object. An alternate approach would be to "split" the two types, do the $lookup and $concatArrays between the Users and the "strings". But that would not maintain the original array order, so $map may be a better fit.

I will add of note that the same basic process can be applied in a "client" operation by similarly filtering the content of the "players" array to contain just the ObjectId values and then calling the "model" form of .populate() from "inside" the response of the initial query. The documentation shows an example of that form of usage, as do some answers on this site before it was possible to do a "nested populate" with mongoose.

The other point of mind here is that .populate() itself existed as a mongoose method long before the $lookup aggregation pipeline operator came about, and was a solution for a time when MongoDB itself was incapable of performing a "join" of any sort. So the operations are indeed "client" side as an emulation and really only perform additional queries that you do not need to be aware of in issuing the statements yourself.

Therefore it should generally be desirable in a modern scenario to use the "server" features, and avoid the overhead involved with multiple queries in order to get the result.


问:
bower command not found windows
I am having huge problems trying to use bower (to install foundation 5) or get anything bower related to work on the command line.

I've installed

ruby 1.9.3

git (with run from command prompt option)

Nodejs

I've successfully ran

```<code>npm install -g bower grunt-cli
gem install foundation
</code>```

and these have ran fine. I've looked in the npm/node_modules directory and I can see bower folder in there.

Every time I type bower either into the cmd, ruby cmd or git bash I get

command not recognized

I've set the git path in the environment variables.

What's annoying is the instruction on the bower site. It states:

```<code>npm install -g bower
bower install
</code>```

Well this doesn't work!

答: As others mentioned have to add bower into environment variables, but the easiest way to locate is just simply type in your npm location first, then use Browse File and locate bower on your system(you can search for it in search bar as well), because the location may vary for different users.

Title: bower command not found windows

Body:
I am having huge problems trying to use bower (to install foundation 5) or get anything bower related to work on the command line.

I've installed

ruby 1.9.3

git (with run from command prompt option)

Nodejs

I've successfully ran

npm install -g bower grunt-cli
gem install foundation

and these have ran fine. I've looked in the npm/node_modules directory and I can see bower folder in there.

Every time I type bower either into the cmd, ruby cmd or git bash I get

command not recognized

I've set the git path in the environment variables.

What's annoying is the instruction on the bower site. It states:

npm install -g bower
bower install

Well this doesn't work!


问:
Discrete Fourier Transforms in Javascript
I want to present the pulse wave using Highcharts.
With idea data, the chart is fine as
image

However, when there are noises, the algorithm does not work
image with bad points

so I decided to do with Fourier transform.

Is there any library can do the DFT? or I have to write it myself.

please tell me the library name or way to solve this question and how do you get the idea.

Thanks a lot!

答:
I made a suggestion in another thread on Stack Overflow: Fast Fourier Transform Javascript .

It accepts entry of a 1D array, assumes they are equally spaced, and outputs the DFT. Perhaps this is what you are looking for?


问:
How do I change the size of my JButton?
I have to design a swing game where one side is a grid and the other side is somewhat of a display panel where I have several JLabels and a JButton. But no matter if I use setSize(); or setPrefferedSize (); or setBounds(); or even setPrefferedSize(new Dimension()); it will not become smaller but instead stretches the entirety of that section. Any JLabel/JButton aligned in the center takes up the entire center. How do I fix this?

This is the code to my class referencing to another class in the project containing the grid:

```<code>import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;

public class Scoreboard extends JPanel{
    /**
     *
     */
    private static final long serialVersionUID = 1L;
    JLabel scoreLabel;
    JLabel coord;
    JLabel title;
    JButton quit;
    public Scoreboard (int score){
        setLayout(new BorderLayout());
        setSize(490,400);
        setPreferredSize(getSize());
        setBackground(Color.BLUE);
        title = new JLabel();
        title.setIcon(new ImageIcon("C:\\Users\\Rachel\\Workspace\\Assignment2\\Planet1.png"));
        title.setSize(200,200);
        title.setHorizontalAlignment(SwingConstants.CENTER);
        add (title,BorderLayout.NORTH);
        scoreLabel = new JLabel("Score: "+Integer.toString(score));
        scoreLabel.setSize(200,200);
        scoreLabel.setBackground(Color.BLUE);
        scoreLabel.setHorizontalAlignment(SwingConstants.CENTER);
        scoreLabel.setFont(new Font("Source Sans Pro", Font.BOLD, 40));
        scoreLabel.setForeground(Color.WHITE);
        add(scoreLabel, BorderLayout.CENTER);
        coord = new JLabel ("Click the aliens!");
        coord.setSize(200,400);
        coord.setBackground(Color.RED);
        coord.setHorizontalAlignment(SwingConstants.CENTER);
        coord.setFont(new Font("Source Sans Pro", Font.BOLD, 20));
        coord.setForeground(Color.WHITE);
        add(coord,BorderLayout.SOUTH);
        JButton quit = new JButton ("Quit Game");
        quit.setBounds(20,30,50,30);
        quit.setHorizontalAlignment(SwingConstants.CENTER);
        add(quit, BorderLayout.CENTER);

    }
}
</code>```

答:
The following code does not solve the problem. Instead it shows some tips related to your question, as well as some others.
In general try to avoid "manually control" components layout, but use the right layout managers. </p>

```<code>import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.WindowConstants;

public class Scoreboard extends JPanel{

    JLabel scoreLabel;
    JLabel coord;
    JLabel title;
    JButton quit;
    private final int W = 490;
    private final int H = 400;

    public Scoreboard (int score){
        setLayout(new BorderLayout());
        setPreferredSize(new Dimension(W, H));
        setBackground(Color.BLUE);
        title = new JLabel("My Title");
        //if you use images in your SO posted code use web links
        //title.setIcon(new ImageIcon("C:\\Users\\Rachel\\Workspace\\Assignment2\\Planet1.png"));
        //title.setSize(200,200); run the code without it and see it has no effect
        title.setHorizontalAlignment(SwingConstants.CENTER);
        add (title,BorderLayout.NORTH);

        scoreLabel = new JLabel("Score: "+Integer.toString(score));
        scoreLabel.setSize(200,200);
        scoreLabel.setBackground(Color.BLUE);
        scoreLabel.setHorizontalAlignment(SwingConstants.CENTER);
        scoreLabel.setFont(new Font("Source Sans Pro", Font.BOLD, 40));
        scoreLabel.setForeground(Color.WHITE);
        //this is directly related to your question. You can't add 2 components
        //to the center.
        //instead add a JPanel to the center, apply a layout manager to it,
        //and add scorelabel and quit button to that JPanel
        add(scoreLabel, BorderLayout.CENTER);

        coord = new JLabel ("Click the aliens!");
        //coord.setSize(200,400); run the code without it and see it has no effect
        coord.setBackground(Color.RED);
        coord.setOpaque(true); //if you want the color show
        coord.setHorizontalAlignment(SwingConstants.CENTER);
        coord.setFont(new Font("Source Sans Pro", Font.BOLD, 20));
        coord.setForeground(Color.WHITE);
        add(coord,BorderLayout.SOUTH);

        JButton quit = new JButton ("Quit Game");
        //no need to set bounds. That is what the layout manager does
        //quit.setBounds(20,30,50,30);
        quit.setHorizontalAlignment(SwingConstants.CENTER);
        add(quit, BorderLayout.CENTER);
    }

    //add main to your questions to make it runnable
    public static void main(String[] args){

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);

        JPanel panel = new Scoreboard(50);
        frame.getContentPane().add(panel);

        frame.pack();
        frame.setVisible(true);
    }
}
</code>```

Title: How do I change the size of my JButton?

Body:
I have to design a swing game where one side is a grid and the other side is somewhat of a display panel where I have several JLabels and a JButton. But no matter if I use setSize(); or setPrefferedSize (); or setBounds(); or even setPrefferedSize(new Dimension()); it will not become smaller but instead stretches the entirety of that section. Any JLabel/JButton aligned in the center takes up the entire center. How do I fix this?

This is the code to my class referencing to another class in the project containing the grid:

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;

public class Scoreboard extends JPanel{
    /**
     *
     */
    private static final long serialVersionUID = 1L;
    JLabel scoreLabel;
    JLabel coord;
    JLabel title;
    JButton quit;
    public Scoreboard (int score){
        setLayout(new BorderLayout());
        setSize(490,400);
        setPreferredSize(getSize());
        setBackground(Color.BLUE);
        title = new JLabel();
        title.setIcon(new ImageIcon("C:\\Users\\Rachel\\Workspace\\Assignment2\\Planet1.png"));
        title.setSize(200,200);
        title.setHorizontalAlignment(SwingConstants.CENTER);
        add (title,BorderLayout.NORTH);
        scoreLabel = new JLabel("Score: "+Integer.toString(score));
        scoreLabel.setSize(200,200);
        scoreLabel.setBackground(Color.BLUE);
        scoreLabel.setHorizontalAlignment(SwingConstants.CENTER);
        scoreLabel.setFont(new Font("Source Sans Pro", Font.BOLD, 40));
        scoreLabel.setForeground(Color.WHITE);
        add(scoreLabel, BorderLayout.CENTER);
        coord = new JLabel ("Click the aliens!");
        coord.setSize(200,400);
        coord.setBackground(Color.RED);
        coord.setHorizontalAlignment(SwingConstants.CENTER);
        coord.setFont(new Font("Source Sans Pro", Font.BOLD, 20));
        coord.setForeground(Color.WHITE);
        add(coord,BorderLayout.SOUTH);
        JButton quit = new JButton ("Quit Game");
        quit.setBounds(20,30,50,30);
        quit.setHorizontalAlignment(SwingConstants.CENTER);
        add(quit, BorderLayout.CENTER);

    }
}

Body:
The following code does not solve the problem. Instead it shows some tips related to your question, as well as some others.
In general try to avoid "manually control" components layout, but use the right layout managers.

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.WindowConstants;

public class Scoreboard extends JPanel{

    JLabel scoreLabel;
    JLabel coord;
    JLabel title;
    JButton quit;
    private final int W = 490;
    private final int H = 400;

    public Scoreboard (int score){
        setLayout(new BorderLayout());
        setPreferredSize(new Dimension(W, H));
        setBackground(Color.BLUE);
        title = new JLabel("My Title");
        //if you use images in your SO posted code use web links
        //title.setIcon(new ImageIcon("C:\\Users\\Rachel\\Workspace\\Assignment2\\Planet1.png"));
        //title.setSize(200,200); run the code without it and see it has no effect
        title.setHorizontalAlignment(SwingConstants.CENTER);
        add (title,BorderLayout.NORTH);

        scoreLabel = new JLabel("Score: "+Integer.toString(score));
        scoreLabel.setSize(200,200);
        scoreLabel.setBackground(Color.BLUE);
        scoreLabel.setHorizontalAlignment(SwingConstants.CENTER);
        scoreLabel.setFont(new Font("Source Sans Pro", Font.BOLD, 40));
        scoreLabel.setForeground(Color.WHITE);
        //this is directly related to your question. You can't add 2 components
        //to the center.
        //instead add a JPanel to the center, apply a layout manager to it,
        //and add scorelabel and quit button to that JPanel
        add(scoreLabel, BorderLayout.CENTER);

        coord = new JLabel ("Click the aliens!");
        //coord.setSize(200,400); run the code without it and see it has no effect
        coord.setBackground(Color.RED);
        coord.setOpaque(true); //if you want the color show
        coord.setHorizontalAlignment(SwingConstants.CENTER);
        coord.setFont(new Font("Source Sans Pro", Font.BOLD, 20));
        coord.setForeground(Color.WHITE);
        add(coord,BorderLayout.SOUTH);

        JButton quit = new JButton ("Quit Game");
        //no need to set bounds. That is what the layout manager does
        //quit.setBounds(20,30,50,30);
        quit.setHorizontalAlignment(SwingConstants.CENTER);
        add(quit, BorderLayout.CENTER);
    }

    //add main to your questions to make it runnable
    public static void main(String[] args){

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);

        JPanel panel = new Scoreboard(50);
        frame.getContentPane().add(panel);

        frame.pack();
        frame.setVisible(true);
    }
}


问:
Gulp + Browsersync: Only want to inject CSS
I have been attempting to get live injecting working for two days now... Getting ready to give up as I've read the docks and more git is:issues than I want to repeat.

I don't use preprcessors like less or sass. I just want to have the changed CSS live reload through Browsersync. The page reloads if I save the file and my headers are set. I've tried so many options, my head is spinning.
This is the latest iteration of my attempts. Anybody care to lead me to the right path?

```<code>var gulp        = require('gulp');
var autoprefixer = require('gulp-autoprefixer');
var browserSync = require('browser-sync').create();

gulp.task('serve', function() {
    browserSync.init({
      proxy: "https://subdomain.mysite.dev",
      open: false,
      browser: 'firefox-developer',
      injectChanges: true,
      logLevel: "debug"
    });
    gulp.watch("./style.css", ['css']);
});

gulp.task('css', function() {
  return gulp.src('./style.css')
    .pipe(autoprefixer('last 2 versions'))
    .pipe(browserSync.stream());
});

gulp.task('default', ['serve']);
</code>```

Kubuntu Linux 17.04

browser-sync --version

2.18.12

node -v

v7.10.0

npm -v

5.0.1

答:
Try

```<code>.pipe(browserSync.reload({ stream:true }));
</code>```

instead of

```<code>.pipe(browserSync.stream());
</code>```

and then as @The Dancing Code says have that gulp.dest after your autoprefixer call and make sure that resultant file is the one in your html.

Body:
I have been attempting to get live injecting working for two days now... Getting ready to give up as I've read the docks and more git is:issues than I want to repeat.

I don't use preprcessors like less or sass. I just want to have the changed CSS live reload through Browsersync. The page reloads if I save the file and my headers are set. I've tried so many options, my head is spinning.
This is the latest iteration of my attempts. Anybody care to lead me to the right path?

var gulp        = require('gulp');
var autoprefixer = require('gulp-autoprefixer');
var browserSync = require('browser-sync').create();

gulp.task('serve', function() {
    browserSync.init({
      proxy: "https://subdomain.mysite.dev",
      open: false,
      browser: 'firefox-developer',
      injectChanges: true,
      logLevel: "debug"
    });
    gulp.watch("./style.css", ['css']);
});

gulp.task('css', function() {
  return gulp.src('./style.css')
    .pipe(autoprefixer('last 2 versions'))
    .pipe(browserSync.stream());
});

gulp.task('default', ['serve']);

Kubuntu Linux 17.04

browser-sync --version

2.18.12

node -v

v7.10.0

npm -v

5.0.1

Body:
Try

.pipe(browserSync.reload({ stream:true }));

instead of

.pipe(browserSync.stream());

and then as @The Dancing Code says have that gulp.dest after your autoprefixer call and make sure that resultant file is the one in your html.


问:
Go equivalent of C's negated scansets
What is the way to mimick the negated scansets that exist in C?

For an example input string: aaaa, bbbb

In go using:

```<code>fmt.Sscanf(input, "%s, %s", &str1, &str2)
</code>```

The result is only str1 being set as: aaaa,

In C one could use a format string as "%[^,], %s" to avoid this problem, is there a way to accomplish this in go?

答:
Go doesn't support this directly like C, partially because you should be reading a line and using something like strings.FieldsFunc. But that's naturally a very simplistic view. For data formatted in a homogeneous manner, you could use bufio.Scanner to essentially do the same thing with any io.Reader. However, if you had to deal with something like this format:

```<code>// Name; email@domain
//
// Anything other than ';' is valid for name.
// Anything before '@' is valid for email.
// For domain, only A-Z, a-z, and 0-9, as well as '-' and '.' are valid.
sscanf("%[^;]; %[^@]@%[-." ALNUM "]", name, email, domain);
</code>```

then you'd run into trouble because you're now dealing with a particular state. In such a case, you might prefer working with bufio.Reader to manually parse things. There's also the option of implementing fmt.Scanner. Here's some sample code to give you an idea of how easy it can be to implement fmt.Scanner:

```<code>// Scanset acts as a filter when scanning strings.
// The zero value of a Scanset will discard all non-whitespace characters.
type Scanset struct {
    ps        *string
    delimFunc func(rune) bool
}

// Create a new Scanset to filter delimiter characters.
// Once f(delimChar) returns false, scanning will end.
// If s is nil, characters for which f(delimChar) returns true are discarded.
// If f is nil, !unicode.IsSpace(delimChar) is used
// (i.e. read until unicode.IsSpace(delimChar) returns true).
func NewScanset(s *string, f func(r rune) bool) *Scanset {
    return &Scanset{
        ps:        s,
        delimFunc: f,
    }
}

// Scan implements the fmt.Scanner interface for the Scanset type.
func (s *Scanset) Scan(state fmt.ScanState, verb rune) error {
    if verb != 'v' && verb != 's' {
        return errors.New("scansets only work with %v and %s verbs")
    }
    tok, err := state.Token(false, s.delimFunc)
    if err != nil {
        return err
    }
    if s.ps != nil {
        *s.ps = string(tok)
    }
    return nil
}
</code>```

Playground example

It's not C's scansets, but it's close enough. As mentioned, you should be validating your data anyway, even with formatted input, because formatting lacks context (and adding it while dealing with formatting violates the KISS principle and worsens the readability of your code).

For example, a short regex like [A-Za-z]([A-Za-z0-9-]?.)[A-Za-z0-9] isn't enough to validate a domain name, and a simplistic scanset would simply be the equivalent of [A-Za-z0-9.-]. The scanset, however, would be enough to scan the string from a file or whatever other reader you might be using, but it wouldn't be enough to validate the string alone. For that, a regex or even a proper library would be a much better option.

Title: Go equivalent of C's negated scansets

Body:
What is the way to mimick the negated scansets that exist in C?

For an example input string: aaaa, bbbb

In go using:

fmt.Sscanf(input, "%s, %s", &str1, &str2)

The result is only str1 being set as: aaaa,

In C one could use a format string as "%[^,], %s" to avoid this problem, is there a way to accomplish this in go?

Body:
Go doesn't support this directly like C, partially because you should be reading a line and using something like strings.FieldsFunc. But that's naturally a very simplistic view. For data formatted in a homogeneous manner, you could use bufio.Scanner to essentially do the same thing with any io.Reader. However, if you had to deal with something like this format:

// Name; email@domain
//
// Anything other than ';' is valid for name.
// Anything before '@' is valid for email.
// For domain, only A-Z, a-z, and 0-9, as well as '-' and '.' are valid.
sscanf("%[^;]; %[^@]@%[-." ALNUM "]", name, email, domain);

then you'd run into trouble because you're now dealing with a particular state. In such a case, you might prefer working with bufio.Reader to manually parse things. There's also the option of implementing fmt.Scanner. Here's some sample code to give you an idea of how easy it can be to implement fmt.Scanner:

// Scanset acts as a filter when scanning strings.
// The zero value of a Scanset will discard all non-whitespace characters.
type Scanset struct {
    ps        *string
    delimFunc func(rune) bool
}

// Create a new Scanset to filter delimiter characters.
// Once f(delimChar) returns false, scanning will end.
// If s is nil, characters for which f(delimChar) returns true are discarded.
// If f is nil, !unicode.IsSpace(delimChar) is used
// (i.e. read until unicode.IsSpace(delimChar) returns true).
func NewScanset(s *string, f func(r rune) bool) *Scanset {
    return &Scanset{
        ps:        s,
        delimFunc: f,
    }
}

// Scan implements the fmt.Scanner interface for the Scanset type.
func (s *Scanset) Scan(state fmt.ScanState, verb rune) error {
    if verb != 'v' && verb != 's' {
        return errors.New("scansets only work with %v and %s verbs")
    }
    tok, err := state.Token(false, s.delimFunc)
    if err != nil {
        return err
    }
    if s.ps != nil {
        *s.ps = string(tok)
    }
    return nil
}

Playground example

It's not C's scansets, but it's close enough. As mentioned, you should be validating your data anyway, even with formatted input, because formatting lacks context (and adding it while dealing with formatting violates the KISS principle and worsens the readability of your code).

For example, a short regex like [A-Za-z]([A-Za-z0-9-]?.)[A-Za-z0-9] isn't enough to validate a domain name, and a simplistic scanset would simply be the equivalent of [A-Za-z0-9.-]. The scanset, however, would be enough to scan the string from a file or whatever other reader you might be using, but it wouldn't be enough to validate the string alone. For that, a regex or even a proper library would be a much better option.


问:
Pausing time.time flow
I making a game with Python and Pygame, and I'm using time.time to time the users going through levels. However, I also have a pause menu. How can I make so when the pause menu is open, time.time won't continue?</p>

答:
I think I'd do something like this: Use the time that clock.tick() returns to increase a timer each frame if the game is not paused, and when the user pauses and unpauses the game call it without an argument to discard the time that passed while the game was paused.

```<code>import sys
import pygame as pg

pg.init()
screen = pg.display.set_mode((640, 480))
clock = pg.time.Clock()
font = pg.font.Font(None, 30)
timer = 0
dt = 0
paused = False
running = True

while running:
    for event in pg.event.get():
        if event.type == pg.QUIT:
            running = False
        elif event.type == pg.KEYDOWN:
            paused = not paused
            # This is needed to discard the time that
            # passed while the game was paused.
            clock.tick()

    if not paused:
        timer += dt  # Add delta time to increase the timer.

        screen.fill((30, 30, 30))
        txt = font.render(str(round(timer, 2)), True, (90, 120, 40))
        screen.blit(txt, (20, 20))

        pg.display.flip()
        dt = clock.tick(30) / 1000  # dt = time in seconds since last tick.

pg.quit()
sys.exit()
</code>```

Title: Pausing time.time flow

Body:
I think I'd do something like this: Use the time that clock.tick() returns to increase a timer each frame if the game is not paused, and when the user pauses and unpauses the game call it without an argument to discard the time that passed while the game was paused.

import sys
import pygame as pg

pg.init()
screen = pg.display.set_mode((640, 480))
clock = pg.time.Clock()
font = pg.font.Font(None, 30)
timer = 0
dt = 0
paused = False
running = True

while running:
    for event in pg.event.get():
        if event.type == pg.QUIT:
            running = False
        elif event.type == pg.KEYDOWN:
            paused = not paused
            # This is needed to discard the time that
            # passed while the game was paused.
            clock.tick()

    if not paused:
        timer += dt  # Add delta time to increase the timer.

        screen.fill((30, 30, 30))
        txt = font.render(str(round(timer, 2)), True, (90, 120, 40))
        screen.blit(txt, (20, 20))

        pg.display.flip()
        dt = clock.tick(30) / 1000  # dt = time in seconds since last tick.

pg.quit()
sys.exit()


问:
How to run this subquery in Laravel 5.4 and MySQL
I need to run this subquery in Laravel 5.4 and the answers that I have found on StackOverflow are for Laravel <5.

```<code>SELECT DISTINCT *
                    FROM (
                           SELECT DISTINCT
                             testing_results.pluginName,
                             SUBSTRING_INDEX(SUBSTRING_INDEX(cvss_vector, '#', -1), '/', 1) AS access_vector,
                             SUBSTRING_INDEX(SUBSTRING_INDEX(cvss_vector, '/', 2), '/', -1) AS access_complexity,
                             SUBSTRING_INDEX(SUBSTRING_INDEX(cvss_vector, '/', 3), '/', -1) AS authentication,
                             SUBSTRING_INDEX(SUBSTRING_INDEX(cvss_vector, '/', 4), '/', -1) AS confidentiality,
                             SUBSTRING_INDEX(SUBSTRING_INDEX(cvss_vector, '/', 5), '/', -1) AS integrity,
                             SUBSTRING_INDEX(SUBSTRING_INDEX(cvss_vector, '/', 6), '/', -1) AS availability
                           FROM
                             testing_results
                           WHERE
                             testing_results.cvss_vector != ''
                         ) sub
                         WHERE sub.access_vector LIKE '%AV:L%'
</code>```

Thank you very in advanced for your help.

Best regards,

答:
Simplest way to do this is:</p>

```<code>$query = <<<SQL
SELECT DISTINCT *
                FROM (
                       SELECT DISTINCT
                         testing_results.pluginName,
                         SUBSTRING_INDEX(SUBSTRING_INDEX(cvss_vector, '#', -1), '/', 1) AS access_vector,
                         SUBSTRING_INDEX(SUBSTRING_INDEX(cvss_vector, '/', 2), '/', -1) AS access_complexity,
                         SUBSTRING_INDEX(SUBSTRING_INDEX(cvss_vector, '/', 3), '/', -1) AS authentication,
                         SUBSTRING_INDEX(SUBSTRING_INDEX(cvss_vector, '/', 4), '/', -1) AS confidentiality,
                         SUBSTRING_INDEX(SUBSTRING_INDEX(cvss_vector, '/', 5), '/', -1) AS integrity,
                         SUBSTRING_INDEX(SUBSTRING_INDEX(cvss_vector, '/', 6), '/', -1) AS availability
                       FROM
                         testing_results
                       WHERE
                         testing_results.cvss_vector != ''
                     ) sub
                     WHERE sub.access_vector LIKE '%AV:L%'
SQL;

dd(DB::select($query));
</code>```

Body:
I need to run this subquery in Laravel 5.4 and the answers that I have found on StackOverflow are for Laravel <5.

SELECT DISTINCT *
                    FROM (
                           SELECT DISTINCT
                             testing_results.pluginName,
                             SUBSTRING_INDEX(SUBSTRING_INDEX(cvss_vector, '#', -1), '/', 1) AS access_vector,
                             SUBSTRING_INDEX(SUBSTRING_INDEX(cvss_vector, '/', 2), '/', -1) AS access_complexity,
                             SUBSTRING_INDEX(SUBSTRING_INDEX(cvss_vector, '/', 3), '/', -1) AS authentication,
                             SUBSTRING_INDEX(SUBSTRING_INDEX(cvss_vector, '/', 4), '/', -1) AS confidentiality,
                             SUBSTRING_INDEX(SUBSTRING_INDEX(cvss_vector, '/', 5), '/', -1) AS integrity,
                             SUBSTRING_INDEX(SUBSTRING_INDEX(cvss_vector, '/', 6), '/', -1) AS availability
                           FROM
                             testing_results
                           WHERE
                             testing_results.cvss_vector != ''
                         ) sub
                         WHERE sub.access_vector LIKE '%AV:L%'

Thank you very in advanced for your help.

Best regards,

Body:
Simplest way to do this is:

$query = <<<SQL
SELECT DISTINCT *
                FROM (
                       SELECT DISTINCT
                         testing_results.pluginName,
                         SUBSTRING_INDEX(SUBSTRING_INDEX(cvss_vector, '#', -1), '/', 1) AS access_vector,
                         SUBSTRING_INDEX(SUBSTRING_INDEX(cvss_vector, '/', 2), '/', -1) AS access_complexity,
                         SUBSTRING_INDEX(SUBSTRING_INDEX(cvss_vector, '/', 3), '/', -1) AS authentication,
                         SUBSTRING_INDEX(SUBSTRING_INDEX(cvss_vector, '/', 4), '/', -1) AS confidentiality,
                         SUBSTRING_INDEX(SUBSTRING_INDEX(cvss_vector, '/', 5), '/', -1) AS integrity,
                         SUBSTRING_INDEX(SUBSTRING_INDEX(cvss_vector, '/', 6), '/', -1) AS availability
                       FROM
                         testing_results
                       WHERE
                         testing_results.cvss_vector != ''
                     ) sub
                     WHERE sub.access_vector LIKE '%AV:L%'
SQL;

dd(DB::select($query));


问:
How to set the shadow of TextView border
I want to set a shadow for the TextView border

```<code>TextView t = new TextView(getBaseContext());
</code>```

If I implement the below code, it creates a shadow for the text within the TextView

```<code>t.setShadowLayer(1.5f, -1, 1, Color.BLACK);
</code>```

But is there a way to set the shadow for the TextView's border?

答: To get the shadow effect on the border, you can wrap the TextView in a CardView.</p>

Body:
I want to set a shadow for the TextView border

TextView t = new TextView(getBaseContext());

If I implement the below code, it creates a shadow for the text within the TextView

t.setShadowLayer(1.5f, -1, 1, Color.BLACK);

But is there a way to set the shadow for the TextView's border?


问:
How to put name an array of JSON objects using GSON?
I'm creating a JSON file with GSON, but the arrays doesn't have names.

My result:

```<code>[
      {
      "name": Jonh,
      "date": "Feb 16, 2066",
      "hour": "10:15:00 PM"
   },
      {
      "name": Maria,
      "date": "Feb 16, 2066",
      "hour": "10:15:00 PM"
   }
]
</code>```

What I need:

```<code>{
  "users": {
    "user": [
      {
        "name": John,
        "date": "Feb 16, 2066",
        "hour": "10:15:00 PM"
      },
      {
        "name": Maria,
        "date": "Feb 16, 2066",
        "hour": "10:15:00 PM"
      }
    ]
  }
}
</code>```

Someone knows how can I put name an arrays?

--EDIT

I'm using this code for generate my JSON file.

```<code>    @GET
    @Produces(MediaType.APPLICATION_JSON)
    @Path("user/list")
    public String getListUsers() throws Exception {

        List<Object> list;

        UserDAOImpl daoUser = new UserDAOImpl();
        list = daoUser.listAllUsers();

        Gson g = new Gson();
        return g.toJson(list);

    }
</code>```

答:
Try this.</p>

```<code>Map<String, List<Object>> user = new TreeMap<>();
user.put("user", list);
Map<String, Map<String, List<Object>>> users = new TreeMap<>();
users.put("users", user);
Gson gson = new Gson();
return gson.toJson(users);
</code>```

Body:
I'm creating a JSON file with GSON, but the arrays doesn't have names.

My result:

[
      {
      "name": Jonh,
      "date": "Feb 16, 2066",
      "hour": "10:15:00 PM"
   },
      {
      "name": Maria,
      "date": "Feb 16, 2066",
      "hour": "10:15:00 PM"
   }
]

What I need:

{
  "users": {
    "user": [
      {
        "name": John,
        "date": "Feb 16, 2066",
        "hour": "10:15:00 PM"
      },
      {
        "name": Maria,
        "date": "Feb 16, 2066",
        "hour": "10:15:00 PM"
      }
    ]
  }
}

Someone knows how can I put name an arrays?

--EDIT

I'm using this code for generate my JSON file.

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    @Path("user/list")
    public String getListUsers() throws Exception {

        List<Object> list;

        UserDAOImpl daoUser = new UserDAOImpl();
        list = daoUser.listAllUsers();

        Gson g = new Gson();
        return g.toJson(list);

    }

Body:
Try this.

Map<String, List<Object>> user = new TreeMap<>();
user.put("user", list);
Map<String, Map<String, List<Object>>> users = new TreeMap<>();
users.put("users", user);
Gson gson = new Gson();
return gson.toJson(users);


问:
Dispatch Queues for Asynchronous Web Service Call
I'm calling the Facebook Graph API to get the email, facebook ID and name of a user that logs into my app through Facebook.

I  successfully get the information; I'm now trying to use dispatch groups so the function that call graph waits until the graph API call completes before returning. The graph request is asynchronous.

I can't figure out why this code is locking up.

1) Create a dispatch group

2) Enter said display group

3) Leave the group once info is retrieved or an error is found

4) Wait for the group leave before returning

It seems like my dispatch group enter is not called correctly but I can't figure out why.

```<code>class func getFBInformation()->Bool {
    var fbResult = false

    let fbGraphGroup = DispatchGroup()

    fbGraphGroup.enter()

    FBSDKGraphRequest(graphPath: "/me", parameters: ["fields": "id, name, email"]).start { (connection, result, err) in
        if err != nil {
            fbResult = false
            print("Pre Error Signal")
            fbGraphGroup.leave()
            return
        }

        if let resultDict = result as? [String:AnyObject] {
            <Do things with graph results>

            print("Pre success signal")
            fbResult = true
            fbGraphGroup.leave()
        }
    }

    fbGraphGroup.wait()
    print("Post signal")

    return fbResult
}
</code>```

答:
How could it work?
First you enter the group, next you are waiting on main thread for completion handler until it leave the group. But the completion handler is not able to execute on the main thread to be able to leave the group.

As far as I know, your completion handler is dispatched on the main queue by the API. It is not necessary to use any other kind of synchronization.

Body:
I'm calling the Facebook Graph API to get the email, facebook ID and name of a user that logs into my app through Facebook.

I  successfully get the information; I'm now trying to use dispatch groups so the function that call graph waits until the graph API call completes before returning. The graph request is asynchronous.

I can't figure out why this code is locking up.

1) Create a dispatch group

2) Enter said display group

3) Leave the group once info is retrieved or an error is found

4) Wait for the group leave before returning

It seems like my dispatch group enter is not called correctly but I can't figure out why.

class func getFBInformation()->Bool {
    var fbResult = false

    let fbGraphGroup = DispatchGroup()

    fbGraphGroup.enter()

    FBSDKGraphRequest(graphPath: "/me", parameters: ["fields": "id, name, email"]).start { (connection, result, err) in
        if err != nil {
            fbResult = false
            print("Pre Error Signal")
            fbGraphGroup.leave()
            return
        }

        if let resultDict = result as? [String:AnyObject] {
            <Do things with graph results>

            print("Pre success signal")
            fbResult = true
            fbGraphGroup.leave()
        }
    }

    fbGraphGroup.wait()
    print("Post signal")

    return fbResult
}


问:
Image Buttons that user can only select one of JavaFX
I'm working on a Mood Journal app and at the moment, it asks the user to rate their mood on a scale of 1-5 before saving their entry as shown on the image below.

I want to replace this with 5 small buttons laid out horizontally with respective emoji images as their background. I already have chosen the images I would like to use, and I looked into implementing a normal FX Button or an ImageView, but with those it appears that clicking the button simply does some action; rather, I want the user to only be able to select one at a time (like a Radio Button). How can I accomplish this?

答:
Suggestion 1:

You can use ControlsFX SegmentedButton(Set as the graphic of the button you preferred emoji):

From the doc:

The SegmentedButton is a simple control that forces together a group of ToggleButton instances such that they appear as one collective button (with sub-buttons), rather than as individual buttons. This is better clarified with a picture:

There is very little API on this control, you essentially create ToggleButton instances as per usual (and don't bother putting them into a ToggleGroup, as this is done by the SegmentedButton itself), and then you place these buttons inside the buttons list. The long-hand way to code this is as follows:

```<code> ToggleButton b1 = new ToggleButton("day");
 ToggleButton b2 = new ToggleButton("week");
 ToggleButton b3 = new ToggleButton("month");
 ToggleButton b4 = new ToggleButton("year");

 SegmentedButton segmentedButton = new SegmentedButton();
 segmentedButton.getButtons().addAll(b1, b2, b3, b4);
</code>```

A slightly shorter way of doing this is to pass the ToggleButton instances into the varargs constructor, as such:

```<code>SegmentedButton segmentedButton = new SegmentedButton(b1, b2, b3, b4);
</code>```

Suggestion 2:

You can use ControlsFX Rating :

From the docs:

A control for allowing users to provide a rating. This control supports partial ratings (i.e. not whole numbers and dependent upon where the user clicks in the control) and updating the rating on hover.

To create a Rating control that looks like this is simple:

```<code>final Rating rating = new Rating();
</code>```

This creates a default horizontal rating control. To create a vertical Rating control, simply change the orientation, as such:

```<code>final Rating rating = new Rating();
 rating.setOrientation(Orientation.VERTICAL);
</code>```

You can continue reading from the doc...

Suggestion 3:(No Third Library Needed)

You can make a custom ToolBar with 5 Button , each one will have a PseudoClass(selected) and every time one of them is pressed the others will have the Pseudoclass(selected=false) , so the user can see which one is selected.

So you can make something similar to :

Read this article if you want to implement it -> http://fxexperience.com/2012/02/customized-segmented-toolbar-buttons/

Body:
Suggestion 1:

You can use ControlsFX SegmentedButton(Set as the graphic of the button you preferred emoji):

From the doc:

The SegmentedButton is a simple control that forces together a group of ToggleButton instances such that they appear as one collective button (with sub-buttons), rather than as individual buttons. This is better clarified with a picture:

There is very little API on this control, you essentially create ToggleButton instances as per usual (and don't bother putting them into a ToggleGroup, as this is done by the SegmentedButton itself), and then you place these buttons inside the buttons list. The long-hand way to code this is as follows:

 ToggleButton b1 = new ToggleButton("day");
 ToggleButton b2 = new ToggleButton("week");
 ToggleButton b3 = new ToggleButton("month");
 ToggleButton b4 = new ToggleButton("year");

 SegmentedButton segmentedButton = new SegmentedButton();
 segmentedButton.getButtons().addAll(b1, b2, b3, b4);

A slightly shorter way of doing this is to pass the ToggleButton instances into the varargs constructor, as such:

SegmentedButton segmentedButton = new SegmentedButton(b1, b2, b3, b4);

Suggestion 2:

You can use ControlsFX Rating :

From the docs:

A control for allowing users to provide a rating. This control supports partial ratings (i.e. not whole numbers and dependent upon where the user clicks in the control) and updating the rating on hover.

To create a Rating control that looks like this is simple:

final Rating rating = new Rating();

This creates a default horizontal rating control. To create a vertical Rating control, simply change the orientation, as such:

final Rating rating = new Rating();
 rating.setOrientation(Orientation.VERTICAL);

You can continue reading from the doc...

Suggestion 3:(No Third Library Needed)

You can make a custom ToolBar with 5 Button , each one will have a PseudoClass(selected) and every time one of them is pressed the others will have the Pseudoclass(selected=false) , so the user can see which one is selected.

So you can make something similar to :

Read this article if you want to implement it -> http://fxexperience.com/2012/02/customized-segmented-toolbar-buttons/


问:
How can I create a transparent tableview with each cells being transparent?
I tried all this inside

```<code>- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
1.tableView.backgroundColor = [UIColor clearColor];
2.cell.backgroundColor = [UIColor clearColor];
3.cell.contentView.backgroundColor = [UIColor clearColor];
</code>```

It only responds to the 1st line and makes the background a translucent kind of black. What should I do to get 100% transparency?

答:
I've had this same problem before.  As suggested in a comment, try [setOpaque:NO]

If push comes to shove, make a simple 1px clear .png.  Then, make a stretchable UIImage with it, and say [setBackgroundView:imageViewWithClearImage].  That's a bit hacky, though.

Body:
I tried all this inside

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
1.tableView.backgroundColor = [UIColor clearColor];
2.cell.backgroundColor = [UIColor clearColor];
3.cell.contentView.backgroundColor = [UIColor clearColor];

It only responds to the 1st line and makes the background a translucent kind of black. What should I do to get 100% transparency?


问:
"using namespace std;" without any #include?
I tried following, it worked without problem, but in this situation, std was not defined.</p>

```<code>    using namespace std;

    int main()
    {
       ....
    }
</code>```

答:
All using namespace std does is tell the compiler that, when an identifier (named variable, type, etc) appears in code, to look in the std namespace for candidates to match the name.

Within your main() function, no identifiers are being used at all (the {} is an empty block).   So there is no need to find matching candidates, and the result of compiling will be the same in both cases.

If you add a statement like cout << "Hello\n" to main(), then the using namespace std will cause the compiler to consider anything named cout  within namespace std as a valid match for the identifier cout.   If this comes after #include <iostream>, then std::cout is considered a viable match.   If declarations in <iostream> are not visible to the compiler (in your case, because there is no #include <iostream>) then the compiler cannot consider std::cout to be a candidate match for cout, and will issue a diagnostic accordingly.

The C++ standard does not specify anything different about std or about using directives that require using namespace std and using namespace othername to behave differently.   If your compiler treats them differently (recognising namespace std but not others, even if there is no declaration of one) then that is specific to your compiler.

Body:
I tried following, it worked without problem, but in this situation, std was not defined.

    using namespace std;

    int main()
    {
       ....
    }


问:
Is there a way to automatically generate getters and setters in Eclipse?
I am working on a new Android project (Java), and created an Object with a large number of variables. Since I am planning to add getters and setters for all of them, I was wondering: is there a shortcut in Eclipse for automatically generating the getters and setters in a given class?

答:
Open the class file in Eclipse

Double click on the class name or highlight it

Then navigate to Source -> Insert Code

Click on Getter and Setter

It opens a popup to select the fields for which getter/setter methods to be generated. Select the fields and click on "Generate" button.


问:
Grouped alternating row colors with a variation
This is a simple logical problem but I am having a mental block. I have groups of rows as follows:

Observe the following:

Group #1 has 2 records

Group #2 has 2 records

Group #3 has 1 record

Group #4 has 2 records

Group #5 has 1 record

Group #6 has 2 records

I want each record in each group to have the same background color as the other records in the group, yet a different background color from the next grouping after it. So, what I am trying to achieve is:

Both records in group 1 should have a white background color.

Both records in group 2 should have a gray background color.

The sole record in group 3 should have a white background color.

Both records in group 4 should have a gray background color.

...and so forth. So instead of the typical alternating row colors in which each record's bgcolor alternates, I want each group's bgcolor to alternate, while the colors within each group stays consistent with each other.

My current logic does this:

```<code>if($gameID != $previousGameID)
    $rowColor = "#ffffff";
else
    $rowColor = "#F0F0F0";
</code>```

Although that code is PHP, this question is not unique to PHP, it's just a logic problem, which is why I tagged this question with PHP, C#, and JS (3 languages I know). My code above is wrong because it causes the background color to change for each record, rather than for each group of records. The records in each group have the same gameID, and that gameID will be different from all other groups. So the gameID is part of the key to solving this little puzzle, but I can't get my head around the solution.

Note: You cannot assume that each grouping will have either 1 or 2 records. Although my example doesn't show it, on rare occasions there will be 3 records in a group (and all 3 in that case would have the same gameID as each other).

Any ideas?

答:
The problem with the current logic is that you always change $rowColor, even when gameID hasn't changed.

Create an alternateColor() function that, when invoked, changes $rowColor between gray and white.

Then update you condition to

```<code>if($gameID != $previousGameID)
    alternateColor();
</code>```

and then use the updated $rowColor.

This solution will work for any type of IDs (number, string etc.). A simple case would be that of numeric sequential IDs, that is: 1, 2, 3 etc. In this case the logic could be:

```<code>if ($gameID % 2 == 0)
    $rowColor = "#ffffff";
else
    $rowColor = "#F0F0F0";
</code>```

That is, based on the fact that an ID is odd or even, the corresponding color is picked.

UPDATE:

Regarding sequential IDs, I didn't imply your IDs were sequential. I implied that if they were, than the modulus solution would be enough. The alternateColor() function approach will work for any type of IDs.

As an example of alternateColor(), consider this (C#):

Inside the class where your logic is, create an instance method AlternateColor  AND make sure your rowColor variable is an instance-level variable:

```<code>private string rowColor == "#ffffff"; // let's start with white

private void AlternateColor()
{
    this.currentColor = this.currentColor == "#ffffff" ? "#F0F0F0" : "#ffffff";
}
</code>```

Now every time you call AlternateColor it will alternate rowColor between the two colors. And this is done when the current gameID changes.

UPDATE 2:

Not sure about the correctness of the following PHP, but you should get the idea:

```<code>class Games {
  private var $rowColor;

  private function alternateColor(){
     $this->$rowColor = ($this->$rowColor == "#ffffff" ? "#F0F0F0" : "#ffffff");
  }

  public function theFuncWhereYouOutputTheTable(){
     ...

     if($gameID != $previousGameID)
         $this->alternateColor();

     // use $rowColor afterwards
     ...
  }

}
</code>```

Body:
This is a simple logical problem but I am having a mental block. I have groups of rows as follows:

Observe the following:

Group #1 has 2 records

Group #2 has 2 records

Group #3 has 1 record

Group #4 has 2 records

Group #5 has 1 record

Group #6 has 2 records

I want each record in each group to have the same background color as the other records in the group, yet a different background color from the next grouping after it. So, what I am trying to achieve is:

Both records in group 1 should have a white background color.

Both records in group 2 should have a gray background color.

The sole record in group 3 should have a white background color.

Both records in group 4 should have a gray background color.

...and so forth. So instead of the typical alternating row colors in which each record's bgcolor alternates, I want each group's bgcolor to alternate, while the colors within each group stays consistent with each other.

My current logic does this:

if($gameID != $previousGameID)
    $rowColor = "#ffffff";
else
    $rowColor = "#F0F0F0";

Although that code is PHP, this question is not unique to PHP, it's just a logic problem, which is why I tagged this question with PHP, C#, and JS (3 languages I know). My code above is wrong because it causes the background color to change for each record, rather than for each group of records. The records in each group have the same gameID, and that gameID will be different from all other groups. So the gameID is part of the key to solving this little puzzle, but I can't get my head around the solution.

Note: You cannot assume that each grouping will have either 1 or 2 records. Although my example doesn't show it, on rare occasions there will be 3 records in a group (and all 3 in that case would have the same gameID as each other).

Any ideas?

Body:
The problem with the current logic is that you always change $rowColor, even when gameID hasn't changed.

Create an alternateColor() function that, when invoked, changes $rowColor between gray and white.

Then update you condition to

if($gameID != $previousGameID)
    alternateColor();

and then use the updated $rowColor.

This solution will work for any type of IDs (number, string etc.). A simple case would be that of numeric sequential IDs, that is: 1, 2, 3 etc. In this case the logic could be:

if ($gameID % 2 == 0)
    $rowColor = "#ffffff";
else
    $rowColor = "#F0F0F0";

That is, based on the fact that an ID is odd or even, the corresponding color is picked.

UPDATE:

Regarding sequential IDs, I didn't imply your IDs were sequential. I implied that if they were, than the modulus solution would be enough. The alternateColor() function approach will work for any type of IDs.

As an example of alternateColor(), consider this (C#):

Inside the class where your logic is, create an instance method AlternateColor  AND make sure your rowColor variable is an instance-level variable:

private string rowColor == "#ffffff"; // let's start with white

private void AlternateColor()
{
    this.currentColor = this.currentColor == "#ffffff" ? "#F0F0F0" : "#ffffff";
}

Now every time you call AlternateColor it will alternate rowColor between the two colors. And this is done when the current gameID changes.

UPDATE 2:

Not sure about the correctness of the following PHP, but you should get the idea:

class Games {
  private var $rowColor;

  private function alternateColor(){
     $this->$rowColor = ($this->$rowColor == "#ffffff" ? "#F0F0F0" : "#ffffff");
  }

  public function theFuncWhereYouOutputTheTable(){
     ...

     if($gameID != $previousGameID)
         $this->alternateColor();

     // use $rowColor afterwards
     ...
  }

}