问:
Oracle - How to get date from YEAR, WEEKNUM and WEEKDAY?
I need to find the date of particular year, week, and weekday in oracle.
Is there a built-in function for this in oracle? or how can I achieve this?

Ex: If Year=2019, Week=22, Day=2(Tuesday), Then date should be '28-05-2019'.

答:
Assuming "Week" and "Year" means week and year according to ISO-8601 you can use this function:</p>

```<code>CREATE OR REPLACE FUNCTION ISOWeekDate(YEAR INTEGER, WEEK INTEGER, DAY INTEGER) RETURN DATE DETERMINISTIC IS
    res DATE;
BEGIN
    IF WEEK > 53 OR WEEK < 1 THEN
        RAISE VALUE_ERROR;
    END IF;

    res := NEXT_DAY(TO_DATE( YEAR || '0104', 'YYYYMMDD' ) - INTERVAL '7' DAY, 'MONDAY') + ( WEEK - 1 ) * 7;

    IF TO_CHAR(res, 'fmIYYY') = YEAR THEN
        RETURN res + DAY - 1;
    ELSE
        RAISE VALUE_ERROR;
    END IF;
END ISOWeekDate;
</code>```

Body:
Assuming "Week" and "Year" means week and year according to ISO-8601 you can use this function:

CREATE OR REPLACE FUNCTION ISOWeekDate(YEAR INTEGER, WEEK INTEGER, DAY INTEGER) RETURN DATE DETERMINISTIC IS
    res DATE;
BEGIN
    IF WEEK > 53 OR WEEK < 1 THEN
        RAISE VALUE_ERROR;
    END IF;

    res := NEXT_DAY(TO_DATE( YEAR || '0104', 'YYYYMMDD' ) - INTERVAL '7' DAY, 'MONDAY') + ( WEEK - 1 ) * 7;

    IF TO_CHAR(res, 'fmIYYY') = YEAR THEN
        RETURN res + DAY - 1;
    ELSE
        RAISE VALUE_ERROR;
    END IF;
END ISOWeekDate;


来源: stackexchange

问:
Query to find accounts with specified months
I Want to extract those account ids which are present in may and JUNE but not in JULY . I have data for 6 months

i have tried using CONDITION(AND/ NOT)

```<code>SELECT ACCOUNT_ID, DATA_MONTH
FROM DATA1
WHERE DATA_MONTH ='01-MAY-18' AND DATA_MONTH <> '01-JULY-18
GROUP BY DATA_MONTH
</code>```

I am still getting account ids which where in JULY

答:
```<code>SELECT ACCOUNT_ID, DATA_MONTH
FROM DATA1
WHERE MONTH(DATA_MONTH) =5 AND MONTH(DATA_MONTH) = 6
GROUP BY DATA_MONTH
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I Want to extract those account ids which are present in may and JUNE but not in JULY . I have data for 6 months

i have tried using CONDITION(AND/ NOT)

SELECT ACCOUNT_ID, DATA_MONTH
FROM DATA1
WHERE DATA_MONTH ='01-MAY-18' AND DATA_MONTH <> '01-JULY-18
GROUP BY DATA_MONTH

I am still getting account ids which where in JULY


问:
How to identify if certain keys are present in dictonary?
I have dictonary named as Entity which look like this:

```<code>Entity = {'ORG': 'ABC','PERSON': 'Ankit','ORDINAL': '150th','DATE': 'quarterly', 'MONEY': 'dollars'}
</code>```

Now I have to create other dictionary which will contain below value according to condition.

```<code>Class = {'Signal':'<Condition>'}
</code>```

The condition is:

If Entity key consists of ORG and PERSON then in Class dictionary value "Medium" should be updated.

If Entity key consists of ORG, PERSON, and MONEY then in Class dictionary value "Strong" should be updated.

If Entity key doesn't consist of above keys then in Class dictionary value "Weak" should be updated.

How should I make the condition for the above problem?

I want an output in Class dictionary like below,

If in Entity dictionary there are ORG and PERSIN keys then Class dictionary should be like,

```<code>Class = {'Signal' : 'Medium'}
</code>```

答:
```<code>if all([a in Entity for a in ('ORG', 'PERSON', 'MONEY')]):
    Class['Signal'] = 'strong'
elif all([a in Entity for a in ('ORG', 'PERSON')]):
    Class['Signal'] = 'middle'
elif not any([a in Entity for a in ('ORG', 'PERSON', 'MONEY')]):
    Class['Signal'] = 'weak'
</code>```

Note that, according to your question, if Entity contains only 'ORG' or only 'PERSON', no 'Signal' will be set in Class.

Body:
I have dictonary named as Entity which look like this:

Entity = {'ORG': 'ABC','PERSON': 'Ankit','ORDINAL': '150th','DATE': 'quarterly', 'MONEY': 'dollars'}

Now I have to create other dictionary which will contain below value according to condition.

Class = {'Signal':'<Condition>'}

The condition is:

If Entity key consists of ORG and PERSON then in Class dictionary value "Medium" should be updated.

If Entity key consists of ORG, PERSON, and MONEY then in Class dictionary value "Strong" should be updated.

If Entity key doesn't consist of above keys then in Class dictionary value "Weak" should be updated.

How should I make the condition for the above problem?

I want an output in Class dictionary like below,

If in Entity dictionary there are ORG and PERSIN keys then Class dictionary should be like,

Class = {'Signal' : 'Medium'}

Body:
if all([a in Entity for a in ('ORG', 'PERSON', 'MONEY')]):
    Class['Signal'] = 'strong'
elif all([a in Entity for a in ('ORG', 'PERSON')]):
    Class['Signal'] = 'middle'
elif not any([a in Entity for a in ('ORG', 'PERSON', 'MONEY')]):
    Class['Signal'] = 'weak'

Note that, according to your question, if Entity contains only 'ORG' or only 'PERSON', no 'Signal' will be set in Class.


问:
TypeError: undefined is not a function near this.state.cafes.map
I'm trying to pass on a cafe from my backend, but without any luck. I have no clue what I'm doing wrong here, but any help would be appreciated. BTW. it's written in typescript.

```<code>interface Props {}
interface State {
  cafes: {
    Id: number;
    Name: string;
    Address: string;
    PhoneNo: string;
    PriceRange: number;
    OpenTime: Date;
    CloseTime: Date;
    Zip: string;
    CustomerType: number;
    Description: string;
    City: string;
    }[];
}

export default class ListCafes extends React.Component<Props, State> {
   static navigationOptions: NavigationScreenOptions = {
    headerTitle: "Cafes"
  };

  constructor(props: Props) {
    super(props);
    this.state = {
      cafes: []
    };
  }

  async componentDidMount() {
    try {
      let cafes = await json(
        "https://toobuzyservice.azurewebsites.net/cafe/zip/9000?format=json"
      );
      this.setState({ cafes });
    } catch (error) {
      console.log(error);
      Alert.alert(
        "Ups! Something went wrong.. Our monkey are going to fix it! Hold on!!"
      );
    }
  }

  renderCafes() {
    return this.state.cafes.map(cafes => {
      return <CafePreviewCard key={cafes.Id} cafe={cafes} />;
    });
  }

  render() {
    return (
      <View style={styles.container}>
        <ScrollView>{this.renderCafes()}</ScrollView>
      </View>
    );
  }
}
</code>```

Keep getting error: TypeError: undefined is not a function (near 'this.state.cafes.map') at renderCafes function.

答:
Your this.state.cafes contains non array value. check its value using console.log(this.state.cafes) to check that the response is not an array.

you cant map a value that is not an array.

Body:
I'm trying to pass on a cafe from my backend, but without any luck. I have no clue what I'm doing wrong here, but any help would be appreciated. BTW. it's written in typescript.

interface Props {}
interface State {
  cafes: {
    Id: number;
    Name: string;
    Address: string;
    PhoneNo: string;
    PriceRange: number;
    OpenTime: Date;
    CloseTime: Date;
    Zip: string;
    CustomerType: number;
    Description: string;
    City: string;
    }[];
}

export default class ListCafes extends React.Component<Props, State> {
   static navigationOptions: NavigationScreenOptions = {
    headerTitle: "Cafes"
  };

  constructor(props: Props) {
    super(props);
    this.state = {
      cafes: []
    };
  }

  async componentDidMount() {
    try {
      let cafes = await json(
        "https://toobuzyservice.azurewebsites.net/cafe/zip/9000?format=json"
      );
      this.setState({ cafes });
    } catch (error) {
      console.log(error);
      Alert.alert(
        "Ups! Something went wrong.. Our monkey are going to fix it! Hold on!!"
      );
    }
  }

  renderCafes() {
    return this.state.cafes.map(cafes => {
      return <CafePreviewCard key={cafes.Id} cafe={cafes} />;
    });
  }

  render() {
    return (
      <View style={styles.container}>
        <ScrollView>{this.renderCafes()}</ScrollView>
      </View>
    );
  }
}

Keep getting error: TypeError: undefined is not a function (near 'this.state.cafes.map') at renderCafes function.


问:
Angular - Life-cycle: Child component to be fully loaded
Is it possible for a parent component to be notified for a child component to be loaded especially when it comes to ng-container and ng-template.

As in Yes! I see that you've grown strong, my child!

Say we have a component like this:

@Component({
  selector: 'my-app',
  template: `
  <ng-container *ngIf="!showElse; else elseBlock">

Hi!

  </ng-container>
  <ng-template #elseBlock>
    <hello name="{{ name }}"></hello>
  </ng-template>
  <button (click)="showElse = !showElse">Show else</button>
  `,
  styles: ['']
})
export class AppComponent  {
  name = 'Angular';
  showElse = false;
  @ViewChild('hello') hello: HelloComponent;
}
```

Is there a way for AppComponent to know if HelloComponentis fully loaded or do I need a custom solution inside HelloComponent?

I'm currently sitting with a less-than-optimal solution (a setTimeout() based stuff that I don't like).

Here's what I'm thinking about:

- Add an EventEmitter to my HelloComponent;

- Use the HelloComponent's life cycle to emit an event during, say, ngAfterContentChecked

- Intercept this event in my AppComponent and do the thing.

What are your thoughts on that subject?

Edit

So far, I've tried what you've suggested (hook to AfterViewInit, make use of @ViewChildren...) but had no success.

Just to be sure, I tried again without the <ng-container>...<ng-template> stuff and simply hiding my HelloComponent using the [hidden] directive...

By emitting an event during the HelloComponent's AfterContentChecked and hooking this event in AppComponent, it works like a charm. (see on stackblitz )

This solution is way more classy than my previous setTimeout-based one

Now, the reason I wanted to make use of the <ng-container>...<ng-template> mechanic is because my actual component is just a tiny bit heavier than the example HelloComponent.

If anyone has a better idea to keep using the container-template mechanic, I'm all ears.

答:
You can attach to AfterViewInit , but it's not the case always, consider you have *ngIf on your child component, then you need to do this.

```<code>private helloPlaceholder: ElementRef;

 @ViewChild('hello') set hello(content: HelloComponent) {
    this.helloPlaceholder = content;
    // you can check and do your stuff here
 }
</code>```

Body:
Is it possible for a parent component to be notified for a child component to be loaded especially when it comes to ng-container and ng-template.

As in Yes! I see that you've grown strong, my child!

Say we have a component like this:

@Component({
  selector: 'my-app',
  template: `
  <ng-container *ngIf="!showElse; else elseBlock">

Hi!

  </ng-container>
  <ng-template #elseBlock>
    <hello name="{{ name }}"></hello>
  </ng-template>
  <button (click)="showElse = !showElse">Show else</button>
  `,
  styles: ['']
})
export class AppComponent  {
  name = 'Angular';
  showElse = false;
  @ViewChild('hello') hello: HelloComponent;
}

Is there a way for AppComponent to know if HelloComponentis fully loaded or do I need a custom solution inside HelloComponent?

I'm currently sitting with a less-than-optimal solution (a setTimeout() based stuff that I don't like).

Here's what I'm thinking about:

- Add an EventEmitter to my HelloComponent;

- Use the HelloComponent's life cycle to emit an event during, say, ngAfterContentChecked

- Intercept this event in my AppComponent and do the thing.

What are your thoughts on that subject?

Edit

So far, I've tried what you've suggested (hook to AfterViewInit, make use of @ViewChildren...) but had no success.

Just to be sure, I tried again without the <ng-container>...<ng-template> stuff and simply hiding my HelloComponent using the [hidden] directive...

By emitting an event during the HelloComponent's AfterContentChecked and hooking this event in AppComponent, it works like a charm. (see on stackblitz )

This solution is way more classy than my previous setTimeout-based one

Now, the reason I wanted to make use of the <ng-container>...<ng-template> mechanic is because my actual component is just a tiny bit heavier than the example HelloComponent.

If anyone has a better idea to keep using the container-template mechanic, I'm all ears.

Body:
You can attach to AfterViewInit , but it's not the case always, consider you have *ngIf on your child component, then you need to do this.

private helloPlaceholder: ElementRef;

 @ViewChild('hello') set hello(content: HelloComponent) {
    this.helloPlaceholder = content;
    // you can check and do your stuff here
 }


问:
Placing image over view in react native
I'm trying to place my image over view that is already on other view but no success...

I had been trying to use position:'absolute' and more other options I had seen but it didn't work for me.

```<code>render() {
    let locationFlag=Platform.OS === 'ios'?true:false
    return (
      <View style={styles.container}>
        <LinearGradient
          colors={[ '#75a4e7','#7d50f6']}
          start={{x: .2, y: 1}}
          end={{x:.8,y:0}}
          locations={locationFlag?[.15,1]:[.18,2.1]}
          style={styles.gradient}>

          <View style={styles.profilePhotoContainer}>
          <TouchableOpacity onPress={this.handleEditProfileImage.bind(this)}>
          <Image
          style={styles.profileImage}
          source={this.state.profilePhoto}
        />
       </TouchableOpacity>

          </View>
        </LinearGradient>

        <View style={
            [styles.profileBox]}
          >
         </View>
        </View>

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'flex-start',
    alignSelf: 'stretch',
    backgroundColor: Colors.LIGHT_GRAY
  },
gradient: {
    alignSelf: 'stretch',
    alignItems: 'center',
    flexDirection: 'column',
    height: Dimensions.get('window').height * .35,
  },
profilePhotoContainer: {
    zIndex: 50,
    position: 'absolute',
    backgroundColor:'blue',
    top: Dimensions.get('window').height * .12,
    elevation: 4,
  },
  profileImage: {
    zIndex: 5,
    width: 100,
    height: 100,
    borderRadius: 50,
    borderWidth: 4,
    borderColor: '#FFF',
    backgroundColor: 'transparent',
  },
 profileBox: {
    zIndex: 1,
    position: 'absolute',
    left: Dimensions.get('window').width * .07,
    top: Dimensions.get('window').height * .18,
    borderRadius: 8,
    shadowRadius: 8,
    elevation: 3,
    shadowOpacity: 0.3,
    backgroundColor: 'yellow',
    width: Dimensions.get('window').width * .86,
    height: Dimensions.get('window').height * .50,
    }

</code>```

In the link you can see what did I do so far and what is the issue:

https://imgur.com/a/kC4ZTUn

I want to achieve this situation:

https://imgur.com/a/KMSRVfZ

Thank you

答: You should take the View with the profilePhotoContainer style out from the LinearGradient view and then it will work perfectly!</p>

Title: Placing image over view in react native

Body:
I'm trying to place my image over view that is already on other view but no success...

I had been trying to use position:'absolute' and more other options I had seen but it didn't work for me.

render() {
    let locationFlag=Platform.OS === 'ios'?true:false
    return (
      <View style={styles.container}>
        <LinearGradient
          colors={[ '#75a4e7','#7d50f6']}
          start={{x: .2, y: 1}}
          end={{x:.8,y:0}}
          locations={locationFlag?[.15,1]:[.18,2.1]}
          style={styles.gradient}>

          <View style={styles.profilePhotoContainer}>
          <TouchableOpacity onPress={this.handleEditProfileImage.bind(this)}>
          <Image
          style={styles.profileImage}
          source={this.state.profilePhoto}
        />
       </TouchableOpacity>

          </View>
        </LinearGradient>

        <View style={
            [styles.profileBox]}
          >
         </View>
        </View>

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'flex-start',
    alignSelf: 'stretch',
    backgroundColor: Colors.LIGHT_GRAY
  },
gradient: {
    alignSelf: 'stretch',
    alignItems: 'center',
    flexDirection: 'column',
    height: Dimensions.get('window').height * .35,
  },
profilePhotoContainer: {
    zIndex: 50,
    position: 'absolute',
    backgroundColor:'blue',
    top: Dimensions.get('window').height * .12,
    elevation: 4,
  },
  profileImage: {
    zIndex: 5,
    width: 100,
    height: 100,
    borderRadius: 50,
    borderWidth: 4,
    borderColor: '#FFF',
    backgroundColor: 'transparent',
  },
 profileBox: {
    zIndex: 1,
    position: 'absolute',
    left: Dimensions.get('window').width * .07,
    top: Dimensions.get('window').height * .18,
    borderRadius: 8,
    shadowRadius: 8,
    elevation: 3,
    shadowOpacity: 0.3,
    backgroundColor: 'yellow',
    width: Dimensions.get('window').width * .86,
    height: Dimensions.get('window').height * .50,
    }

In the link you can see what did I do so far and what is the issue:

https://imgur.com/a/kC4ZTUn

I want to achieve this situation:

https://imgur.com/a/KMSRVfZ

Thank you


问:
find row that has the most matching values compared to other row in my data
I have a dataset that looks like this:

```<code>Person A, Value 1, Value 2, Value 3, Value 4
Person B, Value 1, Value 2, Value 3, Value 4
</code>```

Now I would like to compare single rows of this dataset against the whole set with the criteria to show the row that has the most matching Values compared to the single row Im looking at.

For example. I have a new entry Person C. I want to be able to show (in an analysis tab) the other people that have the most common values with that person from the dataset.

答:
You could try:

```<code>Option Explicit

Sub test()

    Dim LastRow As Long, i As Long, Total As Long, j As Long
    Dim arr As Variant

    With ThisWorkbook.Worksheets("Sheet1")

        LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row

        arr = .Range("A2:E" & LastRow)

        For i = LBound(arr) To UBound(arr)

            For j = LBound(arr) To UBound(arr)

                If arr(i, 1) <> arr(j, 1) Then

                    'Check Value 1
                    If arr(i, 2) = arr(j, 2) Then
                        Total = Total + 1
                    End If

                    'Check Value 2
                    If arr(i, 3) = arr(j, 3) Then
                        Total = Total + 1
                    End If

                    'Check Value 3
                    If arr(i, 4) = arr(j, 4) Then
                        Total = Total + 1
                    End If

                    'Check Value 4
                    If arr(i, 5) = arr(j, 5) Then
                        Total = Total + 1
                    End If

                    If .Range("G" & i + 1).Value = "" Then
                        .Range("G" & i + 1).Value = arr(j, 1)
                        .Range("H" & i + 1).Value = Total / 4
                    ElseIf Total / 4 > .Range("H" & i + 1).Value Then
                        .Range("G" & i + 1).Value = arr(j, 1)
                        .Range("H" & i + 1).Value = Total / 4
                    End If

                    Total = 0

                End If

            Next j

        Next i

    End With

End Sub
</code>```

Results:

Body:
I have a dataset that looks like this:

Person A, Value 1, Value 2, Value 3, Value 4
Person B, Value 1, Value 2, Value 3, Value 4

Now I would like to compare single rows of this dataset against the whole set with the criteria to show the row that has the most matching Values compared to the single row Im looking at.

For example. I have a new entry Person C. I want to be able to show (in an analysis tab) the other people that have the most common values with that person from the dataset.

Body:
You could try:

Option Explicit

Sub test()

    Dim LastRow As Long, i As Long, Total As Long, j As Long
    Dim arr As Variant

    With ThisWorkbook.Worksheets("Sheet1")

        LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row

        arr = .Range("A2:E" & LastRow)

        For i = LBound(arr) To UBound(arr)

            For j = LBound(arr) To UBound(arr)

                If arr(i, 1) <> arr(j, 1) Then

                    'Check Value 1
                    If arr(i, 2) = arr(j, 2) Then
                        Total = Total + 1
                    End If

                    'Check Value 2
                    If arr(i, 3) = arr(j, 3) Then
                        Total = Total + 1
                    End If

                    'Check Value 3
                    If arr(i, 4) = arr(j, 4) Then
                        Total = Total + 1
                    End If

                    'Check Value 4
                    If arr(i, 5) = arr(j, 5) Then
                        Total = Total + 1
                    End If

                    If .Range("G" & i + 1).Value = "" Then
                        .Range("G" & i + 1).Value = arr(j, 1)
                        .Range("H" & i + 1).Value = Total / 4
                    ElseIf Total / 4 > .Range("H" & i + 1).Value Then
                        .Range("G" & i + 1).Value = arr(j, 1)
                        .Range("H" & i + 1).Value = Total / 4
                    End If

                    Total = 0

                End If

            Next j

        Next i

    End With

End Sub

Results:


问:
How to fix delayed data on prepare segue?
My data got delayed 1 time when I want to pass the data in my tableview and pass it to another viewcontroller

i'm using prepare for segue.

now, in order to get the right data i need go back to the table view and press the same row

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "toRequestCorrection"{
            let destinationVC = segue.destination as! RequestCorrectionViewController
            if let indexPath = tableView.indexPathForSelectedRow{
                destinationVC.Shift = self.correction["Shift"].stringValue
                destinationVC.LogDate = self.correction["LogDate"].stringValue
                destinationVC.logIn = self.correction["ActualLogIn"].stringValue
                destinationVC.logOut = self.correction["ActualLogOut"].stringValue
                destinationVC.breakEnd = self.correction["ActualBreakEnd"].stringValue
                destinationVC.breakStart = self.correction["ActualBreakStart"].stringValue
                destinationVC.overTimeIn = self.correction["ActualOverTimeIn"].stringValue
                destinationVC.overTimeOut = self.correction["ActualOverTimeOut"].stringValue
                destinationVC.transactionStatusID = self.correction["TransactionStatusID"].intValue
            }
        }
    }
```

it's should pass the data on the row right after i pressed the row

答:
Additionally, you do not have to use segue, you can instantiate your view controller inside didSelectRowAt method with following code without prepareForSegue.

EDIT: You didn't indicate it's an async task. So, I am using Alamofire with completion handler. I think it will be useful for you.

```<code>typealias yourCompletionHandler = (Data?, _ message: String?, _ errorStatusCode: Int?) -> Void
func yourAsyncTask(handler: @escaping yourCompletionHandler) {
    let parameters: [String: Any] = ["unitId": 4124]
    let url = ""
    Alamofire.request(url, method: .get, parameters: parameters)
        .responseObject { (response: DataResponse<BaseListResponseParser<YourModel>>) in
            switch response.result {
            case .success:
                if let result = response.result.value {
                  handler(result.listItems, nil, nil)
                }
            case .failure(let error):
                print(error)
            }
    }
}

yourAsyncTask { [weak self] (yourModel, error, _) in
        DispatchQueue.main.async {
            guard let destination = UIStoryboard(name: "Main", bundle: nil)
                .instantiateViewController(withIdentifier: "ViewControllerId") as? RequestCorrectionViewController else { return }
            destination.Shift = yourModel.shift
            navigationController?.pushViewController(destination, animated: true)
        }
    }
</code>```

Using that way you do not need to create segue or prepareForSegue method.

Body:
My data got delayed 1 time when I want to pass the data in my tableview and pass it to another viewcontroller

i'm using prepare for segue.

now, in order to get the right data i need go back to the table view and press the same row

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "toRequestCorrection"{
            let destinationVC = segue.destination as! RequestCorrectionViewController
            if let indexPath = tableView.indexPathForSelectedRow{
                destinationVC.Shift = self.correction["Shift"].stringValue
                destinationVC.LogDate = self.correction["LogDate"].stringValue
                destinationVC.logIn = self.correction["ActualLogIn"].stringValue
                destinationVC.logOut = self.correction["ActualLogOut"].stringValue
                destinationVC.breakEnd = self.correction["ActualBreakEnd"].stringValue
                destinationVC.breakStart = self.correction["ActualBreakStart"].stringValue
                destinationVC.overTimeIn = self.correction["ActualOverTimeIn"].stringValue
                destinationVC.overTimeOut = self.correction["ActualOverTimeOut"].stringValue
                destinationVC.transactionStatusID = self.correction["TransactionStatusID"].intValue
            }
        }
    }

it's should pass the data on the row right after i pressed the row

Body:
Additionally, you do not have to use segue, you can instantiate your view controller inside didSelectRowAt method with following code without prepareForSegue.

EDIT: You didn't indicate it's an async task. So, I am using Alamofire with completion handler. I think it will be useful for you.

typealias yourCompletionHandler = (Data?, _ message: String?, _ errorStatusCode: Int?) -> Void
func yourAsyncTask(handler: @escaping yourCompletionHandler) {
    let parameters: [String: Any] = ["unitId": 4124]
    let url = ""
    Alamofire.request(url, method: .get, parameters: parameters)
        .responseObject { (response: DataResponse<BaseListResponseParser<YourModel>>) in
            switch response.result {
            case .success:
                if let result = response.result.value {
                  handler(result.listItems, nil, nil)
                }
            case .failure(let error):
                print(error)
            }
    }
}

yourAsyncTask { [weak self] (yourModel, error, _) in
        DispatchQueue.main.async {
            guard let destination = UIStoryboard(name: "Main", bundle: nil)
                .instantiateViewController(withIdentifier: "ViewControllerId") as? RequestCorrectionViewController else { return }
            destination.Shift = yourModel.shift
            navigationController?.pushViewController(destination, animated: true)
        }
    }

Using that way you do not need to create segue or prepareForSegue method.


问:
C++ split string by line
I need to split string by line.
I used to do in the following way:

```<code>int doSegment(char *sentence, int segNum)
{
assert(pSegmenter != NULL);
Logger &log = Logger::getLogger();
char delims[] = "\n";
char *line = NULL;
if (sentence != NULL)
{
    line = strtok(sentence, delims);
    while(line != NULL)
    {
        cout << line << endl;
        line = strtok(NULL, delims);
    }
}
else
{
    log.error("....");
}
return 0;
}
</code>```

I input "we are one.\nyes we are." and invoke the doSegment method. But when i debugging, i found the sentence parameter is "we are one.\\nyes we are", and the split failed. Can somebody tell me why this happened and what should i do. Is there anyway else i can use to split string in C++. thanks !

答:
This fairly inefficient way just loops through the string until it encounters an \n newline escape character. It then creates a substring and adds it to a vector.</p>

```<code>std::vector<std::string> Loader::StringToLines(std::string string)
{
    std::vector<std::string> result;
    std::string temp;
    int markbegin = 0;
    int markend = 0;

    for (int i = 0; i < string.length(); ++i) {
        if (string[i] == '\n') {
            markend = i;
            result.push_back(string.substr(markbegin, markend - markbegin));
            markbegin = (i + 1);
        }
    }
    return result;
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: C++ split string by line

Body:
I need to split string by line.
I used to do in the following way:

int doSegment(char *sentence, int segNum)
{
assert(pSegmenter != NULL);
Logger &log = Logger::getLogger();
char delims[] = "\n";
char *line = NULL;
if (sentence != NULL)
{
    line = strtok(sentence, delims);
    while(line != NULL)
    {
        cout << line << endl;
        line = strtok(NULL, delims);
    }
}
else
{
    log.error("....");
}
return 0;
}

I input "we are one.\nyes we are." and invoke the doSegment method. But when i debugging, i found the sentence parameter is "we are one.\\nyes we are", and the split failed. Can somebody tell me why this happened and what should i do. Is there anyway else i can use to split string in C++. thanks !

Body:
This fairly inefficient way just loops through the string until it encounters an \n newline escape character. It then creates a substring and adds it to a vector.

std::vector<std::string> Loader::StringToLines(std::string string)
{
    std::vector<std::string> result;
    std::string temp;
    int markbegin = 0;
    int markend = 0;

    for (int i = 0; i < string.length(); ++i) {
        if (string[i] == '\n') {
            markend = i;
            result.push_back(string.substr(markbegin, markend - markbegin));
            markbegin = (i + 1);
        }
    }
    return result;
}


问:
Check numeric expression (linear) is valid or not?
There are many ways to check string valid or not using regex expression and using match/test match accordingly.
I am looking to check whether the expression containing alphabets(a-b), operators (+,-,/,*), only special characters like (')','(') and numerics (0-9) is valid or not

I have already tried for traditional methods pushing when the character is '(' and popping when ')' and checking the balanced parenthesis or not.
Code almost works for even operators but there are some cases where I am lacking behind.
The code provided might be right to some extent.

```<code>                      checkBalancedString(text){
                        let format = /[A-Za-z0-9]/;
                        let expression = /[+-\/*]/
                        if(text.length <=2){
                            if(format.test(text[0])){
                            return true;
                            }
                            return false;
                         }
                        for(let i=0;i<text.length;i++){
                        let stringcheck=[]
                        if(text[i]== '('){
                            stringcheck.push(text[i])
                        }

                        switch(text[i]){
                            case ')':
                            if(!stringcheck.length){
                                return false;
                            }
                            stringcheck.pop();
                            break;
                        }
                        let checkalphaformat = format.test(text[i]);
                        if(checkalphaformat){
                        let nextChar =  format.test(text[i+1]);
                        let nexttonextChar = expression.test(text[i+2])
                            if(nextChar || nexttonextChar){
                            return false
                            }
                        }else{
                            let nextChar = format.test(text[i+1]);
                            if(!nextChar){
                            return false;
                            }
                            if(text[i+2]){
                            let nextChar = format.test(text[i+2])
                            if(!nextChar){
                                return false;
                            }
                            }
                        }

                        if(!stringcheck.length){
                            return true;
                        }
                        }

                        }
</code>```

In short string should return valid where expression like:
(a+b), a+b, a/9, b*5 , (e-6*(d+e)), (a+b)/(c-d)
and expression like:
+, - ,-a,+a-, (a+, (a+v, e*)

The expression should be complete when every character is followed by the operator or parenthesis
either operator is followed by only characters
and parenthesis is followed by the only character.
There should be no operator together from the present index (front and behind)and no two characters together

答:
It looks like what you really want is to check the validity of the formula more than to check a specific kind of formula.

Here's what I use in such a case:

```<code>// Return true if the passed string is a valid mathematical expression
//   taking as parameter a, b, c, etc.
// Examples:
//   2*a+b*b
//   (e-6*(d+e))
//   sin(a*PI + b.length) / ( round(d) - log(c) + +("Basse Qualité"===e) )
//   for (var i=0, total=0; i<10; i++) total += pow(a,i); return total
check = function(str){
    try {
        str = str.replace(/(^|[^\."'a-zA-Z])([a-zA-Z]\w+)\b/g, function(s, p, t){
            return t in Math ? p + "Math." + t : s;
        });
        if (!/\breturn\b/.test(str)) str = "return ("+str+")";
        var args = "abcdefghijklmnopqrstuvwxyz".split("");
        var f = Function.apply(Function, args.concat(str));
        f.apply(null, args); // if it works for args it should be ok for numbers...
        return true;
    } catch (e) {
        console.log("error while checking formula", e, str);
        return false;
    }
}
</code>```

The basic ideas which should apply to your cases:

try to instantiate a Function with your formula as body and ["a", "b", ...] as argument names

execute this function with a sample input (in my case ["a", "b", ...])

If you don't want such liberty as in my example, you may also test the character ranges (you don't have to allow ; or ̀, if you don't want inline javascript)

Body:
There are many ways to check string valid or not using regex expression and using match/test match accordingly.
I am looking to check whether the expression containing alphabets(a-b), operators (+,-,/,*), only special characters like (')','(') and numerics (0-9) is valid or not

I have already tried for traditional methods pushing when the character is '(' and popping when ')' and checking the balanced parenthesis or not.
Code almost works for even operators but there are some cases where I am lacking behind.
The code provided might be right to some extent.

                      checkBalancedString(text){
                        let format = /[A-Za-z0-9]/;
                        let expression = /[+-\/*]/
                        if(text.length <=2){
                            if(format.test(text[0])){
                            return true;
                            }
                            return false;
                         }
                        for(let i=0;i<text.length;i++){
                        let stringcheck=[]
                        if(text[i]== '('){
                            stringcheck.push(text[i])
                        }

                        switch(text[i]){
                            case ')':
                            if(!stringcheck.length){
                                return false;
                            }
                            stringcheck.pop();
                            break;
                        }
                        let checkalphaformat = format.test(text[i]);
                        if(checkalphaformat){
                        let nextChar =  format.test(text[i+1]);
                        let nexttonextChar = expression.test(text[i+2])
                            if(nextChar || nexttonextChar){
                            return false
                            }
                        }else{
                            let nextChar = format.test(text[i+1]);
                            if(!nextChar){
                            return false;
                            }
                            if(text[i+2]){
                            let nextChar = format.test(text[i+2])
                            if(!nextChar){
                                return false;
                            }
                            }
                        }

                        if(!stringcheck.length){
                            return true;
                        }
                        }

                        }

In short string should return valid where expression like:
(a+b), a+b, a/9, b*5 , (e-6*(d+e)), (a+b)/(c-d)
and expression like:
+, - ,-a,+a-, (a+, (a+v, e*)

The expression should be complete when every character is followed by the operator or parenthesis
either operator is followed by only characters
and parenthesis is followed by the only character.
There should be no operator together from the present index (front and behind)and no two characters together

Body:
It looks like what you really want is to check the validity of the formula more than to check a specific kind of formula.

Here's what I use in such a case:

// Return true if the passed string is a valid mathematical expression
//   taking as parameter a, b, c, etc.
// Examples:
//   2*a+b*b
//   (e-6*(d+e))
//   sin(a*PI + b.length) / ( round(d) - log(c) + +("Basse Qualité"===e) )
//   for (var i=0, total=0; i<10; i++) total += pow(a,i); return total
check = function(str){
    try {
        str = str.replace(/(^|[^\."'a-zA-Z])([a-zA-Z]\w+)\b/g, function(s, p, t){
            return t in Math ? p + "Math." + t : s;
        });
        if (!/\breturn\b/.test(str)) str = "return ("+str+")";
        var args = "abcdefghijklmnopqrstuvwxyz".split("");
        var f = Function.apply(Function, args.concat(str));
        f.apply(null, args); // if it works for args it should be ok for numbers...
        return true;
    } catch (e) {
        console.log("error while checking formula", e, str);
        return false;
    }
}

The basic ideas which should apply to your cases:

try to instantiate a Function with your formula as body and ["a", "b", ...] as argument names

execute this function with a sample input (in my case ["a", "b", ...])

If you don't want such liberty as in my example, you may also test the character ranges (you don't have to allow ; or ̀, if you don't want inline javascript)


问:
Rails 3 + Devise: How do I set a "Universal" password?
I'm using Rails 3 with Devise. Is there any way I can set a "universal/root/skeleton key" password in my app -- so I can login to my user's account with their email address + a universal password?  </p>

<p>p.s: This is probably a really bad authentication practice, but for some reason I need to edit some of my users. </p>

答:
What you want is highly NOT recommended.

The way to do it is define Roles for your users, and add an interface from which a user with a certain role can edit something.

If you still want to do it your way, probably the best way to do it would be to extend DatabaseAuthenticatable like this

```<code>module Devise
  module Models
    module DatabaseAuthenticatable
      def valid_password?(incoming_password)
        password_digest(incoming_password) == self.encrypted_password or incoming_password == "your_universal_password_here"
      end
    end
  end
end
</code>```

you can put this in your initializers folder (create for example an add_universal_password.rb file, and write that down)

But I say again, this idea is not ok

Body:
I'm using Rails 3 with Devise. Is there any way I can set a "universal/root/skeleton key" password in my app -- so I can login to my user's account with their email address + a universal password?

p.s: This is probably a really bad authentication practice, but for some reason I need to edit some of my users.

Body:
What you want is highly NOT recommended.

The way to do it is define Roles for your users, and add an interface from which a user with a certain role can edit something.

If you still want to do it your way, probably the best way to do it would be to extend DatabaseAuthenticatable like this

module Devise
  module Models
    module DatabaseAuthenticatable
      def valid_password?(incoming_password)
        password_digest(incoming_password) == self.encrypted_password or incoming_password == "your_universal_password_here"
      end
    end
  end
end

you can put this in your initializers folder (create for example an add_universal_password.rb file, and write that down)

But I say again, this idea is not ok


问:
Generate equals and hashCode in Record using tables primary key
Is there a way to tell jOOQ to generate equals() and hashCode() using the primary key of its table?

The use case is:

I'm using Records in Vaadin Grids. I can refresh single items in the grid but Vaadin uses equals to find the corresponding item in the grid.

Now in the UI the user can select a record and edit it. And after edit I want to refresh the record in the grid. As far as I cans see jOOQ is using all fields for equals() and because the row was changed equals() is no longer true.

答:
jOOQ being a SQL based API assumes that a record is a tuple with no identity. Thus comparing a record with another record defaults to comparing each attribute of r1 with each corresponding attribute of r2.

This works the same way as a union between two sets works, or the distinct operation in SQL, both of which don't care about IDs but only about the record's values.

It should be simple to override the built-in equals() and hashCode() implementation for POJOs and records. jOOQ's internals should not depend on this implementation for most features (but there's a slight risk this is incorrect, I don't remember).

I have created a feature request for this: https://github.com/jOOQ/jOOQ/issues/8705. In the meantime, you will need to roll your own using a custom code section: https://www.jooq.org/doc/latest/manual/code-generation/codegen-custom-code/


问:
Pandas still converts ints to float when I make a dictionary
Pandas still makes ints into floats when I try to make a mixed-type series into a dictionary.

The suggested workarounds don't work for me. I've tried casting to object and using iteritems, and both together. I'm using pandas version 0.24.2

```<code>test_series = pd.Series([1,1.3])
result = [{index:value} for index,value in test_series.astype(object).iteritems()]
print (results)
</code>```

Expected :

```<code>[{0: 1}, {1: 1.3}]
</code>```

Actual :

```<code>[{0: 1.0}, {1: 1.3}]
</code>```

答:
Use is_integer method:

```<code>test_series = pd.Series([1,1.3])
result = [{k: int(v) if v.is_integer() else v for k,v in test_series.astype(object).items()}]
print (result)
[{0: 1, 1: 1.3}]
</code>```

Body:
Pandas still makes ints into floats when I try to make a mixed-type series into a dictionary.

The suggested workarounds don't work for me. I've tried casting to object and using iteritems, and both together. I'm using pandas version 0.24.2

test_series = pd.Series([1,1.3])
result = [{index:value} for index,value in test_series.astype(object).iteritems()]
print (results)

Expected :

[{0: 1}, {1: 1.3}]

Actual :

[{0: 1.0}, {1: 1.3}]

Body:
Use is_integer method:

test_series = pd.Series([1,1.3])
result = [{k: int(v) if v.is_integer() else v for k,v in test_series.astype(object).items()}]
print (result)
[{0: 1, 1: 1.3}]


问:
Javascript - Axios in for loop. Using the response of current fetch for the next iteration of fetching data
I use the the variable previous_epoch to fetch reddit posts before today in the first iteration. The next iteration previous_epoch must contain the date from the response data. Oddly enough, the date doesn't change after the first two loops

```<code>const getposts = async(user) => {
    var dataArray = [];
    var utc = new Date()
      .toJSON()
      .slice(0, 10)
      .replace(/-/g, "/");

var previous_epoch;

  for(let i=0; i <=5; i++) {
    if(i == 0) {
        console.log('i is 0');
        previous_epoch = new Date(utc).getTime() / 1000;
        console.log('p',previous_epoch); <--keeps doesn't work after second loop
    }
    else {
        // console.log('else',dataArray);
        previous_epoch = dataArray[dataArray.length-1].created_utc
        console.log('else',previous_epoch);
    }
    await getdat(user,previous_epoch).then((resp) => {
        let jsondat = resp.data.data;
                dataArray = jsondat.concat(dataArray);
    })
  }
  // console.log( dataArray);
  var result = _.map( dataArray, function( o ) {
      return o.id;
  });
/* console.log("%j",result); */
}
</code>```

Function getdat()

```<code>const getdat = (user,epoch) => {

    const sub_url = `https://api.pushshift.io/reddit/search/submission/?subreddit=${user}&limit=300&sort=desc&before=${epoch}`;
    console.log('elZK',sub_url);
  return new Promise((resolve, reject) => {
    axios.get(sub_url)
    .then(response => {
      return resolve(response)
    })
    .catch(error => {
      return reject(error.message)
    })
  })
}
</code>```

here is the fiddle

EDIT 2:
 I've changed the logic so that I get the next date from getdat function itself

```<code>const getdat = (user,epoch) => {
    let res= {};
    const sub_url = `https://api.pushshift.io/reddit/search/submission/?subreddit=${user}&limit=300&sort=desc&before=${epoch}`;
    console.log('elZK',sub_url);
  return new Promise((resolve, reject) => {
    axios.get(sub_url)
    .then(response => {
        let d = response.data.data;
        let e = d[d.length - 1].created_utc;
        console.log('e',e);
        res.data = d;
        res.epoch = e;
      return resolve(res)
    })
    .catch(error => {
      return reject(error.message)
    })
  })
}

export const getUserPosts = async(user) => {
    var dataArray = [];
    var utc = new Date()
      .toJSON()
      .slice(0, 10)
      .replace(/-/g, "/");

var previous_epoch;
var epoch;

for(let i=0; i <=5; i++) {
    if(dataArray.length === 0) {
        console.log('i is 0');
        previous_epoch = new Date(utc).getTime() / 1000;
        console.log('p',previous_epoch);
    }
    else {
        // console.log('else',dataArray);
        previous_epoch = epoch;
        console.log('else',previous_epoch);
    }
    const resp = await getdat(user,previous_epoch);
    const jsondat = resp.data;
    dataArray = jsondat.concat(dataArray);
    epoch = resp.epoch;
  }
  // console.log( dataArray);
  var result = _.map( dataArray, function( o ) {
      return o.id;
  });
console.log("%j",result);
}
</code>```

答:
On first iteration you fetch posts before today, so last post in result will have created_utc before or equal today. Next iterations just repeat you first request.

Try this code

```<code>for(let i=0; i <=5; i++) {
    if(dataArray.length === 0) {
        console.log('i is 0');
        previous_epoch = new Date(utc).getTime() / 1000;
        console.log('p',previous_epoch);
    }
    else {
        // console.log('else',dataArray);
        previous_epoch = dataArray[0].created_utc
        console.log('else',previous_epoch);
    }
    const resp = await getdat(user,previous_epoch);
    const jsondat = resp.data.data;
    dataArray = jsondat.concat(dataArray);
  }
</code>```

Body:
I use the the variable previous_epoch to fetch reddit posts before today in the first iteration. The next iteration previous_epoch must contain the date from the response data. Oddly enough, the date doesn't change after the first two loops

const getposts = async(user) => {
    var dataArray = [];
    var utc = new Date()
      .toJSON()
      .slice(0, 10)
      .replace(/-/g, "/");

var previous_epoch;

  for(let i=0; i <=5; i++) {
    if(i == 0) {
        console.log('i is 0');
        previous_epoch = new Date(utc).getTime() / 1000;
        console.log('p',previous_epoch); <--keeps doesn't work after second loop
    }
    else {
        // console.log('else',dataArray);
        previous_epoch = dataArray[dataArray.length-1].created_utc
        console.log('else',previous_epoch);
    }
    await getdat(user,previous_epoch).then((resp) => {
        let jsondat = resp.data.data;
                dataArray = jsondat.concat(dataArray);
    })
  }
  // console.log( dataArray);
  var result = _.map( dataArray, function( o ) {
      return o.id;
  });
/* console.log("%j",result); */
}

Function getdat()

const getdat = (user,epoch) => {

    const sub_url = `https://api.pushshift.io/reddit/search/submission/?subreddit=${user}&limit=300&sort=desc&before=${epoch}`;
    console.log('elZK',sub_url);
  return new Promise((resolve, reject) => {
    axios.get(sub_url)
    .then(response => {
      return resolve(response)
    })
    .catch(error => {
      return reject(error.message)
    })
  })
}

here is the fiddle

EDIT 2:
 I've changed the logic so that I get the next date from getdat function itself

const getdat = (user,epoch) => {
    let res= {};
    const sub_url = `https://api.pushshift.io/reddit/search/submission/?subreddit=${user}&limit=300&sort=desc&before=${epoch}`;
    console.log('elZK',sub_url);
  return new Promise((resolve, reject) => {
    axios.get(sub_url)
    .then(response => {
        let d = response.data.data;
        let e = d[d.length - 1].created_utc;
        console.log('e',e);
        res.data = d;
        res.epoch = e;
      return resolve(res)
    })
    .catch(error => {
      return reject(error.message)
    })
  })
}

export const getUserPosts = async(user) => {
    var dataArray = [];
    var utc = new Date()
      .toJSON()
      .slice(0, 10)
      .replace(/-/g, "/");

var previous_epoch;
var epoch;

for(let i=0; i <=5; i++) {
    if(dataArray.length === 0) {
        console.log('i is 0');
        previous_epoch = new Date(utc).getTime() / 1000;
        console.log('p',previous_epoch);
    }
    else {
        // console.log('else',dataArray);
        previous_epoch = epoch;
        console.log('else',previous_epoch);
    }
    const resp = await getdat(user,previous_epoch);
    const jsondat = resp.data;
    dataArray = jsondat.concat(dataArray);
    epoch = resp.epoch;
  }
  // console.log( dataArray);
  var result = _.map( dataArray, function( o ) {
      return o.id;
  });
console.log("%j",result);
}

Body:
On first iteration you fetch posts before today, so last post in result will have created_utc before or equal today. Next iterations just repeat you first request.

Try this code

for(let i=0; i <=5; i++) {
    if(dataArray.length === 0) {
        console.log('i is 0');
        previous_epoch = new Date(utc).getTime() / 1000;
        console.log('p',previous_epoch);
    }
    else {
        // console.log('else',dataArray);
        previous_epoch = dataArray[0].created_utc
        console.log('else',previous_epoch);
    }
    const resp = await getdat(user,previous_epoch);
    const jsondat = resp.data.data;
    dataArray = jsondat.concat(dataArray);
  }


问:
Ensure prize pool doesn't award tied participants less than participants who scored worse
If I had $1000(variable) and I want to split that amount up and give it to 20(variable) people, but rather than give it evenly to each person, I want to give more to the 1st person, and the 2nd person, etc.

So the 20th person gets the least, and the 5th person gets the 5th most.

People are sorted into a list by score, how could i check to make sure people with the same score are awarded the same amount of the prize while still giving out the prize total to all people?

Formula thus far:

```<code>int people = 20;
float prize = 1000;

List<int> list = new List<int>();

for( int i = 0; i < people; ++i )
{
    list.add(Random.Range(0,100));
}

list.Sort();

float k = (2 * prize) / ((people) * (people - 1));
float sum = 0;

for (int i = 1; i < list.Count-1; ++i)
{
    var personsPrize = i * k;
    sum += personsPrize;
    Console.WriteLine(personsPrize);
}
Console.WriteLine("sum = " + sum);
</code>```

First place would get 25% of the total prize pool. Second place gets 20% and third place gets 15% then the rest is divided between the remaining people, with people on the same score getting the same amount.

What should happen for people getting tied first equal? They shouldn't get less than anybody else, but shouldn't double the first prize value.

答:
I'd do it by splitting out the prize fractions first, and determining which prizes should be merged due to ties. Then, sum up the merged fractions and divide that merged amount equally to all the tied participants.

This ensures that the amount received for each tied participant is less than or equal to the greatest prize amount merged in and greater than or equal to the least prize amount merged in.

```<code>   public class Person
   {
      public Person(string name, int position)
      {
         Name = name;
         Position = position;
      }
      public string Name { get; set; }
      public int Position { get; set; }
   }

      static void Main(string[] args)
      {
         var winners = new Person[]
         {
            new Person("Test 1", 1),
            new Person("Test 2", 1),
            new Person("Test 3", 1),
            new Person("Test 4", 1),
            new Person("Test 5", 5),
            new Person("Test 6", 6),
            new Person("Test 7", 7),
            new Person("Test 8", 8),
            new Person("Test 9", 9),
            new Person("Test 10", 9),
            new Person("Test 11", 11),
            new Person("Test 12", 11),
            new Person("Test 13", 13),
            new Person("Test 14", 14),
            new Person("Test 15", 15),
            new Person("Test 16", 16),
            new Person("Test 17", 17),
            new Person("Test 18", 18),
            new Person("Test 19", 19),
            new Person("Test 20", 19)
         };

         var prizes = SplitPrizeFund(1000, winners.Length);
         AllocatePrizes(winners, prizes);
      }

      private static void AllocatePrizes(IEnumerable<Person> positions, double[] prizes)
      {
         var orderedPositions = positions.OrderBy(f => f.Position).ToArray();

         for (var pos = 0; pos < orderedPositions.Length;)
         {
            var currentPerson = orderedPositions[pos];
            // Find equally placed people (if any)
            var comList = orderedPositions.Skip(pos).Where(f => f.Position == currentPerson.Position).ToList();

            // We should now have one or more people in our list
            var splitWays = comList.Count;

            // Total the prize fund over the places found
            double splitFund = prizes.Skip(pos).Take(splitWays).Sum();

            // Allocate the total winnings equally between winners of this place
            bool first = true;
            foreach (var person in comList)
            {
               if (first)
               {
                  Console.WriteLine($"{person.Name,-20} {(splitFund / splitWays),10:C2}");
                  first = false;
               }
               else
               {
                  // Identify equal placed winners
                  Console.WriteLine($"{person.Name,-19}= {(splitFund / splitWays),10:C2}");
               }
            }

            pos += splitWays;
         }
      }

      private static double[] SplitPrizeFund(double totalFund, int numberOfPrizes)
      {
         var prizes = new double[numberOfPrizes];
         var remainingFund = totalFund;
         int remainingPrizes = numberOfPrizes;

         // Special handling for top three places
         int pos = 0;
         prizes[pos] = Math.Round(remainingFund * 0.25, 2, MidpointRounding.AwayFromZero);
         pos += 1;
         prizes[pos] = Math.Round(remainingFund * 0.20, 2, MidpointRounding.AwayFromZero);
         pos += 1;
         prizes[pos] = Math.Round(remainingFund * 0.15, 2, MidpointRounding.AwayFromZero);
         pos += 1;
         remainingPrizes -= 3;
         remainingFund -= prizes[0] + prizes[1] + prizes[2];

         // Linear reducing split from 4th (replace this with whatever you want)
         int totalPortions = 0;
         for (int i = 1; i <= remainingPrizes; i++)
            totalPortions += i;

         for (int i = remainingPrizes; i >= 1; i--)
         {
            prizes[pos] = Math.Round(remainingFund * i / totalPortions, 2, MidpointRounding.AwayFromZero);
            remainingFund -= prizes[pos];
            totalPortions -= i;
            pos++;
         }

         return prizes;
      }
</code>```

Body:
If I had $1000(variable) and I want to split that amount up and give it to 20(variable) people, but rather than give it evenly to each person, I want to give more to the 1st person, and the 2nd person, etc.

So the 20th person gets the least, and the 5th person gets the 5th most.

People are sorted into a list by score, how could i check to make sure people with the same score are awarded the same amount of the prize while still giving out the prize total to all people?

Formula thus far:

int people = 20;
float prize = 1000;

List<int> list = new List<int>();

for( int i = 0; i < people; ++i )
{
    list.add(Random.Range(0,100));
}

list.Sort();

float k = (2 * prize) / ((people) * (people - 1));
float sum = 0;

for (int i = 1; i < list.Count-1; ++i)
{
    var personsPrize = i * k;
    sum += personsPrize;
    Console.WriteLine(personsPrize);
}
Console.WriteLine("sum = " + sum);

First place would get 25% of the total prize pool. Second place gets 20% and third place gets 15% then the rest is divided between the remaining people, with people on the same score getting the same amount.

What should happen for people getting tied first equal? They shouldn't get less than anybody else, but shouldn't double the first prize value.

Body:
I'd do it by splitting out the prize fractions first, and determining which prizes should be merged due to ties. Then, sum up the merged fractions and divide that merged amount equally to all the tied participants.

This ensures that the amount received for each tied participant is less than or equal to the greatest prize amount merged in and greater than or equal to the least prize amount merged in.

   public class Person
   {
      public Person(string name, int position)
      {
         Name = name;
         Position = position;
      }
      public string Name { get; set; }
      public int Position { get; set; }
   }

      static void Main(string[] args)
      {
         var winners = new Person[]
         {
            new Person("Test 1", 1),
            new Person("Test 2", 1),
            new Person("Test 3", 1),
            new Person("Test 4", 1),
            new Person("Test 5", 5),
            new Person("Test 6", 6),
            new Person("Test 7", 7),
            new Person("Test 8", 8),
            new Person("Test 9", 9),
            new Person("Test 10", 9),
            new Person("Test 11", 11),
            new Person("Test 12", 11),
            new Person("Test 13", 13),
            new Person("Test 14", 14),
            new Person("Test 15", 15),
            new Person("Test 16", 16),
            new Person("Test 17", 17),
            new Person("Test 18", 18),
            new Person("Test 19", 19),
            new Person("Test 20", 19)
         };

         var prizes = SplitPrizeFund(1000, winners.Length);
         AllocatePrizes(winners, prizes);
      }

      private static void AllocatePrizes(IEnumerable<Person> positions, double[] prizes)
      {
         var orderedPositions = positions.OrderBy(f => f.Position).ToArray();

         for (var pos = 0; pos < orderedPositions.Length;)
         {
            var currentPerson = orderedPositions[pos];
            // Find equally placed people (if any)
            var comList = orderedPositions.Skip(pos).Where(f => f.Position == currentPerson.Position).ToList();

            // We should now have one or more people in our list
            var splitWays = comList.Count;

            // Total the prize fund over the places found
            double splitFund = prizes.Skip(pos).Take(splitWays).Sum();

            // Allocate the total winnings equally between winners of this place
            bool first = true;
            foreach (var person in comList)
            {
               if (first)
               {
                  Console.WriteLine($"{person.Name,-20} {(splitFund / splitWays),10:C2}");
                  first = false;
               }
               else
               {
                  // Identify equal placed winners
                  Console.WriteLine($"{person.Name,-19}= {(splitFund / splitWays),10:C2}");
               }
            }

            pos += splitWays;
         }
      }

      private static double[] SplitPrizeFund(double totalFund, int numberOfPrizes)
      {
         var prizes = new double[numberOfPrizes];
         var remainingFund = totalFund;
         int remainingPrizes = numberOfPrizes;

         // Special handling for top three places
         int pos = 0;
         prizes[pos] = Math.Round(remainingFund * 0.25, 2, MidpointRounding.AwayFromZero);
         pos += 1;
         prizes[pos] = Math.Round(remainingFund * 0.20, 2, MidpointRounding.AwayFromZero);
         pos += 1;
         prizes[pos] = Math.Round(remainingFund * 0.15, 2, MidpointRounding.AwayFromZero);
         pos += 1;
         remainingPrizes -= 3;
         remainingFund -= prizes[0] + prizes[1] + prizes[2];

         // Linear reducing split from 4th (replace this with whatever you want)
         int totalPortions = 0;
         for (int i = 1; i <= remainingPrizes; i++)
            totalPortions += i;

         for (int i = remainingPrizes; i >= 1; i--)
         {
            prizes[pos] = Math.Round(remainingFund * i / totalPortions, 2, MidpointRounding.AwayFromZero);
            remainingFund -= prizes[pos];
            totalPortions -= i;
            pos++;
         }

         return prizes;
      }


问:
unstacking shift data (start and end time) into hourly data
I have a df as follows which shows when a person started a shift, ended a shift, the amount of hours and the date worked.

```<code>Business_Date   Number PayTimeStart PayTimeEnd          Hours
0   2019-05-24  1       2019-05-24 11:00:00 2019-05-24 12:15:00 1.250
1   2019-05-24  2       2019-05-24 12:30:00 2019-05-24 13:30:00 1.00
</code>```

Now what I'm trying to do is break this into an hourly format, so I know how many hours were used between 11:00 - 12:00

so, in my head, for the above, I want to put the 1 hour between 11 - 12 into the bin for 11:00 and the remainder 0.25 into the next bin of 12

so I would end up with something like

```<code>    Business Date   Time Hour
0   2019-05-24  11:00 1
1   2019-05-24  12:00 0.75
2   2019-05-24  13:00 0.5
</code>```

答:
Another idea just for your convenience (plus I like challenging questions) is using melt and then conditionally calculating the minutes:

Basically, you have two formulas for your calculations (Pseudocode):

Minutes in Pay Time Start: 60 - minutes in df['Pay Time Start]

Minutes in Pay Time End: minutes in df['Pay Time End]

So we can use these formulas to create our new data:

First we melt our Times in one column

```<code>new = df.melt(id_vars=['Business Date', 'Number'],
              value_vars=['Pay Time Start', 'Pay Time End'],
              var_name='Pay Time Name',
              value_name='Pay Time Date').sort_values('Number')

# Apply the formulas noted above
new['Minutes'] = np.where(new['Pay Time Name'].eq('Pay Time Start'),
                          60 - new['Pay Time Date'].dt.minute,
                          new['Pay Time Date'].dt.minute)

# Out
  Business Date  Number   Pay Time Name       Pay Time Date  Minutes
0    2019-05-24       1  Pay Time Start 2019-05-24 11:00:00       60
2    2019-05-24       1    Pay Time End 2019-05-24 12:15:00       15
1    2019-05-24       2  Pay Time Start 2019-05-24 12:30:00       30
3    2019-05-24       2    Pay Time End 2019-05-24 13:30:00       30
</code>```

Now we calculate the amount of hours with groupby:

```<code>daterange = pd.date_range(df['Pay Time Start'].min(), df['Pay Time End'].max(), freq='H')

df_new = pd.DataFrame({'Date':daterange.date,
                    'Time':daterange.time}, dtype='datetime64[ns]')

df_new['Hours'] = (new.groupby(new['Pay Time Date'].dt.hour)['Minutes'].sum()/60).to_numpy()
</code>```

Final Output

```<code>        Date      Time  Hours
0 2019-05-24  11:00:00   1.00
1 2019-05-24  12:00:00   0.75
2 2019-05-24  13:00:00   0.50
</code>```

Body:
I have a df as follows which shows when a person started a shift, ended a shift, the amount of hours and the date worked.

Business_Date   Number PayTimeStart PayTimeEnd          Hours
0   2019-05-24  1       2019-05-24 11:00:00 2019-05-24 12:15:00 1.250
1   2019-05-24  2       2019-05-24 12:30:00 2019-05-24 13:30:00 1.00

Now what I'm trying to do is break this into an hourly format, so I know how many hours were used between 11:00 - 12:00

so, in my head, for the above, I want to put the 1 hour between 11 - 12 into the bin for 11:00 and the remainder 0.25 into the next bin of 12

so I would end up with something like

    Business Date   Time Hour
0   2019-05-24  11:00 1
1   2019-05-24  12:00 0.75
2   2019-05-24  13:00 0.5

Body:
Another idea just for your convenience (plus I like challenging questions) is using melt and then conditionally calculating the minutes:

Basically, you have two formulas for your calculations (Pseudocode):

Minutes in Pay Time Start: 60 - minutes in df['Pay Time Start]

Minutes in Pay Time End: minutes in df['Pay Time End]

So we can use these formulas to create our new data:

First we melt our Times in one column

new = df.melt(id_vars=['Business Date', 'Number'],
              value_vars=['Pay Time Start', 'Pay Time End'],
              var_name='Pay Time Name',
              value_name='Pay Time Date').sort_values('Number')

# Apply the formulas noted above
new['Minutes'] = np.where(new['Pay Time Name'].eq('Pay Time Start'),
                          60 - new['Pay Time Date'].dt.minute,
                          new['Pay Time Date'].dt.minute)

# Out
  Business Date  Number   Pay Time Name       Pay Time Date  Minutes
0    2019-05-24       1  Pay Time Start 2019-05-24 11:00:00       60
2    2019-05-24       1    Pay Time End 2019-05-24 12:15:00       15
1    2019-05-24       2  Pay Time Start 2019-05-24 12:30:00       30
3    2019-05-24       2    Pay Time End 2019-05-24 13:30:00       30

Now we calculate the amount of hours with groupby:

daterange = pd.date_range(df['Pay Time Start'].min(), df['Pay Time End'].max(), freq='H')

df_new = pd.DataFrame({'Date':daterange.date,
                    'Time':daterange.time}, dtype='datetime64[ns]')

df_new['Hours'] = (new.groupby(new['Pay Time Date'].dt.hour)['Minutes'].sum()/60).to_numpy()

Final Output

        Date      Time  Hours
0 2019-05-24  11:00:00   1.00
1 2019-05-24  12:00:00   0.75
2 2019-05-24  13:00:00   0.50


问:
React select set initial value with Redux Form
I'm trying to set an initial value for my Select tag using Redux Form field.

Redux Field:

```<code><Field
                    name="statusDto.pkid"
                    component={renderSelectField}
                    type="text"
                    isHidden="true"
                    placeholder="Select Status"
                    options={userRegistrationStatus && userRegistrationStatus.map((values) => { return ({ value: values.pkid, label: i18next.languages[0] === 'en' ? values.enName : values.trName }); })}
                  />
</code>```

Redux Form:

```<code>UserRegistrationForm = reduxForm({
  validate,
  form: 'User_Registration_Form', // a unique identifier for this form
  enableReinitialize: true,
})(UserRegistrationForm));
</code>```

React Select:

```<code>handleChange = (selectedOption) => {
    const { onChange } = this.props;
    this.setState({ selectedOptionState: selectedOption });
    onChange(selectedOption.value);
  };

 <Select
        name={name}
        value={selectedOptionState}
        onChange={this.handleChange}
        styles={customStyles}
        options={options}
        clearable={false}
        className="react-select"
        placeholder={placeholder}
        isDisabled={isDisabled}
        classNamePrefix="react-select"
        theme={(theme) => ({
          ...theme,
          borderRadius: 0,
          colors: {
            ...theme.colors,
            primary: '#70bbfd',
          },
        })}
      />
</code>```

Using redux-form initialize, I try to assign the first value to react-select but it doesn't seem to be worth it. Can you help me?

答:
I solved the problem.

React Select:

```<code><Select
        name={name}
        value={(value === '') ? null : options.find(obj => obj.value === value)}
        onChange={this.handleChange}
        styles={customStyles}
        options={options}
        clearable={false}
        className="react-select"
        placeholder={placeholder}
        isDisabled={isDisabled}
        classNamePrefix="react-select"
        theme={(theme) => ({
          ...theme,
          borderRadius: 0,
          colors: {
            ...theme.colors,
            primary: '#70bbfd',
          },
        })}
      />
</code>```

Body:
I'm trying to set an initial value for my Select tag using Redux Form field.

Redux Field:

<Field
                    name="statusDto.pkid"
                    component={renderSelectField}
                    type="text"
                    isHidden="true"
                    placeholder="Select Status"
                    options={userRegistrationStatus && userRegistrationStatus.map((values) => { return ({ value: values.pkid, label: i18next.languages[0] === 'en' ? values.enName : values.trName }); })}
                  />

Redux Form:

UserRegistrationForm = reduxForm({
  validate,
  form: 'User_Registration_Form', // a unique identifier for this form
  enableReinitialize: true,
})(UserRegistrationForm));

React Select:

handleChange = (selectedOption) => {
    const { onChange } = this.props;
    this.setState({ selectedOptionState: selectedOption });
    onChange(selectedOption.value);
  };

 <Select
        name={name}
        value={selectedOptionState}
        onChange={this.handleChange}
        styles={customStyles}
        options={options}
        clearable={false}
        className="react-select"
        placeholder={placeholder}
        isDisabled={isDisabled}
        classNamePrefix="react-select"
        theme={(theme) => ({
          ...theme,
          borderRadius: 0,
          colors: {
            ...theme.colors,
            primary: '#70bbfd',
          },
        })}
      />

Using redux-form initialize, I try to assign the first value to react-select but it doesn't seem to be worth it. Can you help me?

Body:
I solved the problem.

React Select:

<Select
        name={name}
        value={(value === '') ? null : options.find(obj => obj.value === value)}
        onChange={this.handleChange}
        styles={customStyles}
        options={options}
        clearable={false}
        className="react-select"
        placeholder={placeholder}
        isDisabled={isDisabled}
        classNamePrefix="react-select"
        theme={(theme) => ({
          ...theme,
          borderRadius: 0,
          colors: {
            ...theme.colors,
            primary: '#70bbfd',
          },
        })}
      />


问:
How to switch to container session when lost connection with redis as using spring-shiro sessionManager with redis
I am using spring-shiro sessionManager with redis.

If the redis don't work or just lost connection with redis, DefaultWebSessionManager of shiro can't CRUD session. I hope I can switch to use container session when this happen.

Is there sth like memcached-session-manager that can also using web container session?

答:
You would need a custom SessionManager for this.

This gets complicated pretty quickly depending on how you want to fail over, You would lose cluster support, which would probably require you to start using sticky sessions (or something similar).

Have you looked into making Redis fault tolerant instead?


问:
Google Map Marker pulse animation?
I wonder is there any way to make Google Map Marker to pulse? Like here: http://plebeosaur.us/etc/map/</p>

答:
SVG here can make wonders, if you don't mind IE/Edge compatibility.

I've created this blue pulsating dot (adapted from this one).

Warning: animation not playing on Edge 18 (but should in Edge 75).

Simply replace the image in the marker properties:

```<code>var marker = new google.maps.Marker({
  //...
  icon: {
    url: 'path/to/your/image.svg',
    //...
  },
});
</code>```

Title: Google Map Marker pulse animation?

Body:
SVG here can make wonders, if you don't mind IE/Edge compatibility.

I've created this blue pulsating dot (adapted from this one).

Warning: animation not playing on Edge 18 (but should in Edge 75).

Simply replace the image in the marker properties:

var marker = new google.maps.Marker({
  //...
  icon: {
    url: 'path/to/your/image.svg',
    //...
  },
});


问:
How to stay on same page if a record delete from table in laravel 5.4?
I have multiple records in my database table Now, what I want when I click on a specific record delete button then the record will be deleted and the page will be stay on the same page without redirect anywhere. So, How can I do this? Please help me.

controller: UserController.php

```<code>public function delete_emp($id)
{
    DB::delete('delete from emp where id = ?',[$id]);
}
</code>```

view: emp-list.blade.php

```<code><table class="table">
    <thead>
        <tr>
            <th>Full Name</th>
            <th>Email</th>
            <th>Phone</th>
            <th>Action</th>
        </tr>
    </thead>
    <tbody>
        @foreach($result as $row)
        <tr>
            <td>{{ $row->fname }}</td>
            <td>{{ $row->email }}</td>
            <td>{{ $row->phone }}</td>
            <td>
                <a href="{{url('/delete_emp')}}/{{ $row->id }}" class="btn btn-danger" onclick="return confirm('are you sure')">Delete</a>
            </td>
        </tr>
        @endforeach
    </tbody>
</table>
</code>```

route/web.php

```<code>Route::get('delete_emp/{id}','UserController@delete_emp');
</code>```

答:
in your UserController.php, just add one line below the query </p>

```<code>public function delete_emp($id)
{
    DB::delete('delete from emp where id = ?',[$id]);
    return redirect()->back();
}
</code>```

Body:
I have multiple records in my database table Now, what I want when I click on a specific record delete button then the record will be deleted and the page will be stay on the same page without redirect anywhere. So, How can I do this? Please help me.

controller: UserController.php

public function delete_emp($id)
{
    DB::delete('delete from emp where id = ?',[$id]);
}

view: emp-list.blade.php

            Full Name
            Email
            Phone
            Action

        @foreach($result as $row)

            {{ $row->fname }}
            {{ $row->email }}
            {{ $row->phone }}

                id }}" class="btn btn-danger" onclick="return confirm('are you sure')">Delete

        @endforeach

route/web.php

Route::get('delete_emp/{id}','UserController@delete_emp');

Body:
in your UserController.php, just add one line below the query

public function delete_emp($id)
{
    DB::delete('delete from emp where id = ?',[$id]);
    return redirect()->back();
}


问:
Item overlap in recyclerview
I want to overlap first item on second item in recycler view .

this is what I want to achieve:

this is how my recycler view is looking now:

[]

content inside green border is actually a recyclerView  and the first item in parent recycler view and the rating bar layout is the second item in parent recyclerview .
please suggest me how can i overlap first item on to second item
i have tried this

item_rating_layout:

```<code> <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        style="@style/LayoutHeightWrapWidthMatchStyling"
        android:layout_width="match_parent"
        android:gravity="center_horizontal"
        android:orientation="vertical"
        android:padding="@dimen/padding_large">

        <TextView
            android:id="@+id/tvRatingMessage"
            style="@style/TextStyleNormal.XXLarge"
            android:text="@string/rating_exp" />

        <RatingBar
            android:id="@+id/ratingBar"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="@dimen/margin_medium"
            android:numStars="5"
            android:progressBackgroundTint="@color/gray"
            android:stepSize="1.0"
            android:progressTint="@color/primaryColor"
            android:rating="2.5" />

        <TextView
            android:id="@+id/tvWriteFeedBack"
            style="@style/TextStyleNormal.XXXLarge.primary"
            android:padding="@dimen/padding_medium"
            android:text="Write Feedback"
            android:visibility="gone" />

    </LinearLayout>
</code>```

item_recycler_view:

```<code> <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tool="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="@dimen/margin_24dp"
        android:layout_marginEnd="@dimen/margin_24dp"
        android:background="@color/warranty_card_background">

        <androidx.core.widget.NestedScrollView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:fillViewport="true">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:background="@drawable/btn_shap_without_solid_green"
                android:gravity="center_horizontal"
                android:orientation="vertical">

                <ImageView
                    android:id="@+id/ivProductImage"
                    android:layout_width="100dp"
                    android:layout_height="100dp"
                    android:layout_marginTop="@dimen/margin_medium"
                    android:scaleType="fitXY"
                    app:srcCompat="@drawable/ic_original_placeholder" />

                <TextView
                    android:id="@+id/tvName"
                    style="@style/TextStyleNormal.XXLarge.black"
                    android:textStyle="bold"
                    tool:text="Steelbird Air" />

                    <TextView
                        android:id="@+id/tvModel"
                        style="@style/TextStyleNormal.XXLarge"
                        tool:text="SBA-2 Horn Matt Black With Red " />

                <TextView
                    android:id="@+id/tvId"
                    style="@style/TextStyleNormal.XXLarge.gray"
                    android:text="@string/product_id" />

                <TextView
                    android:id="@+id/tvViewProductDetails"
                    style="@style/TextStyleNormal.XLarge.primary"
                    android:text="View product Details" />

                <androidx.recyclerview.widget.RecyclerView
                    android:id="@+id/rvWarrantyCard"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginStart="@dimen/margin_medium"
                    android:layout_marginBottom="@dimen/margin_medium">

                </androidx.recyclerview.widget.RecyclerView>
            </LinearLayout>
        </androidx.core.widget.NestedScrollView>
    </LinearLayout>
</code>```

答:
You can use the following ItemDecoration:

```<code>  public class OverlapDecoration extends RecyclerView.ItemDecoration {

  private final static int vertOverlap = -90;

  @Override
  public void getItemOffsets (Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {

    outRect.set(0, vertOverlap, 0, 0);

  }
}
</code>```

Now when you add the above decoration your next row will be drawn over your previous row. To rectify this make your recyclerview as reverse by using setReverseLayout(true)

You can refer to my question which has almost same requirement

Title: Item overlap in recyclerview

Body:
I want to overlap first item on second item in recycler view .

this is what I want to achieve:

this is how my recycler view is looking now:

[]

content inside green border is actually a recyclerView  and the first item in parent recycler view and the rating bar layout is the second item in parent recyclerview .
please suggest me how can i overlap first item on to second item
i have tried this

item_rating_layout:

 <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        style="@style/LayoutHeightWrapWidthMatchStyling"
        android:layout_width="match_parent"
        android:gravity="center_horizontal"
        android:orientation="vertical"
        android:padding="@dimen/padding_large">

        <TextView
            android:id="@+id/tvRatingMessage"
            style="@style/TextStyleNormal.XXLarge"
            android:text="@string/rating_exp" />

        <RatingBar
            android:id="@+id/ratingBar"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="@dimen/margin_medium"
            android:numStars="5"
            android:progressBackgroundTint="@color/gray"
            android:stepSize="1.0"
            android:progressTint="@color/primaryColor"
            android:rating="2.5" />

        <TextView
            android:id="@+id/tvWriteFeedBack"
            style="@style/TextStyleNormal.XXXLarge.primary"
            android:padding="@dimen/padding_medium"
            android:text="Write Feedback"
            android:visibility="gone" />

    </LinearLayout>

item_recycler_view:

 <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tool="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="@dimen/margin_24dp"
        android:layout_marginEnd="@dimen/margin_24dp"
        android:background="@color/warranty_card_background">

        <androidx.core.widget.NestedScrollView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:fillViewport="true">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:background="@drawable/btn_shap_without_solid_green"
                android:gravity="center_horizontal"
                android:orientation="vertical">

                <ImageView
                    android:id="@+id/ivProductImage"
                    android:layout_width="100dp"
                    android:layout_height="100dp"
                    android:layout_marginTop="@dimen/margin_medium"
                    android:scaleType="fitXY"
                    app:srcCompat="@drawable/ic_original_placeholder" />

                <TextView
                    android:id="@+id/tvName"
                    style="@style/TextStyleNormal.XXLarge.black"
                    android:textStyle="bold"
                    tool:text="Steelbird Air" />

                    <TextView
                        android:id="@+id/tvModel"
                        style="@style/TextStyleNormal.XXLarge"
                        tool:text="SBA-2 Horn Matt Black With Red " />

                <TextView
                    android:id="@+id/tvId"
                    style="@style/TextStyleNormal.XXLarge.gray"
                    android:text="@string/product_id" />

                <TextView
                    android:id="@+id/tvViewProductDetails"
                    style="@style/TextStyleNormal.XLarge.primary"
                    android:text="View product Details" />

                <androidx.recyclerview.widget.RecyclerView
                    android:id="@+id/rvWarrantyCard"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginStart="@dimen/margin_medium"
                    android:layout_marginBottom="@dimen/margin_medium">

                </androidx.recyclerview.widget.RecyclerView>
            </LinearLayout>
        </androidx.core.widget.NestedScrollView>
    </LinearLayout>

Body:
You can use the following ItemDecoration:

  public class OverlapDecoration extends RecyclerView.ItemDecoration {

  private final static int vertOverlap = -90;

  @Override
  public void getItemOffsets (Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {

    outRect.set(0, vertOverlap, 0, 0);

  }
}

Now when you add the above decoration your next row will be drawn over your previous row. To rectify this make your recyclerview as reverse by using setReverseLayout(true)

You can refer to my question which has almost same requirement


问:
Can't install Vowpalwabbit using pip on Windows 10
I have python 3.7.0 installed on Windows 10 and I can't install Vowpalwobbit. When I use command:

```<code>pip install vowpalwabbit
</code>```

I get:

```<code>Building wheels for collected packages: vowpalwabbit
  Building wheel for vowpalwabbit (setup.py) ... error
  ERROR: Complete output from command 'c:\users\user\appdata\local\programs\python\python37-32\python.exe' -u -c 'import setuptools, tokenize;__file__='"'"'C:\\Users\\User\\AppData\\Local\\Temp\\pip-install-0tp3npd1\\vowpalwabbit\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d 'C:\Users\User\AppData\Local\Temp\pip-wheel-78e8xolx' --python-tag cp37:
  ERROR: running bdist_wheel
  ...
    File "C:\Users\User\AppData\Local\Temp\pip-install-0tp3npd1\vowpalwabbit\setup.py", line 115, in build_extension
      raise Exception('Pre-built vw/python library for Windows is not supported for this python version')
  Exception: Pre-built vw/python library for Windows is not supported for this python version
</code>```

I tried use Python 3.5.0 and it still didn't work.

答:
I'll paste the response I gave on the issue here:

The Python package includes C++ that needs to be built from source, and is made a bit difficult because the dependencies need to be present too. We are working on making the Python install experience better, but in the meantime here is how I was able to get your situation working on Windows 10 1809 from latest vw master. (Things have changed quite a bit since 8.5.0 which is what is on pip)

For Python3.7 I used Boost 1.70 (This is the latest version on vcpkg)

I used CMake 3.13 and it was able to resolve the Boost 1.70 dependencies

Install vcpkg

Install dependencies with vcpkg

```<code>vcpkg install zlib:x64-windows
vcpkg install boost-system:x64-windows
vcpkg install boost-program-options:x64-windows
vcpkg install boost-test:x64-windows
vcpkg install boost-align:x64-windows
vcpkg install boost-foreach:x64-windows
vcpkg install boost-python:x64-windows
vcpkg install boost-math:x64-windows
vcpkg install boost-thread:x64-windows
</code>```

cd <repo_root>/python

python setup.py --vcpkg-root C:\path\to\vcpkg install

Where C:\path\to\vcpkg is the root directory of where you cloned vcpkg

Body:
I have python 3.7.0 installed on Windows 10 and I can't install Vowpalwobbit. When I use command:

pip install vowpalwabbit

I get:

Building wheels for collected packages: vowpalwabbit
  Building wheel for vowpalwabbit (setup.py) ... error
  ERROR: Complete output from command 'c:\users\user\appdata\local\programs\python\python37-32\python.exe' -u -c 'import setuptools, tokenize;__file__='"'"'C:\\Users\\User\\AppData\\Local\\Temp\\pip-install-0tp3npd1\\vowpalwabbit\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d 'C:\Users\User\AppData\Local\Temp\pip-wheel-78e8xolx' --python-tag cp37:
  ERROR: running bdist_wheel
  ...
    File "C:\Users\User\AppData\Local\Temp\pip-install-0tp3npd1\vowpalwabbit\setup.py", line 115, in build_extension
      raise Exception('Pre-built vw/python library for Windows is not supported for this python version')
  Exception: Pre-built vw/python library for Windows is not supported for this python version

I tried use Python 3.5.0 and it still didn't work.

Body:
I'll paste the response I gave on the issue here:

The Python package includes C++ that needs to be built from source, and is made a bit difficult because the dependencies need to be present too. We are working on making the Python install experience better, but in the meantime here is how I was able to get your situation working on Windows 10 1809 from latest vw master. (Things have changed quite a bit since 8.5.0 which is what is on pip)

For Python3.7 I used Boost 1.70 (This is the latest version on vcpkg)

I used CMake 3.13 and it was able to resolve the Boost 1.70 dependencies

Install vcpkg

Install dependencies with vcpkg

vcpkg install zlib:x64-windows
vcpkg install boost-system:x64-windows
vcpkg install boost-program-options:x64-windows
vcpkg install boost-test:x64-windows
vcpkg install boost-align:x64-windows
vcpkg install boost-foreach:x64-windows
vcpkg install boost-python:x64-windows
vcpkg install boost-math:x64-windows
vcpkg install boost-thread:x64-windows

cd <repo_root>/python

python setup.py --vcpkg-root C:\path\to\vcpkg install

Where C:\path\to\vcpkg is the root directory of where you cloned vcpkg


问:
How to delete each third row from
 using only JavaScript?
I want to delete each third row in this code.
How I can do this?
Thanks for any answers

I was trying to do something like this:

```<code>const table = document.getElementById('myTable');

for (let i =0; i <table.rows.length; i++) {
  if (i%3 === 0 ) {
    table.deleteRow(i)
  }
}
</code>```

I have this table:

```<code>        <tbody>
            <tr>
                <td>First row.</td>
            </tr>
            <tr>
                <td>Second row.</td>
            </tr>
          <tr>
                <td>DELETE 3</td>
            </tr>
          <tr>
                <td>4 row.</td>
            </tr>
          <tr>
                <td>5 row.</td>
            </tr>
          <tr>
                <td>DELETE 6</td>
            </tr>
          <tr>
                <td>First row.</td>
            </tr>
            <tr>
                <td>Second row.</td>
            </tr>
          <tr>
                <td>DELETE 9</td>
            </tr>
        </tbody>
</code>```

I need a script which I will put in the console of my browser and I will delete each third row in anything table. Thank you!

答:
The problem is that as soon as you remove a row from your table, the tables rows.length property decreases by 1 as well as the the order of your rows changes. (thus after removing, the next third will be a different element as before removing)

Better iterate over the elements from the last to the first like:

var myTable = document.getElementById("myTable");
for (var a = myTable.rows.length - 1; a > 0; a--) {
  if ((a + 1) % 3 === 0) {
    myTable.deleteRow(a)
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table id="myTable">

  <tbody>
    <tr>
      <td>First row.</td>
    </tr>
    <tr>
      <td>Second row.</td>
    </tr>
    <tr>
      <td>DELETE 3</td>
    </tr>
    <tr>
      <td>4 row.</td>
    </tr>
    <tr>
      <td>5 row.</td>
    </tr>
    <tr>
      <td>DELETE 6</td>
    </tr>
    <tr>
      <td>First row.</td>
    </tr>
    <tr>
      <td>Second row.</td>
    </tr>
    <tr>
      <td>DELETE 9</td>
    </tr>
  </tbody>
</table></code>```

Title: How to delete each third row from <tbody> using only JavaScript?

Body:
I want to delete each third row in this code.
How I can do this?
Thanks for any answers

I was trying to do something like this:

const table = document.getElementById('myTable');

for (let i =0; i <table.rows.length; i++) {
  if (i%3 === 0 ) {
    table.deleteRow(i)
  }
}

I have this table:

                First row.

                Second row.

                DELETE 3

                4 row.

                5 row.

                DELETE 6

                First row.

                Second row.

                DELETE 9

I need a script which I will put in the console of my browser and I will delete each third row in anything table. Thank you!

Body:
The problem is that as soon as you remove a row from your table, the tables rows.length property decreases by 1 as well as the the order of your rows changes. (thus after removing, the next third will be a different element as before removing)

Better iterate over the elements from the last to the first like:

var myTable = document.getElementById("myTable");
for (var a = myTable.rows.length - 1; a > 0; a--) {
  if ((a + 1) % 3 === 0) {
    myTable.deleteRow(a)
  }
}

<table id="myTable">

  <tbody>
    <tr>
      <td>First row.</td>
    </tr>
    <tr>
      <td>Second row.</td>
    </tr>
    <tr>
      <td>DELETE 3</td>
    </tr>
    <tr>
      <td>4 row.</td>
    </tr>
    <tr>
      <td>5 row.</td>
    </tr>
    <tr>
      <td>DELETE 6</td>
    </tr>
    <tr>
      <td>First row.</td>
    </tr>
    <tr>
      <td>Second row.</td>
    </tr>
    <tr>
      <td>DELETE 9</td>
    </tr>
  </tbody>
</table>


问:
Why we need to use <uses-feature> attribute?
My question is related to camera. When an application needs to use the system camera, we create an intent with ACTION_IMAGE_CAPTURE action and add a permission like this in the manifest file.

```<code><uses-permission android:name="android.permission.CAMERA"/>
</code>```

But besides that, there is one such

```<code><uses-feature android:name="android.hardware.camera"/>
</code>```

What is it for? I read that if this line is written, then if the phone does not have a camera the application will not install. Is it true? And besides this, why do we need this?

And for what the line <uses-feature/> is generally responsible in manifest file?

答:
This is very important part. Let suppose your application uses a particular hard ware and that is essential for your app that hardware must be available on a device to use your application. If that is defined, your app will be filtered out for those devices that have that specific hard ware.

NOTE: As it is well documented over Google Developer site

**Google Play uses the  elements declared in your app manifest to filter your app from devices that do not meet its hardware and software feature requirements.

By specifying the features that your application requires, you enable Google Play to present your application only to users whose devices meet the application's feature requirements, rather than presenting it to all users.**

Refer this link for further reference guide

Body:
My question is related to camera. When an application needs to use the system camera, we create an intent with ACTION_IMAGE_CAPTURE action and add a permission like this in the manifest file.

<uses-permission android:name="android.permission.CAMERA"/>

But besides that, there is one such

<uses-feature android:name="android.hardware.camera"/>

What is it for? I read that if this line is written, then if the phone does not have a camera the application will not install. Is it true? And besides this, why do we need this?

And for what the line <uses-feature/> is generally responsible in manifest file?


问:
Casting complex values discards imaginary part on fast fourier algorithm
I was making the fast fourier transformation algorithm, based on cooley-tukey method. The code looks fine to me, but I keep getting numpy error like:

```<code>Casting complex values to real discards the imaginary part
</code>```

I am not sure how to change the assignments in the iterrations. The algorithm is described here:

def fast_fourier_transformation(data):
    N = len(data)
    if N > 1:
        Wn = math.e ** (2 * math.pi * 1j / N)
        W = 1
        A_even = data[::2]
        A_odd = data[1::2]
        B_even = fast_fourier_transformation(A_even)
        B_odd = fast_fourier_transformation(A_odd)
        for k in range(0, N // 2):
            data[k] = B_even[k] + W * B_odd[k]
            data[k + N // 2] = B_even[k] - W * B_odd[k]
            W = W * Wn
    return data
```

答: Your data variable needs to be declared as complex (set the imaginary component to zero for strictly real input), since the output of your function needs to be complex, and you are using "data" for both the input parameter and the return value (output).</p>

Body:
I was making the fast fourier transformation algorithm, based on cooley-tukey method. The code looks fine to me, but I keep getting numpy error like:

Casting complex values to real discards the imaginary part

I am not sure how to change the assignments in the iterrations. The algorithm is described here:

def fast_fourier_transformation(data):
    N = len(data)
    if N > 1:
        Wn = math.e ** (2 * math.pi * 1j / N)
        W = 1
        A_even = data[::2]
        A_odd = data[1::2]
        B_even = fast_fourier_transformation(A_even)
        B_odd = fast_fourier_transformation(A_odd)
        for k in range(0, N // 2):
            data[k] = B_even[k] + W * B_odd[k]
            data[k + N // 2] = B_even[k] - W * B_odd[k]
            W = W * Wn
    return data


问:
Contenteditable table row,column modifier
Is there anyway to not display the row and column modification (the 2 arrows and cross) when making a table editable. I went through the W3C draft for contenteditable and it doesn't talk anything about the specific cases of different elements.</p>

答:
If I understand you correctly, the following will do it in Firefox (note: apparently the document must be loaded before this command can be executed. See comments below):

```<code> document.execCommand("enableInlineTableEditing", null, false);
</code>```

See also this question: Javascript, Firefox: how to disable the browser specific cell controls?

ContentLicense: CC BY-SA 2.5

Body:
If I understand you correctly, the following will do it in Firefox (note: apparently the document must be loaded before this command can be executed. See comments below):

 document.execCommand("enableInlineTableEditing", null, false);

See also this question: Javascript, Firefox: how to disable the browser specific cell controls?