问:
Correct use of polymorphism and inheritance for some logic
I have basic class:

```<code>@Entity
@Table(name = "data_model_query")
@Inheritance
@DiscriminatorColumn(name="query_type",
public abstract class Query {

    private String dmlQuery;

    private String ddlQuery;

    //getters and setters
}
</code>```

And two child. SimpleQuery:

```<code>@Entity
@DiscriminatorValue("SIMPLE")
public class SimpleQuery extends Query {

    private ConnectionInfo connectionInfo; //initialize via constructor or setter

    public Integer getConnectionId() {
        return connectionInfo.getId();
    }

}
</code>```

SummaryQuery:

```<code>@Entity
@DiscriminatorValue("COMPLEX")
public class SummaryQuery extends Query {

    private List<SimpleQuery> children;

}
</code>```

In some service, I want add some logic for validate sql query. I created method:

```<code>@Service
class SomeService {
    //some business logic
    @Autowired
    private final DataExtractorService dataExtractorService;

    private void validateQueries(Query query) {
        if (query instanceof SimpleQuery) {
            String sqlQuery = ((SimpleQuery) query).getSqlQuery();
            Integer connectionId = ((SimpleQuery) query).getConnectionId();
            //validate by sqlQuery and connectionId
            dataExtractorService.tryToextractOneRecord(connectionId , sqlQuery);
        } else {
            SummaryQuery summaryQuery = (SummaryQuery) query;
            List<SimpleQuery> children = ((SummaryQuery) query).getChildren();
            children.forEach(query -> dataExtractorService.tryToextractOneRecord(query.getConnectionId(), query.getSqlQuery());
        }
    }
}
</code>```

In this solution, I strongly dislike the use of if check, as well as the use of instanceof. What if I had more than two inheritors, the code would be too huge and I need to remember to add another if. This is not a OOP approach. How could this problem be solved?

EDIT:

Query validation is essentially executing it on the DB. For this you need ddlQuery and connectionId. To do this, you need a service for working with the database. I can't inject it in POJO classes, because of this I can't implement the validate() method

答:
Add this method to your Query class:

```<code>public abstract class Query {

    private String dmlQuery;

    private String ddlQuery;

    //getters and setters

    public abstract boolean validate();  //  <----
}
</code>```

Then implement the method in your children classes

```<code>public class SimpleQuery extends Query {

    private ConnectionInfo connectionInfo;

    public Integer getConnectionId() {
        return connectionInfo.getId();
    }

    @Override
    public boolean validate() {  //  <----
        //Simple Query validation code here
    }

}
public class SummaryQuery extends Query {

    private List<SimpleQuery> children;

    @Override
    public boolean validate() {  //  <----
        //Summary Query validation code here
    }

}
</code>```

Then all you have to do is call that method.  Any additional Query classes will be forced to define a validate method.

```<code>class SomeService {
    //some business logic

    private void validateQueries(Query query) {
         // Some logic
         boolean isValid = query.validate();
         // Other logic
    }
}
</code>```

Body:
I have basic class:

@Entity
@Table(name = "data_model_query")
@Inheritance
@DiscriminatorColumn(name="query_type",
public abstract class Query {

    private String dmlQuery;

    private String ddlQuery;

    //getters and setters
}

And two child. SimpleQuery:

@Entity
@DiscriminatorValue("SIMPLE")
public class SimpleQuery extends Query {

    private ConnectionInfo connectionInfo; //initialize via constructor or setter

    public Integer getConnectionId() {
        return connectionInfo.getId();
    }

}

SummaryQuery:

@Entity
@DiscriminatorValue("COMPLEX")
public class SummaryQuery extends Query {

    private List<SimpleQuery> children;

}

In some service, I want add some logic for validate sql query. I created method:

@Service
class SomeService {
    //some business logic
    @Autowired
    private final DataExtractorService dataExtractorService;

    private void validateQueries(Query query) {
        if (query instanceof SimpleQuery) {
            String sqlQuery = ((SimpleQuery) query).getSqlQuery();
            Integer connectionId = ((SimpleQuery) query).getConnectionId();
            //validate by sqlQuery and connectionId
            dataExtractorService.tryToextractOneRecord(connectionId , sqlQuery);
        } else {
            SummaryQuery summaryQuery = (SummaryQuery) query;
            List<SimpleQuery> children = ((SummaryQuery) query).getChildren();
            children.forEach(query -> dataExtractorService.tryToextractOneRecord(query.getConnectionId(), query.getSqlQuery());
        }
    }
}

In this solution, I strongly dislike the use of if check, as well as the use of instanceof. What if I had more than two inheritors, the code would be too huge and I need to remember to add another if. This is not a OOP approach. How could this problem be solved?

EDIT:

Query validation is essentially executing it on the DB. For this you need ddlQuery and connectionId. To do this, you need a service for working with the database. I can't inject it in POJO classes, because of this I can't implement the validate() method

Body:
Add this method to your Query class:

public abstract class Query {

    private String dmlQuery;

    private String ddlQuery;

    //getters and setters

    public abstract boolean validate();  //  <----
}

Then implement the method in your children classes

public class SimpleQuery extends Query {

    private ConnectionInfo connectionInfo;

    public Integer getConnectionId() {
        return connectionInfo.getId();
    }

    @Override
    public boolean validate() {  //  <----
        //Simple Query validation code here
    }

}
public class SummaryQuery extends Query {

    private List<SimpleQuery> children;

    @Override
    public boolean validate() {  //  <----
        //Summary Query validation code here
    }

}

Then all you have to do is call that method.  Any additional Query classes will be forced to define a validate method.

class SomeService {
    //some business logic

    private void validateQueries(Query query) {
         // Some logic
         boolean isValid = query.validate();
         // Other logic
    }
}


来源: stackexchange

问:
Memory leak with any n_jobs doing cross validation
I am running a code to do a binary classification and predict labels afterwards. The code runs perfectly with one specific database of size 257673 rows and 47 columns. When I try with one of 91690 rows and 10 columns, which is certainly smaller, I get the error call:

```<code>TerminatedWorkerError: A worker process managed by the executor was unexpectedly terminated. This could be caused by a segmentation fault while calling the function or by an excessive memory usage causing the Operating System to kill the worker. The exit codes of the workers are {SIGKILL(-9)}
</code>```

I am using a cross validation line with n_job=-1

```<code>cross_val_score(model, X.drop(target,axis=1), X[target], cv=outer_cv, n_jobs=-1, scoring='neg_mean_squared_error')

outer_cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=1)
</code>```

model is any of the sklearn algorithms, I have tried with AdaBoostClassifier, LogisticRegression, KNN, SVM, GradientBoosting, RandomForest, DecisionTreeClassifier... and many others and I keep getting the same error.

I have tried changing n_jobs=-2, 1, 2 and still the error persists. I am running the code on a jupyter notebook and my laptop has the following properties:

```<code>Ubuntu 18.04.4 LTS
RAM: 15,5 Gb
Processor: Intel® Core™ i7-8550U CPU @ 1.80GHz × 8
</code>```

How could I solve this issue?

答:
I found the answer to this question.
It seems that some of the scikit-learn algorithms produce these errors depending on the encoding method of categorical features. In my case, I had to remove from the list of algorithms I was using: CategoricalNB(), Ridge(), ElasticNet() and GaussianProcessClassifier(), because they were producing the bugs either with StandardScaler() or with MinMaxScaler(). </p>

ContentLicense: CC BY-SA 4.0

Body:
I am running a code to do a binary classification and predict labels afterwards. The code runs perfectly with one specific database of size 257673 rows and 47 columns. When I try with one of 91690 rows and 10 columns, which is certainly smaller, I get the error call:

TerminatedWorkerError: A worker process managed by the executor was unexpectedly terminated. This could be caused by a segmentation fault while calling the function or by an excessive memory usage causing the Operating System to kill the worker. The exit codes of the workers are {SIGKILL(-9)}

I am using a cross validation line with n_job=-1

cross_val_score(model, X.drop(target,axis=1), X[target], cv=outer_cv, n_jobs=-1, scoring='neg_mean_squared_error')

outer_cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=1)

model is any of the sklearn algorithms, I have tried with AdaBoostClassifier, LogisticRegression, KNN, SVM, GradientBoosting, RandomForest, DecisionTreeClassifier... and many others and I keep getting the same error.

I have tried changing n_jobs=-2, 1, 2 and still the error persists. I am running the code on a jupyter notebook and my laptop has the following properties:

Ubuntu 18.04.4 LTS
RAM: 15,5 Gb
Processor: Intel® Core™ i7-8550U CPU @ 1.80GHz × 8

How could I solve this issue?


问:
How to calculate reconstruction error?
How to calculate reconstruction error and where can I find information about it? (I will calculate reconstruction error of my data after K-means algorithm)</p>

答:
One way to calculate the reconstruction error from a given vector is to compute the euclidean distance between it and its representation.  In K-means, each vector is represented by its nearest center.

So after running k means: For each vector, calculate the error for the vector as the euclidean distance between that vector and its centroid.  Sum them up the errors for every vector, and you have the error on your training set.  Lower errors will tend to give better clusterings overall.

Indeed, the K-Means algorithm is itself tries to optimize this very metric, and if you let it run to convergence, it will find a local minimum on for the euclidean distance reconstruction error.

ContentLicense: CC BY-SA 3.0

Title: How to calculate reconstruction error?


问:
How to disable modal-ok slot of b-modal in vue bootstrap?
I have used modal-ok slot available in b-modal slots to render the OK button of b-modal. I want to conditionally disable the OK button. I have tried 2 methods with no luck. Any suggestion is welcome on how to disable the OK button rendered using the slot.

Disabled prop

```<code> <div
    slot="modal-ok"
    :disabled="true"
    @click.stop="uploadFile(item.id)"
  >
    Upload
  </div>
</code>```

ok-disabled prop of b-modal

```<code>  <div
    slot="modal-ok"
    :ok-disabled="true"
    @click.stop="uploadFile(item.id)"
  >
    Upload
  </div>
</code>```

答:
Use the ok-disabled prop on , to conditionally enable/disable the ok button.

```

For more information check out this section of the documentation.

Body:
I have used modal-ok slot available in b-modal slots to render the OK button of b-modal. I want to conditionally disable the OK button. I have tried 2 methods with no luck. Any suggestion is welcome on how to disable the OK button rendered using the slot.

Disabled prop

    Upload

ok-disabled prop of b-modal

    Upload

Body:
Use the ok-disabled prop on <b-modal>, to conditionally enable/disable the ok button.

<b-modal :ok-disabled="true">
  <!-- Content -->
</b-modal>

For more information check out this section of the documentation.


问:
"No suitable application records were found" when uploading Xcode Archive
When submitting an archive to the App Store I receive the following error:

No suitable application records were found. Verify your bundle identifier 'org.cocoapods.grpcpp' is correct.

I've already double checked that my bundle identifier is correctly set in my project's target (same as in App Store Connect).

Reinstalling Cocoapods did not help either.

Screenshot: https://i.imgur.com/igarpPy.png

答: If you created app in iTunes connect and still facing this issue then check for Xcode(>11.0) File-> Workspace Setting -> Build System - Legacy Build System. Also you can check with adding apple account again in Xcode.


问:
Flex issue in React Native
Styling help needed and am so bad at "Flex".
That icon shows up if a message is long. click it and message expands. need it to be displayed next to time stamp as shown below.

code:

```<code> <View style={row}>
<View style={textContainer}>
              <Text style={title}>Hospital Authority </Text>
              { arrowClicked === true ?
              <Textstyle={subtitle}>{alert}</Text>
              :
              <Textstyle={subtitle}>{alert}</Text>
              }
              <Text style={time}>{timestampToStr(createDate)}</Text>
            </View>

            { alert.charAt(100) !== "" ?
           arrowClicked === true ?
          <Icon type='materialicons' name='arrow-drop-up' size={35} onPress={()=>{this.setFullLength()}}  />
          :
          <Icon type='materialicons' name='arrow-drop-down' size={35} onPress={()=>{this.setFullLength()}}  />
          : null
          }

          </View>
</View>

</code>```

css:

```<code>const styles = StyleSheet.create({
  row: {
    flexDirection: 'row',
    alignItems: 'flex-start',
    marginLeft: 15,
    marginRight: 15,
    paddingTop: 5,
    paddingBottom: 10
  },
  textContainer: {
    flex: 3,
    paddingLeft: 15
  },
title: {
    flex: 1,
    color: '#000000',
    fontWeight: 'bold'
  },
  subTitle: {
    flex: 1,
    color: '#000000'
  },
  time: {
    flex: 1,
    color: '#808080'
  }
})

</code>```

Please need help with this styling!!!!!
Struggling with this from hours !

Update:

Used common view for both and it worked. But I have some extra space that I need to remove. How can I do that???

答:
First off, I noticed you have 3 closed <View/> tags and only 2 open <View> tags. Maybe it was an issue with the copy/paste you did.

I would start first by thinking about the structure of what we want to display.

Since you want to align a text and an icon together, it would make sense for them to share the same container.

```<code><View style={row}>
  <View style={textContainer}>
    <Text style={title}>Hospital Authority </Text>
    { arrowClicked === true ?
    <Textstyle={subtitle}>{alert}</Text>
    :
    <Textstyle={subtitle}>{alert}</Text>
    }
    <View style={timestampAndArrowContainer}>
      <Text style={time}>{timestampToStr(createDate)}</Text>
      {
        alert.charAt(100) !== "" ?
          arrowClicked === true ?
          <Icon type='materialicons' name='arrow-drop-up' size={35} onPress={()=>{this.setFullLength()}}  />
          :
          <Icon type='materialicons' name='arrow-drop-down' size={35} onPress={()=>{this.setFullLength()}}  />
        : null
      }
    </View>
  </View>
</View>
</code>```

And for your styles, you could try something like this

```<code>const styles = StyleSheet.create({
  [...] // rest of your styles
  timestampAndArrowContainer: {
    flex: 1,
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
  }
})
</code>```

Title: Flex issue in React Native

Body:
Styling help needed and am so bad at "Flex".
That icon shows up if a message is long. click it and message expands. need it to be displayed next to time stamp as shown below.

code:

 <View style={row}>
<View style={textContainer}>
              <Text style={title}>Hospital Authority </Text>
              { arrowClicked === true ?
              <Textstyle={subtitle}>{alert}</Text>
              :
              <Textstyle={subtitle}>{alert}</Text>
              }
              <Text style={time}>{timestampToStr(createDate)}</Text>
            </View>

            { alert.charAt(100) !== "" ?
           arrowClicked === true ?
          <Icon type='materialicons' name='arrow-drop-up' size={35} onPress={()=>{this.setFullLength()}}  />
          :
          <Icon type='materialicons' name='arrow-drop-down' size={35} onPress={()=>{this.setFullLength()}}  />
          : null
          }

          </View>
</View>

css:

const styles = StyleSheet.create({
  row: {
    flexDirection: 'row',
    alignItems: 'flex-start',
    marginLeft: 15,
    marginRight: 15,
    paddingTop: 5,
    paddingBottom: 10
  },
  textContainer: {
    flex: 3,
    paddingLeft: 15
  },
title: {
    flex: 1,
    color: '#000000',
    fontWeight: 'bold'
  },
  subTitle: {
    flex: 1,
    color: '#000000'
  },
  time: {
    flex: 1,
    color: '#808080'
  }
})

Please need help with this styling!!!!!
Struggling with this from hours !

Update:

Used common view for both and it worked. But I have some extra space that I need to remove. How can I do that???

Body:
First off, I noticed you have 3 closed <View/> tags and only 2 open <View> tags. Maybe it was an issue with the copy/paste you did.

I would start first by thinking about the structure of what we want to display.

Since you want to align a text and an icon together, it would make sense for them to share the same container.

<View style={row}>
  <View style={textContainer}>
    <Text style={title}>Hospital Authority </Text>
    { arrowClicked === true ?
    <Textstyle={subtitle}>{alert}</Text>
    :
    <Textstyle={subtitle}>{alert}</Text>
    }
    <View style={timestampAndArrowContainer}>
      <Text style={time}>{timestampToStr(createDate)}</Text>
      {
        alert.charAt(100) !== "" ?
          arrowClicked === true ?
          <Icon type='materialicons' name='arrow-drop-up' size={35} onPress={()=>{this.setFullLength()}}  />
          :
          <Icon type='materialicons' name='arrow-drop-down' size={35} onPress={()=>{this.setFullLength()}}  />
        : null
      }
    </View>
  </View>
</View>

And for your styles, you could try something like this

const styles = StyleSheet.create({
  [...] // rest of your styles
  timestampAndArrowContainer: {
    flex: 1,
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
  }
})


问:
MP4 video loads fine in all browsers except from Safari
My mp4 videos are not loading in safari for some reason, in every other browser the html5 player works absolutely fine, but in safari it doesn't. This is for a clients website i'm helping with.

I must stress, i cant host these videos on a different server or video hosting platform. does anyone know how i can this to work.

http://superflyanimalphysio.co.uk/course-videos/Caveltti%20Intro.mp4

my code for the player :

```<code><video class="eltdf-self-hosted-video" controls="true" preload="auto">
                    <source type="video/mp4" src="http://superflyanimalphysio.co.uk/course-videos/Caveltti%20Intro.mp4">

                    </video>
</code>```

答:
You server appears to be not set up to handle range requests properly.

Some browsers will ignore this and simply handle the full video being downloaded, but Safari seems to not play the video in this case - unfortunately the error message in the console is not that helpful.

You can check this by doing a range request test - Apple explain the approach here:

https://developer.apple.com/library/archive/documentation/AppleApplications/Reference/SafariWebContent/CreatingVideoforSafarioniPhone/CreatingVideoforSafarioniPhone.html#//apple_ref/doc/uid/TP40006514-SW6

If the tool reports that it downloaded 100 bytes, the media server correctly handled the byte-range request. If it downloads the entire file, you may need to update the media server.

Doing this for your video confirms that the server is downloading the full video rather than just the range requested:

It may be worth contacting your hosting provider to ask them to correct the server configuration.

Body:
My mp4 videos are not loading in safari for some reason, in every other browser the html5 player works absolutely fine, but in safari it doesn't. This is for a clients website i'm helping with.

I must stress, i cant host these videos on a different server or video hosting platform. does anyone know how i can this to work.

http://superflyanimalphysio.co.uk/course-videos/Caveltti%20Intro.mp4

my code for the player :

<video class="eltdf-self-hosted-video" controls="true" preload="auto">
                    <source type="video/mp4" src="http://superflyanimalphysio.co.uk/course-videos/Caveltti%20Intro.mp4">

                    </video>


问:
How to add a CAPTCHA to all forms for specific IP address with Ruby on Rails
I have table that track users and IP address' actions and mark them as spammers if some conditions occurs.

I want to add a CAPTCHA field to all forms when the user or IP address is marked as a spammer.

What is the right way to do that?

答:
I think you should use custom form builder with your custom behaviour for 'spammers'. Check this out:
Form builder


问:
How to add values from the dom selector?
I use html () to get the value of the html attribute then I add 2 values but it's just like adding a string, how can I add the Dom selector to add numbers?

```<code>var phantram = $('#giamtheophantram').html();
var phantram1 = $('#chuadungma').html();
if(phantram1 == 'contuer'){
  phantram1 = 0;
}
$(document).ready(function() {
document.getElementById('tonggiam').innerHTML = phantram + phantram1;
});
</code>```

答:
+ append strings (there is no auto retype as in PHP), use parseInt() to retype to numbers and make a sum. If decimals are allowed, use parseFloat().

```<code>$(document).ready(function() {
    document.getElementById('tonggiam').innerHTML = parseInt(phantram) + parseInt(phantram1);
});
</code>```

Body:
I use html () to get the value of the html attribute then I add 2 values but it's just like adding a string, how can I add the Dom selector to add numbers?

var phantram = $('#giamtheophantram').html();
var phantram1 = $('#chuadungma').html();
if(phantram1 == 'contuer'){
  phantram1 = 0;
}
$(document).ready(function() {
document.getElementById('tonggiam').innerHTML = phantram + phantram1;
});

Body:
+ append strings (there is no auto retype as in PHP), use parseInt() to retype to numbers and make a sum. If decimals are allowed, use parseFloat().

$(document).ready(function() {
    document.getElementById('tonggiam').innerHTML = parseInt(phantram) + parseInt(phantram1);
});


问:
iterate over array of objects and fetch only specific key to form a new array of object in react js
I have below object. I want to iterate over it and need to fetch only key's values of ability and value key.

var object = [{
    ability: "Strong",
    name: "STRENGTH",
    value: "customer has 10 properties",
    type: "MultiChoice"
  },
  {
    ability: "Good",
    name: "STRENGTH",
    value: "customer has 5 properties",
    type: "MultiChoice"
  },
  {
    ability: "average",
    name: "STRENGTH",
    value: "customer has 3 properties",
    type: "MultiChoice"
  }
]
```

<p>So my expected output should be like below. </p>

<pre class="lang-js prettyprint-override"><code>[{
    ability: "Strong"
    value: "customer has 10 properties"
  },
  {
    ability: "Good"
    value: "customer has 5 properties"
  },
  {
    ability: "average"
    value: "customer has 3 properties"
  }
]
</code>```

Then I again want to use above object to iterate over it and bind its values to dropdown. So my drop-down will display "value" to end user and DB will have "ability". I am trying below code snippet but its not giving expected output. Something I am doing wrong here.

var object = [{
    ability: "Strong",
    name: "STRENGTH",
    value: "customer has 10 properties",
    type: "MultiChoice"
  },
  {
    ability: "Good",
    name: "STRENGTH",
    value: "customer has 5 properties",
    type: "MultiChoice"
  },
  {
    ability: "average",
    name: "STRENGTH",
    value: "customer has 3 properties",
    type: "MultiChoice"
  }
]

let multiChoiceResult = [];
let ability, value
Object.entries(object).map(([key, value]) => {
  ability = value.ability;
  value = value.value;
  multiChoiceResult.push(ability, value);
});
console.log(multiChoiceResult);```

答:
Your solution expects an object as input. But object actually is an array. You can simply use the map function on the given items as follows:

var object = [
  {
    ability: "Strong",
    name: "STRENGTH",
    value: "customer has 10 properties",
    type: "MultiChoice"
  },
  {
    ability: "Good",
    name: "STRENGTH",
    value: "customer has 5 properties",
    type: "MultiChoice"
  },
  {
    ability: "average",
    name: "STRENGTH",
    value: "customer has 3 properties",
    type: "MultiChoice"
  }
];

console.log(
    object.map((item) => ({ ability: item.ability, value: item.value }))
)```

Body:
I have below object. I want to iterate over it and need to fetch only key's values of ability and value key.

var object = [{
    ability: "Strong",
    name: "STRENGTH",
    value: "customer has 10 properties",
    type: "MultiChoice"
  },
  {
    ability: "Good",
    name: "STRENGTH",
    value: "customer has 5 properties",
    type: "MultiChoice"
  },
  {
    ability: "average",
    name: "STRENGTH",
    value: "customer has 3 properties",
    type: "MultiChoice"
  }
]

So my expected output should be like below.

[{
    ability: "Strong"
    value: "customer has 10 properties"
  },
  {
    ability: "Good"
    value: "customer has 5 properties"
  },
  {
    ability: "average"
    value: "customer has 3 properties"
  }
]

Then I again want to use above object to iterate over it and bind its values to dropdown. So my drop-down will display "value" to end user and DB will have "ability". I am trying below code snippet but its not giving expected output. Something I am doing wrong here.

var object = [{
    ability: "Strong",
    name: "STRENGTH",
    value: "customer has 10 properties",
    type: "MultiChoice"
  },
  {
    ability: "Good",
    name: "STRENGTH",
    value: "customer has 5 properties",
    type: "MultiChoice"
  },
  {
    ability: "average",
    name: "STRENGTH",
    value: "customer has 3 properties",
    type: "MultiChoice"
  }
]

let multiChoiceResult = [];
let ability, value
Object.entries(object).map(([key, value]) => {
  ability = value.ability;
  value = value.value;
  multiChoiceResult.push(ability, value);
});
console.log(multiChoiceResult);


问:
how to add token to header in reactjs
I have a web app that I want to use api with. I want to fetch a data that needs a token. I already have the token Ii got the token by running the login function in my postman). The question is: where do I put this token? Some say I need to put it in the headers but I can't find where to make this headers. Here is my code:

```<code>componentDidMount() {
  fetch('API_GOES_HERE', {
    headers: { Authentication: `Bearer ajsbdjabsjhdbfquhjwbeasbdasdjwbqjbds
  }})
 .then(res => res.json())
 .then(json => {
     this.setState({
       contact: json,
       isLoaded: true,
     })
 })
 .catch(err => console.log(err));
}
</code>```

Without the token, the api always returns this {"message":"missing or malformed jwt"}. I already tried this data fetch from postman itself and it works, because I already set the token variable with my token.

I censored the endpoint and the token by changing it to ENDPOINT_API and API_TOKEN. Thanks, any help will be appreciated.

答:
you need to include token in the request header</p>

```<code>fetch('API_ENDPOINT', {
   headers: { Authentication: `Bearer ${token}`
})
.then(res => res.json())
.then(json => {
    this.setState({
      contact: json,
      isLoaded: true,
    })
})
.catch(err => console.log(err));
</code>```

Title: how to add token to header in reactjs

Body:
I have a web app that I want to use api with. I want to fetch a data that needs a token. I already have the token Ii got the token by running the login function in my postman). The question is: where do I put this token? Some say I need to put it in the headers but I can't find where to make this headers. Here is my code:

componentDidMount() {
  fetch('API_GOES_HERE', {
    headers: { Authentication: `Bearer ajsbdjabsjhdbfquhjwbeasbdasdjwbqjbds
  }})
 .then(res => res.json())
 .then(json => {
     this.setState({
       contact: json,
       isLoaded: true,
     })
 })
 .catch(err => console.log(err));
}

Without the token, the api always returns this {"message":"missing or malformed jwt"}. I already tried this data fetch from postman itself and it works, because I already set the token variable with my token.

I censored the endpoint and the token by changing it to ENDPOINT_API and API_TOKEN. Thanks, any help will be appreciated.

Body:
you need to include token in the request header

fetch('API_ENDPOINT', {
   headers: { Authentication: `Bearer ${token}`
})
.then(res => res.json())
.then(json => {
    this.setState({
      contact: json,
      isLoaded: true,
    })
})
.catch(err => console.log(err));


问:
Add total label ChartWrapper Google Chart
How can I add total label on each column to ChartWrapper google chart?
I tryed to search into documentation from google charts, but I'm new in google chart and is not so easy for me.

The link of image below it's a example I want.
example I want

Follow my code below, it's a simple code.

```

答:
to add labels above the bars, you can use an annotation column role.

```<code>{ role: 'annotation', type: 'string' }
</code>```

however, in this case, candle stick series do not support annotations.

you can check which roles are supported by reviewing the data format for each chart type.

as such, we need to add a second bar series, then add the annotation column.

```<code>{ label: 'bar series', type: 'number' },{ role: 'annotation', type: 'string' }
</code>```

see following working example, for the bar series, we just use a value of zero...

google.charts.load('current', {
  callback: drawChart_var,
  packages: ['corechart']
});
function drawChart_var() {
  var dataChart = new google.visualization.arrayToDataTable(
    [[{ label: 'Category', type: 'string' },{ label: '', type: 'number' },
    { label: 'Base 2', type: 'number' },{ label: 'Base 3', type: 'number' },
    { label: 'Base 4', type: 'number' },{ role: 'style', type: 'string', p: { role: 'style' } },
    { label: 'bar series', type: 'number' },{ role: 'annotation', type: 'string' }],
    ['VAR', 0, 0, 3.42, 0, '#EEB14C', 0, '3.42'],['MIX', 0, 3.42, 3.73, 0, '#69AA51', 0, '0.31'],
    ['BNS', 0, 3.73, 3.42, 0, '#D53C38', 0, '-0.31'],['MTRL', 0, 3.42, 2.34, 0, '#D53C38', 0, '-1.08'],
    ['OTHER', 0, 2.34, 2.69, 0, '#69AA51', 0, '0.35'],['CORP', 0, 2.69, 0.7, 0, '#D53C38', 0, '-1.99'],
    ['COST', 0, 0.7, 1.94, 0, '#69AA51', 0, '1.24'],['PNL', 0, 1.94, 0, 0, '#EEB14C', 0, '1.94']]
  );

  var options = {
    animation: {duration: 1500,easing: 'inAndOut',startup: true},
    backgroundColor: 'transparent',bar: {group: {width: '85%'}},
    chartArea: {left: 50,right: 20,bottom: 60,top: 50,width: "100%",height: "70%"},
    hAxis: {textStyle: {fontSize: 12}},
    height: 400,
    legend: 'none',
    seriesType: 'bars',
    series: {0: {type: 'candlesticks'}},
    tooltip: {isHtml: true,trigger: 'both'},
    vAxis: {format: 'short',textStyle: {color: '#616161'},viewWindow: {min: 0,max: 11}},
    width: '100%',
    annotations: {stem: {color: "transparent",length: 100},
    textStyle: {color: "#000000",fontSize: 16,}}
  };

  var chart = new google.visualization.ChartWrapper();
  chart.setChartType('ComboChart');
  chart.setDataTable(dataChart);
  chart.setContainerId('chart_var');
  chart.setOptions(options);
  chart.draw();
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_var"></div></code>```

EDIT

as for the position of the annotation.
given we are using a value of zero for the column the annotation is for,
the position is being set by option --> annotations.stem.length = 100
meaning it will always be 100 pixels from the bottom of the chart.

to make the position dynamic, we need to remove the length option,
and give the column a value greater than zero.
the column value should be the max value of the candlesticks.

to find the max value, we can use data table method --> getColumnRange(colIndex)
this method will return an object with properties for the min & max values of the column we provide.

we need to find the max between the Base 2 and Base 3 columns.

```<code>// find max height
var maxBase2 = dataChart.getColumnRange(2);
var maxBase3 = dataChart.getColumnRange(3);
var maxColumn = Math.max(maxBase2.max, maxBase3.max);
</code>```

then update our annotation column with the max value.

```<code>// update column values to max
for (var i = 0; i < dataChart.getNumberOfRows(); i++) {
  dataChart.setValue(i, 6, maxColumn);
}
</code>```

to ensure the annotation displays on top of the column,
add option --> alwaysOutside

```<code>annotations: {
  alwaysOutside: true,
  stem: {color: 'transparent'},
  textStyle: {color: '#000000',fontSize: 16}
}
</code>```

again, remove the length option.

and also set the color of the column series to transparent.

```<code>  1: {color: 'transparent'}
</code>```

this will cause the annotation to always appear just above the candlesticks.

see following working snippet...

google.charts.load('current', {
  callback: drawChart_var,
  packages: ['corechart']
});
function drawChart_var() {

  var dataChart = new google.visualization.arrayToDataTable(
    [[{ label: 'Category', type: 'string' },{ label: '', type: 'number' },
    { label: 'Base 2', type: 'number' },{ label: 'Base 3', type: 'number' },
    { label: 'Base 4', type: 'number' },{ role: 'style', type: 'string', p: { role: 'style' } },
    { label: 'bar series', type: 'number' },{ role: 'annotation', type: 'string' }],
    ['VAR', 0, 0, 3.42, 0, '#EEB14C', 0, '3.42'],['MIX', 0, 3.42, 3.73, 0, '#69AA51', 0, '0.31'],
    ['BNS', 0, 3.73, 3.42, 0, '#D53C38', 0, '-0.31'],['MTRL', 0, 3.42, 2.34, 0, '#D53C38', 0, '-1.08'],
    ['OTHER', 0, 2.34, 2.69, 0, '#69AA51', 0, '0.35'],['CORP', 0, 2.69, 0.7, 0, '#D53C38', 0, '-1.99'],
    ['COST', 0, 0.7, 1.94, 0, '#69AA51', 0, '1.24'],['PNL', 0, 1.94, 0, 0, '#EEB14C', 0, '1.94']]
  );

    // find max height
    var maxBase2 = dataChart.getColumnRange(2);
    var maxBase3 = dataChart.getColumnRange(3);
    var maxColumn = Math.max(maxBase2.max, maxBase3.max);

    // update column values to max
    for (var i = 0; i < dataChart.getNumberOfRows(); i++) {
      dataChart.setValue(i, 6, maxColumn);
    }

  var options = {
    animation: {duration: 1500,easing: 'inAndOut',startup: true},
    backgroundColor: 'transparent',bar: {group: {width: '85%'}},
    chartArea: {left: 50,right: 20,bottom: 60,top: 50,width: '100%',height: '70%'},
    hAxis: {textStyle: {fontSize: 12}},
    height: 400,
    legend: 'none',
    seriesType: 'bars',
    series: {
      0: {type: 'candlesticks'},
      1: {color: 'transparent'}
    },
    tooltip: {isHtml: true,trigger: 'both'},
    vAxis: {format: 'short',textStyle: {color: '#616161'},viewWindow: {min: 0,max: 11}},
    width: '100%',
    annotations: {
      alwaysOutside: true,
      stem: {color: 'transparent'},
      textStyle: {color: '#000000',fontSize: 16}
    }
  };

  var chart = new google.visualization.ChartWrapper();
  chart.setChartType('ComboChart');
  chart.setDataTable(dataChart);
  chart.setContainerId('chart_var');
  chart.setOptions(options);
  chart.draw();
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_var"></div></code>```

Body:
to add labels above the bars, you can use an annotation column role.

{ role: 'annotation', type: 'string' }

however, in this case, candle stick series do not support annotations.

you can check which roles are supported by reviewing the data format for each chart type.

as such, we need to add a second bar series, then add the annotation column.

{ label: 'bar series', type: 'number' },{ role: 'annotation', type: 'string' }

see following working example, for the bar series, we just use a value of zero...

google.charts.load('current', {
  callback: drawChart_var,
  packages: ['corechart']
});
function drawChart_var() {
  var dataChart = new google.visualization.arrayToDataTable(
    [[{ label: 'Category', type: 'string' },{ label: '', type: 'number' },
    { label: 'Base 2', type: 'number' },{ label: 'Base 3', type: 'number' },
    { label: 'Base 4', type: 'number' },{ role: 'style', type: 'string', p: { role: 'style' } },
    { label: 'bar series', type: 'number' },{ role: 'annotation', type: 'string' }],
    ['VAR', 0, 0, 3.42, 0, '#EEB14C', 0, '3.42'],['MIX', 0, 3.42, 3.73, 0, '#69AA51', 0, '0.31'],
    ['BNS', 0, 3.73, 3.42, 0, '#D53C38', 0, '-0.31'],['MTRL', 0, 3.42, 2.34, 0, '#D53C38', 0, '-1.08'],
    ['OTHER', 0, 2.34, 2.69, 0, '#69AA51', 0, '0.35'],['CORP', 0, 2.69, 0.7, 0, '#D53C38', 0, '-1.99'],
    ['COST', 0, 0.7, 1.94, 0, '#69AA51', 0, '1.24'],['PNL', 0, 1.94, 0, 0, '#EEB14C', 0, '1.94']]
  );

  var options = {
    animation: {duration: 1500,easing: 'inAndOut',startup: true},
    backgroundColor: 'transparent',bar: {group: {width: '85%'}},
    chartArea: {left: 50,right: 20,bottom: 60,top: 50,width: "100%",height: "70%"},
    hAxis: {textStyle: {fontSize: 12}},
    height: 400,
    legend: 'none',
    seriesType: 'bars',
    series: {0: {type: 'candlesticks'}},
    tooltip: {isHtml: true,trigger: 'both'},
    vAxis: {format: 'short',textStyle: {color: '#616161'},viewWindow: {min: 0,max: 11}},
    width: '100%',
    annotations: {stem: {color: "transparent",length: 100},
    textStyle: {color: "#000000",fontSize: 16,}}
  };

  var chart = new google.visualization.ChartWrapper();
  chart.setChartType('ComboChart');
  chart.setDataTable(dataChart);
  chart.setContainerId('chart_var');
  chart.setOptions(options);
  chart.draw();
}

<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_var"></div>

EDIT

as for the position of the annotation.
given we are using a value of zero for the column the annotation is for,
the position is being set by option --> annotations.stem.length = 100
meaning it will always be 100 pixels from the bottom of the chart.

to make the position dynamic, we need to remove the length option,
and give the column a value greater than zero.
the column value should be the max value of the candlesticks.

to find the max value, we can use data table method --> getColumnRange(colIndex)
this method will return an object with properties for the min & max values of the column we provide.

we need to find the max between the Base 2 and Base 3 columns.

// find max height
var maxBase2 = dataChart.getColumnRange(2);
var maxBase3 = dataChart.getColumnRange(3);
var maxColumn = Math.max(maxBase2.max, maxBase3.max);

then update our annotation column with the max value.

// update column values to max
for (var i = 0; i < dataChart.getNumberOfRows(); i++) {
  dataChart.setValue(i, 6, maxColumn);
}

to ensure the annotation displays on top of the column,
add option --> alwaysOutside

annotations: {
  alwaysOutside: true,
  stem: {color: 'transparent'},
  textStyle: {color: '#000000',fontSize: 16}
}

again, remove the length option.

and also set the color of the column series to transparent.

  1: {color: 'transparent'}

this will cause the annotation to always appear just above the candlesticks.

see following working snippet...

google.charts.load('current', {
  callback: drawChart_var,
  packages: ['corechart']
});
function drawChart_var() {

  var dataChart = new google.visualization.arrayToDataTable(
    [[{ label: 'Category', type: 'string' },{ label: '', type: 'number' },
    { label: 'Base 2', type: 'number' },{ label: 'Base 3', type: 'number' },
    { label: 'Base 4', type: 'number' },{ role: 'style', type: 'string', p: { role: 'style' } },
    { label: 'bar series', type: 'number' },{ role: 'annotation', type: 'string' }],
    ['VAR', 0, 0, 3.42, 0, '#EEB14C', 0, '3.42'],['MIX', 0, 3.42, 3.73, 0, '#69AA51', 0, '0.31'],
    ['BNS', 0, 3.73, 3.42, 0, '#D53C38', 0, '-0.31'],['MTRL', 0, 3.42, 2.34, 0, '#D53C38', 0, '-1.08'],
    ['OTHER', 0, 2.34, 2.69, 0, '#69AA51', 0, '0.35'],['CORP', 0, 2.69, 0.7, 0, '#D53C38', 0, '-1.99'],
    ['COST', 0, 0.7, 1.94, 0, '#69AA51', 0, '1.24'],['PNL', 0, 1.94, 0, 0, '#EEB14C', 0, '1.94']]
  );

    // find max height
    var maxBase2 = dataChart.getColumnRange(2);
    var maxBase3 = dataChart.getColumnRange(3);
    var maxColumn = Math.max(maxBase2.max, maxBase3.max);

    // update column values to max
    for (var i = 0; i < dataChart.getNumberOfRows(); i++) {
      dataChart.setValue(i, 6, maxColumn);
    }

  var options = {
    animation: {duration: 1500,easing: 'inAndOut',startup: true},
    backgroundColor: 'transparent',bar: {group: {width: '85%'}},
    chartArea: {left: 50,right: 20,bottom: 60,top: 50,width: '100%',height: '70%'},
    hAxis: {textStyle: {fontSize: 12}},
    height: 400,
    legend: 'none',
    seriesType: 'bars',
    series: {
      0: {type: 'candlesticks'},
      1: {color: 'transparent'}
    },
    tooltip: {isHtml: true,trigger: 'both'},
    vAxis: {format: 'short',textStyle: {color: '#616161'},viewWindow: {min: 0,max: 11}},
    width: '100%',
    annotations: {
      alwaysOutside: true,
      stem: {color: 'transparent'},
      textStyle: {color: '#000000',fontSize: 16}
    }
  };

  var chart = new google.visualization.ChartWrapper();
  chart.setChartType('ComboChart');
  chart.setDataTable(dataChart);
  chart.setContainerId('chart_var');
  chart.setOptions(options);
  chart.draw();
}

<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_var"></div>


问:
How to right click on a link and open the link in a new tab using Selenium through Java
I am trying to right click on the Forgotten account? link on the Facebook login page using Selenium but it is not working.

I am trying to send.Keys() after contextClick() but the key press is happening on the page and not on the context menu.

```<code>package keyboardandmouseaction;

import java.awt.AWTException;
import java.util.Iterator;
import java.util.Set;

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Action;
import org.openqa.selenium.interactions.Actions;

public class testcase8 {
    public static void main(String[] args) throws AWTException, InterruptedException {

        System.out.println("Running keyboardandmouseactions > testcase8");

        System.setProperty("webdriver.chrome.driver", "D:\\chromedriver\\chromedriver.exe");
        WebDriver driver=new ChromeDriver();

        driver.manage().window().maximize();
        driver.get("https://www.facebook.com/");

        WebElement link=driver.findElement(By.xpath("//a[contains(text(),\"Forgotten account?\")]"));
        Actions a=new Actions(driver);

        // defective code start
        Action builder=a.moveToElement(link).contextClick(link).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ENTER).build();
        // defective code end
        builder.perform();

        Set<String> windowid =driver.getWindowHandles();
        Iterator<String> itr =windowid.iterator();

        String mainwindow=itr.next();
        String childwindow=itr.next();
        System.out.println("The mainwindow id is "+mainwindow);
        System.out.println("The childwindow id is "+childwindow);
        driver.switchTo().window(childwindow);
        driver.get("http://demo.automationtesting.in/Alerts.html");
        driver.close();

}
}
</code>```

答:
Instead of right click on the link and open the link in a new tab you can press ctrl and click() to open the link in a new tab and finally switch to the new tab using the following Locator Strategies:

Code Block:

```<code>import java.util.Collections;

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

public class Control_Click {

    public static void main(String[] args) {

        System.setProperty("webdriver.chrome.driver","C:\\WebDrivers\\chromedriver.exe");
        ChromeOptions options = new ChromeOptions();
        options.addArguments("--start-maximized");
        options.setExperimentalOption("excludeSwitches", Collections.singletonList("enable-automation"));
        options.setExperimentalOption("useAutomationExtension", false);
        WebDriver driver =  new ChromeDriver(options);
        driver.get("https://www.facebook.com/");
        WebElement forgotPassword = new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.linkText("Forgotten account?")));
        String parentWindow = driver.getWindowHandle();
        System.out.println("The mainwindow handle is "+driver.getWindowHandle());
        new Actions(driver).keyDown(Keys.CONTROL).click(forgotPassword).keyUp(Keys.CONTROL).build().perform();
        new WebDriverWait(driver, 10).until(ExpectedConditions.numberOfWindowsToBe(2));
        for(String window:driver.getWindowHandles()) {
            if(!parentWindow.equalsIgnoreCase(window)) {
                driver.switchTo().window(window);
                System.out.println("The childwindow id is "+driver.getWindowHandle());
                driver.get("http://demo.automationtesting.in/Alerts.html");
            }
        }
    }
}
</code>```

Console Output:

```<code>The mainwindow handle is CDwindow-0753C465F9132427837081CE5AB8C67D
The childwindow id is CDwindow-79C688CE476CA8EC4729EFFDE93C84EA
</code>```

Browser Snapshot:

Reference

You can find a couple of relevant detailed discussions in:

Opening a new tab using Ctrl + click combination in Selenium Webdriver

Best way to keep track and iterate through tabs and windows using WindowHandles using Selenium

Body:
I am trying to right click on the Forgotten account? link on the Facebook login page using Selenium but it is not working.

I am trying to send.Keys() after contextClick() but the key press is happening on the page and not on the context menu.

package keyboardandmouseaction;

import java.awt.AWTException;
import java.util.Iterator;
import java.util.Set;

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Action;
import org.openqa.selenium.interactions.Actions;

public class testcase8 {
    public static void main(String[] args) throws AWTException, InterruptedException {

        System.out.println("Running keyboardandmouseactions > testcase8");

        System.setProperty("webdriver.chrome.driver", "D:\\chromedriver\\chromedriver.exe");
        WebDriver driver=new ChromeDriver();

        driver.manage().window().maximize();
        driver.get("https://www.facebook.com/");

        WebElement link=driver.findElement(By.xpath("//a[contains(text(),\"Forgotten account?\")]"));
        Actions a=new Actions(driver);

        // defective code start
        Action builder=a.moveToElement(link).contextClick(link).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ENTER).build();
        // defective code end
        builder.perform();

        Set<String> windowid =driver.getWindowHandles();
        Iterator<String> itr =windowid.iterator();

        String mainwindow=itr.next();
        String childwindow=itr.next();
        System.out.println("The mainwindow id is "+mainwindow);
        System.out.println("The childwindow id is "+childwindow);
        driver.switchTo().window(childwindow);
        driver.get("http://demo.automationtesting.in/Alerts.html");
        driver.close();

}
}

Body:
Instead of right click on the link and open the link in a new tab you can press ctrl and click() to open the link in a new tab and finally switch to the new tab using the following Locator Strategies:

Code Block:

import java.util.Collections;

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

public class Control_Click {

    public static void main(String[] args) {

        System.setProperty("webdriver.chrome.driver","C:\\WebDrivers\\chromedriver.exe");
        ChromeOptions options = new ChromeOptions();
        options.addArguments("--start-maximized");
        options.setExperimentalOption("excludeSwitches", Collections.singletonList("enable-automation"));
        options.setExperimentalOption("useAutomationExtension", false);
        WebDriver driver =  new ChromeDriver(options);
        driver.get("https://www.facebook.com/");
        WebElement forgotPassword = new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.linkText("Forgotten account?")));
        String parentWindow = driver.getWindowHandle();
        System.out.println("The mainwindow handle is "+driver.getWindowHandle());
        new Actions(driver).keyDown(Keys.CONTROL).click(forgotPassword).keyUp(Keys.CONTROL).build().perform();
        new WebDriverWait(driver, 10).until(ExpectedConditions.numberOfWindowsToBe(2));
        for(String window:driver.getWindowHandles()) {
            if(!parentWindow.equalsIgnoreCase(window)) {
                driver.switchTo().window(window);
                System.out.println("The childwindow id is "+driver.getWindowHandle());
                driver.get("http://demo.automationtesting.in/Alerts.html");
            }
        }
    }
}

Console Output:

The mainwindow handle is CDwindow-0753C465F9132427837081CE5AB8C67D
The childwindow id is CDwindow-79C688CE476CA8EC4729EFFDE93C84EA

Browser Snapshot:

Reference

You can find a couple of relevant detailed discussions in:

Opening a new tab using Ctrl + click combination in Selenium Webdriver

Best way to keep track and iterate through tabs and windows using WindowHandles using Selenium


问:
Testing reducer using Jest receiving state prefixed with "0": {before the actual state}
So, I was working with Jest to test the reducer and I'm getting the following error

Jest error:

Expected: [{"assignedfrom": "", "isLoggedIn": false, "username": ""},
{"assignedfrom": "test"}]

Received: {"0": {"assignedfrom": "", "isLoggedIn": false, "username": ""}, "assignedfrom": "test"}

Note: 0 is being added irrespective of the case/action type

My Reducer:

```<code> switch (action.type) {
       case "login":
                return {
                    ...state,
                username: action.payload.username,
                isLoggedIn:action.payload.isLoggedIn
                }

        case "logout":
            return{
                ...state,
                username:action.payload.username,
                isLoggedIn:action.payload.isLoggedIn
            }

        case "assign":
            return{
                ...state,
                assignedfrom:action.payload.assignedfrom
            }
        case "removeassign":
            return{
                ...state,
                assignedfrom:action.payload.assignedfrom
            }

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

Jest Test:

```<code>it('should return assignedRN ', () => {
        expect(
            loggedReducer(
              [
                {
                  username: '',
                  isLoggedIn: false,  // initial state
                  assignedfrom: ''
                }
              ],
              {
                type: 'assign',
                payload:{
                    assignedfrom:'test' //action
                }
              }
            )
          ).toEqual(
            [

                {
                    username: '',
                    isLoggedIn: false,
                    assignedfrom: ''
                },
            {
            assignedfrom: 'test'
            }
        ])
        })
</code>```

If I change the test like this, it is getting passed:

```<code> it('should return assignedRN ', () => {
        expect(
            loggedReducer(
              [
                {
                  username: '',
                  isLoggedIn: false,
                  assignedfrom: ''
                }
              ],
              {
                type: 'assign',
                payload:{
                    assignedfrom:'test'
                }
              }
            )
          ).toEqual(
            {
            '0':
                {
                    username: '',
                    isLoggedIn: false,
                    assignedfrom: ''
                }
            ,
            assignedfrom: 'test',

            }

          )
        })
</code>```

So, why is that 0 being added? And is there a solution to get the normal state without it being prefixed?

答:
That the test doesn't meet expectations means that there's either a mistake in tested unit or in the test itself.

In this case loggedReducer is misused. It's expected to receive plain object as a state and return plain object, while an array was given. This results in plain object with 0 key and incorrectly processed assignedfrom key.

It should be:

```<code>  expect(
    loggedReducer(
      {
          username: '',
          isLoggedIn: false,
          assignedfrom: ''
      },
      {
        type: 'assign',
        payload:{
            assignedfrom:'test'
        }
      }
    )
  )
  ...
</code>```

Body:
So, I was working with Jest to test the reducer and I'm getting the following error

Jest error:

Expected: [{"assignedfrom": "", "isLoggedIn": false, "username": ""},
{"assignedfrom": "test"}]

Received: {"0": {"assignedfrom": "", "isLoggedIn": false, "username": ""}, "assignedfrom": "test"}

Note: 0 is being added irrespective of the case/action type

My Reducer:

 switch (action.type) {
       case "login":
                return {
                    ...state,
                username: action.payload.username,
                isLoggedIn:action.payload.isLoggedIn
                }

        case "logout":
            return{
                ...state,
                username:action.payload.username,
                isLoggedIn:action.payload.isLoggedIn
            }

        case "assign":
            return{
                ...state,
                assignedfrom:action.payload.assignedfrom
            }
        case "removeassign":
            return{
                ...state,
                assignedfrom:action.payload.assignedfrom
            }

        default:
           return state;
   }

Jest Test:

it('should return assignedRN ', () => {
        expect(
            loggedReducer(
              [
                {
                  username: '',
                  isLoggedIn: false,  // initial state
                  assignedfrom: ''
                }
              ],
              {
                type: 'assign',
                payload:{
                    assignedfrom:'test' //action
                }
              }
            )
          ).toEqual(
            [

                {
                    username: '',
                    isLoggedIn: false,
                    assignedfrom: ''
                },
            {
            assignedfrom: 'test'
            }
        ])
        })

If I change the test like this, it is getting passed:

 it('should return assignedRN ', () => {
        expect(
            loggedReducer(
              [
                {
                  username: '',
                  isLoggedIn: false,
                  assignedfrom: ''
                }
              ],
              {
                type: 'assign',
                payload:{
                    assignedfrom:'test'
                }
              }
            )
          ).toEqual(
            {
            '0':
                {
                    username: '',
                    isLoggedIn: false,
                    assignedfrom: ''
                }
            ,
            assignedfrom: 'test',

            }

          )
        })

So, why is that 0 being added? And is there a solution to get the normal state without it being prefixed?

Body:
That the test doesn't meet expectations means that there's either a mistake in tested unit or in the test itself.

In this case loggedReducer is misused. It's expected to receive plain object as a state and return plain object, while an array was given. This results in plain object with 0 key and incorrectly processed assignedfrom key.

It should be:

  expect(
    loggedReducer(
      {
          username: '',
          isLoggedIn: false,
          assignedfrom: ''
      },
      {
        type: 'assign',
        payload:{
            assignedfrom:'test'
        }
      }
    )
  )
  ...


问:
what is the difference between .done() and .end() function in node and when they shall be used?
I am trying to understand the use case of end() function while writing the API test script in mocha and Chai. Also at the same time, I am confused about whether I shall use the done() function here or not and also what is the exact difference between .end() and .done().

Here's the code:

describe("Suite", () => {
    it('Post Test case', (done) => {
        request('https://reqres.in')
        .post('/api/users')
        .send({
            "name": "morpheus",
            "job": "leader"
        })
        .set('Accept', 'application/json')
        .expect(200,'Content-Type', /json/)
        .then((err,res) => {
            console.log(JSON.stringify(err))
            console.log(JSON.stringify(res.body))
            console.log(JSON.stringify("           "))

        })
        done();
    });
    it('Put Test case', (done) => {
        request('https://reqres.in')
        .put('/api/users/2')
        .send({
            "name": "morpheus",
            "job": "zion residents"
        })
        .expect(200)
        .end((err, res) => {
            console.log(JSON.stringify(err))
            console.log(JSON.stringify(res.body))
            console.log(JSON.stringify("           "))

        })
        done();
    })
})
```

答:
You are mixings things a little bit.

end is a method of the expressjs framework and it ends the server response.

done is a parameter of mocha test function. You call this parameter when you are finished with your asynchronous test to let the mocha know that your asynchronous code is done executing, and it can move on to another test.

And in your case, you need them both.


问:
How to display maximum element of vector<myStruct>?
I have a source code which contains as follows:

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

struct st
{
    int id;
    double d;
};

bool comp(int a, int b)
{
    return (a < b);
}

bool comp2(st &a, st& b) { return a.d < b.d; }

int main()
{
    vector<int> v = { 9, 4, 7, 2, 5, 15, 11, 12, 1, 3, 6 };
    vector<st> vec = {{1, 5.6},{2, 5.7},{3, 4.3}};

    auto max = std::max_element(v.begin(), v.end(), comp);
    cout << "Max element of v: " << *max; // It's working

    auto max2 = std::max_element(vec.begin(), vec.end(), comp2);
    cout << "Max element of vec: " << *max2; // It's not working

    return 0;
}
</code>```

When I try display the maximum value of vector vec I get the following error:

```<code>[Error] cannot bind 'std::basic_ostream<char>' lvalue to 'std::basic_ostream<char>&&'
</code>```

What is the possible solution to the problem?

答:
You did not define the operator << for objects of the type struct st. So the compiler issues an error for this statement

```<code>cout << "Max element of vec: " << *max2;
</code>```

Instead you could write for example

```<code>cout << "Max element of vec: " << max2->id << ", " << max2->d << '\n';
</code>```

Or you cold define the operator << for objects of the type struct st something like

```<code>std::ostream & operator <<( std::ostream &os, const st &obj )
{
    return os << "( " << obj.id << ", " << obj.d << " )";
}
</code>```

Body:
I have a source code which contains as follows:

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;

struct st
{
    int id;
    double d;
};

bool comp(int a, int b)
{
    return (a < b);
}

bool comp2(st &a, st& b) { return a.d < b.d; }

int main()
{
    vector<int> v = { 9, 4, 7, 2, 5, 15, 11, 12, 1, 3, 6 };
    vector<st> vec = {{1, 5.6},{2, 5.7},{3, 4.3}};

    auto max = std::max_element(v.begin(), v.end(), comp);
    cout << "Max element of v: " << *max; // It's working

    auto max2 = std::max_element(vec.begin(), vec.end(), comp2);
    cout << "Max element of vec: " << *max2; // It's not working

    return 0;
}

When I try display the maximum value of vector vec I get the following error:

[Error] cannot bind 'std::basic_ostream<char>' lvalue to 'std::basic_ostream<char>&&'

What is the possible solution to the problem?

Body:
You did not define the operator << for objects of the type struct st. So the compiler issues an error for this statement

cout << "Max element of vec: " << *max2;

Instead you could write for example

cout << "Max element of vec: " << max2->id << ", " << max2->d << '\n';

Or you cold define the operator << for objects of the type struct st something like

std::ostream & operator <<( std::ostream &os, const st &obj )
{
    return os << "( " << obj.id << ", " << obj.d << " )";
}


问:
html send array inside form onsubmit
I'm wondering if it's possible to send array of values for javascript function via onsubmit inside the form.
Let's say I have five inputs in form, and in the form I have:

```<code>onsubmit="return checkvalues(value1, value2, value3, value4, value5)"
</code>```

So the checkvalues() function can validate the inputed values.
But I'm wondering how not to send 5 values but one array, so something like:

```<code>onsubmit="return checkvalues(array(value1, value2, value3, value4, value5))"
</code>```

is it possible so the Javascript function will recognize "someArray" as array?:

```<code>function checkvalues(array someArray) {
    somehow_loop_through_array someArray
}
</code>```

答:
you can send the values like this

```<code>onsubmit="return checkvalues(value1, value2, value3, value4, value5)"
</code>```

and you will be able to receive the values in a function using spread operator

```<code>function checkvalues(...values){
  console.log(values.length);
}
</code>```

OR

you can receive in the below manner also

```<code>function checkvalues(v1,v2,v3,v4){
  console.log(arguments[0]);
}
</code>```

Title: html send array inside form onsubmit

Body:
I'm wondering if it's possible to send array of values for javascript function via onsubmit inside the form.
Let's say I have five inputs in form, and in the form I have:

onsubmit="return checkvalues(value1, value2, value3, value4, value5)"

So the checkvalues() function can validate the inputed values.
But I'm wondering how not to send 5 values but one array, so something like:

onsubmit="return checkvalues(array(value1, value2, value3, value4, value5))"

is it possible so the Javascript function will recognize "someArray" as array?:

function checkvalues(array someArray) {
    somehow_loop_through_array someArray
}

Body:
you can send the values like this

onsubmit="return checkvalues(value1, value2, value3, value4, value5)"

and you will be able to receive the values in a function using spread operator

function checkvalues(...values){
  console.log(values.length);
}

OR

you can receive in the below manner also

function checkvalues(v1,v2,v3,v4){
  console.log(arguments[0]);
}


问:
PHP: Extract string from another
i have some strings (address), all like this:

2 rue lambda, 75018, PARIS

I want to get the postal code, in this exemple "75018". I've been trying different solution, but i'm not familiar with escaped characters , and don't know how to detect coma in the string. Which function should i use to extract the postal code?

答:
you can try this:

```<code>preg_match('/([0-9]{5})/',$string,$match);
echo $match[1];
</code>```

This will work whenever there is an address comma separated or simply space separated

Title: PHP: Extract string from another

Body:
you can try this:

preg_match('/([0-9]{5})/',$string,$match);
echo $match[1];

This will work whenever there is an address comma separated or simply space separated


问:
Send AJAX data to Node.js
Unable to send data to Node.js from my HTML/AJAX, I have variable selectValue which I want to send to my Node server. While making use of data: { selectValue: selectValue} does not help.

index.html

```<code><script type="text/javascript">
    $(document).ready(function(){
    var selectElement = document.getElementById('selectDetails');
    var selectValue='';
        $.ajax({
                 url: "http://localhost:8070/api/route1",
                 type: 'POST',
                 dataType:'json',

                 success: function(res) {
                     console.log(res);
                     console.log(res.content);
                     $.each(res.content, function(key,value) {
                        console.log(value);
                        selectElement.options[selectElement.options.length] = new Option(value.hostname+":"+value.port);
                    });
                    $("#myButton").click(function(){
                        var selectValue = document.getElementById("selectDetails").value;
                        console.log(selectValue);
                    });
                },
                data: { selectValue: selectValue}
            });
        });
</script>
</code>```

app.js

```<code>router.post('/route1', function(req, res){
    var selValue= req.body.selectValue;
    console.log("Select Value"+selValue);
});
</code>```

console.log("Select Value"+selValue); give an undefined value. How do I send the value of selectValue to my node server.

答:
This should be moved out of of the post / XHR callback:

```<code>$("#myButton").click(function(){
    var selectValue = document.getElementById("selectDetails").value;
    console.log(selectValue);
});
</code>```

Now you are sending empty string ''; to the server, and editing the value of another variable called 'selectValue' inside call handler. The inner selectValue variable shadows the original value, but the orginal value will never be changed.

something like this could work

```<code><script type="text/javascript">
    $(document).ready(function(){
    var selectElement = document.getElementById('selectDetails');
    var selectValue='foo';

     $("#myButton").click(function(){
         // NO VAR HERE, TO NOT SHADOW THE OUTER VARIABLE
         selectValue = document.getElementById("selectDetails").value;
         console.log('1', selectValue);
         $.ajax({
            url: "http://localhost:8070/api/route1",
            type: 'POST',
            dataType:'json',
            data: {selectValue: selectValue},
            success: function(res) {
               console.log(res);
              console.log(res.content);
            }
         });
     });

</script>

</code>```

Title: Send AJAX data to Node.js

Body:
Unable to send data to Node.js from my HTML/AJAX, I have variable selectValue which I want to send to my Node server. While making use of data: { selectValue: selectValue} does not help.

index.html

app.js

router.post('/route1', function(req, res){
    var selValue= req.body.selectValue;
    console.log("Select Value"+selValue);
});

console.log("Select Value"+selValue); give an undefined value. How do I send the value of selectValue to my node server.

Body:
This should be moved out of of the post / XHR callback:

$("#myButton").click(function(){
    var selectValue = document.getElementById("selectDetails").value;
    console.log(selectValue);
});

Now you are sending empty string ''; to the server, and editing the value of another variable called 'selectValue' inside call handler. The inner selectValue variable shadows the original value, but the orginal value will never be changed.

something like this could work

<script type="text/javascript">
    $(document).ready(function(){
    var selectElement = document.getElementById('selectDetails');
    var selectValue='foo';

     $("#myButton").click(function(){
         // NO VAR HERE, TO NOT SHADOW THE OUTER VARIABLE
         selectValue = document.getElementById("selectDetails").value;
         console.log('1', selectValue);
         $.ajax({
            url: "http://localhost:8070/api/route1",
            type: 'POST',
            dataType:'json',
            data: {selectValue: selectValue},
            success: function(res) {
               console.log(res);
              console.log(res.content);
            }
         });
     });

</script>


问:
fs.open does not open desired file in nodejs
I am just a beginner to nodejs and I came across the fs module. I tried to write a few lines of code.

```<code>var fs = require('fs');

// Open file demo.txt in read mode
fs.open('/users/Upwn/desktop/ashok_pant.txt', 'r+', function (err, f) {
  if(err) throw err;
   console.log('Opened!');
});
</code>```

The output was "Opened!" but nothing was opened from my local file system. What may be wrong with this?

答:
If you want to open the file using the default OS application linked to the filetype, the following answer from Philipp Kief might be what you're looking for.

You can use the open module:

```<code>npm install --save open
</code>```

and then call it in your Node.js file:

const open = require('open');
open('my-file.txt');
```

This module already contains the logic to detect the operating system and it runs the > default program that is associated to this file type by your system.

--- https://stackoverflow.com/a/61891139/1487756

Body:
I am just a beginner to nodejs and I came across the fs module. I tried to write a few lines of code.

var fs = require('fs');

// Open file demo.txt in read mode
fs.open('/users/Upwn/desktop/ashok_pant.txt', 'r+', function (err, f) {
  if(err) throw err;
   console.log('Opened!');
});

The output was "Opened!" but nothing was opened from my local file system. What may be wrong with this?

Body:
If you want to open the file using the default OS application linked to the filetype, the following answer from Philipp Kief might be what you're looking for.

You can use the open module:

npm install --save open

and then call it in your Node.js file:

const open = require('open');
open('my-file.txt');

This module already contains the logic to detect the operating system and it runs the > default program that is associated to this file type by your system.

--- https://stackoverflow.com/a/61891139/1487756


问:
What is meant by Net IO in JProfiler?
What is meant by Net IO time in JProfiler?

JProfilerguide says following but I dont know what exactly it means? Is the time spent on network or waiting on network?  What to fix if the net io time is huge?

During network operations, many calls in the Java standard libraries
  can  block because they're waiting for more data. This kind of
  blocking is called "Net I/O" in JProfiler. JProfiler knows the list of
  methods in the JRE that lead to blocked net I/O and instruments them
  at load time.

答: "Net I/O" state that keeps track of the times when a thread is waiting for network data. This is important for analyzing servers and database drivers, because that time can be relevant for performance analysis, such as for investigating slow SQL queries.</p>

Title: What is meant by Net IO in JProfiler?


答:
As in your code snippet, it's an array of objects. So you can use the map function to iterate it.</p>

```<code>object.map((item) => ({ ability: item.ability, value: item.value }));
</code>```

Title: iterate over array of objects and fetch only specific key to form a new array of object in react js

Body:
I have below object. I want to iterate over it and need to fetch only key's values of ability and value key.

var object = [{
    ability: "Strong",
    name: "STRENGTH",
    value: "customer has 10 properties",
    type: "MultiChoice"
  },
  {
    ability: "Good",
    name: "STRENGTH",
    value: "customer has 5 properties",
    type: "MultiChoice"
  },
  {
    ability: "average",
    name: "STRENGTH",
    value: "customer has 3 properties",
    type: "MultiChoice"
  }
]

So my expected output should be like below.

[{
    ability: "Strong"
    value: "customer has 10 properties"
  },
  {
    ability: "Good"
    value: "customer has 5 properties"
  },
  {
    ability: "average"
    value: "customer has 3 properties"
  }
]

Then I again want to use above object to iterate over it and bind its values to dropdown. So my drop-down will display "value" to end user and DB will have "ability". I am trying below code snippet but its not giving expected output. Something I am doing wrong here.

var object = [{
    ability: "Strong",
    name: "STRENGTH",
    value: "customer has 10 properties",
    type: "MultiChoice"
  },
  {
    ability: "Good",
    name: "STRENGTH",
    value: "customer has 5 properties",
    type: "MultiChoice"
  },
  {
    ability: "average",
    name: "STRENGTH",
    value: "customer has 3 properties",
    type: "MultiChoice"
  }
]

let multiChoiceResult = [];
let ability, value
Object.entries(object).map(([key, value]) => {
  ability = value.ability;
  value = value.value;
  multiChoiceResult.push(ability, value);
});
console.log(multiChoiceResult);

Body:
As in your code snippet, it's an array of objects. So you can use the map function to iterate it.

object.map((item) => ({ ability: item.ability, value: item.value }));


问:
Creating CSize wrapper from QSize
I am trying to create a wrapper for QSize class of Qt.
Here is the code snippet.

```<code>class CSize
{
private:
    QSize m_szSize;

public:
    int cx,cy;

CSize();
CSize(int cx,int cy)
{

}
CSize(const CSize& obj)
{
    m_szSize.setWidth(obj.cx);
    m_szSize.setHeight(obj.cy);
}
};
</code>```

But when following situation arrives,

```<code>CSize sz;
sz.cx = 10;
sz.cy = 20;
</code>```

How can i update the values of m_szSize.
Someone please help me out.

答:
You need to put cx and cy as private, and add accessors for cx and cy:

```<code>void setCx(int p_cx) { cx = p_cx; m_szSize.setWidth(cx); }
void setCy(int p_cy) { cy = p_cy; m_szSize.setHeight(cy); }
int getCx() const { return cx; }
int getCy() const { return cy; }
</code>```

Title: Creating CSize wrapper from QSize

Body:
I am trying to create a wrapper for QSize class of Qt.
Here is the code snippet.

class CSize
{
private:
    QSize m_szSize;

public:
    int cx,cy;

CSize();
CSize(int cx,int cy)
{

}
CSize(const CSize& obj)
{
    m_szSize.setWidth(obj.cx);
    m_szSize.setHeight(obj.cy);
}
};

But when following situation arrives,

CSize sz;
sz.cx = 10;
sz.cy = 20;

How can i update the values of m_szSize.
Someone please help me out.

Body:
You need to put cx and cy as private, and add accessors for cx and cy:

void setCx(int p_cx) { cx = p_cx; m_szSize.setWidth(cx); }
void setCy(int p_cy) { cy = p_cy; m_szSize.setHeight(cy); }
int getCx() const { return cx; }
int getCy() const { return cy; }


问:
Check if navigation.navigate is called in react native testing
I've been using 'react-test-renderer' for testing react-native, Mostly on it's functions. Lately I've found out that there is a testing library for react-native which is @testing-library/react-native. What I wanted to do is to check if navigation.navigate or alert has been called in a function. I don't know which of these libraries can achieve that and how.</p>

```<code>onSubmitPress = () => {
  if (true) {
    this.props.navigation.navigate('MainPage');
  else {
     showAlert( "Not Allowed);
  }
</code>```

答:
You can use 'react-test-renderer':

like this:

const fakeNavigation = {
  navigate: jest.fn(),

};
const tree = renderer.create(

        <YourComponent navigation={fakeNavigation}  />

    );
```

<p>after that you can use jest <code>expect</code> function to test if mock <code>navigation.navigate</code> is called someThing like this:</p>

<pre class="lang-js prettyprint-override"><code>const instance = tree.getInstance();
instance.onSubmit();
expect(fakeNavigation.navigate).toBeCalledWith('MainPage')
</code>```

for react-native-testing-library it's a bit different as you test mostly what user sees depending of the behavior of your component.

Basically you look for your button that calls onSubmit and then use fireEvent from react-native-testing-library to press it, after that you expect the text of your alert to be shown in screen or not.

If you have a button like this in your component=

<TouchableOpacity onPress={onSubmit}>
 <Text>Submit</Text>
</TouchableOpacity>
```

<p>You can test the behavior of you function like this:</p>

<pre class="lang-js prettyprint-override"><code>const {getByText} = render(<YourComponent/>)
let buttonText = getByText('Submit');
fireEvent(buttonText.parent, 'press'); //parent to get to TouchableOpacity
alertText = getByText('Not Allowed');
expect(alertText).toBeDefined();
</code>```

Body:
I've been using 'react-test-renderer' for testing react-native, Mostly on it's functions. Lately I've found out that there is a testing library for react-native which is @testing-library/react-native. What I wanted to do is to check if navigation.navigate or alert has been called in a function. I don't know which of these libraries can achieve that and how.

onSubmitPress = () => {
  if (true) {
    this.props.navigation.navigate('MainPage');
  else {
     showAlert( "Not Allowed);
  }

Body:
You can use 'react-test-renderer':

like this:

const fakeNavigation = {
  navigate: jest.fn(),

};
const tree = renderer.create(

        <YourComponent navigation={fakeNavigation}  />

    );

after that you can use jest expect function to test if mock navigation.navigate is called someThing like this:

const instance = tree.getInstance();
instance.onSubmit();
expect(fakeNavigation.navigate).toBeCalledWith('MainPage')

for react-native-testing-library it's a bit different as you test mostly what user sees depending of the behavior of your component.

Basically you look for your button that calls onSubmit and then use fireEvent from react-native-testing-library to press it, after that you expect the text of your alert to be shown in screen or not.

If you have a button like this in your component=

<TouchableOpacity onPress={onSubmit}>
 <Text>Submit</Text>
</TouchableOpacity>

You can test the behavior of you function like this:

const {getByText} = render(<YourComponent/>)
let buttonText = getByText('Submit');
fireEvent(buttonText.parent, 'press'); //parent to get to TouchableOpacity
alertText = getByText('Not Allowed');
expect(alertText).toBeDefined();


问:
Lost references in Visual Studio 2017 solution
I've been working on a project with a coworker and we're using Visual Studio 2017 as IDE and also Git to push the versions to VS repository. We had a few problems and decided to start a new project in Visual Studio with the content we already had.

The weird thing is: when cloned the repository to my computer and synched, some of the references were lost. A yellow triangle appears next to the lost references icons in Solution Explorer, and it doesn't have a path set like the ones that work. Also, inside Source > Repos, the project folder has all files, including the ones that are missing. I tried deleting the project and cloning it again, tried to download only the .zip file and starting the project offline, and also running VS 2017 as administrator (it appears this solved similar problems for others before) and nothing worked. My coworker (who pushed the project to the repo in first place) can compile normally and is not facing this reference problem.

Has anyone ever experienced this issue?

答: In my case after a merge with the master branch, I had conflicts in the project file (.csproj). When resolving the issue VS2019 automatically had unloaded the project file where those conflicts were and I didn't notice. A check for that might save time for someone.</p>


问:
Pandas: extract data from df to a new df based on condition
I have the following df1:

```<code>Person  Day1  Day2  Day3
1       2     1     1
2       2     0     7
3       4     1     2
</code>```

And then another df2:

```<code>Person  Day1  Day2  Day3
1       a     b     b
2       a     c     a
3       c     b     c
</code>```

So these two dataframes have the same index and columns. How can I select elements of df1 that only have "c" in df2?

The result should be values from df1 when the condition is met, and 0 otherwise:

```<code>Person  Day1  Day2  Day3
1       0     0     0
2       0     0     0
3       4     0     2
</code>```

答:
If first column is index use DataFrame.where:

```<code>df = df1.where(df2.eq('c'), 0)
print (df)
        Day1  Day2  Day3
Person
1          0     0     0
2          0     0     0
3          4     0     2
</code>```

If first column is not index, one possible idea is select all columns without first and assign back:

```<code>df1.iloc[:, 1:]= df1.iloc[:, 1:].where(df2.iloc[:, 1:].eq('c'), 0)
print (df1)
   Person  Day1  Day2  Day3
0       1     0     0     0
1       2     0     0     0
2       3     4     0     2
</code>```

Or:

```<code>df = df1.set_index('Person').where(df2.set_index('Person').eq('c'), 0).reset_index()
print (df)
   Person  Day1  Day2  Day3
0       1     0     0     0
1       2     0     0     0
2       3     4     0     2
</code>```

Body:
I have the following df1:

Person  Day1  Day2  Day3
1       2     1     1
2       2     0     7
3       4     1     2

And then another df2:

Person  Day1  Day2  Day3
1       a     b     b
2       a     c     a
3       c     b     c

So these two dataframes have the same index and columns. How can I select elements of df1 that only have "c" in df2?

The result should be values from df1 when the condition is met, and 0 otherwise:

Person  Day1  Day2  Day3
1       0     0     0
2       0     0     0
3       4     0     2

Body:
If first column is index use DataFrame.where:

df = df1.where(df2.eq('c'), 0)
print (df)
        Day1  Day2  Day3
Person
1          0     0     0
2          0     0     0
3          4     0     2

If first column is not index, one possible idea is select all columns without first and assign back:

df1.iloc[:, 1:]= df1.iloc[:, 1:].where(df2.iloc[:, 1:].eq('c'), 0)
print (df1)
   Person  Day1  Day2  Day3
0       1     0     0     0
1       2     0     0     0
2       3     4     0     2

Or:

df = df1.set_index('Person').where(df2.set_index('Person').eq('c'), 0).reset_index()
print (df)
   Person  Day1  Day2  Day3
0       1     0     0     0
1       2     0     0     0
2       3     4     0     2


问:
Reading XML and converting it to JSON Smartly
I have code which does the formatting and convert the XML to JSON but it is vary big and lethargic. I need to pick some 50 elements out of XML and format JSON using these elements.so many part is repeating but with different elements.
Below is the code:-

private String createBrokeredMessage(String payload) {
    String message = "";
    String Ver = "";
    String ID = "";
            |
            |
    String Rec = "";
    String default1 = "[]";

    try {
        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        InputSource src = new InputSource();
        src.setCharacterStream(new StringReader(payload));

        Document doc = builder.parse(src);
        NodeList n1 = doc.getElementsByTagName("Ver");
        if (n1.getLength() > 0) {
            Ver = n1.item(0).getTextContent();
            if(Ver == "") {
                Ver = default1;
            }
            else {
                Ver = "\""+Ver+"\"";
            }
        }

        NodeList n2 = doc.getElementsByTagName("ID");
        if (n2.getLength() > 0) {
            ID = n2.item(0).getTextContent();
            if(ID == "") {
                ID = default1;
            }
            else {
                ID = "\""+ID+"\"";
            }
        }
        //|
        //|
        //|
        //|
        //|
        //|

        NodeList n49 = doc.getElementsByTagName("Rec");
        if (n49.getLength() > 0) {
            Rec = n49.item(0).getTextContent();
            if(Rec == "") {
                Rec = default1;
            }
            else {
                Rec = "\""+Rec+"\"";
            }
        }

        message = "{\"Envelope\":{\"Ver\":"+Ver+",\"ID\":"+ID+-------------------",\"Rec\":"+Rec+"}]}";
        System.out.println("Created message with ID" + message);
    } catch (Exception e){
            e.printStackTrace();
    }

    return message;
}
```

<p>Example XML:-</p>

```<?xml Version="1.0" encoding="UTF-8" standalone="no"?>
<Data xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <Envelope>
    <Ver>1.13</Ver>
    <ID>SAO</ID>
    <Rec>men</Rec>
    <TransactionID>0987714805168</TransactionID>
  </Envelope>
  124
  <City></City>
  <CompCodes>
    <CompCode>US</CompCode>
    <Vend>13</Vend>
  </CompCodes>
  <BankData>
    123
    <BankAcctNum>231</BankAcctNum>
  </BankData>
  <BankData>
    124
    <BankAcctNum>431</BankAcctNum>
  </BankData>
</Data>
```

<p>Output JSON:-</p>

```{
   "Envelope": {
      "Ver": "1.13",
      "ID": "SAO",
      "Rec": "men",
      "TransactionID": "0987714805168"
   },
   "Code": "124",
   "City": [],
   "CompCodes": [{
      "CompCode": "US",
      "Vend": "13"
   }],
   "BankData": [
      {
         "Code": "123",
         "BankAcctNum": "231"
      },
      {
         "Code": "124",
         "BankAcctNum": "431"
      }
   ]
}
```

Any help will be appreciated!

答:
We can convert XML to JSON array using org.json.XML class, this provides a static method, XML.toJSONObject() to convert XML to JSON array.

Syntax

public static JSONObject toJSONObject(java.lang.String string) throws JSONException

In the below example, converting XML to JSON array

```<code>   import org.json.*;
   public class ConvertXMLToJSONArrayTest {
   public static String xmlString= "<?xml version=\"1.0\" ?><root><test       attrib=\"jsontext1\">tutorialspoint</test><test attrib=\"jsontext2\">tutorix</test></root>";
   public static void main(String[] args) {
      try {
       JSONObject json = XML.toJSONObject(xmlString); // converts xml to json
       String jsonPrettyPrintString = json.toString(4); // json pretty print
       System.out.println(jsonPrettyPrintString);
      } catch(JSONException je) {
         System.out.println(je.toString());
      }
    }
 }
</code>```

In your case the code will be...

```<code>import org.json.*;
public class ConvertXMLToJSONArrayTest {
public static String xmlString= "<?xml Version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>" +
    "<Data xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">" +
    "<Envelope><Ver>1.13</Ver><ID>SAO</ID><Rec>men</Rec><TransactionID>0987714805168</TransactionID>"+
    "</Envelope><Code>124</Code><City></City><CompCodes><CompCode>US</CompCode><Vend>13</Vend></CompCodes>"+
    "<BankData><Code>123</Code><BankAcctNum>231</BankAcctNum></BankData><BankData><Code>124</Code><BankAcctNum>431</BankAcctNum>"+
    "</BankData></Data>";
    public static void main(String[] args) {
  try {
     JSONObject json = XML.toJSONObject(xmlString); // converts xml to json
     String jsonPrettyPrintString = json.toString(4); // json pretty print
     System.out.println(jsonPrettyPrintString);
  } catch(JSONException je) {
     System.out.println(je.toString());
  }
  }
 }
</code>```

Output :

```<code>{"Data": {
"CompCodes": {
    "CompCode": "US",
    "Vend": 13
},
"BankData": [
    {
        "BankAcctNum": 231,
        "Code": 123
    },
    {
        "BankAcctNum": 431,
        "Code": 124
    }
],
"xmlns:xsi": "http://www.w3.org/2001/XMLSchema-instance",
"City": "",
"Envelope": {
    "Rec": "men",
    "Ver": 1.13,
    "ID": "SAO",
    "TransactionID": "0987714805168"
},
"Code": 124
}}
</code>```

Body:
I have code which does the formatting and convert the XML to JSON but it is vary big and lethargic. I need to pick some 50 elements out of XML and format JSON using these elements.so many part is repeating but with different elements.
Below is the code:-

private String createBrokeredMessage(String payload) {
    String message = "";
    String Ver = "";
    String ID = "";
            |
            |
    String Rec = "";
    String default1 = "[]";

    try {
        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        InputSource src = new InputSource();
        src.setCharacterStream(new StringReader(payload));

        Document doc = builder.parse(src);
        NodeList n1 = doc.getElementsByTagName("Ver");
        if (n1.getLength() > 0) {
            Ver = n1.item(0).getTextContent();
            if(Ver == "") {
                Ver = default1;
            }
            else {
                Ver = "\""+Ver+"\"";
            }
        }

        NodeList n2 = doc.getElementsByTagName("ID");
        if (n2.getLength() > 0) {
            ID = n2.item(0).getTextContent();
            if(ID == "") {
                ID = default1;
            }
            else {
                ID = "\""+ID+"\"";
            }
        }
        //|
        //|
        //|
        //|
        //|
        //|

        NodeList n49 = doc.getElementsByTagName("Rec");
        if (n49.getLength() > 0) {
            Rec = n49.item(0).getTextContent();
            if(Rec == "") {
                Rec = default1;
            }
            else {
                Rec = "\""+Rec+"\"";
            }
        }

        message = "{\"Envelope\":{\"Ver\":"+Ver+",\"ID\":"+ID+-------------------",\"Rec\":"+Rec+"}]}";
        System.out.println("Created message with ID" + message);
    } catch (Exception e){
            e.printStackTrace();
    }

    return message;
}

Example XML:-

<?xml Version="1.0" encoding="UTF-8" standalone="no"?>
<Data xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <Envelope>
    <Ver>1.13</Ver>
    <ID>SAO</ID>
    <Rec>men</Rec>
    <TransactionID>0987714805168</TransactionID>
  </Envelope>
  124
  <City></City>
  <CompCodes>
    <CompCode>US</CompCode>
    <Vend>13</Vend>
  </CompCodes>
  <BankData>
    123
    <BankAcctNum>231</BankAcctNum>
  </BankData>
  <BankData>
    124
    <BankAcctNum>431</BankAcctNum>
  </BankData>
</Data>

Output JSON:-

{
   "Envelope": {
      "Ver": "1.13",
      "ID": "SAO",
      "Rec": "men",
      "TransactionID": "0987714805168"
   },
   "Code": "124",
   "City": [],
   "CompCodes": [{
      "CompCode": "US",
      "Vend": "13"
   }],
   "BankData": [
      {
         "Code": "123",
         "BankAcctNum": "231"
      },
      {
         "Code": "124",
         "BankAcctNum": "431"
      }
   ]
}

Any help will be appreciated!

Body:
We can convert XML to JSON array using org.json.XML class, this provides a static method, XML.toJSONObject() to convert XML to JSON array.

Syntax

public static JSONObject toJSONObject(java.lang.String string) throws JSONException

In the below example, converting XML to JSON array

   import org.json.*;
   public class ConvertXMLToJSONArrayTest {
   public static String xmlString= "<?xml version=\"1.0\" ?><root><test       attrib=\"jsontext1\">tutorialspoint</test><test attrib=\"jsontext2\">tutorix</test></root>";
   public static void main(String[] args) {
      try {
       JSONObject json = XML.toJSONObject(xmlString); // converts xml to json
       String jsonPrettyPrintString = json.toString(4); // json pretty print
       System.out.println(jsonPrettyPrintString);
      } catch(JSONException je) {
         System.out.println(je.toString());
      }
    }
 }

In your case the code will be...

import org.json.*;
public class ConvertXMLToJSONArrayTest {
public static String xmlString= "<?xml Version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>" +
    "<Data xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">" +
    "<Envelope><Ver>1.13</Ver><ID>SAO</ID><Rec>men</Rec><TransactionID>0987714805168</TransactionID>"+
    "</Envelope><Code>124</Code><City></City><CompCodes><CompCode>US</CompCode><Vend>13</Vend></CompCodes>"+
    "<BankData><Code>123</Code><BankAcctNum>231</BankAcctNum></BankData><BankData><Code>124</Code><BankAcctNum>431</BankAcctNum>"+
    "</BankData></Data>";
    public static void main(String[] args) {
  try {
     JSONObject json = XML.toJSONObject(xmlString); // converts xml to json
     String jsonPrettyPrintString = json.toString(4); // json pretty print
     System.out.println(jsonPrettyPrintString);
  } catch(JSONException je) {
     System.out.println(je.toString());
  }
  }
 }

Output :

{"Data": {
"CompCodes": {
    "CompCode": "US",
    "Vend": 13
},
"BankData": [
    {
        "BankAcctNum": 231,
        "Code": 123
    },
    {
        "BankAcctNum": 431,
        "Code": 124
    }
],
"xmlns:xsi": "http://www.w3.org/2001/XMLSchema-instance",
"City": "",
"Envelope": {
    "Rec": "men",
    "Ver": 1.13,
    "ID": "SAO",
    "TransactionID": "0987714805168"
},
"Code": 124
}}


问:
Cannot read property 'series' of undefined HighCharts
Want to fetch complete data with chart type and all but I get this error Cannot read property 'series' of undefined.

here is the component.ts and service file

```<code>const sampleData: Overview[] = [
      {
        chart: {
          type: 'column',
        },
        title: {
          text: 'Total Predected Revenue Vs Actual Revenue',
        },
        xAxis: {
          categories: [
            '2010',
            '2011',
            '2012',
            '2013',
            '2014',
            '2015',
            '2016',
            '2017',
          ],
          crosshair: true,
        },
        yAxis: {
          min: 0,
        },
        series: [
          {
            name: 'Predected',
            data: [14, 17, 9, 10, 6, 19, 6, 8],
          },
          {
            name: 'Actual',
            data: [65, 74, 44, 66, 9, 23, 36, 51],
          },
        ],
      }
    ];
</code>```

and this is .ts file

```<code>data: Overview[] = [];

private onLoaded(state: OverviewLoadedState) {
    const me = this;
    me.data = state.data;
    me.error = false;
    me.loading = false;
    console.log(me.data)
  }
</code>```

and here is the .html

```<code><div *ngIf="data">
        <highcharts-chart style="width: 100%; display: block" [Highcharts]="Highcharts" [options]="data"
            [(update)]="updateDemo" [runOutsideAngular]=true>
        </highcharts-chart>
    </div>
</code>```

Help me to slove this error.

答:
Probelm is in your if condition in template, change it to :-

```<code><div *ngIf="data?.length > 0">
        <highcharts-chart style="width: 100%; display: block" [Highcharts]="Highcharts" [options]="data"
            [(update)]="updateDemo" [runOutsideAngular]=true>
        </highcharts-chart>
    </div>
</code>```

because your condition would have also satisfied in case of blank array.

Body:
Want to fetch complete data with chart type and all but I get this error Cannot read property 'series' of undefined.

here is the component.ts and service file

const sampleData: Overview[] = [
      {
        chart: {
          type: 'column',
        },
        title: {
          text: 'Total Predected Revenue Vs Actual Revenue',
        },
        xAxis: {
          categories: [
            '2010',
            '2011',
            '2012',
            '2013',
            '2014',
            '2015',
            '2016',
            '2017',
          ],
          crosshair: true,
        },
        yAxis: {
          min: 0,
        },
        series: [
          {
            name: 'Predected',
            data: [14, 17, 9, 10, 6, 19, 6, 8],
          },
          {
            name: 'Actual',
            data: [65, 74, 44, 66, 9, 23, 36, 51],
          },
        ],
      }
    ];

and this is .ts file

data: Overview[] = [];

private onLoaded(state: OverviewLoadedState) {
    const me = this;
    me.data = state.data;
    me.error = false;
    me.loading = false;
    console.log(me.data)
  }

and here is the .html

        <highcharts-chart style="width: 100%; display: block" [Highcharts]="Highcharts" [options]="data"
            [(update)]="updateDemo" [runOutsideAngular]=true>
        </highcharts-chart>

Help me to slove this error.

Body:
Probelm is in your if condition in template, change it to :-

<div *ngIf="data?.length > 0">
        <highcharts-chart style="width: 100%; display: block" [Highcharts]="Highcharts" [options]="data"
            [(update)]="updateDemo" [runOutsideAngular]=true>
        </highcharts-chart>
    </div>

because your condition would have also satisfied in case of blank array.