问:
it is correct to use setup in unit test C#
I am explaining better, I am studying how to do unit tests in C # with NUnit and justmock. I am reading the book the art of unit tests, Here I am told that whenever possible try to avoid [SetUp] for a previous scenario configuration a try. But googling me on blog that if it's good to use these settings in [SetUp], I'm really confused,
I am aware that if the scenario is very large, the arrange of my test method grows and I have to rafactorizar, Entonce the best elaborate question would be,
When using [SetUp] or if there is some type of pattern when the scenario to test is very large and the Arrange code is affected by this, helpmee???

for example:

```<code>[TestMethod]
    [Owner("Joaquin")]
    public void Update_CorrectViewDtoAndAllowedUser_ReturnsTrue()
    {
        // Arrange
        const string userName = "johndoe";
        var viewDto = new ViewDto { Id = 1 };
        var view = new View { Id = 1 };

        var authorizationService = Mock.Create<IAuthorizationService>();
        Mock.Arrange(() => authorizationService.GetAccessLevel(viewDto.Id,userName))
            .Returns(AccessLevel.ReadWrite);

        var mapper = Mock.Create<ITypeMapperService>();
        Mock.Arrange(() => mapper.Map<View>(Arg.Is(viewDto)))
            .Returns(view);

        var viewService = Mock.Create<IViewService>();
        Mock.Arrange(() => viewService.GetById(view.Id))
            .Returns(view);

        var viewAppService = CreateViewAppService(viewService, authorizationService, mapper);

        // Act
        var result = viewAppService.Update(viewDto, userName);

        // Assert
        Assert.IsTrue(result);
    }
</code>```

Here my arrange is very extensive and I would not want to remove it for a private method or pass it to the [SetUp] there is no pattern to solve this in another way

答:
The main problem with SetUp is, that NUnit uses one instance of a TestFixture for all tests in it. Changes to the state will be available to all unit tests.

The main problem is, that unit tests have no execution order. The leftover state could break the following unit tests. Errors like that are extremely hard to find. (and may depend on your test environment. Your build server can get different test results, then your local machine).

The usage SetUp is no problem, as long you reset all changed state in TearDown.

Another alternative is to use XUnit, which does not use the same instance for all tests. The SetUp is done in the constructor, and because the class is not reused, no cleanup is needed.

EDIT: But as you stated you are reading "The art of unit testing". The book has nearly a complete chapter on this problem. And will probably explain this a lot better than me ;)

Body:
I am explaining better, I am studying how to do unit tests in C # with NUnit and justmock. I am reading the book the art of unit tests, Here I am told that whenever possible try to avoid [SetUp] for a previous scenario configuration a try. But googling me on blog that if it's good to use these settings in [SetUp], I'm really confused,
I am aware that if the scenario is very large, the arrange of my test method grows and I have to rafactorizar, Entonce the best elaborate question would be,
When using [SetUp] or if there is some type of pattern when the scenario to test is very large and the Arrange code is affected by this, helpmee???

for example:

[TestMethod]
    [Owner("Joaquin")]
    public void Update_CorrectViewDtoAndAllowedUser_ReturnsTrue()
    {
        // Arrange
        const string userName = "johndoe";
        var viewDto = new ViewDto { Id = 1 };
        var view = new View { Id = 1 };

        var authorizationService = Mock.Create<IAuthorizationService>();
        Mock.Arrange(() => authorizationService.GetAccessLevel(viewDto.Id,userName))
            .Returns(AccessLevel.ReadWrite);

        var mapper = Mock.Create<ITypeMapperService>();
        Mock.Arrange(() => mapper.Map<View>(Arg.Is(viewDto)))
            .Returns(view);

        var viewService = Mock.Create<IViewService>();
        Mock.Arrange(() => viewService.GetById(view.Id))
            .Returns(view);

        var viewAppService = CreateViewAppService(viewService, authorizationService, mapper);

        // Act
        var result = viewAppService.Update(viewDto, userName);

        // Assert
        Assert.IsTrue(result);
    }

Here my arrange is very extensive and I would not want to remove it for a private method or pass it to the [SetUp] there is no pattern to solve this in another way


来源: stackexchange

问:
Failing to see the benefit of stateless components in Redux
I'm new to React, and I made the mistake of thinking Redux is essential to writing any react app. I wrote all my components to be stateless, but I'm not really seeing the benefit:

It just feels really awkward when I have nested components catering to nested objects. At every component level, I have to pass in the all the previous indexes so the child component can update the correct value. Also, I can't even use the data passed into the FlatList because it won't be Redux aware; I have to use the data from the store.

Is this how stateless components are supposed to be written or am I doing something horribly wrong?

Example:

State structure

{
  appetizers: [...],
  desserts: [
    ...array of deserts,
    { fruits: [
      ... array of fruits,
      { name: 'apple',
       calories: 100,
      }]
    }
  ]
}
```

<p><strong>Child class</strong></p>

<pre class="lang-js prettyprint-override"><code>class Child extends Component {
  update() {
    const props = this.props;
    props.dispatch(actions.eat(props.food, props.dessertIndex, props.fruitIndex));
  }
  render(){
    const props = this.props;
    return (
      <TouchableHighlight onPress={() => this.update()}>
        <Text>{props.desserts[props.dessertIndex].fruits[props.fruitIndex]}</Text>
      </TouchableHighlight>
    )
  }
}
const mapStateToProps = state => ({ desserts: state.desserts })
export default connect(mapStateToProps)(Child);
</code>```

parent class

class Parent extends Component {
  render(){
    return (
      <FlatList
        ...props
        data={this.desserts[this.props.dessertIndex].fruits}
        renderItem={({item, index}) => (<Child food={item}, dessertIndex={this.parent}, fruitIndex={index}>)} />
    )
  }
}
const mapStateToProps = state => ({ desserts: state.desserts })
export default connect(mapStateToProps)(Parent);
```

<p><strong>grandparent class</strong></p>

<pre class="lang-js prettyprint-override"><code>class GrandParent extends Components {
  render() {
    return (
      { this.desserts.map((item, index) => {
        return <Child data={item} dessertIndex={index} />
      }) }
    )
  }
}
const mapStateToProps = state => ({ desserts: state.desserts })
export default connect(mapStateToProps)(GrandParent)
</code>```

答:
A few thoughts:

First, Redux is not essential to building a React app.  However, there are very good reasons to use Redux with React - I talked about a few of them in a post on why using Redux and React together is a good idea.

Second, I've seen a number of people say that you "should keep absolutely all your state in Redux, and only use functional components".  I completely disagree with that.  Per the Redux FAQ entry on using Redux state vs React component state, it's up to you as a developer to decide what state lives where.  In addition, per this Dan Abramov tweet, it's totally fine to use class components if you need state or lifecycle methods.

Third, it looks like your current Redux state structure is storing very nested data.  You can do that, but it's not the recommended approach.  Instead, you are encouraged to keep your state flattened and normalized as much as possible, which simplifies lookups like the ones you're dealing with.  See the Redux docs section on Structuring Reducers - Normalizing State Shape for examples.

Fourth, the best pattern for good Redux performance and simpler props management is to have many components connected to the Redux store, especially for things like list items.  You can pass in item IDs and other values as props to the connected component, and use those values in its mapState function to extract only the item that one specific component instance needs.  I've got examples of this in my post Practical Redux, Part 6: Connected Lists, Forms, and Performance, and more articles on the topic in the Redux Performance section of my React/Redux links list.

Hopefully that points you more in the right direction.  If you've got more questions, please come drop by the Reactiflux chat channels on Discord and ask!  The invite link is at https://www.reactiflux.com .

ContentLicense: CC BY-SA 3.0

Body:
I'm new to React, and I made the mistake of thinking Redux is essential to writing any react app. I wrote all my components to be stateless, but I'm not really seeing the benefit:

It just feels really awkward when I have nested components catering to nested objects. At every component level, I have to pass in the all the previous indexes so the child component can update the correct value. Also, I can't even use the data passed into the FlatList because it won't be Redux aware; I have to use the data from the store.

Is this how stateless components are supposed to be written or am I doing something horribly wrong?

Example:

State structure

{
  appetizers: [...],
  desserts: [
    ...array of deserts,
    { fruits: [
      ... array of fruits,
      { name: 'apple',
       calories: 100,
      }]
    }
  ]
}

Child class

class Child extends Component {
  update() {
    const props = this.props;
    props.dispatch(actions.eat(props.food, props.dessertIndex, props.fruitIndex));
  }
  render(){
    const props = this.props;
    return (
      <TouchableHighlight onPress={() => this.update()}>
        <Text>{props.desserts[props.dessertIndex].fruits[props.fruitIndex]}</Text>
      </TouchableHighlight>
    )
  }
}
const mapStateToProps = state => ({ desserts: state.desserts })
export default connect(mapStateToProps)(Child);

parent class

class Parent extends Component {
  render(){
    return (
      <FlatList
        ...props
        data={this.desserts[this.props.dessertIndex].fruits}
        renderItem={({item, index}) => (<Child food={item}, dessertIndex={this.parent}, fruitIndex={index}>)} />
    )
  }
}
const mapStateToProps = state => ({ desserts: state.desserts })
export default connect(mapStateToProps)(Parent);

grandparent class

class GrandParent extends Components {
  render() {
    return (
      { this.desserts.map((item, index) => {
        return <Child data={item} dessertIndex={index} />
      }) }
    )
  }
}
const mapStateToProps = state => ({ desserts: state.desserts })
export default connect(mapStateToProps)(GrandParent)


问:
Can I modify values as I classify a Perl 6 list?
The List.classify method can transform a list into a hash by some mapping that I define. The result of that mapping is the hash key and the original value

```<code>my @list = (
    <Camelia 5>,
    <Camelia 6>,
    <Camelia 7>,
    <Amelia 1>,
    <Amelia 2>,
    <Amelia 3>
    );

my %hash = @list.classify: *.[0];

say %hash;
</code>```

The hash values are lists of lists because the original thinygs it classified were lists:

```<code>{
Amelia => [(Amelia 1) (Amelia 2) (Amelia 3)],
Camelia => [(Camelia 5) (Camelia 6) (Camelia 7)]
}
</code>```

But, I'd really want this:

```<code>{
Amelia => ( 1 2 3 ),
Camelia => ( 5 6 7 )
}
</code>```

I could do some extra work, but that seems a bit too much work:

```<code>my @list = (
    <Camelia 5>,
    <Camelia 6>,
    <Camelia 7>,
    <Amelia 1>,
    <Amelia 2>,
    <Amelia 3>
    );

my %hash = @list
    .classify( *.[0] )
    .kv
    .map( {
        $^a => $^b.map: *.[*-1]
        } )
    ;

say %hash;
</code>```

答:
There's another undocumented adverb :into, which I think is mostly there to be an adapter into classify-list in Hash (although something with "list" in the method name should be in List):

```<code>my @list = (
    <Camelia 5>,
    <Camelia 6>,
    <Camelia 7>,
    <Amelia 1>,
    <Amelia 2>,
    <Amelia 3>
    );

@list.classify: *.[0], :into(my %hash), :as( *.[1] );

say %hash;
</code>```

This form of it seems to make more sense, but this is also what you get when you don't use the :into adverb. I think there are two hashes in there:

```<code> my %hash = Hash.new.classify-list: *.[0], @list, :as( *.[1] );
</code>```

Body:
The List.classify method can transform a list into a hash by some mapping that I define. The result of that mapping is the hash key and the original value

my @list = (
    <Camelia 5>,
    <Camelia 6>,
    <Camelia 7>,
    <Amelia 1>,
    <Amelia 2>,
    <Amelia 3>
    );

my %hash = @list.classify: *.[0];

say %hash;

The hash values are lists of lists because the original thinygs it classified were lists:

{
Amelia => [(Amelia 1) (Amelia 2) (Amelia 3)],
Camelia => [(Camelia 5) (Camelia 6) (Camelia 7)]
}

But, I'd really want this:

{
Amelia => ( 1 2 3 ),
Camelia => ( 5 6 7 )
}

I could do some extra work, but that seems a bit too much work:

my @list = (
    <Camelia 5>,
    <Camelia 6>,
    <Camelia 7>,
    <Amelia 1>,
    <Amelia 2>,
    <Amelia 3>
    );

my %hash = @list
    .classify( *.[0] )
    .kv
    .map( {
        $^a => $^b.map: *.[*-1]
        } )
    ;

say %hash;

Body:
There's another undocumented adverb :into, which I think is mostly there to be an adapter into classify-list in Hash (although something with "list" in the method name should be in List):

my @list = (
    <Camelia 5>,
    <Camelia 6>,
    <Camelia 7>,
    <Amelia 1>,
    <Amelia 2>,
    <Amelia 3>
    );

@list.classify: *.[0], :into(my %hash), :as( *.[1] );

say %hash;

This form of it seems to make more sense, but this is also what you get when you don't use the :into adverb. I think there are two hashes in there:

 my %hash = Hash.new.classify-list: *.[0], @list, :as( *.[1] );


问:
Use Master dataframe to aggregate regression loop using rbind
All, I'm very new to R, and can't find anything in the existing questions database that fits my exact issue. I'm running a loop of several regressions (200), and am trying to bind the results/coefficients into a single dataframe that I can export to Excel, with one set of headers.  All variables in each regression are identical.  The regression part of my loop looks like,

```<code>getreg<-OutChg~USInput
stepreg<-lm(getreg,data=mydata)
</code>```

I'm trying use a "master" dataframe to bind everything together, such as,

```<code>master<-data.frame()
master<-rbind(master,stepreg$coefficients)
</code>```

But I get the response Error in stepreg$coefficients : $ operator is invalid for atomic vectors.  Ideally, I'd like to have something where I don't even have to define master<-data.frame().

Any advice is much appreciated.  Thank you!

答:
Try using getreg <- as.formula(OutChg ~ USInput) or just put that in the for the lm() function.
If you use str(stepreg) you will probably find that it is not a list but some other data type (in this case an atomic vector).
In order to use rbind() the variable "master" has to exist (as something)

Body:
All, I'm very new to R, and can't find anything in the existing questions database that fits my exact issue. I'm running a loop of several regressions (200), and am trying to bind the results/coefficients into a single dataframe that I can export to Excel, with one set of headers.  All variables in each regression are identical.  The regression part of my loop looks like,

getreg<-OutChg~USInput
stepreg<-lm(getreg,data=mydata)

I'm trying use a "master" dataframe to bind everything together, such as,

master<-data.frame()
master<-rbind(master,stepreg$coefficients)

But I get the response Error in stepreg$coefficients : $ operator is invalid for atomic vectors.  Ideally, I'd like to have something where I don't even have to define master<-data.frame().

Any advice is much appreciated.  Thank you!


问:
Arrays and Pass-By-Reference
I am new to coding and need to know how to display the Max, Min, Avg, and the new normalized values of my array. I have the max min and avg working correctly as of now, but am very confused on how i would have my function display the proper new values of the array. The point is to use the function;
xi'=(xi-min)/(max-min)
My current code is the following:</p>

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

void normalizeMinMaxAvg(double data[], int size,double& min, double& max, double& avg)
{
    max = 0;
    min = 0;
    int sum = 0;
    int i;
    avg = 0;

    for (i = 0; i < size; i++) {
        sum += data[i];
        if ( max < data[i]) {
            max = data[i];
        }
        if (min > data[i]) {
            min = data[i];
        }
    }
    avg = sum/size;

    for (i = 0; i < size; i++){
        data[i] = (data[i]-min)/(max-min);
    }
}

int main()
{
    double data[] = {-10.0,0.0,20.0,30.0,500.0};
    double min, max, avg;

    normalizeMinMaxAvg (data, 5, min, max, avg);
    cout << "min = " << min << "\n";
    cout << "max = " << max << "\n";
    cout << "avg = " << avg << "\n";
    cout << data;
    return 0;
}
</code>```

答:
Your code is correctly updating the array values. But to display the array values properly use for loop like this:

```<code>int arrSize = sizeof(data)/sizeof(data[0]);
for(int i =0; i<arrSize; ++i)
    cout << data[i]<<" ";
</code>```

Alternatively, you can use the vector instead of a raw array like this:

```<code>vector<double> data ={-10.0,0.0,20.0,30.0,500.0};
</code>```

And pass it by reference to your function.

Title: Arrays and Pass-By-Reference

Body:
I am new to coding and need to know how to display the Max, Min, Avg, and the new normalized values of my array. I have the max min and avg working correctly as of now, but am very confused on how i would have my function display the proper new values of the array. The point is to use the function;
xi'=(xi-min)/(max-min)
My current code is the following:

#include <iostream>
using namespace std;

void normalizeMinMaxAvg(double data[], int size,double& min, double& max, double& avg)
{
    max = 0;
    min = 0;
    int sum = 0;
    int i;
    avg = 0;

    for (i = 0; i < size; i++) {
        sum += data[i];
        if ( max < data[i]) {
            max = data[i];
        }
        if (min > data[i]) {
            min = data[i];
        }
    }
    avg = sum/size;

    for (i = 0; i < size; i++){
        data[i] = (data[i]-min)/(max-min);
    }
}

int main()
{
    double data[] = {-10.0,0.0,20.0,30.0,500.0};
    double min, max, avg;

    normalizeMinMaxAvg (data, 5, min, max, avg);
    cout << "min = " << min << "\n";
    cout << "max = " << max << "\n";
    cout << "avg = " << avg << "\n";
    cout << data;
    return 0;
}

Body:
Your code is correctly updating the array values. But to display the array values properly use for loop like this:

int arrSize = sizeof(data)/sizeof(data[0]);
for(int i =0; i<arrSize; ++i)
    cout << data[i]<<" ";

Alternatively, you can use the vector instead of a raw array like this:

vector<double> data ={-10.0,0.0,20.0,30.0,500.0};

And pass it by reference to your function.


问:
Make a loop inside NodeJS Web server?
I'm doing a big project in NodeJS using Express and I wonder if I can make an infinite loop inside the server application. I think this cannot be accomplished in other languages such as Java (because it would stall the application) but I'm not sure about the JS behavior in this case.

The server application has to do two main tasks. The first one is to handle the web page (it has to listen for requests and stuff like that). The second one would be looping through a cluster  of arduinos via wifi in order to get some values. These values would be sent to the web page using socket.io.

So, the question is: is it possible for the server to do two tasks at the same time? I imagine the requests sent from the web page to the server as events that would stop the loop iteration, and once they are answered the loop continues.

Sorry for my bad english. Thanks in advance!

答:
You could use setInterval and clearInterval to start and stop the loop.

const interval = setInterval(() => console.log('loop'), 1000);
setTimeout(() => clearInterval(interval), 100000);```
</div>
</div>
</p>

<p>Other approach (here you may dynamically change the interval if you like):</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let counter = 0;
const task = () => {
  console.log('loop');
  counter++;
  setTimeout(() => counter < 10? task() : void 0, 1000);
};
task();</code>```

Title: Make a loop inside NodeJS Web server?

Body:
You could use setInterval and clearInterval to start and stop the loop.

const interval = setInterval(() => console.log('loop'), 1000);
setTimeout(() => clearInterval(interval), 100000);

Other approach (here you may dynamically change the interval if you like):

let counter = 0;
const task = () => {
  console.log('loop');
  counter++;
  setTimeout(() => counter < 10? task() : void 0, 1000);
};
task();


问:
Java lambda expression passing method argument in lambda expression
I am trying to use lambda expression in my code but i am getting an error.

```<code>public static method getInstance(List<String> a, List<String> b, String c){

    result = (a, b, c) -> createConnection(a, b, c);

}
</code>```

i am getting an error like a,b,c are already used and other error is that its expecting java util list but getting lambda paramter.

答:
the code snippets has reported errors is resonable since it is just a part of lambda expression in JLS, you have duplicated parameter names both in method and lambda expression.

It is a compile-time error if a receiver parameter (§8.4.1) appears in the FormalParameters of a lambda expression.

```<code>public static method getInstance(List<String> a, List<String> b, String c){
     // duplicated parameter names   --->     |               |         |
                                    result = (a,              b,        c) ->
                                             createConnection(a, b, c);

}
</code>```

you should rename the parameter names in labmda expression or in the method signature, for example:

```<code>public static method getInstance(List<String> a, List<String> b, String c){

    result = (a2, b2, c2) -> createConnection(a2, b2, c2);

}
</code>```

Body:
I am trying to use lambda expression in my code but i am getting an error.

public static method getInstance(List<String> a, List<String> b, String c){

    result = (a, b, c) -> createConnection(a, b, c);

}

i am getting an error like a,b,c are already used and other error is that its expecting java util list but getting lambda paramter.

Body:
the code snippets has reported errors is resonable since it is just a part of lambda expression in JLS, you have duplicated parameter names both in method and lambda expression.

It is a compile-time error if a receiver parameter (§8.4.1) appears in the FormalParameters of a lambda expression.

public static method getInstance(List<String> a, List<String> b, String c){
     // duplicated parameter names   --->     |               |         |
                                    result = (a,              b,        c) ->
                                             createConnection(a, b, c);

}

you should rename the parameter names in labmda expression or in the method signature, for example:

public static method getInstance(List<String> a, List<String> b, String c){

    result = (a2, b2, c2) -> createConnection(a2, b2, c2);

}


问:
Is there a tool for converting VB to a scripting language, e.g. Python or Ruby?
I've discovered VB2Py, but it's been silent for almost 5 years. Are there any other tools out there which could be used to convert VB6 projects to Python, Ruby, Tcl, whatever?</p>

答:
I doubt there would be a good solution for that since VB6 relies too much on the windows API and VBRun libraries though you could translate code that does something else besides GUI operations

Is there something special you need to do with that code? You could compile your VB6 functionality and expose it as a COM object and connect it to python with IronPython or IronRuby which are Python and Ruby implementations in .Net thus, allowing you to access .Net functionality although im not quite sure if COM exposed objects are easily pluggable to those interpreters.

Maybe if you explain a bit more what you want to do you would get a wiser response.

OwnerDisplayName: boost

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Gustavo Rubio


问:
Pros and Cons of Multi-value Databases
I've just started a new job where I'm going to have to do a fair amount of work with a multi-value database (UniVerse). What little database experience I have is in relational databases (SqlServer) and I'm looking for some un-biased information about what the pros and cons of a MVD are compared to relational databases.

Everyone in the office either comes from a relational database background (and hates UniVerse) or has been here for years and loves it.

答:
First, a disclaimer. I work with UniData (the sister DB of UniVerse) and occasionally blog on it, so I cannot claim to be completely unbiased; I will try, however.

Here are some points of consideration for you:

A big difference between an SQL DB and a Multivalue DB is that the MVDB does not adhere to 1NF. This has pros and cons to it. It can be (and commonly is) abused, but there are times when it can be extremely functional. The biggest benefit is that it means you don't always need a join table which can make certain queries much faster.

It stores meta-data in a completely novel manner when compared to regular SQL DBs. Each file/table does not have a concrete schema. Instead, it has 1 or more 'dictionary' files which is made up of records that tell you how the data should be interpreted. This allows you to have not only store multiple interpretations of the data (raw/uppercase/lowercase, combined fields, etc) but also allows you to perform the equivalent of enums and joins. It can be extremely powerful if done right.

Sadly, although the concept has much potential, the DBMS's toolset is lacking. Development is driven but a extremely small set of businesses cases that appear to be driven by a 'keep-the-lights-on' mentality of existing & aging software systems that were built on it. Although it has tools for integration (such as .NET connectors, ODBC interface for SQL queries, etc) they do have issues. For example, the UniObjects .NET interface lacks any granulation in security (basically all or nothing).

It isn't just a DBMS, but is essentially an entire application platform. Even though UniBasic isn't as powerful as say a .NET based language, it sure beats the pants off T-SQL and has a fast turn around for pumping out business rules.

Title: Pros and Cons of Multi-value Databases


问:
select query to display result and the parameter that got the result when using OR clause in where (Oracle)
I have a query

```<code>select columnX from tableA
  where (columnY like '%string1%' or columnY like '%string2%');
</code>```

but I also want to know what parameter (string1 or string2) got matched because of which I got my result, so I modify my query to

```<code>  select columnX value,'string1' pattern from tableA
  where columnY like '%string1%'
  union
  select columnX,'string2' from tableA
  where columnY like '%string2%'
</code>```

This gives me my result but makes the query huge (as I have hundreds of patterns to match against so basically I write the entire query for each parameter), I highly doubt this would be the best way to do this, is there some other way to do this where I do not have to write a new query for all the patterns that I want to match ?
Can this be done by simply modifying the query or will I have to use any advanced construct of Oracle SQL to perform what I need ?

答:
```<code>SELECT columnX,
CASE
    WHEN columnY like '%string1%' THEN 'string1'
    WHEN columnY like '%string2%' THEN 'string2'
    ELSE NULL
END AS pattern
FROM tableA
WHERE (columnY like '%string1%' or columnY like '%string2%');
</code>```

Edit: you can also use ISNULL('string1','value you want') if value of 'string1' and 'string2' can possibly be null

Body:
I have a query

select columnX from tableA
  where (columnY like '%string1%' or columnY like '%string2%');

but I also want to know what parameter (string1 or string2) got matched because of which I got my result, so I modify my query to

  select columnX value,'string1' pattern from tableA
  where columnY like '%string1%'
  union
  select columnX,'string2' from tableA
  where columnY like '%string2%'

This gives me my result but makes the query huge (as I have hundreds of patterns to match against so basically I write the entire query for each parameter), I highly doubt this would be the best way to do this, is there some other way to do this where I do not have to write a new query for all the patterns that I want to match ?
Can this be done by simply modifying the query or will I have to use any advanced construct of Oracle SQL to perform what I need ?

Body:
SELECT columnX,
CASE
    WHEN columnY like '%string1%' THEN 'string1'
    WHEN columnY like '%string2%' THEN 'string2'
    ELSE NULL
END AS pattern
FROM tableA
WHERE (columnY like '%string1%' or columnY like '%string2%');

Edit: you can also use ISNULL('string1','value you want') if value of 'string1' and 'string2' can possibly be null


答:
If you want to "print out" your array you need to iterate over each member as you have already done several times:

```<code>for (int i = 0; i < array_size; i++){
    cout << data[i] << "\n";
}
</code>```

What you are doing currently:

```<code>cout << data;
</code>```

Will simply print the address of the array.

Title: Arrays and Pass-By-Reference

Body:
If you want to "print out" your array you need to iterate over each member as you have already done several times:

for (int i = 0; i < array_size; i++){
    cout << data[i] << "\n";
}

What you are doing currently:

cout << data;

Will simply print the address of the array.


问:
How can I make a macro to copy an entire column but change a single row number?
I have inherited a poorly designed workbook, and I am trying to make it work a bit better without starting from scratch.
The last problem I have is that I have a formula in a column that I need to copy to the next column, but change the row number referenced in the formula. The easiest thing to do would be to change the format of the workbook but that will cause an uprising by the users.

```<code>=IF((CommaSeparatedListContains(RTM!$I$8,ROW()-2))=TRUE,"X","")
</code>```

The code above is what I need to copy, but I need to change it so that it looks at I9 instead of I8. RTM is the name of the sheet that the cell is on, and CommaSeparatedListContains is a macro that will return true if the referenced cell has a value (ROW()-2) in the comma delimited list.
Basically I need a macro to add a new column to the worksheet that works like the others, so that the end users who don't know how to use Excel can just click a button and add a column.
For example, that code is in cell A1, and I need to move it to B1 keeping the I the same but increment the row number. If I remove Both $ signs it would change it to J8, if I have $I8 it stays I8, and if I have $I$8 it stays I8.

答:
Thanks for re-affirming my understanding.  I'll give this a shot with providing some code, based on your string:

```<code>Dim LC as Long, i as Integer

Columns(9).Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
Cells(1,10).Value="" 'Add your header

LC = Cells(1, Columns.Count).End(xlToLeft).Column
i = LC-1 'See description below code

Range("J2:J100").Formula="=IF((CommaSeparatedListContains(RTM!$I$" & i & ",ROW()-2))=TRUE,""X"","""")"
</code>```

For i, you want to ensure that you substract the correct number... given the example of I8 being the cell you want to reference, and assuming that Column I is the last column of your sheet, then the 9th column, 8th row, is the cell you want to reference.  So, the variable i = last column - 1, in this example.

In this case, the column is always added to the right of column I, the assumed last column in the sheet.

One other assumption is that you're using rows 2 to 100 for the range that you have the formula... So, Range("J2:J100").Formula will be affected by your actual range for the formula.

Body:
I have inherited a poorly designed workbook, and I am trying to make it work a bit better without starting from scratch.
The last problem I have is that I have a formula in a column that I need to copy to the next column, but change the row number referenced in the formula. The easiest thing to do would be to change the format of the workbook but that will cause an uprising by the users.

=IF((CommaSeparatedListContains(RTM!$I$8,ROW()-2))=TRUE,"X","")

The code above is what I need to copy, but I need to change it so that it looks at I9 instead of I8. RTM is the name of the sheet that the cell is on, and CommaSeparatedListContains is a macro that will return true if the referenced cell has a value (ROW()-2) in the comma delimited list.
Basically I need a macro to add a new column to the worksheet that works like the others, so that the end users who don't know how to use Excel can just click a button and add a column.
For example, that code is in cell A1, and I need to move it to B1 keeping the I the same but increment the row number. If I remove Both $ signs it would change it to J8, if I have $I8 it stays I8, and if I have $I$8 it stays I8.

Body:
Thanks for re-affirming my understanding.  I'll give this a shot with providing some code, based on your string:

Dim LC as Long, i as Integer

Columns(9).Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
Cells(1,10).Value="" 'Add your header

LC = Cells(1, Columns.Count).End(xlToLeft).Column
i = LC-1 'See description below code

Range("J2:J100").Formula="=IF((CommaSeparatedListContains(RTM!$I$" & i & ",ROW()-2))=TRUE,""X"","""")"

For i, you want to ensure that you substract the correct number... given the example of I8 being the cell you want to reference, and assuming that Column I is the last column of your sheet, then the 9th column, 8th row, is the cell you want to reference.  So, the variable i = last column - 1, in this example.

In this case, the column is always added to the right of column I, the assumed last column in the sheet.

One other assumption is that you're using rows 2 to 100 for the range that you have the formula... So, Range("J2:J100").Formula will be affected by your actual range for the formula.


问:
Failed prop type: Invalid prop `params` of type `object` supplied to `SignUp`, expected `array`
I am getting this proptype validation error "Invalid prop" if I set it to receive array then It will show expected array but receive object and in other case same error expected function but receive object.
In (signupData : PropTypes.object || PropTypes.array) this warning
 related to if I set PropTypes for only Object then error
 is " Invalid prop params of type object" and
if set PropTypes for Array then error is " Invalid prop
params of type object". any body have solution?

```<code>     import React,{PropTypes} from 'react';
     import { connect } from "react-redux";
     import * as AuthAction from "../../actions/authActions";
     import * as step2DataActions from "../../actions/step2DataActions";
     import update from 'react-addons-update';

 class SIGNUP extends React.Component{
 constructor(props){
      super(props);

 this.state = {
      teacherId:props.signupData.teacherId,
      data: props.signupData.step4.data,

      endTime: props.signupData.step4.endTime,
      head: props.signupData.step4.head,
      errorInput:'',
      errorField: '',
      valid: true,
      };
      }

      submitStepSignupForm(){
      let step3 = {single_classes:false,multiple_classes:true};
      let step4 =      {head:this.state.head,startTime:this.state.startTime,endTime:this.state.endTime,data:this.state.data};
      let submitData = {};
      submitData['teacher_id'] = this.state.teacherId;
      submitData['firstname'] = this.props.signupData.firstname;
      submitData['lastname'] = this.props.signupData.lastname;
      submitData['state'] = this.props.signupData.State;
      submitData['zipcode'] = this.props.signupData.zipcode;
      submitData['prefix'] = this.props.signupData.prefix;
      submitData['step2'] = this.props.step2Data;
      submitData['step3'] = step3;
      submitData['step4'] = step4;
      this.props.signupStep4(submitData);
      }
      closeModal(){
      this.props.scheduleData.dataExist = false;
      }

      render(){
      let tableStyle = {
           align:"center"
      };
      let list = this.state.data.map((p,index) =>{
           return (
                <tr className="grey2" key={index}>
                     {Object.keys(p).filter(k => k !== 'id').map(k => {
                           return (<td className="grey1" key={p.id+''+k}><div suppressContentEditableWarning="true" contentEditable="true"
                          value={k} onInput={this.editColumn.bind(this,{p},{k})}>{p[k]}</div></td>);
                     })}
                </tr>
           );
      });

      let startList = null;
      startList = this.state.startTime.map((obj,index)=>{
           let keyName = Object.keys(obj)[0];
           return(
                <td className="" key={index}><TimePicker start="08:00" end="18:00" step={1} name="C1StartTime" value={obj.StartTime} onChange={this.changeStartTime.bind(this,index,keyName)} /></td>
           );
      });

      let endList = null;
      endList = this.state.endTime.map((obj,index)=>{
           let keyName = Object.keys(obj)[0];
           return(
                <td className="" key={index}><TimePicker start="08:00" end="18:00" step={1} value={obj.EndTime} onChange={this.changeEndTime.bind(this,index,keyName)} /></td>
           );
      });

      let head = null;
      head = this.state.head.map((obj,index)=>{
           return (
                <td className="grey1" key={index}>{obj['class']}</td>
           );
      });

      return (
           <fieldset className="step-4">
                <div className="heading">
                     <h3>Tell us about your schedule</h3>
                     {/*<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit </p>*/}
                </div>
                <div className="schedule table-responsive">
                     <table cellSpacing="3" id="mytable" style={tableStyle}>
                          <tbody>
                               <tr className="grey2" >
                                    {head}
                               </tr>
                               <tr className="grey2" >
                                    <td className="">Start Time</td>
                                    {startList}
                               </tr>
                               <tr className="grey2" >
                                    <td className="">End Time</td>
                                         {endList}
                               </tr>

                               {list}</tbody>
                     </table>
                     <p><a id="add_row" className="btn btn-default" onClick={this.appendColumn}>Add +</a>
                     <a id="add_row" className="btn btn-default" onClick={this.removeColumn}>Remove -</a>
                     <span className="inputError" >{this.state.errorInput}</span>
                     <span className="inputError" >{this.state.errorField}</span>
                </p>
                </div>
                <input type="button" name="previous" className="previous pre-btn action-button" value="Previous" />
                {(this.state.valid)?(<input type="submit" name="submit" className="submit1 action-button1" value="Submit" onClick={this.submitStepSignupForm.bind(this)}/>):(<input type="submit"  name="submit" className="disable-step4" value="Submit"  />)}
           </fieldset>
      );
      }
      }
      STEP4SIGNUP.propTypes = {
       signupData : PropTypes.object || PropTypes.array,
       getSchedule : PropTypes.object || PropTypes.array,
       step2Data : PropTypes.object || PropTypes.array,
       scheduleData : PropTypes.object || PropTypes.array,
       signupStep4 : PropTypes.func
      };
      const mapStateToProps = (state) => {
       return {
        user: state,
        step2Data: state.step2Data.step2Data,
        scheduleData: state.step2Data.scheduleData,
        step4Data: state.step4Reducer.step4
      };
     };
     const mapDispatchToProps = (dispatch) => {
      return {
           signupStep4: submitData =>       dispatch(AuthAction.signupStep4(submitData)),
           getSchedule: (teacher_id) => dispatch(step2DataActions.getSchedule(teacher_id)),
 };
 };

    export default connect(mapStateToProps,mapDispatchToProps)(STEP4SIGNUP);
</code>```

答:
when you write signupData : PropTypes.object || PropTypes.array you're basically saying

```<code>if(PropTypes.object){
   return PropTypes.object;
} else {
   return PropTypes.array;
}
</code>```

in other words, since PropTypes.object will always evaluate to true you're declaring your prop as PropTypes.object all the time.

if you want to validate a prop against more than one type, use oneOfType

```<code>  // An object that could be one of many types
  optionalUnion: PropTypes.oneOfType([
    PropTypes.string,
    PropTypes.number,
    PropTypes.instanceOf(Message)
  ])
</code>```

Body:
I am getting this proptype validation error "Invalid prop" if I set it to receive array then It will show expected array but receive object and in other case same error expected function but receive object.
In (signupData : PropTypes.object || PropTypes.array) this warning
 related to if I set PropTypes for only Object then error
 is " Invalid prop params of type object" and
if set PropTypes for Array then error is " Invalid prop
params of type object". any body have solution?

     import React,{PropTypes} from 'react';
     import { connect } from "react-redux";
     import * as AuthAction from "../../actions/authActions";
     import * as step2DataActions from "../../actions/step2DataActions";
     import update from 'react-addons-update';

 class SIGNUP extends React.Component{
 constructor(props){
      super(props);

 this.state = {
      teacherId:props.signupData.teacherId,
      data: props.signupData.step4.data,

      endTime: props.signupData.step4.endTime,
      head: props.signupData.step4.head,
      errorInput:'',
      errorField: '',
      valid: true,
      };
      }

      submitStepSignupForm(){
      let step3 = {single_classes:false,multiple_classes:true};
      let step4 =      {head:this.state.head,startTime:this.state.startTime,endTime:this.state.endTime,data:this.state.data};
      let submitData = {};
      submitData['teacher_id'] = this.state.teacherId;
      submitData['firstname'] = this.props.signupData.firstname;
      submitData['lastname'] = this.props.signupData.lastname;
      submitData['state'] = this.props.signupData.State;
      submitData['zipcode'] = this.props.signupData.zipcode;
      submitData['prefix'] = this.props.signupData.prefix;
      submitData['step2'] = this.props.step2Data;
      submitData['step3'] = step3;
      submitData['step4'] = step4;
      this.props.signupStep4(submitData);
      }
      closeModal(){
      this.props.scheduleData.dataExist = false;
      }

      render(){
      let tableStyle = {
           align:"center"
      };
      let list = this.state.data.map((p,index) =>{
           return (

                     {Object.keys(p).filter(k => k !== 'id').map(k => {
                           return (
{p[k]}
	);
                     })}

           );
      });

      let startList = null;
      startList = this.state.startTime.map((obj,index)=>{
           let keyName = Object.keys(obj)[0];
           return(
                <TimePicker start="08:00" end="18:00" step={1} name="C1StartTime" value={obj.StartTime} onChange={this.changeStartTime.bind(this,index,keyName)} />
           );
      });

      let endList = null;
      endList = this.state.endTime.map((obj,index)=>{
           let keyName = Object.keys(obj)[0];
           return(
                <TimePicker start="08:00" end="18:00" step={1} value={obj.EndTime} onChange={this.changeEndTime.bind(this,index,keyName)} />
           );
      });

      let head = null;
      head = this.state.head.map((obj,index)=>{
           return (
                {obj['class']}
           );
      });

      return (
           <fieldset className="step-4">

Tell us about your schedule

                     {/*
Lorem ipsum dolor sit amet, consectetur adipisicing elit
*/}

                                    {head}

                                    Start Time
                                    {startList}

                                    End Time
                                         {endList}

                               {list}

Add +
                     Remove -
                     {this.state.errorInput}
                     {this.state.errorField}

                <input type="button" name="previous" className="previous pre-btn action-button" value="Previous" />
                {(this.state.valid)?(<input type="submit" name="submit" className="submit1 action-button1" value="Submit" onClick={this.submitStepSignupForm.bind(this)}/>):(<input type="submit"  name="submit" className="disable-step4" value="Submit"  />)}
           </fieldset>
      );
      }
      }
      STEP4SIGNUP.propTypes = {
       signupData : PropTypes.object || PropTypes.array,
       getSchedule : PropTypes.object || PropTypes.array,
       step2Data : PropTypes.object || PropTypes.array,
       scheduleData : PropTypes.object || PropTypes.array,
       signupStep4 : PropTypes.func
      };
      const mapStateToProps = (state) => {
       return {
        user: state,
        step2Data: state.step2Data.step2Data,
        scheduleData: state.step2Data.scheduleData,
        step4Data: state.step4Reducer.step4
      };
     };
     const mapDispatchToProps = (dispatch) => {
      return {
           signupStep4: submitData =>       dispatch(AuthAction.signupStep4(submitData)),
           getSchedule: (teacher_id) => dispatch(step2DataActions.getSchedule(teacher_id)),
 };
 };

    export default connect(mapStateToProps,mapDispatchToProps)(STEP4SIGNUP);

Body:
when you write signupData : PropTypes.object || PropTypes.array you're basically saying

if(PropTypes.object){
   return PropTypes.object;
} else {
   return PropTypes.array;
}

in other words, since PropTypes.object will always evaluate to true you're declaring your prop as PropTypes.object all the time.

if you want to validate a prop against more than one type, use oneOfType

  // An object that could be one of many types
  optionalUnion: PropTypes.oneOfType([
    PropTypes.string,
    PropTypes.number,
    PropTypes.instanceOf(Message)
  ])


问:
WAR Spring JAVA file is too small
I already export spring java to war and war size is around 20 mb and when I put dependency boot spring and then I export to war again, the size war just around 20 kb, when I remove the spring boot dependency and I export again, still just around 20 kb. So, when I deploy to tomcat, the method not found.

How to fix this problem?

my pom.xml

```<code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.project.spring</groupId>
    <artifactId>TaspenNCBSpring</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>TaspenNCBSpring Maven Webapp</name>
    <url>http://maven.apache.org</url>

    <properties>
        <java-version>1.8</java-version>
        <jersey.version>1.8</jersey.version>
        <org.springframework-version>4.3.7.RELEASE</org.springframework-version>
        <jackson.version>2.7.5</jackson.version>
        <jaxb-api.version>2.2.11</jaxb-api.version>
        <hibernate.version>4.3.11.Final</hibernate.version>
        <slf4j.version>1.7.21</slf4j.version>
        <tomcat.version>9.0.0</tomcat.version>
    </properties>

    <repositories>
        <repository>
            <id>java.net2</id>
            <name>Repository hosting the jee6 artifacts</name>
            <url>http://download.java.net/maven/2</url>
        </repository>
    </repositories>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.8.2</version>
            <scope>test</scope>
        </dependency>

        <!-- Jersey -->
        <dependency>
            <groupId>com.sun.jersey.contribs</groupId>
            <artifactId>jersey-multipart</artifactId>
            <version>1.8</version>
        </dependency>

        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-servlet</artifactId>
            <version>1.19.3</version>
        </dependency>

        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-core</artifactId>
            <version>${jersey.version}</version>
        </dependency>

        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-server</artifactId>
            <version>${jersey.version}</version>
        </dependency>

        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-json</artifactId>
            <version>${jersey.version}</version>
        </dependency>

        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-client</artifactId>
            <version>${jersey.version}</version>
        </dependency>

        <!-- Hibernate Validator -->
        <dependency>
            <groupId>javax.validation</groupId>
            <artifactId>validation-api</artifactId>
            <version>1.1.0.Final</version>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>5.4.1.Final</version>
        </dependency>

        <!-- Spring -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${org.springframework-version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${org.springframework-version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${org.springframework-version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>${org.springframework-version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>${org.springframework-version}</version>
        </dependency>

        <!-- Servlet+JSP+JSTL -->

        <dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-web-api</artifactId>
            <version>6.0</version>
            <scope>provided</scope>
        </dependency>

        <!-- JSON -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.8.7</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.8.7</version>
        </dependency>

        <!-- Dependency untuk mysql -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.9</version>
        </dependency>

        <!-- Hibernate -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>${hibernate.version}</version>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-simple</artifactId>
            <version>${slf4j.version}</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>${slf4j.version}</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>jul-to-slf4j</artifactId>
            <version>${slf4j.version}</version>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>${slf4j.version}</version>
        </dependency>

        <!-- Swagger -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.6.1</version>
            <scope>compile</scope>
        </dependency>

        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.6.1</version>
            <scope>compile</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-core</artifactId>
            <version>4.2.2.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-config</artifactId>
            <version>4.2.2.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-web</artifactId>
            <version>4.2.2.RELEASE</version>
        </dependency>

    </dependencies>
    <build>
        <finalName>TaspenNCBSpring</finalName>
        <pluginManagement>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.6.1</version>
                    <configuration>
                        <source>1.8</source>
                        <target>1.8</target>
                    </configuration>
                </plugin>

                <plugin>
                    <groupId>org.apache.tomcat.maven</groupId>
                    <artifactId>tomcat7-maven-plugin</artifactId>
                    <version>2.2</version>
                    <configuration>
                        <port>8085</port>
                        <path>/TaspenNCBSpring</path>
                    </configuration>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>
</project>
</code>```

答:
ADD below code into your pom</p>

```<code><build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

<repositories>
    <repository>
        <id>spring-snapshots</id>
        <name>Spring Snapshots</name>
        <url>http://repo.springsource.org/snapshot</url>
        <snapshots>
            <enabled>true</enabled>
        </snapshots>
    </repository>
    <repository>
        <id>spring-milestones</id>
        <name>Spring Milestones</name>
        <url>http://repo.springsource.org/milestone</url>
        <snapshots>
            <enabled>false</enabled>
        </snapshots>
    </repository>
</repositories>
<pluginRepositories>
    <pluginRepository>
        <id>spring-snapshots</id>
        <name>Spring Snapshots</name>
        <url>http://repo.springsource.org/snapshot</url>
        <snapshots>
            <enabled>true</enabled>
        </snapshots>
    </pluginRepository>
    <pluginRepository>
        <id>spring-milestones</id>
        <name>Spring Milestones</name>
        <url>http://repo.springsource.org/milestone</url>
        <snapshots>
            <enabled>false</enabled>
        </snapshots>
    </pluginRepository>
</pluginRepositories>
</code>```

Title: WAR Spring JAVA file is too small

Body:
I already export spring java to war and war size is around 20 mb and when I put dependency boot spring and then I export to war again, the size war just around 20 kb, when I remove the spring boot dependency and I export again, still just around 20 kb. So, when I deploy to tomcat, the method not found.

How to fix this problem?

my pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.project.spring</groupId>
    <artifactId>TaspenNCBSpring</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>TaspenNCBSpring Maven Webapp</name>
    <url>http://maven.apache.org</url>

    <properties>
        <java-version>1.8</java-version>
        <jersey.version>1.8</jersey.version>
        <org.springframework-version>4.3.7.RELEASE</org.springframework-version>
        <jackson.version>2.7.5</jackson.version>
        <jaxb-api.version>2.2.11</jaxb-api.version>
        <hibernate.version>4.3.11.Final</hibernate.version>
        <slf4j.version>1.7.21</slf4j.version>
        <tomcat.version>9.0.0</tomcat.version>
    </properties>

    <repositories>
        <repository>
            <id>java.net2</id>
            <name>Repository hosting the jee6 artifacts</name>
            <url>http://download.java.net/maven/2</url>
        </repository>
    </repositories>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.8.2</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>com.sun.jersey.contribs</groupId>
            <artifactId>jersey-multipart</artifactId>
            <version>1.8</version>
        </dependency>

        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-servlet</artifactId>
            <version>1.19.3</version>
        </dependency>

        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-core</artifactId>
            <version>${jersey.version}</version>
        </dependency>

        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-server</artifactId>
            <version>${jersey.version}</version>
        </dependency>

        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-json</artifactId>
            <version>${jersey.version}</version>
        </dependency>

        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-client</artifactId>
            <version>${jersey.version}</version>
        </dependency>

        <dependency>
            <groupId>javax.validation</groupId>
            <artifactId>validation-api</artifactId>
            <version>1.1.0.Final</version>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>5.4.1.Final</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${org.springframework-version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${org.springframework-version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${org.springframework-version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>${org.springframework-version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>${org.springframework-version}</version>
        </dependency>

        <dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-web-api</artifactId>
            <version>6.0</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.8.7</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.8.7</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.9</version>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>${hibernate.version}</version>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-simple</artifactId>
            <version>${slf4j.version}</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>${slf4j.version}</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>jul-to-slf4j</artifactId>
            <version>${slf4j.version}</version>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>${slf4j.version}</version>
        </dependency>

        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.6.1</version>
            <scope>compile</scope>
        </dependency>

        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.6.1</version>
            <scope>compile</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-core</artifactId>
            <version>4.2.2.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-config</artifactId>
            <version>4.2.2.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-web</artifactId>
            <version>4.2.2.RELEASE</version>
        </dependency>

    </dependencies>
    <build>
        <finalName>TaspenNCBSpring</finalName>
        <pluginManagement>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.6.1</version>
                    <configuration>
                        <source>1.8</source>
                        <target>1.8</target>
                    </configuration>
                </plugin>

                <plugin>
                    <groupId>org.apache.tomcat.maven</groupId>
                    <artifactId>tomcat7-maven-plugin</artifactId>
                    <version>2.2</version>
                    <configuration>
                        <port>8085</port>
                        <path>/TaspenNCBSpring</path>
                    </configuration>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>
</project>

Body:
ADD below code into your pom

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

<repositories>
    <repository>
        <id>spring-snapshots</id>
        <name>Spring Snapshots</name>
        <url>http://repo.springsource.org/snapshot</url>
        <snapshots>
            <enabled>true</enabled>
        </snapshots>
    </repository>
    <repository>
        <id>spring-milestones</id>
        <name>Spring Milestones</name>
        <url>http://repo.springsource.org/milestone</url>
        <snapshots>
            <enabled>false</enabled>
        </snapshots>
    </repository>
</repositories>
<pluginRepositories>
    <pluginRepository>
        <id>spring-snapshots</id>
        <name>Spring Snapshots</name>
        <url>http://repo.springsource.org/snapshot</url>
        <snapshots>
            <enabled>true</enabled>
        </snapshots>
    </pluginRepository>
    <pluginRepository>
        <id>spring-milestones</id>
        <name>Spring Milestones</name>
        <url>http://repo.springsource.org/milestone</url>
        <snapshots>
            <enabled>false</enabled>
        </snapshots>
    </pluginRepository>
</pluginRepositories>


问:
addClass on hover for multiple items
So I've been working on this script all day and all the examples I've seen just don't seem to do what I want. Here's my example CodePen. Try to hover over "MENUS" and over "SETTINGS". I'll try to explain the problem with words:

The Script:

```<code>var activeItem = $("#menu .active");
var items = $("#menu .main:not(.active)");

activeItem.addClass("active-2");

items.hover(function () {
    "use strict";
    activeItem.toggleClass("active-2");
});

$(document).mousemove(function (event) {
    "use strict";
    if ($(".sub-1").css("background-clip").toLowerCase() == "content-box") {
        $(".sub-1").parents(".main").addClass("active-2");
        $(".sub-1").parents(".main").css("background-color", "#CCC");
    } else {
        $(".sub-1").parents(".main").removeClass("active-2");
        $(".sub-1").parents(".main").css("background-color", "");
    }
});
</code>```

The above code gives the blue line (class active-2) to the active item. In this case "HOME". The items variable counts all main menu items that are not active and is used to toggle blue line (active-2) from "HOME" when other items are hovered. So far so good.

The Problem:

I have submenu items (the dark-grey ones). When the mouse is anywhere over these submenu items I want to give the parent main item the blue line (active-2) until the mouse leaves, then return the blue line to the currently active item activeItem, in this case "HOME".

When there is only 1 subitem group (like the one under "MENUS"), it works. But when I added a second submenu group (under "SETTINGS") it broke. I'm looking for a way to make it so no matter how many submenu groups I have the main item's blue line should be visible when my mouse is over it's submenu items and return to activeItem when I'm no longer hovering it. If you delete one of the uls with class .sub-1 under "MENUS" or "SETTINGS" with the inspector it will start working again.

Why mousemove???

I tried to .addClass in .hover and .removeClass in it's callback function but that didn't work... Or maybe I'm just not doing it right? So basically the only way I could think of achieving this effect was with mousemove, checking for meaningless CSS properties that are given to subitems only when they are visible:

```<code>#menu li:hover > ul {
    left: auto;
    background-clip: content-box;
}
</code>```

So... I have no idea how to make it work in a meaningful way. Please help.

Edit:

Provided CodePen link at the top of the question.

答:
Please in your codepen replace CSS line #329 with the following:

#menu li.main:hover > a:before, #menu .active > a:before {

And JS will be:

```<code>var activeItem = $("#menu .active");

items.hover(function () {
    activeItem.toggleClass("active");
});
</code>```

Title: addClass on hover for multiple items

Body:
So I've been working on this script all day and all the examples I've seen just don't seem to do what I want. Here's my example CodePen. Try to hover over "MENUS" and over "SETTINGS". I'll try to explain the problem with words:

The Script:

var activeItem = $("#menu .active");
var items = $("#menu .main:not(.active)");

activeItem.addClass("active-2");

items.hover(function () {
    "use strict";
    activeItem.toggleClass("active-2");
});

$(document).mousemove(function (event) {
    "use strict";
    if ($(".sub-1").css("background-clip").toLowerCase() == "content-box") {
        $(".sub-1").parents(".main").addClass("active-2");
        $(".sub-1").parents(".main").css("background-color", "#CCC");
    } else {
        $(".sub-1").parents(".main").removeClass("active-2");
        $(".sub-1").parents(".main").css("background-color", "");
    }
});

The above code gives the blue line (class active-2) to the active item. In this case "HOME". The items variable counts all main menu items that are not active and is used to toggle blue line (active-2) from "HOME" when other items are hovered. So far so good.

The Problem:

I have submenu items (the dark-grey ones). When the mouse is anywhere over these submenu items I want to give the parent main item the blue line (active-2) until the mouse leaves, then return the blue line to the currently active item activeItem, in this case "HOME".

When there is only 1 subitem group (like the one under "MENUS"), it works. But when I added a second submenu group (under "SETTINGS") it broke. I'm looking for a way to make it so no matter how many submenu groups I have the main item's blue line should be visible when my mouse is over it's submenu items and return to activeItem when I'm no longer hovering it. If you delete one of the uls with class .sub-1 under "MENUS" or "SETTINGS" with the inspector it will start working again.

Why mousemove???

I tried to .addClass in .hover and .removeClass in it's callback function but that didn't work... Or maybe I'm just not doing it right? So basically the only way I could think of achieving this effect was with mousemove, checking for meaningless CSS properties that are given to subitems only when they are visible:

#menu li:hover > ul {
    left: auto;
    background-clip: content-box;
}

So... I have no idea how to make it work in a meaningful way. Please help.

Edit:

Provided CodePen link at the top of the question.

Body:
Please in your codepen replace CSS line #329 with the following:

#menu li.main:hover > a:before, #menu .active > a:before {

And JS will be:

var activeItem = $("#menu .active");

items.hover(function () {
    activeItem.toggleClass("active");
});


问:
Django Tutorial Templates without head, body and Doctype?
I'm just wondering, wether it is the right/recommended way to omit the Doctype, head und body tags? Because at least the Django tutorial does it, as can be seen in tutorial 3,
in the polls/templates/polls/index.html:</p>

```<code>{% if latest_question_list %}
    <ul>
    {% for question in latest_question_list %}
        <li><a href="/polls/{{ question.id }}/">{{ question.question_text }}</a></li>
    {% endfor %}
    </ul>
{% else %}
    <p>No polls are available.</p>
{% endif %}
</code>```

答: Include all the required tags. As on the tutorials they remove so that you can focus on the key point rather then the usual tags. Don't omit the required tags on your work. For learning you can.</p>

Body:
I'm just wondering, wether it is the right/recommended way to omit the Doctype, head und body tags? Because at least the Django tutorial does it, as can be seen in tutorial 3,
in the polls/templates/polls/index.html:

{% if latest_question_list %}

    {% for question in latest_question_list %}

{{ question.question_text }}

    {% endfor %}

{% else %}

No polls are available.

{% endif %}


问:
Possibility of using maven surfire plugin for SOAP webservice tests
I have a challenge of using maven surfire plugin for SOAP webservices testing.
What I need to check whether this plugin can be used while running webservices tests in CI environment.
Any suggestions are appreciated.

Many thanks for your comments and feedback.

答:
Take a look at Karate which easily integrates into a standard Java / Maven project. You can actually generate the standard JUnit XML report format which most CI tools understand. Or you have the option of integrating 3rd party reports via Maven. The test execution is via the Maven surefire plugin.

And yes, Karate has excellent support for SOAP and XML.

Disclaimer: I am the dev.


问:
Auto call a method upon instantiating a class
I have a this code:

```<code>from selenium import webdriver
from bs4 import BeautifulSoup as BS
from types import NoneType

class Alluris(object):

    def __init__(self, username, password):
        self.username = username
        self.password = password

    def log_in(self):
        driver =
webdriver.PhantomJS('C:\Users\V\Desktop\PY\web_scrape\phantomjs.exe')
        driver.get('https://alluris.han.nl')
        driver.find_element_by_id('username').send_keys(self.username)
        driver.find_element_by_id('password').send_keys(self.password)
        driver.find_element_by_xpath('//*
[@id="formfields"]/input[3]').click()
        soup = BS(driver.page_source, 'lxml')
        if type(soup.find('div', {'id' : 'errormessage'})) == NoneType:
            return 'Logged in successfully'
        else:
            return soup.find('div', {'id' : 'errormessage'}).text
</code>```

I want the log_in method to auto run when i create an instance of a class, for example:

```<code>  print Alluris('username', 'password')
</code>```

Output should be :

```<code>Logged in successfully
</code>```

Or

```<code>Incorrect username or password
</code>```

Basically I don't want to run the log_in method manually like

```<code> print Alluris('username', 'password').log_in()
</code>```

EDIT: I tried putting self.log_in() in the __init__ method but it only return the class object.

答:
You can do that by calling the method in your __init__ method:

```<code>class Alluris(object):

    def __init__(self, username, password):
        self.username = username
        self.password = password
        self.log_in()
</code>```

Body:
I have a this code:

from selenium import webdriver
from bs4 import BeautifulSoup as BS
from types import NoneType

class Alluris(object):

    def __init__(self, username, password):
        self.username = username
        self.password = password

    def log_in(self):
        driver =
webdriver.PhantomJS('C:\Users\V\Desktop\PY\web_scrape\phantomjs.exe')
        driver.get('https://alluris.han.nl')
        driver.find_element_by_id('username').send_keys(self.username)
        driver.find_element_by_id('password').send_keys(self.password)
        driver.find_element_by_xpath('//*
[@id="formfields"]/input[3]').click()
        soup = BS(driver.page_source, 'lxml')
        if type(soup.find('div', {'id' : 'errormessage'})) == NoneType:
            return 'Logged in successfully'
        else:
            return soup.find('div', {'id' : 'errormessage'}).text

I want the log_in method to auto run when i create an instance of a class, for example:

  print Alluris('username', 'password')

Output should be :

Logged in successfully

Or

Incorrect username or password

Basically I don't want to run the log_in method manually like

 print Alluris('username', 'password').log_in()

EDIT: I tried putting self.log_in() in the __init__ method but it only return the class object.

Body:
You can do that by calling the method in your __init__ method:

class Alluris(object):

    def __init__(self, username, password):
        self.username = username
        self.password = password
        self.log_in()


问:
Postfix and prefix increment that causes an error
Why does that code does not compile due to an error:

```<code>#include <iostream>

using namespace std;

int main()
{
    int i = 0;
    cout << ++(i++) << " " << i << endl;
    return 0;
}
</code>```

While that code does compile:

```<code>#include <iostream>

using namespace std;

int main()
{
    int i = 0;
    cout << (++i)++ << " " << i << endl;
    return 0;
}
</code>```

I do not understand that. From my point of view it would be pretty reasonable for the first chunk to compile. The expression ++(i++) would just mean take i, increment it and output, then increment it again.

I am not asking about an undefined behavior in int overflow. I do not know about r and l value at all at the time of writing the question and I do not care why is ++i considered an l-value, but i++ is not.

答:
When you compile it with clang you get error message that says it all.

```<code><source>:8:13: error: expression is not assignable
cout << ++(i++) << " " << i << endl;
</code>```

Maybe it is good to start with ++ operator. In fact it is shorthand for i = i + 1. Now if we look at postfix version i++, it says in standard that it returns copy of original value and as side efect it increments original value.
So from (i++) you get rvalue and are trying to assign to it and as we know you can't assign to rvalue.

Body:
Why does that code does not compile due to an error:

#include <iostream>

using namespace std;

int main()
{
    int i = 0;
    cout << ++(i++) << " " << i << endl;
    return 0;
}

While that code does compile:

#include <iostream>

using namespace std;

int main()
{
    int i = 0;
    cout << (++i)++ << " " << i << endl;
    return 0;
}

I do not understand that. From my point of view it would be pretty reasonable for the first chunk to compile. The expression ++(i++) would just mean take i, increment it and output, then increment it again.

I am not asking about an undefined behavior in int overflow. I do not know about r and l value at all at the time of writing the question and I do not care why is ++i considered an l-value, but i++ is not.

Body:
When you compile it with clang you get error message that says it all.

<source>:8:13: error: expression is not assignable
cout << ++(i++) << " " << i << endl;

Maybe it is good to start with ++ operator. In fact it is shorthand for i = i + 1. Now if we look at postfix version i++, it says in standard that it returns copy of original value and as side efect it increments original value.
So from (i++) you get rvalue and are trying to assign to it and as we know you can't assign to rvalue.


问:
How to make a menu pop up after mouse release
Hi I am using C# and taoframework opengl and glut

here is my BuildMenu()

```<code>private static void BuildMenu()
{
    submenu1 = Glut.glutCreateMenu(selectMessage);
            Glut.glutAddMenuEntry("New Game(N)", 1);
            Glut.glutAddMenuEntry("Reset(R)", 2);
            Glut.glutAddMenuEntry("Quit(Q)", 3);
    Glut.glutAttachMenu(button); //**makes the menu pop up once the button is pressed.**
}
</code>```

How can I make it pop up after mouse release??

答:
Using GLUT? You can't (or only with a lot of headaches). The solution?

Don't use GLUT. GLUT started as some in-situ framework for demonstrating simple OpenGL programs. It's neither part of OpenGL nor very flexible (as you found out). And it's unmaintained.

Either use a real toolkit, there are a lot of them: Qt, GTK, wxWidgets, FLTK, Fox... Or if you're really focused on only doing OpenGL I may suggest using GLFW, which is the better GLUT, but you'll have to draw the menus yourself (using OpenGL).

Body:
Hi I am using C# and taoframework opengl and glut

here is my BuildMenu()

private static void BuildMenu()
{
    submenu1 = Glut.glutCreateMenu(selectMessage);
            Glut.glutAddMenuEntry("New Game(N)", 1);
            Glut.glutAddMenuEntry("Reset(R)", 2);
            Glut.glutAddMenuEntry("Quit(Q)", 3);
    Glut.glutAttachMenu(button); //**makes the menu pop up once the button is pressed.**
}

How can I make it pop up after mouse release??


问:
Whats wrong with my python program

tip and tax calculator

```<code>bill = price + tax + tip

price = raw_input("What is the price of the meal")

tax = price * .06

tip = price * 0.20
</code>```

what is wrong with my code
I have tried everything
please answer and get back to me

答:
Heres a couple of things wrong with the code:

You're trying to calculate the total before some variables have been defined.

The raw_input function returns a string so you can't do proper mathematical calculations before you coerce it into an integer.

In calculate the tips/tax you should use a float with the whole number 1(1.20) to take the whole value of the bill + 20%.

Below is a code snippet that should work how you want and give you something to think about on how to pass dynamic values into the modifiers within the calculate_bill function for custom tip floats and custom tax floats:

```<code>def calculate_bill(bill, bill_modifiers):
    for modifier in bill_modifiers:
        bill = modifier(bill)
    return bill

def calculate_tip(bill, percentage=1.20):
    return bill * percentage

def calculate_tax(bill, percentage=1.06):
    return bill * percentage

if __name__ == '__main__':
    bill = int(input("What is the price of the meal: "))
    total_bill = calculate_bill(bill, [calculate_tip, calculate_tax])
    print(total_bill)
</code>```

Title: Whats wrong with my python program

Body:
tip and tax calculator

bill = price + tax + tip

price = raw_input("What is the price of the meal")

tax = price * .06

tip = price * 0.20

what is wrong with my code
I have tried everything
please answer and get back to me

Body:
Heres a couple of things wrong with the code:

You're trying to calculate the total before some variables have been defined.

The raw_input function returns a string so you can't do proper mathematical calculations before you coerce it into an integer.

In calculate the tips/tax you should use a float with the whole number 1(1.20) to take the whole value of the bill + 20%.

Below is a code snippet that should work how you want and give you something to think about on how to pass dynamic values into the modifiers within the calculate_bill function for custom tip floats and custom tax floats:

def calculate_bill(bill, bill_modifiers):
    for modifier in bill_modifiers:
        bill = modifier(bill)
    return bill

def calculate_tip(bill, percentage=1.20):
    return bill * percentage

def calculate_tax(bill, percentage=1.06):
    return bill * percentage

if __name__ == '__main__':
    bill = int(input("What is the price of the meal: "))
    total_bill = calculate_bill(bill, [calculate_tip, calculate_tax])
    print(total_bill)


问:
Issues with Generating Authorization code and User Token using Apache OAuth client 2.0 library in Java
I trying to Automate the User Level Token Creation/Generation process (REST/Authorization Grant Code) using Apache OAuth Client 2.0 Library in Java.
And below is the Code that am using which i got from https://cwiki.apache.org/confluence/display/OLTU/OAuth+2.0+Client+Quickstart,

```<code>`/*Previous Codes & starting the below with Try/Catch*/
OAuthClientRequest request = OAuthClientRequest
   .authorizationLocation("Authorization URL")
   .setClientId("ClientID")
   .setRedirectURI("Redirect URL")
   .buildQueryMessage();
request.getLocationUri();
OAuthAuthzResponse oar = OAuthAuthzResponse.oauthCodeAuthzResponse(request);
String code = oar.getCode();
/*Other Codes and starting the below with Try/Catch*/
OAuthClientRequest request = OAuthClientRequest
                .tokenLocation("TokenEndPointURL")
                .setGrantType(GrantType.AUTHORIZATION_CODE)
                .setClientId("ClientID")
                .setClientSecret("ClientSecret")
                .setRedirectURI("REdirectURL")
                .setCode(code)//Authorization Code from above
                .buildQueryMessage();
OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient());
GitHubTokenResponse oAuthResponse = oAuthClient.accessToken(request, GitHubTokenResponse.class);
String accessToken = oAuthResponse.getAccessToken();
String expiresIn = oAuthResponse.getExpiresIn();`
</code>```

However, I am getting a (inference from the error in Eclipse) Compilation Error on the below lines,

The oauthCodeAuthzResponse method accepts httpservlet Object and does not support OAuthAuthzReponse Type

```<code>OAuthAuthzResponse oar = OAuthAuthzResponse.oauthCodeAuthzResponse(request);
</code>```

Could anyone please let me know if there is a work around to resolve this ?
Or
How to Convert the oauthCodeAuthzResponse Request to a httpservlet Request ?
Or
Am I doing anything wrong or missing something ?

答:
OAuthAuthzResponse oar = OAuthAuthzResponse.oauthCodeAuthzResponse(request);
String code = oar.getCode();
```
<p>I think that the above code should be written in the implementation of the redirect URI endpoint, not in the client code.</p>
<p>It would be of help to understand the Authorization Code Flow correctly. An <strong>authorization code</strong> is issued from the authorization endpoint of the authorization server and it is delivered to the location which is pointed to by the redirect URI. That is, the authorization code is NOT delivered to the client application directly.</p>
<p>When an authorization server issues an authorization code, it sends an HTTP response like below back to the client's web browser.</p>
```HTTP/1.1 302 Found
Location: {Redirect URI}
  ?code={Authorization Code}  // - Always included
  &state={Arbitrary String}   // - Included if the authorization
                              //   request included 'state'.
```

302 Found triggers the web browser to go to the location pointed to by the Location header. Therefore, you have to implement the location to receive the authorization code, and the implementation has to pass the authorization code to the client application in some way or other.

Also note that an authorization page (HTML) is displayed between (a) an authorization request (= a request to the authorization endpoint) and (b) a token request (= a request to the token endpoint) and the page requires end-user interaction. See "1. Authorization Code Flow" in "Diagrams And Movies Of All The OAuth 2.0 Flows" for details.

Body:
I trying to Automate the User Level Token Creation/Generation process (REST/Authorization Grant Code) using Apache OAuth Client 2.0 Library in Java.
And below is the Code that am using which i got from https://cwiki.apache.org/confluence/display/OLTU/OAuth+2.0+Client+Quickstart,

`/*Previous Codes & starting the below with Try/Catch*/
OAuthClientRequest request = OAuthClientRequest
   .authorizationLocation("Authorization URL")
   .setClientId("ClientID")
   .setRedirectURI("Redirect URL")
   .buildQueryMessage();
request.getLocationUri();
OAuthAuthzResponse oar = OAuthAuthzResponse.oauthCodeAuthzResponse(request);
String code = oar.getCode();
/*Other Codes and starting the below with Try/Catch*/
OAuthClientRequest request = OAuthClientRequest
                .tokenLocation("TokenEndPointURL")
                .setGrantType(GrantType.AUTHORIZATION_CODE)
                .setClientId("ClientID")
                .setClientSecret("ClientSecret")
                .setRedirectURI("REdirectURL")
                .setCode(code)//Authorization Code from above
                .buildQueryMessage();
OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient());
GitHubTokenResponse oAuthResponse = oAuthClient.accessToken(request, GitHubTokenResponse.class);
String accessToken = oAuthResponse.getAccessToken();
String expiresIn = oAuthResponse.getExpiresIn();`

However, I am getting a (inference from the error in Eclipse) Compilation Error on the below lines,

The oauthCodeAuthzResponse method accepts httpservlet Object and does not support OAuthAuthzReponse Type

OAuthAuthzResponse oar = OAuthAuthzResponse.oauthCodeAuthzResponse(request);

Could anyone please let me know if there is a work around to resolve this ?
Or
How to Convert the oauthCodeAuthzResponse Request to a httpservlet Request ?
Or
Am I doing anything wrong or missing something ?

Body:
OAuthAuthzResponse oar = OAuthAuthzResponse.oauthCodeAuthzResponse(request);
String code = oar.getCode();

I think that the above code should be written in the implementation of the redirect URI endpoint, not in the client code.

It would be of help to understand the Authorization Code Flow correctly. An authorization code is issued from the authorization endpoint of the authorization server and it is delivered to the location which is pointed to by the redirect URI. That is, the authorization code is NOT delivered to the client application directly.

When an authorization server issues an authorization code, it sends an HTTP response like below back to the client's web browser.

HTTP/1.1 302 Found
Location: {Redirect URI}
  ?code={Authorization Code}  // - Always included
  &state={Arbitrary String}   // - Included if the authorization
                              //   request included 'state'.

302 Found triggers the web browser to go to the location pointed to by the Location header. Therefore, you have to implement the location to receive the authorization code, and the implementation has to pass the authorization code to the client application in some way or other.

Also note that an authorization page (HTML) is displayed between (a) an authorization request (= a request to the authorization endpoint) and (b) a token request (= a request to the token endpoint) and the page requires end-user interaction. See "1. Authorization Code Flow" in "Diagrams And Movies Of All The OAuth 2.0 Flows" for details.


问:
How to filter just the name of the Object on Ionic 2?
I've got a problem. I have a list of cities, but when I use the search-bar, I just want the cities with the same name to appear.

Currently i'm trying this:

```<code>   <ion-searchbar
      [(ngModel)]="selectedCity"
      [showCancelButton]="shouldShowCancel"
      (ionCancel)="onCancel($event)">
    </ion-searchbar>

  <ion-item *ngFor="let city of cities | orderBy: name | filter: selectedCity">
          <ion-label>{{city.name}}</ion-label>
    <button (click)="onActive(city.detalhe.id)" *ngIf="city.active" ion-button outline item-right>Desativar</button>
    <button (click)="onActive(city.detalhe.id)" *ngIf="!city.active" ion-button outline item-right>Ativar</button>
        </ion-item>
</code>```

But I know it will never works 'cause i'm sending the object city to the pipe 'filter' and not the name, how can I send just the name for the pipe? I need the object for the method 'onActive'

The Pipe:

```<code>@Pipe({
name: "filter",
pure: false
})

export class FilterArrayPipe implements PipeTransform {

transform(items: Array<any>, conditions: {[field: string]: any}): Array<any> {
    return items.filter(item => {
        for (let field in conditions) {
            if (item[field] !== conditions[field]) {
                return false;
            }
        }
        return true;
    });
}
}
</code>```

And 'selectedCity' is a String. When I try the pipe out with others strings, It works. Another point, I need to filter comparing the name of the object but I need the whole object after this.

答:
Well to begin with it looks like you'd need to send 2 parameters to the filter. The first being the literal 'name', the second selectedCity unquoted in the *ngFor of <ion-item>.
Then you could filter by items[field] !== selectedCity - where field would contain 'name'

I take it you've got the orderBy Example from here

You did see the comments below in the order by example link too... avoid using pipes for orderby.. Do it in components. I would address doing both at the component level personally.

Body:
I've got a problem. I have a list of cities, but when I use the search-bar, I just want the cities with the same name to appear.

Currently i'm trying this:

   <ion-searchbar
      [(ngModel)]="selectedCity"
      [showCancelButton]="shouldShowCancel"
      (ionCancel)="onCancel($event)">
    </ion-searchbar>

  <ion-item *ngFor="let city of cities | orderBy: name | filter: selectedCity">
          <ion-label>{{city.name}}</ion-label>
    <button (click)="onActive(city.detalhe.id)" *ngIf="city.active" ion-button outline item-right>Desativar</button>
    <button (click)="onActive(city.detalhe.id)" *ngIf="!city.active" ion-button outline item-right>Ativar</button>
        </ion-item>

But I know it will never works 'cause i'm sending the object city to the pipe 'filter' and not the name, how can I send just the name for the pipe? I need the object for the method 'onActive'

The Pipe:

@Pipe({
name: "filter",
pure: false
})

export class FilterArrayPipe implements PipeTransform {

transform(items: Array<any>, conditions: {[field: string]: any}): Array<any> {
    return items.filter(item => {
        for (let field in conditions) {
            if (item[field] !== conditions[field]) {
                return false;
            }
        }
        return true;
    });
}
}

And 'selectedCity' is a String. When I try the pipe out with others strings, It works. Another point, I need to filter comparing the name of the object but I need the whole object after this.