问:
Text-indent has effect on the first child span element of div?
here is the code: https://jsfiddle.net/zz89emkr/1/

```<code>.menu-items {
  width: 400px;
  text-indent: 5%;
}
<div class="menu-items">
    <span>Lorem ipsum dolor, sit amet consectetur adipisicing elit. Necessitatibus quia maiores voluptatum adipisci iusto perferendis earum quasi, accusamus magni temporibus alias consectetur, provident vel quis nesciunt expedita sit nemo aliquam?</span>
    <div>Lorem ipsum dolor sit, amet consectetur adipisicing elit. Illo quas esse eius. Quos atque ea necessitatibus labore est error hic. At quae veritatis sit aperiam debitis animi provident dolorum dolore?</div>
    <span>Lorem ipsum, dolor sit amet consectetur adipisicing elit. Cumque, eaque atque adipisci, fugiat fuga maiores repellendus voluptas non explicabo odio et ut tenetur sint iusto minima unde. Ex, voluptas sed?</span>
</div>
</code>```

I know that text-indent will not work on inline element, however, in this example, the first span will get text-indent. What's more, in firefox, the text-indent in the first span element is larger than that in the div element.

答:
Text-indent has effect on the first child span

No, actually the indentation has nothing to do with the span. Being that you have set text-indent on a block element - .menu-items - indentation will be applied before:

1) The first element/node in the container - regardless of whether that element is inline or block or whether the element is text or other content (such as an image) and...

2) All subsequent block level text elements in the container (*)(see below)

.wpr {
  text-indent: 5%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wpr">
  This is just a regular text node. However, since it's the <strong>first node</strong> in the container - it is indented (due to text-indent being set on the wrapper div)
  <p>This is some block level text - it's indented</p>
  <span>Here is some inline level text</span>
  <div>Here's some more block level text - again, indented</div>
  This text node is <strong>not indented</strong>
</div>
<hr>
<div class="wpr">
  <img src="http://via.placeholder.com/350x150" alt="">
  <p>Notice that the image above is indented (it's the first element in the container) This block level text - so it's also indented</p>
  <span>Here is some inline level text</span>
  <div>Here's some more block level text - again, indented</div>
  This text node is <strong>not indented</strong>
</div></code>```

What's more, in firefox, the text-indent in the first span element is
  larger than that in the div element

Firstly, this discrepancy on firefox can only be reproduced when:

1) The container element has a set width (less than the viewport width)

2) text-indent is set with a percentage value

3) The first element in container is not block level

(All 3 criteria are present in the example fiddle you provided)

This looks like a bug, since firefox renders the indentation (before the first element) as a percentage value of the viewport width instead of a percentage of the container width!

Codepen Demo (Resize in firefox to see this - and keep your eye on the indentation of the first line)

Being that The spec clearly states (bold mine):

Percentages:  refers to width of containing block

...I'd say that firefox is doing it wrong.

(*) That's my understanding of what is said in the spec:

Unless otherwise specified by the each-line and/or hanging keywords,
  only lines that are the first formatted line [CSS21] of an element
  are affected. For example, the first line of an anonymous block box is
  only affected if it is the first child of its parent element.

The spec elsewhere elaborates on the meaning of "first formatted line":

The "first formatted line" of an element may occur inside a
  block-level descendant in the same flow (i.e., a block-level
  descendant that is not positioned and not a float). E.g., the first
  line of the DIV in

This line...

 is the first line of
  the P (assuming that both P and DIV are block-level).

Body:
here is the code: https://jsfiddle.net/zz89emkr/1/

.menu-items {
  width: 400px;
  text-indent: 5%;
}

    Lorem ipsum dolor, sit amet consectetur adipisicing elit. Necessitatibus quia maiores voluptatum adipisci iusto perferendis earum quasi, accusamus magni temporibus alias consectetur, provident vel quis nesciunt expedita sit nemo aliquam?

Lorem ipsum dolor sit, amet consectetur adipisicing elit. Illo quas esse eius. Quos atque ea necessitatibus labore est error hic. At quae veritatis sit aperiam debitis animi provident dolorum dolore?

    Lorem ipsum, dolor sit amet consectetur adipisicing elit. Cumque, eaque atque adipisci, fugiat fuga maiores repellendus voluptas non explicabo odio et ut tenetur sint iusto minima unde. Ex, voluptas sed?

I know that text-indent will not work on inline element, however, in this example, the first span will get text-indent. What's more, in firefox, the text-indent in the first span element is larger than that in the div element.

Body:
Text-indent has effect on the first child span

No, actually the indentation has nothing to do with the span. Being that you have set text-indent on a block element - .menu-items - indentation will be applied before:

1) The first element/node in the container - regardless of whether that element is inline or block or whether the element is text or other content (such as an image) and...

2) All subsequent block level text elements in the container (*)(see below)

.wpr {
  text-indent: 5%;
}

<div class="wpr">
  This is just a regular text node. However, since it's the <strong>first node</strong> in the container - it is indented (due to text-indent being set on the wrapper div)
  <p>This is some block level text - it's indented</p>
  <span>Here is some inline level text</span>
  <div>Here's some more block level text - again, indented</div>
  This text node is <strong>not indented</strong>
</div>
<hr>
<div class="wpr">
  <img src="http://via.placeholder.com/350x150" alt="">
  <p>Notice that the image above is indented (it's the first element in the container) This block level text - so it's also indented</p>
  <span>Here is some inline level text</span>
  <div>Here's some more block level text - again, indented</div>
  This text node is <strong>not indented</strong>
</div>

What's more, in firefox, the text-indent in the first span element is
  larger than that in the div element

Firstly, this discrepancy on firefox can only be reproduced when:

1) The container element has a set width (less than the viewport width)

2) text-indent is set with a percentage value

3) The first element in container is not block level

(All 3 criteria are present in the example fiddle you provided)

This looks like a bug, since firefox renders the indentation (before the first element) as a percentage value of the viewport width instead of a percentage of the container width!

Codepen Demo (Resize in firefox to see this - and keep your eye on the indentation of the first line)

Being that The spec clearly states (bold mine):

Percentages:  refers to width of containing block

...I'd say that firefox is doing it wrong.

(*) That's my understanding of what is said in the spec:

Unless otherwise specified by the each-line and/or hanging keywords,
  only lines that are the first formatted line [CSS21] of an element
  are affected. For example, the first line of an anonymous block box is
  only affected if it is the first child of its parent element.

The spec elsewhere elaborates on the meaning of "first formatted line":

The "first formatted line" of an element may occur inside a
  block-level descendant in the same flow (i.e., a block-level
  descendant that is not positioned and not a float). E.g., the first
  line of the DIV in <DIV><P>This line...</P></DIV> is the first line of
  the P (assuming that both P and DIV are block-level).


来源: stackexchange

问:
How to fix "Setting an expiry date or a maximum age in the HTTP headers"
I am using Ftp
When I run my website on page speed tools, it gives me the following message "Setting an expiry date or a maximum age in the HTTP headers for static resources instructs the browser to load previously downloaded resources from local disk rather than over the network."
How Can I fix this ?

答: <meta http-equiv="Expires" content="30"> Where it will expires in 30 days.If your contents are updating daily,then you can set it to 1.It always checks daily for any updation.

ContentLicense: CC BY-SA 3.0


问:
How to query many to many relation tables in laravel?
i am trying to query many to many relation for my get api call. i have three table as shown here but i am not using pivot table.

This is my Projects model class and this the function

```<code>  public function projectRewd()
   {

     return $this
               ->belongsToMany('App\Rewards','rewards','project_id','reward_id');

   }
</code>```

And this is my Rewards model class and function

```<code>public function projectShip()
    {
        return $this->belongsToMany('App\Shipping_location','shipping_location','projects_id','rewards_id');

    }
</code>```

This is my api controller function

```<code>Route::get('projects/{id}', function($id) {
    $proj = Projects::whereHas('projectRewd', function($q)
    {
        $q->where('id', $id);
    });
    return $proj;

 });
</code>```

i am using this link for api call

```<code>http://localhost:8000/api/projects/1
</code>```

i want to extract rewards data and shipping_location data associate with project_id.

i am getting this error

```<code>"message": "Object of class Illuminate\\Database\\Eloquent\\Builder could not be converted to string"
</code>```

i check and tried all related error from different post.

i also search and tried many technique. Cant solve my problem.
Please suggest me how to do this??
can i do this type of query in larvel without using pivot table??

答:
You are getting Builder model because you forgot to add ->first() or ->get().

You should write:

```<code>$proj = Projects::whereHas('projectRewd', function($q){
        $q->where('id', $id);
})->first();
</code>```

Body:
i am trying to query many to many relation for my get api call. i have three table as shown here but i am not using pivot table.

This is my Projects model class and this the function

  public function projectRewd()
   {

     return $this
               ->belongsToMany('App\Rewards','rewards','project_id','reward_id');

   }

And this is my Rewards model class and function

public function projectShip()
    {
        return $this->belongsToMany('App\Shipping_location','shipping_location','projects_id','rewards_id');

    }

This is my api controller function

Route::get('projects/{id}', function($id) {
    $proj = Projects::whereHas('projectRewd', function($q)
    {
        $q->where('id', $id);
    });
    return $proj;

 });

i am using this link for api call

http://localhost:8000/api/projects/1

i want to extract rewards data and shipping_location data associate with project_id.

i am getting this error

"message": "Object of class Illuminate\\Database\\Eloquent\\Builder could not be converted to string"

i check and tried all related error from different post.

i also search and tried many technique. Cant solve my problem.
Please suggest me how to do this??
can i do this type of query in larvel without using pivot table??

Body:
You are getting Builder model because you forgot to add ->first() or ->get().

You should write:

$proj = Projects::whereHas('projectRewd', function($q){
        $q->where('id', $id);
})->first();


问:
Get selected element type
I want to get the type of element, that I've got selected using jQuery selectors.

Markup:

```<code><select name="a"></select>
<input name="b" type="text" />
<textarea name="c"></textarea>
</code>```

Javascript:

```<code>var field_names = new Array(
    'a',
    'b',
    'c'
);

for(var i = 0; i < field_names.length; i++) {
    var field = $('[name=' + required_fields[i] + ']:visible');

    // ?????
    // What do I write here to get one of those outputs:
    //    Element with name a is <select>
    //    Element with name b is <input>
    //    Element with name c is <textarea>

    alert('Element with name ' + required_fields[i] + ' is ' + element_type);
}
</code>```

答:
Use the DOM element's tagName property:

```<code>var element_type = field[0].tagName;
</code>```

Note that browsers are not entirely consistent about the case returned by tagName, so you should probably call toLowerCase to be safe: field[0].tagName.toLowerCase().

ContentLicense: CC BY-SA 2.5

Title: Get selected element type

Body:
I want to get the type of element, that I've got selected using jQuery selectors.

Markup:

<select name="a"></select>
<input name="b" type="text" />
<textarea name="c"></textarea>

Javascript:

var field_names = new Array(
    'a',
    'b',
    'c'
);

for(var i = 0; i < field_names.length; i++) {
    var field = $('[name=' + required_fields[i] + ']:visible');

    // ?????
    // What do I write here to get one of those outputs:
    //    Element with name a is <select>
    //    Element with name b is <input>
    //    Element with name c is <textarea>

    alert('Element with name ' + required_fields[i] + ' is ' + element_type);
}

Body:
Use the DOM element's tagName property:

var element_type = field[0].tagName;

Note that browsers are not entirely consistent about the case returned by tagName, so you should probably call toLowerCase to be safe: field[0].tagName.toLowerCase().


问:
how to compare results in for-loop in python
I created a class, it has some initial variable like coefficient and error. And in my method, I have a for loop to calculate something, in each run, I will get a number which is named as error. And in each run, I got a error and also have a coefficient number. What I want to do is, at the first run, I can get a error and a coefficient set. At the second run, I will compare error with the previous error, if it is smaller than previous one, then, update error to the smaller error, and also update the coefficient. Else, keep the previous error and coefficient.

```<code>class getMinError():
def __init__(self):
    self.error = 0
    self.ce1 = 0
    self.ce2 = 0

def process(self):
     for i in range(any number):
        run to get error, ce1,and ce2
        save the first run's result to self.error, self.ce1,and self.ce2
</code>```

or just save it without update to the initial variables.

compare in the next loops, and
update only when error is smaller than previous ones.

答:
You should store the result from first run to compare it to the next ones.
Then in each iteration compare the current run's error to the number stored in smallestError (the smallest err found yet). If you find a smaler error than smallestError then do the updations of co-efficienets and error and change smallestError to the recently found error.
Hope this helps :) .</p>

```<code>class getMinError():
def __init__(self):
    self.error = 0
    self.ce1 = 0
    self.ce2 = 0

//store the error of first run
run to get error, ce1,and ce2
smallestError = error

def process(self):
     for i in range(2:n):
        run to get error, ce1,and ce2
        if smallestError > error :
           self.error=error
           self.ce1=ce1
           self.ce2=ce2
           smallestError = error
</code>```

Body:
I created a class, it has some initial variable like coefficient and error. And in my method, I have a for loop to calculate something, in each run, I will get a number which is named as error. And in each run, I got a error and also have a coefficient number. What I want to do is, at the first run, I can get a error and a coefficient set. At the second run, I will compare error with the previous error, if it is smaller than previous one, then, update error to the smaller error, and also update the coefficient. Else, keep the previous error and coefficient.

class getMinError():
def __init__(self):
    self.error = 0
    self.ce1 = 0
    self.ce2 = 0

def process(self):
     for i in range(any number):
        run to get error, ce1,and ce2
        save the first run's result to self.error, self.ce1,and self.ce2

or just save it without update to the initial variables.

compare in the next loops, and
update only when error is smaller than previous ones.

Body:
You should store the result from first run to compare it to the next ones.
Then in each iteration compare the current run's error to the number stored in smallestError (the smallest err found yet). If you find a smaler error than smallestError then do the updations of co-efficienets and error and change smallestError to the recently found error.
Hope this helps :) .

class getMinError():
def __init__(self):
    self.error = 0
    self.ce1 = 0
    self.ce2 = 0

//store the error of first run
run to get error, ce1,and ce2
smallestError = error

def process(self):
     for i in range(2:n):
        run to get error, ce1,and ce2
        if smallestError > error :
           self.error=error
           self.ce1=ce1
           self.ce2=ce2
           smallestError = error


问:
I have two values on the first row of the table it_courses field course_branch. When i join branch table with it_courses table result only one value
these are the tables

and it results
I have two values on the first row of the table it_courses field course_branch. When i join branch table with it_courses table result is like this.it doesnt shows the second value in the 1st row that was entered in the it_coursestable

Query :

```<code>SELECT branch.branch_name
FROM `branch`
JOIN `it_courses` ON it_courses.course_branch = branch.branch_id
</code>```

答:
You can try this database structure and query :

Table:

tbl_it_courses (id - PK, cource_name, branch_id - FK)

tbl_branch (id - PK, branch_id, branch_name)

Table : tbl_it_courses

```<code>CREATE TABLE tbl_it_courses (
    id INT NOT NULL AUTO_INCREMENT,
    cource_name VARCHAR(70) NOT NULL,
    branch_id VARCHAR(70) DEFAULT NULL,
    PRIMARY KEY(id)
);

INSERT INTO `tbl_it_courses` (`Id`, `cource_name`, `branch_id`) VALUES (NULL, 'PHP', '1,4'),(NULL, '.NET', '3'), (NULL, 'CCNA', '3');
</code>```

Table : tbl_branch

```<code>CREATE TABLE tbl_branch (
    id INT NOT NULL AUTO_INCREMENT,
    branch_id VARCHAR(70) DEFAULT NULL,
    branch_name VARCHAR(70) NOT NULL,
    PRIMARY KEY(id)
);

INSERT INTO `tbl_branch` (`Id`, `branch_id`, `branch_name`) VALUES (NULL, 'Ern', 'brn92b224'),(NULL, 'Klm', 'brnaf3650'), (NULL, 'Tvm', 'brn272493');
</code>```

Query :

```<code>SELECT tbl_it_courses.cource_name, (SELECT GROUP_CONCAT(tbl_branch.branch_name) FROM tbl_branch WHERE FIND_IN_SET(tbl_branch.id,tbl_it_courses.branch_id) > 0)  as branch_name
FROM tbl_it_courses
</code>```

I Hope It will Help you.

Body:
these are the tables

and it results
I have two values on the first row of the table it_courses field course_branch. When i join branch table with it_courses table result is like this.it doesnt shows the second value in the 1st row that was entered in the it_coursestable

Query :

SELECT branch.branch_name
FROM `branch`
JOIN `it_courses` ON it_courses.course_branch = branch.branch_id

Body:
You can try this database structure and query :

Table:

tbl_it_courses (id - PK, cource_name, branch_id - FK)

tbl_branch (id - PK, branch_id, branch_name)

Table : tbl_it_courses

CREATE TABLE tbl_it_courses (
    id INT NOT NULL AUTO_INCREMENT,
    cource_name VARCHAR(70) NOT NULL,
    branch_id VARCHAR(70) DEFAULT NULL,
    PRIMARY KEY(id)
);

INSERT INTO `tbl_it_courses` (`Id`, `cource_name`, `branch_id`) VALUES (NULL, 'PHP', '1,4'),(NULL, '.NET', '3'), (NULL, 'CCNA', '3');

Table : tbl_branch

CREATE TABLE tbl_branch (
    id INT NOT NULL AUTO_INCREMENT,
    branch_id VARCHAR(70) DEFAULT NULL,
    branch_name VARCHAR(70) NOT NULL,
    PRIMARY KEY(id)
);

INSERT INTO `tbl_branch` (`Id`, `branch_id`, `branch_name`) VALUES (NULL, 'Ern', 'brn92b224'),(NULL, 'Klm', 'brnaf3650'), (NULL, 'Tvm', 'brn272493');

Query :

SELECT tbl_it_courses.cource_name, (SELECT GROUP_CONCAT(tbl_branch.branch_name) FROM tbl_branch WHERE FIND_IN_SET(tbl_branch.id,tbl_it_courses.branch_id) > 0)  as branch_name
FROM tbl_it_courses

I Hope It will Help you.


问:
how to check array index
I have following code in jquery

```<code>var newFeeds = [];
$(data.d).each(function () {
  newFeeds.push({
    content: this.Name,
    id: this.Id
  });
});
</code>```

I am able to access values from newFeeds[0].content, newFeeds[1].content, newFeeds[2].content but when I tried to
 access newFeeds[3].content its showing undefined error and checked typeof equals(===) undefined but its showing Uncaught TypeError: Cannot read property 'content' of undefined error. How can I avoid this error. I have only 3 elements in the array. Is there a way in Jquery to avoid this error or Can I set value not available in non existence index ?

答:
I have done this way</p>

```<code> for (i = 0; i < 14;i++)
     {
        if (typeof newFeeds[i] !== undefined)
              {
                newFeeds.push({
                content: 'NA',
                id: 0
                             });

                 }

      }
</code>```

Title: how to check array index

Body:
I have following code in jquery

var newFeeds = [];
$(data.d).each(function () {
  newFeeds.push({
    content: this.Name,
    id: this.Id
  });
});

I am able to access values from newFeeds[0].content, newFeeds[1].content, newFeeds[2].content but when I tried to
 access newFeeds[3].content its showing undefined error and checked typeof equals(===) undefined but its showing Uncaught TypeError: Cannot read property 'content' of undefined error. How can I avoid this error. I have only 3 elements in the array. Is there a way in Jquery to avoid this error or Can I set value not available in non existence index ?

Body:
I have done this way

 for (i = 0; i < 14;i++)
     {
        if (typeof newFeeds[i] !== undefined)
              {
                newFeeds.push({
                content: 'NA',
                id: 0
                             });

                 }

      }


问:
Insert and select data in sql server
I want to insert data from table sp_test with two columns; (empid and amount) into another table sp_emp (regisno,empid,itemid,year,month,week,amount,paymentdate).

This is the query I used

```<code>Insert into sp_emp(regisno,empid,itemid,year,month,week,amount,paymentdate)
Select * from sp_test
</code>```

and it returned as select list for insert statement has fewer items. How should I put the values for another column?

答:
You have to use NULL or 0 for the remaining columns.

Try the following:

```<code>Insert into sp_emp(regisno,empid,itemid,year,month,week,amount,paymentdate)
Select NULL,EmpID,NULL,NULL,NULL,NULL,Amount,NULL from sp_test
</code>```

Title: Insert and select data in sql server

Body:
I want to insert data from table sp_test with two columns; (empid and amount) into another table sp_emp (regisno,empid,itemid,year,month,week,amount,paymentdate).

This is the query I used

Insert into sp_emp(regisno,empid,itemid,year,month,week,amount,paymentdate)
Select * from sp_test

and it returned as select list for insert statement has fewer items. How should I put the values for another column?

Body:
You have to use NULL or 0 for the remaining columns.

Try the following:

Insert into sp_emp(regisno,empid,itemid,year,month,week,amount,paymentdate)
Select NULL,EmpID,NULL,NULL,NULL,NULL,Amount,NULL from sp_test


问:
unordered_map: which one is faster find() or count()?
What is the fastest way to figure out if an unordered_map container has an item with a specified key?

答:
find() and count() are applicable to many containers in C++.

For maps, sets etc. find() will always have constant execution time, since it just calculate the hash, and returns an iterator to the first element found (end() if not found).

count() on the other hand, has a constant execution time O(e), where e is the number of times the provided key is found. The worst case is a collection where all members are the same, so count() could have a complexity O(n)

map or unordered_map do not allow for duplicates, therefore their asymptotic run time would be the same.

The choice depends on the semantics in your code. If you want just to check if a key exist, you could just use count. If you would like to check if a key exists, and use its value, then go for find since you will already have an iterator pointing to that element.

ContentLicense: CC BY-SA 4.0


问:
Python: how to find the first nonzero in a multi-series dataframe?
I have a dataframe with 5 columns indexed to date.  the data is consisted of 0's and 1's.  I would like to find the first nonzeros in each series and multiple it (and only it) by 100.

Date   A   B   C   D   E
3/1/16  0   0   0   0   0
3/2/16  0   0   1   0   0
3/3/16  1   0   0   0   0
3/4/16  0   1   0   0   0
3/7/16  0   0   1   0   1
3/8/16  0   0   0   0   1
3/9/16  0   0   0   1   1

I tried the following code, but it didn't work.

```<code>for col in df.columns:
    idx = df[col].first_valid_index()
    df[col][idx] = df[col][idx]*100.
</code>```

Body:
I have a dataframe with 5 columns indexed to date.  the data is consisted of 0's and 1's.  I would like to find the first nonzeros in each series and multiple it (and only it) by 100.

Date   A   B   C   D   E
3/1/16  0   0   0   0   0
3/2/16  0   0   1   0   0
3/3/16  1   0   0   0   0
3/4/16  0   1   0   0   0
3/7/16  0   0   1   0   1
3/8/16  0   0   0   0   1
3/9/16  0   0   0   1   1

I tried the following code, but it didn't work.

for col in df.columns:
    idx = df[col].first_valid_index()
    df[col][idx] = df[col][idx]*100.

Body:
I knew there was a way to use argmax here.

df = df.set_index('Date')

v = df.values
v[v.argmax(0), np.arange(df.shape[1] - 1)] *= 100
df[:] = v

df.reset_index()

     Date    A    B    C    D    E
0  3/1/16    0    0    0    0    0
1  3/2/16    0    0  100    0    0
2  3/3/16  100    0    0    0    0
3  3/4/16    0  100    0    0    0
4  3/7/16    0    0  100    0    1
5  3/8/16    0    0    0    0  100
6  3/9/16    0    0    0  100    1

Had a little help from here.


问:
Value types in object stored in heap as well?
I can imagine this question has been asked thousands of times, but I didn't have much luck in finding the answer, plus this is more out of curiosity than need.

Digging into the nuts and bolts of C#, I was wondering since objects are stored in the heap, are the value types within the objects stored in the heap as well or are they placed in the stack?

答: They are stored in the heap, inside of the memory allocated for the reference type.  In addition, value types are often stored in places other than "the stack".  However, the CLI spec does not specify where the memory pool that stores value types resides - it's an implementation detail that should not matter.</p>


问:
The C Programming Language, Ch.1 Exercise 1.10 (Getchar and Putchar)
I've been working on this for 2 hours and I am stuck... I found the answer online, but that isn't going to help me learn the concept that I'm obviously missing.

Prompt: Write a program to copy its input to its output, replacing each tab by \t , each backspace by \b , and each backslash by \\ . This makes tabs and backspaces visible in an unambiguous way.

Here's what I came up with, it doesn't replace a tab or \ with the indicated putchar, it just adds it in front of it.(I didn't do backspace because I can't really input a backspace...):

This is how I read the code. What am I missing?:

"There is some integer c. c is equal to the input. When the input is not equal to end of file proceed. If input is tab then the output \t. If input is \ then output \\. Output the input to console."

```<code>int c;

while((c=getchar())!=EOF)
{
    if(c=='\t')
        {
            putchar('\\');
            putchar('t');
        }

    if(c=='\\')
        {
            putchar('\\');
            putchar('\\');
        }
    putchar(c);
}
</code>```

答:
I know im late to the party, but this question pops up in chapter one before else, case, continue, and functions are introduced.

Here is a working solution to exercise 1-10 that involves only concepts introduced up to the point of the exercise.  You need to keep track of whether an escaped character was found and then display the copied character only if one was not found.

```<code>#include <stdio.h>

int main() {

  int input;

  while((input = getchar()) != EOF){

    int escaped = 0;

    if(input == '\t'){
        putchar('\\');
        putchar('t');
        escaped = 1;
    }

    if(input == '\b'){
        putchar('\\');
        putchar('b');
        escaped = 1;
    }

    if(input == '\\'){
        putchar('\\');
        putchar('\\');
        escaped = 1;
    }

    if(escaped == 0){
      putchar(input);
    }
  }
}
</code>```

Body:
I've been working on this for 2 hours and I am stuck... I found the answer online, but that isn't going to help me learn the concept that I'm obviously missing.

Prompt: Write a program to copy its input to its output, replacing each tab by \t , each backspace by \b , and each backslash by \\ . This makes tabs and backspaces visible in an unambiguous way.

Here's what I came up with, it doesn't replace a tab or \ with the indicated putchar, it just adds it in front of it.(I didn't do backspace because I can't really input a backspace...):

This is how I read the code. What am I missing?:

"There is some integer c. c is equal to the input. When the input is not equal to end of file proceed. If input is tab then the output \t. If input is \ then output \\. Output the input to console."

int c;

while((c=getchar())!=EOF)
{
    if(c=='\t')
        {
            putchar('\\');
            putchar('t');
        }

    if(c=='\\')
        {
            putchar('\\');
            putchar('\\');
        }
    putchar(c);
}

Body:
I know im late to the party, but this question pops up in chapter one before else, case, continue, and functions are introduced.

Here is a working solution to exercise 1-10 that involves only concepts introduced up to the point of the exercise.  You need to keep track of whether an escaped character was found and then display the copied character only if one was not found.

#include <stdio.h>

int main() {

  int input;

  while((input = getchar()) != EOF){

    int escaped = 0;

    if(input == '\t'){
        putchar('\\');
        putchar('t');
        escaped = 1;
    }

    if(input == '\b'){
        putchar('\\');
        putchar('b');
        escaped = 1;
    }

    if(input == '\\'){
        putchar('\\');
        putchar('\\');
        escaped = 1;
    }

    if(escaped == 0){
      putchar(input);
    }
  }
}


问:
Parse Error on Nodejs POST request
I am looking to send a request to a server running on localhost and process its' response and reply back to the user. </p>

```<code>        var post_data = qs.stringify({
            'parameter':'some value'
        });

        var post_options = {
            uri: 'http://localhost:9000',

            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'Content-Length': Buffer.byteLength(post_data)
            }
        };

        var post_req = request(post_options,function(error,response,body){
            response.setEncoding('utf-8');
            if(response.statusCode==200)
            {
                console.log(body);
                var resp_data = JSON.parse(body);
                var result = validate(resp_data,expected_output);
                res.setHeader('Access-Control-Allow-Origin','*');
                res.writeHead(200,{"Content-Type":"application/json"});
                res.write(JSON.stringify(result));
                res.end();
            }
        });
        post_req.write(post_data);
        post_req.end();
</code>```

<p>However, the 'body' parameter in the call back function of 'post_req' is undefined even though server running on localhost:9000 returns a response. On checking the 'error' parameter, it shows 'Error: Parse Error'. Help me out. </p>

答:
Are you passing JSON.parse(body) valid JSON? If not, it will give you that error.

Have a look at this question if you are passing it seemingly valid JSON. It could be that you're passing it as an object or array.

Title: Parse Error on Nodejs POST request

Body:
I am looking to send a request to a server running on localhost and process its' response and reply back to the user.

        var post_data = qs.stringify({
            'parameter':'some value'
        });

        var post_options = {
            uri: 'http://localhost:9000',

            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'Content-Length': Buffer.byteLength(post_data)
            }
        };

        var post_req = request(post_options,function(error,response,body){
            response.setEncoding('utf-8');
            if(response.statusCode==200)
            {
                console.log(body);
                var resp_data = JSON.parse(body);
                var result = validate(resp_data,expected_output);
                res.setHeader('Access-Control-Allow-Origin','*');
                res.writeHead(200,{"Content-Type":"application/json"});
                res.write(JSON.stringify(result));
                res.end();
            }
        });
        post_req.write(post_data);
        post_req.end();

However, the 'body' parameter in the call back function of 'post_req' is undefined even though server running on localhost:9000 returns a response. On checking the 'error' parameter, it shows 'Error: Parse Error'. Help me out.


问:
nokogiri gem - ERROR: Failed to build gem native extension.
i'm trying to deploy a rails application with capistrano but i'm having some problems with nokogiri gem when is bundle installing in the server ubuntu 16.04

The backtrace is the following:

```<code>Tasks: TOP => deploy:updated => bundler:install
(See full trace by running task with --trace)
The deploy has failed with an error: Exception while executing as root@104.236.11.204: bundle exit status: 5
bundle stdout: Gem::Ext::BuildError: ERROR: Failed to build gem native extension.

current directory:
/var/www/denunciabarranquillafinal/shared/bundle/ruby/2.3.0/gems/nokogiri-1.8.1/ext/nokogiri
/usr/local/rvm/rubies/ruby-2.3.0/bin/ruby -r ./siteconf20171113-30499-1nk84ws.rb
extconf.rb --use-system-libraries
Cannot allocate memory - /usr/local/rvm/rubies/ruby-2.3.0/bin/ruby -r
./siteconf20171113-30499-1nk84ws.rb extconf.rb --use-system-libraries 2>&1

Gem files will remain installed in
/var/www/denunciabarranquillafinal/shared/bundle/ruby/2.3.0/gems/nokogiri-1.8.1
for inspection.
Results logged to
/var/www/denunciabarranquillafinal/shared/bundle/ruby/2.3.0/extensions/x86_64-linux/2.3.0/nokogiri-1.8.1/gem_make.out

An error occurred while installing nokogiri (1.8.1), and Bundler cannot
continue.
Make sure that `gem install nokogiri -v '1.8.1'` succeeds before bundling.

In Gemfile:
  rails was resolved to 4.2.4, which depends on
    actionmailer was resolved to 4.2.4, which depends on
      actionpack was resolved to 4.2.4, which depends on
        actionview was resolved to 4.2.4, which depends on
          rails-dom-testing was resolved to 1.0.8, which depends on
            nokogiri
bundle stderr: Nothing written
</code>```

I ran the command

```<code>sudo apt-get install build-essential patch ruby-dev zlib1g-dev liblzma-dev
</code>```

in my server, and if I run "gem install nokogiri" the gem is installed normally.

I hope someone can help me to fix the error.

答:
try this :</p>

```<code>$ sudo apt-get update
$ sudo apt-get install libxml2-dev libxslt-dev
$ sudo gem install nokogiri
</code>```

Body:
i'm trying to deploy a rails application with capistrano but i'm having some problems with nokogiri gem when is bundle installing in the server ubuntu 16.04

The backtrace is the following:

Tasks: TOP => deploy:updated => bundler:install
(See full trace by running task with --trace)
The deploy has failed with an error: Exception while executing as root@104.236.11.204: bundle exit status: 5
bundle stdout: Gem::Ext::BuildError: ERROR: Failed to build gem native extension.

current directory:
/var/www/denunciabarranquillafinal/shared/bundle/ruby/2.3.0/gems/nokogiri-1.8.1/ext/nokogiri
/usr/local/rvm/rubies/ruby-2.3.0/bin/ruby -r ./siteconf20171113-30499-1nk84ws.rb
extconf.rb --use-system-libraries
Cannot allocate memory - /usr/local/rvm/rubies/ruby-2.3.0/bin/ruby -r
./siteconf20171113-30499-1nk84ws.rb extconf.rb --use-system-libraries 2>&1

Gem files will remain installed in
/var/www/denunciabarranquillafinal/shared/bundle/ruby/2.3.0/gems/nokogiri-1.8.1
for inspection.
Results logged to
/var/www/denunciabarranquillafinal/shared/bundle/ruby/2.3.0/extensions/x86_64-linux/2.3.0/nokogiri-1.8.1/gem_make.out

An error occurred while installing nokogiri (1.8.1), and Bundler cannot
continue.
Make sure that `gem install nokogiri -v '1.8.1'` succeeds before bundling.

In Gemfile:
  rails was resolved to 4.2.4, which depends on
    actionmailer was resolved to 4.2.4, which depends on
      actionpack was resolved to 4.2.4, which depends on
        actionview was resolved to 4.2.4, which depends on
          rails-dom-testing was resolved to 1.0.8, which depends on
            nokogiri
bundle stderr: Nothing written

I ran the command

sudo apt-get install build-essential patch ruby-dev zlib1g-dev liblzma-dev

in my server, and if I run "gem install nokogiri" the gem is installed normally.

I hope someone can help me to fix the error.

Body:
try this :

$ sudo apt-get update
$ sudo apt-get install libxml2-dev libxslt-dev
$ sudo gem install nokogiri


问:
display result of max() function with imshow in opencv
I have 2 Mat of 1 image with a little differences in some pixels. I want to find max for each pixel and show them. I wrote this code in Visual C++ 2010 (Console):

```<code>Mat dst;
max(result0, result1, dst);
imshow("dst", dst);
</code>```

and the dst image was displayed perfectly, but when I copied this code in windows form I received this error: "error C2440: '?' : cannot convert from 'cv::MatExpr' to 'bool'" so I changed the code to this:

```<code>Mat dst;
max(&result0, &result1, &dst);
imshow("dst", dst);
</code>```

but in run time this error was appeared:
"An unhandled exception of type 'System.Runtime.InteropServices.SEHException' occurred in OpenCVProject.exe
Additional information: External component has thrown an exception."

please help me to display the image.
thanks in advance

答:
As suggested by dekai adding the below but after the using namespace headers worked for me</p>

```<code>#undef max
#undef min
</code>```

Body:
I have 2 Mat of 1 image with a little differences in some pixels. I want to find max for each pixel and show them. I wrote this code in Visual C++ 2010 (Console):

Mat dst;
max(result0, result1, dst);
imshow("dst", dst);

and the dst image was displayed perfectly, but when I copied this code in windows form I received this error: "error C2440: '?' : cannot convert from 'cv::MatExpr' to 'bool'" so I changed the code to this:

Mat dst;
max(&result0, &result1, &dst);
imshow("dst", dst);

but in run time this error was appeared:
"An unhandled exception of type 'System.Runtime.InteropServices.SEHException' occurred in OpenCVProject.exe
Additional information: External component has thrown an exception."

please help me to display the image.
thanks in advance

Body:
As suggested by dekai adding the below but after the using namespace headers worked for me

#undef max
#undef min


答:
Andrew Hare is right. For the full details, see Eric Lippert's blog entry:

I'm disturbed by the myth that "value types go on the stack" ... It is usually stated incorrectly: the statement should be "value types can be stored on the stack", instead of the more common "value types are always stored on the stack".

Title: Value types in object stored in heap as well?

Body:
I can imagine this question has been asked thousands of times, but I didn't have much luck in finding the answer, plus this is more out of curiosity than need.

Digging into the nuts and bolts of C#, I was wondering since objects are stored in the heap, are the value types within the objects stored in the heap as well or are they placed in the stack?


问:
how to get the count of specific letters occurances from a array of words
i want to get the count of some text that starts with specific letter with "/"
 just like as follows. i want the count of all "A/" occurancves in that array.</p>

```<code><?php
$arr_vals = array("A/V","A/B","B/A","D/D","A/v","A/A");

$count_A = count($arr_vals,"A/*");

?>
</code>```

答:
Using fnmatch would also work and uses shell wildcards, e.g. * and ?:

```<code>function count_pattern(array $input, string $pattern): int {
    $count = 0;
    foreach ($input as $string) {
        $count += fnmatch($pattern, $string);
    }
    return $count;
}
</code>```

Usage

```<code>$arr_vals = array("A/V","A/B","B/A","D/D","A/v","A/A");
echo count_pattern($arr_vals, "A/*"); // 4
</code>```

Note: in order to use scalar type hints and returns you need PHP7. If you are not on PHP7 yet, you can just omit them.

Body:
i want to get the count of some text that starts with specific letter with "/"
 just like as follows. i want the count of all "A/" occurancves in that array.

<?php
$arr_vals = array("A/V","A/B","B/A","D/D","A/v","A/A");

$count_A = count($arr_vals,"A/*");

?>

Body:
Using fnmatch would also work and uses shell wildcards, e.g. * and ?:

function count_pattern(array $input, string $pattern): int {
    $count = 0;
    foreach ($input as $string) {
        $count += fnmatch($pattern, $string);
    }
    return $count;
}

Usage

$arr_vals = array("A/V","A/B","B/A","D/D","A/v","A/A");
echo count_pattern($arr_vals, "A/*"); // 4

Note: in order to use scalar type hints and returns you need PHP7. If you are not on PHP7 yet, you can just omit them.


问:
How to make passportjs local username be case insensitive?
Right now I'm using passportjs (local) for authentication on my site, but the username field is case sensitive, is there a way to change this? I thought about making the username all lowercase at the moment of registration, but that doesn't seem like a very efficient choice and still doesn't let me make log in case insensitive. </p>

```<code>router.post("/login", middleware.isNotLoggedIn, passport.authenticate("local", {
successRedirect: "",
failureRedirect: "/login"
}), function(req, res){
    res.redirect("back");
});
</code>```

答:
@robertklep was on to the right idea by suggesting a new LocalStrategy(...).  Notice the new RegExp(username, "i") to make the comparison case-insensitive.

```<code>passport.use(new LocalStrategy(
  function(username, password, done) {
   //User.getUserByUsername(username, function(err, user){
     User.getUserByUsername(new RegExp("^" + username + "$", "i"), function(err, user){
    if(err) throw err;
    if(!user){
        return done(null, false, {message: 'Unknown User'});
    }
    ...
</code>```

Body:
Right now I'm using passportjs (local) for authentication on my site, but the username field is case sensitive, is there a way to change this? I thought about making the username all lowercase at the moment of registration, but that doesn't seem like a very efficient choice and still doesn't let me make log in case insensitive.

router.post("/login", middleware.isNotLoggedIn, passport.authenticate("local", {
successRedirect: "",
failureRedirect: "/login"
}), function(req, res){
    res.redirect("back");
});

Body:
@robertklep was on to the right idea by suggesting a new LocalStrategy(...).  Notice the new RegExp(username, "i") to make the comparison case-insensitive.

passport.use(new LocalStrategy(
  function(username, password, done) {
   //User.getUserByUsername(username, function(err, user){
     User.getUserByUsername(new RegExp("^" + username + "$", "i"), function(err, user){
    if(err) throw err;
    if(!user){
        return done(null, false, {message: 'Unknown User'});
    }
    ...


问:
I am trying to run my app in background . But service Class is not working in background
It is an app that calculates some data and I want it to work in background if the app is closed. Here is my code

Here is the main activity.

```<code>  public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";
    RadioButton selectedRdb;
    RadioGroup gender;
    EditText drinkingTime;
    EditText bodyweight;
    EditText volume;

    EditText size;
    Intent counterIntent;

    String genderOfThePerson;
    Button start;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        gender = (RadioGroup) findViewById(R.id.genderRbGroup);

        drinkingTime = (EditText) findViewById(R.id.juontiAika);
        bodyweight = (EditText) findViewById(R.id.kehonPaino);

        volume = (EditText)findViewById(R.id.vahvuus);
        size = (EditText)findViewById(R.id.koko);
        start = (Button)findViewById(R.id.startBtn);
        counterIntent = new Intent(this, Counter.class);
    }

    public void startCounter(View view) {
        if(gender.getCheckedRadioButtonId()==-1)
        {
            Toast.makeText(getApplicationContext(), "Please select Gender", Toast.LENGTH_SHORT).show();
        }
        else{
            int selectedId = gender.getCheckedRadioButtonId();
            selectedRdb = (RadioButton)findViewById(selectedId);
            if(selectedRdb.getText().toString().equalsIgnoreCase("male")){
                genderOfThePerson = "male";
            }
            else if(selectedRdb.getText().toString().equalsIgnoreCase("female")){
                genderOfThePerson = "female";
            }

        }

        int bodyWeight = Integer.parseInt(bodyweight.getText().toString());

        double drinkSize = Double.parseDouble(size.getText().toString());
        drinkSize = drinkSize/10;

        double drinkVolume = Double.parseDouble(volume.getText().toString());
        double drinkingtime = Double.parseDouble(drinkingTime.getText().toString());

        //muutetaan juomisaika tunneiksi
        drinkingtime = drinkingtime / 60;

        counterIntent.putExtra("juomankoko", drinkSize);
        counterIntent.putExtra("juomanvahvuus", drinkVolume);
        counterIntent.putExtra("sukupuoli", genderOfThePerson);
        counterIntent.putExtra("kehonpaino", bodyWeight);

        counterIntent.putExtra("juontiaika", drinkingtime);

        startActivity(counterIntent);

    }

}
</code>```

Here is Counter Activity :-

```<code>    package com.mypackage.henri.beerdrinkreminder;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

import android.content.IntentFilter;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.mypackage.henri.beerdrinkreminder.Un.MainActivity;

import java.text.DecimalFormat;

public class Counter extends AppCompatActivity {

    Intent mainactivityIntent;
    Intent serviceIntent;
    TextView promilletTxt;
    TextView kanniAika;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_counter);

        mainactivityIntent  = new Intent(this, MainActivity.class);

        promilletTxt = (TextView)findViewById(R.id.bacTxt);
        kanniAika = (TextView)findViewById(R.id.känniAika);

        Button drinkButton = (Button)findViewById(R.id.drinkBtn);
        Button lopetaBtn = (Button)findViewById(R.id.stopBtn);
        Intent i = getIntent();

        //GETS THE USER INFO VARIABLES FROM INTENT AND SENDS THE FORWARD TO THE SERVICE
        serviceIntent = new Intent(Counter.this, CounterService.class);

        serviceIntent.putExtra("juomankoko", i.getDoubleExtra("juomankoko", 0));
        serviceIntent.putExtra("juomanvahvuus", i.getDoubleExtra("juomanvahvuus", 0));
        serviceIntent.putExtra("sukupuoli", i.getStringExtra("sukupuoli"));
        serviceIntent.putExtra("kehonpaino", i.getIntExtra("kehonpaino", 0));
        serviceIntent.putExtra("juontiaika", i.getDoubleExtra("juontiaika",0));

        startService(serviceIntent);
        registerReceiver(broadcastReceiver, new IntentFilter(CounterService.BROADCAST_ACTION));

        drinkButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //THIS IS FOR ADDING ANOTHER DRINK WHEN THE CALCULATOR IS ALREADY RUNNING
                AlertDialog.Builder builder = new AlertDialog.Builder(Counter.this);
                View dView = getLayoutInflater().inflate(R.layout.drinkdialog,null);
                final EditText dSize = (EditText)dView.findViewById(R.id.drinkSize);
                final EditText dTime = (EditText)dView.findViewById(R.id.drinkingTime);
                final EditText dStrenght = (EditText)dView.findViewById(R.id.juomanVahvuus);
                Button submitBtn = (Button)dView.findViewById(R.id.drinkBtn);

                builder.setView(dView);
                final AlertDialog dialog = builder.create();

                dialog.show();

                submitBtn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if(dSize.getText().toString().isEmpty()){
                            Toast.makeText(Counter.this, "Add the size of the drink", Toast.LENGTH_SHORT).show();
                        }
                        else if(dTime.getText().toString().isEmpty()){
                            Toast.makeText(Counter.this, "Add the drinking time", Toast.LENGTH_SHORT).show();
                        }
                        else{
                            double juomankoko = Double.parseDouble(dSize.getText().toString());
                            double juontiaika = Double.parseDouble(dTime.getText().toString());
                            double juomanvahvuus = Double.parseDouble(dStrenght.getText().toString());

                            serviceIntent.putExtra("juomankoko", juomankoko);
                            serviceIntent.putExtra("juontiaika", juontiaika);
                            serviceIntent.putExtra("juomanvahvuus", juomanvahvuus);

                            //THIS IS ID IS FOR CHECKING WHERE DID THE START REQUEST COME FROM. IF THE ID IS NOT 0,
                            // THEN THE SERVICE HAS ALREADY STARTED ATLEAST ONCE AND THE ALCOHOL CALCULATOR HAS BEEN CREATED ALREADY.
                            serviceIntent.putExtra("id", 123);

                            //STARTS SERVICE AGAIN
                            startService(serviceIntent);
                            dialog.cancel();

                        }
                    }
                });

            }
        });

        //THIS BUTTON IS FOR CANCELLING THE CALCULATIONS
        lopetaBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                AlertDialog.Builder builder = new AlertDialog.Builder(Counter.this);
                View dView = getLayoutInflater().inflate(R.layout.lopetusdialogi,null);

                TextView bac = (TextView) dView.findViewById(R.id.bac);
                TextView aikaaPäisn = (TextView)dView.findViewById(R.id.aikaaPäisn);
                /*bac.setText(alcCal.calculateCurrentBac(palamisVauhtiSekunissa) + "%");

                double aika = (alcCal.getGrammat() / palamisVauhtiSekunissa) / 3600;
                int tunnit = (int)Math.floor(aika);
                int minuutit = (int)Math.floor((aika - tunnit) * 60);

                aikaaPäisn.setText(tunnit + " hours " + minuutit + " minutes");
                */
                builder.setView(dView);
                final AlertDialog dialog = builder.create();

                dialog.show();

                Button dialoginLopetus = (Button)dView.findViewById(R.id.dialoginLopetus);

                dialoginLopetus.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        startActivity(mainactivityIntent);
                    }
                });

            }
        });
    }

    @Override
    protected void onPause() {
        super.onPause();

        startService(serviceIntent);
        registerReceiver(broadcastReceiver, new IntentFilter(CounterService.BROADCAST_ACTION));
    }

    @Override
    protected void onStop() {
        super.onStop();

        unregisterReceiver(broadcastReceiver);
        startService(new Intent(this, CounterService.class));
     //   registerReceiver(broadcastReceiver, new IntentFilter(CounterService.BROADCAST_ACTION));

    }

    private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {

            updateUI(intent);
        }
    };

    private void updateUI(Intent intent) {

        //THIS METHOD GETS THE CALCULATED ALCOHOL LEVEL AND TIME FROM THE PARAMETER INTENT AND DISPLAYS IT IN THE TEXTVIEWS
        double promillet = intent.getDoubleExtra("promillet", 0.0);
        double aikaPäisn = intent.getDoubleExtra("aika", 0.0);
        double grammat = intent.getDoubleExtra("grammat", 0.0);

        DecimalFormat df = new DecimalFormat("0.000");

        int tunnit = (int)Math.floor(aikaPäisn);
        int minuutit = (int)Math.floor((aikaPäisn - tunnit) * 60);

        promilletTxt.setText(df.format(promillet) + " %");
        kanniAika.setText(tunnit + " hours " + minuutit + " minutes");

    }
}
</code>```

I am trying to run this app when I destroy all activity.
Here is my Counter Service

```<code>package com.mypackage.henri.beerdrinkreminder;

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

public class CounterService extends Service {

    private static final String TAG = "CounterService";
    private Intent intent;
    public static final String BROADCAST_ACTION = "com.mypackage.henri.beerdrinkreminder.CounterService";

    private Handler handler = new Handler();

    AlcoholCalc alcCalc;

    //VARIABLES FOR THE CALCULATIONS
    double palamisVauhtiSekunissa;
    double promillet;
    private int aloitusLukema = 0;

    @Override
    public void onCreate() {
        super.onCreate();
        intent = new Intent(BROADCAST_ACTION);

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
      //  intent = new Intent(BROADCAST_ACTION);
        aloitusLukema++;

        //THIS IS FOR CHECKING IF THE SERVICE IS STARTED FOR THE FIRST TIME. IF IT IS, THEN WE CONSTRUCT THE ALCOHOL CALCULATOR.

        if(aloitusLukema == 1){

            int kehonpaino = intent.getIntExtra("kehonpaino", 0);
            Toast.makeText(getApplicationContext(),""+kehonpaino,Toast.LENGTH_SHORT).show();

            double juomanKoko = intent.getDoubleExtra("juomankoko", 0.0);

            double juomanVahvuus = intent.getDoubleExtra("juomanvahvuus", 0.0);

            double juontiaika = (intent.getDoubleExtra("juontiaika", 0.0));

            String sukupuoli = intent.getStringExtra("sukupuoli");

            alcCalc = new AlcoholCalc(sukupuoli,
                    kehonpaino,
                    juomanVahvuus,
                    juontiaika,
                    juomanKoko);
            double palamisvauhtiTunnissa = kehonpaino / 10;

            palamisVauhtiSekunissa = palamisvauhtiTunnissa / 3600;

        }
       /*
        //THIS SECTION IS DONE IF THE USER PRESSES THE DRINK-BUTTON IN COUNTER ACVITIVY AND ADDS ANOTHER DRINK.
        else if (intent.getIntExtra("id", 0) != 0){

            double juomanKoko = intent.getDoubleExtra("juomankoko", 0.0);

            double juomanVahvuus = intent.getDoubleExtra("juomanvahvuus", 0.0);

            double juontiaika = (intent.getDoubleExtra("juontiaika", 0.0));

            alcCalc.drinkABeer(juomanKoko/10, juontiaika, juomanVahvuus);

        }
        */

        handler.removeCallbacks(sendUpdatesToUI);
        handler.postDelayed(sendUpdatesToUI, 1000);

        return START_STICKY;

    }

    private Runnable sendUpdatesToUI = new Runnable() {
        public void run() {
            AlcCalculations();
            handler.postDelayed(this, 1000);
        }
    };

    private void AlcCalculations() {

        //THIS IS FOR CALCULATING THE ALCOHOL LEVEL
        promillet = alcCalc.calculateCurrentBac(palamisVauhtiSekunissa);

        double aikaTunteina = (alcCalc.getGrammat() / palamisVauhtiSekunissa) / 3600;

        intent.putExtra("aika", aikaTunteina);
        intent.putExtra("promillet", promillet);
        intent.putExtra("grammat", alcCalc.getGrammat());
        sendBroadcast(intent);

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        handler.removeCallbacks(sendUpdatesToUI);

    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }

}
</code>```

The app runs well in OnPause State. When I close the app it shows some error message :-

```<code>11-14 04:59:15.149 3539-3539/? E/AndroidRuntime: FATAL EXCEPTION: main
                                                 java.lang.RuntimeException: Unable to start service com.mypackage.henri.beerdrinkreminder.CounterService@536765c8 with null: java.lang.NullPointerException
                                                     at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:2507)
                                                     at android.app.ActivityThread.access$1900(ActivityThread.java:130)
                                                     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1292)
                                                     at android.os.Handler.dispatchMessage(Handler.java:99)
                                                     at android.os.Looper.loop(Looper.java:137)
                                                     at android.app.ActivityThread.main(ActivityThread.java:4745)
                                                     at java.lang.reflect.Method.invokeNative(Native Method)
                                                     at java.lang.reflect.Method.invoke(Method.java:511)
                                                     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
                                                     at dalvik.system.NativeStart.main(Native Method)
                                                  Caused by: java.lang.NullPointerException
                                                     at com.mypackage.henri.beerdrinkreminder.CounterService.onStartCommand(CounterService.java:46)
                                                     at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:2490)
                                                     at android.app.ActivityThread.access$1900(ActivityThread.java:130)
                                                     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1292)
                                                     at android.os.Handler.dispatchMessage(Handler.java:99)
                                                     at android.os.Looper.loop(Looper.java:137)
                                                     at android.app.ActivityThread.main(ActivityThread.java:4745)
                                                     at java.lang.reflect.Method.invokeNative(Native Method)
                                                     at java.lang.reflect.Method.invoke(Method.java:511)
                                                     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
                                                     at dalvik.system.NativeStart.main(Native Method)
11-14 04:59:17.345 3539-3539/? I/Process: Sending signal. PID: 3539 SIG: 9
</code>```

答:
In your onStartCommand() method, you are returning the flag START_STICKY. This flag is used when your OS kills the service and it could be

START_STICKY: If the Service process is terminated by the system, the Service is going to be restarted and no processed Intents will be delivered to the onStartCommand function. When no start Intents are pending for delivery, a null Intent is passed to the onStartCommand function. If a start request didn't return before the system kills the Service, the start request is submitted again on the restarted Service passing START_FLAG_RETRY on the onStartCommand second argument.

START_NOT_STICKY: If the Service is terminated by the system, the Service is only restarted when there is at least one pending start request to be delivered.

START_REDELIVER_INTENT: If the Service is terminated by the system, the Service will be restarted redelivering the last delivered start Intent and any pending requests. This kind of service is similar to START_STICKY, but instead of delivering a null Intent in the start command, the last successfully delivered Intent is dispatched. When the start request is redelivered, the flag START_ FLAG_REDELIVERY is passed in on the onStartCommand second argument.

When you are closing the app, you are killing the process in which the service resides.

I would suggest you return START_NOT_STICKY or START_REDELIVER_INTENT and check if it is working or not.
Also, check if the issue gets resolved after adding the attribute android:stopTask = "false", in the service tag of the manifest file, which basically doesn't kill the service when the app gets killed.

Go through this link if you still have some doubts:
Understanding Android Services

Body:
It is an app that calculates some data and I want it to work in background if the app is closed. Here is my code

Here is the main activity.

  public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";
    RadioButton selectedRdb;
    RadioGroup gender;
    EditText drinkingTime;
    EditText bodyweight;
    EditText volume;

    EditText size;
    Intent counterIntent;

    String genderOfThePerson;
    Button start;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        gender = (RadioGroup) findViewById(R.id.genderRbGroup);

        drinkingTime = (EditText) findViewById(R.id.juontiAika);
        bodyweight = (EditText) findViewById(R.id.kehonPaino);

        volume = (EditText)findViewById(R.id.vahvuus);
        size = (EditText)findViewById(R.id.koko);
        start = (Button)findViewById(R.id.startBtn);
        counterIntent = new Intent(this, Counter.class);
    }

    public void startCounter(View view) {
        if(gender.getCheckedRadioButtonId()==-1)
        {
            Toast.makeText(getApplicationContext(), "Please select Gender", Toast.LENGTH_SHORT).show();
        }
        else{
            int selectedId = gender.getCheckedRadioButtonId();
            selectedRdb = (RadioButton)findViewById(selectedId);
            if(selectedRdb.getText().toString().equalsIgnoreCase("male")){
                genderOfThePerson = "male";
            }
            else if(selectedRdb.getText().toString().equalsIgnoreCase("female")){
                genderOfThePerson = "female";
            }

        }

        int bodyWeight = Integer.parseInt(bodyweight.getText().toString());

        double drinkSize = Double.parseDouble(size.getText().toString());
        drinkSize = drinkSize/10;

        double drinkVolume = Double.parseDouble(volume.getText().toString());
        double drinkingtime = Double.parseDouble(drinkingTime.getText().toString());

        //muutetaan juomisaika tunneiksi
        drinkingtime = drinkingtime / 60;

        counterIntent.putExtra("juomankoko", drinkSize);
        counterIntent.putExtra("juomanvahvuus", drinkVolume);
        counterIntent.putExtra("sukupuoli", genderOfThePerson);
        counterIntent.putExtra("kehonpaino", bodyWeight);

        counterIntent.putExtra("juontiaika", drinkingtime);

        startActivity(counterIntent);

    }

}

Here is Counter Activity :-

    package com.mypackage.henri.beerdrinkreminder;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

import android.content.IntentFilter;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.mypackage.henri.beerdrinkreminder.Un.MainActivity;

import java.text.DecimalFormat;

public class Counter extends AppCompatActivity {

    Intent mainactivityIntent;
    Intent serviceIntent;
    TextView promilletTxt;
    TextView kanniAika;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_counter);

        mainactivityIntent  = new Intent(this, MainActivity.class);

        promilletTxt = (TextView)findViewById(R.id.bacTxt);
        kanniAika = (TextView)findViewById(R.id.känniAika);

        Button drinkButton = (Button)findViewById(R.id.drinkBtn);
        Button lopetaBtn = (Button)findViewById(R.id.stopBtn);
        Intent i = getIntent();

        //GETS THE USER INFO VARIABLES FROM INTENT AND SENDS THE FORWARD TO THE SERVICE
        serviceIntent = new Intent(Counter.this, CounterService.class);

        serviceIntent.putExtra("juomankoko", i.getDoubleExtra("juomankoko", 0));
        serviceIntent.putExtra("juomanvahvuus", i.getDoubleExtra("juomanvahvuus", 0));
        serviceIntent.putExtra("sukupuoli", i.getStringExtra("sukupuoli"));
        serviceIntent.putExtra("kehonpaino", i.getIntExtra("kehonpaino", 0));
        serviceIntent.putExtra("juontiaika", i.getDoubleExtra("juontiaika",0));

        startService(serviceIntent);
        registerReceiver(broadcastReceiver, new IntentFilter(CounterService.BROADCAST_ACTION));

        drinkButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //THIS IS FOR ADDING ANOTHER DRINK WHEN THE CALCULATOR IS ALREADY RUNNING
                AlertDialog.Builder builder = new AlertDialog.Builder(Counter.this);
                View dView = getLayoutInflater().inflate(R.layout.drinkdialog,null);
                final EditText dSize = (EditText)dView.findViewById(R.id.drinkSize);
                final EditText dTime = (EditText)dView.findViewById(R.id.drinkingTime);
                final EditText dStrenght = (EditText)dView.findViewById(R.id.juomanVahvuus);
                Button submitBtn = (Button)dView.findViewById(R.id.drinkBtn);

                builder.setView(dView);
                final AlertDialog dialog = builder.create();

                dialog.show();

                submitBtn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if(dSize.getText().toString().isEmpty()){
                            Toast.makeText(Counter.this, "Add the size of the drink", Toast.LENGTH_SHORT).show();
                        }
                        else if(dTime.getText().toString().isEmpty()){
                            Toast.makeText(Counter.this, "Add the drinking time", Toast.LENGTH_SHORT).show();
                        }
                        else{
                            double juomankoko = Double.parseDouble(dSize.getText().toString());
                            double juontiaika = Double.parseDouble(dTime.getText().toString());
                            double juomanvahvuus = Double.parseDouble(dStrenght.getText().toString());

                            serviceIntent.putExtra("juomankoko", juomankoko);
                            serviceIntent.putExtra("juontiaika", juontiaika);
                            serviceIntent.putExtra("juomanvahvuus", juomanvahvuus);

                            //THIS IS ID IS FOR CHECKING WHERE DID THE START REQUEST COME FROM. IF THE ID IS NOT 0,
                            // THEN THE SERVICE HAS ALREADY STARTED ATLEAST ONCE AND THE ALCOHOL CALCULATOR HAS BEEN CREATED ALREADY.
                            serviceIntent.putExtra("id", 123);

                            //STARTS SERVICE AGAIN
                            startService(serviceIntent);
                            dialog.cancel();

                        }
                    }
                });

            }
        });

        //THIS BUTTON IS FOR CANCELLING THE CALCULATIONS
        lopetaBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                AlertDialog.Builder builder = new AlertDialog.Builder(Counter.this);
                View dView = getLayoutInflater().inflate(R.layout.lopetusdialogi,null);

                TextView bac = (TextView) dView.findViewById(R.id.bac);
                TextView aikaaPäisn = (TextView)dView.findViewById(R.id.aikaaPäisn);
                /*bac.setText(alcCal.calculateCurrentBac(palamisVauhtiSekunissa) + "%");

                double aika = (alcCal.getGrammat() / palamisVauhtiSekunissa) / 3600;
                int tunnit = (int)Math.floor(aika);
                int minuutit = (int)Math.floor((aika - tunnit) * 60);

                aikaaPäisn.setText(tunnit + " hours " + minuutit + " minutes");
                */
                builder.setView(dView);
                final AlertDialog dialog = builder.create();

                dialog.show();

                Button dialoginLopetus = (Button)dView.findViewById(R.id.dialoginLopetus);

                dialoginLopetus.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        startActivity(mainactivityIntent);
                    }
                });

            }
        });
    }

    @Override
    protected void onPause() {
        super.onPause();

        startService(serviceIntent);
        registerReceiver(broadcastReceiver, new IntentFilter(CounterService.BROADCAST_ACTION));
    }

    @Override
    protected void onStop() {
        super.onStop();

        unregisterReceiver(broadcastReceiver);
        startService(new Intent(this, CounterService.class));
     //   registerReceiver(broadcastReceiver, new IntentFilter(CounterService.BROADCAST_ACTION));

    }

    private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {

            updateUI(intent);
        }
    };

    private void updateUI(Intent intent) {

        //THIS METHOD GETS THE CALCULATED ALCOHOL LEVEL AND TIME FROM THE PARAMETER INTENT AND DISPLAYS IT IN THE TEXTVIEWS
        double promillet = intent.getDoubleExtra("promillet", 0.0);
        double aikaPäisn = intent.getDoubleExtra("aika", 0.0);
        double grammat = intent.getDoubleExtra("grammat", 0.0);

        DecimalFormat df = new DecimalFormat("0.000");

        int tunnit = (int)Math.floor(aikaPäisn);
        int minuutit = (int)Math.floor((aikaPäisn - tunnit) * 60);

        promilletTxt.setText(df.format(promillet) + " %");
        kanniAika.setText(tunnit + " hours " + minuutit + " minutes");

    }
}

I am trying to run this app when I destroy all activity.
Here is my Counter Service

package com.mypackage.henri.beerdrinkreminder;

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

public class CounterService extends Service {

    private static final String TAG = "CounterService";
    private Intent intent;
    public static final String BROADCAST_ACTION = "com.mypackage.henri.beerdrinkreminder.CounterService";

    private Handler handler = new Handler();

    AlcoholCalc alcCalc;

    //VARIABLES FOR THE CALCULATIONS
    double palamisVauhtiSekunissa;
    double promillet;
    private int aloitusLukema = 0;

    @Override
    public void onCreate() {
        super.onCreate();
        intent = new Intent(BROADCAST_ACTION);

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
      //  intent = new Intent(BROADCAST_ACTION);
        aloitusLukema++;

        //THIS IS FOR CHECKING IF THE SERVICE IS STARTED FOR THE FIRST TIME. IF IT IS, THEN WE CONSTRUCT THE ALCOHOL CALCULATOR.

        if(aloitusLukema == 1){

            int kehonpaino = intent.getIntExtra("kehonpaino", 0);
            Toast.makeText(getApplicationContext(),""+kehonpaino,Toast.LENGTH_SHORT).show();

            double juomanKoko = intent.getDoubleExtra("juomankoko", 0.0);

            double juomanVahvuus = intent.getDoubleExtra("juomanvahvuus", 0.0);

            double juontiaika = (intent.getDoubleExtra("juontiaika", 0.0));

            String sukupuoli = intent.getStringExtra("sukupuoli");

            alcCalc = new AlcoholCalc(sukupuoli,
                    kehonpaino,
                    juomanVahvuus,
                    juontiaika,
                    juomanKoko);
            double palamisvauhtiTunnissa = kehonpaino / 10;

            palamisVauhtiSekunissa = palamisvauhtiTunnissa / 3600;

        }
       /*
        //THIS SECTION IS DONE IF THE USER PRESSES THE DRINK-BUTTON IN COUNTER ACVITIVY AND ADDS ANOTHER DRINK.
        else if (intent.getIntExtra("id", 0) != 0){

            double juomanKoko = intent.getDoubleExtra("juomankoko", 0.0);

            double juomanVahvuus = intent.getDoubleExtra("juomanvahvuus", 0.0);

            double juontiaika = (intent.getDoubleExtra("juontiaika", 0.0));

            alcCalc.drinkABeer(juomanKoko/10, juontiaika, juomanVahvuus);

        }
        */

        handler.removeCallbacks(sendUpdatesToUI);
        handler.postDelayed(sendUpdatesToUI, 1000);

        return START_STICKY;

    }

    private Runnable sendUpdatesToUI = new Runnable() {
        public void run() {
            AlcCalculations();
            handler.postDelayed(this, 1000);
        }
    };

    private void AlcCalculations() {

        //THIS IS FOR CALCULATING THE ALCOHOL LEVEL
        promillet = alcCalc.calculateCurrentBac(palamisVauhtiSekunissa);

        double aikaTunteina = (alcCalc.getGrammat() / palamisVauhtiSekunissa) / 3600;

        intent.putExtra("aika", aikaTunteina);
        intent.putExtra("promillet", promillet);
        intent.putExtra("grammat", alcCalc.getGrammat());
        sendBroadcast(intent);

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        handler.removeCallbacks(sendUpdatesToUI);

    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }

}

The app runs well in OnPause State. When I close the app it shows some error message :-

11-14 04:59:15.149 3539-3539/? E/AndroidRuntime: FATAL EXCEPTION: main
                                                 java.lang.RuntimeException: Unable to start service com.mypackage.henri.beerdrinkreminder.CounterService@536765c8 with null: java.lang.NullPointerException
                                                     at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:2507)
                                                     at android.app.ActivityThread.access$1900(ActivityThread.java:130)
                                                     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1292)
                                                     at android.os.Handler.dispatchMessage(Handler.java:99)
                                                     at android.os.Looper.loop(Looper.java:137)
                                                     at android.app.ActivityThread.main(ActivityThread.java:4745)
                                                     at java.lang.reflect.Method.invokeNative(Native Method)
                                                     at java.lang.reflect.Method.invoke(Method.java:511)
                                                     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
                                                     at dalvik.system.NativeStart.main(Native Method)
                                                  Caused by: java.lang.NullPointerException
                                                     at com.mypackage.henri.beerdrinkreminder.CounterService.onStartCommand(CounterService.java:46)
                                                     at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:2490)
                                                     at android.app.ActivityThread.access$1900(ActivityThread.java:130)
                                                     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1292)
                                                     at android.os.Handler.dispatchMessage(Handler.java:99)
                                                     at android.os.Looper.loop(Looper.java:137)
                                                     at android.app.ActivityThread.main(ActivityThread.java:4745)
                                                     at java.lang.reflect.Method.invokeNative(Native Method)
                                                     at java.lang.reflect.Method.invoke(Method.java:511)
                                                     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
                                                     at dalvik.system.NativeStart.main(Native Method)
11-14 04:59:17.345 3539-3539/? I/Process: Sending signal. PID: 3539 SIG: 9


问:
How to let the user pick certain positions in an array and write it to a file
I have been stuck for some time now. In my code, I want to read all of the names I have from a separate file, and I want to allow the user to select how many names they want to save to a new separate file and allow them to select which names they want to save to the file (by selecting the number in-front of the names printed to the screen).
I am not sure on how I would allow the user to select certain positions in the array "names" to print to a new file. My idea was to use the array "select" and check what number was in that array (eg select[0] = 1) and print out number[1].

Any help would be much appreciated, thankyou!

```<code>public class Main {
        public static void main(String[] args) throws IOException {
            BufferedWriter writefile;
            BufferedReader readfile;
            Scanner scan = new Scanner(System.in);
            readfile = new BufferedReader(new FileReader("names.txt"));
            writefile = new BufferedWriter(new FileWriter("nameChoices.txt"));
            String names[] = new String[10];
            System.out.println("Here are the list of names:");
            System.out.println();
            for (int i = 0; i < 10; i++) {
                names[i] = readfile.readLine();
                System.out.println(i + ". " + names[i]);
            }
            System.out.println();
            System.out.println("Please enter the number of names you want to select:");
            int choice = scan.nextInt();
            System.out.println("Enter the number infront of the names you want to select: ");
            int select[] = new int[choice];
            for (int j = 0; j < choice; j++) {
                select[j] = scan.nextInt();
            }

        }

    }
</code>```

答:
Your Question: "I am not sure on how I would allow the user to select certain positions in the array "names" to print to a new file."

There is nothing wrong with the way you have already opted to do this other than perhaps letting the User know what selection they happen to be currently on and trapping for invalid entries such as values too high or too low and of course alpha characters where numerical characters are required. Without taking care of this business you leave things open to specific Error Exceptions. When asking the User for input a good solution would be for you to take care of what can go wrong and if it does, allow the User to re-enter the required data.

The biggest problem you have is that you have no mechanism in place to write the desired data to file. You've started by declaring a BufferedWriter object but you have yet to implement it. This would of course entail iterating through the select array which ultimately each element holds the index of the names desired to save to file. Simply iterate through the select array and write each name to file:

```<code>for (int i = 0; i < select.length; i++) {
    writefile.write(name[select[i]] + System.lineSeparator());
    writefile.flush();
}
// Close the file when all writing is done.
writefile.close();
</code>```

With what is discussed above you might have a solution that would look something like this:

```<code>try {
    BufferedWriter writefile = new BufferedWriter(new FileWriter("nameChoices.txt"));
    BufferedReader readfile = new BufferedReader(new FileReader("names.txt"));
    Scanner scan = new Scanner(System.in);

    String allNames = "", fileLine = "";
    while((fileLine = readfile.readLine()) != null) {
        // Using a 'Terary Operator' to fill the allNames variable
        // with a comma delimited string of all the names in file. It
        // doesn't matter how many names are in file.
        allNames+= (allNames.equals("")) ? fileLine : "," + fileLine;
    }
    // Split the string in allNames to the names array.
    String names[] = allNames.split(",");

    // Display the names in console:
    // Use the System.out.format() method
    // to create a columnar display.
    System.out.println("Here are the list of names:");
    for (int i = 0; i < names.length; i++) {
        // Use the modulus operator to ensure 4 columns
        if (i % 4 == 0){
            // Print a new line
            System.out.print("\n");
        }
        System.out.format("%-15s", (i+1) + ". " + names[i]);
    }
    readfile.close(); // Close the reader. Don't need to leave it open.
    System.out.println();

    // Get the number of names the User wants to save...
    int choice = 0;
    while (choice == 0) {
        System.out.println("\nPlease enter the number of names you want to select:");
        try {
            choice = scan.nextInt();
        }
        catch (InputMismatchException ex) {
            System.err.println("Invalid Entry! Numerical value Only!\n");
            scan.nextLine(); // Clear the scanner buffer
            choice = 0;
        }
    }

    // Get the actual names the User wants to save...
    System.out.println();
    int j = 0;
    int select[] = new int[choice];
    System.out.println("Enter the numbers in front of the names you want to select: ");
    while (j < choice) {
        System.out.println("Enter the number for name #" + (j+1) + ": ");
        try {
            int index = scan.nextInt();
            if (index < 1 || index > names.length) {
                throw new InputMismatchException();
            }
            select[j] = index;
            j++;
        }
        catch (InputMismatchException ex) {
            System.err.println("Invalid Entry! Numerical value Only (1 to " +
                               names.length + ")!\n");
            scan.nextLine(); // Clear the scanner buffer
        }
    }

    //Write choices to file and Console...
    System.out.print("\nSaving Names: ");
    for (int i = 0; i < select.length; i++) {
        String save = names[select[i]-1] ;
        System.out.print(save + "\t");
        writefile.write(save + System.lineSeparator());
        writefile.flush();
    }
    writefile.close(); // close the writer
    System.out.println("\nDONE! File Created!");
}
catch (IOException ex) { ex.printStackTrace(); }
</code>```

In this example invalid entries are taken care of and the User is given the chance to enter valid data.

Body:
I have been stuck for some time now. In my code, I want to read all of the names I have from a separate file, and I want to allow the user to select how many names they want to save to a new separate file and allow them to select which names they want to save to the file (by selecting the number in-front of the names printed to the screen).
I am not sure on how I would allow the user to select certain positions in the array "names" to print to a new file. My idea was to use the array "select" and check what number was in that array (eg select[0] = 1) and print out number[1].

Any help would be much appreciated, thankyou!

public class Main {
        public static void main(String[] args) throws IOException {
            BufferedWriter writefile;
            BufferedReader readfile;
            Scanner scan = new Scanner(System.in);
            readfile = new BufferedReader(new FileReader("names.txt"));
            writefile = new BufferedWriter(new FileWriter("nameChoices.txt"));
            String names[] = new String[10];
            System.out.println("Here are the list of names:");
            System.out.println();
            for (int i = 0; i < 10; i++) {
                names[i] = readfile.readLine();
                System.out.println(i + ". " + names[i]);
            }
            System.out.println();
            System.out.println("Please enter the number of names you want to select:");
            int choice = scan.nextInt();
            System.out.println("Enter the number infront of the names you want to select: ");
            int select[] = new int[choice];
            for (int j = 0; j < choice; j++) {
                select[j] = scan.nextInt();
            }

        }

    }

Body:
Your Question: "I am not sure on how I would allow the user to select certain positions in the array "names" to print to a new file."

There is nothing wrong with the way you have already opted to do this other than perhaps letting the User know what selection they happen to be currently on and trapping for invalid entries such as values too high or too low and of course alpha characters where numerical characters are required. Without taking care of this business you leave things open to specific Error Exceptions. When asking the User for input a good solution would be for you to take care of what can go wrong and if it does, allow the User to re-enter the required data.

The biggest problem you have is that you have no mechanism in place to write the desired data to file. You've started by declaring a BufferedWriter object but you have yet to implement it. This would of course entail iterating through the select array which ultimately each element holds the index of the names desired to save to file. Simply iterate through the select array and write each name to file:

for (int i = 0; i < select.length; i++) {
    writefile.write(name[select[i]] + System.lineSeparator());
    writefile.flush();
}
// Close the file when all writing is done.
writefile.close();

With what is discussed above you might have a solution that would look something like this:

try {
    BufferedWriter writefile = new BufferedWriter(new FileWriter("nameChoices.txt"));
    BufferedReader readfile = new BufferedReader(new FileReader("names.txt"));
    Scanner scan = new Scanner(System.in);

    String allNames = "", fileLine = "";
    while((fileLine = readfile.readLine()) != null) {
        // Using a 'Terary Operator' to fill the allNames variable
        // with a comma delimited string of all the names in file. It
        // doesn't matter how many names are in file.
        allNames+= (allNames.equals("")) ? fileLine : "," + fileLine;
    }
    // Split the string in allNames to the names array.
    String names[] = allNames.split(",");

    // Display the names in console:
    // Use the System.out.format() method
    // to create a columnar display.
    System.out.println("Here are the list of names:");
    for (int i = 0; i < names.length; i++) {
        // Use the modulus operator to ensure 4 columns
        if (i % 4 == 0){
            // Print a new line
            System.out.print("\n");
        }
        System.out.format("%-15s", (i+1) + ". " + names[i]);
    }
    readfile.close(); // Close the reader. Don't need to leave it open.
    System.out.println();

    // Get the number of names the User wants to save...
    int choice = 0;
    while (choice == 0) {
        System.out.println("\nPlease enter the number of names you want to select:");
        try {
            choice = scan.nextInt();
        }
        catch (InputMismatchException ex) {
            System.err.println("Invalid Entry! Numerical value Only!\n");
            scan.nextLine(); // Clear the scanner buffer
            choice = 0;
        }
    }

    // Get the actual names the User wants to save...
    System.out.println();
    int j = 0;
    int select[] = new int[choice];
    System.out.println("Enter the numbers in front of the names you want to select: ");
    while (j < choice) {
        System.out.println("Enter the number for name #" + (j+1) + ": ");
        try {
            int index = scan.nextInt();
            if (index < 1 || index > names.length) {
                throw new InputMismatchException();
            }
            select[j] = index;
            j++;
        }
        catch (InputMismatchException ex) {
            System.err.println("Invalid Entry! Numerical value Only (1 to " +
                               names.length + ")!\n");
            scan.nextLine(); // Clear the scanner buffer
        }
    }

    //Write choices to file and Console...
    System.out.print("\nSaving Names: ");
    for (int i = 0; i < select.length; i++) {
        String save = names[select[i]-1] ;
        System.out.print(save + "\t");
        writefile.write(save + System.lineSeparator());
        writefile.flush();
    }
    writefile.close(); // close the writer
    System.out.println("\nDONE! File Created!");
}
catch (IOException ex) { ex.printStackTrace(); }

In this example invalid entries are taken care of and the User is given the chance to enter valid data.


问:
Azure function with additional input data parameter binding
I am trying to create an Azure Function with a ServiceBus Queue trigger and an additional input data.
That is the function should trigger on blob update giving the blob name as input. I want to have a Blob data as an additional input.

The function.json created is as below.

```<code>{
  "bindings": [
    {
      "name": "myQueueItem",
      "type": "serviceBusTrigger",
      "direction": "in",
      "queueName": "afqueue",
      "connection": "CONNECTIONSTRING",
      "accessRights": "Listen"
    },
    {
      "type": "blob",
      "name": "inputBlob",
      "path": "samplecontainer/{name}",
      "connection": "AzureWebJobsDashboard",
      "direction": "in"
    }
  ],
  "disabled": false
}
</code>```

The function signature defined is as follows.

```<code>public static void Run(string myQueueItem, Stream inputBlob, TraceWriter log){}
</code>```

This gives an error as below

```<code>Function ($ServiceBusQueueTriggerCSharp1) Error: Microsoft.Azure.WebJobs.Host: Error indexing method 'Functions.ServiceBusQueueTriggerCSharp1'. Microsoft.Azure.WebJobs.Host: No binding parameter exists for 'name'.
</code>```

Instead of paramter {name}, if a hardcoded value is given the function is working properly.
How to do the binding to input data variable.

答:
Input binding can be templated from trigger parameters. So, name should be part of your service bus message payload. You could implement the function like this:

public class MyQueueItem
{
    public string name { get; set; }
}

public static void Run(MyQueueItem myQueueItem, Stream inputBlob, TraceWriter log)
{}
```

Note that the only trigger for this function are Service Bus messages. The function will NOT be triggered by blob updates, unless some other code of yours sends a Service Bus message with blob name for each update in the system.

Body:
I am trying to create an Azure Function with a ServiceBus Queue trigger and an additional input data.
That is the function should trigger on blob update giving the blob name as input. I want to have a Blob data as an additional input.

The function.json created is as below.

{
  "bindings": [
    {
      "name": "myQueueItem",
      "type": "serviceBusTrigger",
      "direction": "in",
      "queueName": "afqueue",
      "connection": "CONNECTIONSTRING",
      "accessRights": "Listen"
    },
    {
      "type": "blob",
      "name": "inputBlob",
      "path": "samplecontainer/{name}",
      "connection": "AzureWebJobsDashboard",
      "direction": "in"
    }
  ],
  "disabled": false
}

The function signature defined is as follows.

public static void Run(string myQueueItem, Stream inputBlob, TraceWriter log){}

This gives an error as below

Function ($ServiceBusQueueTriggerCSharp1) Error: Microsoft.Azure.WebJobs.Host: Error indexing method 'Functions.ServiceBusQueueTriggerCSharp1'. Microsoft.Azure.WebJobs.Host: No binding parameter exists for 'name'.

Instead of paramter {name}, if a hardcoded value is given the function is working properly.
How to do the binding to input data variable.

Body:
Input binding can be templated from trigger parameters. So, name should be part of your service bus message payload. You could implement the function like this:

public class MyQueueItem
{
    public string name { get; set; }
}

public static void Run(MyQueueItem myQueueItem, Stream inputBlob, TraceWriter log)
{}

Note that the only trigger for this function are Service Bus messages. The function will NOT be triggered by blob updates, unless some other code of yours sends a Service Bus message with blob name for each update in the system.


问:
Javascript html: Constructing a Quoted Google search String
I would like to construct a quoted google search string, and put this string in a link. The user would click on the link and be taken to the quoted search result. (Using JQuery)

```<code>$(".abstract_text",this).append('<div><a href="http://google.com/search?btnI=1&q="'+art_title.make_search()+'"> Search For Fulltext</a></div>');
</code>```

The above code gives this output:

```<code>http://google.com/search?btnI=1&q=The+Q+switched+ND+YAG+laser+effectively+treats+tattoos+in+darkly+pigmented+skin
</code>```

I would like to find a way to produce this output:

```<code>http://google.com/search?btnI=1&q="The+Q+switched+ND+YAG+laser+effectively+treats+tattoos+in+darkly+pigmented+skin"
</code>```

My question seems to be related to this question but I'm not exactly sure how to apply the answer that was accepted there: Nesting Quotes in JavaScript/HTML

*Please Note that though the search results are the same regardless of the output in this case, they will be different in general.

Solution:Use the encode URI function

```<code>$(".abstract_text",this).append('<div><a href="http://google.com/search?btnI=1&q='+encodeURI('"'+art_title.make_search()+'"')+'"> Search For Fulltext</a></div>');
</code>```

Output:

```<code>http://www.google.com/search?btnI=1&q=%22Early+treatment+of+traumatic+tattoo+by+erbium+YAG+laser%22
</code>```

答:
Try this:</p>

```<code>$(".abstract_text", this).append('<div><a href=\'http://google.com/search?btnI=1&q=\"'+art_title.make_search()+'\"\'> Search For Fulltext</a></div>');
</code>```

Body:
I would like to construct a quoted google search string, and put this string in a link. The user would click on the link and be taken to the quoted search result. (Using JQuery)

$(".abstract_text",this).append('
 Search For Fulltext
');

The above code gives this output:

http://google.com/search?btnI=1&q=The+Q+switched+ND+YAG+laser+effectively+treats+tattoos+in+darkly+pigmented+skin

I would like to find a way to produce this output:

http://google.com/search?btnI=1&q="The+Q+switched+ND+YAG+laser+effectively+treats+tattoos+in+darkly+pigmented+skin"

My question seems to be related to this question but I'm not exactly sure how to apply the answer that was accepted there: Nesting Quotes in JavaScript/HTML

*Please Note that though the search results are the same regardless of the output in this case, they will be different in general.

Solution:Use the encode URI function

$(".abstract_text",this).append('
 Search For Fulltext
');

Output:

http://www.google.com/search?btnI=1&q=%22Early+treatment+of+traumatic+tattoo+by+erbium+YAG+laser%22

Body:
Try this:

$(".abstract_text", this).append('<div><a href=\'http://google.com/search?btnI=1&q=\"'+art_title.make_search()+'\"\'> Search For Fulltext</a></div>');


问:
advanced selector doesn't match using jquery
I have three ids in DOM, but somehow this code don't work? No error

```<code>$(function() {
  console.log('test')

  $('[div][id*="sohai"]').each(function() {
  console.log($(this))
})
})
</code>```

https://jsbin.com/bumoyezena/edit?html,js,console,output

答:
Remove [] surrounding the div selector

$(function() {
  console.log('test')

  $('div[id*="sohai"]').each(function() {
  //^---^--------------------
     console.log(this.id);
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="sohai-1"></div>
<div id="sohai-2"></div>
<div id="sohai-3"></div></code>```

Body:
I have three ids in DOM, but somehow this code don't work? No error

$(function() {
  console.log('test')

  $('[div][id*="sohai"]').each(function() {
  console.log($(this))
})
})

https://jsbin.com/bumoyezena/edit?html,js,console,output

Body:
Remove [] surrounding the div selector

$(function() {
  console.log('test')

  $('div[id*="sohai"]').each(function() {
  //^---^--------------------
     console.log(this.id);
  });
});

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