问:
MPAndroid chart setValueFormatter function information required
```<code>    xl.setValueFormatter(new IAxisValueFormatter() {
            @Override
            public String getFormattedValue(float value, AxisBase axis) {
                if ((int)value != 0){
                final HashMap<Integer, String>numMap = new HashMap<>();

                    for (int i = 0; i < clxaxisArray.size(); i++) {

                        numMap.put(i, ""+clxaxisArray.get(clxaxisArray.size() - 1 - i));

                    }

                    Log.e("intvalue", ""+(value));
                    return "";
                }
                else
                {
                    return "";
                }
            }
            @Override
            public int getDecimalDigits() {
                return 0;
            }
        });
    }
</code>```

What is value and axis in this function getFormattedValue and what are the uses of these values?For educational purpose please describe anyone.

答:
Solved by custom class

```<code>public class MyXAxisValueFormatter implements IAxisValueFormatter {

    private List mValues;
    private List<?>  reverse_mValues;

    public MyXAxisValueFormatter(List values) {
        this.mValues = values;
        this.reverse_mValues =  values.subList(0, values.size());
        Collections.reverse(reverse_mValues);
    }

    @Override
    public String getFormattedValue(float value, AxisBase axis) {
        // "value" represents the position of the label on the axis (x or y)
        if((int) value < 0 || (int) value >= reverse_mValues.size()){
            return "";
        }else{
            return (String) reverse_mValues.get((int) value);
        }

    }

    /** this is only needed if numbers are returned, else return 0 */
    @Override
    public int getDecimalDigits() { return 0; }
}
</code>```

In display graph function

```<code>XAxis xl = myChart.getXAxis();
        xl.setPosition(XAxis.XAxisPosition.BOTTOM);
        xl.setDrawAxisLine(true);
        xl.setDrawGridLines(false);
        xl.setGranularity(1f);
        xl.setDrawLabels(true);
        xl.setAvoidFirstLastClipping(false);
        xl.setAxisMaximum(mlxaxisArray.size());
        xl.setAxisMinimum(0);
        xl.setLabelCount(mlxaxisArray.size()+1);

        if (mlxaxisArray.size()!=0){

            xl.setValueFormatter(new MyXAxisValueFormatter(mlxaxisArray));
}
</code>```

Since my requirement was values in reverse order so inverse function is used in above class. Inverse function; Collections.reverse(reverse_mValues);

Body:
    xl.setValueFormatter(new IAxisValueFormatter() {
            @Override
            public String getFormattedValue(float value, AxisBase axis) {
                if ((int)value != 0){
                final HashMap<Integer, String>numMap = new HashMap<>();

                    for (int i = 0; i < clxaxisArray.size(); i++) {

                        numMap.put(i, ""+clxaxisArray.get(clxaxisArray.size() - 1 - i));

                    }

                    Log.e("intvalue", ""+(value));
                    return "";
                }
                else
                {
                    return "";
                }
            }
            @Override
            public int getDecimalDigits() {
                return 0;
            }
        });
    }

What is value and axis in this function getFormattedValue and what are the uses of these values?For educational purpose please describe anyone.

Body:
Solved by custom class

public class MyXAxisValueFormatter implements IAxisValueFormatter {

    private List mValues;
    private List<?>  reverse_mValues;

    public MyXAxisValueFormatter(List values) {
        this.mValues = values;
        this.reverse_mValues =  values.subList(0, values.size());
        Collections.reverse(reverse_mValues);
    }

    @Override
    public String getFormattedValue(float value, AxisBase axis) {
        // "value" represents the position of the label on the axis (x or y)
        if((int) value < 0 || (int) value >= reverse_mValues.size()){
            return "";
        }else{
            return (String) reverse_mValues.get((int) value);
        }

    }

    /** this is only needed if numbers are returned, else return 0 */
    @Override
    public int getDecimalDigits() { return 0; }
}

In display graph function

XAxis xl = myChart.getXAxis();
        xl.setPosition(XAxis.XAxisPosition.BOTTOM);
        xl.setDrawAxisLine(true);
        xl.setDrawGridLines(false);
        xl.setGranularity(1f);
        xl.setDrawLabels(true);
        xl.setAvoidFirstLastClipping(false);
        xl.setAxisMaximum(mlxaxisArray.size());
        xl.setAxisMinimum(0);
        xl.setLabelCount(mlxaxisArray.size()+1);

        if (mlxaxisArray.size()!=0){

            xl.setValueFormatter(new MyXAxisValueFormatter(mlxaxisArray));
}

Since my requirement was values in reverse order so inverse function is used in above class. Inverse function; Collections.reverse(reverse_mValues);


来源: stackexchange

问:
How do I manage this form in redux?

I'm building an online store and I'm creating a form where the user will select an option and the option's price will be added to the total price

```<code>class SingleProduct extends Component {
constructor(props) {
    super(props);
    this.state = {};

    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }
  handleChange(event) {
    this.setState({value: event.target.value});
  }

  handleSubmit(event) {
    event.preventDefault();

    var products = this.props.products.products;

         var ID = this.props.router.location.pathname.slice(9, 100)

            var productArray = this.props.products.products.data.filter(function(product) {
              return product.id === ID;
            })

            var product = productArray[0];
      var addToCart = (id, options) => {
        this.props.dispatch((dispatch) => {

            if(this.props.value == 'select'){
                this.props.product.options = 0;
            }
            else if(this.state.value == 'no-edge'){
                this.props.product.options = 0;
            }
            else if(this.state.value == '2inchHemOnly'){
                this.props.product.options = 20;
            }
            else if(this.state.value == '2inchHG'){
                this.props.product.options = 25;
            }
            else if(this.state.value == 'HandG'){
                this.props.product.options = 30;
            }
            else if(this.state.value == 'rope-rail'){
                this.props.product.options = 35;
            }
            else if(this.state.value == 'pole-pocket'){
                this.props.product.options = 40;
            }
        var values = this.props.product.values;
        var options = this.props.product.options;
          api.AddCart(id, this.props.product.quantity)

          .then((options) => {
              console.log(options)
              dispatch({type: "Update_Options", payload: options})
          })
          .then((values) => {
            console.log(values)
            dispatch({type: "Update_Value", payload: values})
          })
          .then((cart) => {
            console.log(cart)
            dispatch({type: "Cart_Updated", gotNew: false})
          })

          .then(() => {
              dispatch({type: "Fetch_Cart_Start", gotNew: false})

              api.GetCartItems()

              .then((cart, options, values) => {
                dispatch({type: "Fetch_Cart_End", payload: cart, gotNew: true})
                dispatch({type: "Update_Options", payload: options})
                dispatch({type: "Update_Value", payload: values})
              })
          })
          .then(() => {
              console.error(options)
          })
          .catch((e) => {
            console.log(e)
          })
        })
      }

      addToCart(product.id);
  }
return (
    <main role="main" id="container" className="main-container push">
    <section className="product">
      <div className="content">
          <div className="product-listing">

              <div className="product-description">
                  <p className="price"><span className="hide-content">Unit price </span>{'$' + product.meta.display_price.with_tax.amount/100 + this.props.product.options}</p>
                <form className="product" onSubmit={this.handleSubmit.bind(this)}>
                    <label>SELECT EDGING OPTION</label>
                    <select name="edging" value={this.state.value} onChange={this.handleChange}>
                            <option value="select">-- Please select --</option>
                            <option value="no-edge">No Edge</option>
                            <option value="2inchHemOnly">2” Hem Only</option>
                            <option value="2inchHG">2” Hem and Grommets 24” On Center</option>
                            <option value="HandG">Hem and Grommets 12” on Center</option>
                    </select>

                        <div className="quantity-input" style={style}>
                            <p className="hide-content">Product quantity.</p>

                        <button type="submit" className="submit">Add to cart</button>
                </form>
              </div>
          </div>

      </section>
      <MailingList />
  </main>
  )
}
}

export default connect(mapStateToProps)(SingleProduct);
</code>```

And here is my reducer:

```<code>const initialState = {
quantity: 1,
options: 0,
values: [
{ value: '-- Please select --' },
{ value: 'No Edge' },
{ value: '2” Hem Only' },
{ value: 'No Edge' },
{ value: '2” Hem and Grommets 24” On Center' },
{ value: 'Hem and Grommets 12” on Center' }
]
}

const ProductReducer = (state=initialState, action) => {
switch (action.type) {
case "Update_Quantity": {
  return {...state, quantity: action.payload};
}
case "Update_Options": {
  return {...state,
    options: action.payload};
}
case "Update_Value": {
  return {...state,
    value: action.payload};
}
default: {
  return {...state};
}
}
};

export default ProductReducer;
</code>```

When I add to the cart my 'value' is undefined. And on refresh, 'options' goes back to 0. My quantity stays in the state though. I just don't know why this is happening.

答:
The react docs state: Whether you declare a component as a function or a class, it must never modify its own props.

Therefore, you might want to make a copy of the props into a variable and then modify the copy. One way to do this might be to place this line:

```<code>let propsCopy = { ...this.props }
</code>```

above the line var addToCart = (id, options) => {

and then use propsCopy in place of props in the subsequent lines.

ContentLicense: CC BY-SA 4.0

Title: How do I manage this form in redux?

Body:
I'm building an online store and I'm creating a form where the user will select an option and the option's price will be added to the total price

class SingleProduct extends Component {
constructor(props) {
    super(props);
    this.state = {};

    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }
  handleChange(event) {
    this.setState({value: event.target.value});
  }

  handleSubmit(event) {
    event.preventDefault();

    var products = this.props.products.products;

         var ID = this.props.router.location.pathname.slice(9, 100)

            var productArray = this.props.products.products.data.filter(function(product) {
              return product.id === ID;
            })

            var product = productArray[0];
      var addToCart = (id, options) => {
        this.props.dispatch((dispatch) => {

            if(this.props.value == 'select'){
                this.props.product.options = 0;
            }
            else if(this.state.value == 'no-edge'){
                this.props.product.options = 0;
            }
            else if(this.state.value == '2inchHemOnly'){
                this.props.product.options = 20;
            }
            else if(this.state.value == '2inchHG'){
                this.props.product.options = 25;
            }
            else if(this.state.value == 'HandG'){
                this.props.product.options = 30;
            }
            else if(this.state.value == 'rope-rail'){
                this.props.product.options = 35;
            }
            else if(this.state.value == 'pole-pocket'){
                this.props.product.options = 40;
            }
        var values = this.props.product.values;
        var options = this.props.product.options;
          api.AddCart(id, this.props.product.quantity)

          .then((options) => {
              console.log(options)
              dispatch({type: "Update_Options", payload: options})
          })
          .then((values) => {
            console.log(values)
            dispatch({type: "Update_Value", payload: values})
          })
          .then((cart) => {
            console.log(cart)
            dispatch({type: "Cart_Updated", gotNew: false})
          })

          .then(() => {
              dispatch({type: "Fetch_Cart_Start", gotNew: false})

              api.GetCartItems()

              .then((cart, options, values) => {
                dispatch({type: "Fetch_Cart_End", payload: cart, gotNew: true})
                dispatch({type: "Update_Options", payload: options})
                dispatch({type: "Update_Value", payload: values})
              })
          })
          .then(() => {
              console.error(options)
          })
          .catch((e) => {
            console.log(e)
          })
        })
      }

      addToCart(product.id);
  }
return (

Unit price {'$' + product.meta.display_price.with_tax.amount/100 + this.props.product.options}

                <form className="product" onSubmit={this.handleSubmit.bind(this)}>
                    SELECT EDGING OPTION
                    <select name="edging" value={this.state.value} onChange={this.handleChange}>
                            <option value="select">-- Please select --</option>
                            <option value="no-edge">No Edge</option>
                            <option value="2inchHemOnly">2” Hem Only</option>
                            <option value="2inchHG">2” Hem and Grommets 24” On Center</option>
                            <option value="HandG">Hem and Grommets 12” on Center</option>
                    </select>

Product quantity.

                        <button type="submit" className="submit">Add to cart</button>
                </form>

      <MailingList />

  )
}
}

export default connect(mapStateToProps)(SingleProduct);

And here is my reducer:

const initialState = {
quantity: 1,
options: 0,
values: [
{ value: '-- Please select --' },
{ value: 'No Edge' },
{ value: '2” Hem Only' },
{ value: 'No Edge' },
{ value: '2” Hem and Grommets 24” On Center' },
{ value: 'Hem and Grommets 12” on Center' }
]
}

const ProductReducer = (state=initialState, action) => {
switch (action.type) {
case "Update_Quantity": {
  return {...state, quantity: action.payload};
}
case "Update_Options": {
  return {...state,
    options: action.payload};
}
case "Update_Value": {
  return {...state,
    value: action.payload};
}
default: {
  return {...state};
}
}
};

export default ProductReducer;

When I add to the cart my 'value' is undefined. And on refresh, 'options' goes back to 0. My quantity stays in the state though. I just don't know why this is happening.

Body:
The react docs state: Whether you declare a component as a function or a class, it must never modify its own props.

Therefore, you might want to make a copy of the props into a variable and then modify the copy. One way to do this might be to place this line:

let propsCopy = { ...this.props }

above the line var addToCart = (id, options) => {

and then use propsCopy in place of props in the subsequent lines.

ContentLicense: CC BY-SA 3.0


问:
Figuring out firestore with ngrx
I seem to be stuck on this, as there is not many guides or tutorials out there on how to use firestore with ngrx.

Lets say we have list of organisations, all of these will be used in 2 componants, componantA and componentB.

I can make an effect, that takes an LOAD_ACTION that merges the collection valuechanges observable and also map it out to LOAD_ACTION_SUCCESS for each component.

Now everytime there is a change, LOAD_ACTION_SUCCESS will be called, saving our data to each of their store state.

But this requires the component to dispatch LOAD_ACTION to start with, which might seem a bit errornous for REAL_TIME_DATA, as it will continue to update after. Even when not used.

I could just connect the services observable of valuechanges (the same as LOAD_ACTION does), in the component itself. It will not have state saved, but the Firebase observable is kinda like a Store (as long as it isnt saved on client), so if it has already gotten the data, it is already there.

Not using up 2 copies of data for state anymore.

Which leads me to:

Should it maybe have a store for the 'collection' from the service, which both components get data from, such as there is not multiple copies of that state everywhere it is used.

Any information or guidence to help me get further is appreciated, i seem to be stuck at such a trivial issue, obviously i can keep coding, but rather want it correct.

As dealing with real time data seems to be confusing me when it comes to ngrx.

Examples will also be appreciated.

答:
I just wrote a little blog about that issue where I want to compare the different ways to connect Firestore with NGRX.

Basically, you can map the valueChanges() actions to your store actions and the store will be in sync. I used an effect doing, but that can be in an service as well.

```<code>  @Effect()
  getData$ = this.dataDb.getFakeDataStateChanges().pipe(
    mergeMap(actions => actions),
    map(action => {
      return {
        type: `[FirstData] ${action.type}`,
        payload: { id: action.payload.doc.id, ...action.payload.doc.data() }
      };
    })
  );
</code>```

Where the actions are like

```<code>export enum FirstActionTypes {
  FIRST_DATA_ADDED = '[FirstData] added',
  FIRST_DATA_MODIFIED = '[FirstData] modified',
  FIRST_DATA_REMOVED = '[FirstData] removed'
}
</code>```

and the reducer handles the data

```<code>export function firstReducer(state: State = initialState, action: FirstAction) {
  switch (action.type) {
    case FirstActionTypes.FIRST_DATA_ADDED:
      return firstAdapter.addOne(action.payload, state);

    case FirstActionTypes.FIRST_DATA_MODIFIED:
      return firstAdapter.updateOne(
      {
        id: action.payload.id,
        changes: action.payload
      },
      state
    );

    case FirstActionTypes.FIRST_DATA_REMOVED:
      return firstAdapter.removeOne(action.payload.id, state);

    default: {
      return state;
    }
  }
}
</code>```

Title: Figuring out firestore with ngrx

Body:
I just wrote a little blog about that issue where I want to compare the different ways to connect Firestore with NGRX.

Basically, you can map the valueChanges() actions to your store actions and the store will be in sync. I used an effect doing, but that can be in an service as well.

  @Effect()
  getData$ = this.dataDb.getFakeDataStateChanges().pipe(
    mergeMap(actions => actions),
    map(action => {
      return {
        type: `[FirstData] ${action.type}`,
        payload: { id: action.payload.doc.id, ...action.payload.doc.data() }
      };
    })
  );

Where the actions are like

export enum FirstActionTypes {
  FIRST_DATA_ADDED = '[FirstData] added',
  FIRST_DATA_MODIFIED = '[FirstData] modified',
  FIRST_DATA_REMOVED = '[FirstData] removed'
}

and the reducer handles the data

export function firstReducer(state: State = initialState, action: FirstAction) {
  switch (action.type) {
    case FirstActionTypes.FIRST_DATA_ADDED:
      return firstAdapter.addOne(action.payload, state);

    case FirstActionTypes.FIRST_DATA_MODIFIED:
      return firstAdapter.updateOne(
      {
        id: action.payload.id,
        changes: action.payload
      },
      state
    );

    case FirstActionTypes.FIRST_DATA_REMOVED:
      return firstAdapter.removeOne(action.payload.id, state);

    default: {
      return state;
    }
  }
}


问:
Evaluating a mathematical expression in a string form
This is a standard interview question, evaluate a mathematical expression given in the form of a string.

So provided, '3+3-6*2'
The answer should be -6

Now if the expressions only support four operations +,-,*,/
Then is there a simple way to do it using a stack.

I've solved it by converting the infix notation to postfix and then solving it using a stack - but I'm looking for a different approach that supports only these four operations. This is my solution,

def evaluate(self, s: str) -> int:
    expr = [i for i in re.split(r'(\d+|\W+)', s) if i]
    rpn = self.convertToPostfix(expr)
    return self.evalPostfix(rpn)

def convertToPostfix(self, infix: list) -> list:
    stack = collections.deque()
    result = []
    for item in infix:
        if item.isdigit():
            result.append(item)
        else:
            while len(stack) > 0 and self.has_higher_precedence(stack[-1], item):
                result.append(stack[-1])
                stack.pop()
            stack.append(item)
    while len(stack) > 0:
        result.append(stack.pop())
    return result

def has_higher_precedence(self, a: str, b: str) -> bool:
    if a == '/' and b == '*' or b == '+' or b == '-':
        return True
    if a == '*' and b == '+' or '-':
        return True
    if a == '+' and b == '-':
        return True
    return False

def evalPostfix(self, p: list) -> int:
    stack = collections.deque()
    for item in p:
        if item.isdigit():
            stack.append(int(item))
        elif item[1:].isdigit():
            stack.append(int(item))
        else:
            curr = stack.pop()
            prev = stack.pop()
            if item == '+':
                total = prev + curr
            elif item == '-':
                total = prev - curr
            elif item == '*':
                total = prev * curr
            else:
                total = prev / curr
            stack.append(total)
    return stack.pop()
```

Also I'm aware that this can be solved by designing a recursive lexical parser but that's beyond the scope of this question.

So my question is, is there a simple way to do this in O(n) time using a stack if there are only four operators

答:
You could store the string as a list of characters and then run through it linearly 2 times, first calculating for multiplication/division then addition/subtraction.

i.e. In the first iteration have

```<code>1+10/2 -> 1 + 5
</code>```

then have

```<code>1 + 5 -> 6
</code>```

This could also easily be implemented with a stack, to which you add the numbers with the + or - sign. When you are adding to the stack and realize you have reached a / or * sign, you pop the previous element, multiply or divide it by the current number, and push it back. Finally, you find the sum of all the elements in a stack.

Even further, you can make the observation that in the previous example, the only element of the stack being used was one directly preceding the answer. This suggests that you can store the previous element while maintaining a sum and if you reach a * or / sign, then subtracting the previous element from the sum and adding the updated element. This method effectively solves the problem in one O(n) scan with O(1) extra storage, making it possibly the optimal solution for this problem.

Body:
This is a standard interview question, evaluate a mathematical expression given in the form of a string.

So provided, '3+3-6*2'
The answer should be -6

Now if the expressions only support four operations +,-,*,/
Then is there a simple way to do it using a stack.

I've solved it by converting the infix notation to postfix and then solving it using a stack - but I'm looking for a different approach that supports only these four operations. This is my solution,

def evaluate(self, s: str) -> int:
    expr = [i for i in re.split(r'(\d+|\W+)', s) if i]
    rpn = self.convertToPostfix(expr)
    return self.evalPostfix(rpn)

def convertToPostfix(self, infix: list) -> list:
    stack = collections.deque()
    result = []
    for item in infix:
        if item.isdigit():
            result.append(item)
        else:
            while len(stack) > 0 and self.has_higher_precedence(stack[-1], item):
                result.append(stack[-1])
                stack.pop()
            stack.append(item)
    while len(stack) > 0:
        result.append(stack.pop())
    return result

def has_higher_precedence(self, a: str, b: str) -> bool:
    if a == '/' and b == '*' or b == '+' or b == '-':
        return True
    if a == '*' and b == '+' or '-':
        return True
    if a == '+' and b == '-':
        return True
    return False

def evalPostfix(self, p: list) -> int:
    stack = collections.deque()
    for item in p:
        if item.isdigit():
            stack.append(int(item))
        elif item[1:].isdigit():
            stack.append(int(item))
        else:
            curr = stack.pop()
            prev = stack.pop()
            if item == '+':
                total = prev + curr
            elif item == '-':
                total = prev - curr
            elif item == '*':
                total = prev * curr
            else:
                total = prev / curr
            stack.append(total)
    return stack.pop()

Also I'm aware that this can be solved by designing a recursive lexical parser but that's beyond the scope of this question.

So my question is, is there a simple way to do this in O(n) time using a stack if there are only four operators

Body:
You could store the string as a list of characters and then run through it linearly 2 times, first calculating for multiplication/division then addition/subtraction.

i.e. In the first iteration have

1+10/2 -> 1 + 5

then have

1 + 5 -> 6

This could also easily be implemented with a stack, to which you add the numbers with the + or - sign. When you are adding to the stack and realize you have reached a / or * sign, you pop the previous element, multiply or divide it by the current number, and push it back. Finally, you find the sum of all the elements in a stack.

Even further, you can make the observation that in the previous example, the only element of the stack being used was one directly preceding the answer. This suggests that you can store the previous element while maintaining a sum and if you reach a * or / sign, then subtracting the previous element from the sum and adding the updated element. This method effectively solves the problem in one O(n) scan with O(1) extra storage, making it possibly the optimal solution for this problem.


问:
Use of google map library on manifest file
Why do we use the below code on our android manifest file.Can anyone please explain?</p>

```<code>        <uses-library
        android:name="com.google.android.maps"
        android:required="true" />
</code>```

答: Please check this out : uses-library. This will give the clear idea.</p>

Body:
Why do we use the below code on our android manifest file.Can anyone please explain?

        <uses-library
        android:name="com.google.android.maps"
        android:required="true" />


问:
How to display Google Maps with different location in multiple pages?

Is there possible to display a Google Map for each page with different locations ?</p>

答:
Yes its possible.Try this code in differnt pages with differen id and differnt coordinates.</p>

```<code><!DOCTYPE html>
<html>
  <head>
    <style>
       #map {
        height: 400px;
        width: 100%;
       }
    </style>
  </head>
  <body>
    <h3>My Google Maps Demo</h3>
    <div id="map"></div>
    <script>
      function initMap() {
        var uluru = {lat: -25.363, lng: 131.044};
        var map = new google.maps.Map(document.getElementById('map'), {
          zoom: 4,
          center: uluru
        });
        var marker = new google.maps.Marker({
          position: uluru,
          map: map
        });
      }
    </script>
    <script async defer
    src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
    </script>
  </body>
</html>
</code>```

Body:
Yes its possible.Try this code in differnt pages with differen id and differnt coordinates.

<!DOCTYPE html>
<html>
  <head>
    <style>
       #map {
        height: 400px;
        width: 100%;
       }
    </style>
  </head>
  <body>
    <h3>My Google Maps Demo</h3>
    <div id="map"></div>
    <script>
      function initMap() {
        var uluru = {lat: -25.363, lng: 131.044};
        var map = new google.maps.Map(document.getElementById('map'), {
          zoom: 4,
          center: uluru
        });
        var marker = new google.maps.Marker({
          position: uluru,
          map: map
        });
      }
    </script>
    <script async defer
    src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
    </script>
  </body>
</html>


问:
Having issues with simple VB script
I am having issues running the following VB script to create a new directory in my SSIS package. It should create the following new path D:\customers\documents\orders\20171205.

Public Sub Main()
    'set dir path
    Dts.Variables("var_DirPath").Value =
        "D:\customers\documents\orders\" + Date.Today.Year.ToString +
        Date.Today.Month.ToString + Date.Today.Day.ToString
    Dts.TaskResult = ScriptResults.Success
End Sub
```

<p>The ReadWriteVariables of the script task editor is configured to User:var_DirPath. The value of the variable is “D:\customers\documents\orders\" </p>

<p>The file task is configured for</p>

```UseDirector/Exists = True
Operation = Create directory
IsSourcePathAvailable = True
Source variable = User:var_DirPath
```

It resolves in the package during debugging, but I do not know why this simple script does not work.

Any assistance is appreciated.

答:
Some Suggestions

You have to make sure that the variable name is typed correctly, because the name is case sensitive. Also you can use Date.Now.ToString("yyyyMMdd") instead of concatenating the date parts.

Public Sub Main()
    'set dir path
    Dts.Variables("var_DirPath").Value =
    "D:\customers\documents\orders\" & Date.Now.ToString("yyyyMMdd")
    Dts.TaskResult = ScriptResults.Success
End Sub
```

<p><strong>Also make sure to set the File System Task <code>Delay Validation</code> property to <code>True</code></strong></p>

<h1>Simpler Solution - Using Expression</h1>

<p>By the way you can achieve this using a expressions, Just go to the variable list, click on the variable <code>var_DirPath</code>, press F4 to show the properties Tab, Set <code>Evaluate as expression</code> property to <code>True</code>, click on the <code>Expression</code> property and use the following expression:</p>

``` "D:\\customers\\documents\\orders\\" + (DT_STR, 4, 1252) DATEPART("yyyy" , GETDATE()) + RIGHT("0" + (DT_STR, 2, 1252) DATEPART("MM" , GETDATE()), 2) + RIGHT("0" + (DT_STR, 2, 1252) DATEPART("dd" , GETDATE()), 2)
```

Title: Having issues with simple VB script

Body:
I am having issues running the following VB script to create a new directory in my SSIS package. It should create the following new path D:\customers\documents\orders\20171205.

Public Sub Main()
    'set dir path
    Dts.Variables("var_DirPath").Value =
        "D:\customers\documents\orders\" + Date.Today.Year.ToString +
        Date.Today.Month.ToString + Date.Today.Day.ToString
    Dts.TaskResult = ScriptResults.Success
End Sub

The ReadWriteVariables of the script task editor is configured to User:var_DirPath. The value of the variable is “D:\customers\documents\orders\"

The file task is configured for

UseDirector/Exists = True
Operation = Create directory
IsSourcePathAvailable = True
Source variable = User:var_DirPath

It resolves in the package during debugging, but I do not know why this simple script does not work.

Any assistance is appreciated.

Body:
Some Suggestions

You have to make sure that the variable name is typed correctly, because the name is case sensitive. Also you can use Date.Now.ToString("yyyyMMdd") instead of concatenating the date parts.

Public Sub Main()
    'set dir path
    Dts.Variables("var_DirPath").Value =
    "D:\customers\documents\orders\" & Date.Now.ToString("yyyyMMdd")
    Dts.TaskResult = ScriptResults.Success
End Sub

Also make sure to set the File System Task Delay Validation property to True

Simpler Solution - Using Expression

By the way you can achieve this using a expressions, Just go to the variable list, click on the variable var_DirPath, press F4 to show the properties Tab, Set Evaluate as expression property to True, click on the Expression property and use the following expression:

 "D:\\customers\\documents\\orders\\" + (DT_STR, 4, 1252) DATEPART("yyyy" , GETDATE()) + RIGHT("0" + (DT_STR, 2, 1252) DATEPART("MM" , GETDATE()), 2) + RIGHT("0" + (DT_STR, 2, 1252) DATEPART("dd" , GETDATE()), 2)


问:
why is FBSDKGraphRequest(graphPath: "me", parameters: params).start being called only once
I'm trying to obtain certain Facebook info of my test user and this method that I used to obtain the user info only seemed to be called when signing up but not when logging in I want to return these info everytime user log in using Facebook. I'm using the following method in didCompleteWith method

```<code>let params = ["fields" : "email, name, friendlists"]
        let graphRequest = FBSDKGraphRequest(graphPath: "me", parameters: params)
        _ = graphRequest?.start(completionHandler: { (connection, result, error) in
            if error != nil {
                print(error!.localizedDescription)
                return
            }

            if let result = result as? [String:Any]{
                guard let email = result["email"] as? String else {
                    return
                }

                guard let username = result["name"] as? String else {
                    return
                }

                guard let friendList = result["friendlists"] as? String else {
                    return
                }

                print(email, username, friendList)
            }
        })
</code>```

Is there some other method I should use?

UPDATE: I believe I'm not using correct parameter for obtaining friends list too.

答: Your code has no problem. Probably you are not waiting for the completion block to execute. Just wait for a few seconds so that the block can execute.</p>

Body:
I'm trying to obtain certain Facebook info of my test user and this method that I used to obtain the user info only seemed to be called when signing up but not when logging in I want to return these info everytime user log in using Facebook. I'm using the following method in didCompleteWith method

let params = ["fields" : "email, name, friendlists"]
        let graphRequest = FBSDKGraphRequest(graphPath: "me", parameters: params)
        _ = graphRequest?.start(completionHandler: { (connection, result, error) in
            if error != nil {
                print(error!.localizedDescription)
                return
            }

            if let result = result as? [String:Any]{
                guard let email = result["email"] as? String else {
                    return
                }

                guard let username = result["name"] as? String else {
                    return
                }

                guard let friendList = result["friendlists"] as? String else {
                    return
                }

                print(email, username, friendList)
            }
        })

Is there some other method I should use?

UPDATE: I believe I'm not using correct parameter for obtaining friends list too.


问:
Django Rest API, return json list of a model with only required fields - lambda did not work
In my Django Rest API, I have problem trying to do a query list and return json response based on the fields that I require (like just id, username instead of all in the model). One way is trying with lambda but it didnt work.

This is a continuation for this: Django API list with pagination - Page is not JSON serializable

I have an API query where I want to list model record of specific fields. For example (just id and username) instead of all the fields in the model. I am trying to use lambda to generate the json fields according to a helper function .as_dict() defined in the model. But it causes an error as show in the traceback below.

Here is my function based rest API, see the lambda part at the bottom that is the problem:

```<code>@api_view(['POST'])
def employee_get_list_by_page(request):
    # ----- YAML below for Swagger -----
    """
    description: employee_get_list_by_page
    parameters:
      - name: token
        type: string
        required: true
        location: form
      - name: page
        type: string
        required: true
        location: form
      - name: page_limit
        type: string
        required: true
        location: form
    """
    token = request.POST['token']
    try:
        auth_employee = AuthEmployeeSessionToken.objects.get(token=token)

    except AuthEmployeeSessionToken.DoesNotExist:
        return Response("Invalid Token", status=status.HTTP_406_NOT_ACCEPTABLE)

    employee_list = Employee.objects.filter(company = auth_employee.employee.company.id).order_by('id')

    page = request.GET.get('page', request.POST['page'])
    paginator = Paginator(employee_list, request.POST['page_limit'])

    try:
       employees = paginator.page(page)
    except PageNotAnInteger:
       employees = paginator.page(request.POST['page'])
    except EmptyPage:
       employees = paginator.page(paginator.num_pages)

    #  Here we map a lambda function over the queryset of Models to return the dictionary representation for each element in the list
    employees_page = list(
       map(lambda employee: employee.as_dict(), list(employees))
    )
    return Response(employees_page ,status=status.HTTP_200_OK)
</code>```

This is the error from the traceback:
https://gist.github.com/axilaris/ee40b0936d7d5591275d593acdcdd62a

```<code>AttributeError: 'dict' object has no attribute 'as_dict'
</code>```

without the lambda, the result it returns the result that looks like this. https://gist.github.com/axilaris/a92f7be8978212a9cbabbf10b9d120ea. Maybe it doesnt recognize .as_dict() because of employee key does not exist ? I am not familiar how lambda works here.

model.py (Employee model with as_dict() for json)

```<code>class Employee(models.Model):

    user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='employee')
    company = models.ForeignKey(Company)
    username = models.CharField(max_length=30, blank=False)
    email = models.CharField(max_length=30, blank=False)
    first_name = models.CharField(max_length=30, blank=False)
    last_name = models.CharField(max_length=30, blank=False)

    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.user.username

    def as_dict(self):
        return {"id": "%d" % self.id,
                "username": self.username if self.username else ""}
</code>```

Question:
How can do I query list and return a json response based on the fields that I require (like just id, username instead of all) ?

答:
Try doing this:</p>

```<code>employee_list = Employee.objects.filter(company = auth_employee.employee.company.id).values("id", "username").order_by('id')
</code>```

Body:
In my Django Rest API, I have problem trying to do a query list and return json response based on the fields that I require (like just id, username instead of all in the model). One way is trying with lambda but it didnt work.

This is a continuation for this: Django API list with pagination - Page is not JSON serializable

I have an API query where I want to list model record of specific fields. For example (just id and username) instead of all the fields in the model. I am trying to use lambda to generate the json fields according to a helper function .as_dict() defined in the model. But it causes an error as show in the traceback below.

Here is my function based rest API, see the lambda part at the bottom that is the problem:

@api_view(['POST'])
def employee_get_list_by_page(request):
    # ----- YAML below for Swagger -----
    """
    description: employee_get_list_by_page
    parameters:
      - name: token
        type: string
        required: true
        location: form
      - name: page
        type: string
        required: true
        location: form
      - name: page_limit
        type: string
        required: true
        location: form
    """
    token = request.POST['token']
    try:
        auth_employee = AuthEmployeeSessionToken.objects.get(token=token)

    except AuthEmployeeSessionToken.DoesNotExist:
        return Response("Invalid Token", status=status.HTTP_406_NOT_ACCEPTABLE)

    employee_list = Employee.objects.filter(company = auth_employee.employee.company.id).order_by('id')

    page = request.GET.get('page', request.POST['page'])
    paginator = Paginator(employee_list, request.POST['page_limit'])

    try:
       employees = paginator.page(page)
    except PageNotAnInteger:
       employees = paginator.page(request.POST['page'])
    except EmptyPage:
       employees = paginator.page(paginator.num_pages)

    #  Here we map a lambda function over the queryset of Models to return the dictionary representation for each element in the list
    employees_page = list(
       map(lambda employee: employee.as_dict(), list(employees))
    )
    return Response(employees_page ,status=status.HTTP_200_OK)

This is the error from the traceback:
https://gist.github.com/axilaris/ee40b0936d7d5591275d593acdcdd62a

AttributeError: 'dict' object has no attribute 'as_dict'

without the lambda, the result it returns the result that looks like this. https://gist.github.com/axilaris/a92f7be8978212a9cbabbf10b9d120ea. Maybe it doesnt recognize .as_dict() because of employee key does not exist ? I am not familiar how lambda works here.

model.py (Employee model with as_dict() for json)

class Employee(models.Model):

    user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='employee')
    company = models.ForeignKey(Company)
    username = models.CharField(max_length=30, blank=False)
    email = models.CharField(max_length=30, blank=False)
    first_name = models.CharField(max_length=30, blank=False)
    last_name = models.CharField(max_length=30, blank=False)

    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.user.username

    def as_dict(self):
        return {"id": "%d" % self.id,
                "username": self.username if self.username else ""}

Question:
How can do I query list and return a json response based on the fields that I require (like just id, username instead of all) ?

Body:
Try doing this:

employee_list = Employee.objects.filter(company = auth_employee.employee.company.id).values("id", "username").order_by('id')


问:
XPath trying to get the third position
I want to get the authors on the third position. I am using //authors[3]. Is there any reason this way does not work? When i type //authors[1] i get the whole row.

```<code><publications>

    <publication>

    <publication_name> Group agency: The possibility, design, and status of corporate agents </publication_name>
    <authors> C List,P Pettit  </authors>
    <publisher> Oxford University Press </publisher>
    <year> 2011 </year>
    <citation> 598 </citation>

</publication>

<publication>

    <publication_name> Aggregating sets of judgments: An impossibility result</publication_name>
    <authors> C List, P Pettit  </authors>
    <publisher> Economics and Philosophy </publisher>
    <volume> 18 </volume>
    <number> 1 </number>
    <pages> 89- 110 </pages>
    <citation> 558 </citation>
    <year> 2002 </year>e

</publication>

<publication>

    <publication_name> Epistemic democracy: generalizing the Condorcet jury theorem</publication_name>
    <authors> C List, RE Goodin  </authors>
    <publisher> Journal of Political Philosophy </publisher>
    <volume> 9 </volume>
    <number> 3 </number>
    <pages> 277-306 </pages>
    <citation> 409 </citation>
    <year> 2001 </year>

</publication>

<publication>

    <publication_name> Arrow’s theorem in judgment aggregation </publication_name>
    <authors> F Dietrich, C List  </authors>
    <publisher> Social Choice and Welfare </publisher>
    <volume> 29 </volume>
    <number> 1 </number>
    <pages> 19 - 33 </pages>
    <citation> 220 </citation>
    <year> 2007 </year>

</publication>

<publication>

    <publication_name> Deliberation, single-peakedness, and the possibility of meaningful democracy: evidence from deliberative polls </publication_name>
    <authors> C List, RC Luskin, JS Fishkin, I McLean  </authors>
    <publisher> Journal of Politics </publisher>
    <volume> 75 </volume>
    <number> 01 </number>
    <pages> 80-95 </pages>
    <citation> 143 </citation>
    <year> 2013 </year>

</publication>

<publication>

    <publication_name> Swarm intelligence: When uncertainty meets conflict </publication_name>
    <authors> L Conradt, C List, TJ Roper </authors>
    <publisher> The American Naturalist </publisher>
    <volume> 182 </volume>
    <number> 5 </number>
    <pages> 592-610 </pages>
    <citation> 10 </citation>
    <year> 2013 </year>

</publication>

<publication>

    <publication_name> Intradimensional Single-peakedness and the Multidimensional Arrow Problem </publication_name>
    <authors> C List </authors>
    <publisher> Theory and Decision </publisher>
    <citation> 10 </citation>
    <year> 2004 </year>

</publication>

<publication>

    <publication_name> The methodology of political theory </publication_name>
    <authors> C List, L Valentini  </authors>
    <publisher> The Oxford Handbook of Philosophical Methodology </publisher>
    <citation> 8 </citation>
    <year> 2016 </year>

</publication>

<publication>

    <publication_name> Social choice theory and deliberative democracy: a response to Aldred </publication_name>
    <authors> JS Dryzek, C List </authors>
    <publisher> British Journal of Political Science </publisher>
    <volume> 34 </volume>
    <number> 4 </number>
    <pages> 752-758 </pages>
    <citation> 8 </citation>
    <year> 2004 </year>

</publication>

<publication>

    <publication_name> Episteme symposium on group agency: Replies to Gaus, Cariani, Sylvan, and Briggs </publication_name>
    <authors> C List, P Pettit </authors>
    <publisher> Episteme </publisher>
    <volume> 9 </volume>
    <number> 3 </number>
    <pages> 293 </pages>
    <citation> 5 </citation>
    <year> 2012 </year>

</publication>

<publication>

    <publication_name> Two intuitions about free will: Alternative possibilities and intentional endorsement </publication_name>
    <authors> C List, W Rabinowicz  </authors>
    <publication> Philosophical Perspectives </publication>
    <volume> 28 </volume>
    <number> 1 </number>
    <pages> 155-172 </pages>
    <citation> 4 </citation>
    <year> 2014 </year>

</publication>

<publication>

    <publication_name> Reasons for (prior) belief in Bayesian epistemology </publication_name>
    <authors> F Dietrich, C List  </authors>
    <publisher> Synthese </publisher>
    <volume> 190 </volume>
    <number> 5 </number>
    <pages> 787-808 </pages>
    <citation> 4 </citation>
    <year> 2013 </year>

</publication>

<publication>

    <publication_name> Freedom as independence </publication_name>
    <authors> C List, L Valentini  </authors>
    <publisher> Ethics </publisher>
    <volume> 126 </volume>
    <number> 4 </number>
    <pages> 1043-1074 </pages>
    <citation> 3 </citation>
    <year> 2016 </year>

</publication>

<publication>

    <publication_name> Belief revision generalized: A joint characterization of Bayes' and Jeffrey's rules </publication_name>
    <authors> F Dietrich, C List, R Bradley </authors>
    <publisher> Journal of Economic Theory </publisher>
    <volume> 162</volume>
    <pages> 352–371 </pages>
    <citation> 3 </citation>
    <year> 2016 </year>

</publication>

    <publication>

        <publication_name>Which worlds are possible? A judgment aggregation problem</publication_name>
        <authors>C List</authors>
        <publisher>Journal of Philosophical Logic</publisher>
        <volume>37</volume>
        <number>1</number>
        <pages>57-65</pages>
        <citation>12</citation>
        <year>2008</year>

    </publication>

</publications>
</code>```

I only want to get the author on the third position.

There is no result and i get an error saying: The XPath query returned no results. XPath scope:current file.

答:
You can select third author with this xpath</p>

```<code>//authors[contains(text(),' C List, RE Goodin ')]
</code>```

Title: XPath trying to get the third position

Body:
I want to get the authors on the third position. I am using //authors[3]. Is there any reason this way does not work? When i type //authors[1] i get the whole row.

<publications>

    <publication>

    <publication_name> Group agency: The possibility, design, and status of corporate agents </publication_name>
    <authors> C List,P Pettit  </authors>
    <publisher> Oxford University Press </publisher>
    <year> 2011 </year>
    <citation> 598 </citation>

</publication>

<publication>

    <publication_name> Aggregating sets of judgments: An impossibility result</publication_name>
    <authors> C List, P Pettit  </authors>
    <publisher> Economics and Philosophy </publisher>
    <volume> 18 </volume>
    <number> 1 </number>
    <pages> 89- 110 </pages>
    <citation> 558 </citation>
    <year> 2002 </year>e

</publication>

<publication>

    <publication_name> Epistemic democracy: generalizing the Condorcet jury theorem</publication_name>
    <authors> C List, RE Goodin  </authors>
    <publisher> Journal of Political Philosophy </publisher>
    <volume> 9 </volume>
    <number> 3 </number>
    <pages> 277-306 </pages>
    <citation> 409 </citation>
    <year> 2001 </year>

</publication>

<publication>

    <publication_name> Arrow’s theorem in judgment aggregation </publication_name>
    <authors> F Dietrich, C List  </authors>
    <publisher> Social Choice and Welfare </publisher>
    <volume> 29 </volume>
    <number> 1 </number>
    <pages> 19 - 33 </pages>
    <citation> 220 </citation>
    <year> 2007 </year>

</publication>

<publication>

    <publication_name> Deliberation, single-peakedness, and the possibility of meaningful democracy: evidence from deliberative polls </publication_name>
    <authors> C List, RC Luskin, JS Fishkin, I McLean  </authors>
    <publisher> Journal of Politics </publisher>
    <volume> 75 </volume>
    <number> 01 </number>
    <pages> 80-95 </pages>
    <citation> 143 </citation>
    <year> 2013 </year>

</publication>

<publication>

    <publication_name> Swarm intelligence: When uncertainty meets conflict </publication_name>
    <authors> L Conradt, C List, TJ Roper </authors>
    <publisher> The American Naturalist </publisher>
    <volume> 182 </volume>
    <number> 5 </number>
    <pages> 592-610 </pages>
    <citation> 10 </citation>
    <year> 2013 </year>

</publication>

<publication>

    <publication_name> Intradimensional Single-peakedness and the Multidimensional Arrow Problem </publication_name>
    <authors> C List </authors>
    <publisher> Theory and Decision </publisher>
    <citation> 10 </citation>
    <year> 2004 </year>

</publication>

<publication>

    <publication_name> The methodology of political theory </publication_name>
    <authors> C List, L Valentini  </authors>
    <publisher> The Oxford Handbook of Philosophical Methodology </publisher>
    <citation> 8 </citation>
    <year> 2016 </year>

</publication>

<publication>

    <publication_name> Social choice theory and deliberative democracy: a response to Aldred </publication_name>
    <authors> JS Dryzek, C List </authors>
    <publisher> British Journal of Political Science </publisher>
    <volume> 34 </volume>
    <number> 4 </number>
    <pages> 752-758 </pages>
    <citation> 8 </citation>
    <year> 2004 </year>

</publication>

<publication>

    <publication_name> Episteme symposium on group agency: Replies to Gaus, Cariani, Sylvan, and Briggs </publication_name>
    <authors> C List, P Pettit </authors>
    <publisher> Episteme </publisher>
    <volume> 9 </volume>
    <number> 3 </number>
    <pages> 293 </pages>
    <citation> 5 </citation>
    <year> 2012 </year>

</publication>

<publication>

    <publication_name> Two intuitions about free will: Alternative possibilities and intentional endorsement </publication_name>
    <authors> C List, W Rabinowicz  </authors>
    <publication> Philosophical Perspectives </publication>
    <volume> 28 </volume>
    <number> 1 </number>
    <pages> 155-172 </pages>
    <citation> 4 </citation>
    <year> 2014 </year>

</publication>

<publication>

    <publication_name> Reasons for (prior) belief in Bayesian epistemology </publication_name>
    <authors> F Dietrich, C List  </authors>
    <publisher> Synthese </publisher>
    <volume> 190 </volume>
    <number> 5 </number>
    <pages> 787-808 </pages>
    <citation> 4 </citation>
    <year> 2013 </year>

</publication>

<publication>

    <publication_name> Freedom as independence </publication_name>
    <authors> C List, L Valentini  </authors>
    <publisher> Ethics </publisher>
    <volume> 126 </volume>
    <number> 4 </number>
    <pages> 1043-1074 </pages>
    <citation> 3 </citation>
    <year> 2016 </year>

</publication>

<publication>

    <publication_name> Belief revision generalized: A joint characterization of Bayes' and Jeffrey's rules </publication_name>
    <authors> F Dietrich, C List, R Bradley </authors>
    <publisher> Journal of Economic Theory </publisher>
    <volume> 162</volume>
    <pages> 352–371 </pages>
    <citation> 3 </citation>
    <year> 2016 </year>

</publication>

    <publication>

        <publication_name>Which worlds are possible? A judgment aggregation problem</publication_name>
        <authors>C List</authors>
        <publisher>Journal of Philosophical Logic</publisher>
        <volume>37</volume>
        <number>1</number>
        <pages>57-65</pages>
        <citation>12</citation>
        <year>2008</year>

    </publication>

</publications>

I only want to get the author on the third position.

There is no result and i get an error saying: The XPath query returned no results. XPath scope:current file.

Body:
You can select third author with this xpath

//authors[contains(text(),' C List, RE Goodin ')]


问:
Uncompress GZIP http-response (using jersey client api, java)
Could someone tell me what I need to do in order to uncompress a GZIP content when getting the response from some Http-call.

To make the call I use the Jersey Client API, see code below:

```<code>String baseURI = "http://api.stackoverflow.com/1.1/answers/7539863?body=true&comments=false";
ClientConfig config = new DefaultClientConfig();
Client client = Client.create(config);
WebResource wr = client.resource(baseURI);
ClientResponse response = null;
response = wr.get(ClientResponse.class);
String response_data = response.getEntity(String.class);

System.out.println(response_data);
</code>```

However the output is GZIP’d and looks like:

```<code>{J?J??t??`$?@??????....
</code>```

It would be good if I could implement the following:

being able to detect whether content is GZIP’d or not;

If not, process like normal in a String; if, so uncompress and get the content in String

答:
In Jersey 2.x (I use 2.26):

```<code>WebTarget target = ...
target.register(GZipEncoder.class);
</code>```

Then getEntity(String.class) can be used on the response as usual.

Body:
Could someone tell me what I need to do in order to uncompress a GZIP content when getting the response from some Http-call.

To make the call I use the Jersey Client API, see code below:

String baseURI = "http://api.stackoverflow.com/1.1/answers/7539863?body=true&comments=false";
ClientConfig config = new DefaultClientConfig();
Client client = Client.create(config);
WebResource wr = client.resource(baseURI);
ClientResponse response = null;
response = wr.get(ClientResponse.class);
String response_data = response.getEntity(String.class);

System.out.println(response_data);

However the output is GZIP’d and looks like:

{J?J??t??`$?@??????....

It would be good if I could implement the following:

being able to detect whether content is GZIP’d or not;

If not, process like normal in a String; if, so uncompress and get the content in String

Body:
In Jersey 2.x (I use 2.26):

WebTarget target = ...
target.register(GZipEncoder.class);

Then getEntity(String.class) can be used on the response as usual.


问:
How to check if string1 is the reverse of string2 using recursion (python)
I know how to reverse a string using recursion

```<code>def reverse(s):
    if len(s) == 0:
        return s
    return s[-1] + reverse(s[0 : -1])

def main() :
    r = reverse("Hello!")
    print(r)
    print("Expected: !olleH")
main()
</code>```

However I'm having trouble figuring out how to check if one string is the reverse of a second given two strings. I want the output to be true if it is the reverse, false if it isn't the reverse. Capitals and lowercases ignored. This is what I have so far:

```<code>def isReversed(str1, str2):
    if len(str1) != len(str2):
        return False
</code>```

I'm not sure how to call the function within itself using two arguments.

答:
If both strings are empty, they are clearly mirror images. Otherwise, compare first and last letters and recurse on the rest of the characters.

```<code>def helper(s1, s2):
    if s1 == "" == s2:  # short for s1 == "" and s2 == ""
        return True
    else:
        return s1[0] == s2[-1] and mirror_images(s1[1:], s2[:-1])
</code>```

The above assumes the strings have the same length; it's best to check that once before you start the recursion:

```<code>def mirror_image(s1, s2):
    return len(s1) == len(s2) and helper(s1, s2)
</code>```

Body:
I know how to reverse a string using recursion

def reverse(s):
    if len(s) == 0:
        return s
    return s[-1] + reverse(s[0 : -1])

def main() :
    r = reverse("Hello!")
    print(r)
    print("Expected: !olleH")
main()

However I'm having trouble figuring out how to check if one string is the reverse of a second given two strings. I want the output to be true if it is the reverse, false if it isn't the reverse. Capitals and lowercases ignored. This is what I have so far:

def isReversed(str1, str2):
    if len(str1) != len(str2):
        return False

I'm not sure how to call the function within itself using two arguments.

Body:
If both strings are empty, they are clearly mirror images. Otherwise, compare first and last letters and recurse on the rest of the characters.

def helper(s1, s2):
    if s1 == "" == s2:  # short for s1 == "" and s2 == ""
        return True
    else:
        return s1[0] == s2[-1] and mirror_images(s1[1:], s2[:-1])

The above assumes the strings have the same length; it's best to check that once before you start the recursion:

def mirror_image(s1, s2):
    return len(s1) == len(s2) and helper(s1, s2)


问:
List object has AttributeError for a method in a self-defined class
I'm trying to calculate weighted averages. We just started OOP and I'm not sure if my problem is with that or lists.

Here is my code:

```<code>class WeightedAverage:
    """ Class to compute weighted averages. """

    def __init__(self):
        """ Creates empty lists. """
        scoresList = []
        weightsList = []

    def addScore(self,score,weight):
        scoreBool = checkScore(score)
        weightBool = checkWeight(weight)

        if scoreBool == True and weightBool == True:
            scoresList.append(score)
            weightsList.append(weight)

    def checkScore(scr):
        if scr in range(1,10):
            scrBl = True
        else:
            scrBl = False
        return scrBl

    def checkWeight(wgt):
        if wgt in [0.5,1,1.5,2]:
            wgtBl = True
        else:
            wgtBl = False
        return wgtBl

    def getScores(self,scoresList):
        return scoresList

    def getWeights(self,weightsList):
        return weightsList

    def getWAvg(self,scoresList,weightsList):
        wAvg = [scoresList*weightsList for scoresList,weightsList in zip(scoresList,weightsList)]
        return wAvg

# For testing
def main():
    scoresData = [1.5,3,9.2]
    weightsData = [0.5,2,1]

    wAvg = scoresData.getWAvg(scoresData,weightsData)
    print(wAvg)    # should display 15.95/3
</code>```

Where main() is defined as a means of testing the code in my class.

When I run main(), I get the following TraceBack:

```<code>Traceback (most recent call last):
  File "H:\WeightAverages.py", line 58, in <module>
    main()
  File "H:\WeightAverages.py", line 54, in main
    wAvg = scoresData.getWAvg(scoresData,weightsData)
AttributeError: 'list' object has no attribute 'getWAvg'
</code>```

Is this a problem with my class or is it just a list issue? This is my first time writing OO code so I'm not entirely sure this is even right!

答:
Manoj Jadhav's comment seems to be right. In order to call the getWAvg function, you need to create an instance of the WeightedAverage class.

Here's a version of your code where an instance is created, and used to call the getWavg function. Also notice I changed getWAvg.

```<code>class WeightedAverage:
    """ Class to compute weighted averages. """

    def __init__(self):
        """ Creates empty lists. """
        scoresList = []
        weightsList = []

    def addScore(self,score,weight):
        scoreBool = checkScore(score)
        weightBool = checkWeight(weight)

        if scoreBool == True and weightBool == True:
            scoresList.append(score)
            weightsList.append(weight)

    def checkScore(scr):
        if scr in range(1,10):
            scrBl = True
        else:
            scrBl = False
        return scrBl

    def checkWeight(wgt):
        if wgt in [0.5,1,1.5,2]:
            wgtBl = True
        else:
            wgtBl = False
        return wgtBl

    def getScores(self,scoresList):
        return scoresList

    def getWeights(self,weightsList):
        return weightsList

    def getWAvg(self,scoresList,weightsList):
        wAvg = sum([s*w for s,w in zip(scoresList,weightsList)]) / len(scoresList)
        return wAvg

# For testing
def main():
    scoresData = [1.5,3,9.2]
    weightsData = [0.5,2,1]

    instance = WeightedAverage()
    wAvg = instance.getWAvg(scoresData,weightsData)

    print(wAvg)    # should display 15.95/3
</code>```

Body:
I'm trying to calculate weighted averages. We just started OOP and I'm not sure if my problem is with that or lists.

Here is my code:

class WeightedAverage:
    """ Class to compute weighted averages. """

    def __init__(self):
        """ Creates empty lists. """
        scoresList = []
        weightsList = []

    def addScore(self,score,weight):
        scoreBool = checkScore(score)
        weightBool = checkWeight(weight)

        if scoreBool == True and weightBool == True:
            scoresList.append(score)
            weightsList.append(weight)

    def checkScore(scr):
        if scr in range(1,10):
            scrBl = True
        else:
            scrBl = False
        return scrBl

    def checkWeight(wgt):
        if wgt in [0.5,1,1.5,2]:
            wgtBl = True
        else:
            wgtBl = False
        return wgtBl

    def getScores(self,scoresList):
        return scoresList

    def getWeights(self,weightsList):
        return weightsList

    def getWAvg(self,scoresList,weightsList):
        wAvg = [scoresList*weightsList for scoresList,weightsList in zip(scoresList,weightsList)]
        return wAvg

# For testing
def main():
    scoresData = [1.5,3,9.2]
    weightsData = [0.5,2,1]

    wAvg = scoresData.getWAvg(scoresData,weightsData)
    print(wAvg)    # should display 15.95/3

Where main() is defined as a means of testing the code in my class.

When I run main(), I get the following TraceBack:

Traceback (most recent call last):
  File "H:\WeightAverages.py", line 58, in <module>
    main()
  File "H:\WeightAverages.py", line 54, in main
    wAvg = scoresData.getWAvg(scoresData,weightsData)
AttributeError: 'list' object has no attribute 'getWAvg'

Is this a problem with my class or is it just a list issue? This is my first time writing OO code so I'm not entirely sure this is even right!

Body:
Manoj Jadhav's comment seems to be right. In order to call the getWAvg function, you need to create an instance of the WeightedAverage class.

Here's a version of your code where an instance is created, and used to call the getWavg function. Also notice I changed getWAvg.

class WeightedAverage:
    """ Class to compute weighted averages. """

    def __init__(self):
        """ Creates empty lists. """
        scoresList = []
        weightsList = []

    def addScore(self,score,weight):
        scoreBool = checkScore(score)
        weightBool = checkWeight(weight)

        if scoreBool == True and weightBool == True:
            scoresList.append(score)
            weightsList.append(weight)

    def checkScore(scr):
        if scr in range(1,10):
            scrBl = True
        else:
            scrBl = False
        return scrBl

    def checkWeight(wgt):
        if wgt in [0.5,1,1.5,2]:
            wgtBl = True
        else:
            wgtBl = False
        return wgtBl

    def getScores(self,scoresList):
        return scoresList

    def getWeights(self,weightsList):
        return weightsList

    def getWAvg(self,scoresList,weightsList):
        wAvg = sum([s*w for s,w in zip(scoresList,weightsList)]) / len(scoresList)
        return wAvg

# For testing
def main():
    scoresData = [1.5,3,9.2]
    weightsData = [0.5,2,1]

    instance = WeightedAverage()
    wAvg = instance.getWAvg(scoresData,weightsData)

    print(wAvg)    # should display 15.95/3


问:
Delphi TIdHttp with proxy sometimes no timeout and a GET does not return
I use Delphi 10.2 Tokyo with Indy (the integrated version).

Scenario:
I do http GET requests (TIdHttp) in threads, and use proxies.
Sometimes, a proxy seems to cause Indy not to timeout, and not to return from a GET.
I also assign the onWork event handler to react to an Abort button and call within this handler the idHttp.Disconnect function. When the GET seems to be frozen, the abort also does not work, possible that in this case the onWork event is not triggered, I have no idea.

The main thread is idle and only create lets say 50 threads, each does a GET via its instance of TIdHttp. Ans sometiumes, as I mentioend, a proxy cause of GET not to return which result then in a "hanging" thread.

My question is: How can I force Indy to abort, from an external thread? Is there anything what can be done via code when the GET refuse to return?

答:
I solved my issues by using a background thread to disconnect sockets and implement a timeout, which seems to work even socket are "frozen" and the onWork is not triggered.
I do this by adding the TIdHttp instances I create to an array, together with the time the instance was created. If the GET return normal, the array entry will be removed. In a background thread, I check if the user clicked Abort, and then loop through the array and call disconnect on each instance. I also check in the same thread if a timeout period was reached, and also call disconnect.
Might not be the perfect solution, but it works for me.</p>


问:
Get all records arranged by maximum number of columns matched
I'm looking out for a way to get all records from a table arranged or ordered in such a way that maximum number of columns matched are at top and then further

Example: Table Name(Vehicle)

```<code>Id     Name    VehicleMileage    VehicleAverage    VehicleCC    Gear
1    Vehicle1     30HP@2000         25000             1000        3
2    Vehicle2     30HP@2000         22000             8000        2
3    Vehicle3     20HP@2000         21000             5000        4
4    Vehicle4     60HP@2000         25000             1000        3
5    Vehicle5     70HP@2000         23000             3000        3
</code>```

Over here lets assume the searched parameters are as follows:

```<code>VehicleMileage: 30HP@2000
VehicleAverage: 25000
VehicleCC: 1000
Gear: 3
</code>```

The queried result would be in following order:

```<code>Vehicle1 (Reason: 4 matched columns)
Vehicle4 (Reason: 3 matched columns)
Vehicle2 (Reason: 1 matched column)
Vehicle5 (Reason: 1 matched column)
Vehicle3 (No matched column)
</code>```

My database is on SQL server.

答:
Try some thing like this</p>

```<code>SELECT Name + ' (Reason: '+CAST(MatchCount AS VARCHAR)+' matched columns)'
FROM (
        SELECT NAME,(CASE WHEN VehicleMileage ='30HP@2000' THEN 1 ELSE 0 END +
                     CASE WHEN VehicleAverage='25000' THEN 1 ELSE 0 END +
                     CASE WHEN VehicleCC =1000 THEN 1 ELSE 0 END +
                     CASE WHEN Gear =3 THEN 1 ELSE 0 END ) AS MatchCount
       FROM TableName
)t
ORDER BY MatchCount
</code>```

Body:
I'm looking out for a way to get all records from a table arranged or ordered in such a way that maximum number of columns matched are at top and then further

Example: Table Name(Vehicle)

Id     Name    VehicleMileage    VehicleAverage    VehicleCC    Gear
1    Vehicle1     30HP@2000         25000             1000        3
2    Vehicle2     30HP@2000         22000             8000        2
3    Vehicle3     20HP@2000         21000             5000        4
4    Vehicle4     60HP@2000         25000             1000        3
5    Vehicle5     70HP@2000         23000             3000        3

Over here lets assume the searched parameters are as follows:

VehicleMileage: 30HP@2000
VehicleAverage: 25000
VehicleCC: 1000
Gear: 3

The queried result would be in following order:

Vehicle1 (Reason: 4 matched columns)
Vehicle4 (Reason: 3 matched columns)
Vehicle2 (Reason: 1 matched column)
Vehicle5 (Reason: 1 matched column)
Vehicle3 (No matched column)

My database is on SQL server.

Body:
Try some thing like this

SELECT Name + ' (Reason: '+CAST(MatchCount AS VARCHAR)+' matched columns)'
FROM (
        SELECT NAME,(CASE WHEN VehicleMileage ='30HP@2000' THEN 1 ELSE 0 END +
                     CASE WHEN VehicleAverage='25000' THEN 1 ELSE 0 END +
                     CASE WHEN VehicleCC =1000 THEN 1 ELSE 0 END +
                     CASE WHEN Gear =3 THEN 1 ELSE 0 END ) AS MatchCount
       FROM TableName
)t
ORDER BY MatchCount


问:
java.lang.IllegalArgumentException: No suitable parent found from the given view. Please provide a valid view
my app crashes when trying to display server message and I think the problem could be with my getView(). below is the registerActivity were the crash occurs and my activity_register.xml

```<code>import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.fastchat.helper.SQLiteHandler;
import com.fastchat.helper.SessionManager;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class RegisterActivity extends Activity {

private static final String TAG = RegisterActivity.class.getSimpleName();
private Button btnRegister;
private Button btnLinkToLogin;
private EditText inputFullName;
private EditText inputEmail;
private EditText inputPassword;
private ProgressDialog pDialog;
private SessionManager session;
private SQLiteHandler db;
private ProgressBar progress;

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

    inputFullName = (EditText) findViewById(R.id.name);
    inputEmail = (EditText) findViewById(R.id.email);
    inputPassword = (EditText) findViewById(R.id.password);
    btnRegister = (Button) findViewById(R.id.btnRegister);
    btnLinkToLogin = (Button) findViewById(R.id.btnLinkToLoginScreen);

    // Progress dialog
    pDialog = new ProgressDialog(this);
    pDialog.setCancelable(true);

    /*
    // Session manager
    session = new SessionManager(getApplicationContext());

    // SQLite database handler
    db = new SQLiteHandler(getApplicationContext());

    // Check if user is already logged in or not
   if (session.isLoggedIn()) {
        // User is already logged in. Take him to main activity
        Intent intent = new Intent(RegisterActivity.this,
                SearchableActivity.class);
        startActivity(intent);
        finish();

    }
*/
    // Register Button Click event
    btnRegister.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            String name = inputFullName.getText().toString();
            String email = inputEmail.getText().toString();
            String password = inputPassword.getText().toString();

            if (!name.isEmpty() && !email.isEmpty() && !password.isEmpty()) {
                registerProcess(name, email, password);
            } else {
                Toast.makeText(getApplicationContext(),
                        "Please enter your details!", Toast.LENGTH_LONG)
                        .show();
            }
        }
    });

    // Link to Login Screen
    btnLinkToLogin.setOnClickListener(new View.OnClickListener() {

        public void onClick(View view) {
            Intent i = new Intent(getApplicationContext(),
                    LoginActivity.class);
            startActivity(i);
            finish();
        }
    });

}

 private void registerProcess(String name,String email,String password){

    String tag_string_req = "req_register";
    //pDialog = new AlertDialog.Builder(getActivity());
    pDialog.setMessage("please wait");
    pDialog.show();

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(Constants.BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .build();

    RequestInterface requestInterface = retrofit.create(RequestInterface.class);

    User user = new User();
    user.setName(name);
    user.setEmail(email);
    user.setPassword(password);
    ServerRequest request = new ServerRequest();
    request.setOperation(Constants.REGISTER_OPERATION);
    request.setUser(user);
    Call<ServerResponse> response = requestInterface.operation(request);

    response.enqueue(new Callback<ServerResponse>() {
        private View view;

        public View getView() {
            return view;

        }

        @Override
        public void onResponse(Call<ServerResponse> call, retrofit2.Response<ServerResponse> response) {

            ServerResponse resp = response.body();

           if(resp !=null)//tried to check if resp is null but its not

//crash occurs here
            Snackbar.make(getView(),resp.getMessage(), Snackbar.LENGTH_LONG).show();
            pDialog.dismiss();
        }

        @Override
        public void onFailure(Call<ServerResponse> call, Throwable t) {

           // progress.setVisibility(View.INVISIBLE);
            Log.d(Constants.TAG, "failed");
            Toast.makeText(getApplicationContext(), t.getLocalizedMessage(), Toast.LENGTH_LONG).show();
            pDialog.dismiss();

        }
    });
}
</code>```

activity_register.xml

```<code>  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:tools="http://schemas.android.com/tools"
android:background="@color/bg_register"
android:gravity="center"
android:orientation="vertical"
android:padding="10dp"
android:id="@+id/chat">

<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:orientation="vertical"
    android:paddingLeft="20dp"
    android:paddingRight="20dp" >

    <ImageView
        android:layout_width="389dp"
        android:layout_height="72dp"
        android:layout_gravity="center_horizontal"
        android:layout_marginBottom="24dp"
        android:src="@drawable/logo"
        tools:ignore="ContentDescription" />

    <EditText
        android:id="@+id/name"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="10dp"
        android:background="@color/input_register_bg"
        android:hint="@string/hint_name"
        android:padding="10dp"
        android:singleLine="true"
        android:inputType="textCapWords"
        android:textColor="@color/input_register"
        android:textColorHint="@color/input_register_hint" />

    <EditText
        android:id="@+id/email"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="10dp"
        android:background="@color/input_register_bg"
        android:hint="@string/hint_email"
        android:inputType="textEmailAddress"
        android:padding="10dp"
        android:singleLine="true"
        android:textColor="@color/input_register"
        android:textColorHint="@color/input_register_hint" />

    <EditText
        android:id="@+id/password"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="10dp"
        android:background="@color/input_register_bg"
        android:hint="@string/hint_password"
        android:inputType="textPassword"
        android:padding="10dp"
        android:singleLine="true"
        android:textColor="@color/input_register"
        android:textColorHint="@color/input_register_hint" />

    <!-- Login Button -->

    <Button
        android:id="@+id/btnRegister"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dip"
        android:background="#ea4c88"
        android:text="register"
        android:textColor="@color/white" />

    <!-- Link to Login Screen -->

    <Button
        android:id="@+id/btnLinkToLoginScreen"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="40dip"
        android:background="@null"
        android:text="already a member? login"
        android:textAllCaps="false"
        android:textColor="@color/white"
        android:textSize="15dp" />
</LinearLayout>
</code>```

below is logcat message

```<code> java.lang.IllegalArgumentException: No suitable parent found from the given view. Please provide a valid view.
                                                              at android.support.design.widget.Snackbar.make(Snackbar.java:137)
                                                              at com.chat.RegisterActivity$3.onResponse(RegisterActivity.java:143)
                                                              at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall$1$1.run(ExecutorCallAdapterFactory.java:68)
                                                              at android.os.Handler.handleCallback(Handler.java:739)
                                                              at android.os.Handler.dispatchMessage(Handler.java:95)
</code>```

答:
Instead of this :

```<code>Snackbar.make(getView(),resp.getMessage(), Snackbar.LENGTH_LONG).show();
</code>```

Replace getView() with an existing view component of your current activity, like this:

```<code>Snackbar.make(findViewById(R.id. chat),resp.getMessage(), Snackbar.LENGTH_LONG).show();
</code>```

Body:
my app crashes when trying to display server message and I think the problem could be with my getView(). below is the registerActivity were the crash occurs and my activity_register.xml

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.fastchat.helper.SQLiteHandler;
import com.fastchat.helper.SessionManager;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class RegisterActivity extends Activity {

private static final String TAG = RegisterActivity.class.getSimpleName();
private Button btnRegister;
private Button btnLinkToLogin;
private EditText inputFullName;
private EditText inputEmail;
private EditText inputPassword;
private ProgressDialog pDialog;
private SessionManager session;
private SQLiteHandler db;
private ProgressBar progress;

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

    inputFullName = (EditText) findViewById(R.id.name);
    inputEmail = (EditText) findViewById(R.id.email);
    inputPassword = (EditText) findViewById(R.id.password);
    btnRegister = (Button) findViewById(R.id.btnRegister);
    btnLinkToLogin = (Button) findViewById(R.id.btnLinkToLoginScreen);

    // Progress dialog
    pDialog = new ProgressDialog(this);
    pDialog.setCancelable(true);

    /*
    // Session manager
    session = new SessionManager(getApplicationContext());

    // SQLite database handler
    db = new SQLiteHandler(getApplicationContext());

    // Check if user is already logged in or not
   if (session.isLoggedIn()) {
        // User is already logged in. Take him to main activity
        Intent intent = new Intent(RegisterActivity.this,
                SearchableActivity.class);
        startActivity(intent);
        finish();

    }
*/
    // Register Button Click event
    btnRegister.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            String name = inputFullName.getText().toString();
            String email = inputEmail.getText().toString();
            String password = inputPassword.getText().toString();

            if (!name.isEmpty() && !email.isEmpty() && !password.isEmpty()) {
                registerProcess(name, email, password);
            } else {
                Toast.makeText(getApplicationContext(),
                        "Please enter your details!", Toast.LENGTH_LONG)
                        .show();
            }
        }
    });

    // Link to Login Screen
    btnLinkToLogin.setOnClickListener(new View.OnClickListener() {

        public void onClick(View view) {
            Intent i = new Intent(getApplicationContext(),
                    LoginActivity.class);
            startActivity(i);
            finish();
        }
    });

}

 private void registerProcess(String name,String email,String password){

    String tag_string_req = "req_register";
    //pDialog = new AlertDialog.Builder(getActivity());
    pDialog.setMessage("please wait");
    pDialog.show();

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(Constants.BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .build();

    RequestInterface requestInterface = retrofit.create(RequestInterface.class);

    User user = new User();
    user.setName(name);
    user.setEmail(email);
    user.setPassword(password);
    ServerRequest request = new ServerRequest();
    request.setOperation(Constants.REGISTER_OPERATION);
    request.setUser(user);
    Call<ServerResponse> response = requestInterface.operation(request);

    response.enqueue(new Callback<ServerResponse>() {
        private View view;

        public View getView() {
            return view;

        }

        @Override
        public void onResponse(Call<ServerResponse> call, retrofit2.Response<ServerResponse> response) {

            ServerResponse resp = response.body();

           if(resp !=null)//tried to check if resp is null but its not

//crash occurs here
            Snackbar.make(getView(),resp.getMessage(), Snackbar.LENGTH_LONG).show();
            pDialog.dismiss();
        }

        @Override
        public void onFailure(Call<ServerResponse> call, Throwable t) {

           // progress.setVisibility(View.INVISIBLE);
            Log.d(Constants.TAG, "failed");
            Toast.makeText(getApplicationContext(), t.getLocalizedMessage(), Toast.LENGTH_LONG).show();
            pDialog.dismiss();

        }
    });
}

activity_register.xml

  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:tools="http://schemas.android.com/tools"
android:background="@color/bg_register"
android:gravity="center"
android:orientation="vertical"
android:padding="10dp"
android:id="@+id/chat">

<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:orientation="vertical"
    android:paddingLeft="20dp"
    android:paddingRight="20dp" >

    <ImageView
        android:layout_width="389dp"
        android:layout_height="72dp"
        android:layout_gravity="center_horizontal"
        android:layout_marginBottom="24dp"
        android:src="@drawable/logo"
        tools:ignore="ContentDescription" />

    <EditText
        android:id="@+id/name"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="10dp"
        android:background="@color/input_register_bg"
        android:hint="@string/hint_name"
        android:padding="10dp"
        android:singleLine="true"
        android:inputType="textCapWords"
        android:textColor="@color/input_register"
        android:textColorHint="@color/input_register_hint" />

    <EditText
        android:id="@+id/email"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="10dp"
        android:background="@color/input_register_bg"
        android:hint="@string/hint_email"
        android:inputType="textEmailAddress"
        android:padding="10dp"
        android:singleLine="true"
        android:textColor="@color/input_register"
        android:textColorHint="@color/input_register_hint" />

    <EditText
        android:id="@+id/password"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="10dp"
        android:background="@color/input_register_bg"
        android:hint="@string/hint_password"
        android:inputType="textPassword"
        android:padding="10dp"
        android:singleLine="true"
        android:textColor="@color/input_register"
        android:textColorHint="@color/input_register_hint" />

    <Button
        android:id="@+id/btnRegister"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dip"
        android:background="#ea4c88"
        android:text="register"
        android:textColor="@color/white" />

    <Button
        android:id="@+id/btnLinkToLoginScreen"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="40dip"
        android:background="@null"
        android:text="already a member? login"
        android:textAllCaps="false"
        android:textColor="@color/white"
        android:textSize="15dp" />
</LinearLayout>

below is logcat message

 java.lang.IllegalArgumentException: No suitable parent found from the given view. Please provide a valid view.
                                                              at android.support.design.widget.Snackbar.make(Snackbar.java:137)
                                                              at com.chat.RegisterActivity$3.onResponse(RegisterActivity.java:143)
                                                              at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall$1$1.run(ExecutorCallAdapterFactory.java:68)
                                                              at android.os.Handler.handleCallback(Handler.java:739)
                                                              at android.os.Handler.dispatchMessage(Handler.java:95)

Body:
Instead of this :

Snackbar.make(getView(),resp.getMessage(), Snackbar.LENGTH_LONG).show();

Replace getView() with an existing view component of your current activity, like this:

Snackbar.make(findViewById(R.id. chat),resp.getMessage(), Snackbar.LENGTH_LONG).show();


问:
How to get all route params/data
Given a route config

```<code>{
   path: '/root/:rootId',
   children: [{
       path: '/child1/:child1Id',
       children: [{
           path: '/child2/:child2Id
           component: TestComponent
       }]
   }]
}
</code>```

In TestComponent how can I easily get all route params. I'm wondering if there is an easier way than

```<code>let rootId = route.parent.parent.snapshot.params;
let child1Id = route.parent.snapshot.params;
let child2Id = route.snapshot.params;
</code>```

This seems overly redundant especially if I'm watching the route params observable instead of access the param through the route snapshot. This method also seems fragile since it would break If I moved any any of the routes/params around. Im used to angular ui-router where a single object $stateParams was supplied with all param data easily accessible. I have these same concerns with route resolved data along being accessed from a single node in the route tree. Any help would be much appreciated. Thanks in advance

答:
```<code>constructor(private route: ActivatedRoute) {}

data$ = of(this.route).pipe(
    expand(route => of(route['parent'])),
    takeWhile(route => !!route['parent']),
    pluck('snapshot', 'data'),
    reduce(merge));
</code>```

Explanation:

Calling expand here creates an observable for each route in the parent chain. Takewhile is used so that it stops recursing when route['parent'] returns null, or at the root route.

Then, for all of those routes in the observable, pluck will map each to it's 'snapshot.data' property.

Finally, reduce is being fed the merge function from lodash to combine all the data objects into one object. This stream aggregates all the data from the current route through the parent routes

Title: How to get all route params/data

Body:
Given a route config

{
   path: '/root/:rootId',
   children: [{
       path: '/child1/:child1Id',
       children: [{
           path: '/child2/:child2Id
           component: TestComponent
       }]
   }]
}

In TestComponent how can I easily get all route params. I'm wondering if there is an easier way than

let rootId = route.parent.parent.snapshot.params;
let child1Id = route.parent.snapshot.params;
let child2Id = route.snapshot.params;

This seems overly redundant especially if I'm watching the route params observable instead of access the param through the route snapshot. This method also seems fragile since it would break If I moved any any of the routes/params around. Im used to angular ui-router where a single object $stateParams was supplied with all param data easily accessible. I have these same concerns with route resolved data along being accessed from a single node in the route tree. Any help would be much appreciated. Thanks in advance

Body:
constructor(private route: ActivatedRoute) {}

data$ = of(this.route).pipe(
    expand(route => of(route['parent'])),
    takeWhile(route => !!route['parent']),
    pluck('snapshot', 'data'),
    reduce(merge));

Explanation:

Calling expand here creates an observable for each route in the parent chain. Takewhile is used so that it stops recursing when route['parent'] returns null, or at the root route.

Then, for all of those routes in the observable, pluck will map each to it's 'snapshot.data' property.

Finally, reduce is being fed the merge function from lodash to combine all the data objects into one object. This stream aggregates all the data from the current route through the parent routes


答:
```<code>>>> qq = 'xyz'
>>> ww = 'zyx'
>>> qq == ww
 False
>>> ww[::-1]
 'xyz'
>>> qq == ww[::-1]
 True
</code>```

use can use lower() to take care of the case
here is a fuller solution:

```<code>In [130]: def rev(x, y):
     ...:     if x == '' and y == '':
     ...:         return True
     ...:     elif x == '' or y == '':
     ...:         return False
     ...:     elif x[0].lower() != y[-1].lower():
     ...:         return False
     ...:     else:
     ...:         return rev(x[1:], y[:-1])
     ...:
     ...:
In [131]: rev('abc', 'cba')
Out[131]: True
In [132]: rev('abc', 'cb')
Out[132]: False
In [133]: rev('abc', '')
Out[133]: False
In [134]: rev('', '')
Out[134]: True
</code>```

Title: How to check if string1 is the reverse of string2 using recursion (python)

Body:
>>> qq = 'xyz'
>>> ww = 'zyx'
>>> qq == ww
 False
>>> ww[::-1]
 'xyz'
>>> qq == ww[::-1]
 True

use can use lower() to take care of the case
here is a fuller solution:

In [130]: def rev(x, y):
     ...:     if x == '' and y == '':
     ...:         return True
     ...:     elif x == '' or y == '':
     ...:         return False
     ...:     elif x[0].lower() != y[-1].lower():
     ...:         return False
     ...:     else:
     ...:         return rev(x[1:], y[:-1])
     ...:
     ...:
In [131]: rev('abc', 'cba')
Out[131]: True
In [132]: rev('abc', 'cb')
Out[132]: False
In [133]: rev('abc', '')
Out[133]: False
In [134]: rev('', '')
Out[134]: True


问:
Why doesn't this code work? Combination of for and if for a "test" login page
I'm trying to make some kind of login page (I don't care about security or some sort. This is a test, and I'm not even that advanced of a coder. And I'm struggling with the coding. I want to make it as:

```<code>    If the username was filled in as "Ardent" and the password as "1",
        Say something like "Welcome!"
    If the username or(and) the password are(is) incorrect,
        alert("The username and password is incorrect.");
and make it loop, leading to asking for username and password again.
</code>```

So, this is what I coded (I could not find out how this can work, so I don't even have the basic structure of it).

```<code>for([id == prompt("What is your ID?"), password == prompt("What is your password?")];
     id == "Ardent" || password == "1" ;) {

    prompt("What is your ID?");
    prompt("What is your password?");
    if(id == "Ardent" || password == "1") {
        alert("Welcome back!");
    }
}
</code>```

Thank you!
Sorry if it is actually a complete mess :(
I'm so bad at coding and I'm just a beginner.

答:
You can start with very clear code as per below.

while(true){
    var username = prompt("What is your username");
    var password = prompt("What is your password");

    if(username == "Ardent" && password == "1"){
       alert("Welcome");
        break;
    }
    else{
       alert("Try again");
    }
}```

Hope it helps.

Body:
I'm trying to make some kind of login page (I don't care about security or some sort. This is a test, and I'm not even that advanced of a coder. And I'm struggling with the coding. I want to make it as:

    If the username was filled in as "Ardent" and the password as "1",
        Say something like "Welcome!"
    If the username or(and) the password are(is) incorrect,
        alert("The username and password is incorrect.");
and make it loop, leading to asking for username and password again.

So, this is what I coded (I could not find out how this can work, so I don't even have the basic structure of it).

for([id == prompt("What is your ID?"), password == prompt("What is your password?")];
     id == "Ardent" || password == "1" ;) {

    prompt("What is your ID?");
    prompt("What is your password?");
    if(id == "Ardent" || password == "1") {
        alert("Welcome back!");
    }
}

Thank you!
Sorry if it is actually a complete mess :(
I'm so bad at coding and I'm just a beginner.

Body:
You can start with very clear code as per below.

while(true){
    var username = prompt("What is your username");
    var password = prompt("What is your password");

    if(username == "Ardent" && password == "1"){
       alert("Welcome");
        break;
    }
    else{
       alert("Try again");
    }
}

Hope it helps.


问:
Linq to SQL Case WHEN in VB.NET?
How do I do a Case WHEN in Linq to SQL (vb.net please).

In SQL it would be like this:

```<code>SELECT
CASE
  WHEN condition THEN trueresult
  [...n]
[ELSE elseresult]
END
</code>```

How would I do this in Linq to SQL?

答:
I haven't tried this but you may be able to do something like:

```<code>Dim query = From tbl In db.Table _
            Select result =_
                If(tbl.Col1 < tbl.Col2,"Less than",_
                    If(tbl.Col1 = tbl.Col2,"Equal to","Greater than"))
</code>```

You would just need to keep nesting the If functions to handle all of your cases.

You can find more examples of various queries at http://msdn.microsoft.com/en-us/library/bb386913.aspx

OwnerDisplayName: EdenMachine

ContentLicense: CC BY-SA 2.5

Title: Linq to SQL Case WHEN in VB.NET?

Body:
How do I do a Case WHEN in Linq to SQL (vb.net please).

In SQL it would be like this:

SELECT
CASE
  WHEN condition THEN trueresult
  [...n]
[ELSE elseresult]
END

How would I do this in Linq to SQL?

LastEditorDisplayName: Fabian Steeg

Body:
I haven't tried this but you may be able to do something like:

Dim query = From tbl In db.Table _
            Select result =_
                If(tbl.Col1 < tbl.Col2,"Less than",_
                    If(tbl.Col1 = tbl.Col2,"Equal to","Greater than"))

You would just need to keep nesting the If functions to handle all of your cases.

You can find more examples of various queries at http://msdn.microsoft.com/en-us/library/bb386913.aspx

OwnerDisplayName: tvanfosson