问:
Can I use case enum comparison as a boolean expression?
I have an enum with associated values:

```<code>enum SessionState {
    ...
    case active(authToken: String)
    ...
}
</code>```

I can use case let to compare enum cases with associated values:

```<code>if case .active = session.state {
    return true
} else {
    return false
}
</code>```

But can I directly return the case as a bool expression? Something like:

```<code>// Error: Enum 'case' is not allowed outside of an enum
return (case .active = session.state)
</code>```

A simple comparison doesn’t work either:

```<code>// Binary operator '==' cannot be applied to operands of type 'SessionState' and '_'
return (session.state == .active)
</code>```

答:
Unfortunately, you cannot (directly) use a case condition as a Bool expression. They are only accessible in statements such as if, guard, while, for etc.

This is detailed in the language grammar, with:

```<code>case-condition → <b>case</b> pattern initializer```

This is then used in a condition:

```<code>condition → expression | availability-condition | case-condition | optional-binding-condition```

(where expression represents a Bool expression)

This is then used in condition-list:

```<code>condition-list → condition | condition <b>,</b> condition-list```

which is then used in statements such as if:

```<code>if-statement → <b>if</b> condition-list code-block else-clause<sub> opt</sub>```

So you can see that unfortunately case-condition is not an expression, rather just a special condition you can use in given statements.

To pack it into an expression, you'll either have to use an immediately-evaluated closure:

```<code>return { if case .active = session.state { return true }; return false }()```

Or otherwise write convenience computed properties on the enum in order to get a Bool in order  to check for a given case, as shown in this Q&A.

Both of which are quite unsatisfactory. This has been filed as an improvement request, but nothing has come of it yet (at the time of posting). Hopefully it's something that will be possible in a future version of the language.

Body:
I have an enum with associated values:

enum SessionState {
    ...
    case active(authToken: String)
    ...
}

I can use case let to compare enum cases with associated values:

if case .active = session.state {
    return true
} else {
    return false
}

But can I directly return the case as a bool expression? Something like:

// Error: Enum 'case' is not allowed outside of an enum
return (case .active = session.state)

A simple comparison doesn’t work either:

// Binary operator '==' cannot be applied to operands of type 'SessionState' and '_'
return (session.state == .active)

Body:
Unfortunately, you cannot (directly) use a case condition as a Bool expression. They are only accessible in statements such as if, guard, while, for etc.

This is detailed in the language grammar, with:

case-condition → case pattern initializer

This is then used in a condition:

condition → expression | availability-condition | case-condition | optional-binding-condition

(where expression represents a Bool expression)

This is then used in condition-list:

condition-list → condition | condition , condition-list

which is then used in statements such as if:

if-statement → if condition-list code-block else-clause opt

So you can see that unfortunately case-condition is not an expression, rather just a special condition you can use in given statements.

To pack it into an expression, you'll either have to use an immediately-evaluated closure:

return { if case .active = session.state { return true }; return false }()

Or otherwise write convenience computed properties on the enum in order to get a Bool in order  to check for a given case, as shown in this Q&A.

Both of which are quite unsatisfactory. This has been filed as an improvement request, but nothing has come of it yet (at the time of posting). Hopefully it's something that will be possible in a future version of the language.


来源: stackexchange

问:
Maintain selected cells after sorting a table view in Swift
I have a table view with multiple selection enabled. Users are supposed to be able to select multiple options in a list and then change the sort order of the list. I would like to be able to keep the same cells selected, but the order of them will have changed from the sort. I'm not seeing a way to achieve this so any suggestions are appreciated.</p>

答:
If you have a "selected" indicator in your data structure, you could use it to rebuild the tableView selection.

If you can't add such an indicator to the data, you could perform your sort in two steps:  1) compute the new element indexes, 2) apply these indexes to your data array to perform the sort.

With the sort indexes, you can rebuild the selection based on the new location of the original indexes:

For example:

```<code>// Assuming your tableview is named "tableView",
// and the data array is named "dataArray",
// and you sort uses a member of dataArray called "sortKey"

// prepare list of new indexes for sorted data
let newIndexes   = dataArray.enumerated().sorted{ $0.1.sortKey < $1.1.sortKey }.map{$0.0}

// determine new indexes of current selection
let newSelection = tableView.indexPathsForSelectedRows?
                   .map{IndexPath(row:newIndexes.index(of:$0.row)!, section:0)}

// sort and reload the data
dataArray        = newIndexes.map{ self.dataArray[$0] }
tableView.reloadData()

// reapply the selection
tableView.indexPathsForSelectedRows?.forEach{tableView.deselectRow(at:$0, animated:false)}
for indexPath in newSelection ?? []
{ self.tableView.selectRow(at: indexPath, animated: false, scrollPosition: .none) }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
If you have a "selected" indicator in your data structure, you could use it to rebuild the tableView selection.

If you can't add such an indicator to the data, you could perform your sort in two steps:  1) compute the new element indexes, 2) apply these indexes to your data array to perform the sort.

With the sort indexes, you can rebuild the selection based on the new location of the original indexes:

For example:

// Assuming your tableview is named "tableView",
// and the data array is named "dataArray",
// and you sort uses a member of dataArray called "sortKey"

// prepare list of new indexes for sorted data
let newIndexes   = dataArray.enumerated().sorted{ $0.1.sortKey < $1.1.sortKey }.map{$0.0}

// determine new indexes of current selection
let newSelection = tableView.indexPathsForSelectedRows?
                   .map{IndexPath(row:newIndexes.index(of:$0.row)!, section:0)}

// sort and reload the data
dataArray        = newIndexes.map{ self.dataArray[$0] }
tableView.reloadData()

// reapply the selection
tableView.indexPathsForSelectedRows?.forEach{tableView.deselectRow(at:$0, animated:false)}
for indexPath in newSelection ?? []
{ self.tableView.selectRow(at: indexPath, animated: false, scrollPosition: .none) }


问:
Python - how to use few times the same next iteration?
I would like to search a list:

```<code>[0, 0, 1, 0, 1, 1, 1, 0, 1, 1]
</code>```

and replace/edit items different from the previous item and next item. For xxample: I want to get rid of/edit 1 at index 2 in the list above.

Take a look at my code below and please continue reading my core question beneath my code:

!Update: Result should be: [0, 0, 0, 0, 1, 1, 1, 1, 1, 1]

```<code>x = [0, 0, 1, 0, 1, 1, 1, 0, 1, 1]
print(x)
hiter = iter(x)
next(hiter)
prev = None

for i in x:
    try:
        print('prev %s - CURRENT %s - next %s' % (prev, i, next(hiter)))
        prev = i

        #if i != prev and i != next(hiter):
        #   x[i] = prev

    except StopIteration:
        break

print(x)
</code>```

We know the previous item, the next item and the current item.

But everytime I use:

```
if i != prev and <b>i != next(hiter)</b>...
```

the next(hiter) destroys order. In other words, if I use next(hiter) more than 1 time in my loop, Python reads the next item as double, because I used next(hiter) two times in a loop.

I tried also declare seperate variable like y = next(hiter) - but still it didn't work (obviously won't work but I was desperate to check it anyway xD).

I have no clues, in addition, hiter.__next__() does the same as next(hiter).

答:
!Update 2: Thank You everyone for contribution. It was really helpful and I learned a lot today. Here is what I meant (Sorry @MSeifert but I had to do it my way, I know generators are faster and they don't eat memory).
Solution:

```<code>x = [0, 0, 1, 0, 1, 1, 1, 0, 1, 1]
print(x)
for i in range(1, len(x)-1):
    current = x[i]
    nxt = x[i+1]
    prev = x[i-1]

    if current != prev and current != nxt:
        print('prev: %s - CURRENT: %s - next: %s [ X ]' % (prev, current, nxt))
        x[i] = x[i-1]
    else:
        print('prev: %s - CURRENT: %s - next: %s' % (prev, current, nxt))

print(x)
</code>```

Body:
I would like to search a list:

[0, 0, 1, 0, 1, 1, 1, 0, 1, 1]

and replace/edit items different from the previous item and next item. For xxample: I want to get rid of/edit 1 at index 2 in the list above.

Take a look at my code below and please continue reading my core question beneath my code:

!Update: Result should be: [0, 0, 0, 0, 1, 1, 1, 1, 1, 1]

x = [0, 0, 1, 0, 1, 1, 1, 0, 1, 1]
print(x)
hiter = iter(x)
next(hiter)
prev = None

for i in x:
    try:
        print('prev %s - CURRENT %s - next %s' % (prev, i, next(hiter)))
        prev = i

        #if i != prev and i != next(hiter):
        #   x[i] = prev

    except StopIteration:
        break

print(x)

We know the previous item, the next item and the current item.

But everytime I use:

if i != prev and i != next(hiter)...

the next(hiter) destroys order. In other words, if I use next(hiter) more than 1 time in my loop, Python reads the next item as double, because I used next(hiter) two times in a loop.

I tried also declare seperate variable like y = next(hiter) - but still it didn't work (obviously won't work but I was desperate to check it anyway xD).

I have no clues, in addition, hiter.__next__() does the same as next(hiter).

Body:
!Update 2: Thank You everyone for contribution. It was really helpful and I learned a lot today. Here is what I meant (Sorry @MSeifert but I had to do it my way, I know generators are faster and they don't eat memory).
Solution:

x = [0, 0, 1, 0, 1, 1, 1, 0, 1, 1]
print(x)
for i in range(1, len(x)-1):
    current = x[i]
    nxt = x[i+1]
    prev = x[i-1]

    if current != prev and current != nxt:
        print('prev: %s - CURRENT: %s - next: %s [ X ]' % (prev, current, nxt))
        x[i] = x[i-1]
    else:
        print('prev: %s - CURRENT: %s - next: %s' % (prev, current, nxt))

print(x)


问:
How to create a list where each new element is obtained as the last element plus a constant?
Given these variables:

```<code>a_4th =  6.08
delta_a = 0.052
</code>```

I would like to create a list that contains:

```<code>a = [a_4th, a_5th, a_6th, a_7th ... ]
</code>```

where:

```<code>a_5th = a_4th + delta_a
a_6th = a_5th + delta_a
a_7th = a_6th + delta_a
</code>```

This code:

```<code>a = []  # create the empty list
a.insert(0, a_4th) # initialize the 1st item of the list

for i in xrange (1,19):   # I would like the list to be 18 items long.
                          # a[0] is defined in the previous line.
  a[i] = a[i-1] + delta_a
</code>```

is giving this error:

Traceback (most recent call last):
  File "so.py", line 8, in <module>
    a[i] = a[i-1] + delta_a
IndexError: list assignment index out of range
```

答:
I would use a Python generator if I were you since it gives you extra expressiveness with the ability to express an "infinitely" large sequence.

```<code>def succession(initial, delta):
  while True:
    yield initial
    # value, then, the next time you call
    initial += delta

values_generator = succession(6.08, 0.052)

# later we decide how many values we want to consume from the generator
for i in range(20):
  print(next(values_generator))
</code>```

Update:

Adding more explanation on generators. Generators are a mechanism provided by Python that allows to build efficient data processing pipelines.

Say you have a list of numbers from 0 to 100_000, and you want to apply some transformations to it like filtering, then mapping, and so on, if you use regular Python2 map and filter your solution won't scale well because in each step (filtering, mapping, etc) an entire new list of intermediate results with potentially many elements that might not even be used in the final result will be computed. The key idea of building these functional pipelines is that we want them to be combinators that is, small functions that we can combine to create yet new functions that later can be combined, but we don't want to pay a price in performance. Generators basically come to solve this in Python (in Clojure you have transducers and in Haskell lazy evaluation). With generators Python won't build the intermediate lists but to push one value on one end of the pipeline, transform it, and pop it out the other end, this for each element in the initial data set you wish to transform.

A simple example of a generator would be:

```<code>def trivial_generator():
  print "running until first yield..."
  yield 1
  print "running until second yield..."
  yield 2
  print "exiting..."

generator = trivial_generator()

result = generator.next()
print "got result ", result
result = generator.next()
print "got result ", result
generator.next()
</code>```

if you run that you'll get:

```<code>running until first yield...
got result  1
running until second yield...
got result  2
exiting...
Traceback (most recent call last):
  File "foo.py", line 14, in <module>
    generator.next()
StopIteration
</code>```

which illustrates the behavior of generators which is:

You create one by calling a function that contains a yield

Every time you call the .next() method on it, or pass it to the next(generator) function, the body of the generator will be executed until a yield is found

When a yield is found, the value specified in the yield will be returned and the generator will stay paused until you call its .next() method again, at which point it will resume from the last point it was paused (notice that all the internal state of the generator is kept between calls)

If you call .next() on a generator and no other yield is found (which means is the end of it) an StopIteration is raised (which is very convenient since is the exception a for loops expects to happen at the en d of an iterator)

In the example solution I used, I took advantage of the pause/resume capabilities of the generators, by putting the yield inside an infinite loop, I got a generator that will give me as many values I need efficiently.

Body:
Given these variables:

a_4th =  6.08
delta_a = 0.052

I would like to create a list that contains:

a = [a_4th, a_5th, a_6th, a_7th ... ]

where:

a_5th = a_4th + delta_a
a_6th = a_5th + delta_a
a_7th = a_6th + delta_a

This code:

a = []  # create the empty list
a.insert(0, a_4th) # initialize the 1st item of the list

for i in xrange (1,19):   # I would like the list to be 18 items long.
                          # a[0] is defined in the previous line.
  a[i] = a[i-1] + delta_a

is giving this error:

Traceback (most recent call last):
  File "so.py", line 8, in <module>
    a[i] = a[i-1] + delta_a
IndexError: list assignment index out of range

Body:
I would use a Python generator if I were you since it gives you extra expressiveness with the ability to express an "infinitely" large sequence.

def succession(initial, delta):
  while True:
    yield initial
    # value, then, the next time you call
    initial += delta

values_generator = succession(6.08, 0.052)

# later we decide how many values we want to consume from the generator
for i in range(20):
  print(next(values_generator))

Update:

Adding more explanation on generators. Generators are a mechanism provided by Python that allows to build efficient data processing pipelines.

Say you have a list of numbers from 0 to 100_000, and you want to apply some transformations to it like filtering, then mapping, and so on, if you use regular Python2 map and filter your solution won't scale well because in each step (filtering, mapping, etc) an entire new list of intermediate results with potentially many elements that might not even be used in the final result will be computed. The key idea of building these functional pipelines is that we want them to be combinators that is, small functions that we can combine to create yet new functions that later can be combined, but we don't want to pay a price in performance. Generators basically come to solve this in Python (in Clojure you have transducers and in Haskell lazy evaluation). With generators Python won't build the intermediate lists but to push one value on one end of the pipeline, transform it, and pop it out the other end, this for each element in the initial data set you wish to transform.

A simple example of a generator would be:

def trivial_generator():
  print "running until first yield..."
  yield 1
  print "running until second yield..."
  yield 2
  print "exiting..."

generator = trivial_generator()

result = generator.next()
print "got result ", result
result = generator.next()
print "got result ", result
generator.next()

if you run that you'll get:

running until first yield...
got result  1
running until second yield...
got result  2
exiting...
Traceback (most recent call last):
  File "foo.py", line 14, in <module>
    generator.next()
StopIteration

which illustrates the behavior of generators which is:

You create one by calling a function that contains a yield

Every time you call the .next() method on it, or pass it to the next(generator) function, the body of the generator will be executed until a yield is found

When a yield is found, the value specified in the yield will be returned and the generator will stay paused until you call its .next() method again, at which point it will resume from the last point it was paused (notice that all the internal state of the generator is kept between calls)

If you call .next() on a generator and no other yield is found (which means is the end of it) an StopIteration is raised (which is very convenient since is the exception a for loops expects to happen at the en d of an iterator)

In the example solution I used, I took advantage of the pause/resume capabilities of the generators, by putting the yield inside an infinite loop, I got a generator that will give me as many values I need efficiently.


问:
AcquireTokenAsync not found for auth context when trying to get token
I am trying to get the bearer token to call an API via a powershell script like so:

```<code>function GetAuthToken
{
    param
    (
        [Parameter(Mandatory=$true)]
        $ApiEndpointUri,

        [Parameter(Mandatory=$true)]
        $AADTenant
)
$adal = "C:\Program Files (x86)\Reference Assemblies\Microsoft\WindowsPowerShell\3.0\" + `
            "Microsoft.IdentityModel.Clients.ActiveDirectory.dll"
$adalforms = "C:\Program Files (x86)\Reference Assemblies\Microsoft\WindowsPowerShell\3.0\" + `
                "Microsoft.IdentityModel.Clients.ActiveDirectory.WindowsForms.dll"

[System.Reflection.Assembly]::LoadFrom($adal) | Out-Null
[System.Reflection.Assembly]::LoadFrom($adalforms) | Out-Null

$clientId = "1950a258-227b-4e31-a9cf-717495945fc2"
$redirectUri = "urn:ietf:wg:oauth:2.0:oob"
$authorityUri = “https://login.windows.net/$aadTenant”

$authContext = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext" -ArgumentList $authorityUri

$authResult = $authContext.AcquireTokenAsync($ApiEndpointUri, $clientId,$redirectUri, "Auto")
$authResult.Wait();

return $authResult
$ApiEndpointUri = "https://management.azure.com/" #change this to graph api uri
$AADTenant = 'GUID' #AAD tenant guid
$token = GetAuthToken -ApiEndPointUri $ApiEndpointUri -AADTenant $AADTenant
$header = @{
'Content-Type'='application\json'
'Authorization'=$token.CreateAuthorizationHeader()
}

$request = ``
(Invoke-RestMethod -Uri $request -Headers $header -Method Get).value
</code>```

However, acquiretokenasync is failing with this error:

```<code>Cannot find an overload for "AcquireTokenAsync" and the argument count: "4".
</code>```

Any ideas why I am getting this issue? AcquireTokenAsync takes 4 arguments from what I know.

答: I had a similar error on Windows 10 build 1703 (though the script was working on build 1607).  I had version 3.13.9 installed of Microsoft.IdentityModel.Clients.ActiveDirectory.  I replaced those assemblies with version 3.13.8  and restarted PowerShell, which cleared my error.</p>

Body:
I am trying to get the bearer token to call an API via a powershell script like so:

function GetAuthToken
{
    param
    (
        [Parameter(Mandatory=$true)]
        $ApiEndpointUri,

        [Parameter(Mandatory=$true)]
        $AADTenant
)
$adal = "C:\Program Files (x86)\Reference Assemblies\Microsoft\WindowsPowerShell\3.0\" + `
            "Microsoft.IdentityModel.Clients.ActiveDirectory.dll"
$adalforms = "C:\Program Files (x86)\Reference Assemblies\Microsoft\WindowsPowerShell\3.0\" + `
                "Microsoft.IdentityModel.Clients.ActiveDirectory.WindowsForms.dll"

[System.Reflection.Assembly]::LoadFrom($adal) | Out-Null
[System.Reflection.Assembly]::LoadFrom($adalforms) | Out-Null

$clientId = "1950a258-227b-4e31-a9cf-717495945fc2"
$redirectUri = "urn:ietf:wg:oauth:2.0:oob"
$authorityUri = “https://login.windows.net/$aadTenant”

$authContext = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext" -ArgumentList $authorityUri

$authResult = $authContext.AcquireTokenAsync($ApiEndpointUri, $clientId,$redirectUri, "Auto")
$authResult.Wait();

return $authResult
$ApiEndpointUri = "https://management.azure.com/" #change this to graph api uri
$AADTenant = 'GUID' #AAD tenant guid
$token = GetAuthToken -ApiEndPointUri $ApiEndpointUri -AADTenant $AADTenant
$header = @{
'Content-Type'='application\json'
'Authorization'=$token.CreateAuthorizationHeader()
}

$request = ``
(Invoke-RestMethod -Uri $request -Headers $header -Method Get).value

However, acquiretokenasync is failing with this error:

Cannot find an overload for "AcquireTokenAsync" and the argument count: "4".

Any ideas why I am getting this issue? AcquireTokenAsync takes 4 arguments from what I know.


问:
How to correct and improve this c++ code using templates and inheritance?
I'm learning c++ and know roughly what I want to do but I'm doing it the wrong way and I'm very tired.  What's the best way (the correct way first of all) of doing something like this:</p>

```<code>// Query.hpp
class Query {
public:
 Query();

 template<typename T>
 std::vector<boost::shared_ptr<BaseResult> > run();

private:
 std::string sql;
};

// Firstly, something like this:
// I would like to do the equivalent of passing in a type T that would be
// derived from BaseResult and create a new instance of it when adding
// to vector of BaseResult:
template<typename T>
std::vector<boost::shared_ptr<BaseResult> > Query::run() {
 std::vector<boost::shared_ptr<BaseResult> > results;

 // ResultSet is from the mysql c++ connector
 boost::shared_ptr<sql::ResultSet> res(stmt->executeQuery(this->sql));

 // I want to add a new T to results here
 while (res->next()) {
  results.push_back(new T(res));
 }

 // RVO prevents copy in release - yes?
 return results;
}

// Query.cpp
Query::Query() {
}

// main.cpp
void foo(const std::vector<boost::shared_ptr<BaseResult> >& results) {
 // loop through calling virtual method on each item
}

int main(int argc, char* argv[])
 // Determine query type
 ProgramOptions opts(argc, argv);

 // Should this indeed be a pointer because
 // of code below or is it wrong?
 std::vector<boost::shared_ptr<BaseResult> >* results;

    // Secondly, something like this:
 if (opts.getquerytype() == "type1") {

  // I'd like to get a
  // std::vector<boost::shared_ptr<BaseResult> > returned here
  // containing many instances of a
  // type derived from BaseResult

  // I'd like to be able to do something like this
  // Is this assignment correct?
        *results = getQuery().run<DerivedResult>();
 }
 else {
  // I'd like to get a
  // std::vector<boost::shared_ptr<BaseResult> > returned here
  // containing many instances of a
  // different type derived from BaseResult

  // I'd like to be able to do something like this
  // Is this assignment correct?
        *results = getQuery().run<DifferentDerivedResult>();
 }

    foo(results);
}
</code>```

答:
Firstly, your assignment is not correct

```<code>*results = getQuery().run<DifferentDerivedResult>();
</code>```

De-references a non-initialised pointer!

I would do a few changes to your code, firstly, having to use vector<...> everywhere is going to induce RSI, typedef it

```<code>class Query {
public:

 // Query::ResultType
 typedef std::vector<boost::shared_ptr<BaseResult> > ResultType;

 Query();

 // next, pass in the vector where the results will be stored...
 template<typename T>
   void run(ResultType& records);

private:
 std::string sql;
};
</code>```

Now the implementation:

```<code>template<typename T>
void Query::run(ResultType& records) {

 // ResultSet is from the mysql c++ connector
 boost::shared_ptr<sql::ResultSet> res(stmt->executeQuery(this->sql));

 // I want to add a new T to results here
 while (res->next()) {
  records.push_back(new T(res));
 }

 // No need to worry about RVO
}
</code>```

Now in your main:

```<code>Query::ResultType results; // not a pointer!
</code>```

Then you can invoke each type, e.g.

```<code>getQuery().run<DifferentDerivedResult>(results);
</code>```

This introduces minimal changes to your design, if you wanted to avoid the BaseResult type completely you can template everything - but I'm not sure what functionality BaseResult is giving you and whether this would be possible..

ContentLicense: CC BY-SA 2.5

Body:
I'm learning c++ and know roughly what I want to do but I'm doing it the wrong way and I'm very tired.  What's the best way (the correct way first of all) of doing something like this:

// Query.hpp
class Query {
public:
 Query();

 template<typename T>
 std::vector<boost::shared_ptr<BaseResult> > run();

private:
 std::string sql;
};

// Firstly, something like this:
// I would like to do the equivalent of passing in a type T that would be
// derived from BaseResult and create a new instance of it when adding
// to vector of BaseResult:
template<typename T>
std::vector<boost::shared_ptr<BaseResult> > Query::run() {
 std::vector<boost::shared_ptr<BaseResult> > results;

 // ResultSet is from the mysql c++ connector
 boost::shared_ptr<sql::ResultSet> res(stmt->executeQuery(this->sql));

 // I want to add a new T to results here
 while (res->next()) {
  results.push_back(new T(res));
 }

 // RVO prevents copy in release - yes?
 return results;
}

// Query.cpp
Query::Query() {
}

// main.cpp
void foo(const std::vector<boost::shared_ptr<BaseResult> >& results) {
 // loop through calling virtual method on each item
}

int main(int argc, char* argv[])
 // Determine query type
 ProgramOptions opts(argc, argv);

 // Should this indeed be a pointer because
 // of code below or is it wrong?
 std::vector<boost::shared_ptr<BaseResult> >* results;

    // Secondly, something like this:
 if (opts.getquerytype() == "type1") {

  // I'd like to get a
  // std::vector<boost::shared_ptr<BaseResult> > returned here
  // containing many instances of a
  // type derived from BaseResult

  // I'd like to be able to do something like this
  // Is this assignment correct?
        *results = getQuery().run<DerivedResult>();
 }
 else {
  // I'd like to get a
  // std::vector<boost::shared_ptr<BaseResult> > returned here
  // containing many instances of a
  // different type derived from BaseResult

  // I'd like to be able to do something like this
  // Is this assignment correct?
        *results = getQuery().run<DifferentDerivedResult>();
 }

    foo(results);
}

Body:
Firstly, your assignment is not correct

*results = getQuery().run<DifferentDerivedResult>();

De-references a non-initialised pointer!

I would do a few changes to your code, firstly, having to use vector<...> everywhere is going to induce RSI, typedef it

class Query {
public:

 // Query::ResultType
 typedef std::vector<boost::shared_ptr<BaseResult> > ResultType;

 Query();

 // next, pass in the vector where the results will be stored...
 template<typename T>
   void run(ResultType& records);

private:
 std::string sql;
};

Now the implementation:

template<typename T>
void Query::run(ResultType& records) {

 // ResultSet is from the mysql c++ connector
 boost::shared_ptr<sql::ResultSet> res(stmt->executeQuery(this->sql));

 // I want to add a new T to results here
 while (res->next()) {
  records.push_back(new T(res));
 }

 // No need to worry about RVO
}

Now in your main:

Query::ResultType results; // not a pointer!

Then you can invoke each type, e.g.

getQuery().run<DifferentDerivedResult>(results);

This introduces minimal changes to your design, if you wanted to avoid the BaseResult type completely you can template everything - but I'm not sure what functionality BaseResult is giving you and whether this would be possible..


问:
span tag text-align not working
I'm trying to make a line for price and I want the text-align like the first one on the left, second one on the center and the third one will be on right.

Normally the text-align works but I can't keep all three of them in them in the same line. Should I use something different? or there's a solution for this!?

First I tried like this:

.price span {
  display: inline;
  /* also tried with block and inline-block */
}

.previous-price {
  text-align: left;
}

.present-price {
  text-align: center;
}

.discount-price {
  text-align: right;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p class="price">
  <span class="previous-price"><s>Tk. 350000</s></span>
   <span class="present-price">Tk. 227500</span>
   <span class="discount-price">(35% OFF)</span>
  </p></code>```

答:
You need to NOT use display:inline for .price span and give it a width either fixed (like px) or in percentage.

E.g:

  .price{
    width:100%;
  }
  .price span {
        display: inline-block; /* also tried with block and inline-block */
        width:150px;
    }
    .previous-price {
        text-align: left;
    }
    .present-price {
        text-align: center;
    }
    .discount-price {
        text-align: right;
    } ```
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <p class="price">
        <span class="previous-price"><s>Tk. 350000</s></span>
        <span class="present-price">Tk. 227500</span>
        <span class="discount-price">(35% OFF)</span>
    </p></code>```

Title: span tag text-align not working

Body:
I'm trying to make a line for price and I want the text-align like the first one on the left, second one on the center and the third one will be on right.

Normally the text-align works but I can't keep all three of them in them in the same line. Should I use something different? or there's a solution for this!?

First I tried like this:

.price span {
  display: inline;
  /* also tried with block and inline-block */
}

.previous-price {
  text-align: left;
}

.present-price {
  text-align: center;
}

.discount-price {
  text-align: right;
}

  <s>Tk. 350000</s>
   Tk. 227500
   (35% OFF)

Body:
You need to NOT use display:inline for .price span and give it a width either fixed (like px) or in percentage.

E.g:

  .price{
    width:100%;
  }
  .price span {
        display: inline-block; /* also tried with block and inline-block */
        width:150px;
    }
    .previous-price {
        text-align: left;
    }
    .present-price {
        text-align: center;
    }
    .discount-price {
        text-align: right;
    }

    <p class="price">
        <span class="previous-price"><s>Tk. 350000</s></span>
        <span class="present-price">Tk. 227500</span>
        <span class="discount-price">(35% OFF)</span>
    </p>


问:
Ruby: Compare 2 arrays for matches, and count the number of match instances
I have 2 arrays:

```<code>@array1 = [a,b,c,d,e]
@array2 = [d,e,f,g,h]
</code>```

I want to compare the two arrays to find matches (d,e) and count the number of matches found (2)?

```<code><% if @array2.include?(@array1) %>
  # yes, but how to count instances?
<% else %>
  no matches found...
<% end %>
</code>```

Thanks in advance~

答:
To find the number of total matches between the arrays, add them together, then subtract the unique set.  The difference between the length of the superset array and the uniq set will be the count of the matches of the second array in the first.  This method works best if a2 is a unique set.</p>

```<code>a1 = ['a','b','c','d','d','d']
a2 = ['a','d']

superset = (a1 + a2)
subset = superset.uniq

matches = superset.count - subset.count
</code>```

Body:
I have 2 arrays:

@array1 = [a,b,c,d,e]
@array2 = [d,e,f,g,h]

I want to compare the two arrays to find matches (d,e) and count the number of matches found (2)?

<% if @array2.include?(@array1) %>
  # yes, but how to count instances?
<% else %>
  no matches found...
<% end %>

Thanks in advance~

Body:
To find the number of total matches between the arrays, add them together, then subtract the unique set.  The difference between the length of the superset array and the uniq set will be the count of the matches of the second array in the first.  This method works best if a2 is a unique set.

a1 = ['a','b','c','d','d','d']
a2 = ['a','d']

superset = (a1 + a2)
subset = superset.uniq

matches = superset.count - subset.count


问:
Bitmap move gradually to a click (easeljs)
I'd like my bitmap to go to a click position but I want to see a progression between the bitmap.x/bitmap.y and the click.x/click.y
How can I make this animation ?

Thanks a lot

答:
You can create a tween using TweenJS when the stage is clicked:

```<code>stage.on("stagemousedown", function(event) {
    // Tween to the new position. Override old tweens on the same object.
    createjs.Tween.get(bitmapInstance, {override:true}).to({x:event.stageX, y:event.stageY}, 500, createjs.Ease.quadIn);
})
</code>```

Here is a quick fiddle: http://jsfiddle.net/jemohtgh/

Or you can store the clicked position, and basically have the shape always try to reach that position (fiddle):

```<code>var pos = new createjs.Point();
stage.on("stagemousedown", function(event) {
    pos.setValues(event.stageX, event.stageY);
})
function tick(event) {
    // Move towards the position
    s.x += (pos.x - s.x) / 2;
    s.y += (pos.y - s.y) / 2;
    stage.update(event);
}
</code>```

You can also do the same thing with a mouse follow instead of a click (fiddle):

```<code>function tick(event) {
    s.x += (stage.mouseX - s.x) / 5;
    s.y += (stage.mouseY - s.y) / 5;
    stage.update(event);
}
</code>```

Cheers.

Body:
You can create a tween using TweenJS when the stage is clicked:

stage.on("stagemousedown", function(event) {
    // Tween to the new position. Override old tweens on the same object.
    createjs.Tween.get(bitmapInstance, {override:true}).to({x:event.stageX, y:event.stageY}, 500, createjs.Ease.quadIn);
})

Here is a quick fiddle: http://jsfiddle.net/jemohtgh/

Or you can store the clicked position, and basically have the shape always try to reach that position (fiddle):

var pos = new createjs.Point();
stage.on("stagemousedown", function(event) {
    pos.setValues(event.stageX, event.stageY);
})
function tick(event) {
    // Move towards the position
    s.x += (pos.x - s.x) / 2;
    s.y += (pos.y - s.y) / 2;
    stage.update(event);
}

You can also do the same thing with a mouse follow instead of a click (fiddle):

function tick(event) {
    s.x += (stage.mouseX - s.x) / 5;
    s.y += (stage.mouseY - s.y) / 5;
    stage.update(event);
}

Cheers.


问:
Access Unit and AUD in Transport Stream
What data should an access unit contain?

```

    [SPS][PPS][IDR][PFrame][BFrame]

```

is an access unit?
I got the concept that, access unit delimiters are required in ts packet. But, if the source file(I am using .264 file as input) do not contain AUD? then should I add AUD explicitly? If yes, then of how many bytes?
Should it be the following?

```

    0x00000169(of Header+1 Byte)

```

And where should I add the AUD?
Currently my TS file contains this formation:

```

    [TS Header][PES Header][SPS][PPS][IDR][PFrame][BFrame][TS Header]...

```

Is this structure okay? Also, can one access unit contain multiple I frames?

答:
f the source file does not contain AUD should I add AUD explicitly?

YES

Also, can one access unit contain multiple I frames

No, an an access unit is analogous to a single frame, they are used to explesit delimit frames. Hence the name.

0x00000169(of Header+1 Byte)

0x00000169FF80  just use this for the AUD. You can hard code it.

Title: Access Unit and AUD in Transport Stream

Body:
What data should an access unit contain?

    [SPS][PPS][IDR][PFrame][BFrame]

is an access unit?
I got the concept that, access unit delimiters are required in ts packet. But, if the source file(I am using .264 file as input) do not contain AUD? then should I add AUD explicitly? If yes, then of how many bytes?
Should it be the following?

    0x00000169(of Header+1 Byte)

And where should I add the AUD?
Currently my TS file contains this formation:

    [TS Header][PES Header][SPS][PPS][IDR][PFrame][BFrame][TS Header]...

Is this structure okay? Also, can one access unit contain multiple I frames?


问:
how can i do download of PDF archive of jasper report using AJAX?
I have a jasper report that I need to be printed using AJAX, however, with the jquery ajax call it does not work:

```<code>    $.ajax(
                {
                    method: 'POST',
                    url: 'ExportReport',
                    async : false,
                    data: {
                          typeOfClient          : _type,
                          mouthOfSelect         : _mounth
                },
                    success : function (html) {
                        alert("Sucess");
                }
</code>```

If i use submit form, this work:

```<code>//create dynamic form
var formularioElement = document.createElement('form');
formularioElement.setAttribute('id', 'formSync');
formularioElement.method = 'POST';
formularioElement.action = 'ExportReport';

// Create input
var formularioInput = document.createElement('input');
formularioInput.type = 'text';
formularioInput.name = 'typeOfClient';
formularioInput.value = _type;

// Create input 2
var formularioInput2 = document.createElement('input');
formularioInput2.type = 'text';
formularioInput2.name = 'mouthOfSelect';
formularioInput2.value = _mouth;

formularioElement.appendChild(formularioInput);
formularioElement.appendChild(formularioInput2);

// add the form to DOM
document.body.appendChild(formularioElement);

// submit
formularioElement.submit();
</code>```

the both codes call the server side and create the jasper PDF equals, but just the form.submit() do the download of file, the ajax code don't download the file.

Is possible I do it with AJAX?

答: you can't do it with AJAX because JS cannot save archives directly to a computer (for security reasons).</p>

Body:
I have a jasper report that I need to be printed using AJAX, however, with the jquery ajax call it does not work:

    $.ajax(
                {
                    method: 'POST',
                    url: 'ExportReport',
                    async : false,
                    data: {
                          typeOfClient          : _type,
                          mouthOfSelect         : _mounth
                },
                    success : function (html) {
                        alert("Sucess");
                }

If i use submit form, this work:

//create dynamic form
var formularioElement = document.createElement('form');
formularioElement.setAttribute('id', 'formSync');
formularioElement.method = 'POST';
formularioElement.action = 'ExportReport';

// Create input
var formularioInput = document.createElement('input');
formularioInput.type = 'text';
formularioInput.name = 'typeOfClient';
formularioInput.value = _type;

// Create input 2
var formularioInput2 = document.createElement('input');
formularioInput2.type = 'text';
formularioInput2.name = 'mouthOfSelect';
formularioInput2.value = _mouth;

formularioElement.appendChild(formularioInput);
formularioElement.appendChild(formularioInput2);

// add the form to DOM
document.body.appendChild(formularioElement);

// submit
formularioElement.submit();

the both codes call the server side and create the jasper PDF equals, but just the form.submit() do the download of file, the ajax code don't download the file.

Is possible I do it with AJAX?


问:
Unable to merge android manifests. See the Console for more details
I got following error while making apk file from unity. I set minimum API level=19 and target 24. because I build a apk for Gear VR and I have Samsung S7 Edge.

CommandInvokationFailure: Unable to merge android manifests. See the
  Console for more details.  C:/Program
  Files/Java/jdk1.8.0_131\bin\java.exe -Xmx2048M
  -Dcom.android.sdkmanager.toolsdir="C:/Android/sdk\tools" -Dfile.encoding=UTF8 -jar "C:\Users\saad asghar\Editor\Data\PlaybackEngines\AndroidPlayer/Tools\sdktools.jar" -

stderr[ Error:Invalid command manifmerger ] stdout[

] exit code: 64 UnityEditor.Android.Command.Run
  (System.Diagnostics.ProcessStartInfo psi,
  UnityEditor.Android.WaitingForProcessToExit waitingForProcessToExit,
  System.String errorMsg)
  UnityEditor.Android.AndroidSDKTools.RunCommandInternal (System.String
  javaExe, System.String sdkToolsDir, System.String[] sdkToolCommand,
  Int32 memoryMB, System.String workingdir,
  UnityEditor.Android.WaitingForProcessToExit waitingForProcessToExit,
  System.String errorMsg)
  UnityEditor.Android.AndroidSDKTools.RunCommandSafe (System.String
  javaExe, System.String sdkToolsDir, System.String[] sdkToolCommand,
  Int32 memoryMB, System.String workingdir,
  UnityEditor.Android.WaitingForProcessToExit waitingForProcessToExit,
  System.String errorMsg) UnityEditor.HostView:OnGUI()

答:
The error happens due to this Unity bug (related to the latest Android SDK tools version).

You can see in the error message that the "manifmerger" tool returns an error code (64):

stderr[ Error:Invalid command manifmerger ] stdout[

] exit code: 64

The bug is fixed in the latest Unity (beta) version. There is a workaround, as described on that page:

Workaround for the customers.

just open https://developer.android.com/studio/index.html

scroll down to the bottom of that page

go to downloads

scroll down to the bottom of that page

find Windows "tools_r25.2.3-windows.zip" download and unzip it

or, on mac: find MacOSX "tools_r25.2.3-macosx.zip" download and unzip it.

In the SDK path replace the tools folder.

This is a quote from the issuetracker page. I've added direct links to the downloads, since they seem to be missing from the Android website.


问:
Debugging monit
I find debugging monit to be a major pain. Monit's shell environment basically has nothing in it (no paths or other environment variables). Also, there are no log file that I can find.

The problem is, if the start or stop command in the monit script fails, it is difficult to discern what is wrong with it. Often times it is not as simple as just running the command on the shell because the shell environment is different from the monit shell environment.

What are some techniques that people use to debug monit configurations?

For example, I would be happy to have a monit shell, to test my scripts in, or a log file to see what went wrong.

答:
Be sure to always double check your conf and monitor your processes by hand before letting monit handle everything. systat(1), top(1) and ps(1) are your friends to figure out resource usage and limits. Knowing the process you monitor is essential too.

Regarding the start and stop scripts i use a wrapper script to redirect output and inspect environment and other variables. Something like this :

```<code>$ cat monit-wrapper.sh

#!/bin/sh
{
  echo "MONIT-WRAPPER date"
  date
  echo "MONIT-WRAPPER env"
  env
  echo "MONIT-WRAPPER $@"
  $@
  R=$?
  echo "MONIT-WRAPPER exit code $R"
} >/tmp/monit.log 2>&1
</code>```

Then in monit :

```<code>start program = "/home/billitch/bin/monit-wrapper.sh my-real-start-script and args"
stop program = "/home/billitch/bin/monit-wrapper.sh my-real-stop-script and args"
</code>```

You still have to figure out what infos you want in the wrapper, like process infos, id, system resources limits, etc.

Title: Debugging monit

Body:
Be sure to always double check your conf and monitor your processes by hand before letting monit handle everything. systat(1), top(1) and ps(1) are your friends to figure out resource usage and limits. Knowing the process you monitor is essential too.

Regarding the start and stop scripts i use a wrapper script to redirect output and inspect environment and other variables. Something like this :

$ cat monit-wrapper.sh

#!/bin/sh
{
  echo "MONIT-WRAPPER date"
  date
  echo "MONIT-WRAPPER env"
  env
  echo "MONIT-WRAPPER $@"
  $@
  R=$?
  echo "MONIT-WRAPPER exit code $R"
} >/tmp/monit.log 2>&1

Then in monit :

start program = "/home/billitch/bin/monit-wrapper.sh my-real-start-script and args"
stop program = "/home/billitch/bin/monit-wrapper.sh my-real-stop-script and args"

You still have to figure out what infos you want in the wrapper, like process infos, id, system resources limits, etc.


问:
Spring Security does not accept correct credentials
I have a web app that uses Spring Security. The user database is a H2 file database. Whenever Spring Security tries to authenticate correct a username/password combination it throws a BadCredentialsExcpetion. If, however, I manually execute the exact same query as Spring Security it successfully finds the user in the table.

SecurityConfiguration.java

```<code>@Configuration
@EnableWebSecurity
public class SpringConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    private DataSource dataSource;

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.jdbcAuthentication()
                .dataSource(dataSource)
                .usersByUsernameQuery("SELECT `USERNAME`, `PASSWORD`, `ENABLED` FROM `users` WHERE `USERNAME` = ?")
                .authoritiesByUsernameQuery("SELECT `USERNAME`, `AUTHORITY` FROM `authorities` WHERE `USERNAME` = ?");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
    }

}
</code>```

AuthenticationServiceImpl.java

```<code>@SpringComponent
@ApplicationScope
public class AuthenticationServiceImpl implements AuthenticationService {

    private final AuthenticationManager authenticationManager;

    @Autowired
    public AuthenticationServiceImpl(AuthenticationManager authenticationManager) {
        this.authenticationManager = authenticationManager;
    }

    @Override
    public void authenticate(String user, String password) throws BadCredentialsException, AuthenticationException, IOException {
        authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(user, password));
    }

}
</code>```

I have tried using MySQL instead, but it didn't change anything.

SQL Schema

```<code>CREATE TABLE `users` (
  `USERNAME` varchar(10) NOT NULL,
  `PASSWORD` varchar(60) NOT NULL,
  `ENABLED` tinyint(1) NOT NULL,
  PRIMARY KEY (`USERNAME`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

CREATE TABLE `authorities` (
  `USERNAME` varchar(10) NOT NULL,
  `AUTHORITY` varchar(10) NOT NULL,
  PRIMARY KEY (`USERNAME`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
</code>```

Stacktrace

```<code>org.springframework.security.authentication.BadCredentialsException: Bad credentials
    at org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider.authenticate(AbstractUserDetailsAuthenticationProvider.java:151)
    at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:174)
    at posproject17.data.AuthenticationServiceImpl.authenticate(AuthenticationServiceImpl.java:29)
    at posproject17.data.AuthenticationServiceImpl$$FastClassBySpringCGLIB$$2acc9e9c.invoke(<generated>)
    at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:738)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
    at org.springframework.aop.support.DelegatingIntroductionInterceptor.doProceed(DelegatingIntroductionInterceptor.java:133)
    at org.springframework.aop.support.DelegatingIntroductionInterceptor.invoke(DelegatingIntroductionInterceptor.java:121)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:673)
    at posproject17.data.AuthenticationServiceImpl$$EnhancerBySpringCGLIB$$d3f6b712.authenticate(<generated>)
    at posproject17.view.LoginView.lambda$init$61446b05$1(LoginView.java:49)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.vaadin.event.ListenerMethod.receiveEvent(ListenerMethod.java:510)
    at com.vaadin.event.EventRouter.fireEvent(EventRouter.java:211)
    at com.vaadin.event.EventRouter.fireEvent(EventRouter.java:174)
    at com.vaadin.server.AbstractClientConnector.fireEvent(AbstractClientConnector.java:1029)
    at com.vaadin.ui.Button.fireClick(Button.java:370)
    at com.vaadin.ui.Button$1.click(Button.java:57)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.vaadin.server.ServerRpcManager.applyInvocation(ServerRpcManager.java:155)
    at com.vaadin.server.ServerRpcManager.applyInvocation(ServerRpcManager.java:116)
    at com.vaadin.server.communication.ServerRpcHandler.handleInvocation(ServerRpcHandler.java:445)
    at com.vaadin.server.communication.ServerRpcHandler.handleInvocations(ServerRpcHandler.java:410)
    at com.vaadin.server.communication.ServerRpcHandler.handleRpc(ServerRpcHandler.java:274)
    at com.vaadin.server.communication.UidlRequestHandler.synchronizedHandleRequest(UidlRequestHandler.java:90)
    at com.vaadin.server.SynchronizedRequestHandler.handleRequest(SynchronizedRequestHandler.java:41)
    at com.vaadin.server.VaadinService.handleRequest(VaadinService.java:1464)
    at com.vaadin.server.VaadinServlet.service(VaadinServlet.java:381)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:317)
    at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:114)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:137)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:111)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:170)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:64)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:214)
    at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:177)
    at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346)
    at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:262)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:105)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:81)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:478)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:80)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:799)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:861)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1455)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:748)
</code>```

答:
The BadCredentialsException means that the user hasnt been found. There is logging in the AbstractUserDetailsAuthenticationProvider.java class at debug which will output the username.

Increase the logging and see the username that is coming through - one issue might be the charsets differing as your db is latin1 so it might be creating an issue

Body:
I have a web app that uses Spring Security. The user database is a H2 file database. Whenever Spring Security tries to authenticate correct a username/password combination it throws a BadCredentialsExcpetion. If, however, I manually execute the exact same query as Spring Security it successfully finds the user in the table.

SecurityConfiguration.java

@Configuration
@EnableWebSecurity
public class SpringConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    private DataSource dataSource;

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.jdbcAuthentication()
                .dataSource(dataSource)
                .usersByUsernameQuery("SELECT `USERNAME`, `PASSWORD`, `ENABLED` FROM `users` WHERE `USERNAME` = ?")
                .authoritiesByUsernameQuery("SELECT `USERNAME`, `AUTHORITY` FROM `authorities` WHERE `USERNAME` = ?");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
    }

}

AuthenticationServiceImpl.java

@SpringComponent
@ApplicationScope
public class AuthenticationServiceImpl implements AuthenticationService {

    private final AuthenticationManager authenticationManager;

    @Autowired
    public AuthenticationServiceImpl(AuthenticationManager authenticationManager) {
        this.authenticationManager = authenticationManager;
    }

    @Override
    public void authenticate(String user, String password) throws BadCredentialsException, AuthenticationException, IOException {
        authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(user, password));
    }

}

I have tried using MySQL instead, but it didn't change anything.

SQL Schema

CREATE TABLE `users` (
  `USERNAME` varchar(10) NOT NULL,
  `PASSWORD` varchar(60) NOT NULL,
  `ENABLED` tinyint(1) NOT NULL,
  PRIMARY KEY (`USERNAME`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

CREATE TABLE `authorities` (
  `USERNAME` varchar(10) NOT NULL,
  `AUTHORITY` varchar(10) NOT NULL,
  PRIMARY KEY (`USERNAME`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Stacktrace

org.springframework.security.authentication.BadCredentialsException: Bad credentials
    at org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider.authenticate(AbstractUserDetailsAuthenticationProvider.java:151)
    at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:174)
    at posproject17.data.AuthenticationServiceImpl.authenticate(AuthenticationServiceImpl.java:29)
    at posproject17.data.AuthenticationServiceImpl$$FastClassBySpringCGLIB$$2acc9e9c.invoke(<generated>)
    at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:738)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
    at org.springframework.aop.support.DelegatingIntroductionInterceptor.doProceed(DelegatingIntroductionInterceptor.java:133)
    at org.springframework.aop.support.DelegatingIntroductionInterceptor.invoke(DelegatingIntroductionInterceptor.java:121)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:673)
    at posproject17.data.AuthenticationServiceImpl$$EnhancerBySpringCGLIB$$d3f6b712.authenticate(<generated>)
    at posproject17.view.LoginView.lambda$init$61446b05$1(LoginView.java:49)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.vaadin.event.ListenerMethod.receiveEvent(ListenerMethod.java:510)
    at com.vaadin.event.EventRouter.fireEvent(EventRouter.java:211)
    at com.vaadin.event.EventRouter.fireEvent(EventRouter.java:174)
    at com.vaadin.server.AbstractClientConnector.fireEvent(AbstractClientConnector.java:1029)
    at com.vaadin.ui.Button.fireClick(Button.java:370)
    at com.vaadin.ui.Button$1.click(Button.java:57)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.vaadin.server.ServerRpcManager.applyInvocation(ServerRpcManager.java:155)
    at com.vaadin.server.ServerRpcManager.applyInvocation(ServerRpcManager.java:116)
    at com.vaadin.server.communication.ServerRpcHandler.handleInvocation(ServerRpcHandler.java:445)
    at com.vaadin.server.communication.ServerRpcHandler.handleInvocations(ServerRpcHandler.java:410)
    at com.vaadin.server.communication.ServerRpcHandler.handleRpc(ServerRpcHandler.java:274)
    at com.vaadin.server.communication.UidlRequestHandler.synchronizedHandleRequest(UidlRequestHandler.java:90)
    at com.vaadin.server.SynchronizedRequestHandler.handleRequest(SynchronizedRequestHandler.java:41)
    at com.vaadin.server.VaadinService.handleRequest(VaadinService.java:1464)
    at com.vaadin.server.VaadinServlet.service(VaadinServlet.java:381)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:317)
    at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:114)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:137)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:111)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:170)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:64)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:214)
    at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:177)
    at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346)
    at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:262)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:105)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:81)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:478)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:80)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:799)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:861)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1455)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:748)


问:
Sum multiple BigDecimals to a Map<String, BigDecimal>
I'm trying to sum multiple BigDecimals from a List. Currently, I'm using two streams, but would like to have only one stream if possible. I'm unsure how I can rewrite below in a performant way.

```<code>BigDecimal totalCharges = tableRowDataList.stream()
            .map(el -> el.getSums().getCharges())
            .reduce(BigDecimal.ZERO, BigDecimal::add);
BigDecimal totalFees = tableRowDataList.stream()
            .map(el -> el.getSums().getFees())
            .reduce(BigDecimal.ZERO, BigDecimal::add);
</code>```

As you can see, the streams are doing basically the same, only the call to getCharges/getFees differ.

What is the best way to get a resulting Map<String, BigDecimal> from above? (Where key would be charges/fees)

答:
If you have a list of objects List<TableRowDataElement>, each of which has a Sums object-- do you control the definition of TableRowDataElement and/or Sums?

If you create an add method in either TableRowDataElement or Sums, then you can simplify this without the need for an additional class--

```<code>Sums sums = tableRowDataList.stream()
        .map(el -> el.getSums())
        .reduce(new Sums(0,0), Sums::add);
</code>```

Body:
I'm trying to sum multiple BigDecimals from a List. Currently, I'm using two streams, but would like to have only one stream if possible. I'm unsure how I can rewrite below in a performant way.

BigDecimal totalCharges = tableRowDataList.stream()
            .map(el -> el.getSums().getCharges())
            .reduce(BigDecimal.ZERO, BigDecimal::add);
BigDecimal totalFees = tableRowDataList.stream()
            .map(el -> el.getSums().getFees())
            .reduce(BigDecimal.ZERO, BigDecimal::add);

As you can see, the streams are doing basically the same, only the call to getCharges/getFees differ.

What is the best way to get a resulting Map<String, BigDecimal> from above? (Where key would be charges/fees)

Body:
If you have a list of objects List<TableRowDataElement>, each of which has a Sums object-- do you control the definition of TableRowDataElement and/or Sums?

If you create an add method in either TableRowDataElement or Sums, then you can simplify this without the need for an additional class--

Sums sums = tableRowDataList.stream()
        .map(el -> el.getSums())
        .reduce(new Sums(0,0), Sums::add);


问:
Is there a way to tell iOS which version to put on simulator?
So I just want to test my application on an earlier version of iOS. It seems that there's no way to change the iOS version on the simulator, is there a different way to tell the simulator which iOS to run?</p>

答:
```<code>XCode --> Preferences --> Components
</code>```

This will allow you to install older versions of the simulators.  Then when you deploy from Xamarin you can pick which simulator image to use.

Body:
XCode --> Preferences --> Components

This will allow you to install older versions of the simulators.  Then when you deploy from Xamarin you can pick which simulator image to use.


问:
How to detect top legit search engine bots?
I want to develop a very robust method to detect only a few top search engines spiders such as googlebot and let them access content on my site, otherwise usual user registeration/login required to view that content.

Note that I also make use of cookies to let users access some content without being registered. So if cookies are disabled on client browser, no content except front page is offered. But I heard search engine spiders dont accept cookies so this will also shut out legitimate search engine bots. Is this correct?

One suggestion I heard is to do reverse lookup from ip address and if it resolves to for example googlebot.com, then do a forward dns lookup and if get back the original ip, then its legitimate and not some one impersonating as googlebot. I am using Java on linux server , so java based solution I am looking for.

I am only letting in top good search engine spiders such as google yahoo bing alexa etc and keep the others out to reduce server loads. But its very important top spiders index my site.

答:
Check out this site:

http://www.user-agents.org/

They also have an XML version of the database that you can download and incorporate.  They classify known "User-Agent" header identities by whether they are a Browser, Link/Server-Checker, Downloading tool, Proxy Server, Robot/Spider/Search Engine, or Spam/bad-bot.

NOTE
I have experienced a couple User-Agent strings that represent the Java runtime someone hacked together to scrape a site.  It turned out that someone was doing their own search engine scraper in that case, but it could just as well be a spider to download all your content for offsite/disconnected use.


问:
Convert character 'A' to 'B' if I add 1
Suppose you have one character/string, "A".

What do you write to convert it to 'B' if add 1 to 'A'. If I add '2' it should be converted to 'C' and so on...

答:
Furthering Sergio's answer, you can isolate the letter-ordinals and use modulo.

```<code>class String
  def plus n
    case self
    when ('a'..'z')
      (((ord - 97 + n) % 26) + 97).chr            #ord means self.ord
    when ('A'..'Z')
      (((ord - 65 + n) % 26) + 65).chr
    else
      raise "single-letters only"
    end
  end
end

'a'.plus 2 #=> 'c'
'z'.plus 1 #=> 'a'
'A'.plus 0 #=> 'A'
'Z'.plus 9 #=> 'I'
'/'.plus 1 #=> test.rb:9:in `plus': single-letters only (RuntimeError)
</code>```

Your question is unclear, but as alluded to in the comments by Stefan, you may want 'A' + 1 #=> 'B' notation. Ruby does allow an overwrite of String#+. But don't do this, this is just to show you that you can:

```<code>class String
  def +(n)
   #code as above...
  end
end
</code>```

then via syntactic sugar, you can do:

```<code>'a' + 2 #=> 'c'
'z' + 1 #=> 'a'
'A' + 0 #=> 'A'
'Z' + 9 #=> 'I'
'/' + 1 #=> test.rb:9:in `plus': single-letters only (RuntimeError)
</code>```

Title: Convert character 'A' to 'B' if I add 1

Body:
Furthering Sergio's answer, you can isolate the letter-ordinals and use modulo.

class String
  def plus n
    case self
    when ('a'..'z')
      (((ord - 97 + n) % 26) + 97).chr            #ord means self.ord
    when ('A'..'Z')
      (((ord - 65 + n) % 26) + 65).chr
    else
      raise "single-letters only"
    end
  end
end

'a'.plus 2 #=> 'c'
'z'.plus 1 #=> 'a'
'A'.plus 0 #=> 'A'
'Z'.plus 9 #=> 'I'
'/'.plus 1 #=> test.rb:9:in `plus': single-letters only (RuntimeError)

Your question is unclear, but as alluded to in the comments by Stefan, you may want 'A' + 1 #=> 'B' notation. Ruby does allow an overwrite of String#+. But don't do this, this is just to show you that you can:

class String
  def +(n)
   #code as above...
  end
end

then via syntactic sugar, you can do:

'a' + 2 #=> 'c'
'z' + 1 #=> 'a'
'A' + 0 #=> 'A'
'Z' + 9 #=> 'I'
'/' + 1 #=> test.rb:9:in `plus': single-letters only (RuntimeError)


问:
angular 4 reduce html content
I have a (grid) component witch is used many times. The problem is it is to large, and it's ~70% could be dynamically generated - I think, but there are many way to solve, which is the best?

The html file:

```<code><div class="items containerX" fxLayout="column" fxFlexFill>

    <!--Operations-->
    <div class="operations">
        <div class="mobile-operations" fxShow.xs="true" fxHide.gt-xs="true">
            <div fxLayout="row" fxFlex>
                <div fxFlex="90" class="buttons">
                    <button type="button" class="adminButton" (click)="onAdd();">
                        <span class="fa fa-plus"></span> Add
                    </button>

                    <button type="button" class="adminButton" (click)="onDelete();" [disabled]='!hasSelectedSong'>
                        <span class="fa fa-times"></span> Remove
                    </button>

                    <button type="button" class="adminButton" (click)="onEdit();" [disabled]='!hasSelectedSong'>
                        <span class="fa fa-edit"></span> Edit
                    </button>
                </div>

                <div fxFlex="10" class="buttons" (click)="searchToggle = !searchToggle;" >
                    <span class="fa fa-search fa-lg searchButton"></span>
                </div>
            </div>

            <div class="searchbar" *ngIf="searchToggle" fxFlex fxHide.gt-xs="true">
                <form [formGroup]="simpleForm" fxFlex>
                    <input class="searchfield" type="text" placeholder="..." formControlName="simple" fxFlex>
                </form>
            </div>
        </div>

        <div class="operations" fxLayout="row" fxHide.lt-sm="true">
            <div fxFlex class="buttons">
                <button type="button" class="adminButton" (click)="onAdd();">
                    <span class="fa fa-plus"></span> <span fxHide.lt-md="true"> Add</span>
                </button>

                <button type="button" class="adminButton" (click)="onDelete();" [disabled]='!hasSelectedSong'>
                    <span class="fa fa-times"></span> <span fxHide.lt-md="true"> Remove</span>
                </button>

                <button type="button" class="adminButton" (click)="onEdit();" [disabled]='!hasSelectedSong'>
                    <span class="fa fa-edit"></span> <span fxHide.lt-md="true"> Edit</span>
                </button>
            </div>

            <div fxFlex class="buttons">
                <button type="button" class="adminButton" (click)="paginator.first()">
                    <span class="fa fa-caret-left"></span>
                    <span class="fa fa-caret-left"></span>
                    <span fxHide.lt-md="true">First</span>
                </button>

                <button type="button" class="adminButton" (click)="paginator.prev()">
                    <span class="fa fa-caret-left"></span>
                    <span fxHide.lt-md="true">Prev</span>
                </button>

                <span class="page-number">{{paginator.page}}</span>

                <button type="button" class="adminButton" (click)="paginator.next()">
                    <span fxHide.lt-md="true">Next</span>
                    <span class="fa fa-caret-right"></span>
                </button>

                <button type="button" class="adminButton" (click)="paginator.last()">
                    <span fxHide.lt-md="true">Last</span>
                    <span class="fa fa-caret-right"></span>
                    <span class="fa fa-caret-right"></span>
                </button>
            </div>

            <div fxFlex class="buttons">
                <form [formGroup]="simpleForm">
                    <input class="globalSearch" type="text" placeholder="..." formControlName="simple">

                    <button type="button" (click)="onSearch();" class="searchButton">
                        <span class="fa fa-search"></span>
                    </button>
                </form>
            </div>
        </div>
    </div>

    <div class="itemView">
        <!--Header-->
        <div class="header" fxLayout="row" [ngClass.xs]="{'search-open' : searchToggle, 'mobile-header' : true}">
            <div fxFlex="100px" fxFlex.lt-sm="75px">
                <span class="fa fa-hashtag" aria-hidden="true" (click)="paginator.reset()"></span>
            </div>

            <div fxFlex>
                <div fxFlex="75px" fxHide.lt-sm="true" [ngClass]="{'sortBy' : sort == 'code'}">
                    <span class="item" (click)="onSortBy('code');">
                        Type <span *ngIf="sort == 'code'" class="fa" [ngClass]="getDirection('code')"></span>
                    </span>
                </div>

                <div fxFlex [ngClass]="{'sortBy' : sort == 'artist'}">
                    <span class="item" (click)="onSortBy('artist');">
                        Level <span *ngIf="sort == 'artist'" class="fa" [ngClass]="getDirection('artist')"></span>
                    </span>
                </div>

                <div fxFlex [ngClass]="{'sortBy' : sort == 'title'}">
                    <span class="item" (click)="onSortBy('title');">
                        Stat <span *ngIf="sort == 'title'" class="fa" [ngClass]="getDirection('title')"></span>
                    </span>
                </div>

                <div class="listLast" fxFlex="30px" fxHide.lt-sm="true"></div>
            </form>
        </div>

        <!--items-->
        <div class="items dd-list">
            <div class="item" fxLayout="row" *ngFor="let item of items; let i = index;" [ngClass.xs]="{'search-open' : searchToggle}">
                <div class="listFirst" scope="row" fxFlex="100px" fxFlex.lt-sm="75px">
                    <span fxFlex="25px" class="form-check-label adminCheckbox tools" (click)="selectItem(item._id);">
                        <i class="fa" aria-hidden="true" [ngClass]="{'fa-check-square': isSelected(item._id), 'fa-square': !isSelected(item._id)}"></i>
                    </span>

                    <span class="index" fxFlex>{{(i+1*paginator.page)}}</span>

                    <span class="tools" fxFlex="25px">
                        <a fxHide.lt-sm="true" (click)="onEdit(item._id)" class="fa fa-edit" aria-hidden="true"></a>
                    </span>
                </div>

                <div fxFlex>
                    <div class="listMiddle" fxFlex="75px" fxHide.lt-sm="true">{{item.type}}</div>
                    <div class="listMiddle artist" fxFlex title={{item.level}}>{{item.level}}</div>
                    <div class="listMiddle title" fxFlex title={{item.stats}}>{{item.stats | json}}</div>
                </div>

                <div class="tools listLast" fxFlex="30px" fxHide.lt-sm="true">
                    <a fxHide.lt-sm="true" (click)="onDelete(item._id);" class="fa fa-times " aria-hidden="true"></a>
                </div>
            </div>
        </div>
    </div>
</div>

<!--Popups-->
<popup name="removeItemAlert" type="alert">
    <div popup-body>
        Are you sure?
    </div>
</popup>
</code>```

As you can see I only have to change the columns name, search input names, items fields and dom element attributes (class, fxFlex) - to be responsive. What is the best practice (separated components, template, directive) to compress the content, but keep easily usable?

(The number fields of the item object varies).

Additional info:

Basic methods implemented in ItemsComponent, and this way I can overwrite them is required.

```<code>    import { Component, OnInit, OnDestroy } from '@angular/core';
import { Router } from '@angular/router';
import {
FormGroup,
FormControl,
Validators,
FormBuilder,
FormArray
} from "@angular/forms";

import {
    StorageService,
    SystemService,
    RequestService,
    PopupService,
    PaginatorService
} from '../_shared';

import {
    ItemsComponent
} from '../_generals';

@Component({
selector: 'app-basic-characters',
templateUrl: './basic-characters.component.html',
styleUrls: ['./basic-characters.component.scss'],
providers: [PaginatorService]
})
export class BasicCharactersComponent extends ItemsComponent implements OnInit {
    public item: string = "basicCharacters";
    public class: string = 'BasicCharactersComponent';

    constructor(
        router:  Router,

        paginator: PaginatorService,
        popup:   PopupService,
        storage: StorageService,
        request: RequestService
    ) {
        super(router, paginator, popup, storage, request);
    }

    public ngOnInit() {
        super.ngOnInit();

        // console.log('child init');
    }

    public newSearchForm(){
        return new FormGroup({
            'type': new FormControl(''),
            'level': new FormControl(''),
            'stats': new FormControl(''),
        });
    }

    public newSimpleForm(){
        return new FormGroup({
            'simple': new FormControl('')
        });
    }
}
</code>```

答:
This section of code appeared twice. As @ken mentioned before, if you have a component (for example named button-group), then you can reuse this component by defining different functions within the component.</p>

```<code>        <div fxFlex="90" class="buttons">
            <button type="button" class="adminButton" (click)="onAdd();">
                <span class="fa fa-plus"></span> Add
            </button>

            <button type="button" class="adminButton" (click)="onDelete();" [disabled]='!hasSelectedSong'>
                <span class="fa fa-times"></span> Remove
            </button>

            <button type="button" class="adminButton" (click)="onEdit();" [disabled]='!hasSelectedSong'>
                <span class="fa fa-edit"></span> Edit
            </button>
            </div>
</code>```

Title: angular 4 reduce html content

Body:
I have a (grid) component witch is used many times. The problem is it is to large, and it's ~70% could be dynamically generated - I think, but there are many way to solve, which is the best?

The html file:

                    <button type="button" class="adminButton" (click)="onAdd();">
                         Add
                    </button>

                    <button type="button" class="adminButton" (click)="onDelete();" [disabled]='!hasSelectedSong'>
                         Remove
                    </button>

                    <button type="button" class="adminButton" (click)="onEdit();" [disabled]='!hasSelectedSong'>
                         Edit
                    </button>

                <form [formGroup]="simpleForm" fxFlex>
                    <input class="searchfield" type="text" placeholder="..." formControlName="simple" fxFlex>
                </form>

                <button type="button" class="adminButton" (click)="onAdd();">
                      Add
                </button>

                <button type="button" class="adminButton" (click)="onDelete();" [disabled]='!hasSelectedSong'>
                      Remove
                </button>

                <button type="button" class="adminButton" (click)="onEdit();" [disabled]='!hasSelectedSong'>
                      Edit
                </button>

                <button type="button" class="adminButton" (click)="paginator.first()">

                    First
                </button>

                <button type="button" class="adminButton" (click)="paginator.prev()">

                    Prev
                </button>

                {{paginator.page}}

                <button type="button" class="adminButton" (click)="paginator.next()">
                    Next

                </button>

                <button type="button" class="adminButton" (click)="paginator.last()">
                    Last

                </button>

                <form [formGroup]="simpleForm">
                    <input class="globalSearch" type="text" placeholder="..." formControlName="simple">

                    <button type="button" (click)="onSearch();" class="searchButton">

                    </button>
                </form>

                        Type

                        Level

                        Stat

            </form>

                    {{(i+1*paginator.page)}}

{{item.type}}

{{item.level}}

{{item.stats | json}}

<popup name="removeItemAlert" type="alert">

        Are you sure?

</popup>

As you can see I only have to change the columns name, search input names, items fields and dom element attributes (class, fxFlex) - to be responsive. What is the best practice (separated components, template, directive) to compress the content, but keep easily usable?

(The number fields of the item object varies).

Additional info:

Basic methods implemented in ItemsComponent, and this way I can overwrite them is required.

    import { Component, OnInit, OnDestroy } from '@angular/core';
import { Router } from '@angular/router';
import {
FormGroup,
FormControl,
Validators,
FormBuilder,
FormArray
} from "@angular/forms";

import {
    StorageService,
    SystemService,
    RequestService,
    PopupService,
    PaginatorService
} from '../_shared';

import {
    ItemsComponent
} from '../_generals';

@Component({
selector: 'app-basic-characters',
templateUrl: './basic-characters.component.html',
styleUrls: ['./basic-characters.component.scss'],
providers: [PaginatorService]
})
export class BasicCharactersComponent extends ItemsComponent implements OnInit {
    public item: string = "basicCharacters";
    public class: string = 'BasicCharactersComponent';

    constructor(
        router:  Router,

        paginator: PaginatorService,
        popup:   PopupService,
        storage: StorageService,
        request: RequestService
    ) {
        super(router, paginator, popup, storage, request);
    }

    public ngOnInit() {
        super.ngOnInit();

        // console.log('child init');
    }

    public newSearchForm(){
        return new FormGroup({
            'type': new FormControl(''),
            'level': new FormControl(''),
            'stats': new FormControl(''),
        });
    }

    public newSimpleForm(){
        return new FormGroup({
            'simple': new FormControl('')
        });
    }
}

Body:
This section of code appeared twice. As @ken mentioned before, if you have a component (for example named button-group), then you can reuse this component by defining different functions within the component.

        <div fxFlex="90" class="buttons">
            <button type="button" class="adminButton" (click)="onAdd();">
                <span class="fa fa-plus"></span> Add
            </button>

            <button type="button" class="adminButton" (click)="onDelete();" [disabled]='!hasSelectedSong'>
                <span class="fa fa-times"></span> Remove
            </button>

            <button type="button" class="adminButton" (click)="onEdit();" [disabled]='!hasSelectedSong'>
                <span class="fa fa-edit"></span> Edit
            </button>
            </div>


问:
minDate and maxDate options are not working in datepicker
I'm using the "datepicker" plugin on my project, it's set to decade view, and I want to disable the future dates, for this I have used the maxDate option but it's not working, my code:

$('#data_1 .input-group.date').datepicker({
    todayBtn: "linked",
    maxDate: "0",
    keyboardNavigation: false,
    forceParse: false,
    calendarWeeks: true,
    autoclose: true
});
```

tried with 0 and new Date

答:
Note that bootstrap-datepicker has no maxDate option, you have to use endDate.

Here a working sample:

$("#datepicker").datepicker({
  todayBtn: "linked",
  endDate: new Date(),
  keyboardNavigation: false,
  forceParse: false,
  calendarWeeks: true,
  autoclose: true
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.6.4/css/bootstrap-datepicker3.css" rel="stylesheet"/>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.6.4/js/bootstrap-datepicker.js"></script>

<input type="text" class="form-control" id="datepicker"></code>```

Body:
I'm using the "datepicker" plugin on my project, it's set to decade view, and I want to disable the future dates, for this I have used the maxDate option but it's not working, my code:

$('#data_1 .input-group.date').datepicker({
    todayBtn: "linked",
    maxDate: "0",
    keyboardNavigation: false,
    forceParse: false,
    calendarWeeks: true,
    autoclose: true
});

tried with 0 and new Date

Body:
Note that bootstrap-datepicker has no maxDate option, you have to use endDate.

Here a working sample:

$("#datepicker").datepicker({
  todayBtn: "linked",
  endDate: new Date(),
  keyboardNavigation: false,
  forceParse: false,
  calendarWeeks: true,
  autoclose: true
});

<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.6.4/css/bootstrap-datepicker3.css" rel="stylesheet"/>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.6.4/js/bootstrap-datepicker.js"></script>

<input type="text" class="form-control" id="datepicker">


问:
How can i use Toplevel method?
Hi I tried to use toplevel method in tkinter and it didnt work...
What should i write to open two windows in different time in two methods, while there is method running in parallel?
the decide what method running in parallel with the receiving method... The code get stuck in the receiving method at "window = Toplevel(root)". Of course its get a message but I dont want to overflow you guys...</p>

```<code>from Tkinter import *
import threading

def decide_what(self):

    global root
    root = Tk()

    root.title("options")
    root.geometry("600x250")
    root.resizable(width=FALSE, height=FALSE)  # cant resize

    self.label = Label(root, text='CHOOSE YOUR FIRST OPTION!', font=30)
    self.label.place(x=200, y=13)

    self.button1 = Button(root, text='PrivateChat', font=30,
    command=self.private)
    self.button1.place(x=1, y=50, width=200, height=199)

    self.button2 = Button(root, text='GroupChat', font=30,
    command=self.group)
    self.button2.place(x=201, y=50, width=199, height=199)

    self.button3 = Button(root, text='BroadCast', font=30,
    command=self.broadcast)
    self.button3.place(x=400, y=50, width=200, height=199)

    self.button4 = Button(root, text='WAIT', font=30, command=self.wait)
    self.button4.place(x=500, y=10)

    root.mainloop()

def receiving_message(self):  # a function that responsible to receive a message from the server, **shes in a class**

    print "receive??????????????????"
    while True:

        data = self.sock.recv(1024)

        data = decryption(data)
        print "data", data

        if data[:2] == "Br":

            print "got into br"

            window = Toplevel(root)
            print "window V"

            window.title("BroadCastZone")
            label = Label(window, text=data)
            label.pack()
            button = Button(window, text="ok", command=window.destroy)
            button.pack()

            print data
</code>```

答: All tkinter code needs to run in the same thread. If receiving_message is running in a separate thread, it can't create an instance of Toplevel. It will need to send a message to the main thread and ask it to open a window.

Title: How can i use Toplevel method?

Body:
Hi I tried to use toplevel method in tkinter and it didnt work...
What should i write to open two windows in different time in two methods, while there is method running in parallel?
the decide what method running in parallel with the receiving method... The code get stuck in the receiving method at "window = Toplevel(root)". Of course its get a message but I dont want to overflow you guys...

from Tkinter import *
import threading

def decide_what(self):

    global root
    root = Tk()

    root.title("options")
    root.geometry("600x250")
    root.resizable(width=FALSE, height=FALSE)  # cant resize

    self.label = Label(root, text='CHOOSE YOUR FIRST OPTION!', font=30)
    self.label.place(x=200, y=13)

    self.button1 = Button(root, text='PrivateChat', font=30,
    command=self.private)
    self.button1.place(x=1, y=50, width=200, height=199)

    self.button2 = Button(root, text='GroupChat', font=30,
    command=self.group)
    self.button2.place(x=201, y=50, width=199, height=199)

    self.button3 = Button(root, text='BroadCast', font=30,
    command=self.broadcast)
    self.button3.place(x=400, y=50, width=200, height=199)

    self.button4 = Button(root, text='WAIT', font=30, command=self.wait)
    self.button4.place(x=500, y=10)

    root.mainloop()

def receiving_message(self):  # a function that responsible to receive a message from the server, **shes in a class**

    print "receive??????????????????"
    while True:

        data = self.sock.recv(1024)

        data = decryption(data)
        print "data", data

        if data[:2] == "Br":

            print "got into br"

            window = Toplevel(root)
            print "window V"

            window.title("BroadCastZone")
            label = Label(window, text=data)
            label.pack()
            button = Button(window, text="ok", command=window.destroy)
            button.pack()

            print data