问:
Modify the code (lapply function) in R
How can I modify this code (or add more functions) in a way that

I could have the name of each element of responseList in summaries instead of having [[1]], [[2]],....

How can I extract the hp:am with the p-value less than 0.05

How can I have the normality plot of residual (but all histograms in just one page)

Example:

```<code>responseList <- names(mtcars)[-c(4,9)]
modelList <- lapply(responseList, function(resp) {
    mF <- formula(paste(resp, " ~ hp * am"))
    aov(mF, data = mtcars)
})
summaries <- lapply(modelList, summary)
resid <- lapply(modelList, resid)
normal <- lapply(resid, function(x) shapiro.test(x))
</code>```

答:
[ 1]

```<code>modelList <- lapply(mtcars[-c(4,9)], function(x) aov(x ~ hp*am, data=mtcars) )
</code>```

[2]

```<code>df2 <- plyr::ldply(modelList, function(x) summary(x)[[1]][["Pr(>F)"]])
names(df2) <- c(attr(modelList[[1]]$terms, "term.labels"), "residuals")
</code>```

[3]

```<code>res.list <- lapply(modelList, '[[', "residuals")

par(mfrow=c(5,2), oma=c(0,0,0,0))
lapply(res.list, hist)
</code>```

Title: Modify the code (lapply function) in R

Body:
How can I modify this code (or add more functions) in a way that

I could have the name of each element of responseList in summaries instead of having [[1]], [[2]],....

How can I extract the hp:am with the p-value less than 0.05

How can I have the normality plot of residual (but all histograms in just one page)

Example:

responseList <- names(mtcars)[-c(4,9)]
modelList <- lapply(responseList, function(resp) {
    mF <- formula(paste(resp, " ~ hp * am"))
    aov(mF, data = mtcars)
})
summaries <- lapply(modelList, summary)
resid <- lapply(modelList, resid)
normal <- lapply(resid, function(x) shapiro.test(x))

Body:
[ 1]

modelList <- lapply(mtcars[-c(4,9)], function(x) aov(x ~ hp*am, data=mtcars) )

[2]

df2 <- plyr::ldply(modelList, function(x) summary(x)[[1]][["Pr(>F)"]])
names(df2) <- c(attr(modelList[[1]]$terms, "term.labels"), "residuals")

[3]

res.list <- lapply(modelList, '[[', "residuals")

par(mfrow=c(5,2), oma=c(0,0,0,0))
lapply(res.list, hist)


来源: stackexchange

问:
No datas coming from Firebase : Todo list
I'm really angry against myself because I can't figure it out. My problem is I need to use firebase for a big project, but it's my first time with it, and with noSQL. So I started the Todo list tutorial using ionic creator (https://www.youtube.com/watch?v=IrwrZBBOiP8&list=PLG71uQ6L5PWNOsIDFrP3X-_s-W4T6vBzP).

My problem is, I set the database like this :

Tried, like that :

Here you can find the service I use and how I call it on todos pages :

//todos.js file

angular.module('todos', ['firebase'])

.run(function(){

  // Initialize Firebase
  var config = {
    apiKey: "//",
    authDomain: "//",
    databaseURL: "//",
    storageBucket: "//",
  };
  firebase.initializeApp(config);

})

.service("Todos", ["$firebaseArray", function($firebaseArray){
    var ref = firebase.database().ref().child("todos");
    var items = $firebaseArray(ref);

    var todos = {
        items: items,
        addItem: function(title){
            items.$add({
                title: title,
            })
        },
        setFinished: function(item, newV){
            item.finished = newV;
            items.$save(item);
        }
    }
    return todos;
}]);```
</div>
</div>
</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>// todos page

function ($scope, $stateParams, Todos) {

    $scope.items = Todos.items;
}

// Finished item page

function ($scope, $stateParams, Todos) {

    $scope.items = Todos.items;
}

// todo item page

function ($scope, $stateParams) {

    $scope.itemid = $stateParams.items;

}</code>```

And I still have no datas coming from Firebase, I tried to print "Todos.items" in the console, but there are too many fields in this array, I can't find my datas. When starting the app, I have these blanks pages but no errors :

答:
Just go to your Firebase project/database/rules and allow read option. </p>

```<code>{
  "rules": {
    ".read": true,
    ".write": "auth != null"
  }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm really angry against myself because I can't figure it out. My problem is I need to use firebase for a big project, but it's my first time with it, and with noSQL. So I started the Todo list tutorial using ionic creator (https://www.youtube.com/watch?v=IrwrZBBOiP8&list=PLG71uQ6L5PWNOsIDFrP3X-_s-W4T6vBzP).

My problem is, I set the database like this :

Tried, like that :

Here you can find the service I use and how I call it on todos pages :

//todos.js file

angular.module('todos', ['firebase'])

.run(function(){

  // Initialize Firebase
  var config = {
    apiKey: "//",
    authDomain: "//",
    databaseURL: "//",
    storageBucket: "//",
  };
  firebase.initializeApp(config);

})

.service("Todos", ["$firebaseArray", function($firebaseArray){
    var ref = firebase.database().ref().child("todos");
    var items = $firebaseArray(ref);

    var todos = {
        items: items,
        addItem: function(title){
            items.$add({
                title: title,
            })
        },
        setFinished: function(item, newV){
            item.finished = newV;
            items.$save(item);
        }
    }
    return todos;
}]);

// todos page

function ($scope, $stateParams, Todos) {

    $scope.items = Todos.items;
}

// Finished item page

function ($scope, $stateParams, Todos) {

    $scope.items = Todos.items;
}

// todo item page

function ($scope, $stateParams) {

    $scope.itemid = $stateParams.items;

}

And I still have no datas coming from Firebase, I tried to print "Todos.items" in the console, but there are too many fields in this array, I can't find my datas. When starting the app, I have these blanks pages but no errors :

Body:
Just go to your Firebase project/database/rules and allow read option.

{
  "rules": {
    ".read": true,
    ".write": "auth != null"
  }
}


问:
jQuery detecting cookies enabled
I have a jQuery-based web app. My requirement is fairly simple: I want to use jQuery to find out if the user has enabled or disabled cookies in their web browser. I'm aware that there's a plugin available which can be used to create/retrieve/delete/update a cookie. But, is there a way jQuery can detect the user agent's settings?</p>

答:
Why are you testing with the property cookieEnabled? just try to create a cookie and check if it's done. And in case cookies work, delete the test created cookie.

```<code> function are_cookies_enabled()
    {
            document.cookie="testcookie=valid";
            cookieEnabled = (document.cookie.indexOf("testcookie") != -1) ? true : false;

            if(cookieEnabled){
               document.cookie = "testcookie=; expires=Thu, 01 Jan 1970 00:00:00 UTC;";
            }

            return cookieEnabled;
    }
</code>```

Title: jQuery detecting cookies enabled

Body:
Why are you testing with the property cookieEnabled? just try to create a cookie and check if it's done. And in case cookies work, delete the test created cookie.

 function are_cookies_enabled()
    {
            document.cookie="testcookie=valid";
            cookieEnabled = (document.cookie.indexOf("testcookie") != -1) ? true : false;

            if(cookieEnabled){
               document.cookie = "testcookie=; expires=Thu, 01 Jan 1970 00:00:00 UTC;";
            }

            return cookieEnabled;
    }


问:
Create Multidimensional Array grouped by week and user while showing zero values
Here is what I have so far:

```<code>$year = date("Y");
$start = "01/01/".$year;
$today = date("Y-m-d");
$first = $year."-05-14";

$volumeYTDsm = [];

$assignments = "
SELECT COUNT(j.leadid) AS leadcount, DATE_ADD(j.leadcreated, INTERVAL(1-DAYOFWEEK(j.leadcreated)) DAY) AS weeks,
  DATE_ADD(j.leadcreated, INTERVAL(7-DAYOFWEEK(j.leadcreated)) DAY), u.username
  FROM jobbooktbl j
  INNER JOIN assignmentstbl a
    ON j.leadid=a.custid
  INNER JOIN usertbl u
    ON a.userid=u.userid
  WHERE j.leadcreated >= '".$first."' AND j.leadcreated <= '".$today."' AND YEAR(j.leadcreated) = '".$year."'
  GROUP BY WEEK(j.leadcreated), a.userid";
$assignmentsqry = mysqli_query($db,$assignments);
while ($row = mysqli_fetch_array($assignmentsqry)) {
  $sm = $row['username'];
  $float = floatval($row['leadcount']);
  $date = $row["weeks"];
  $newdate = date("n/j/Y", strtotime($date));
  array_push($volumeYTDsm, [$sm,$float]);
}
</code>```

This outputs the following multidimensional array:

```<code>[["Ryan Balcom",10],["Ryan Balcom",1],["Jared Beckwith",13],["Jared Beckwith",7],["Jared Beckwith",5],["Jared Beckwith",2],["Jim Roberts",9],["Jim Roberts",4],["Jim Roberts",2],["Jim Roberts",4],["Jim Kelly",14],["Jim Kelly",16],["Jim Kelly",10],["Jim Kelly",6],["Josh Bell",9],["Josh Bell",8],["Josh Bell",5],["Josh Bell",10],["Mike Horton",16],["Mike Horton",5],["Mike Horton",5],["Mike Horton",2],["Paul Schilthuis",7],["Paul Schilthuis",6],["Paul Schilthuis",4]]
</code>```

There are two problems with this outcome that I am having trouble rectifying.

1. I need the count to return 0 if the count is 0.
I have tried the following to no avail:

```<code>COALESCE(COUNT(j.leadid),0) AS leadcount
IFNULL(COUNT(j.leadid),0) AS leadcount
</code>```

2. I need the inner arrays to be actually grouped by the users like the following:

```<code>[["Ryan Balcom",0,0,10,1],["Jared Beckwith",13,7,5,2],["Jim Roberts",9,4,2,4],["Jim Kelly",14,16,10,6],["Josh Bell",9,8,5,10],["Mike Horton",16,5,5,2],["Paul Schilthuis",0,7,6,4]]
</code>```

I am still learning these more complex queries.

Update

Thanks to Waldson Patricio, half of the puzzle is solved.  Now the array is formatting properly but it is not portraying 0s as I would like them to.

Here is the updated code:

```<code>$assignments = "
  SELECT COUNT(j.leadid) AS leadcount, DATE_ADD(j.leadcreated, INTERVAL(1-DAYOFWEEK(j.leadcreated)) DAY) AS weeks,
    DATE_ADD(j.leadcreated, INTERVAL(7-DAYOFWEEK(j.leadcreated)) DAY), u.username
  FROM jobbooktbl j
  LEFT JOIN assignmentstbl a
    ON j.leadid=a.custid
  LEFT JOIN usertbl u
    ON a.userid=u.userid
  WHERE j.leadcreated >= '".$first."' AND j.leadcreated <= '".$today."' AND YEAR(j.leadcreated) = '".$year."' AND u.salesman = 1
  GROUP BY WEEK(j.leadcreated), a.userid";
$assignmentsqry = mysqli_query($db,$assignments);
while ($row = mysqli_fetch_array($assignmentsqry)) {
  $key = $row['username']; //unnecessary variable for demonstration purposes
  if (!isset($volumeYTDsm[$key])) {
    $volumeYTDsm[$key] = [$row['username']];
  }
  $float = floatval($row['leadcount']);
    $volumeYTDsm[$key][] = $float;
  }
  $volumeYTDsm = array_values($volumeYTDsm);//removing keys
}
</code>```

This outputs:

```<code>[["Ryan Balcom",10,1],["Jared Beckwith",13,7,5,2],["Jim Roberts",9,4,2,4],["Jim Kelly",14,16,10,6],["Josh Bell",9,8,5,10],["Mike Horton",16,5,5,2],["Paul Schilthuis",7,6,4]]
</code>```

I have tried changing the joins to below but that did not work either:

```<code>FROM usertbl u
LEFT JOIN assignmentstbl a
  ON u.userid=a.userid
LEFT JOIN jobbooktbl j
  ON a.custid=j.leadid
</code>```

I have also tried coalesce and ifnull and nothing:

```<code>COALESCE(COUNT(j.leadid),0) AS leadcount
IFNULL(COUNT(j.leadid),0) AS leadcount
</code>```

答:
Answering your questions:

I need the count to return 0 if the count is 0

You're selecting from  jobbooktbl j and inner joining with assignmentstbl a  ON j.leadid=a.custid. This ON clause ensures that leadid must be equal to a.custid. Your count will never be 0. If you want rows from j that doesn't have relations with a table, use LEFT JOIN instead of INNER JOIN (for this to work, you should do the same with the other INNER JOIN too):

```<code>$assignments = "
SELECT COUNT(j.leadid) AS leadcount, DATE_ADD(j.leadcreated, INTERVAL(1-DAYOFWEEK(j.leadcreated)) DAY) AS weeks,
  DATE_ADD(j.leadcreated, INTERVAL(7-DAYOFWEEK(j.leadcreated)) DAY), u.username
  FROM jobbooktbl j
  LEFT JOIN assignmentstbl a
    ON j.leadid=a.custid
  LEFT JOIN usertbl u
    ON a.userid=u.userid
  WHERE j.leadcreated >= '".$first."' AND j.leadcreated <= '".$today."' AND YEAR(j.leadcreated) = '".$year."'
  GROUP BY WEEK(j.leadcreated), a.userid";
</code>```

I need the inner arrays to be actually grouped by the users like the following:

Here, I'm assuming that u.username is unique (if it isn't, you could add u.userid in your field list and use it as key instead of username):

```<code>$assignmentsqry = mysqli_query($db,$assignments);
while ($row = mysqli_fetch_array($assignmentsqry)) {
    $key = $row['username']; //unnecessary variable for demonstration purposes

    if (!isset($volumeYTDsm[$key])) {
        $volumeYTDsm[$key] = [$row['username']];
    }

    $float = floatval($row['leadcount']);
    $volumeYTDsm[$key][] = $float;
    //$date = $row["weeks"]; // You're not using it
    //$newdate = date("n/j/Y", strtotime($date)); // You're not using it
}
$volumeYTDsm = array_values($volumeYTDsm);//removing keys
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Here is what I have so far:

$year = date("Y");
$start = "01/01/".$year;
$today = date("Y-m-d");
$first = $year."-05-14";

$volumeYTDsm = [];

$assignments = "
SELECT COUNT(j.leadid) AS leadcount, DATE_ADD(j.leadcreated, INTERVAL(1-DAYOFWEEK(j.leadcreated)) DAY) AS weeks,
  DATE_ADD(j.leadcreated, INTERVAL(7-DAYOFWEEK(j.leadcreated)) DAY), u.username
  FROM jobbooktbl j
  INNER JOIN assignmentstbl a
    ON j.leadid=a.custid
  INNER JOIN usertbl u
    ON a.userid=u.userid
  WHERE j.leadcreated >= '".$first."' AND j.leadcreated <= '".$today."' AND YEAR(j.leadcreated) = '".$year."'
  GROUP BY WEEK(j.leadcreated), a.userid";
$assignmentsqry = mysqli_query($db,$assignments);
while ($row = mysqli_fetch_array($assignmentsqry)) {
  $sm = $row['username'];
  $float = floatval($row['leadcount']);
  $date = $row["weeks"];
  $newdate = date("n/j/Y", strtotime($date));
  array_push($volumeYTDsm, [$sm,$float]);
}

This outputs the following multidimensional array:

[["Ryan Balcom",10],["Ryan Balcom",1],["Jared Beckwith",13],["Jared Beckwith",7],["Jared Beckwith",5],["Jared Beckwith",2],["Jim Roberts",9],["Jim Roberts",4],["Jim Roberts",2],["Jim Roberts",4],["Jim Kelly",14],["Jim Kelly",16],["Jim Kelly",10],["Jim Kelly",6],["Josh Bell",9],["Josh Bell",8],["Josh Bell",5],["Josh Bell",10],["Mike Horton",16],["Mike Horton",5],["Mike Horton",5],["Mike Horton",2],["Paul Schilthuis",7],["Paul Schilthuis",6],["Paul Schilthuis",4]]

There are two problems with this outcome that I am having trouble rectifying.

1. I need the count to return 0 if the count is 0.
I have tried the following to no avail:

COALESCE(COUNT(j.leadid),0) AS leadcount
IFNULL(COUNT(j.leadid),0) AS leadcount

2. I need the inner arrays to be actually grouped by the users like the following:

[["Ryan Balcom",0,0,10,1],["Jared Beckwith",13,7,5,2],["Jim Roberts",9,4,2,4],["Jim Kelly",14,16,10,6],["Josh Bell",9,8,5,10],["Mike Horton",16,5,5,2],["Paul Schilthuis",0,7,6,4]]

I am still learning these more complex queries.

Update

Thanks to Waldson Patricio, half of the puzzle is solved.  Now the array is formatting properly but it is not portraying 0s as I would like them to.

Here is the updated code:

$assignments = "
  SELECT COUNT(j.leadid) AS leadcount, DATE_ADD(j.leadcreated, INTERVAL(1-DAYOFWEEK(j.leadcreated)) DAY) AS weeks,
    DATE_ADD(j.leadcreated, INTERVAL(7-DAYOFWEEK(j.leadcreated)) DAY), u.username
  FROM jobbooktbl j
  LEFT JOIN assignmentstbl a
    ON j.leadid=a.custid
  LEFT JOIN usertbl u
    ON a.userid=u.userid
  WHERE j.leadcreated >= '".$first."' AND j.leadcreated <= '".$today."' AND YEAR(j.leadcreated) = '".$year."' AND u.salesman = 1
  GROUP BY WEEK(j.leadcreated), a.userid";
$assignmentsqry = mysqli_query($db,$assignments);
while ($row = mysqli_fetch_array($assignmentsqry)) {
  $key = $row['username']; //unnecessary variable for demonstration purposes
  if (!isset($volumeYTDsm[$key])) {
    $volumeYTDsm[$key] = [$row['username']];
  }
  $float = floatval($row['leadcount']);
    $volumeYTDsm[$key][] = $float;
  }
  $volumeYTDsm = array_values($volumeYTDsm);//removing keys
}

This outputs:

[["Ryan Balcom",10,1],["Jared Beckwith",13,7,5,2],["Jim Roberts",9,4,2,4],["Jim Kelly",14,16,10,6],["Josh Bell",9,8,5,10],["Mike Horton",16,5,5,2],["Paul Schilthuis",7,6,4]]

I have tried changing the joins to below but that did not work either:

FROM usertbl u
LEFT JOIN assignmentstbl a
  ON u.userid=a.userid
LEFT JOIN jobbooktbl j
  ON a.custid=j.leadid

I have also tried coalesce and ifnull and nothing:

COALESCE(COUNT(j.leadid),0) AS leadcount
IFNULL(COUNT(j.leadid),0) AS leadcount

Body:
Answering your questions:

I need the count to return 0 if the count is 0

You're selecting from  jobbooktbl j and inner joining with assignmentstbl a  ON j.leadid=a.custid. This ON clause ensures that leadid must be equal to a.custid. Your count will never be 0. If you want rows from j that doesn't have relations with a table, use LEFT JOIN instead of INNER JOIN (for this to work, you should do the same with the other INNER JOIN too):

$assignments = "
SELECT COUNT(j.leadid) AS leadcount, DATE_ADD(j.leadcreated, INTERVAL(1-DAYOFWEEK(j.leadcreated)) DAY) AS weeks,
  DATE_ADD(j.leadcreated, INTERVAL(7-DAYOFWEEK(j.leadcreated)) DAY), u.username
  FROM jobbooktbl j
  LEFT JOIN assignmentstbl a
    ON j.leadid=a.custid
  LEFT JOIN usertbl u
    ON a.userid=u.userid
  WHERE j.leadcreated >= '".$first."' AND j.leadcreated <= '".$today."' AND YEAR(j.leadcreated) = '".$year."'
  GROUP BY WEEK(j.leadcreated), a.userid";

I need the inner arrays to be actually grouped by the users like the following:

Here, I'm assuming that u.username is unique (if it isn't, you could add u.userid in your field list and use it as key instead of username):

$assignmentsqry = mysqli_query($db,$assignments);
while ($row = mysqli_fetch_array($assignmentsqry)) {
    $key = $row['username']; //unnecessary variable for demonstration purposes

    if (!isset($volumeYTDsm[$key])) {
        $volumeYTDsm[$key] = [$row['username']];
    }

    $float = floatval($row['leadcount']);
    $volumeYTDsm[$key][] = $float;
    //$date = $row["weeks"]; // You're not using it
    //$newdate = date("n/j/Y", strtotime($date)); // You're not using it
}
$volumeYTDsm = array_values($volumeYTDsm);//removing keys


问:
"this" pointer in C (not C++)
I'm trying to create a stack in C for fun, and came up with the idea of using struct to represent the stack. Then I add function pointers to the struct for push() and pop() operations.

So far all is good it seems, but, for the implementation of the push() and pop() functions I need to refer to *this somehow. How can that (can it?) be done?

This is my struct

```<code>struct Stack {
    int *data;
    int current_size;
    int max_size;
    int (*push)(int);
    int (*pop)();
};
</code>```

And as an example here's push

```<code>int push(int val) {
    if(current_size == max_size -1)
            return 0;

    data[current_size] = val;
    current_size++;

    return 1;
}
</code>```

As you can imagine, the compiler has no idea what current_size is, as it would expect something like stack->current_size.

Is this possible to overcome somehow?

答: C doesn't work like that. It's not an object oriented language. Functions that manipulate data structures need to take a pointer to the structure as an argument.</p>

ContentLicense: CC BY-SA 2.5

Title: "this" pointer in C (not C++)

Body:
I'm trying to create a stack in C for fun, and came up with the idea of using struct to represent the stack. Then I add function pointers to the struct for push() and pop() operations.

So far all is good it seems, but, for the implementation of the push() and pop() functions I need to refer to *this somehow. How can that (can it?) be done?

This is my struct

struct Stack {
    int *data;
    int current_size;
    int max_size;
    int (*push)(int);
    int (*pop)();
};

And as an example here's push

int push(int val) {
    if(current_size == max_size -1)
            return 0;

    data[current_size] = val;
    current_size++;

    return 1;
}

As you can imagine, the compiler has no idea what current_size is, as it would expect something like stack->current_size.

Is this possible to overcome somehow?


问:
How do I disallow specific page from robots.txt
I am creating two pages on my site that are very similar but serve different purposes. One is to thank users for leaving a comment and the other is to encourage users to subscribe.

I don't want the duplicate content but I do want the pages to be available. Can I set the sitemap to hide one? Would I do this in the robots.txt file?

The disallow looks like this:

Disallow: /wp-admin

How would I customize to the a specific page like:

http://sweatingthebigstuff.com/thank-you-for-commenting

答:
robots.txt files use regular expressions to match pages, so to avoid targeting more pages than you intend, you may need to add a $ to the end of the page name:

```<code>Disallow: /thank-you-for-commenting$
</code>```

If you don't you'll also disallow page /thank-you-for-commenting-on-this-too

Body:
robots.txt files use regular expressions to match pages, so to avoid targeting more pages than you intend, you may need to add a $ to the end of the page name:

Disallow: /thank-you-for-commenting$

If you don't you'll also disallow page /thank-you-for-commenting-on-this-too


问:
Print between specific ranges - sed or awk
How can we achieve this using sed or awk?

I have now included the text in a code block to make it clear.

The code block part should be printed  -  is the requirement.

LOGIC 1:

The text 'abc' will be our keyword here which will be unique and will only occur within the code block part

So we'll have to search for 'abc' and from that line till the last occurrence of 'abc' all lines should be printed inclusive

LOGIC 2:

Based on page numbers i.e. select text between page 1 and page n again inclusive
Note: 'Page 1' and 'Page 1 - Page n' can come multiple times.

The whole text is a part of a 4GB file which needs to be parsed for similar occurrences.

Apologies for not being clear.

START OF TEXT IN THE FILE:

Xyz       Page: 1

a

b

c

d

e

QWE       Page: 1

e

r

t

y

```<code>asdabc       Page: 1

t

y

u

I

o

ghjabc       Page: 2

e

d

c

b

bnmabc       Page: 3

uia

asd

ads
</code>```

thm       Page: 1

as

das

da

END OF TEXT IN FILE

答:
I really don't know what exactly you want to print, but you should be able to use sed:

```<code>sed -n '/start pattern/,/end pattern/p' <file>
</code>```

Body:
How can we achieve this using sed or awk?

I have now included the text in a code block to make it clear.

The code block part should be printed  -  is the requirement.

LOGIC 1:

The text 'abc' will be our keyword here which will be unique and will only occur within the code block part

So we'll have to search for 'abc' and from that line till the last occurrence of 'abc' all lines should be printed inclusive

LOGIC 2:

Based on page numbers i.e. select text between page 1 and page n again inclusive
Note: 'Page 1' and 'Page 1 - Page n' can come multiple times.

The whole text is a part of a 4GB file which needs to be parsed for similar occurrences.

Apologies for not being clear.

START OF TEXT IN THE FILE:

Xyz       Page: 1

a

b

c

d

e

QWE       Page: 1

e

r

t

y

asdabc       Page: 1

t

y

u

I

o

ghjabc       Page: 2

e

d

c

b

bnmabc       Page: 3

uia

asd

ads

thm       Page: 1

as

das

da

END OF TEXT IN FILE

Body:
I really don't know what exactly you want to print, but you should be able to use sed:

sed -n '/start pattern/,/end pattern/p' <file>


问:
Method List in Visual Studio Code
I've recently started using the Visual Studio Code editor.  I'm really loving it, but there's one critical feature (for me) that I haven't been able to find.  Is there a method list, similar to the Navigator in NetBeans or Member dropdown in Visual Studio?</p>

答: CTRL+F12 (CMD+F12 for Mac) - opens for me all methods and members in PHP class.

Title: Method List in Visual Studio Code


问:
Angular js 1.5 - $injector:modulerr
I'm trying to duplicate an angular Material example as described on https://material.angularjs.org/latest/demo/autocomplete and it's driving me nuts.

I get the following error every time, everywhere (on my machine and JSfiddle)

```<code>> Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.5.5/$injector/modulerr?p0=autocompleteCustomT…ogleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.5.5%2Fangular.min.js%3A21%3A332)
    at angular.min.js:6
    at angular.min.js:40
    at q (angular.min.js:7)
    at g (angular.min.js:39)
    at bb (angular.min.js:43)
    at c (angular.min.js:21)
    at yc (angular.min.js:21)
    at ee (angular.min.js:20)
    at angular.min.js:313
    at HTMLDocument.b (angular.min.js:188)
</code>```

The JS fiddle is on this link: https://jsfiddle.net/nicothed/rqv8fLn7

I based it on the blank application on that page: https://material.angularjs.org/latest/getting-started#documentation-version.

Would anyone have an idea of what is happening and how to fix it?

答:
I was able to make it work in the fiddle by setting JAVASCRIPT>LOAD TYPE to "No wrap - in < body>", here is the fiddle: Updated Fiddle</p>

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

Title: Angular js 1.5 - $injector:modulerr

Body:
I'm trying to duplicate an angular Material example as described on https://material.angularjs.org/latest/demo/autocomplete and it's driving me nuts.

I get the following error every time, everywhere (on my machine and JSfiddle)

> Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.5.5/$injector/modulerr?p0=autocompleteCustomT…ogleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.5.5%2Fangular.min.js%3A21%3A332)
    at angular.min.js:6
    at angular.min.js:40
    at q (angular.min.js:7)
    at g (angular.min.js:39)
    at bb (angular.min.js:43)
    at c (angular.min.js:21)
    at yc (angular.min.js:21)
    at ee (angular.min.js:20)
    at angular.min.js:313
    at HTMLDocument.b (angular.min.js:188)

The JS fiddle is on this link: https://jsfiddle.net/nicothed/rqv8fLn7

I based it on the blank application on that page: https://material.angularjs.org/latest/getting-started#documentation-version.

Would anyone have an idea of what is happening and how to fix it?

Body:
I was able to make it work in the fiddle by setting JAVASCRIPT>LOAD TYPE to "No wrap - in < body>", here is the fiddle: Updated Fiddle

<body></body>


问:
Rails Devise Error: Missing host to link to
Really weird error hitting my rails app on localhost when I create a new user (using Devise gem) and attempt to get a confirmation email:

```<code>ArgumentError in Registrations#create
Showing     /Users/matthewvandenboogart/Sites/certlocal/app/views/devise/mailer/confirmation_instructions.html.erb where line #5 raised:

Missing host to link to! Please provide the :host parameter, set default_url_options[:host], or set :only_path to true
</code>```

For the record, other emails are sending fine from localhost. The only email that seems to pop this error is the initial confirmation email. To top it off, I'm not seeing the error when code is pushed up to staging (on Heroku).

config/development.rb:

```<code> config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }
</code>```

Anyone have insights into what may be going on or where to look to resolve? It's an annoying type error that I would like to resolve so one day it doesn't end up happening on production.

答:
You said "other emails are sending fine from localhost. The only email that seems to pop this error is the initial confirmation email"

Hmmm. I am not sure what issue you are getting. but if every email work well except the first email, so I think that email was cached.
Try to check your development.rb this line

config.action_mailer.perform_caching = false

If it is true, set it to false.

Body:
Really weird error hitting my rails app on localhost when I create a new user (using Devise gem) and attempt to get a confirmation email:

ArgumentError in Registrations#create
Showing     /Users/matthewvandenboogart/Sites/certlocal/app/views/devise/mailer/confirmation_instructions.html.erb where line #5 raised:

Missing host to link to! Please provide the :host parameter, set default_url_options[:host], or set :only_path to true

For the record, other emails are sending fine from localhost. The only email that seems to pop this error is the initial confirmation email. To top it off, I'm not seeing the error when code is pushed up to staging (on Heroku).

config/development.rb:

 config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }

Anyone have insights into what may be going on or where to look to resolve? It's an annoying type error that I would like to resolve so one day it doesn't end up happening on production.


问:
How do I set Min Date in DateTimepicker from another DateTimepicker?
I want the date on the first DateTimePicker to be the MinDate on the second one,I found some solutions but they were about DatePicker and doesn't work

This is my code:

```<code>$(document).ready(function(){
       $('#arrival').datetimepicker({
                locale: "<?php echo $lang['datetimepicker_lang']; ?>",
                format: "<?php echo $lang['datetimepicker_format']; ?>",
            });

        $('#departure').datetimepicker({
            locale: "<?php echo $lang['datetimepicker_lang']; ?>",
            format: "<?php echo $lang['datetimepicker_format']; ?>",
        });
});
</code>```

答:
I think this is it: Set mindate for bootstrap...

THe main part is this:

```<code>on('dp.change', function(e) {
  $('#txtEndTime').data("DateTimePicker").minDate(e.date)
</code>```

Here you are using the event options of datetimepicker, so each time you change its value it will use the minDate function to set the minDate of the other datetimepicker.

Body:
I want the date on the first DateTimePicker to be the MinDate on the second one,I found some solutions but they were about DatePicker and doesn't work

This is my code:

$(document).ready(function(){
       $('#arrival').datetimepicker({
                locale: "<?php echo $lang['datetimepicker_lang']; ?>",
                format: "<?php echo $lang['datetimepicker_format']; ?>",
            });

        $('#departure').datetimepicker({
            locale: "<?php echo $lang['datetimepicker_lang']; ?>",
            format: "<?php echo $lang['datetimepicker_format']; ?>",
        });
});

Body:
I think this is it: Set mindate for bootstrap...

THe main part is this:

on('dp.change', function(e) {
  $('#txtEndTime').data("DateTimePicker").minDate(e.date)

Here you are using the event options of datetimepicker, so each time you change its value it will use the minDate function to set the minDate of the other datetimepicker.


问:
error while starting kafka broker
I was able to successfully set up zookeeper and one kafka broker yesterday. Everything worked as expected. I shut down kafka (ctrl + c) and then zookeeper.

Today I started zookeeper and when I started kafka (bin/kafka-server-start.sh config/server0.properties), I get the following error. I tried various remedies suggested (removing completely my kafka installation and doing it again from scratch). Still I get same error.

```<code>[2016-09-28 16:15:55,895] FATAL Fatal error during KafkaServerStartable startup. Prepare to shutdown (kafka.server.KafkaServerStartable)
java.lang.RuntimeException: A broker is already registered on the path /brokers/ids/0. This probably indicates that you either have configured a brokerid that is already in use, or else you have shutdown this broker and restarted it faster than the zookeeper timeout so it appears to be re-registering.
        at kafka.utils.ZkUtils.registerBrokerInZk(ZkUtils.scala:305)
        at kafka.utils.ZkUtils.registerBrokerInZk(ZkUtils.scala:291)
        at kafka.server.KafkaHealthcheck.register(KafkaHealthcheck.scala:70)
        at kafka.server.KafkaHealthcheck.startup(KafkaHealthcheck.scala:51)
        at kafka.server.KafkaServer.startup(KafkaServer.scala:244)
        at kafka.server.KafkaServerStartable.startup(KafkaServerStartable.scala:37)
        at kafka.Kafka$.main(Kafka.scala:67)
        at kafka.Kafka.main(Kafka.scala)
[2016-09-28 16:15:55,896] INFO [Kafka Server 0], shutting down (kafka.server.KafkaServer)
</code>```

All set up in mac

答:
I found similar issue in my AWS server. The problem was zookeeper was running. So I killed the process first and tried again and it worked. </p>

```<code>$ ps aux | grep zookeeper
$kill -9 <zookeeper.properties process>
</code>```

Title: error while starting kafka broker

Body:
I was able to successfully set up zookeeper and one kafka broker yesterday. Everything worked as expected. I shut down kafka (ctrl + c) and then zookeeper.

Today I started zookeeper and when I started kafka (bin/kafka-server-start.sh config/server0.properties), I get the following error. I tried various remedies suggested (removing completely my kafka installation and doing it again from scratch). Still I get same error.

[2016-09-28 16:15:55,895] FATAL Fatal error during KafkaServerStartable startup. Prepare to shutdown (kafka.server.KafkaServerStartable)
java.lang.RuntimeException: A broker is already registered on the path /brokers/ids/0. This probably indicates that you either have configured a brokerid that is already in use, or else you have shutdown this broker and restarted it faster than the zookeeper timeout so it appears to be re-registering.
        at kafka.utils.ZkUtils.registerBrokerInZk(ZkUtils.scala:305)
        at kafka.utils.ZkUtils.registerBrokerInZk(ZkUtils.scala:291)
        at kafka.server.KafkaHealthcheck.register(KafkaHealthcheck.scala:70)
        at kafka.server.KafkaHealthcheck.startup(KafkaHealthcheck.scala:51)
        at kafka.server.KafkaServer.startup(KafkaServer.scala:244)
        at kafka.server.KafkaServerStartable.startup(KafkaServerStartable.scala:37)
        at kafka.Kafka$.main(Kafka.scala:67)
        at kafka.Kafka.main(Kafka.scala)
[2016-09-28 16:15:55,896] INFO [Kafka Server 0], shutting down (kafka.server.KafkaServer)

All set up in mac

Body:
I found similar issue in my AWS server. The problem was zookeeper was running. So I killed the process first and tried again and it worked.

$ ps aux | grep zookeeper
$kill -9 <zookeeper.properties process>


问:
Distance measure between two sets of possibly different size
I have 2 sets of integers, A and B, not necessarily of the same size. For my needs, I take the distance between each 2 elements a and b (integers) to be just abs(a-b).

I am defining the distance between the two sets as follows:

If the sets are of the same size, minimize the sum of distances of all pairs [a,b] (a from A and b from B), minimization over all possible 'pairs partitions' (there are n! possible partitions).

If the sets are not of the same size, let's say A of size m and B of size n, with m < n, then minimize the distance from (1) over all subsets of B which are of size m.

My question is, is the following algorithm (just an intuitive guess) gives the right answer, according to the definition written above.

Construct a matrix D of size m X n, with D(i,j) = abs(A(i)-B(j))

Find the smallest element of D, accumulate it, and delete the row and the column of that element. Accumulate the next smallest entry, and keep accumulating until all rows and columns are deleted.

for example, if A={0,1,4} and B={3,4}, then D is (with the elements above and to the left):

  3 4

0 3 4

1 2 3

4 1 0

And the distance is 0 + 2 = 2, coming from pairing 4 with 4 and 3 with 1.

答:
In order to get the optimum, solve the assignment problem on D.

The assignment problem finds a perfect matching in a bipartite graph such that the total edge weight is minimized, which maps perfectly to your problem. It is also in P.

EDIT to explain how OP's problem maps onto assignment.

For simplicity of explanation, extend the smaller set with special elements e_k.

Let A be the set of workers, and B be the set of tasks (the contents are just labels).

Let the cost be the distance between an element in A and B (i.e. an entry of D). The distance between e_k and anything is 0.

Then, we want to find a perfect matching of A and B (i.e. every worker is matched with a task), such that the cost is minimized. This is the assignment problem.


问:
"Array item" and constant "define" shows only 0 and not the whole number
I declared an array item "0859" but when I display the array item, it shows only the 0 and not the whole number "0859".

In constant define I set the value to "01238" the result is the same with my array, it shows only the value 0 and not the whole number 01238. I would like to know further about the reason why array item and define that starts with 0 in there item and values shows only the 0 and not the whole number

Array

```<code><?php
  $num = [0859];
  echo $num;

  output: 0

  Why not the the output is "0859"
?>
</code>```

Constant Define

```<code><?php

  define(myNum, 01238);
  echo myNum;

  output: 0

  Why not the the output is "01238"
</code>```

?>

I'm using Wamp PHP version 5.5.12

Please enlighten me why I get the output only 0 and not the whole number

答:
If you're running PHP7 you should probably take a look at this answer.

As said in the linked answer:

This comes from the changes made to how integers, specifically octals,
  are handled in PHP7 (as oppsoed to PHP5).

Invalid octal literals

Previously, octal literals that contained invalid numbers were
  silently truncated (0128 was taken as 012). Now, an invalid octal
  literal will cause a parse error.

Either use them as strings, or actual integers

$a = array(1, 8, 9, 12); // Integers

$a = array("00001", "00008",
  "00009", "00012"); // Strings

You can find more info on Integers/Octals here: http://php.net/manual/en/language.types.integer.php

Body:
I declared an array item "0859" but when I display the array item, it shows only the 0 and not the whole number "0859".

In constant define I set the value to "01238" the result is the same with my array, it shows only the value 0 and not the whole number 01238. I would like to know further about the reason why array item and define that starts with 0 in there item and values shows only the 0 and not the whole number

Array

<?php
  $num = [0859];
  echo $num;

  output: 0

  Why not the the output is "0859"
?>

Constant Define

<?php

  define(myNum, 01238);
  echo myNum;

  output: 0

  Why not the the output is "01238"

?>

I'm using Wamp PHP version 5.5.12

Please enlighten me why I get the output only 0 and not the whole number


问:
Excel: last character/string match in a string
Is there an efficient way to identify the last character/string match in a string using base functions?      I.e. not the last character/string of the string, but the position of a character/string's last occurrence in a string.  Search and find both work left-to-right so I can't think how to apply without lengthy recursive algorithm.  And this solution now seems obsolete.

答:
Considering a part of a Comment made by @SSilk my end goal has really been to get everything to the right of that last occurence an alternative approach with a very simple formula is to copy a column (say A) of strings and on the copy (say ColumnB) apply Find and Replace. For instance taking the example: Drive:\Folder\SubFolder\Filename.ext

This returns what remains (here Filename.ext) after the last instance of whatever character is chosen (here \) which is sometimes the objective anyway and facilitates finding the position of the last such character with a short formula such as:

```<code>=FIND(B1,A1)-1
</code>```

Body:
Considering a part of a Comment made by @SSilk my end goal has really been to get everything to the right of that last occurence an alternative approach with a very simple formula is to copy a column (say A) of strings and on the copy (say ColumnB) apply Find and Replace. For instance taking the example: Drive:\Folder\SubFolder\Filename.ext

This returns what remains (here Filename.ext) after the last instance of whatever character is chosen (here \) which is sometimes the objective anyway and facilitates finding the position of the last such character with a short formula such as:

=FIND(B1,A1)-1


问:
Implicit Functions with Symbol argument in Scala
Why does the following code print:

```<code>class TestClass{
  case class printClass(s: Symbol) {
    def pr() = println(s);
  }
  implicit def implPrint(i: Symbol) = printClass(i)
}

object TestObject extends TestClass{
  def main(args:Array[String]) = {
    'x pr
  }
}
</code>```

while the following code doesn't:

```<code>class TestClass{
  implicit def implPrint(i: Symbol) = println(i)
}

object TestObject extends TestClass{
  def main(args:Array[String]) = {
    'x

    ()
  }
}
</code>```

To my knowledge implicit functions are called automatically by the compiler if it thinks it is a good idea to. Why isn't the compiler calling implPrint() in both cases? What am I overlooking here?

答: Implicits are considered by the compiler when it cannot understand the syntax of the code at hand. In your first example you are attempting to invoke pr() on a Symbol object, syntax which is not understood by the compiler, so it turns to implicits. In your second example you are declaring a Symbol and doing nothing with it, syntax which agrees with the compiler's parsing, so it does not look at implicits.

Body:
Why does the following code print:

class TestClass{
  case class printClass(s: Symbol) {
    def pr() = println(s);
  }
  implicit def implPrint(i: Symbol) = printClass(i)
}

object TestObject extends TestClass{
  def main(args:Array[String]) = {
    'x pr
  }
}

while the following code doesn't:

class TestClass{
  implicit def implPrint(i: Symbol) = println(i)
}

object TestObject extends TestClass{
  def main(args:Array[String]) = {
    'x

    ()
  }
}

To my knowledge implicit functions are called automatically by the compiler if it thinks it is a good idea to. Why isn't the compiler calling implPrint() in both cases? What am I overlooking here?


问:
The character encoding of the HTML document was not declared
When I click to the HTML document to open it in browser the fllowing message appears:
"The character encoding of the HTML document was not declared. The document will render with index.html garbled text in some browser configurations if the document contains characters from outside the US-ASCII range. The character encoding of the page must to be declared in the document or in the transfer protocol.
I don't know how can insert my code here</p>

答:
If you use Atom or sublime, you can install the the very useful package called Emmet. All you have to do is enter ! , then  Ctrl+E, Emmet will automatically complete the basic structure of HTML5 for you. In this case problems like something missing or a typo will not appear, and one less thing for you to worry about.

For sublime, use Ctrl+Shift+P, and install package.

For Atom, here is the GitHub address: Emmet support for Atom


问:
How does Clojure approach Separation of Concerns?
How does Clojure approach Separation of Concerns ? Since code is data, functions can be passed as parameters and used as returns...

And, since there is that principle "Better 1000 functions that work on 1 data structure, than 100 functions on 100 data structures" (or something like that).

I mean, pack everything a map, give it a keyword as key, and that's it ? functions, scalars, collections, everything...

The idea of Separation of Concerns is implemented, in Java, by means of Aspects (aspect oriented programming) and annotations. This is my view of the concept and might be somewhat limited, so don't take it for granted.

What is the right way (idiomatic way) to go about in Clojure, to avoid the WTFs of fellow programmers _

答:
In a functional language, the best way to handle separation of concerns is to convert any programming problem into a set of transformations on a data structure. For instance, if you write a web app, the overall goal is to take a request and transform it into a response, which can be thought of as simply transforming the request data into response data. (In a non-trivial web app, the starting data would probably include not only the request, but also session and database information) Most programming tasks can be thought of in this way.

Each "concern" would be a function in a "pipeline" that helps make the transform possible. In this way, each function is completely decoupled from the other steps.

Note that this means that your data, as it undergoes these transformations, needs to be rich in its structure. Essentially, we want to put all the "intelligence" of our program into the data, not in the code. In a complicated functional program, the data at the different levels may be complex enough that in needs to look like a programming language in its own right- This is where the idea of "domain-specific languages" comes into play.

Clojure has excellent support for manipulating complex heterogenous data structures, which makes this less cumbersome than it may sound (i.e. it's not cumbersome at all if done right)

In addition, Clojure's support for lazy data structures allows these intermediate data structures to actually be (conceptually) infinite in size, which makes this decoupling possible in most scenarios. See the following paper for info on why having infinite data structures is so valuable in this situation: http://www.cs.kent.ac.uk/people/staff/dat/miranda/whyfp90.pdf

This "pipeline" approach can handle 90% of your needs for separating concerns. For the remaining 10% you can use Clojure macros, which, at a high level, can be thought of as a very powerful tool for aspect-oriented programming.

That's how I believe you can best decouple concerns in Clojure- Note that "objects" or "aspects" are not really necessary concepts in this approach.


问:
Paraview: Merge Multiple .stl and save as single (.stl)
How could I merge multiple (.stls) and save as a single (.stl) file?

I would like to save all the (.stls) in the following as a single (.stl) file in Paraview.

答: Select all the STL sources and run Filters -> Append Datasets. Save the result.


问:
Check if any value in array is equal to current value added to array
I have a 2D array initialized to Storage[100][3].

I insert a group values to each row of the array and move on to the next row and do the same,
for example:

1 1 3

2 5 6

3 1 3

(keeps going on to 100 rows)

After completing the insertion of 1 entire row I want to check if the values in this current insertion's column's 2 and 3 match the values in all the previous row's, column's 2 and 3.

for example in the above data set I look at column's 2 and 3 in each row and see that rows 1 and 3 have the same values in those columns.

I wrote a program that can compare the current insertion to the previous insertion. But I want to compare the current insertion with all the insertions in the array.

```<code>const int col=0;

//inserting the values//
for (int row= 0; row < 100; row++) {
    storage[row][col] = t;
    storage[row][col += 1] = xi;
    storage[row][col += 2] = yi;
}

//trying to check if the values are same. need help here//
for (int row = 0; row < 100; row++) {
    if (storage[row][col + 1]==storage[row + 1][col + 1]
        && storage[row][col + 2] == storage[row + 1][col + 2]) {

    }
}
</code>```

答:
```<code>for (int row = 1; row < 100; row++) {
    for (int prevRow = 0; prevRow < row; prevRow++) {
        if (storage[row][1] == storage[prevRow][1]
            && storage[row][2] == storage[prevRow][2]) {

            // do something...

        }
    }
}
</code>```

Outer loop starts from row = 1 becuase row 0 doesn't have previous rows to compare.

Body:
I have a 2D array initialized to Storage[100][3].

I insert a group values to each row of the array and move on to the next row and do the same,
for example:

1 1 3

2 5 6

3 1 3

(keeps going on to 100 rows)

After completing the insertion of 1 entire row I want to check if the values in this current insertion's column's 2 and 3 match the values in all the previous row's, column's 2 and 3.

for example in the above data set I look at column's 2 and 3 in each row and see that rows 1 and 3 have the same values in those columns.

I wrote a program that can compare the current insertion to the previous insertion. But I want to compare the current insertion with all the insertions in the array.

const int col=0;

//inserting the values//
for (int row= 0; row < 100; row++) {
    storage[row][col] = t;
    storage[row][col += 1] = xi;
    storage[row][col += 2] = yi;
}

//trying to check if the values are same. need help here//
for (int row = 0; row < 100; row++) {
    if (storage[row][col + 1]==storage[row + 1][col + 1]
        && storage[row][col + 2] == storage[row + 1][col + 2]) {

    }
}

Body:
for (int row = 1; row < 100; row++) {
    for (int prevRow = 0; prevRow < row; prevRow++) {
        if (storage[row][1] == storage[prevRow][1]
            && storage[row][2] == storage[prevRow][2]) {

            // do something...

        }
    }
}

Outer loop starts from row = 1 becuase row 0 doesn't have previous rows to compare.


问:
How to disable Firebase Crash Reporting when the app is running on debug?
I have successfully implemented Firebase Crash Reporting, but I need to disable the service when the app is running undo the 'debug' Build Variant, in order to avoid non-real crashes in the console during the development.

The official documentation doesn't say anything about this.

答:
With Google Play Services 11.0 you could now disable crash reporting at runtime.</p>

```<code>FirebaseCrash.setCrashCollectionEnabled(!BuildConfig.DEBUG);
</code>```

Body:
With Google Play Services 11.0 you could now disable crash reporting at runtime.

FirebaseCrash.setCrashCollectionEnabled(!BuildConfig.DEBUG);


问:
Mysql Select and count rows with multiple same values
I am trying to create a query that allows me to select the data like shown below

```<code>id  Counter_Type Champion_Name Counter_Lane
---|------------|------------|--------------
1  | 1          | Ahri       | 1
2  | 1          | Ahri       | 2
5  | 1          | Ahri       | 2
3  | 1          | Ahri       | 3
4  | 1          | Ahri       | 2
6  | 1          | Teemo      | 1
7  | 1          | Warwick    | 4
8  | 1          | Warwick    | 4
</code>```

It should count the Counter_Lane and then the Counter_Type with the most should be shown for that name as shown below how it should show the data:

```<code>id  Counter_Type Champion_Name Counter_Lane
---|------------|------------|--------------
1  | 1          | Ahri       | 2
2  | 1          | Teemo      | 1
3  | 1          | Warwick    | 4
</code>```

I have tried the following code and its the closest I have came for over 3 hours now, so could someone help please.

```<code>SELECT
    a.Counter_Type, Champion_For, a.Counter_Lane, a.Champion_Name, COUNT(*) as Amount, sum(vote_type = 'up') as Upvotes, sum(vote_type = 'down') as Downvotes, sum(vote_type = 'up')-sum(vote_type = 'down') as Totalvotes
FROM Champion_Counters_Data a
JOIN ( SELECT c.Counter_Lane, c.Champion_Name, COUNT(*) magnitude
FROM Champion_Counters_Data c
WHERE
    Champion_For = "Aatrox" AND Counter_Type = 1 GROUP BY Champion_Name, Counter_Lane ORDER BY magnitude) b ON a.Champion_Name = b.Champion_Name AND b.Counter_Lane = a.Counter_Lane
GROUP BY Champion_Name
</code>```

答:
Try following SQL statement:

```<code>SELECT Counter_Type , Champion_Name, MAX(Counter_Lane) 'Counter_Lane'
FROM(
    SELECT Counter_Type , Champion_Name , Counter_Lane
    FROM Champion_Counters_Data
    GROUP BY Counter_Type , Champion_Name
    HAVING COUNT(Counter_Lane) >= 2
) tb
GROUP BY Counter_Type , Champion_Name
</code>```

Body:
I am trying to create a query that allows me to select the data like shown below

id  Counter_Type Champion_Name Counter_Lane
---|------------|------------|--------------
1  | 1          | Ahri       | 1
2  | 1          | Ahri       | 2
5  | 1          | Ahri       | 2
3  | 1          | Ahri       | 3
4  | 1          | Ahri       | 2
6  | 1          | Teemo      | 1
7  | 1          | Warwick    | 4
8  | 1          | Warwick    | 4

It should count the Counter_Lane and then the Counter_Type with the most should be shown for that name as shown below how it should show the data:

id  Counter_Type Champion_Name Counter_Lane
---|------------|------------|--------------
1  | 1          | Ahri       | 2
2  | 1          | Teemo      | 1
3  | 1          | Warwick    | 4

I have tried the following code and its the closest I have came for over 3 hours now, so could someone help please.

SELECT
    a.Counter_Type, Champion_For, a.Counter_Lane, a.Champion_Name, COUNT(*) as Amount, sum(vote_type = 'up') as Upvotes, sum(vote_type = 'down') as Downvotes, sum(vote_type = 'up')-sum(vote_type = 'down') as Totalvotes
FROM Champion_Counters_Data a
JOIN ( SELECT c.Counter_Lane, c.Champion_Name, COUNT(*) magnitude
FROM Champion_Counters_Data c
WHERE
    Champion_For = "Aatrox" AND Counter_Type = 1 GROUP BY Champion_Name, Counter_Lane ORDER BY magnitude) b ON a.Champion_Name = b.Champion_Name AND b.Counter_Lane = a.Counter_Lane
GROUP BY Champion_Name

Body:
Try following SQL statement:

SELECT Counter_Type , Champion_Name, MAX(Counter_Lane) 'Counter_Lane'
FROM(
    SELECT Counter_Type , Champion_Name , Counter_Lane
    FROM Champion_Counters_Data
    GROUP BY Counter_Type , Champion_Name
    HAVING COUNT(Counter_Lane) >= 2
) tb
GROUP BY Counter_Type , Champion_Name


问:
Where is the center of vertices from multiple-objects in Maya?
I want to find the center (by center I mean the default pivot position) of a selection of vertices coming from multiple objects in Maya. I thought it was the centroid but it seems that this does not returns the correct coordinates.

Here is an example:

I selected four vertices, the two poles of each sphere. In red is the "center" of this vertices, where Maya place the default pivot, and in blue is the centroid as I computed it.

Either my computations are wrong or the center of the vertices is not the centroid, anyway these are clearly not the same coordinates. Here is my code:

```<code>loc = cmds.spaceLocator ()[0]
vtxList = cmds.ls (sl = True, fl = True)

vtxPosSum = [0, 0, 0]
for vtx in vtxList:
    vtxPos = cmds.xform (vtx, q = True, ws = True, t = True)
    vtxPosSum[0] += vtxPos[0]
    vtxPosSum[1] += vtxPos[1]
    vtxPosSum[2] += vtxPos[2]

barycentre = [vtxPosSum[0] / len(vtxList),
              vtxPosSum[1] / len(vtxList),
              vtxPosSum[2] / len(vtxList)]

cmds.xform (loc, ws = True, t = barycentre)
</code>```

So my question is, how can I find the position of the default Maya pivot when selecting vertices from multiple polygons?

Thanks

答:
I think maya uses the center of the bounding box as the pivot center when selecting multiple components... I could be wrong, but give this a try and see if it's the correct spot:

```<code>import maya.cmds as mc

sel = mc.ls(sl=True)
bb = mc.exactWorldBoundingBox(sel)
pos = ((bb[0] + bb[3]) / 2, (bb[1] + bb[4]) / 2, (bb[2] + bb[5]) / 2)
</code>```

pos would be the world space xyz position to move your locator (or whatever you're testing with)

Body:
I want to find the center (by center I mean the default pivot position) of a selection of vertices coming from multiple objects in Maya. I thought it was the centroid but it seems that this does not returns the correct coordinates.

Here is an example:

I selected four vertices, the two poles of each sphere. In red is the "center" of this vertices, where Maya place the default pivot, and in blue is the centroid as I computed it.

Either my computations are wrong or the center of the vertices is not the centroid, anyway these are clearly not the same coordinates. Here is my code:

loc = cmds.spaceLocator ()[0]
vtxList = cmds.ls (sl = True, fl = True)

vtxPosSum = [0, 0, 0]
for vtx in vtxList:
    vtxPos = cmds.xform (vtx, q = True, ws = True, t = True)
    vtxPosSum[0] += vtxPos[0]
    vtxPosSum[1] += vtxPos[1]
    vtxPosSum[2] += vtxPos[2]

barycentre = [vtxPosSum[0] / len(vtxList),
              vtxPosSum[1] / len(vtxList),
              vtxPosSum[2] / len(vtxList)]

cmds.xform (loc, ws = True, t = barycentre)

So my question is, how can I find the position of the default Maya pivot when selecting vertices from multiple polygons?

Thanks

Body:
I think maya uses the center of the bounding box as the pivot center when selecting multiple components... I could be wrong, but give this a try and see if it's the correct spot:

import maya.cmds as mc

sel = mc.ls(sl=True)
bb = mc.exactWorldBoundingBox(sel)
pos = ((bb[0] + bb[3]) / 2, (bb[1] + bb[4]) / 2, (bb[2] + bb[5]) / 2)

pos would be the world space xyz position to move your locator (or whatever you're testing with)


问:
Summing properties in an object array Angular
I am fairly new to Angular and Javascript so am in need of some guidance. I am wanting to work out the sum and average of values within an object array. The objects are pushed into the array through input boxes, here is my code so far:

```<code>var myApp = angular.module("myApp", []);

myApp.controller("myController", function($scope){

$scope.newLog = {};

$scope.logs = [
    {project: "",
     phase: "",
     date: "",
     startTime: "",
     intTime: "",
     endTime: "",
     comments: ""}
];

$scope.saveLog = function(){

    //CREATING DELTA TIME
    var newTimeLog = $scope.newLog;
    var begin = (newTimeLog.startTime).getTime();
    var end = (newTimeLog.endTime).getTime();

    var i = newTimeLog.intTime;
    var ii = parseInt(i);
    var intMilisec = ii*60000;

    if( isNaN(begin) )
        {
            return "";
        }

        if (begin < end) {
            var milisecDiff = end - begin;
        }else{
            var milisecDiff = begin - end;
        }

        var minusInt = milisecDiff - intMilisec;

        var milisec = parseInt((minusInt%1000)/100)
            , seconds = parseInt((minusInt/1000)%60)
            , minutes = parseInt((minusInt/(1000*60))%60)
            , hours = parseInt((minusInt/(1000*60*60))%24);

        hours = (hours < 10) ? "0" + hours : hours;
        minutes = (minutes < 10) ? "0" + minutes : minutes;
        seconds = (seconds < 10) ? "0" + seconds : seconds;

        var deltaFormat = hours + " Hours " + minutes + " Minutes";

    newTimeLog["deltaTime"] = deltaFormat;

    $scope.logs.push($scope.newLog);
    $scope.newLog = {};
};

$scope.intSum = function(){
    var sum = 0;
    for (var i = 0; i < $scope.logs.length; i++){
        sum += $scope.logs[i].intTime;
    }
    return sum;
};

});
</code>```

So the intSum function is where I am having issues - I am wanting to sum the intTime properties for all the objects. So if object1's intTime = 1, object2's intTime = 2, object3's intTime = 3 the intSum should be 6. However what I am getting from the IntSum currently is 123.

Any help would be greatly appreciated!

答:
Try:

```<code>sum += parseInt($scope.logs[i].intTime);
</code>```

Instead of:

```<code>sum += $scope.logs[i].intTime;
</code>```

EDIT: I would recommend you have a look at reduce function, which is the javascript way of looping on your array in this case:
https://www.w3schools.com/jsref/jsref_reduce.asp

EDIT2: You initialize $scope.logs.intTime to "". This first value stays in your array and generates NaN.
I suggest you initialize your array like this:

```<code>$scope.logs = [];
</code>```

Body:
I am fairly new to Angular and Javascript so am in need of some guidance. I am wanting to work out the sum and average of values within an object array. The objects are pushed into the array through input boxes, here is my code so far:

var myApp = angular.module("myApp", []);

myApp.controller("myController", function($scope){

$scope.newLog = {};

$scope.logs = [
    {project: "",
     phase: "",
     date: "",
     startTime: "",
     intTime: "",
     endTime: "",
     comments: ""}
];

$scope.saveLog = function(){

    //CREATING DELTA TIME
    var newTimeLog = $scope.newLog;
    var begin = (newTimeLog.startTime).getTime();
    var end = (newTimeLog.endTime).getTime();

    var i = newTimeLog.intTime;
    var ii = parseInt(i);
    var intMilisec = ii*60000;

    if( isNaN(begin) )
        {
            return "";
        }

        if (begin < end) {
            var milisecDiff = end - begin;
        }else{
            var milisecDiff = begin - end;
        }

        var minusInt = milisecDiff - intMilisec;

        var milisec = parseInt((minusInt%1000)/100)
            , seconds = parseInt((minusInt/1000)%60)
            , minutes = parseInt((minusInt/(1000*60))%60)
            , hours = parseInt((minusInt/(1000*60*60))%24);

        hours = (hours < 10) ? "0" + hours : hours;
        minutes = (minutes < 10) ? "0" + minutes : minutes;
        seconds = (seconds < 10) ? "0" + seconds : seconds;

        var deltaFormat = hours + " Hours " + minutes + " Minutes";

    newTimeLog["deltaTime"] = deltaFormat;

    $scope.logs.push($scope.newLog);
    $scope.newLog = {};
};

$scope.intSum = function(){
    var sum = 0;
    for (var i = 0; i < $scope.logs.length; i++){
        sum += $scope.logs[i].intTime;
    }
    return sum;
};

});

So the intSum function is where I am having issues - I am wanting to sum the intTime properties for all the objects. So if object1's intTime = 1, object2's intTime = 2, object3's intTime = 3 the intSum should be 6. However what I am getting from the IntSum currently is 123.

Any help would be greatly appreciated!

Body:
Try:

sum += parseInt($scope.logs[i].intTime);

Instead of:

sum += $scope.logs[i].intTime;

EDIT: I would recommend you have a look at reduce function, which is the javascript way of looping on your array in this case:
https://www.w3schools.com/jsref/jsref_reduce.asp

EDIT2: You initialize $scope.logs.intTime to "". This first value stays in your array and generates NaN.
I suggest you initialize your array like this:

$scope.logs = [];


问:
Javascript in HTML not calling correctly
I'm trying to create a simple website using basic java script but I think i'm not able to call to the file correctly have tried multiple sources online but to no success. Can you have a look at my code and tell me what's wrong ?

html:

```<code><html>
<head>
<script src="js/js1.js" type="text/javascript"></script>
</head>
The total number of square feet in your house is:<br>
<script src="js/js1.js">test()</script>square feet.
</code>```

js:

```<code>function test() {
    var test = 15;
    document.write(test);
    return test;
}
</code>```

答:
Base on @MoustafaS's answer, your js file can be fixed:

```<code>function test() {
    var test = 15;
    document.write(test);
    return test;
}
</code>```

Then call it in HTML:

```<code><script>test()</script>
</code>```

JSfiddle Demo

Body:
I'm trying to create a simple website using basic java script but I think i'm not able to call to the file correctly have tried multiple sources online but to no success. Can you have a look at my code and tell me what's wrong ?

html:

The total number of square feet in your house is:

square feet.

js:

function test() {
    var test = 15;
    document.write(test);
    return test;
}

Body:
Base on @MoustafaS's answer, your js file can be fixed:

function test() {
    var test = 15;
    document.write(test);
    return test;
}

Then call it in HTML:

<script>test()</script>

JSfiddle Demo


答: The intTime is defined in your object as String. So when you are doing the sum, it is actually doing a string concatenation. Convert to Number using pasrseInt and do the sum.</p>

Title: Summing properties in an object array Angular


问:
"this" pointer in C (not C++)
I'm trying to create a stack in C for fun, and came up with the idea of using struct to represent the stack. Then I add function pointers to the struct for push() and pop() operations.

So far all is good it seems, but, for the implementation of the push() and pop() functions I need to refer to *this somehow. How can that (can it?) be done?

This is my struct

```<code>struct Stack {
    int *data;
    int current_size;
    int max_size;
    int (*push)(int);
    int (*pop)();
};
</code>```

And as an example here's push

```<code>int push(int val) {
    if(current_size == max_size -1)
            return 0;

    data[current_size] = val;
    current_size++;

    return 1;
}
</code>```

As you can imagine, the compiler has no idea what current_size is, as it would expect something like stack->current_size.

Is this possible to overcome somehow?

答:
There's no implicit this in C. Make it explicit:

```<code>int push(Stack* self, int val) {
    if(self->current_size == self->max_size - 1)
            return 0;

    self->data[self->current_size] = val;
    (self->current_size)++;

    return 1;
}
</code>```

You will of course have to pass the pointer to the struct into every call to push and similar methods.

This is essentially what the C++ compiler is doing for you when you define Stack as a class and push et al as methods.

Title: "this" pointer in C (not C++)

Body:
I'm trying to create a stack in C for fun, and came up with the idea of using struct to represent the stack. Then I add function pointers to the struct for push() and pop() operations.

So far all is good it seems, but, for the implementation of the push() and pop() functions I need to refer to *this somehow. How can that (can it?) be done?

This is my struct

struct Stack {
    int *data;
    int current_size;
    int max_size;
    int (*push)(int);
    int (*pop)();
};

And as an example here's push

int push(int val) {
    if(current_size == max_size -1)
            return 0;

    data[current_size] = val;
    current_size++;

    return 1;
}

As you can imagine, the compiler has no idea what current_size is, as it would expect something like stack->current_size.

Is this possible to overcome somehow?

Body:
There's no implicit this in C. Make it explicit:

int push(Stack* self, int val) {
    if(self->current_size == self->max_size - 1)
            return 0;

    self->data[self->current_size] = val;
    (self->current_size)++;

    return 1;
}

You will of course have to pass the pointer to the struct into every call to push and similar methods.

This is essentially what the C++ compiler is doing for you when you define Stack as a class and push et al as methods.


答:
With full credit to Qirel and his answer here - https://stackoverflow.com/a/40736053/2288334

This is likely due to how PHP is handling what used to be silently parsed to octal literals now is not. Basically, PHP7 thinks you're trying to pass an octal as the only value of the array, but it is invalid.

For Reference:
http://php.net/manual/en/migration70.incompatible.php#migration70.incompatible.integers.invalid-octals
http://php.net/manual/en/language.types.integer.php

Title: "Array item" and constant "define" shows only 0 and not the whole number


问:
Understanding examples from Understand JavaScript Closures With Ease
The last example of http://javascriptissexy.com/understand-javascript-closures-with-ease/ is:

```<code>function celebrityIDCreator (theCelebrities) {
    var i;
    var uniqueID = 100;
    for (i = 0; i < theCelebrities.length; i++) {
        theCelebrities[i]["id"] = function (j)  { // the j parametric variable is the i passed in on invocation of this IIFE
            return function () {
                return uniqueID + j; // each iteration of the for loop passes the current value of i into this IIFE and it saves the correct value to the array
            } () // BY adding () at the end of this function, we are executing it immediately and returning just the value of uniqueID + j, instead of returning a function.
        } (i); // immediately invoke the function passing the i variable as a parameter
    }
    return theCelebrities;
};

var actionCelebs = [{name:"Stallone", id:0}, {name:"Cruise", id:0}, {name:"Willis", id:0}];

var createIdForActionCelebs = celebrityIDCreator (actionCelebs);

var stalloneID = createIdForActionCelebs[0];

console.log(stalloneID.id); // 100

console.log(createIdForActionCelebs[1].id); // 101
</code>```

I don't understand why IIFE is needed here, I replaced celebrityIDCreator with and produced the same results:

```<code>var celebrityIDCreator = function(theCelebrities) {
      var i;
      var uniqueID = 100;
      for (i = 0; i < theCelebrities.length; i++) {
          theCelebrities[i]["id"] = function (j) {
            return uniqueID + j;
              // return function () {

              // } () ;
          } (i);
      }

      return theCelebrities;
};
</code>```

Could some one explains this? Do I miss anything?

答:
I think it is a mistake on the blog. If you see the Closures Gone Awry section's first example, id is created as a function. But, in the second example, which you are referring to and which aims to solve a bug in the first, id is created as a property.

I think the second example should be like this in order to make it similar to the first. Notice the NOTEs in the code, near the IIFE in question and the consumption of id as a function

function celebrityIDCreator(theCelebrities) {
  var i;
  var uniqueID = 100;
  for (i = 0; i < theCelebrities.length; i++) {
    theCelebrities[i]["id"] = function(j) { // the j parametric variable is the i passed in on invocation of this IIFE
      return function() {
        return uniqueID + j; // each iteration of the for loop passes the current value of i into this IIFE and it saves the correct value to the array
      } // NOTE. Not an IIFE
    }(i); // immediately invoke the function passing the i variable as a parameter
  }
  return theCelebrities;
};

var actionCelebs = [{
  name: "Stallone",
  id: 0
}, {
  name: "Cruise",
  id: 0
}, {
  name: "Willis",
  id: 0
}];

var createIdForActionCelebs = celebrityIDCreator(actionCelebs);

var stalloneID = createIdForActionCelebs[0];

console.log(stalloneID.id()); // 100 NOTE: Use as function

console.log(createIdForActionCelebs[1].id()); // 101 NOTE: Use as function```

Apart from this, I believe you're not missing anything. Your code is right, if id needs to be a property.

Body:
The last example of http://javascriptissexy.com/understand-javascript-closures-with-ease/ is:

function celebrityIDCreator (theCelebrities) {
    var i;
    var uniqueID = 100;
    for (i = 0; i < theCelebrities.length; i++) {
        theCelebrities[i]["id"] = function (j)  { // the j parametric variable is the i passed in on invocation of this IIFE
            return function () {
                return uniqueID + j; // each iteration of the for loop passes the current value of i into this IIFE and it saves the correct value to the array
            } () // BY adding () at the end of this function, we are executing it immediately and returning just the value of uniqueID + j, instead of returning a function.
        } (i); // immediately invoke the function passing the i variable as a parameter
    }
    return theCelebrities;
};

var actionCelebs = [{name:"Stallone", id:0}, {name:"Cruise", id:0}, {name:"Willis", id:0}];

var createIdForActionCelebs = celebrityIDCreator (actionCelebs);

var stalloneID = createIdForActionCelebs[0];

console.log(stalloneID.id); // 100

console.log(createIdForActionCelebs[1].id); // 101

I don't understand why IIFE is needed here, I replaced celebrityIDCreator with and produced the same results:

var celebrityIDCreator = function(theCelebrities) {
      var i;
      var uniqueID = 100;
      for (i = 0; i < theCelebrities.length; i++) {
          theCelebrities[i]["id"] = function (j) {
            return uniqueID + j;
              // return function () {

              // } () ;
          } (i);
      }

      return theCelebrities;
};

Could some one explains this? Do I miss anything?

Body:
I think it is a mistake on the blog. If you see the Closures Gone Awry section's first example, id is created as a function. But, in the second example, which you are referring to and which aims to solve a bug in the first, id is created as a property.

I think the second example should be like this in order to make it similar to the first. Notice the NOTEs in the code, near the IIFE in question and the consumption of id as a function

function celebrityIDCreator(theCelebrities) {
  var i;
  var uniqueID = 100;
  for (i = 0; i < theCelebrities.length; i++) {
    theCelebrities[i]["id"] = function(j) { // the j parametric variable is the i passed in on invocation of this IIFE
      return function() {
        return uniqueID + j; // each iteration of the for loop passes the current value of i into this IIFE and it saves the correct value to the array
      } // NOTE. Not an IIFE
    }(i); // immediately invoke the function passing the i variable as a parameter
  }
  return theCelebrities;
};

var actionCelebs = [{
  name: "Stallone",
  id: 0
}, {
  name: "Cruise",
  id: 0
}, {
  name: "Willis",
  id: 0
}];

var createIdForActionCelebs = celebrityIDCreator(actionCelebs);

var stalloneID = createIdForActionCelebs[0];

console.log(stalloneID.id()); // 100 NOTE: Use as function

console.log(createIdForActionCelebs[1].id()); // 101 NOTE: Use as function

Apart from this, I believe you're not missing anything. Your code is right, if id needs to be a property.


问:
Why Symbols not convert string implicitly
Why Symbol('test').toString() works well, but I can't use '' + Symbol('test')?

It will throw Error:

cannot convert a Symbol value to a string

Why does the implicit type conversion not work? Why is the code not equal to '' + Symbol('test').toString()?

答:
According to ECMA-262, using the addition operator on a value of type Symbol in combination with a string value first calls the internal ToPrimitive, which returns the symbol. It then calls the internal ToString which, for Symbols, will throw a TypeError exception.

So calling the internal ToString is not the same as calling Symbol.prototype.toString.

So I guess the answer to:

Why does the implicit type conversion not work?

is "because the spec says so".


问:
Why does databinding not work?
I have a car-class like this:

```<code>public class car
{
    public String Name {get; private set;}

    public car(string name)
    {
      this.Name = name;
    }
}
</code>```

I also have a userControl:

```<code>public partial class CarListItem : UserControl
{
    private Car car;

    public CarListItem (Car car)
    {
        InitializeComponent();
        this.car= car;
    }

}
</code>```

With xaml:

```<code><Grid>
     <Label Content="{Binding Path=car.Name}" Name="lblCarName"/>
</Grid>
</code>```

but the databinding does not work. What am I doing wrong?

I want to show the name of the car on the userControl.

答:
For a binding to work, you need to have a value in a Control's DataContext property. It can also be inherited. So, child controls can also access parent's DataContext if they don't have one.

Properties (not even public) do not help with binding unless used with Self Binding.

To make your code work,

Replace

```<code>this.car = car;
</code>```

With

```<code>this.DataContext = car;
</code>```

And Replace

```<code><Label Content="{Binding Path=car.Name}" Name="lblCarName"/>
</code>```

With

```<code><Label Content="{Binding Path=Name}" Name="lblCarName"/>
</code>```

Title: Why does databinding not work?

Body:
I have a car-class like this:

public class car
{
    public String Name {get; private set;}

    public car(string name)
    {
      this.Name = name;
    }
}

I also have a userControl:

public partial class CarListItem : UserControl
{
    private Car car;

    public CarListItem (Car car)
    {
        InitializeComponent();
        this.car= car;
    }

}

With xaml:

<Grid>

</Grid>

but the databinding does not work. What am I doing wrong?

I want to show the name of the car on the userControl.

Body:
For a binding to work, you need to have a value in a Control's DataContext property. It can also be inherited. So, child controls can also access parent's DataContext if they don't have one.

Properties (not even public) do not help with binding unless used with Self Binding.

To make your code work,

Replace

this.car = car;

With

this.DataContext = car;

And Replace

<Label Content="{Binding Path=car.Name}" Name="lblCarName"/>

With

<Label Content="{Binding Path=Name}" Name="lblCarName"/>


问:
calcAverage issue
I don't know why my code is not calculating the average. It is compiling and running, but gives 0% as average. Here are the instructions for the assignment

Average and Grade (Methods Program):
  Write a program that asks the user to enter 5 test scores.  Your program should then display a letter
  grade for each test score, the average test score and the overall letter grade
  for the average score.  You can NOT use a for loop or an array (we haven't even covered that) in this
  program - the point is to learn how to define methods and call them several
  times if necessary.

```<code>import java.util.Scanner;
import java.text.DecimalFormat;

public class Homework8{

static double average;
static char grade;
public static void main (String[] args)  {
Scanner keyboard = new Scanner(System.in);
char letter1;
char letter2;
char letter3;
char letter4;
char letter5;
double score1;
double score2;
double score3;
double score4;
double score5;
double score;

System.out.println("Please enter the first score between 0 and 100: ");
score1 = keyboard.nextDouble();

System.out.println("Please enter the second score between 0 and 100:             ");
score2 = keyboard.nextDouble();

System.out.println("Please enter the third score between 0 and 100: ");
score3 = keyboard.nextDouble();

System.out.println("Please enter the fourth score between 0 and 100: ");
score4 = keyboard.nextDouble();

System.out.println("Please enter the fifth score between 0 and 100: ");
score5 = keyboard.nextDouble();

//System.out.println("The average of your five tests was: " +

System.out.println(
  "For TestA you scored: " + score1 + " giving you Grade: "
      + determineGrade(score1)
  + "\nFor TestB you scored: " + score2 + " giving you Grade: "
      + determineGrade(score2)
  + "\nFor TestC you scored: " + score3 + " giving you Grade: "
      + determineGrade(score3)
  + "\nFor TestD you scored: " + score4 + " giving you Grade: "
      + determineGrade(score4)
  + "\nFor TestF you scored: " + score5 + " giving you Grade: "
      + determineGrade(score5)
  + "\nBased on your average: " + average + " Your final Grade is: "
      + determineGrade((double)average));
  }

 public static double calcAverage(double score1, double score2, double     score3, double score4, double score5) {
 double average = (score1+score2+score3+score4+score5) / 5;
 return average;

}
public static char determineGrade(double score)
{

   if(score<=100 && score>=90)
   {
   return 'A';
   }

   else if(score>=80)
   {
   return 'B';
   }
   else if(score>=70)
   {
   return 'C';
   }
   else if(score>=60)
   {
   return 'D';
   }

   else
   {
   return 'F';
   }

}
}
</code>```

答:
you define the method calcAverage but you didn't call it.

```<code>import java.util.Scanner;
import java.text.DecimalFormat;

public class Homework8{

static double average;
static char grade;
public static void main (String[] args)  {
Scanner keyboard = new Scanner(System.in);
char letter1;
char letter2;
char letter3;
char letter4;
char letter5;
double score1;
double score2;
double score3;
double score4;
double score5;
double score;

System.out.println("Please enter the first score between 0 and 100: ");
score1 = keyboard.nextDouble();

System.out.println("Please enter the second score between 0 and 100:             ");
score2 = keyboard.nextDouble();

System.out.println("Please enter the third score between 0 and 100: ");
score3 = keyboard.nextDouble();

System.out.println("Please enter the fourth score between 0 and 100: ");
score4 = keyboard.nextDouble();

System.out.println("Please enter the fifth score between 0 and 100: ");
score5 = keyboard.nextDouble();

double average = calcAverage(score1,score2,score3,score4,score5);
//System.out.println("The average of your five tests was: " +

System.out.println(
  "For TestA you scored: " + score1 + " giving you Grade: "
      + determineGrade(score1)
  + "\nFor TestB you scored: " + score2 + " giving you Grade: "
      + determineGrade(score2)
  + "\nFor TestC you scored: " + score3 + " giving you Grade: "
      + determineGrade(score3)
  + "\nFor TestD you scored: " + score4 + " giving you Grade: "
      + determineGrade(score4)
  + "\nFor TestF you scored: " + score5 + " giving you Grade: "
      + determineGrade(score5)
  + "\nBased on your average: " + average + " Your final Grade is: "
      + determineGrade((double)average));
  }

 public static double calcAverage(double score1, double score2, double     score3, double score4, double score5) {
 double average = (score1+score2+score3+score4+score5) / 5.0;
 return average;

}
public static char determineGrade(double score)
{

   if(score<=100 && score>=90)
   {
   return 'A';
   }

   else if(score>=80)
   {
   return 'B';
   }
   else if(score>=70)
   {
   return 'C';
   }
   else if(score>=60)
   {
   return 'D';
   }

   else
   {
   return 'F';
   }

}
}
</code>```

Title: calcAverage issue

Body:
I don't know why my code is not calculating the average. It is compiling and running, but gives 0% as average. Here are the instructions for the assignment

Average and Grade (Methods Program):
  Write a program that asks the user to enter 5 test scores.  Your program should then display a letter
  grade for each test score, the average test score and the overall letter grade
  for the average score.  You can NOT use a for loop or an array (we haven't even covered that) in this
  program - the point is to learn how to define methods and call them several
  times if necessary.

import java.util.Scanner;
import java.text.DecimalFormat;

public class Homework8{

static double average;
static char grade;
public static void main (String[] args)  {
Scanner keyboard = new Scanner(System.in);
char letter1;
char letter2;
char letter3;
char letter4;
char letter5;
double score1;
double score2;
double score3;
double score4;
double score5;
double score;

System.out.println("Please enter the first score between 0 and 100: ");
score1 = keyboard.nextDouble();

System.out.println("Please enter the second score between 0 and 100:             ");
score2 = keyboard.nextDouble();

System.out.println("Please enter the third score between 0 and 100: ");
score3 = keyboard.nextDouble();

System.out.println("Please enter the fourth score between 0 and 100: ");
score4 = keyboard.nextDouble();

System.out.println("Please enter the fifth score between 0 and 100: ");
score5 = keyboard.nextDouble();

//System.out.println("The average of your five tests was: " +

System.out.println(
  "For TestA you scored: " + score1 + " giving you Grade: "
      + determineGrade(score1)
  + "\nFor TestB you scored: " + score2 + " giving you Grade: "
      + determineGrade(score2)
  + "\nFor TestC you scored: " + score3 + " giving you Grade: "
      + determineGrade(score3)
  + "\nFor TestD you scored: " + score4 + " giving you Grade: "
      + determineGrade(score4)
  + "\nFor TestF you scored: " + score5 + " giving you Grade: "
      + determineGrade(score5)
  + "\nBased on your average: " + average + " Your final Grade is: "
      + determineGrade((double)average));
  }

 public static double calcAverage(double score1, double score2, double     score3, double score4, double score5) {
 double average = (score1+score2+score3+score4+score5) / 5;
 return average;

}
public static char determineGrade(double score)
{

   if(score<=100 && score>=90)
   {
   return 'A';
   }

   else if(score>=80)
   {
   return 'B';
   }
   else if(score>=70)
   {
   return 'C';
   }
   else if(score>=60)
   {
   return 'D';
   }

   else
   {
   return 'F';
   }

}
}

Body:
you define the method calcAverage but you didn't call it.

import java.util.Scanner;
import java.text.DecimalFormat;

public class Homework8{

static double average;
static char grade;
public static void main (String[] args)  {
Scanner keyboard = new Scanner(System.in);
char letter1;
char letter2;
char letter3;
char letter4;
char letter5;
double score1;
double score2;
double score3;
double score4;
double score5;
double score;

System.out.println("Please enter the first score between 0 and 100: ");
score1 = keyboard.nextDouble();

System.out.println("Please enter the second score between 0 and 100:             ");
score2 = keyboard.nextDouble();

System.out.println("Please enter the third score between 0 and 100: ");
score3 = keyboard.nextDouble();

System.out.println("Please enter the fourth score between 0 and 100: ");
score4 = keyboard.nextDouble();

System.out.println("Please enter the fifth score between 0 and 100: ");
score5 = keyboard.nextDouble();

double average = calcAverage(score1,score2,score3,score4,score5);
//System.out.println("The average of your five tests was: " +

System.out.println(
  "For TestA you scored: " + score1 + " giving you Grade: "
      + determineGrade(score1)
  + "\nFor TestB you scored: " + score2 + " giving you Grade: "
      + determineGrade(score2)
  + "\nFor TestC you scored: " + score3 + " giving you Grade: "
      + determineGrade(score3)
  + "\nFor TestD you scored: " + score4 + " giving you Grade: "
      + determineGrade(score4)
  + "\nFor TestF you scored: " + score5 + " giving you Grade: "
      + determineGrade(score5)
  + "\nBased on your average: " + average + " Your final Grade is: "
      + determineGrade((double)average));
  }

 public static double calcAverage(double score1, double score2, double     score3, double score4, double score5) {
 double average = (score1+score2+score3+score4+score5) / 5.0;
 return average;

}
public static char determineGrade(double score)
{

   if(score<=100 && score>=90)
   {
   return 'A';
   }

   else if(score>=80)
   {
   return 'B';
   }
   else if(score>=70)
   {
   return 'C';
   }
   else if(score>=60)
   {
   return 'D';
   }

   else
   {
   return 'F';
   }

}
}


问:
How to call a function, but not receive a response until there is a value?
I have a function that queries the DOM and returns an array of data attributes.

```<code>var getUIDs = function () {

    $list = $('.foo');

    if ( $list.length ) {

        // loop through all the .foos and build an array
        return fooArray;

    } else {

        setTimeout(function(){
            getUIDs()
        }, 500);

    }

}
</code>```

This function can sometimes be called prior to .foo being present in the DOM. That's why if I check every half second or so, within a few seconds the array will exist and I could send it back.

My question is, is there an established pattern I should follow that allows a function to be called, but will not receive a return value until there is one?

答:
You can avoid callbacks, promises and recursion by executing this logic synchronously via sequential executor nsynjs:

function addFooClicked() {
    $("#myDiv").append("
Foo
");
}

function synchronousCode() {
    var getUIDs = function () {
        var foo = $('.foo').get();
        while ( foo.length == 0 ) {
            console.log("waiting 5 seconds...");
            nsynWait(nsynjsCtx,5000);
            foo = $('.foo').get();
        };
        console.log("got elements:",foo.length);
        return foo;
    };

    var res = getUIDs();
    console.log("returning...");
    return res;
}

nsynjs.run(synchronousCode,{},function(r){
    console.log("synchronousCode finished, res=",r);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script src="https://rawgit.com/amaksr/nsynjs/master/nsynjs.js"></script>
<script src="https://rawgit.com/amaksr/nsynjs/master/wrappers/nsynWait.js"></script>
<body>
  <button id="buttonStart" onclick="addFooClicked()">Click me few times</button>
  <div id="myDiv"></div>
</body></code>```

Snippet Updated

Body:
I have a function that queries the DOM and returns an array of data attributes.

var getUIDs = function () {

    $list = $('.foo');

    if ( $list.length ) {

        // loop through all the .foos and build an array
        return fooArray;

    } else {

        setTimeout(function(){
            getUIDs()
        }, 500);

    }

}

This function can sometimes be called prior to .foo being present in the DOM. That's why if I check every half second or so, within a few seconds the array will exist and I could send it back.

My question is, is there an established pattern I should follow that allows a function to be called, but will not receive a return value until there is one?

Body:
You can avoid callbacks, promises and recursion by executing this logic synchronously via sequential executor nsynjs:

function addFooClicked() {
    $("#myDiv").append("<div class='foo'>Foo</div>");
}

function synchronousCode() {
    var getUIDs = function () {
        var foo = $('.foo').get();
        while ( foo.length == 0 ) {
            console.log("waiting 5 seconds...");
            nsynWait(nsynjsCtx,5000);
            foo = $('.foo').get();
        };
        console.log("got elements:",foo.length);
        return foo;
    };

    var res = getUIDs();
    console.log("returning...");
    return res;
}

nsynjs.run(synchronousCode,{},function(r){
    console.log("synchronousCode finished, res=",r);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script src="https://rawgit.com/amaksr/nsynjs/master/nsynjs.js"></script>
<script src="https://rawgit.com/amaksr/nsynjs/master/wrappers/nsynWait.js"></script>
<body>
  <button id="buttonStart" onclick="addFooClicked()">Click me few times</button>
  <div id="myDiv"></div>
</body>

Snippet Updated