问:
Filter list of tuples fast
How do I filter a list of tuples efficiently with Python based on whether the first item is the same as the third?

Suppose I have old_data and I want new_data:

```<code>old_data = [(2,3,2), (3,4,4), (7,6,7), (2,1,2), (5,7,2)]

new_data = [(3,4,4), (5,7,2)]
</code>```

My current solution (list comprehension) is too slow:

```<code>new_data_too_slow = [x for x in old_data if x[0] != x[2]]
</code>```

This data is many millions of rows, and I do need to return a list of tuples in the same format.

答:
This could be done efficiently using numpy since its operations are coded in C.

```<code>In [16]: import numpy as np

In [17]: old_data = [(2,3,2), (3,4,4), (7,6,7), (2,1,2), (5,7,2)]

In [18]: np_data = np.asarray(old_data)

In [19]: new_data = np_data[ np_data[:,0] != np_data[:,2 ] ]

In [20]: new_data
Out[20]: array([[3, 4, 4],
                [5, 7, 2]])
</code>```

The comparison of the first and third items will be much faster this way. The conversion to numpy will not necessarily be expensive, because np.asarray (as opposed to just np.array) does not copy the original data unless it has to, it just wraps it.

At this point new_data is a numpy array, which you can iterate over just as if it were a list of tuples if that suffices, but you can easily turn it into a list of lists...

```<code>In [22]: new_data.tolist()
Out[22]: [[3, 4, 4], [5, 7, 2]]
</code>```

...and then into a list of tuples with a list comprehension if it is really necessary for your purposes.

Here are some timings of the comparison part on some generated data with a million rows with all elements either 0 or 1.

```<code>In [58]: test_data = np.random.randint( 0, 2, size=(1000000,3) )

In [59]: test_data
Out[59]:
array([[1, 1, 0],
       [1, 0, 0],
       [0, 1, 0],
       ...,
       [0, 0, 1],
       [0, 1, 0],
       [0, 1, 1]])

In [60]: %%timeit
new_data = test_data[test_data[:,0] != test_data[:,2]]
   ....:
10 loops, best of 3: 26.2 ms per loop

In [61]: test_data = test_data.tolist()

In [62]: %%timeit
new_data = [ x for x in test_data if x[0] != x[2] ]
   ....:
1 loop, best of 3: 345 ms per loop
</code>```

Title: Filter list of tuples fast

Body:
How do I filter a list of tuples efficiently with Python based on whether the first item is the same as the third?

Suppose I have old_data and I want new_data:

old_data = [(2,3,2), (3,4,4), (7,6,7), (2,1,2), (5,7,2)]

new_data = [(3,4,4), (5,7,2)]

My current solution (list comprehension) is too slow:

new_data_too_slow = [x for x in old_data if x[0] != x[2]]

This data is many millions of rows, and I do need to return a list of tuples in the same format.

Body:
This could be done efficiently using numpy since its operations are coded in C.

In [16]: import numpy as np

In [17]: old_data = [(2,3,2), (3,4,4), (7,6,7), (2,1,2), (5,7,2)]

In [18]: np_data = np.asarray(old_data)

In [19]: new_data = np_data[ np_data[:,0] != np_data[:,2 ] ]

In [20]: new_data
Out[20]: array([[3, 4, 4],
                [5, 7, 2]])

The comparison of the first and third items will be much faster this way. The conversion to numpy will not necessarily be expensive, because np.asarray (as opposed to just np.array) does not copy the original data unless it has to, it just wraps it.

At this point new_data is a numpy array, which you can iterate over just as if it were a list of tuples if that suffices, but you can easily turn it into a list of lists...

In [22]: new_data.tolist()
Out[22]: [[3, 4, 4], [5, 7, 2]]

...and then into a list of tuples with a list comprehension if it is really necessary for your purposes.

Here are some timings of the comparison part on some generated data with a million rows with all elements either 0 or 1.

In [58]: test_data = np.random.randint( 0, 2, size=(1000000,3) )

In [59]: test_data
Out[59]:
array([[1, 1, 0],
       [1, 0, 0],
       [0, 1, 0],
       ...,
       [0, 0, 1],
       [0, 1, 0],
       [0, 1, 1]])

In [60]: %%timeit
new_data = test_data[test_data[:,0] != test_data[:,2]]
   ....:
10 loops, best of 3: 26.2 ms per loop

In [61]: test_data = test_data.tolist()

In [62]: %%timeit
new_data = [ x for x in test_data if x[0] != x[2] ]
   ....:
1 loop, best of 3: 345 ms per loop


来源: stackexchange

问:
How to get the last N records in mongodb?
I can't find anywhere it has been documented this. By default, the find() operation will get the records from beginning. How can I get the last N records in mongodb?

Edit: also I want the returned result ordered from less recent to most recent, not the reverse.

答:
You may want to be using the find options :
http://docs.meteor.com/api/collections.html#Mongo-Collection-find

```<code>db.collection.find({}, {sort: {createdAt: -1}, skip:2, limit: 18}).fetch();
</code>```

ContentLicense: CC BY-SA 4.0

Body:
You may want to be using the find options :
http://docs.meteor.com/api/collections.html#Mongo-Collection-find

db.collection.find({}, {sort: {createdAt: -1}, skip:2, limit: 18}).fetch();

ContentLicense: CC BY-SA 3.0


问:
The ROLLBACK TRANSACTION request has no corresponding BEGIN TRANSACTION when ran UDATE statement
Got an error when ran update statement.
For one record it worked fine, but for a chunk of records it gives me an error.

Also, why it tells me that 64801 row(s) affected and then 1 row(s) affected and then 0? How should I interpret that?

This is the script:

```<code>update tblQuotes
set QuoteStatusID = 11, --Not Taken Up
    QuoteStatusReasonID = 9 --"Not Competitive"
where CAST(EffectiveDate as DATE) < CAST('2013-11-27' as DATE)
and CompanyLocationGuid = '32828BB4-E1FA-489F-9764-75D8AF7A78F1' -- Plaza Insurance Company
and LineGUID = '623AA353-9DFE-4463-97D7-0FD398400B6D' --Commercial Auto
</code>```

I added BEGIN TRANSACTION statement, but it still won't work.

```<code>BEGIN TRANSACTION
update tblQuotes
set QuoteStatusID = 11, --Not Taken Up
    QuoteStatusReasonID = 9 --"Not Competitive"
where CAST(EffectiveDate as DATE) < CAST('2017-11-27' as DATE)
 AND CompanyLocationGuid = '32828BB4-E1FA-489F-9764-75D8AF7A78F1' -- Plaza Insurance Company
and LineGUID = '623AA353-9DFE-4463-97D7-0FD398400B6D' --Commercial Auto
IF @@TRANCOUNT>0
COMMIT TRANSACTION
</code>```

答:
In my opinion this is a "flaw", if not a "bug" in SQL Server. When you COMMIT a transaction, TRANCOUNT is decremented by 1. When you ROLLBACK any transaction, all transactions in the calling stack are rolled back! This means that any calling procedure that tries to commit or rollback will have this error and you've lost the integrity of your calling stack.

I worked through this when building a mechanism do do unit testing on SQL Server. I get around it by always using named transactions as shown in the example below. You can obviously also check XACT_STATE. The point is simply that, rather than blindly committing and rolling back anonymous transactions, if you manage transactions by name or transaction id you have better control.

For unit testing, I write a stored procedure as a test that calls the procedure under test. The unit test is in either serializable or snapshot mode and ONLY includes a rollback statement. I call the procedure under test, validate the results, build test output (pass/fail, parameters, etc.) as XML output, then everything gets rolled back. This gets around the need to build "mock data". I can use the data on any environment as the transaction is always rolled back.

```<code>--
-- get @procedure from object_name(@@procid)
-------------------------------------------------
DECLARE @procedure        SYSNAME = N'a_procedure_name_is_a_synonym_so_can_be_longer_than_a_transaction_name'
        , @transaction_id BIGINT;
DECLARE @transaction_name NVARCHAR(32) = RIGHT(@procedure + N'_tx', 32);

--
BEGIN TRANSACTION @transaction_name;

BEGIN
    SELECT @transaction_id = [transaction_id]
    FROM   [sys].[dm_tran_active_transactions]
    WHERE  [name] = @transaction_name;

    SELECT *
    FROM   [sys].[dm_tran_active_transactions]
    WHERE  [name] = @transaction_name;

-- Perform work here
END;

IF EXISTS
   (SELECT *
    FROM   [sys].[dm_tran_active_transactions]
    WHERE  [name] = @transaction_name)
    ROLLBACK TRANSACTION @transaction_name;
</code>```

Body:
Got an error when ran update statement.
For one record it worked fine, but for a chunk of records it gives me an error.

Also, why it tells me that 64801 row(s) affected and then 1 row(s) affected and then 0? How should I interpret that?

This is the script:

update tblQuotes
set QuoteStatusID = 11, --Not Taken Up
    QuoteStatusReasonID = 9 --"Not Competitive"
where CAST(EffectiveDate as DATE) < CAST('2013-11-27' as DATE)
and CompanyLocationGuid = '32828BB4-E1FA-489F-9764-75D8AF7A78F1' -- Plaza Insurance Company
and LineGUID = '623AA353-9DFE-4463-97D7-0FD398400B6D' --Commercial Auto

I added BEGIN TRANSACTION statement, but it still won't work.

BEGIN TRANSACTION
update tblQuotes
set QuoteStatusID = 11, --Not Taken Up
    QuoteStatusReasonID = 9 --"Not Competitive"
where CAST(EffectiveDate as DATE) < CAST('2017-11-27' as DATE)
 AND CompanyLocationGuid = '32828BB4-E1FA-489F-9764-75D8AF7A78F1' -- Plaza Insurance Company
and LineGUID = '623AA353-9DFE-4463-97D7-0FD398400B6D' --Commercial Auto
IF @@TRANCOUNT>0
COMMIT TRANSACTION

Body:
In my opinion this is a "flaw", if not a "bug" in SQL Server. When you COMMIT a transaction, TRANCOUNT is decremented by 1. When you ROLLBACK any transaction, all transactions in the calling stack are rolled back! This means that any calling procedure that tries to commit or rollback will have this error and you've lost the integrity of your calling stack.

I worked through this when building a mechanism do do unit testing on SQL Server. I get around it by always using named transactions as shown in the example below. You can obviously also check XACT_STATE. The point is simply that, rather than blindly committing and rolling back anonymous transactions, if you manage transactions by name or transaction id you have better control.

For unit testing, I write a stored procedure as a test that calls the procedure under test. The unit test is in either serializable or snapshot mode and ONLY includes a rollback statement. I call the procedure under test, validate the results, build test output (pass/fail, parameters, etc.) as XML output, then everything gets rolled back. This gets around the need to build "mock data". I can use the data on any environment as the transaction is always rolled back.

--
-- get @procedure from object_name(@@procid)
-------------------------------------------------
DECLARE @procedure        SYSNAME = N'a_procedure_name_is_a_synonym_so_can_be_longer_than_a_transaction_name'
        , @transaction_id BIGINT;
DECLARE @transaction_name NVARCHAR(32) = RIGHT(@procedure + N'_tx', 32);

--
BEGIN TRANSACTION @transaction_name;

BEGIN
    SELECT @transaction_id = [transaction_id]
    FROM   [sys].[dm_tran_active_transactions]
    WHERE  [name] = @transaction_name;

    SELECT *
    FROM   [sys].[dm_tran_active_transactions]
    WHERE  [name] = @transaction_name;

-- Perform work here
END;

IF EXISTS
   (SELECT *
    FROM   [sys].[dm_tran_active_transactions]
    WHERE  [name] = @transaction_name)
    ROLLBACK TRANSACTION @transaction_name;


问:
Python Split a phrase into words on space and symbols
I'm writing a program where I need to test whether a phrase such as "red car" is present in a variety of sentences: "I bought a new red car", "RED! CAR!", "red#$%^car".

I'm having trouble finding a way to separate out the words from the symbols in the last example.

My code so far is:

```<code>exclude = set(string.punctuation)

text = text.lower
text = ''.join(ch for ch in text if ch not in exclude)
text = text.split()

for word in phrase:
    found = False
    for e2 in text:
        if word == e2:
           found = True
           break
    if not found:
       return False
return True
</code>```

This causes the last example to be 'redcar' so the words aren't split.

All the questions I found on here were talking about delimiters not splitting out two words that are joined by a bunch of symbols.

Should I just use text.split for each individual symbol?

I was thinking of something like:

```<code>for ch in exclude:
    text = text.split(ch)
</code>```

but I was hoping there is a cleaner way to do it.

答:
You can iterate over the sentences and see if both red and car exist in the sentences:

```<code>sentences = ["I bought a new red car", "RED! CAR!", "red#$%^car"]
final_sentences = [sentence for sentence in sentences if "red" in sentence.lower() and "car" in sentence.lower()]
</code>```

Body:
I'm writing a program where I need to test whether a phrase such as "red car" is present in a variety of sentences: "I bought a new red car", "RED! CAR!", "red#$%^car".

I'm having trouble finding a way to separate out the words from the symbols in the last example.

My code so far is:

exclude = set(string.punctuation)

text = text.lower
text = ''.join(ch for ch in text if ch not in exclude)
text = text.split()

for word in phrase:
    found = False
    for e2 in text:
        if word == e2:
           found = True
           break
    if not found:
       return False
return True

This causes the last example to be 'redcar' so the words aren't split.

All the questions I found on here were talking about delimiters not splitting out two words that are joined by a bunch of symbols.

Should I just use text.split for each individual symbol?

I was thinking of something like:

for ch in exclude:
    text = text.split(ch)

but I was hoping there is a cleaner way to do it.

Body:
You can iterate over the sentences and see if both red and car exist in the sentences:

sentences = ["I bought a new red car", "RED! CAR!", "red#$%^car"]
final_sentences = [sentence for sentence in sentences if "red" in sentence.lower() and "car" in sentence.lower()]


问:
Can't resize UIView in IB
Probably something simple, but I can't figure why I cannot resize a UIView in a xib in Interface Builder.

I created a new view XIB in xcode and in the size inspector, the width and height are disabled and grayed out to 320 by 460. This is strange since I can change the size for the other two views (associated with the other two tab bar items).

I am not sure if this has anything to do with but I recently updated the sdk to 3.

Thanks!

答:
Funny I have a similar problem. I've removed all views from the xib file and re-added a view. Set the status bar to being "unspecified" so that the status bar is not accommodated for. The view, when added, get created with x=0, y=0, w=320 h=460 instead of (0,0,320,480) as I would have expected. After changing the height to 480 and connecting it to file's owner and changing the color to make it distinctive in relation to the background. I fount that there was a white band between the top of the screen and the view.
I augmented my code with:

```#define RECTLOG(rect)    (NSLog(@""  #rect @" x:%f y:%f w:%f h:%f", rect.origin.x, rect.origin.y, rect.size.width, rect.size.height ));
```

within viewDidLoad

```
- (void)viewDidLoad {
    [super viewDidLoad];
    RECTLOG(self.view.frame);
}
```

Turns out that the view is as it's loaded from IB is actually (0, 20, 320, 480)
As a work around I reset the view's frame with self.view.frame = CGRectMake(0, 0, 320, 480);

I'm using IB 3.2.5

I'd love to know of a little fix for this one.

OwnerDisplayName: Ayrad

ContentLicense: CC BY-SA 2.5

Title: Can't resize UIView in IB

Body:
Funny I have a similar problem. I've removed all views from the xib file and re-added a view. Set the status bar to being "unspecified" so that the status bar is not accommodated for. The view, when added, get created with x=0, y=0, w=320 h=460 instead of (0,0,320,480) as I would have expected. After changing the height to 480 and connecting it to file's owner and changing the color to make it distinctive in relation to the background. I fount that there was a white band between the top of the screen and the view.
I augmented my code with:

#define RECTLOG(rect)    (NSLog(@""  #rect @" x:%f y:%f w:%f h:%f", rect.origin.x, rect.origin.y, rect.size.width, rect.size.height ));

within viewDidLoad

- (void)viewDidLoad {
    [super viewDidLoad];
    RECTLOG(self.view.frame);
}

Turns out that the view is as it's loaded from IB is actually (0, 20, 320, 480)
As a work around I reset the view's frame with self.view.frame = CGRectMake(0, 0, 320, 480);

I'm using IB 3.2.5

I'd love to know of a little fix for this one.


问:
Coding Hangman in Python
I'm having trouble with this hangman coding.  When I run the code, it asks the question "Type in a letter a - z", but when I type in a letter, instead of it putting a letter, it just ask the same question from the beginning without letting me know if the letter is correct or not. </p>

```<code>import random

possibleAnswers = ["page","computer","cookie","phishing","motherboard","freeware","bus","unix","document","hypertext","node","digital","worm","macro","binary","podcast","paste","virus","toolbar","browser"]

random.shuffle(possibleAnswers)

answers = list(possibleAnswers[1])

display = []
display.extend(answers)

for i in range(len(display)):
    display[i] = "_"

print ' '.join(display)
print "\n\n\n\n"

count = 0

while count < len(answers):

    guess = raw_input("Type in a letter a - z: ")

    guess = guess.upper()

    for i in range(len(answers)):
        if answers[i] == guess:
            display[i] = guess
            count += 1

    print ' '.join(display)
    print "\n\n\n"
</code>```

答: It does tell you, after a fashion.  The problem is that your entire word list is lower-case, but you specifically change all of your input guesses to upper-case.  Those cannot match, so there's never a "correct" guess.  Change the word list to capitals, or change your conversion from upper to lower.

Title: Coding Hangman in Python

Body:
I'm having trouble with this hangman coding.  When I run the code, it asks the question "Type in a letter a - z", but when I type in a letter, instead of it putting a letter, it just ask the same question from the beginning without letting me know if the letter is correct or not.

import random

possibleAnswers = ["page","computer","cookie","phishing","motherboard","freeware","bus","unix","document","hypertext","node","digital","worm","macro","binary","podcast","paste","virus","toolbar","browser"]

random.shuffle(possibleAnswers)

answers = list(possibleAnswers[1])

display = []
display.extend(answers)

for i in range(len(display)):
    display[i] = "_"

print ' '.join(display)
print "\n\n\n\n"

count = 0

while count < len(answers):

    guess = raw_input("Type in a letter a - z: ")

    guess = guess.upper()

    for i in range(len(answers)):
        if answers[i] == guess:
            display[i] = guess
            count += 1

    print ' '.join(display)
    print "\n\n\n"


问:
How do I view the full content of a text or varchar(MAX) column in SQL Server 2008 Management Studio?
In this live SQL Server 2008 (build 10.0.1600) database, there's an Events table, which contains a text column named Details. (Yes, I realize this should actually be a varchar(MAX) column, but whoever set this database up did not do it that way.)

This column contains very large logs of exceptions and associated JSON data that I'm trying to access through SQL Server Management Studio, but whenever I copy the results from the grid to a text editor, it truncates it at 43679 characters.

I've read on various locations on the Internet that you can set your Maximum Characters Retrieved for XML Data in Tools > Options > Query Results > SQL Server > Results To Grid to Unlimited, and then perform a query such as this:

```<code>select Convert(xml, Details) from Events
where EventID = 13920
</code>```

(Note that the data is column is not XML at all. CONVERTing the column to XML is merely a workaround I found from Googling that someone else has used to get around the limit SSMS has from retrieving data from a text or varchar(MAX) column.)

However, after setting the option above, running the query, and clicking on the link in the result, I still get the following error:

Unable to show XML. The following error happened:
  Unexpected end of file has occurred. Line 5, position 220160.

One solution is to increase the number of characters retrieved from the server for XML data. To change this setting, on the Tools menu, click Options.

So, any idea on how to access this data? Would converting the column to varchar(MAX) fix my woes?

答:
Did you try this simple solution? Only 2 clicks away!

At the query window,

set query options to "Results to Grid", run your query

Right click on the results tab at the grid corner, save results as any files

You will get all the text you want to see in the file!!! I can see 130,556 characters for my result of a varchar(MAX) field

Body:
In this live SQL Server 2008 (build 10.0.1600) database, there's an Events table, which contains a text column named Details. (Yes, I realize this should actually be a varchar(MAX) column, but whoever set this database up did not do it that way.)

This column contains very large logs of exceptions and associated JSON data that I'm trying to access through SQL Server Management Studio, but whenever I copy the results from the grid to a text editor, it truncates it at 43679 characters.

I've read on various locations on the Internet that you can set your Maximum Characters Retrieved for XML Data in Tools > Options > Query Results > SQL Server > Results To Grid to Unlimited, and then perform a query such as this:

select Convert(xml, Details) from Events
where EventID = 13920

(Note that the data is column is not XML at all. CONVERTing the column to XML is merely a workaround I found from Googling that someone else has used to get around the limit SSMS has from retrieving data from a text or varchar(MAX) column.)

However, after setting the option above, running the query, and clicking on the link in the result, I still get the following error:

Unable to show XML. The following error happened:
  Unexpected end of file has occurred. Line 5, position 220160.

One solution is to increase the number of characters retrieved from the server for XML data. To change this setting, on the Tools menu, click Options.

So, any idea on how to access this data? Would converting the column to varchar(MAX) fix my woes?


问:
c++: search ignoring accented characters
So... I have a STL vector that I need to search/filter with a user-provided string. (Just mentioning this in case there's a specific/better way to do it in this particular use case)

Currently (this code is old) it's being done by just iterating through it and regex matching each element to see if it matches.

Our problem, however, stems from accented characters. Our desired behavior is for the search to match strings without regard to diacritics (i.e. "telefono" also matches "teléfono" and vice-versa)

Is there a decent way to do this, ideally without having to resort to libraries other than boost?

答:
Short answer:  You "normalize" both strings and then do the search/comparison.

Note that Unicode represents many accented characters in more than one way.  There is a single codepoint (U+00E9 LATIN SMALL E WITH ACUTE ACCENT) to represent the character with the accent, but it can also be represented by a combination of codepoints (U+0065 LATIN SMALL LETTER E and U+0301 COMBINING ACUTE ACCENT).  The general way to deal with this is to choose one Normal Form C (for pre-composed characters) or D (for de-composed characters).  Normalizing can be more complex than it seems.  Once both strings are in the same normal form, you can compare them directly.

If you want to ignore the diacritics altogether, you can make up your own normalization scheme.  For example, you can decompose any pre-composed characters and then drop all the combining codepoints.  The will allow the base character to match an accented character regardless of how the accented character was originally represented.

There are also "kompatibility" normal forms in Unicode (KC and KD) which substitute most special characters with the most common similar base character.  In the case of diacritics, I think this'll do the same thing.  So if you have a Unicode library, you might be able to use it to do all the hard work of normalizing.

In many cases, the database is already in some normal form, so you just have to normalize the search string.

If all that is too complicated, another approach would be to build a regex that will match any representation.  For example, if your search key is telefono, you'd turn that into a regex like t(e|\u00E9|e\u0301)l(e|\u00E9|e\u0301)f(o|\u00F3|o\u0301)n(o|\u00F3|o\u0301).  Those regexes can be bulky pretty fast, depending on how flexible you want the matches to be.


问:
What is this Rspec syntax exactly asking for?
TL;DR I am going to a bootcamp next year and one their assessments to get in is learning ruby. I have a background in JS and am very new to ruby. I have this assessment in which case I am not familiar with what the test wants me to do. Below is the test case(Rspec) and right below that is my answer.

```<code>describe "some silly block functions" do
  describe "reverser" do
    it "reverses the string returned by the default block" do
      result = reverser do
        "hello"
      end

  expect(result).to eq("olleh")
end

it "reverses each word in the string returned by the default block" do
  result = reverser do
    "hello dolly"
  end

  expect(result).to eq("olleh yllod")
  end
end
</code>```

This is my answer code:

```<code>def reverser sentence
  words = sentence.split(" ")
  result = []

  words.length.times do |i|
    result.push(yield(words[i]))
  end

  result.join(" ")
end

reverser("hello dolly") {|n| n.reverse} #=> 'olleh yllod'
</code>```

As I mentioned above I am new to ruby and the idea of yielding is like a callback function for JS. I am having a hard time figuring out what expected code the test case wants me to write. It says that 'it reverses each word in the string returned by the default block' from the statement I just created a block outside of the function where the words are being reversed. I appreciate the help and guidance from whoever can give advice.

答:
yield means "execute the code inside the block and give me the result". Your reverser method can be simply written like this:

```<code>def reverser
  yield.split.map(&:reverse).join(' ') if block_given?
end

result = reverser do
  'hello world'
end

puts result
# => olleh dlrow
</code>```

Ruby automatically returns the last thing called as the return value, so the return value of the block given to reverser is hello world which is what will be assigned to yield.

You could check the documentation for block_given? here. Take a look at this answer for deeper explanation of blocks

Body:
TL;DR I am going to a bootcamp next year and one their assessments to get in is learning ruby. I have a background in JS and am very new to ruby. I have this assessment in which case I am not familiar with what the test wants me to do. Below is the test case(Rspec) and right below that is my answer.

describe "some silly block functions" do
  describe "reverser" do
    it "reverses the string returned by the default block" do
      result = reverser do
        "hello"
      end

  expect(result).to eq("olleh")
end

it "reverses each word in the string returned by the default block" do
  result = reverser do
    "hello dolly"
  end

  expect(result).to eq("olleh yllod")
  end
end

This is my answer code:

def reverser sentence
  words = sentence.split(" ")
  result = []

  words.length.times do |i|
    result.push(yield(words[i]))
  end

  result.join(" ")
end

reverser("hello dolly") {|n| n.reverse} #=> 'olleh yllod'

As I mentioned above I am new to ruby and the idea of yielding is like a callback function for JS. I am having a hard time figuring out what expected code the test case wants me to write. It says that 'it reverses each word in the string returned by the default block' from the statement I just created a block outside of the function where the words are being reversed. I appreciate the help and guidance from whoever can give advice.

Body:
yield means "execute the code inside the block and give me the result". Your reverser method can be simply written like this:

def reverser
  yield.split.map(&:reverse).join(' ') if block_given?
end

result = reverser do
  'hello world'
end

puts result
# => olleh dlrow

Ruby automatically returns the last thing called as the return value, so the return value of the block given to reverser is hello world which is what will be assigned to yield.

You could check the documentation for block_given? here. Take a look at this answer for deeper explanation of blocks


问:
How to change Android application name in Xamarin.Forms?
I am working with Xamarin.Forms in Visual Studio For Mac and I have created a very basic Xamarin.Forms application.

I have checked Android and iOS targets. I got 3 projects:

A common project

An iOS specific project

And a Droid specific project.

The Android specific application has a ".Droid" suffix in application name.

So I decided to right click on droid project, and to remove this suffix in "Assembly name" field.

I got an exception where I run the app (at startup). If I change Assembly name again to put the droid suffix, it does not work anymore.

You can try this with a blank project with the latest version of Xamarin.Forms.

I do not understand why?

答:
Other answer works fine.
But I am adding more details .

Application name is picked from AndroidManifest.xml file i.e. <application android:label=@string/app_name , which in turn refers to values>strings.xml file . Do not hard code app name here. Its good practice separate all strings used in strings.xml file.

strings.xml

```<code><resources>
  <string name="app_name">App Name</string>
</resources>
</code>```

Label property overrides this and sets the app title , apk name to Label value set inside MainActivity.

Its preferable to delete Label value from MainActivity.cs's assembly directive [Activity (as it overrides this manifest value at debug time) change the value in strings.xml so that its global and consistent.

Body:
Other answer works fine.
But I am adding more details .

Application name is picked from AndroidManifest.xml file i.e. <application android:label=@string/app_name , which in turn refers to values>strings.xml file . Do not hard code app name here. Its good practice separate all strings used in strings.xml file.

strings.xml

<resources>
  <string name="app_name">App Name</string>
</resources>

Label property overrides this and sets the app title , apk name to Label value set inside MainActivity.

Its preferable to delete Label value from MainActivity.cs's assembly directive [Activity (as it overrides this manifest value at debug time) change the value in strings.xml so that its global and consistent.


问:
C - Segmentation fault when using strlen?

I'm getting a segmentation fault with using strlen.

My function:

```<code>void myFunction()
{
    int counter = 0;
    char * userInput;
    bool validInput = true;

    while (1)
    {
        validInput = true;
        printf("\nEnter a word: ");
        scanf("%s", userInput);

        for(counter = 0; counter < strlen(userInput); counter++)
        {
            if (islower(userInput[counter]) == 0)
            {
                validInput = false;
                break;
            }
            if (isalpha(userInput[counter]) == 0)
            {
                validInput = false;
                break;
            }
        }

        if (!validInput)
        {
            printf("Please enter a wordcontaining only lower-case letters.\n");
            continue;
        }

        // Do something
        break;
    }
}
</code>```

Is there something wrong with my scanf line? I've never had this sort of issue before with using strlen... so I assume maybe I'm not reading the user's input correctly into 'userInput'.

答:
Use char userInput[128]; instead.

scanf expects a pointer to valid memory to put the contents of the users input in to.

Body:
I'm getting a segmentation fault with using strlen.

My function:

void myFunction()
{
    int counter = 0;
    char * userInput;
    bool validInput = true;

    while (1)
    {
        validInput = true;
        printf("\nEnter a word: ");
        scanf("%s", userInput);

        for(counter = 0; counter < strlen(userInput); counter++)
        {
            if (islower(userInput[counter]) == 0)
            {
                validInput = false;
                break;
            }
            if (isalpha(userInput[counter]) == 0)
            {
                validInput = false;
                break;
            }
        }

        if (!validInput)
        {
            printf("Please enter a wordcontaining only lower-case letters.\n");
            continue;
        }

        // Do something
        break;
    }
}

Is there something wrong with my scanf line? I've never had this sort of issue before with using strlen... so I assume maybe I'm not reading the user's input correctly into 'userInput'.


问:
SQLAlchemy Object already attached to session
I'm trying to get a server for an app working, but I'm getting an error upon login:

```<code>[!] Object '<User at 0x7f12bc185a90>' is already attached to session '2' (this is '3')
</code>```

It seems the session I'm adding is already on the database. This is the snippet of code that is causing the problem:

```<code>@app.route('/login', methods=['POST'])
def login():
    u = User.query.filter(User.username == request.form["username"]).first()
    if not u or u.password != request.form["password"]:
        return error("E1")

    s = Session.get_by_user(u)
    if s is not None:
         db_session.delete(s)
         db_session.commit()

     print db_session.execute("SELECT * FROM sessions").fetchall()

     s = Session(u)
     db_session.add(s)
     db_session.commit()

     return jsonify(s.values)
</code>```

As you can see, I'm printing the content from the sessions table before trying to add anything, and it is empty! ([])

What else could be causing this?

Here is the 'Session' implementation:

```<code>class Session(Base):
__tablename__ = "sessions"
id = Column(Integer, primary_key=True)
user_id = Column(Integer, ForeignKey('users.id'), unique=True)
user = relationship(User)
key = Column(String(50), unique=True)
created = Column(DateTime)

def __init__(self, user=None):
    self.user = user
    self.key = base64.encodestring(os.urandom(24)).strip()
    self.created = datetime.now()

def __repr__(self):
    return '<Session %r>' % (self.key)

@property
def values(self):
    return {"username" : self.user.username,
            "key" : self.key,
            "created" : str(self.created),
            }
@classmethod
def get_by_key(cls, key):
    s = cls.query.filter(cls.key == key).first()
    #print datetime.now() - s.created
    if s and datetime.now() - s.created > settings.SESSION_LIFETIME:
        s = None
    return s

@classmethod
def get_by_user(cls, user):
    s = cls.query.filter(cls.user == user).first()
    if s and datetime.now() - s.created > settings.SESSION_LIFETIME:
        s.query.delete()
        db_session.commit()
        s = None
    return s
</code>```

答:
As @marcinkuzminski mentioned, you can't add an object that is already attached to another session. Just pulling in the original session from the object with object_session() is risky, though, if you aren't sure that session originated in the same thread context you're currently operating in. A thread-safe method is to use merge():

```<code>    local_object = db_session.merge(original_object)
    db_session.add(local_object)
    db_session.commit()
</code>```

Body:
I'm trying to get a server for an app working, but I'm getting an error upon login:

[!] Object '<User at 0x7f12bc185a90>' is already attached to session '2' (this is '3')

It seems the session I'm adding is already on the database. This is the snippet of code that is causing the problem:

@app.route('/login', methods=['POST'])
def login():
    u = User.query.filter(User.username == request.form["username"]).first()
    if not u or u.password != request.form["password"]:
        return error("E1")

    s = Session.get_by_user(u)
    if s is not None:
         db_session.delete(s)
         db_session.commit()

     print db_session.execute("SELECT * FROM sessions").fetchall()

     s = Session(u)
     db_session.add(s)
     db_session.commit()

     return jsonify(s.values)

As you can see, I'm printing the content from the sessions table before trying to add anything, and it is empty! ([])

What else could be causing this?

Here is the 'Session' implementation:

class Session(Base):
__tablename__ = "sessions"
id = Column(Integer, primary_key=True)
user_id = Column(Integer, ForeignKey('users.id'), unique=True)
user = relationship(User)
key = Column(String(50), unique=True)
created = Column(DateTime)

def __init__(self, user=None):
    self.user = user
    self.key = base64.encodestring(os.urandom(24)).strip()
    self.created = datetime.now()

def __repr__(self):
    return '<Session %r>' % (self.key)

@property
def values(self):
    return {"username" : self.user.username,
            "key" : self.key,
            "created" : str(self.created),
            }
@classmethod
def get_by_key(cls, key):
    s = cls.query.filter(cls.key == key).first()
    #print datetime.now() - s.created
    if s and datetime.now() - s.created > settings.SESSION_LIFETIME:
        s = None
    return s

@classmethod
def get_by_user(cls, user):
    s = cls.query.filter(cls.user == user).first()
    if s and datetime.now() - s.created > settings.SESSION_LIFETIME:
        s.query.delete()
        db_session.commit()
        s = None
    return s

Body:
As @marcinkuzminski mentioned, you can't add an object that is already attached to another session. Just pulling in the original session from the object with object_session() is risky, though, if you aren't sure that session originated in the same thread context you're currently operating in. A thread-safe method is to use merge():

    local_object = db_session.merge(original_object)
    db_session.add(local_object)
    db_session.commit()


问:
How to split filename from file extension in Swift?
Given the name of a file in the bundle, I want load the file into my Swift app. So I need to use this method:

```<code>let soundURL = NSBundle.mainBundle().URLForResource(fname, withExtension: ext)
</code>```

For whatever reason, the method needs the filename separated from the file extension. Fine, it's easy enough to separate the two in most languages. But so far I'm not finding it to be so in Swift.

So here is what I have:

```<code>var rt: String.Index = fileName.rangeOfString(".", options:NSStringCompareOptions.BackwardsSearch)
var fname: String = fileName .substringToIndex(rt)
var ext = fileName.substringFromIndex(rt)
</code>```

If I don't include the typing on the first line, I get errors on the two subsequent lines. With it, I'm getting an error on the first line:

```<code>Cannot convert the expression's type '(UnicodeScalarLiteralConvertible, options: NSStringCompareOptions)' to type 'UnicodeScalarLiteralConvertible'
</code>```

How can I split the filename from the extension? Is there some elegant way to do this?

I was all excited about Swift because it seemed like a much more elegant language than Objective C. But now I'm finding that it has its own cumbersomeness.

Second attempt: I decided to make my own string-search method:

```<code>func rfind(haystack: String, needle: Character) -> Int {
    var a = Array(haystack)

    for var i = a.count - 1; i >= 0; i-- {
        println(a[i])
        if a[i] == needle {
            println(i)
            return i;
        }
    }
    return -1
}
</code>```

But now I get an error on the line var rt: String.Index = rfind(fileName, needle: "."):

```<code>'Int' is not convertible to 'String.Index'
</code>```

Without the cast, I get an error on the two subsequent lines.

Can anyone help me to split this filename and extension?

答:
Try this for a simple Swift 4 solution</p>

```<code>extension String {
    func stripExtension(_ extensionSeperator: Character = ".") -> String {
        let selfReversed = self.reversed()
        guard let extensionPosition = selfReversed.index(of: extensionSeperator) else {  return self  }
        return String(self[..<self.index(before: (extensionPosition.base.samePosition(in: self)!))])
    }
}

print("hello.there.world".stripExtension())
// prints "hello.there"
</code>```

Body:
Given the name of a file in the bundle, I want load the file into my Swift app. So I need to use this method:

let soundURL = NSBundle.mainBundle().URLForResource(fname, withExtension: ext)

For whatever reason, the method needs the filename separated from the file extension. Fine, it's easy enough to separate the two in most languages. But so far I'm not finding it to be so in Swift.

So here is what I have:

var rt: String.Index = fileName.rangeOfString(".", options:NSStringCompareOptions.BackwardsSearch)
var fname: String = fileName .substringToIndex(rt)
var ext = fileName.substringFromIndex(rt)

If I don't include the typing on the first line, I get errors on the two subsequent lines. With it, I'm getting an error on the first line:

Cannot convert the expression's type '(UnicodeScalarLiteralConvertible, options: NSStringCompareOptions)' to type 'UnicodeScalarLiteralConvertible'

How can I split the filename from the extension? Is there some elegant way to do this?

I was all excited about Swift because it seemed like a much more elegant language than Objective C. But now I'm finding that it has its own cumbersomeness.

Second attempt: I decided to make my own string-search method:

func rfind(haystack: String, needle: Character) -> Int {
    var a = Array(haystack)

    for var i = a.count - 1; i >= 0; i-- {
        println(a[i])
        if a[i] == needle {
            println(i)
            return i;
        }
    }
    return -1
}

But now I get an error on the line var rt: String.Index = rfind(fileName, needle: "."):

'Int' is not convertible to 'String.Index'

Without the cast, I get an error on the two subsequent lines.

Can anyone help me to split this filename and extension?

Body:
Try this for a simple Swift 4 solution

extension String {
    func stripExtension(_ extensionSeperator: Character = ".") -> String {
        let selfReversed = self.reversed()
        guard let extensionPosition = selfReversed.index(of: extensionSeperator) else {  return self  }
        return String(self[..<self.index(before: (extensionPosition.base.samePosition(in: self)!))])
    }
}

print("hello.there.world".stripExtension())
// prints "hello.there"


问:
Finding whats in one table that is not in another table
I have following two tables:

```<code>CREATE TABLE TEMP1(ID INT)
CREATE TABLE TEMP2(ID INT)

INSERT INTO TEMP1 SELECT 1
INSERT INTO TEMP1 SELECT 2
INSERT INTO TEMP1 SELECT 3
INSERT INTO TEMP1 SELECT 4

INSERT INTO TEMP2 SELECT 1
INSERT INTO TEMP2 SELECT 2
INSERT INTO TEMP2 SELECT 3
INSERT INTO TEMP2 SELECT 4
INSERT INTO TEMP2 SELECT 5

SELECT * FROM TEMP1
SELECT * FROM TEMP2
</code>```

I am trying to find the records which are in TEMP2, but not in TEMP1 i.e. 5.
If I run the following query, I get the proper result:

```<code>  SELECT DISTINCT [ID2] FROM (
   SELECT DISTINCT
   C1.[ID] AS [ID1]
   ,C2.[ID] AS [ID2]
   FROM TEMP1 C1
   FULL JOIN TEMP2 C2 ON C1.[ID]=C2.[ID]
   )A
   WHERE [ID1] IS NULL
   ORDER BY 1
</code>```

But when I run following query, I don't return anything:

```<code>   SELECT DISTINCT T2.[ID] FROM TEMP2 T2
   WHERE T2.[ID] NOT IN (SELECT DISTINCT T1.[ID] FROM TEMP1 T1 )
   ORDER BY 1
</code>```

Any idea whats wrong?

答:
You can use a left join and test for null:</p>

```<code>SELECT DISTINCT T2.ID
   FROM TEMP2 T2
      LEFT JOIN TEMP1 T1 USING(ID)
   WHERE T1.ID IS NULL;
</code>```

Body:
I have following two tables:

CREATE TABLE TEMP1(ID INT)
CREATE TABLE TEMP2(ID INT)

INSERT INTO TEMP1 SELECT 1
INSERT INTO TEMP1 SELECT 2
INSERT INTO TEMP1 SELECT 3
INSERT INTO TEMP1 SELECT 4

INSERT INTO TEMP2 SELECT 1
INSERT INTO TEMP2 SELECT 2
INSERT INTO TEMP2 SELECT 3
INSERT INTO TEMP2 SELECT 4
INSERT INTO TEMP2 SELECT 5

SELECT * FROM TEMP1
SELECT * FROM TEMP2

I am trying to find the records which are in TEMP2, but not in TEMP1 i.e. 5.
If I run the following query, I get the proper result:

  SELECT DISTINCT [ID2] FROM (
   SELECT DISTINCT
   C1.[ID] AS [ID1]
   ,C2.[ID] AS [ID2]
   FROM TEMP1 C1
   FULL JOIN TEMP2 C2 ON C1.[ID]=C2.[ID]
   )A
   WHERE [ID1] IS NULL
   ORDER BY 1

But when I run following query, I don't return anything:

   SELECT DISTINCT T2.[ID] FROM TEMP2 T2
   WHERE T2.[ID] NOT IN (SELECT DISTINCT T1.[ID] FROM TEMP1 T1 )
   ORDER BY 1

Any idea whats wrong?

Body:
You can use a left join and test for null:

SELECT DISTINCT T2.ID
   FROM TEMP2 T2
      LEFT JOIN TEMP1 T1 USING(ID)
   WHERE T1.ID IS NULL;


问:
How to get the return value of INSTALLOPTIONS_DISPLAY_RETURN?
I'm try to get if the back bottom is clicked and avoid displaying the error message when one of input is not filled in.

Rigth now the $R9 variable is not filed is as I expect it.

```<code>Function SetCustom

  ;SectionGetFlags ${SEC04} $R0
  SectionGetFlags ${SEC05} $R5
  SectionGetFlags ${SEC06} $R6
  SectionGetFlags ${SEC07} $R7
  IntOp $R0 $R0 & ${SF_SELECTED}
  IntOp $R5 $R5 & ${SF_SELECTED}
  IntOp $R6 $R6 & ${SF_SELECTED}
  IntOp $R7 $R7 & ${SF_SELECTED}
  IntCmp $R0 ${SF_SELECTED} show
  IntCmp $R5 ${SF_SELECTED} show
  IntCmp $R6 ${SF_SELECTED} show
  IntCmp $R7 ${SF_SELECTED} show

  Abort

  show:
    Input:
    !insertmacro MUI_HEADER_TEXT "Customization" "Please input the Info1 and Info2 of the Customization user."
    !insertmacro MUI_INSTALLOPTIONS_DISPLAY "File.ini"
    !insertmacro INSTALLOPTIONS_READ $R1 "File.ini" "Field 2" "State"
    !insertmacro INSTALLOPTIONS_READ $R2 "File.ini" "Field 3" "State"
    ;!insertmacro INSTALLOPTIONS_SHOW_RETURN
    !insertmacro INSTALLOPTIONS_DISPLAY_RETURN $R9

    MessageBox MB_OK "$R9"
    ${If} "$R9" == "back"
        Abort
     ${Else}
        StrCmp $R1 "" 0 +3
        MessageBox MB_ICONEXCLAMATION|MB_OK "Please enter a Info1."
        Goto Input

        StrCmp $R2 "" 0 +3
        MessageBox MB_ICONEXCLAMATION|MB_OK "Please enter a Info2"
        Goto Input
    ${EndIf}
FunctionEnd
</code>```

答:
The documentation tells you to Pop:

If you need the return value, use the INSTALLOPTIONS_DISPLAY_RETURN or INSTALLOPTIONS_SHOW_RETURN macro. The return value will be added to the stack, so you can use the Pop command to get it.

```<code>!insertmacro INSTALLOPTIONS_DISPLAY_RETURN "File.ini"
Pop $5
${If} $5 == "back"
  ...
${EndIf}
</code>```

Body:
I'm try to get if the back bottom is clicked and avoid displaying the error message when one of input is not filled in.

Rigth now the $R9 variable is not filed is as I expect it.

Function SetCustom

  ;SectionGetFlags ${SEC04} $R0
  SectionGetFlags ${SEC05} $R5
  SectionGetFlags ${SEC06} $R6
  SectionGetFlags ${SEC07} $R7
  IntOp $R0 $R0 & ${SF_SELECTED}
  IntOp $R5 $R5 & ${SF_SELECTED}
  IntOp $R6 $R6 & ${SF_SELECTED}
  IntOp $R7 $R7 & ${SF_SELECTED}
  IntCmp $R0 ${SF_SELECTED} show
  IntCmp $R5 ${SF_SELECTED} show
  IntCmp $R6 ${SF_SELECTED} show
  IntCmp $R7 ${SF_SELECTED} show

  Abort

  show:
    Input:
    !insertmacro MUI_HEADER_TEXT "Customization" "Please input the Info1 and Info2 of the Customization user."
    !insertmacro MUI_INSTALLOPTIONS_DISPLAY "File.ini"
    !insertmacro INSTALLOPTIONS_READ $R1 "File.ini" "Field 2" "State"
    !insertmacro INSTALLOPTIONS_READ $R2 "File.ini" "Field 3" "State"
    ;!insertmacro INSTALLOPTIONS_SHOW_RETURN
    !insertmacro INSTALLOPTIONS_DISPLAY_RETURN $R9

    MessageBox MB_OK "$R9"
    ${If} "$R9" == "back"
        Abort
     ${Else}
        StrCmp $R1 "" 0 +3
        MessageBox MB_ICONEXCLAMATION|MB_OK "Please enter a Info1."
        Goto Input

        StrCmp $R2 "" 0 +3
        MessageBox MB_ICONEXCLAMATION|MB_OK "Please enter a Info2"
        Goto Input
    ${EndIf}
FunctionEnd

Body:
The documentation tells you to Pop:

If you need the return value, use the INSTALLOPTIONS_DISPLAY_RETURN or INSTALLOPTIONS_SHOW_RETURN macro. The return value will be added to the stack, so you can use the Pop command to get it.

!insertmacro INSTALLOPTIONS_DISPLAY_RETURN "File.ini"
Pop $5
${If} $5 == "back"
  ...
${EndIf}


问:
What is the equivalent of the htdocs folder in a JBoss AS instance
Static files can be hosted in a Apache HTTP server under the htdocs folder, what would be its equivalent in a JBoss AS instance.</p>

答:
Technically, there's nothing to stop you putting stuff in deploy\jboss-web.deployer\ROOT.war, and it'll be served from the root, but you're strongly discouraged from doing so.  You should really package your content into a WAR and deploy that.

Remember, JBossAS is a JavaEE application server first, and a web server second.


问:
Angular bug with select component
I'm working with Angular 1.6.6 and I have found a bug related to the select component.

I have the following component:

```<code>            <select ng-model="searchCriterion" ng-change="change()">
                <option value="title">Title</option>
                <option value="description">Description</option>
                <option value="price">Price</option>
                <option value="email">Email</option>
            </select>
</code>```

And the change method is showing on the console the value selected. The first time that I select an option it works well, but the second one it return the value selected + 1:

For instance, if I select description, searchCriterion will be price.

The change method is as simple as follows:

```<code>    $scope.change = function () {
        console.log($scope.searchCriterion)
    }
</code>```

If I use the value in other method, for instance a method that is triggered from a ng-click in a button, it happens the same

I have found on the internet some related info, but I don't get with how to fix the error

答:
The code you have provided works properly.

See this plunker to convince yourself: https://embed.plnkr.co/IVg6KXVTPrBP3UhDxkbk/

Your problem shouldn't exist.

Title: Angular bug with select component

Body:
I'm working with Angular 1.6.6 and I have found a bug related to the select component.

I have the following component:

            <select ng-model="searchCriterion" ng-change="change()">
                <option value="title">Title</option>
                <option value="description">Description</option>
                <option value="price">Price</option>
                <option value="email">Email</option>
            </select>

And the change method is showing on the console the value selected. The first time that I select an option it works well, but the second one it return the value selected + 1:

For instance, if I select description, searchCriterion will be price.

The change method is as simple as follows:

    $scope.change = function () {
        console.log($scope.searchCriterion)
    }

If I use the value in other method, for instance a method that is triggered from a ng-click in a button, it happens the same

I have found on the internet some related info, but I don't get with how to fix the error


问:
In C ,we use %x.ys for string manipulation. What it will be in C++?
How can I replace printf() with cout?
My Code In C++:

```<code>    #include<iostream>
    #include<cstdio>
    using namespace std;
    int main ()
    {
        char st[15]="United Kingdom";
        printf("%5s\n",st);
        printf("%15.6s\n",st);
        printf("%-15.6s\n",st);
        printf("%.3s\n",st); // prints "Uni"
        return 0;
    }
</code>```

The Code Prints:

```<code>United Kingdom

       United

United

Uni
</code>```

How can I manipulate like this in C++?

答:
The std::setw() iomanip will set the field width for insertions, that is, even if the isinsertions shorter than the specified lenth it will get padded to that amount, std::setfill() sets the padding character.

For example:

```<code>std::cout << std::setw(20) << std::setfil('0') << "hey you!" << std::endl;
</code>```

would print "Hey you!000000000000\n" (possibly \r\n instead of just \n if you're using Windows). There is also std::left which would cause the padding to precede rather than follow the insert.

Body:
How can I replace printf() with cout?
My Code In C++:

    #include<iostream>
    #include<cstdio>
    using namespace std;
    int main ()
    {
        char st[15]="United Kingdom";
        printf("%5s\n",st);
        printf("%15.6s\n",st);
        printf("%-15.6s\n",st);
        printf("%.3s\n",st); // prints "Uni"
        return 0;
    }

The Code Prints:

United Kingdom

       United

United

Uni

How can I manipulate like this in C++?

Body:
The std::setw() iomanip will set the field width for insertions, that is, even if the isinsertions shorter than the specified lenth it will get padded to that amount, std::setfill() sets the padding character.

For example:

std::cout << std::setw(20) << std::setfil('0') << "hey you!" << std::endl;

would print "Hey you!000000000000\n" (possibly \r\n instead of just \n if you're using Windows). There is also std::left which would cause the padding to precede rather than follow the insert.


问:
Slot context not taken
Context not found...

Vue.component("custom-table", {
    name: 'CustomTable',
    template: "#custom-table",
    created: function() {
      console.log('Created', this.rows);
    },
    mounted: function() {
      console.log('Mounted', this.rows);
    },
    data: function() {
    },
    props: {
        rows: Array
    }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script type="text/x-template" id="custom-table">
    <table>
        <thead>
            <slot name="head"></slot>
        </thead>
        <tbody slot name="body">
        </tbody>
    </table
</script>

<custom-table :rows="myRows">
  <thead slot="head">
    <tr>
      <th>Name</th>
      <th>Age</th>
    </tr>
  </thead>
  <tbody v-for="it in myRows">
    <tr slot="body">
      <td>{{ it.name }}</td>
      <td>{{ it.ange }}</td>
    </tr>
  </tbody>
</custom-table></code>```

I received this error ..

Property or method "it" is not defined on the instance but referenced during render. Make sure to declare reactive data properties in the data option.
  (found in root instance)

And myRows is

```<code>[
  { name: 'Name1', age: 20 },
  { name: 'Name2', age: 30 }
]
</code>```

答:
You just can't use the thead and tbody elements outside table - in parsing process browser will 'fix' code as yours :) It is well known, documented caveat, btw. So, improve your code. I am using custom table this way:

Vue.component("custom-table", {
  name: 'CustomTable',
  template: "#custom-table",
  props: {
    cols: Array,
    rows: Array
  }
})

new Vue({
  el: '#app',
  data: {
    myRows: [
      {name: 'Name1', age: 20},
      {name: 'Name2', age: 30}
    ]
  }
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="app">
  <custom-table
    :cols="['Name', 'Age']"
    :rows="myRows"
  ></custom-table>
</div>

<script type="text/x-template" id="custom-table">
  <table>
    <thead>
      <tr>
        <th v-for="col in cols">{{ col }}</th>
      </tr>
    </thead>
    <tbody>
      <tr v-for="it in rows">
        <td>{{ it.name }}</td>
        <td>{{ it.age }}</td>
      </tr>
    </tbody>
  </table>
</script>

<script src="https://unpkg.com/vue"></script></code>```

Title: Slot context not taken

Body:
Context not found...

Vue.component("custom-table", {
    name: 'CustomTable',
    template: "#custom-table",
    created: function() {
      console.log('Created', this.rows);
    },
    mounted: function() {
      console.log('Mounted', this.rows);
    },
    data: function() {
    },
    props: {
        rows: Array
    }
});

<custom-table :rows="myRows">

      Name
      Age

      {{ it.name }}
      {{ it.ange }}

</custom-table>

I received this error ..

Property or method "it" is not defined on the instance but referenced during render. Make sure to declare reactive data properties in the data option.
  (found in root instance)

And myRows is

[
  { name: 'Name1', age: 20 },
  { name: 'Name2', age: 30 }
]

Body:
You just can't use the thead and tbody elements outside table - in parsing process browser will 'fix' code as yours :) It is well known, documented caveat, btw. So, improve your code. I am using custom table this way:

Vue.component("custom-table", {
  name: 'CustomTable',
  template: "#custom-table",
  props: {
    cols: Array,
    rows: Array
  }
})

new Vue({
  el: '#app',
  data: {
    myRows: [
      {name: 'Name1', age: 20},
      {name: 'Name2', age: 30}
    ]
  }
})

<div id="app">
  <custom-table
    :cols="['Name', 'Age']"
    :rows="myRows"
  ></custom-table>
</div>

<script type="text/x-template" id="custom-table">
  <table>
    <thead>
      <tr>
        <th v-for="col in cols">{{ col }}</th>
      </tr>
    </thead>
    <tbody>
      <tr v-for="it in rows">
        <td>{{ it.name }}</td>
        <td>{{ it.age }}</td>
      </tr>
    </tbody>
  </table>
</script>

<script src="https://unpkg.com/vue"></script>


问:
Do I have to query the database every second to see if any alarm should start?
I have a desktop application which has the "Alarm" feature. The way I'm thinking to implement is that when user selects the data and time for alarm it gets stored in the database and my application query the database every second and match the current date and time of the system with all date and time in the database and then notify if matches. I don't think querying the database every second is good. I can't think of any other way around. This application is also going to sync the alarm records across multiple devices so storing in database is a must I guess.
How do typical alarm application work in which we can set multiple alarms ?
-Thank You</p>

答: Try create server layer on top of database. Query from db alarm time, create class who send notifications to client apps when alarm time is done. Maybe try use Quartz library?</p>


问:
Rewrite url with 2 or more params
I asked a question like this before but since i still can't find an answer to this i'll ask it again :-s.

I'm using this very basic 'templating' script:

```<code>require_once 'core/init.php';

if(empty($_GET['page'])){
    header('Location: home');
    die();
}

$basePath = dirname(__FILE__) . '/';
$viewPath = $basePath . 'view/';

$view = scandir($viewPath);

foreach($view as $file)
{
    if (!is_dir($viewPath . $file))
    {
        $pages[] = substr($file, 0, strpos($file, '.'));

    }
}

if(in_array($_GET['page'], $pages)){
    include($viewPath . $_GET['page'] . '.php');
} else{
    include($basePath . '404.php');
}
</code>```

and i'm rewriting my url from /base/index.php?page=somepage to /base/somepage(somepage is a .php file in my template folder) using this htaccess file

```<code>RewriteEngine On

RewriteBase /base/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^?]*) index.php?page=$1 [L,QSA]
</code>```

With 1 parameter it works just fine but my problem is that i don't know how to rewrite a second param /base/profile?user=username (with no htaccess file this would have look like this /base/index.php?page=profile?user=username) and i want it to look like this /base/profile/username.

I hope that this question is understandable :-s

答:
Routing is a real issue and I can't be exhaustive in one comment, but I'll try to do my best. Please forgive my aproximative english and let me know if you don't understand. I still have a lot to learn so I'll try to explain through something I made, but it is probably fully improvable.

Today's PHP Standard Recommendation about routing and interpreting request should implement PSR7.

I personnaly use it through a FrontController Design Pattern in a MVC framework I'm building to understand these concepts. My folders are organized like this :

Public :

Where I launch my web server, where you can find JavaScript/CSS. There's an index.php which just contains

require_once('../index.php');

App :
Where there's the router and mostly all generic code

Src :
Where there's the specific code to the app. That means controllers and entities for now.

Vendor :
Composer dependencies such as GuzzleHTTP to have a class between the actual request and the code.

Here's the code in my root's index.php :

```<code><?php
require_once 'vendor/autoload.php';

use Namespace\FrontController;
use \GuzzleHttp\Psr7\ServerRequest;
use function Http\Response\send;

$front_ctrl = new FrontController(ServerRequest::fromGlobals());
send($front_ctrl->getResponse());
</code>```

The main point of it is that I interpret the request within an instance of a class implementing PSR7.

In my FrontController, my request travel through some methods (such as removing trailing slash) to finnaly be sent in a Router class to be handled.

The purpouse of my Router class is to check if the URI exist in the array where I stocked all my routes under this format in a json file :

```<code>{
    "/": [
      "AppController",
      "indexAction",
      ["GET", "POST"]
    ],...
}
</code>```

This is where I use regex to match variable inside the URI (/article/:id for example) too.

This Class can be resumed as "Does this URI exists in my app?".

At this point, I instantiate a new Route class with all the array as parameter. From here, I have to answer questions such as "Is it attached to a method in a controller ?", "Does the method in which it is asked is handled ?" ...

To summarize, at this point, I have an Instance of a Class that represents the Request, another one that represents all my routes. I confront them to get ONE Route which I'm gonna manipulate through an Instance of a Class Route.

If it passed all those tests, then I can instantiate the right Controller, where there will be the logical part specific of the app, requiring some action to get data, that I will send in my views to generate a HTML output which I will send back all the way back to my function send so the output is displayed when you ask for a specific URI.

The main point of this long answer is to show you something that is almost completely independent from the server. It's also useful if your app gets bigger and has to handle more specific rules for routing. It forces you to separates all the bundles of your app : A Controller is not a Model neither a Router...

Try to find some good tutorials to learn Oriented Object Programmation in PHP, which would avoid easy security issues and give you much more comfort when developping an app :)

Hope it was understandable and helpful

Title: Rewrite url with 2 or more params

Body:
I asked a question like this before but since i still can't find an answer to this i'll ask it again :-s.

I'm using this very basic 'templating' script:

require_once 'core/init.php';

if(empty($_GET['page'])){
    header('Location: home');
    die();
}

$basePath = dirname(__FILE__) . '/';
$viewPath = $basePath . 'view/';

$view = scandir($viewPath);

foreach($view as $file)
{
    if (!is_dir($viewPath . $file))
    {
        $pages[] = substr($file, 0, strpos($file, '.'));

    }
}

if(in_array($_GET['page'], $pages)){
    include($viewPath . $_GET['page'] . '.php');
} else{
    include($basePath . '404.php');
}

and i'm rewriting my url from /base/index.php?page=somepage to /base/somepage(somepage is a .php file in my template folder) using this htaccess file

RewriteEngine On

RewriteBase /base/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^?]*) index.php?page=$1 [L,QSA]

With 1 parameter it works just fine but my problem is that i don't know how to rewrite a second param /base/profile?user=username (with no htaccess file this would have look like this /base/index.php?page=profile?user=username) and i want it to look like this /base/profile/username.

I hope that this question is understandable :-s

Body:
Routing is a real issue and I can't be exhaustive in one comment, but I'll try to do my best. Please forgive my aproximative english and let me know if you don't understand. I still have a lot to learn so I'll try to explain through something I made, but it is probably fully improvable.

Today's PHP Standard Recommendation about routing and interpreting request should implement PSR7.

I personnaly use it through a FrontController Design Pattern in a MVC framework I'm building to understand these concepts. My folders are organized like this :

Public :

Where I launch my web server, where you can find JavaScript/CSS. There's an index.php which just contains

require_once('../index.php');

App :
Where there's the router and mostly all generic code

Src :
Where there's the specific code to the app. That means controllers and entities for now.

Vendor :
Composer dependencies such as GuzzleHTTP to have a class between the actual request and the code.

Here's the code in my root's index.php :

<?php
require_once 'vendor/autoload.php';

use Namespace\FrontController;
use \GuzzleHttp\Psr7\ServerRequest;
use function Http\Response\send;

$front_ctrl = new FrontController(ServerRequest::fromGlobals());
send($front_ctrl->getResponse());

The main point of it is that I interpret the request within an instance of a class implementing PSR7.

In my FrontController, my request travel through some methods (such as removing trailing slash) to finnaly be sent in a Router class to be handled.

The purpouse of my Router class is to check if the URI exist in the array where I stocked all my routes under this format in a json file :

{
    "/": [
      "AppController",
      "indexAction",
      ["GET", "POST"]
    ],...
}

This is where I use regex to match variable inside the URI (/article/:id for example) too.

This Class can be resumed as "Does this URI exists in my app?".

At this point, I instantiate a new Route class with all the array as parameter. From here, I have to answer questions such as "Is it attached to a method in a controller ?", "Does the method in which it is asked is handled ?" ...

To summarize, at this point, I have an Instance of a Class that represents the Request, another one that represents all my routes. I confront them to get ONE Route which I'm gonna manipulate through an Instance of a Class Route.

If it passed all those tests, then I can instantiate the right Controller, where there will be the logical part specific of the app, requiring some action to get data, that I will send in my views to generate a HTML output which I will send back all the way back to my function send so the output is displayed when you ask for a specific URI.

The main point of this long answer is to show you something that is almost completely independent from the server. It's also useful if your app gets bigger and has to handle more specific rules for routing. It forces you to separates all the bundles of your app : A Controller is not a Model neither a Router...

Try to find some good tutorials to learn Oriented Object Programmation in PHP, which would avoid easy security issues and give you much more comfort when developping an app :)

Hope it was understandable and helpful


问:
Too many values to unpack list of list
```<code>import random
import re

requestResponseList = [
[r'.*to Paris ?(.*)',
 ["We apologise, but all our services to Paris {0} have been cancelled!"],
 ["We are sorry, but all our flights on {0} to Paris are fully booked!"],
 ["There are no available flights {0} to Paris! Please accept our apologies."]
 ]
]

def analyze(statement):
 for pattern, responses in requestResponseList:
    match = re.match(pattern, statement.rstrip(".!?"))
    if match:
        response = random.choice(responses)
        if match.group(1):
            return response.format(*[(match.group(1))])
        return response.format(*[""])

def main():
statement = "What would be the first available flight to Paris next year?"
print(analyze(statement))

if __name__ == "__main__":
main()
</code>```

This returns a  too many values to unpack (expected 2) error. After googling solutions i replaced

```<code>for pattern, responses in requestResponseList :
</code>```

with this:

```<code>for pattern, responses in enumerate(requestResponseList):
</code>```

This still produces an error: TypeError: first argument must be string or compiled pattern.

The very odd thing is that this code (enumerate omitted) a week ago. Could this be a Python version issue?

答:
List is incorrect constructed - you have three sublists with single strings inside but it has to be one sublist with three strings

```<code>requestResponseList = [
  [r'.*to Paris ?(.*)',
    [
      "We apologise, but all our services to Paris {0} have been cancelled!",
      "We are sorry, but all our flights on {0} to Paris are fully booked!",
      "There are no available flights {0} to Paris! Please accept our apologies."
    ]
  ]
]
</code>```

And now it works for me.

I don't know why you use *[...] if it works without *[...]

```<code>        if match.group(1):
            return response.format( match.group(1) )
        return response.format( "" )
</code>```

Title: Too many values to unpack list of list

Body:
import random
import re

requestResponseList = [
[r'.*to Paris ?(.*)',
 ["We apologise, but all our services to Paris {0} have been cancelled!"],
 ["We are sorry, but all our flights on {0} to Paris are fully booked!"],
 ["There are no available flights {0} to Paris! Please accept our apologies."]
 ]
]

def analyze(statement):
 for pattern, responses in requestResponseList:
    match = re.match(pattern, statement.rstrip(".!?"))
    if match:
        response = random.choice(responses)
        if match.group(1):
            return response.format(*[(match.group(1))])
        return response.format(*[""])

def main():
statement = "What would be the first available flight to Paris next year?"
print(analyze(statement))

if __name__ == "__main__":
main()

This returns a  too many values to unpack (expected 2) error. After googling solutions i replaced

for pattern, responses in requestResponseList :

with this:

for pattern, responses in enumerate(requestResponseList):

This still produces an error: TypeError: first argument must be string or compiled pattern.

The very odd thing is that this code (enumerate omitted) a week ago. Could this be a Python version issue?

Body:
List is incorrect constructed - you have three sublists with single strings inside but it has to be one sublist with three strings

requestResponseList = [
  [r'.*to Paris ?(.*)',
    [
      "We apologise, but all our services to Paris {0} have been cancelled!",
      "We are sorry, but all our flights on {0} to Paris are fully booked!",
      "There are no available flights {0} to Paris! Please accept our apologies."
    ]
  ]
]

And now it works for me.

I don't know why you use *[...] if it works without *[...]

        if match.group(1):
            return response.format( match.group(1) )
        return response.format( "" )


问:
how to determine sizeof class with virtual functions?
this is kind of homework question. For the following code,

```<code>#include <iostream>
using namespace std;

class A
{
public:
    virtual void f(){}
};

class B
{
public:
    virtual void f2(){}
};

class C: public A, public B
{
public:
    virtual void f3(){}
};

class D: public C
{
public:
    virtual void f4(){}
};

int main()
{
    cout<<sizeof(D)<<endl;
}
</code>```

The output is: 8

Could anyone please explain how it is 8 bytes? If the vtable implementation is compiler dependent, what should I answer for this kind of question in interviews? What about virtual base classes?

EDIT: i am working on a 32-bit platform.

答:
This is of course implementation-dependent.  And it would make a terrible interview question.  A good C++ programmer can just trust sizeof to be right and let the compiler worry about those vtable things.

But what's going on here is that a typical vtable-based implementation needs two vtables in objects of class C or D.  Each base class needs its own vtable.  The new virtual methods added by C and D can be handled by extending the vtable format from one base class, but the vtables used by A and B can't be combined.

In pseudo-C-code, here's how a most derived object of type D looks on my implementation (g++ 4.4.5 Linux x86):

```<code>void* D_vtable_part1[] = { (void*) 0, &D_typeinfo, &A::f1, &C::f3, &D::f4 };
void* D_vtable_part2[] = { (void*) -4, &D_typeinfo, &B::f2 };

struct D {
  void** vtable_A;
  void** vtable_B;
};

D d = { D_vtable_part1 + 1, D_vtable_part2 + 1 };
</code>```

Body:
this is kind of homework question. For the following code,

#include <iostream>
using namespace std;

class A
{
public:
    virtual void f(){}
};

class B
{
public:
    virtual void f2(){}
};

class C: public A, public B
{
public:
    virtual void f3(){}
};

class D: public C
{
public:
    virtual void f4(){}
};

int main()
{
    cout<<sizeof(D)<<endl;
}

The output is: 8

Could anyone please explain how it is 8 bytes? If the vtable implementation is compiler dependent, what should I answer for this kind of question in interviews? What about virtual base classes?

EDIT: i am working on a 32-bit platform.

Body:
This is of course implementation-dependent.  And it would make a terrible interview question.  A good C++ programmer can just trust sizeof to be right and let the compiler worry about those vtable things.

But what's going on here is that a typical vtable-based implementation needs two vtables in objects of class C or D.  Each base class needs its own vtable.  The new virtual methods added by C and D can be handled by extending the vtable format from one base class, but the vtables used by A and B can't be combined.

In pseudo-C-code, here's how a most derived object of type D looks on my implementation (g++ 4.4.5 Linux x86):

void* D_vtable_part1[] = { (void*) 0, &D_typeinfo, &A::f1, &C::f3, &D::f4 };
void* D_vtable_part2[] = { (void*) -4, &D_typeinfo, &B::f2 };

struct D {
  void** vtable_A;
  void** vtable_B;
};

D d = { D_vtable_part1 + 1, D_vtable_part2 + 1 };


问:
spark-submit for a .scala file
I have been running some test spark scala code using probably a bad way of doing things with spark-shell:

```<code>spark-shell --conf spark.neo4j.bolt.password=Stuffffit --packages neo4j-contrib:neo4j-spark-connector:2.0.0-M2,graphframes:graphframes:0.2.0-spark2.0-s_2.11 -i neo4jsparkCluster.scala
</code>```

This would execute my code on spark and pop into the shell when done.

Now that I am trying to run this on a cluster, I think I need to use spark-submit, to which I thought would be:

```<code>spark-submit --conf spark.neo4j.bolt.password=Stuffffit --packages neo4j-contrib:neo4j-spark-connector:2.0.0-M2,graphframes:graphframes:0.2.0-spark2.0-s_2.11 -i neo4jsparkCluster.scala
</code>```

but it does not like the .scala file, somehow does it have to be compiled into a class?    the scala code is a simple scala file with several helper classes defined in it and no real main class so to speak.   I don't see int he help files but maybe I am missing it, can I just spark-submit a file or do I have to somehow give it the class?  Thus changing my scala code?

I did add this to my scala code too:

went from this

```<code>val conf = new SparkConf.setMaster("local").setAppName("neo4jspark")

val sc = new SparkContext(conf)
</code>```

To this:

```<code>val sc = new SparkContext(new SparkConf().setMaster("spark://192.20.0.71:7077")
</code>```

答:
You will want to package your scala application with sbt and include Spark as a dependency within your build.sbt file.

See the self contained applications section of the quickstart guide for full instructions https://spark.apache.org/docs/latest/quick-start.html

Title: spark-submit for a .scala file

Body:
I have been running some test spark scala code using probably a bad way of doing things with spark-shell:

spark-shell --conf spark.neo4j.bolt.password=Stuffffit --packages neo4j-contrib:neo4j-spark-connector:2.0.0-M2,graphframes:graphframes:0.2.0-spark2.0-s_2.11 -i neo4jsparkCluster.scala

This would execute my code on spark and pop into the shell when done.

Now that I am trying to run this on a cluster, I think I need to use spark-submit, to which I thought would be:

spark-submit --conf spark.neo4j.bolt.password=Stuffffit --packages neo4j-contrib:neo4j-spark-connector:2.0.0-M2,graphframes:graphframes:0.2.0-spark2.0-s_2.11 -i neo4jsparkCluster.scala

but it does not like the .scala file, somehow does it have to be compiled into a class?    the scala code is a simple scala file with several helper classes defined in it and no real main class so to speak.   I don't see int he help files but maybe I am missing it, can I just spark-submit a file or do I have to somehow give it the class?  Thus changing my scala code?

I did add this to my scala code too:

went from this

val conf = new SparkConf.setMaster("local").setAppName("neo4jspark")

val sc = new SparkContext(conf)

To this:

val sc = new SparkContext(new SparkConf().setMaster("spark://192.20.0.71:7077")


问:
TypeError: Cannot read property 'root' of undefined
I'm trying to put a BasicTable function from Material-Ui to my React.js file.
 Here is my code.

```<code> import React, { Component } from 'react';
 import { Route, Redirect, Switch, Link, HashRouter} from 'react-router-dom';
 import firebase, { auth, provider } from '../firebase.js';
 import '../App.css';

 // Material-ui theme
 import NavBar from '../profile_pages/navBar';

 //For Table Material-ui
 import classNames from 'classnames';
 import PropTypes from 'prop-types';
 import { withStyles } from 'material-ui/styles';
 import Table, { TableBody, TableCell, TableHead, TableRow } from 'material-ui/Table';
 import Paper from 'material-ui/Paper';

 const styles = theme => ({
  root: {
    width: '100%',
    marginTop: theme.spacing.unit * 3,
    overflowX: 'auto',
  },
  table: {
    minWidth: 700,
  },
});

let id = 0;
function createData(name, calories, fat, carbs, protein) {
  id += 1;
  return { id, name, calories, fat, carbs, protein };
}

const data = [
  createData('Frozen yoghurt', 159, 6.0, 24, 4.0),
  createData('Ice cream sandwich', 237, 9.0, 37, 4.3),
  createData('Eclair', 262, 16.0, 24, 6.0),
  createData('Cupcake', 305, 3.7, 67, 4.3),
  createData('Gingerbread', 356, 16.0, 49, 3.9),
];

function BasicTable(props) {
  const { classes } = props;

  return (
    <Paper className={classes.root}>
      <Table className={classes.table}>
        <TableHead>
          <TableRow>
            <TableCell>Dessert (100g serving)</TableCell>
            <TableCell numeric>Calories</TableCell>
            <TableCell numeric>Fat (g)</TableCell>
            <TableCell numeric>Carbs (g)</TableCell>
            <TableCell numeric>Protein (g)</TableCell>
          </TableRow>
        </TableHead>
        <TableBody>
          {data.map(n => {
            return (
              <TableRow key={n.id}>
                <TableCell>{n.name}</TableCell>
                <TableCell numeric>{n.calories}</TableCell>
                <TableCell numeric>{n.fat}</TableCell>
                <TableCell numeric>{n.carbs}</TableCell>
                <TableCell numeric>{n.protein}</TableCell>
              </TableRow>
            );
          })}
        </TableBody>
      </Table>
    </Paper>
  );
}

class Charity extends Component {
  constructor() {
    super()
    this.state = {
      open: false
    }
  }

  //For nav
  handleToggle() {
    this.setState({
      open: !this.state.open
    })
  }

  render() {
   return (
      <div>
        <NavBar
          onToggle={() => this.handleToggle()}
          open={this.state.open}
        />

        {<BasicTable/>}
      </div>
    );
  }
}

BasicTable.propTypes = {
  classes: PropTypes.object.isRequired,
};

export default Charity;
</code>```

Now I have some errors as following.

```<code> <BasicTable>

  42 |  const { classes } = props;
  43 |
  44 |  return (
> 45 |    <Paper className={classes.root}>
  46 |      <Table className={classes.table}>
  47 |        <TableHead>
  48 |          <TableRow>

<./src/index.js>
   8 | //make click events enable to use
   9 | injectTapEventPlugin();
  10 |
> 11 | ReactDOM.render(<Root/>, document.getElementById('root'));
  12 | registerServiceWorker();
  13 |
  14 |
</code>```

What I'm stacking on the action is about the way to call the BasicTable(props) function at the render of Charity class.

How should I resolved the error?

The BasicTable() function is brought from an example of Material-ui website (https://material-ui-next.com/demos/tables/).

Then I put the code to my one without any changes.

答:
You props does not contain classes

If you want to access classes that are in the styles constant, then you might want to do this styles(/*your theme name/*).root

const { classes } = props; doing this is assigning classes=undefined then when you are trying to access classes.root it it throwing the error.

Now, you can either change this

```<code><Paper className={classes.root}>
      <Table className={classes.table}>
</code>```

TO

```<code>// Because the theme argument is never used in the function
<Paper className={styles("").root}>
      <Table className={styles("").table}>
</code>```

OR change this line in Charity component

{<BasicTable />}

TO

{<BasicTable classes={styles("")}/>} given styles

Body:
I'm trying to put a BasicTable function from Material-Ui to my React.js file.
 Here is my code.

 import React, { Component } from 'react';
 import { Route, Redirect, Switch, Link, HashRouter} from 'react-router-dom';
 import firebase, { auth, provider } from '../firebase.js';
 import '../App.css';

 // Material-ui theme
 import NavBar from '../profile_pages/navBar';

 //For Table Material-ui
 import classNames from 'classnames';
 import PropTypes from 'prop-types';
 import { withStyles } from 'material-ui/styles';
 import Table, { TableBody, TableCell, TableHead, TableRow } from 'material-ui/Table';
 import Paper from 'material-ui/Paper';

 const styles = theme => ({
  root: {
    width: '100%',
    marginTop: theme.spacing.unit * 3,
    overflowX: 'auto',
  },
  table: {
    minWidth: 700,
  },
});

let id = 0;
function createData(name, calories, fat, carbs, protein) {
  id += 1;
  return { id, name, calories, fat, carbs, protein };
}

const data = [
  createData('Frozen yoghurt', 159, 6.0, 24, 4.0),
  createData('Ice cream sandwich', 237, 9.0, 37, 4.3),
  createData('Eclair', 262, 16.0, 24, 6.0),
  createData('Cupcake', 305, 3.7, 67, 4.3),
  createData('Gingerbread', 356, 16.0, 49, 3.9),
];

function BasicTable(props) {
  const { classes } = props;

  return (
    <Paper className={classes.root}>

        <TableHead>
          <TableRow>
            <TableCell>Dessert (100g serving)</TableCell>
            <TableCell numeric>Calories</TableCell>
            <TableCell numeric>Fat (g)</TableCell>
            <TableCell numeric>Carbs (g)</TableCell>
            <TableCell numeric>Protein (g)</TableCell>
          </TableRow>
        </TableHead>
        <TableBody>
          {data.map(n => {
            return (
              <TableRow key={n.id}>
                <TableCell>{n.name}</TableCell>
                <TableCell numeric>{n.calories}</TableCell>
                <TableCell numeric>{n.fat}</TableCell>
                <TableCell numeric>{n.carbs}</TableCell>
                <TableCell numeric>{n.protein}</TableCell>
              </TableRow>
            );
          })}
        </TableBody>

    </Paper>
  );
}

class Charity extends Component {
  constructor() {
    super()
    this.state = {
      open: false
    }
  }

  //For nav
  handleToggle() {
    this.setState({
      open: !this.state.open
    })
  }

  render() {
   return (

        <NavBar
          onToggle={() => this.handleToggle()}
          open={this.state.open}
        />

        {<BasicTable/>}

    );
  }
}

BasicTable.propTypes = {
  classes: PropTypes.object.isRequired,
};

export default Charity;

Now I have some errors as following.

 <BasicTable>

  42 |  const { classes } = props;
  43 |
  44 |  return (
> 45 |    <Paper className={classes.root}>
  46 |

  47 |        <TableHead>
  48 |          <TableRow>

<./src/index.js>
   8 | //make click events enable to use
   9 | injectTapEventPlugin();
  10 |
> 11 | ReactDOM.render(<Root/>, document.getElementById('root'));
  12 | registerServiceWorker();
  13 |
  14 |

What I'm stacking on the action is about the way to call the BasicTable(props) function at the render of Charity class.

How should I resolved the error?

The BasicTable() function is brought from an example of Material-ui website (https://material-ui-next.com/demos/tables/).

Then I put the code to my one without any changes.

Body:
You props does not contain classes

If you want to access classes that are in the styles constant, then you might want to do this styles(/*your theme name/*).root

const { classes } = props; doing this is assigning classes=undefined then when you are trying to access classes.root it it throwing the error.

Now, you can either change this

<Paper className={classes.root}>
      <Table className={classes.table}>

TO

// Because the theme argument is never used in the function
<Paper className={styles("").root}>
      <Table className={styles("").table}>

OR change this line in Charity component

{<BasicTable />}

TO

{<BasicTable classes={styles("")}/>} given styles


问:
Add Secondary Text to Responsive Image
I'm fairly new to coding. I would appreciate any help I can get on this.

Is there a way to add secondary text above the background image right under the main header that is also responsive?

I'd like the ability to style the text differently than the h2 header.

I've tried a few different ways of doing this, but none of them worked out. :-( The new text would just overlap in mobile mode instead of stacking under the header.

Appreciate the help if someone could take a look at this code to see what I'm missing.

.homepagetext:after {
content:"";
background: radial-gradient(ellipse at center,  rgba(0,0,0,0.1) 8%,rgba(50,50,50,0.1) 56%,rgba(161,161,161,0) 66%,rgba(255,255,255,0) 100%);
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#a6000000', endColorstr='#00ffffff',GradientType=1 ); /* old IE fallback */
  width: 200%;
  height: 400%;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  z-index: 2;
}

body {
  height: 100%;
  width: 100%;
  overflow:hidden;
  background-image: url(https://globalonline.blob.core.windows.net/globalonlinecourses/Bannerz_1205.png);
  background-repeat: no-repeat;
  background-position: center bottom;
  background-attachment: fixed;
  /* https://snap-photos.s3.amazonaws.com/img-thumbs/960w/SRU39R3XRV.jpg */
  background-size: cover; /* version standardisée */
}

h2 {
  font-family: 'karbon';
  font-weight: normal;
  font-size: 40px;
  color: white;
  padding: 25px;
  position: absolute;
  left: 35%;
  top: 15%;
  transform: translate(-50%, -50%);
  border: 0px solid white;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <h2 class="homepagetext">Introduction to <BR><em>GEORGRAPHIC INFORMATION SYSTEMS</em></h2>
</div>

  </code>```

答:
I believe a few things are throwing you off the trail.

Position absolute is great for putting text over images, but because your image is a background, you don't need it to style to get text to appear over the background image.

Remove:

```<code>position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
</code>```

.homepagetext:after {
content:"";
background: radial-gradient(ellipse at center,  rgba(0,0,0,0.1) 8%,rgba(50,50,50,0.1) 56%,rgba(161,161,161,0) 66%,rgba(255,255,255,0) 100%);
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#a6000000', endColorstr='#00ffffff',GradientType=1 ); /* old IE fallback */
  width: 200%;
  height: 400%;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  z-index: 2;
}

body {
  height: 100%;
  width: 100%;
  overflow:hidden;
  background-image: url(https://globalonline.blob.core.windows.net/globalonlinecourses/Bannerz_1205.png);
  background-repeat: no-repeat;
  background-position: center bottom;
  background-attachment: fixed;
  /* https://snap-photos.s3.amazonaws.com/img-thumbs/960w/SRU39R3XRV.jpg */
  background-size: cover; /* version standardisée */
}

h2 {
  font-family: 'karbon';
  font-weight: normal;
  font-size: 40px;
  color: white;
  padding: 25px 25px 0 25px;
  margin:0;
  position: static;
  border: 0px solid white;
}
.new-class{
  color:#bada55;
  padding:0 25px;
  margin:0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <h2 class="homepagetext">Introduction to <BR><em>GEORGRAPHIC INFORMATION SYSTEMS</em></h2>
  <p class="new-class">secondary text</p>
</div>

  </code>```

Title: Add Secondary Text to Responsive Image

Body:
I'm fairly new to coding. I would appreciate any help I can get on this.

Is there a way to add secondary text above the background image right under the main header that is also responsive?

I'd like the ability to style the text differently than the h2 header.

I've tried a few different ways of doing this, but none of them worked out. :-( The new text would just overlap in mobile mode instead of stacking under the header.

Appreciate the help if someone could take a look at this code to see what I'm missing.

.homepagetext:after {
content:"";
background: radial-gradient(ellipse at center,  rgba(0,0,0,0.1) 8%,rgba(50,50,50,0.1) 56%,rgba(161,161,161,0) 66%,rgba(255,255,255,0) 100%);
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#a6000000', endColorstr='#00ffffff',GradientType=1 ); /* old IE fallback */
  width: 200%;
  height: 400%;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  z-index: 2;
}

body {
  height: 100%;
  width: 100%;
  overflow:hidden;
  background-image: url(https://globalonline.blob.core.windows.net/globalonlinecourses/Bannerz_1205.png);
  background-repeat: no-repeat;
  background-position: center bottom;
  background-attachment: fixed;
  /* https://snap-photos.s3.amazonaws.com/img-thumbs/960w/SRU39R3XRV.jpg */
  background-size: cover; /* version standardisée */
}

h2 {
  font-family: 'karbon';
  font-weight: normal;
  font-size: 40px;
  color: white;
  padding: 25px;
  position: absolute;
  left: 35%;
  top: 15%;
  transform: translate(-50%, -50%);
  border: 0px solid white;
}

Introduction to
GEORGRAPHIC INFORMATION SYSTEMS

Body:
I believe a few things are throwing you off the trail.

Position absolute is great for putting text over images, but because your image is a background, you don't need it to style to get text to appear over the background image.

Remove:

position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);

.homepagetext:after {
content:"";
background: radial-gradient(ellipse at center,  rgba(0,0,0,0.1) 8%,rgba(50,50,50,0.1) 56%,rgba(161,161,161,0) 66%,rgba(255,255,255,0) 100%);
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#a6000000', endColorstr='#00ffffff',GradientType=1 ); /* old IE fallback */
  width: 200%;
  height: 400%;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  z-index: 2;
}

body {
  height: 100%;
  width: 100%;
  overflow:hidden;
  background-image: url(https://globalonline.blob.core.windows.net/globalonlinecourses/Bannerz_1205.png);
  background-repeat: no-repeat;
  background-position: center bottom;
  background-attachment: fixed;
  /* https://snap-photos.s3.amazonaws.com/img-thumbs/960w/SRU39R3XRV.jpg */
  background-size: cover; /* version standardisée */
}

h2 {
  font-family: 'karbon';
  font-weight: normal;
  font-size: 40px;
  color: white;
  padding: 25px 25px 0 25px;
  margin:0;
  position: static;
  border: 0px solid white;
}
.new-class{
  color:#bada55;
  padding:0 25px;
  margin:0;
}

<div>
  <h2 class="homepagetext">Introduction to <BR><em>GEORGRAPHIC INFORMATION SYSTEMS</em></h2>
  <p class="new-class">secondary text</p>
</div>


问:
Javascript: code with no animation with requestAnimationFrame?
I am learning Javacript and test the code from the book (below). It should animate an image but doesn't. I add print out using alert which shows that the function is executed only once. What goes wrong?

```<code><!doctype html>
<html>
<head>
  <title> My home page </title>
  <script>
var cat = document.querySelector("img");
var angle = 0, lastTime = null;
var count = 0;
function animate(time) {
  //alert(count);
  //++count;
  if (lastTime != null)
    angle += (time - lastTime) * 0.001;
  lastTime = time ;
  cat.style.top = (Math.sin(angle) * 20) + "px";
  cat.style.left = (Math.cos(angle) * 200) + "px";
  requestAnimationFrame(animate);
}
  </script>
</head>
<body>
  <p style ="text-align: center">
    <img src ="img/cat.jpg" style ="position: relative">
  </p >
</body>
<script>requestAnimationFrame(animate);</script>
</html>
</code>```

Thank you for the help.

答:
When the browser see a

```

Body:
I am learning Javacript and test the code from the book (below). It should animate an image but doesn't. I add print out using alert which shows that the function is executed only once. What goes wrong?

<!doctype html>

  <title> My home page </title>

Thank you for the help.

Body:
When the browser see a <script> tag, he stop rendering the page, and run the code inside.

So, the problem in the code that the line var cat = document.querySelector("img"); happen before the img is append to the document, so you query get nothing.

the only change you need to do- is to move the  var cat = document.querySelector("img"); to under the body, like so:

</body>
<script>
    var cat = document.querySelector("img");
    requestAnimationFrame(animate);
</script>

</html>


问:
MySql: Inser Into ... Select ... Where return #1054 error
I have two tables with a column both containing the same data.

The first table is called "countries" and has the following structure:

```<code>ID -> primary key;
name_countries;
code_countries;
code_city;
name_city;
longitude_city;
latitude_city.
</code>```

The second table is called "ar_geozone" and has the following structure:

```<code>country;
code_city;
name_city;
longitude;
latitude.
</code>```

I would like to copy all data from "ar_geozone" to "countries", for those rows where there is a match between "ar_geozone.country" and "countries.code_countries".

But when I use this SQL string,

```<code>INSERT INTO countries (code_city, name_city, longitude_city, latitude_city)
SELECT code_city, name_city, longitude, latitude FROM ar_geozone
WHERE ar_geozone.country LIKE countries.code_countries
</code>```

the system returns the error: # 1054 - Unknown column 'countries.code_countries' in 'where clause'.

答:
I'm not sure but try this... Correct If I am wrong</p>

```<code>INSERT INTO countries (code_city, name_city, longitude_city, latitude_city) SELECT code_city, name_city, longitude, latitude FROM ar_geozone WHERE ar_geozone.country LIKE code_countries
</code>```

Body:
I have two tables with a column both containing the same data.

The first table is called "countries" and has the following structure:

ID -> primary key;
name_countries;
code_countries;
code_city;
name_city;
longitude_city;
latitude_city.

The second table is called "ar_geozone" and has the following structure:

country;
code_city;
name_city;
longitude;
latitude.

I would like to copy all data from "ar_geozone" to "countries", for those rows where there is a match between "ar_geozone.country" and "countries.code_countries".

But when I use this SQL string,

INSERT INTO countries (code_city, name_city, longitude_city, latitude_city)
SELECT code_city, name_city, longitude, latitude FROM ar_geozone
WHERE ar_geozone.country LIKE countries.code_countries

the system returns the error: # 1054 - Unknown column 'countries.code_countries' in 'where clause'.

Body:
I'm not sure but try this... Correct If I am wrong

INSERT INTO countries (code_city, name_city, longitude_city, latitude_city) SELECT code_city, name_city, longitude, latitude FROM ar_geozone WHERE ar_geozone.country LIKE code_countries


问:
How can I silence `rustc`'s note about which native artifacts to link against?
I've got a project where Rust source files are being automatically generated and compiled into static libraries. I'd like the output of rustc to be streamed to stdout and stderr as usual, but I wish that the following note wasn't always emitted:

note: link against the following native artifacts when linking against this static library

note: the order and any duplication can be significant on some platforms, and so may need to be preserved

note: library: System

note: library: resolv

note: library: c

note: library: m
```

Is there any way to silence this without silencing too much else? The note was useful to me when I was figuring out how to link things automatically, but it won't be useful to my users who never actually see the linking process.

答:
In Rust 1.21 and earlier, there is no way to turn off the output.

In Rust 1.22, the --print=native-static-libs option was added. When it is not present, it outputs:

note: This list will not be printed by default. Please add --print native-static-libs if you need this information.

Adding the option will silence the warning.

To silence this information without silencing anything else, upgrade to Rust 1.23 once it's released.

https://github.com/rust-lang/rust/pull/43067

Body:
I've got a project where Rust source files are being automatically generated and compiled into static libraries. I'd like the output of rustc to be streamed to stdout and stderr as usual, but I wish that the following note wasn't always emitted:

note: link against the following native artifacts when linking against this static library

note: the order and any duplication can be significant on some platforms, and so may need to be preserved

note: library: System

note: library: resolv

note: library: c

note: library: m

Is there any way to silence this without silencing too much else? The note was useful to me when I was figuring out how to link things automatically, but it won't be useful to my users who never actually see the linking process.


问:
Format Code As a Code Block in R Markdown
Is there anyway to format code in the "code" format offered by many websites like Stackoverflow in R Markdown.

I want to be able to do something like the following:

Any model that takes the form income ~ education + parental_income
  ...

I want to emulate that greyed out text in R markdown for ease of readability when I eventually knit the document.

答:
html could work if you want to have a string with gray color as a background

Changing chunk background color in RMarkdown