问:
How can I parse the text from one countryName to another countryName in R?
I'm just having a really hard time figuring this out. Let's go straight to the data.

```<code>library(countrycode)
countries <- codelist$country.name.en  #list of countries from the library

text <- "(France) Mr. Tom(CEO) from France is getting a new car. The car is a Toyota. His wife will get a Nissan. (Spain) No information available. (Chad) Mr. Smith (from N'Djamena) bought a new house. It's very nice."
</code>```

I'd want to create a list of the parsed text (eg. from "(France)" to "Nissan.") for all three countries. The actual text is 30 pages long and each (countryName) is followed by several paragraphs of text.

All the countryNames are in parentheses but there might be other non-country parentheses in the text or countryNames without parentheses. But the general pattern is that each segment I want to parse starts with (countryName1) and ends with (countryName2)

```<code>Output:
[[1]]
[1] "(France) Mr. Tom(CEO) from France is getting a new car. The car is a Toyota. His wife will get a Nissan."

[[2]]
[1] "(Spain) No information available."

[[3]]
[1] "(Chad) Mr.Smith (from N'Djamena) bought a new house. It's very nice."

</code>```

答:
If all the countries in the 'text' matches with the reference vector, we may paste the reference vector into a single string to split the string just before the country match

```<code>as.list(strsplit(text, sprintf('(?<=\\s)(?=(%s))',
    paste(paste0("\\(", countries), collapse = "|")), perl = TRUE)[[1]])
</code>```

-output

```<code>[[1]]
[1] "(France) Mr. Tom(CEO) from France is getting a new car. The car is a Toyota. His wife will get a Nissan. "

[[2]]
[1] "(Spain) No information available. "

[[3]]
[1] "(Chad) Mr. Smith (from N'Djamena) bought a new house. It's very nice."
</code>```

Body:
I'm just having a really hard time figuring this out. Let's go straight to the data.

library(countrycode)
countries <- codelist$country.name.en  #list of countries from the library

text <- "(France) Mr. Tom(CEO) from France is getting a new car. The car is a Toyota. His wife will get a Nissan. (Spain) No information available. (Chad) Mr. Smith (from N'Djamena) bought a new house. It's very nice."

I'd want to create a list of the parsed text (eg. from "(France)" to "Nissan.") for all three countries. The actual text is 30 pages long and each (countryName) is followed by several paragraphs of text.

All the countryNames are in parentheses but there might be other non-country parentheses in the text or countryNames without parentheses. But the general pattern is that each segment I want to parse starts with (countryName1) and ends with (countryName2)

Output:
[[1]]
[1] "(France) Mr. Tom(CEO) from France is getting a new car. The car is a Toyota. His wife will get a Nissan."

[[2]]
[1] "(Spain) No information available."

[[3]]
[1] "(Chad) Mr.Smith (from N'Djamena) bought a new house. It's very nice."

Body:
If all the countries in the 'text' matches with the reference vector, we may paste the reference vector into a single string to split the string just before the country match

as.list(strsplit(text, sprintf('(?<=\\s)(?=(%s))',
    paste(paste0("\\(", countries), collapse = "|")), perl = TRUE)[[1]])

-output

[[1]]
[1] "(France) Mr. Tom(CEO) from France is getting a new car. The car is a Toyota. His wife will get a Nissan. "

[[2]]
[1] "(Spain) No information available. "

[[3]]
[1] "(Chad) Mr. Smith (from N'Djamena) bought a new house. It's very nice."


来源: stackexchange

问:
Keep the list menu on one line and prevent new line
I am trying to keep this menu on one line, when the browser gets resized, some of them make a new line and go under the first line.
Here is my code:

.menu{
  list-style-type: none;
  margin: 0;
  padding: 0;
  overflow: hidden;
  background-color: #333333;

}
.item{
  float: left;
}
.item a{
  display: inline-block;
  color: white;
  text-align: center;
  padding: 16px 100px 16px 100px;
  text-decoration: none;
  white-space: nowrap;

}
.item a:hover{
  background-color: #111111;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>
 <header>
 <ul class="menu">
            <li class="item">Home</li>
            <li class="item">Popular Categories</li>
            <li class="item">Today's Special</li>
            <li class="item">Locations</li>
        </ul>
</header></code>```

答:
Just use display: flex. I recommend you to have a read here https://css-tricks.com/snippets/css/a-guide-to-flexbox/

.menu{
  display: flex;
  list-style: none;
}
.item a{
  padding: 20px;
  text-decoration: none;
  color: #000;
}
.item a:hover{
  background-color: #000;
  color: #fff;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>
 <header>
 <ul class="menu">
            <li class="item">Home</li>
            <li class="item">Popular Categories</li>
            <li class="item">Today's Special</li>
            <li class="item">Locations</li>
        </ul>
</header></code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to keep this menu on one line, when the browser gets resized, some of them make a new line and go under the first line.
Here is my code:

.menu{
  list-style-type: none;
  margin: 0;
  padding: 0;
  overflow: hidden;
  background-color: #333333;

}
.item{
  float: left;
}
.item a{
  display: inline-block;
  color: white;
  text-align: center;
  padding: 16px 100px 16px 100px;
  text-decoration: none;
  white-space: nowrap;

}
.item a:hover{
  background-color: #111111;
}

Home

Popular Categories

Today's Special

Locations

Body:
Just use display: flex. I recommend you to have a read here https://css-tricks.com/snippets/css/a-guide-to-flexbox/

.menu{
  display: flex;
  list-style: none;
}
.item a{
  padding: 20px;
  text-decoration: none;
  color: #000;
}
.item a:hover{
  background-color: #000;
  color: #fff;
}

 <header>
 <ul class="menu">
            <li class="item"><a href="#">Home</a></li>
            <li class="item"><a href="#">Popular Categories</a></li>
            <li class="item"><a href="#">Today's Special</a></li>
            <li class="item"><a href="#">Locations</a></li>
        </ul>
</header>


问:
How to send GET requests via python over different IPs?
I am currently trying to gather data from an exchange for deep learning. The issue is I need the data with a high resolution (second intervals), therefore I am creating a lot of GET requests for each currency. But I reach fast the limits of the API really.

I would like to know if there is a possibility to route the GET request over a public proxy server to claim to have a different IP-address to make as many requests as possible with a Raspberry PI.

答:
This is just an more detailed version of the verified answers

How To Download?

```<code>pip3 install proxy-requests
</code>```

Example for Basic GET Request

```<code>from proxy_requests import ProxyRequests
r = ProxyRequests("https://dog.ceo/api/breeds/image/random")
r.get()
</code>```

Example for GET Request with Headers

```<code>from proxy_requests import ProxyRequests
h = {'User-Agent': 'NCSA Mosaic/3.0 (Windows 95)'}
r = ProxyRequests('url here')
r.set_headers(h)
r.get_with_headers()
</code>```

Example for POST Request

```<code>from proxy_requests import ProxyRequests
r = ProxyRequests('url here')
r.post({'key1': 'value1', 'key2': 'value2'})
</code>```

Example for POST Request with Headers

```<code>r = ProxyRequests('url here')
r.set_headers({'name': 'rootVIII', 'secret_message': '7Yufs9KIfj33d'})
r.post_with_headers({'key1': 'value1', 'key2': 'value2'})
</code>```

Example for Request with Authentication

```<code>r = ProxyRequestsBasicAuth('url here', 'username', 'password')
r.get()

</code>```

By The way, all these thing are already mentioned on the Github repository.

Body:
This is just an more detailed version of the verified answers

How To Download?

pip3 install proxy-requests

Example for Basic GET Request

from proxy_requests import ProxyRequests
r = ProxyRequests("https://dog.ceo/api/breeds/image/random")
r.get()

Example for GET Request with Headers

from proxy_requests import ProxyRequests
h = {'User-Agent': 'NCSA Mosaic/3.0 (Windows 95)'}
r = ProxyRequests('url here')
r.set_headers(h)
r.get_with_headers()

Example for POST Request

from proxy_requests import ProxyRequests
r = ProxyRequests('url here')
r.post({'key1': 'value1', 'key2': 'value2'})

Example for POST Request with Headers

r = ProxyRequests('url here')
r.set_headers({'name': 'rootVIII', 'secret_message': '7Yufs9KIfj33d'})
r.post_with_headers({'key1': 'value1', 'key2': 'value2'})

Example for Request with Authentication

r = ProxyRequestsBasicAuth('url here', 'username', 'password')
r.get()

By The way, all these thing are already mentioned on the Github repository.


问:
How to verify if a button is clickable with Selenium in Python when the class changes?
I'm trying to find out if a "Ship to Home" button is available and able to be clicked on an item in The Home Depot website. Currently, the only identifier that I find for the button is a class but when you go from store pickup to ship to home the two classes switch places for the button element.
Two Elements Switch

This is even more confusing when the "ship to home" option is unavailable and contains an even more different class. Unavailable Element

I'm trying to avoid using xpath as I am afraid the it might change locations in the future and I would have to constantly update it. I don't know much about selenium but I'm assuming there has to be some type of way to loop a section of the HTML and find out if the element contains some text and if it does to click on that element.

答:
XPATH could be quite flexible and allows to refer a lot of element node's data and also in advance it alows some logical conditions, etc. So I believe it's very powerful and flexible enough to produce some targeted and not fragile results.

Regarding your case:

```<code>clickable_button_xpath = "//a[@type='button'][contains(., 'Ship to Home') and contains(@class, '-unselected')]"
selected_button_xpath = "//a[@type='button'][contains(., 'Ship to Home') and contains(@class, '-selected')]"
unclickable_button_xpath = "//a[@type='button'][contains(., 'Ship to Home') and contains(@class, '-unclickable')]"

some_element = driver.find_element(By.XPATH, some_xpath)
</code>```

Body:
XPATH could be quite flexible and allows to refer a lot of element node's data and also in advance it alows some logical conditions, etc. So I believe it's very powerful and flexible enough to produce some targeted and not fragile results.

Regarding your case:

clickable_button_xpath = "//a[@type='button'][contains(., 'Ship to Home') and contains(@class, '-unselected')]"
selected_button_xpath = "//a[@type='button'][contains(., 'Ship to Home') and contains(@class, '-selected')]"
unclickable_button_xpath = "//a[@type='button'][contains(., 'Ship to Home') and contains(@class, '-unclickable')]"

some_element = driver.find_element(By.XPATH, some_xpath)


问:
Converting Milliseconds to Timecode
I have an audio project I'm working on using BASS from Un4seen. This library uses BYTES mainly but I have a conversion in place that let's me show the current position of the song in Milliseconds.

Knowing that MS = Samples * 1000 / SampleRate
and that Samples = Bytes * 8 / Bits / Channels

So here's my main issue and it's fairly simple... I have a function in my project that converts the Milliseconds to TimeCode in Mins:Secs:Milliseconds.

```<code>Public Function ConvertMStoTimeCode(ByVal lngCurrentMSTimeValue As Long)
        ConvertMStoTimeCode = CheckForLeadingZero(Fix(lngCurrentMSTimeValue / 1000 / 60)) & ":" & _
        CheckForLeadingZero(Int((lngCurrentMSTimeValue / 1000) Mod 60)) & ":" & _
        CheckForLeadingZero(Int((lngCurrentMSTimeValue / 10) Mod 100))
End Function
</code>```

Now the issue comes within the Seconds calculation. Anytime the MS calculation is over .5 the seconds place rounds up to the next second. So 1.5 seconds actually prints as 2.5 seconds. I know for sure that using the Int conversion causes a round down and I know my math is correct as I've checked in a calculator 100 times. I can't figure out why the number is rounding up. Any suggestions?

答:
Here's a Processing/Java equivalent that's fairly straightforward to repurpose. </p>

```<code>String timecodeString(int fps) {
  float ms = millis();
  return String.format("%02d:%02d:%02d+%02d", floor(ms/1000/60/60),    // H
                                              floor(ms/1000/60),       // M
                                              floor(ms/1000%60),       // S
                                              floor(ms/1000*fps%fps)); // F
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: Converting Milliseconds to Timecode

Body:
I have an audio project I'm working on using BASS from Un4seen. This library uses BYTES mainly but I have a conversion in place that let's me show the current position of the song in Milliseconds.

Knowing that MS = Samples * 1000 / SampleRate
and that Samples = Bytes * 8 / Bits / Channels

So here's my main issue and it's fairly simple... I have a function in my project that converts the Milliseconds to TimeCode in Mins:Secs:Milliseconds.

Public Function ConvertMStoTimeCode(ByVal lngCurrentMSTimeValue As Long)
        ConvertMStoTimeCode = CheckForLeadingZero(Fix(lngCurrentMSTimeValue / 1000 / 60)) & ":" & _
        CheckForLeadingZero(Int((lngCurrentMSTimeValue / 1000) Mod 60)) & ":" & _
        CheckForLeadingZero(Int((lngCurrentMSTimeValue / 10) Mod 100))
End Function

Now the issue comes within the Seconds calculation. Anytime the MS calculation is over .5 the seconds place rounds up to the next second. So 1.5 seconds actually prints as 2.5 seconds. I know for sure that using the Int conversion causes a round down and I know my math is correct as I've checked in a calculator 100 times. I can't figure out why the number is rounding up. Any suggestions?

Body:
Here's a Processing/Java equivalent that's fairly straightforward to repurpose.

String timecodeString(int fps) {
  float ms = millis();
  return String.format("%02d:%02d:%02d+%02d", floor(ms/1000/60/60),    // H
                                              floor(ms/1000/60),       // M
                                              floor(ms/1000%60),       // S
                                              floor(ms/1000*fps%fps)); // F
}

ContentLicense: CC BY-SA 3.0


问:
How to apply hover event to the element with lower z-index with keeping pointer events of the element with higher z-index
I have two div elements.

```<code><div class="container">
  <div class="card">...card container...</div>
  <div class="effect-background">...effect container...</div>
</div>
</code>```

and here are styles of them

```<code>.card {
  width: 500px;
  height: 500px;
  z-index: 10;
}
.card:hover {
  ...CARD HOVER STYLES...
}
.effect-background{
  position: fixed;
  left: 0;
  top: 0;
  width: 100vw;
  height: 100vh;
  z-index: 9;
}
.effect-background:hover {
  ...BACKGROUND HOVER STYLES...
}
</code>```

but BACKGROUND HOVER STYLES doesn't work when hovering on card div.

I know pointer-events: none; CSS but I want to keep CARD HOVER STYLES at the same time.

Is it possible?

答:
Use: .card:hover + .effect-background. You can read more about selectors here.

Hope it helped :)

.card {
    position: absolute;
    left: 40vw;
    top: 40vh;
    width: 20vw;
    height: 20vh;
    z-index: 10;
    background-color: yellow;
  }
  .card:hover {
      background-color: yellowgreen;
  }
  .effect-background{
    position: absolute;
    background-color: red;
    left: 0;
    top: 0;
    width: 100vw;
    height: 100vh;
    z-index: 9;
  }
  .card:hover + .effect-background {
background-color: pink;}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="card">...card container...</div>
  <div class="effect-background">...effect container...</div>
</div></code>```

Body:
I have two div elements.

...card container...

...effect container...

and here are styles of them

.card {
  width: 500px;
  height: 500px;
  z-index: 10;
}
.card:hover {
  ...CARD HOVER STYLES...
}
.effect-background{
  position: fixed;
  left: 0;
  top: 0;
  width: 100vw;
  height: 100vh;
  z-index: 9;
}
.effect-background:hover {
  ...BACKGROUND HOVER STYLES...
}

but BACKGROUND HOVER STYLES doesn't work when hovering on card div.

I know pointer-events: none; CSS but I want to keep CARD HOVER STYLES at the same time.

Is it possible?

Body:
Use: .card:hover + .effect-background. You can read more about selectors here.

Hope it helped :)

.card {
    position: absolute;
    left: 40vw;
    top: 40vh;
    width: 20vw;
    height: 20vh;
    z-index: 10;
    background-color: yellow;
  }
  .card:hover {
      background-color: yellowgreen;
  }
  .effect-background{
    position: absolute;
    background-color: red;
    left: 0;
    top: 0;
    width: 100vw;
    height: 100vh;
    z-index: 9;
  }
  .card:hover + .effect-background {
background-color: pink;}

<div class="container">
  <div class="card">...card container...</div>
  <div class="effect-background">...effect container...</div>
</div>


问:
Android 5.0 build number not shown in Settings > About Phone
I have purchased QMobile S1 which has Android 5.0 running.

I am trying to enable developer options but I can't find Build Number in About Phones in Settings. I know I need to tap on Build Number 7 times to become a developer. But the option is not even shown in the About Phone.

I tried taping Android Version in About Phone which showed me animation of Lollipop.

How can I make it appear?

This is how my About Phone screen looks.

答:
Not sure if it's the different Android versions or the phone versions, but on different phones, it may be at different locations. Instead of "Build number" it might be "Software version" on some phones.

Most Android phones:

“Settings”>”About”>Tap ”Build Number” 7 times quickly or more.

Other android phones:

"Settings">"System Management">"About Phone">Tap "Software version" 7
times quickly or more.

Just tap anything in "About" that has "build number" or "software info" or "software version" in it, as different phones seem to have different locations.

In your case, it appears that you want to tap the "Software version" in your screenshot 7 times.


问:
How do I get the YouTube video ID from a URL?
I want to get the v=id from YouTube’s URL with JavaScript (no jQuery, pure JavaScript).

Example YouTube URL formats

http://www.youtube.com/watch?v=u8nQa1cJyX8&a=GxdCwVVULXctT2lYDEPllDR0LRTutYfW

http://www.youtube.com/watch?v=u8nQa1cJyX8

Or any other YouTube format that contains a video ID in the URL.

Result from these formats

u8nQa1cJyX8

答:
I have got a Regex which supports commonly used url's which also includes YouTube Shorts

Regex Pattern:

(youtu.*be.*)\/(watch\?v=|embed\/|v|shorts|)(.*?((?=[&#?])|$))

Javascript Return Method:

function getId(url) {
  let regex = /(youtu.*be.*)\/(watch\?v=|embed\/|v|shorts|)(.*?((?=[&#?])|$))/gm;
  return regex.exec(url)[3];
}
```
<p><strong>Types of URL's supported:</strong></p>
```http://www.youtube.com/watch?v=0zM3nApSvMg&feature=feedrec_grec_index
http://www.youtube.com/user/IngridMichaelsonVEVO#p/a/u/1/QdK8U-VIH_o
http://www.youtube.com/v/0zM3nApSvMg?fs=1&hl=en_US&rel=0
http://www.youtube.com/watch?v=0zM3nApSvMg#t=0m10s
http://www.youtube.com/embed/0zM3nApSvMg?rel=0
http://www.youtube.com/watch?v=0zM3nApSvMg
http://youtu.be/0zM3nApSvMg
https://youtube.com/shorts/0dPkkQeRwTI?feature=share
https://youtube.com/shorts/0dPkkQeRwTI
```

With Test:

https://regex101.com/r/5JhmpW/1

Body:
I have got a Regex which supports commonly used url's which also includes YouTube Shorts

Regex Pattern:

(youtu.*be.*)\/(watch\?v=|embed\/|v|shorts|)(.*?((?=[&#?])|$))

Javascript Return Method:

function getId(url) {
  let regex = /(youtu.*be.*)\/(watch\?v=|embed\/|v|shorts|)(.*?((?=[&#?])|$))/gm;
  return regex.exec(url)[3];
}

Types of URL's supported:

http://www.youtube.com/watch?v=0zM3nApSvMg&feature=feedrec_grec_index
http://www.youtube.com/user/IngridMichaelsonVEVO#p/a/u/1/QdK8U-VIH_o
http://www.youtube.com/v/0zM3nApSvMg?fs=1&amp;hl=en_US&amp;rel=0
http://www.youtube.com/watch?v=0zM3nApSvMg#t=0m10s
http://www.youtube.com/embed/0zM3nApSvMg?rel=0
http://www.youtube.com/watch?v=0zM3nApSvMg
http://youtu.be/0zM3nApSvMg
https://youtube.com/shorts/0dPkkQeRwTI?feature=share
https://youtube.com/shorts/0dPkkQeRwTI

With Test:

https://regex101.com/r/5JhmpW/1


问:
How to theme uitableview uiview and friends
I have a bunch of uiviews and uitable views.  How can I theme them the same way you might make a stylesheet for html pages?

What is the best way to use a custom shared appearance properties across my iphone application

答:
I dont think is possible using something like stylesheet!

I would advice you to theme your views as much as possible in the interface builder! but in this approach you will have to do it again, again and again!

Or you can have your custom components, such as, CustomTableView, which has all your themes! the issue about it, is that you cannot visualize your custom component in Interface Builder.


问:
Clicking on one item changes the background of another item in recycler view
I don't know how to fix it. Below is the video link:
https://www.facebook.com/groups/2297396350278679/permalink/5183111161707169/?app=fbl</p>

答:
i dont know much about recycleview but i am facing the same problem in the listview,
its happend if you make the background changed for example if(_position==1),
to fix it in simple way dont make the background changed onbind and change it onclick and to change it when the content refreshed you can use .setSelection method.</p>


问:
React UI Kitten Styling TabBars
Pretty simple question and concept here, I am using the react UI Kitten Framework for a React Native Project, and for the life of me I cannot change the styling on the TabBar's Tab components. I've looked at the documentation, and this is where it had lead me...

```<code> <View style={LandingPageStyles.container}>
            <View style={LandingPageStyles.tabBarContainer}>
                <TabBar
                    indicatorStyle={{color: '#ffffff !important', borderColor: '#ffffff !important'}}
                    tabBarStyle={LandingPageStyles.loginTab}
                    style={LandingPageStyles.tabBar}
                    selectedIndex={selectedIndex}
                    onSelect={index => setSelectedIndex(index)}
                >
                    <Tab
                        title="Login"
                        tabBarStyle={LandingPageStyles.loginTab}
                        indicatorStyle={{color: '#ffffff !important', borderColor: '#ffffff !important'}}
                        tabBarStyle={LandingPageStyles.loginTab}/>
                    <Tab
                        title='Sign Up'
                        tabBarStyle={LandingPageStyles.signUpTab}
                        indicatorStyle={{color: '#ffffff !important', borderColor: '#ffffff !important'}}
                        tabBarStyle={LandingPageStyles.loginTab}/>
                </TabBar>
            </View>
            <View>
                {determineRender()}
            </View>
        </View>
</code>```

And I have the following styleSheets...

```<code>const LandingPageStyles = StyleSheet.create({
    container: {
        width: maxWidth,
        height: maxHeight,
    },
    tabBarContainer: {
        marginTop: maxHeight * 0.045,
        marginLeft: maxWidth * 0.075,
        marginBottom: maxHeight * 0.06,

        // borderWidth: 1,
        // borderColor: 'black',
        // width: maxWidth * 0.85,
    },
    tabBar: {
        backgroundColor: 'rgba(52, 52, 52, 0.3) !important',
    },
    loginTab: {
        borderBottomColor: "white",
        color: 'white',
    },
    signUpTab: {
        borderBottomColor: "white",
        color: 'white',
    }
})
</code>```

Notice that I'm attempting to style the tabs themselves in anyway possible, adding style tabBarStyle and indicatorStyle anywhere it would be relevant. Unfortunately it does nothing and the text color is still some faded blue/grey instead of white, and the borderBottomColor of the selected tab is just blue. Am I shit out of luck an unable to style Kitten elements or is there something I'm missing?

答:
For Changing certain styles in the react native ui kitten library, you would need to use something known as customize mappings.

You can follow the guide here:

Custom Component Mapping

Customizing mappinghttps://akveo.github.io/react-native-ui-kitten/docs/design-system/customize-mapping#customize-component-mapping

Title: React UI Kitten Styling TabBars

Body:
Pretty simple question and concept here, I am using the react UI Kitten Framework for a React Native Project, and for the life of me I cannot change the styling on the TabBar's Tab components. I've looked at the documentation, and this is where it had lead me...

 <View style={LandingPageStyles.container}>
            <View style={LandingPageStyles.tabBarContainer}>
                <TabBar
                    indicatorStyle={{color: '#ffffff !important', borderColor: '#ffffff !important'}}
                    tabBarStyle={LandingPageStyles.loginTab}
                    style={LandingPageStyles.tabBar}
                    selectedIndex={selectedIndex}
                    onSelect={index => setSelectedIndex(index)}
                >
                    <Tab
                        title="Login"
                        tabBarStyle={LandingPageStyles.loginTab}
                        indicatorStyle={{color: '#ffffff !important', borderColor: '#ffffff !important'}}
                        tabBarStyle={LandingPageStyles.loginTab}/>
                    <Tab
                        title='Sign Up'
                        tabBarStyle={LandingPageStyles.signUpTab}
                        indicatorStyle={{color: '#ffffff !important', borderColor: '#ffffff !important'}}
                        tabBarStyle={LandingPageStyles.loginTab}/>
                </TabBar>
            </View>
            <View>
                {determineRender()}
            </View>
        </View>

And I have the following styleSheets...

const LandingPageStyles = StyleSheet.create({
    container: {
        width: maxWidth,
        height: maxHeight,
    },
    tabBarContainer: {
        marginTop: maxHeight * 0.045,
        marginLeft: maxWidth * 0.075,
        marginBottom: maxHeight * 0.06,

        // borderWidth: 1,
        // borderColor: 'black',
        // width: maxWidth * 0.85,
    },
    tabBar: {
        backgroundColor: 'rgba(52, 52, 52, 0.3) !important',
    },
    loginTab: {
        borderBottomColor: "white",
        color: 'white',
    },
    signUpTab: {
        borderBottomColor: "white",
        color: 'white',
    }
})

Notice that I'm attempting to style the tabs themselves in anyway possible, adding style tabBarStyle and indicatorStyle anywhere it would be relevant. Unfortunately it does nothing and the text color is still some faded blue/grey instead of white, and the borderBottomColor of the selected tab is just blue. Am I shit out of luck an unable to style Kitten elements or is there something I'm missing?


问:
What is the standard or best practice with regards to quotes on JavaScript keys?
I have been going through several questions such as this to see if there is a standard practice/ best practice for whether to put quotes on keys in JavaScript or JSX or TSX. I, however, haven't found anything and would like to know (before building a huge project on bad practices) which is best between:

```<code>obj = {'foo': 'bar'}
</code>```

and

```<code>obj = {foo: 'bar'}
</code>```

Or better yet, is there some document I can refer to for this?

答:
Both work and it's up to you what you want to do but my university teacher did tell us not to use quotations so as to make it a bit different from string value hence our whole class adopted as standard practice</p>
```<code>obj = {foo: 'bar'}
</code>```

Body:
I have been going through several questions such as this to see if there is a standard practice/ best practice for whether to put quotes on keys in JavaScript or JSX or TSX. I, however, haven't found anything and would like to know (before building a huge project on bad practices) which is best between:

obj = {'foo': 'bar'}

and

obj = {foo: 'bar'}

Or better yet, is there some document I can refer to for this?

Body:
Both work and it's up to you what you want to do but my university teacher did tell us not to use quotations so as to make it a bit different from string value hence our whole class adopted as standard practice

obj = {foo: 'bar'}


问:
Get contact attachments using API
I am able to retrieve attachments from contact object but I can't view that attachment because its by default hidden true. How I can retrieve those files without uploading in file manager?</p>

答: Files are attached as note engagements on the contact and would be returned in this API and then get the file metadata from there. One thing to note though is that if a file was uploaded outside of the file manager in HubSpot, i.e. attached directly on the record, then it will show as hidden:true and you can not get the file metadata via API.</p>

Title: Get contact attachments using API


问:
tf.print gives TypeSpec TypeError
What does this error message mean?

```<code>TypeError: Could not build a TypeSpec for name: "tf.print/PrintV2"
op: "PrintV2"
input: "tf.print/StringFormat"
attr {
  key: "end"
  value {
    s: "\n"
  }
}
attr {
  key: "output_stream"
  value {
    s: "stdout"
  }
}
 of unsupported type <class 'google3.third_party.tensorflow.python.framework.ops.Operation'>
</code>```

I'm printing the shape of a tensor.  My code "works" without the print, so I'm sure it is this statement, and the tensor is valid.  I can print the shape of a tensor in a test colab. I'm clueless how to narrow this down and debug this.  My failure is in a big hairy program.

I can't find any information on the web about what might be causing this error.

What does it mean when I get a TypeSpec error from a tf.print?

-- Malcolm
(TF 2.7.0)

答:
I'm sorry for the tardy followup.

Turns out that the output from Keras layers is not a regular tf.tensor. I still don't understand the reason, the error message, or how to give a better message.  :-(

Here is a simple example of the problem (and the error message) and an (undocumented) solution.

```<code>import tensorflow as tf
keras_input = tf.keras.layers.Input([10])
tf.print(keras_input)
==> TypeError: Could not build a TypeSpec for name: "tf.print_2/PrintV2"

tf.keras.backend.print_tensor(keras_input)
==> <KerasTensor: shape=(None, 10) dtype=float32 (created by layer 'tf.keras.backend.print_tensor')>
</code>```

So the moral of the story is use tf.keras.backend.print_tensor when working with Keras models.

Title: tf.print gives TypeSpec TypeError

Body:
What does this error message mean?

TypeError: Could not build a TypeSpec for name: "tf.print/PrintV2"
op: "PrintV2"
input: "tf.print/StringFormat"
attr {
  key: "end"
  value {
    s: "\n"
  }
}
attr {
  key: "output_stream"
  value {
    s: "stdout"
  }
}
 of unsupported type <class 'google3.third_party.tensorflow.python.framework.ops.Operation'>

I'm printing the shape of a tensor.  My code "works" without the print, so I'm sure it is this statement, and the tensor is valid.  I can print the shape of a tensor in a test colab. I'm clueless how to narrow this down and debug this.  My failure is in a big hairy program.

I can't find any information on the web about what might be causing this error.

What does it mean when I get a TypeSpec error from a tf.print?

-- Malcolm
(TF 2.7.0)

Body:
I'm sorry for the tardy followup.

Turns out that the output from Keras layers is not a regular tf.tensor. I still don't understand the reason, the error message, or how to give a better message.  :-(

Here is a simple example of the problem (and the error message) and an (undocumented) solution.

import tensorflow as tf
keras_input = tf.keras.layers.Input([10])
tf.print(keras_input)
==> TypeError: Could not build a TypeSpec for name: "tf.print_2/PrintV2"

tf.keras.backend.print_tensor(keras_input)
==> <KerasTensor: shape=(None, 10) dtype=float32 (created by layer 'tf.keras.backend.print_tensor')>

So the moral of the story is use tf.keras.backend.print_tensor when working with Keras models.


问:
How to set query parameters without reloading component in Vue with Vue-Router
I am trying to set the Query Parameters without reloading component in Vue with Vue-Router. But using below code it reloads the component:

```<code>this.$router.replace({query: this.filters});
</code>```

How we can stop reload the component while changing the Query Parameters?

答:
```<code>this.$router.replace({ ...this.$router.currentRoute, query: this.filters });
</code>```

Going to the current path will not render the currently component again

Body:
I am trying to set the Query Parameters without reloading component in Vue with Vue-Router. But using below code it reloads the component:

this.$router.replace({query: this.filters});

How we can stop reload the component while changing the Query Parameters?

Body:
this.$router.replace({ ...this.$router.currentRoute, query: this.filters });

Going to the current path will not render the currently component again


问:
How do I create an instance of a Class passed as parameter to a function?
I'm building a library in Kotlin and here's my usecase

I have a base class

```<code>abstract class Component(...) {
  // ... class body
}
</code>```

I want the users of my library to define their own sub-classes like say:

```<code>class MyComponent() : Component() {
  // .. class body
}
</code>```

How can I write a helper function that takes in this derived class as a param and create an instance out of it. Something like:

```<code>fun helper(component: Class, props: HashMap<String, String>) : Component {
  // somehow create a new instance of Class and return it?
}
</code>```

Thanks!

答:
```<code>abstract class Component(val prop1: String, val prop2: String) {
  // ... class body
}

class MyComponent(prop1: String, prop2: String) : Component (prop1, prop2) {
  // ... class body
}

fun helper(component: Class<MyComponent>, props: Map<String, String>): Component {
  val constructor = component.constructors.first { it.parameterCount == props.size }
  val arguments = props.values.toTypedArray()
  return constructor.newInstance(*arguments) as Component
}

val instance = helper(MyComponent::class.java, mapOf("prop1" to "value1", "prop2" to "value2"))

println(instance.prop1 + ", " + instance.prop2)   // Prints:   value1, value2
</code>```

Body:
I'm building a library in Kotlin and here's my usecase

I have a base class

abstract class Component(...) {
  // ... class body
}

I want the users of my library to define their own sub-classes like say:

class MyComponent() : Component() {
  // .. class body
}

How can I write a helper function that takes in this derived class as a param and create an instance out of it. Something like:

fun helper(component: Class, props: HashMap<String, String>) : Component {
  // somehow create a new instance of Class and return it?
}

Thanks!


问:
How to fix PlotlyRequestError?
I get an 'PlotlyRequestError: No message' when I execute the code. </p>

```<code>import plotly
import plotly.plotly as py
import plotly.graph_objs as go

Filedata = pd.read_csv('C:\\Documents\\Book4.csv')
data = [go.Scatter(x=Filedata.ix[:,0],y=Filedata.ix[:,1])]
layout = go.Layout(
title='Analysis 2016',
xaxis=dict(title='Startdate'),
yaxis=dict(title='Conductivity'))

fig = go.Figure(data=data, layout=layout)
py.iplot(fig)
</code>```

答:
I had the same issue and I solved the problem by importing plotly and cufflinks like this:

from plotly.offline import iplot
import cufflinks as cf
```
<p>and then apply</p>
<pre class="lang-py prettyprint-override"><code>cf.go_offline()
</code>```

Title: How to fix PlotlyRequestError?

Body:
I get an 'PlotlyRequestError: No message' when I execute the code.

import plotly
import plotly.plotly as py
import plotly.graph_objs as go

Filedata = pd.read_csv('C:\\Documents\\Book4.csv')
data = [go.Scatter(x=Filedata.ix[:,0],y=Filedata.ix[:,1])]
layout = go.Layout(
title='Analysis 2016',
xaxis=dict(title='Startdate'),
yaxis=dict(title='Conductivity'))

fig = go.Figure(data=data, layout=layout)
py.iplot(fig)

Body:
I had the same issue and I solved the problem by importing plotly and cufflinks like this:

from plotly.offline import iplot
import cufflinks as cf

and then apply

cf.go_offline()


问:
how to open and edit py file in command prompt windows 10
I'm finding for a syntax equivalent to mac os terminal open filename.py in windows command prompt.
I've search internet to find answer like type in filename (or location) filename.py into command prompt, but that just run a script or even start filename.py doesn't seems to work too. how do i edit get to edit my code via command prompt?

答:
The open command in MacOS or even xdg-open on Linux is for opening a file with its programs (associated by the operating-system depending on the file-type).

Windows command start

On Windows there is the start command:

Starts a separate Command Prompt window to run a specified program or command.

Python equivalent to start

Also Python has os.startfile:

Start a file with its associated application.

import os
os.startfile("filename.py")
```
<h3>Manage Associations</h3>
<p>The associated shell-execute command (associated default application and command to open the file) usually is stored and can be set in Windows-registry.</p>
<p>In the case of a <code>.py</code> file it can for example:</p>
<ul>
<li>open the file for editing using notepad</li>
<li>execute the script via Python</li>
</ul>
<p>On the Windows command-line <code>cmd.exe</code> you can use <code>assoc</code> and <code>ftype</code> to manage and alter the associations with a given file-type/-extension:</p>
```assoc /?
ftype /?
```

Note: on PowerShell prefix the commands with cmd /c

Use assoc .py to view the current file type association for Python scripts. If the resulting file-type name is pyfile then ftype pyfile=%SystemRoot%\system32\NOTEPAD.EXE %1 binds the notepad (Windows default editor) as opening command/application.

See also

Super User: Linux equivalent command for "open" command on Mac/Windows?

Microsoft Blog: Setting default programs in Windows 10 via command line/Powershell

Microsoft Docs: Making file type associations enterprise ready

Microsoft Docs: Windows 10 – How to configure file associations for IT Pros?

Microsoft Docs: Launching Applications (ShellExecute, ShellExecuteEx, SHELLEXECUTEINFO) - Win32 apps

Body:
The open command in MacOS or even xdg-open on Linux is for opening a file with its programs (associated by the operating-system depending on the file-type).

Windows command start

On Windows there is the start command:

Starts a separate Command Prompt window to run a specified program or command.

Python equivalent to start

Also Python has os.startfile:

Start a file with its associated application.

import os
os.startfile("filename.py")

Manage Associations

The associated shell-execute command (associated default application and command to open the file) usually is stored and can be set in Windows-registry.

In the case of a .py file it can for example:

open the file for editing using notepad

execute the script via Python

On the Windows command-line cmd.exe you can use assoc and ftype to manage and alter the associations with a given file-type/-extension:

assoc /?
ftype /?

Note: on PowerShell prefix the commands with cmd /c

Use assoc .py to view the current file type association for Python scripts. If the resulting file-type name is pyfile then ftype pyfile=%SystemRoot%\system32\NOTEPAD.EXE %1 binds the notepad (Windows default editor) as opening command/application.

See also

Super User: Linux equivalent command for "open" command on Mac/Windows?

Microsoft Blog: Setting default programs in Windows 10 via command line/Powershell

Microsoft Docs: Making file type associations enterprise ready

Microsoft Docs: Windows 10 – How to configure file associations for IT Pros?

Microsoft Docs: Launching Applications (ShellExecute, ShellExecuteEx, SHELLEXECUTEINFO) - Win32 apps


问:
Extracting rows from file based on another file using awk
I have two files.

File 1:

```<code>SNP Allele1 Allele2 Effect  StdErr  PVAL    Direction   HetISq  HetChiSHetDf    HetPVal
rs12266638  t   g   0.4259  0.0838  3.776e-07   +?  0.0 0.000   0   1
rs7995014   t   c   2.2910  0.5012  4.853e-06   +?  0.0 0.000   0   1
</code>```

File 2:

```<code>Chromosome Position SNP EA NEA EAF BETA SE P Direction
10 108627406 rs12266638 t g 0.991 -0.2649 0.0578 4.608e-06 -
11 116365828 rs112127824 a t 0.0327 0.4569 0.0994 4.327e-06 +
</code>```

I would like to print a file 3, based on the "SNP" column. If the SNP exists in file 2, I would like to print the whole row with all columns of file 1.

Output:

```<code>rs12266638  t   g   0.4259  0.0838  3.776e-07   +?  0.0 0.000   0   1
</code>```

I tried the following:

```<code>awk 'FNR==NR{a[$1]=$0; if(NR==1) print $0} ($1 in a) {print a[$1]}' file 1 file 2 > file 3
</code>```

But it prints different SNPs than those present in file 2.

答:
Depending on how big the dataset is, this should be fairly fast, only accessing each file once. Granted, not on a system where I can compare at the moment, so mostly a hunch. A solution like this is probably only suitable if the amount of unique identifiers isn't very large, though.

#!/bin/bash
snp_expression=$(awk 'FNR>1{print $3}' file_2 | sort -u | paste -sd "|")
grep -E "^(${snp})[[:space:]]" file_1 > file_3
```

Body:
I have two files.

File 1:

SNP Allele1 Allele2 Effect  StdErr  PVAL    Direction   HetISq  HetChiSHetDf    HetPVal
rs12266638  t   g   0.4259  0.0838  3.776e-07   +?  0.0 0.000   0   1
rs7995014   t   c   2.2910  0.5012  4.853e-06   +?  0.0 0.000   0   1

File 2:

Chromosome Position SNP EA NEA EAF BETA SE P Direction
10 108627406 rs12266638 t g 0.991 -0.2649 0.0578 4.608e-06 -
11 116365828 rs112127824 a t 0.0327 0.4569 0.0994 4.327e-06 +

I would like to print a file 3, based on the "SNP" column. If the SNP exists in file 2, I would like to print the whole row with all columns of file 1.

Output:

rs12266638  t   g   0.4259  0.0838  3.776e-07   +?  0.0 0.000   0   1

I tried the following:

awk 'FNR==NR{a[$1]=$0; if(NR==1) print $0} ($1 in a) {print a[$1]}' file 1 file 2 > file 3

But it prints different SNPs than those present in file 2.


答:
in practice for Gaussian distribution: data_cases that falls outside mean+/-3*st.dev. are considered to be outliers (as is outside the 99.7% range of distribution)... Thus, for Gaussian & Gaussian-like distributions I would better rewrite the previous answer to:

```<code>data= df[col].values
_mean, _std = np.mean(data), np.std(data)
border = _std * 3
lower, upper = _mean - border, _mean + border
#  outliers
outliers = [x for x in data if x < lower or x > upper]
</code>```

with data - being taken in for-loop for each column_range that you need
___ P.S.  sometimes even 4 st.dev. can be used (covering 99.9% of distribution), but 1 st.dev. is only 68%, 2 st.dev - 95%... So, be sure what you really need

Title: Identifying statistical outliers with pandas: groupby and reduce rows into different dataframe

Body:
I'm trying to understand how to identify statistical outliers in groups of dataframe. I will need to group the rows by the conditions and then reduce those groups into a single row and later find the outliers in all reduced rows.

df = pd.DataFrame({'X0': {0: 1, 1: 1, 2: 1, 3: 1, 4: 0, 5: 1, 6: 1, 7: 1, 8: 0, 9: 1, 10: 0, 11: 1, 12: 0, 13: 1, 14: 1, 15: 1, 16: 0, 17: 0, 18: 0, 19: 1, 20: 0, 21: 1, 22: 1, 23: 1, 24: 1, 25: 0, 26: 1, 27: 1, 28: 1, 29: 1, 30: 0, 31: 1, 32: 0, 33: 1, 34: 0, 35: 1, 36: 1, 37: 0, 38: 1, 39: 0, 40: 1, 41: 0, 42: 1, 43: 0, 44: 0, 45: 1, 46: 1, 47: 1, 48: 1, 49: 0}, 'X1': {0: -0.037112917323895135, 1: -0.10487134240202785, 2: -1.2231079338781112, 3: -1.4422747724730558, 4: 1.1903093112171788, 5: 0.16264503017608584, 6: 0.09575885513801816, 7: -0.04065753545650327, 8: 0.9811627656097434, 9: -1.0895731715012618, 10: 1.2771663221280398, 11: 0.20642136730493899, 12: 1.4502341066082816, 13: 0.393823431298906, 14: 0.3451716634317143, 15: 0.4709902758164765, 16: 0.9982956103799087, 17: 1.189077916373609, 18: 0.9234439359961105, 19: -1.3255857892440723, 20: 1.2098373846214483, 21: -1.0264301443260604, 22: -1.2752711175444444, 23: -1.1775143284917524, 24: 0.259560479915767, 25: 0.8873566136283076, 26: 0.21516987874467863, 27: -1.1480968752611762, 28: -1.1903434754082, 29: 0.16553499639585526, 30: -0.027563846470247143, 31: 0.19474819789386086, 32: 1.5332001783034717, 33: -1.4746621814990961, 34: 0.9251147862187328, 35: 0.009242841373200278, 36: -1.4155649459675044, 37: 1.1476020465617858, 38: -1.3349528515873126, 39: 1.3090049690691499, 40: -1.0159692538569027, 41: 1.006261902461321, 42: -1.161160155994317, 43: 0.8833114074575376, 44: 1.0811966452823563, 45: -1.368200135415236, 46: -1.556580287072397, 47: -1.2006674694322674, 48: 0.13038922844618558, 49: 0.9941283827531714}, 'X2': {0: 1, 1: 1, 2: 0, 3: 0, 4: 0, 5: 1, 6: 1, 7: 1, 8: 0, 9: 0, 10: 0, 11: 1, 12: 0, 13: 1, 14: 1, 15: 1, 16: 0, 17: 0, 18: 0, 19: 0, 20: 0, 21: 0, 22: 0, 23: 0, 24: 1, 25: 0, 26: 1, 27: 0, 28: 0, 29: 1, 30: 1, 31: 1, 32: 0, 33: 0, 34: 0, 35: 1, 36: 0, 37: 0, 38: 0, 39: 0, 40: 0, 41: 0, 42: 0, 43: 0, 44: 0, 45: 0, 46: 0, 47: 0, 48: 1, 49: 0}, 'X3': {0: 0, 1: 0, 2: 1, 3: 1, 4: 1, 5: 0, 6: 0, 7: 0, 8: 0, 9: 1, 10: 0, 11: 0, 12: 1, 13: 0, 14: 0, 15: 0, 16: 1, 17: 0, 18: 1, 19: 1, 20: 1, 21: 1, 22: 1, 23: 0, 24: 0, 25: 1, 26: 0, 27: 1, 28: 1, 29: 0, 30: 0, 31: 0, 32: 1, 33: 1, 34: 1, 35: 0, 36: 1, 37: 1, 38: 1, 39: 0, 40: 1, 41: 1, 42: 1, 43: 1, 44: 1, 45: 1, 46: 1, 47: 1, 48: 0, 49: 1}, 'X4': {0: 1, 1: 1, 2: 1, 3: 1, 4: 0, 5: 1, 6: 1, 7: 1, 8: 0, 9: 1, 10: 0, 11: 1, 12: 0, 13: 1, 14: 1, 15: 1, 16: 0, 17: 0, 18: 0, 19: 1, 20: 0, 21: 1, 22: 1, 23: 1, 24: 1, 25: 0, 26: 1, 27: 1, 28: 1, 29: 1, 30: 1, 31: 1, 32: 0, 33: 1, 34: 0, 35: 1, 36: 1, 37: 0, 38: 1, 39: 0, 40: 1, 41: 0, 42: 1, 43: 0, 44: 0, 45: 1, 46: 1, 47: 1, 48: 1, 49: 0}, 'X5': {0: -1.6251996907891026, 1: -1.4952824550113089, 2: 0.5929477365851917, 3: 0.5188383985894559, 4: 0.8379329230408614, 5: -1.459754180360659, 6: -1.3954747896019781, 7: -1.4228738797414382, 8: 0.7961049502619677, 9: 0.5969844287269782, 10: 0.6254616540670719, 11: -1.1973174138607352, 12: 0.6743779844553507, 13: -1.3773048616218415, 14: -1.5502881165079259, 15: -1.410649926526345, 16: 0.966418551153225, 17: 0.8413042649713098, 18: 0.5947398261267023, 19: 0.5285211133411081, 20: 0.8154880527487283, 21: 0.685523955516477, 22: 0.7052301139466511, 23: 0.5694387744666269, 24: -1.3660759251156689, 25: 0.7376392137717523, 26: -1.2965881798979835, 27: 0.3247985508699227, 28: 0.8492845744063385, 29: -1.3631982627466268, 30: -1.5593937453283628, 31: -1.5647378670163918, 32: 0.7184017737689418, 33: 0.5401478202493889, 34: 0.8549277265014412, 35: -1.4324174459510242, 36: 0.5699907448414805, 37: 0.5278269967299144, 38: 0.6544095431196703, 39: 0.9956765313323911, 40: 0.49341021793456574, 41: 0.8777030715347666, 42: 0.5628001790223106, 43: 0.6932468790071539, 44: 0.5944907552098264, 45: 0.6628094310909329, 46: 0.660678722318602, 47: 0.68454503898171, 48: -1.5961965190965848, 49: 0.7606527604851616}, 'X6': {0: 0, 1: 0, 2: 0, 3: 0, 4: 1, 5: 0, 6: 0, 7: 0, 8: 1, 9: 0, 10: 1, 11: 0, 12: 1, 13: 0, 14: 0, 15: 0, 16: 1, 17: 1, 18: 1, 19: 0, 20: 1, 21: 0, 22: 0, 23: 0, 24: 0, 25: 1, 26: 0, 27: 0, 28: 0, 29: 0, 30: 0, 31: 0, 32: 1, 33: 0, 34: 1, 35: 0, 36: 0, 37: 1, 38: 0, 39: 1, 40: 0, 41: 1, 42: 0, 43: 1, 44: 1, 45: 0, 46: 0, 47: 0, 48: 0, 49: 1}, 'X7': {0: 0, 1: 0, 2: 1, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0, 11: 0, 12: 0, 13: 0, 14: 0, 15: 0, 16: 0, 17: 0, 18: 0, 19: 0, 20: 0, 21: 1, 22: 0, 23: 1, 24: 0, 25: 0, 26: 0, 27: 0, 28: 1, 29: 0, 30: 0, 31: 0, 32: 0, 33: 1, 34: 0, 35: 0, 36: 1, 37: 0, 38: 1, 39: 0, 40: 1, 41: 0, 42: 0, 43: 0, 44: 0, 45: 1, 46: 0, 47: 1, 48: 0, 49: 0}})

Using a dataset like this I would like to group by different conditions such as:

df1 = df[(df['X0'] == 0) & (df['X2'] == 0)]
df2 = df[(df['X0'] == 1) & (df['X3'] == 1)]
df3 = df[(df['X0'] == 1) & (df['X4'] == 1)]
df4 = df[(df['X0'] == 1) & (df['X7'] == 0)]

df5 = df[(df['X2'] == 1) & (df['X6'] == 0)]
df6 = df[(df['X2'] == 1) & (df['X4'] == 1)]
df7 = df[(df['X2'] == 1) & (df['X3'] == 0)]

df8 = df[(df['X3'] == 1) & (df['X7'] == 0)]
df9 = df[(df['X3'] == 1) & (df['X6'] == 1)]

df10 = df[(df['X7'] == 1) & (df['X2'] == 0)]

At this step, I am reducing each data frame into a single row, for that, I have a few ideas, a straightforward way is to take the mean of each dataframe but the problem is some of the columns are categorical and some of them are continuous, to take the mean of the entire data frame, I am converting the categorical columns into freq count columns :

cat_columns = ['X0', 'X2', 'X3', 'X4', 'X6', 'X7']
def add_freq(df, column_name):

    for col in cat_columns:
        df[f'{col}_freq'] = df[col].map(df[col].value_counts())
        df = df.drop(col, axis = 1)
    return df

all_groups  = [df1, df2, df3, df4, df5,
              df6, df7, df8, df9, df10]

all_freq_df = [add_freq(group, cat_columns) for group in all_groups]

which looks like this for each df group:

Now I can take the mean and reduce the data frames into a single row :

all_mean_df = [pd.DataFrame(group.mean()).T for group in all_freq_df]

concatinating all reduced rows in single dataframe :

all_groups  = pd.concat(all_mean_df).reset_index(drop=True)

The final reduced rows data frame looks like this, where each row represents reduced data frame group:

I want to find the outliers in this reduced dataset, I tried to find outliers using zscore such as :

from scipy import stats
all_groups[(np.abs(stats.zscore(all_groups)) < 3).all(axis=1)]

But it doesn't seem to work.
I feel like there has to be a way to do this without too much complexity but I've been stuck on how to proceed.

How can I reduce the groups into single rows and find the outliers in the reduced dataset?

Body:
in practice for Gaussian distribution: data_cases that falls outside mean+/-3*st.dev. are considered to be outliers (as is outside the 99.7% range of distribution)... Thus, for Gaussian & Gaussian-like distributions I would better rewrite the previous answer to:

data= df[col].values
_mean, _std = np.mean(data), np.std(data)
border = _std * 3
lower, upper = _mean - border, _mean + border
#  outliers
outliers = [x for x in data if x < lower or x > upper]

with data - being taken in for-loop for each column_range that you need
___ P.S.  sometimes even 4 st.dev. can be used (covering 99.9% of distribution), but 1 st.dev. is only 68%, 2 st.dev - 95%... So, be sure what you really need


问:
PHP Curl Json Filtering
So basically I have taken over a client's website and Autotrader has made some changes to their API. I can no longer filter out the results with a link. I have never in my life used PHP Curl and the furthest I have gone with PHP is Form validation.

This is the old code I could use:

```<code>      public function list_cars($count = 8, $page = 1)
{
    $core = new Core();
    $cars = $core->send_request('/service/stock-management/search?advertisingLocation=autotraderCars&advertiserId=' . $core->advertiser_id . '&pageSize=' . $count . '&page=' . $page);

    return json_decode($cars);

}
</code>```

This is the new code I have to use:

```<code>      public function list_cars($count = 8, $page = 1)
{
    $core = new Core();
    $cars = $core->send_request('/service/stock-management/stock?&advertiserId=' . $core->advertiser_id . '&pageSize=' . $count . '&page=' . $page);

    return json_decode($cars);

}
</code>```

My problem is that with the new code it is displaying all of the previous Ads for cars that are no longer on the website (Data must still be held even after a car sale)

In order to filter through the ads i need to do this:

```<code>    "adverts": {
         "retailAdverts": {
             "autotraderAdvert": {
                   "status": "PUBLISHED"

            }
</code>```

How on earth do I translate this into PHP Curl??

This is the line of code i have almost been certain i need to add but im so far from correct:

```<code>    json_decode($cars)->adverts->retailAdverts->autotraderAdvert->status == 'PUBLISHED'
</code>```

The response below is from a full lookup submission

```<code>    {
"vehicle": {
    "ownershipCondition": "Used",
    "registration": "AB12CDE",
    "vin": "WAUZXXXXXXXXX12345",
    "make": "Audi",
    "model": "A4",
    "generation": null,
    "derivative": "2.0 TDI ultra S line Saloon 4dr Diesel Manual (109 g/km, 161 bhp)",
    "derivativeId": "09ab072a937c3594b5e8c64251bde2eb",
    "vehicleType": "Car",
    "trim": "S line",
    "bodyType": "Saloon",
    "fuelType": "Diesel",
    "cabType": null,
    "transmissionType": "Manual",
    "wheelbaseType": null,
    "roofHeightType": null,
    "drivetrain": "Front Wheel Drive",
    "seats": 5,
    "doors": 4,
    "co2EmissionGPKM": 109,
    "topSpeedMPH": 140,
    "zeroToSixtyMPHSeconds": 8.3,
    "zeroToOneHundredKMPHSeconds": 8.4,
    "badgeEngineSizeLitres": 2.0,
    "engineCapacityCC": 1968,
    "enginePowerBHP": 161,
    "fuelCapacityLitres": 63.0,
    "emissionClass": "Euro 6",
    "owners": 1,
    "fuelEconomyNEDCExtraUrbanMPG": 74.3,
    "fuelEconomyNEDCUrbanMPG": 56.5,
    "fuelEconomyNEDCCombinedMPG": null,
    "fuelEconomyWLTPLowMPG": null,
    "fuelEconomyWLTPMediumMPG": null,
    "fuelEconomyWLTPHighMPG": null,
    "fuelEconomyWLTPExtraHighMPG": null,
    "fuelEconomyWLTPCombinedMPG": null,
    "bootSpaceSeatsUpLitres": 480.0,
    "insuranceGroup": "29",
    "insuranceSecurityCode": "E",
    "firstRegistrationDate": "2015-09-15",
    "colour": "Black",
    "style": null,
    "subStyle": null,
    "lengthMM": 4701,
    "heightMM": 1427,
    "widthMM": 2040,
    "payloadLengthMM": null,
    "payloadWidthMM": null,
    "payloadHeightMM": null,
    "payloadWeightKG": null,
    "minimumKerbWeightKG": 1540,
    "grossVehicleWeightKG": null,
    "cylinders": 4,
    "bootSpaceSeatsDownLitres": 962.0,
    "odometerReadingMiles": null,
    "motExpiryDate": null,
    "warrantyMonthsOnPurchase": null,
    "serviceHistory": null,
    "plate": "65",
    "yearOfManufacture": "2015",
    "interiorCondition": null,
    "tyreCondition": null,
    "bodyCondition": null,
    "exDemo": null,
    "keys": null,
    "v5Certificate": null,
    "previousOwners": null,
    "driverPosition": null,
    "axleConfiguration": null,
    "upholstery": null,
    "interiorColour": null,
    "exteriorFinish": null,
    "lastServiceOdometerReadingMiles": null,
    "lastServiceDate": null,
    "chassisMake": null,
    "chassisModel": null,
    "bedroomLayout": null,
    "endLayout": null,
    "bedrooms": null,
    "berths": null,
    "standard": {
        "make": "Audi",
        "model": "A4",
        "generation": null,
        "derivative": null,
        "trim": "S line",
        "bodyType": "Saloon",
        "fuelType": "Diesel",
        "transmissionType": "Manual",
        "cabType": null,
        "drivetrain": "Front Wheel Drive",
        "colour": "Black",
        "style": null,
        "subStyle": null
    }
},
"advertiser": {
    "advertiserId": "66897"
},
"adverts": {
    "forecourtPrice": {
        "amountGBP": null
    },
    "purchasePrice": {
        "amountGBP": null
    },
    "preparationCosts": {
        "amountGBP": null
    },
    "dueDate": null,
    "stockInDate": null,
    "stockInValue": {
        "amountGBP": null
    },
    "soldDate": null,
    "soldPrice": {
        "amountGBP": null
    },
    "buyerPostcode": null,
    "manufacturerApproved": null,
    "twelveMonthsMot": null,
    "motInsurance": null,
    "reservationStatus": null,
    "retailAdverts": {
          "price": {
            "amountGBP": 10498
          },
          "totalPrice": {
            "amountGBP": 10598
          },
          "adminFee": {
            "amountGBP": 100
          },
        "priceOnApplication": null,
        "manufacturerRRP": {
            "amountGBP": null
        },
        "vatExcluded": false,
        "attentionGrabber": null,
        "description": null,
        "description2": null,
        "autotraderAdvert": {
            "status": "NOT_PUBLISHED"
        },
        "advertiserAdvert": {
            "status": "NOT_PUBLISHED"
        },
        "locatorAdvert": {
            "status": "NOT_PUBLISHED"
        },
        "exportAdvert": {
            "status": "NOT_PUBLISHED"
        },
        "profileAdvert": {
            "status": "NOT_PUBLISHED"
        },
        "displayOptions": {
            "excludePreviousOwners": false,
            "excludeStrapline": false,
            "excludeMot": false,
            "excludeWarranty": false,
            "excludeInteriorDetails": false,
            "excludeTyreCondition": false,
            "excludeBodyCondition": false
        }
    }
},
"metadata": {
    "stockId": "2c9299d1744ec0a90174587a2fbb3524",
    "searchId": "202009043303511",
    "externalStockId": null,
    "externalStockReference": null,
    "lastUpdated": "2020-09-04T09:37:16.731Z",
    "lastUpdatedByAdvertiser": "2020-09-04T09:37:16.728Z",
    "versionNumber": 1,
    "lifecycleState": "FORECOURT",
    "dateOnForecourt": "2020-09-04"
},
"features": [],
"media": {
    "videoUrl": null,
    "images": []
}
</code>```

}

答:
The issue you are having is not with PHP Curl - it is returning your object results correctly.

It sounds like you only want to return the result if the status is PUBLISHED. To accomplish this you would do something like this:

```<code><?php
      public function list_cars($count = 8, $page = 1)
{
    $core = new Core();
    $cars = $core->send_request('/service/stock-management/stock?&advertiserId=' . $core->advertiser_id . '&pageSize=' . $count . '&page=' . $page);

//    return json_decode($cars);

   $results = json_decode($cars, true);

   $status = $results['adverts']['retailAdverts']['advertiserAdvert']['status'];

   if($status == 'PUBLISHED')
   {
        //return object data
       $results = $results;
   }
   else
   {
       //return nothing
        $results = null;
   }

   return $results;

}

?>
</code>```

Title: PHP Curl Json Filtering

Body:
So basically I have taken over a client's website and Autotrader has made some changes to their API. I can no longer filter out the results with a link. I have never in my life used PHP Curl and the furthest I have gone with PHP is Form validation.

This is the old code I could use:

      public function list_cars($count = 8, $page = 1)
{
    $core = new Core();
    $cars = $core->send_request('/service/stock-management/search?advertisingLocation=autotraderCars&advertiserId=' . $core->advertiser_id . '&pageSize=' . $count . '&page=' . $page);

    return json_decode($cars);

}

This is the new code I have to use:

      public function list_cars($count = 8, $page = 1)
{
    $core = new Core();
    $cars = $core->send_request('/service/stock-management/stock?&advertiserId=' . $core->advertiser_id . '&pageSize=' . $count . '&page=' . $page);

    return json_decode($cars);

}

My problem is that with the new code it is displaying all of the previous Ads for cars that are no longer on the website (Data must still be held even after a car sale)

In order to filter through the ads i need to do this:

    "adverts": {
         "retailAdverts": {
             "autotraderAdvert": {
                   "status": "PUBLISHED"

            }

How on earth do I translate this into PHP Curl??

This is the line of code i have almost been certain i need to add but im so far from correct:

    json_decode($cars)->adverts->retailAdverts->autotraderAdvert->status == 'PUBLISHED'

The response below is from a full lookup submission

    {
"vehicle": {
    "ownershipCondition": "Used",
    "registration": "AB12CDE",
    "vin": "WAUZXXXXXXXXX12345",
    "make": "Audi",
    "model": "A4",
    "generation": null,
    "derivative": "2.0 TDI ultra S line Saloon 4dr Diesel Manual (109 g/km, 161 bhp)",
    "derivativeId": "09ab072a937c3594b5e8c64251bde2eb",
    "vehicleType": "Car",
    "trim": "S line",
    "bodyType": "Saloon",
    "fuelType": "Diesel",
    "cabType": null,
    "transmissionType": "Manual",
    "wheelbaseType": null,
    "roofHeightType": null,
    "drivetrain": "Front Wheel Drive",
    "seats": 5,
    "doors": 4,
    "co2EmissionGPKM": 109,
    "topSpeedMPH": 140,
    "zeroToSixtyMPHSeconds": 8.3,
    "zeroToOneHundredKMPHSeconds": 8.4,
    "badgeEngineSizeLitres": 2.0,
    "engineCapacityCC": 1968,
    "enginePowerBHP": 161,
    "fuelCapacityLitres": 63.0,
    "emissionClass": "Euro 6",
    "owners": 1,
    "fuelEconomyNEDCExtraUrbanMPG": 74.3,
    "fuelEconomyNEDCUrbanMPG": 56.5,
    "fuelEconomyNEDCCombinedMPG": null,
    "fuelEconomyWLTPLowMPG": null,
    "fuelEconomyWLTPMediumMPG": null,
    "fuelEconomyWLTPHighMPG": null,
    "fuelEconomyWLTPExtraHighMPG": null,
    "fuelEconomyWLTPCombinedMPG": null,
    "bootSpaceSeatsUpLitres": 480.0,
    "insuranceGroup": "29",
    "insuranceSecurityCode": "E",
    "firstRegistrationDate": "2015-09-15",
    "colour": "Black",
    "style": null,
    "subStyle": null,
    "lengthMM": 4701,
    "heightMM": 1427,
    "widthMM": 2040,
    "payloadLengthMM": null,
    "payloadWidthMM": null,
    "payloadHeightMM": null,
    "payloadWeightKG": null,
    "minimumKerbWeightKG": 1540,
    "grossVehicleWeightKG": null,
    "cylinders": 4,
    "bootSpaceSeatsDownLitres": 962.0,
    "odometerReadingMiles": null,
    "motExpiryDate": null,
    "warrantyMonthsOnPurchase": null,
    "serviceHistory": null,
    "plate": "65",
    "yearOfManufacture": "2015",
    "interiorCondition": null,
    "tyreCondition": null,
    "bodyCondition": null,
    "exDemo": null,
    "keys": null,
    "v5Certificate": null,
    "previousOwners": null,
    "driverPosition": null,
    "axleConfiguration": null,
    "upholstery": null,
    "interiorColour": null,
    "exteriorFinish": null,
    "lastServiceOdometerReadingMiles": null,
    "lastServiceDate": null,
    "chassisMake": null,
    "chassisModel": null,
    "bedroomLayout": null,
    "endLayout": null,
    "bedrooms": null,
    "berths": null,
    "standard": {
        "make": "Audi",
        "model": "A4",
        "generation": null,
        "derivative": null,
        "trim": "S line",
        "bodyType": "Saloon",
        "fuelType": "Diesel",
        "transmissionType": "Manual",
        "cabType": null,
        "drivetrain": "Front Wheel Drive",
        "colour": "Black",
        "style": null,
        "subStyle": null
    }
},
"advertiser": {
    "advertiserId": "66897"
},
"adverts": {
    "forecourtPrice": {
        "amountGBP": null
    },
    "purchasePrice": {
        "amountGBP": null
    },
    "preparationCosts": {
        "amountGBP": null
    },
    "dueDate": null,
    "stockInDate": null,
    "stockInValue": {
        "amountGBP": null
    },
    "soldDate": null,
    "soldPrice": {
        "amountGBP": null
    },
    "buyerPostcode": null,
    "manufacturerApproved": null,
    "twelveMonthsMot": null,
    "motInsurance": null,
    "reservationStatus": null,
    "retailAdverts": {
          "price": {
            "amountGBP": 10498
          },
          "totalPrice": {
            "amountGBP": 10598
          },
          "adminFee": {
            "amountGBP": 100
          },
        "priceOnApplication": null,
        "manufacturerRRP": {
            "amountGBP": null
        },
        "vatExcluded": false,
        "attentionGrabber": null,
        "description": null,
        "description2": null,
        "autotraderAdvert": {
            "status": "NOT_PUBLISHED"
        },
        "advertiserAdvert": {
            "status": "NOT_PUBLISHED"
        },
        "locatorAdvert": {
            "status": "NOT_PUBLISHED"
        },
        "exportAdvert": {
            "status": "NOT_PUBLISHED"
        },
        "profileAdvert": {
            "status": "NOT_PUBLISHED"
        },
        "displayOptions": {
            "excludePreviousOwners": false,
            "excludeStrapline": false,
            "excludeMot": false,
            "excludeWarranty": false,
            "excludeInteriorDetails": false,
            "excludeTyreCondition": false,
            "excludeBodyCondition": false
        }
    }
},
"metadata": {
    "stockId": "2c9299d1744ec0a90174587a2fbb3524",
    "searchId": "202009043303511",
    "externalStockId": null,
    "externalStockReference": null,
    "lastUpdated": "2020-09-04T09:37:16.731Z",
    "lastUpdatedByAdvertiser": "2020-09-04T09:37:16.728Z",
    "versionNumber": 1,
    "lifecycleState": "FORECOURT",
    "dateOnForecourt": "2020-09-04"
},
"features": [],
"media": {
    "videoUrl": null,
    "images": []
}

}

Body:
The issue you are having is not with PHP Curl - it is returning your object results correctly.

It sounds like you only want to return the result if the status is PUBLISHED. To accomplish this you would do something like this:

<?php
      public function list_cars($count = 8, $page = 1)
{
    $core = new Core();
    $cars = $core->send_request('/service/stock-management/stock?&advertiserId=' . $core->advertiser_id . '&pageSize=' . $count . '&page=' . $page);

//    return json_decode($cars);

   $results = json_decode($cars, true);

   $status = $results['adverts']['retailAdverts']['advertiserAdvert']['status'];

   if($status == 'PUBLISHED')
   {
        //return object data
       $results = $results;
   }
   else
   {
       //return nothing
        $results = null;
   }

   return $results;

}

?>


问:
How to change the background color of a button in an app created with react native on iOS?
I am learning to use react native with expo but at one point they ask me to make a button, the button they create looks good, they did it in android, but I want to do it in iOS and only the word changes color</p>

答:
We mostly use touchable Opacity as a button in React Native app because we have no deeper access to React Native button that's why.

Below is the use of Button made with Touchable Opacity

import React from 'react';
import { Text, StyleSheet, TouchableOpacity } from 'react-native';
import colors from '../../constants/colors';

const Button = props => { // normalText | whiteTheme
    const style = props.normalText ? { fontWeight: 'bold', fontSize: 15, fontFamily: undefined } : {}
    return (
        <TouchableOpacity style={{ ...styles.button, ...props.style, backgroundColor: props.whiteTheme ? colors.secondary : colors.primary }} onPress={props.onPress}>
            <Text style={{ ...styles.text, color: props.whiteTheme ? colors.primary : colors.secondary, ...style, ...props.textStyle }} numberOfLines={1} adjustsFontSizeToFit={true}>
                {props.title}
            </Text>
        </TouchableOpacity>
    );
}

export default Button;

const styles = StyleSheet.create({
    button: {
        backgroundColor: colors.secondary,
        height: 40,
        borderRadius: 6,
        justifyContent: 'center',
        alignItems: 'center'
    },
    text: {
        color: colors.primary,
        fontSize: 17.5,
        fontFamily: 'bold'
    },
});
```

I hope you got it!

Body:
We mostly use touchable Opacity as a button in React Native app because we have no deeper access to React Native button that's why.

Below is the use of Button made with Touchable Opacity

import React from 'react';
import { Text, StyleSheet, TouchableOpacity } from 'react-native';
import colors from '../../constants/colors';

const Button = props => { // normalText | whiteTheme
    const style = props.normalText ? { fontWeight: 'bold', fontSize: 15, fontFamily: undefined } : {}
    return (
        <TouchableOpacity style={{ ...styles.button, ...props.style, backgroundColor: props.whiteTheme ? colors.secondary : colors.primary }} onPress={props.onPress}>
            <Text style={{ ...styles.text, color: props.whiteTheme ? colors.primary : colors.secondary, ...style, ...props.textStyle }} numberOfLines={1} adjustsFontSizeToFit={true}>
                {props.title}
            </Text>
        </TouchableOpacity>
    );
}

export default Button;

const styles = StyleSheet.create({
    button: {
        backgroundColor: colors.secondary,
        height: 40,
        borderRadius: 6,
        justifyContent: 'center',
        alignItems: 'center'
    },
    text: {
        color: colors.primary,
        fontSize: 17.5,
        fontFamily: 'bold'
    },
});

I hope you got it!


问:
Adding a number with a plus button
I want to make a button that will ad a number to existing field. My code:

HTML:

```<code><div class="str">
    <div class="str-img"><div>10</div></div>
    <div class="stat-plus"><img src="images/plus.png" alt="Plus"></div>
    <div class="stat-minus"><img src="images/minus.png" alt="Minus"></div>
    <input type="hidden" name="register-str" value="10">
</div>
</code>```

JAVASCRIPT:

```<code>$(document).ready(function() {
    $('.str .stat-plus img').click(function() {
        var val = $('.str-img div').val();
        var new_val = parseInt($('.str-img div').val(),10) + 1 ;
        $('.str-img div').val(new_val);
    });
});
</code>```

答:
Use .text() to the get the div's text instead of .val() which is use to get the value of an element. Try this. I've completed the function with both increment and decrement capabilities.

$(document).ready(function() {
    $('.stat-plus, .stat-minus', '.str').click(function() {
        var $display = $('.str-img div');
        var new_val = parseInt($display.text()) + ($(this).is('.stat-plus') ? 1 : -1);
        $display.text(new_val);
    });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="str">
    <div class="str-img"><div>10</div></div>
    <div class="stat-plus"><img src="images/plus.png" alt="Plus"></div>
    <div class="stat-minus"><img src="images/minus.png" alt="Minus"></div>
    <input type="hidden" name="register-str" value="10">
</div></code>```

Title: Adding a number with a plus button

Body:
I want to make a button that will ad a number to existing field. My code:

HTML:

10

    <input type="hidden" name="register-str" value="10">

JAVASCRIPT:

$(document).ready(function() {
    $('.str .stat-plus img').click(function() {
        var val = $('.str-img div').val();
        var new_val = parseInt($('.str-img div').val(),10) + 1 ;
        $('.str-img div').val(new_val);
    });
});

Body:
Use .text() to the get the div's text instead of .val() which is use to get the value of an element. Try this. I've completed the function with both increment and decrement capabilities.

$(document).ready(function() {
    $('.stat-plus, .stat-minus', '.str').click(function() {
        var $display = $('.str-img div');
        var new_val = parseInt($display.text()) + ($(this).is('.stat-plus') ? 1 : -1);
        $display.text(new_val);
    });
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="str">
    <div class="str-img"><div>10</div></div>
    <div class="stat-plus"><img src="images/plus.png" alt="Plus"></div>
    <div class="stat-minus"><img src="images/minus.png" alt="Minus"></div>
    <input type="hidden" name="register-str" value="10">
</div>


问:
ROS2 `colcon build` could not generate hpp files
I followed the tutorial: https://docs.ros.org/en/foxy/Tutorials/Custom-ROS2-Interfaces.html to create custom msg and srv, and use colcon build to compile the package, however, I found there is no hpp file generated to use in other packages. For example, I have package agv_interfaces to maintain custom msg and srv. I have CMakeLists.txt as:

```<code>cmake_minimum_required(VERSION 3.5)
project(agv_interfaces)

# Default to C99
if(NOT CMAKE_C_STANDARD)
  set(CMAKE_C_STANDARD 99)
endif()

# Default to C++14
if(NOT CMAKE_CXX_STANDARD)
  set(CMAKE_CXX_STANDARD 14)
endif()

if(CMAKE_COMPILER_IS_GNUCXX OR CMAKE_CXX_COMPILER_ID MATCHES "Clang")
  add_compile_options(-Wall -Wextra -Wpedantic)
endif()

# find dependencies
find_package(ament_cmake REQUIRED)
find_package(rosidl_default_generators REQUIRED)

rosidl_generate_interfaces(${PROJECT_NAME}
  "msg/AgvJoy.msg"
  "srv/JoyLimit.srv"
)

if(BUILD_TESTING)
  find_package(ament_lint_auto REQUIRED)
  # the following line skips the linter which checks for copyrights
  # uncomment the line when a copyright and license is not present in all source files
  #set(ament_cmake_copyright_FOUND TRUE)
  # the following line skips cpplint (only works in a git repo)
  # uncomment the line when this package is not in a git repo
  #set(ament_cmake_cpplint_FOUND TRUE)
  ament_lint_auto_find_test_dependencies()
endif()

ament_package()

</code>```

and its package.xml is as:

```<code><?xml version="1.0"?>
<?xml-model href="http://download.ros.org/schema/package_format3.xsd" schematypens="http://www.w3.org/2001/XMLSchema"?>
<package format="3">
  <name>agv_interfaces</name>
  <version>0.0.0</version>
  <description>TODO: Package description</description>
  <maintainer email="zhoudingjiang@gmail.com">taipan</maintainer>
  <license>TODO: License declaration</license>

  <buildtool_depend>ament_cmake</buildtool_depend>
  <build_depend>rosidl_default_generators</build_depend>
  <exec_depend>rosidl_default_runtime</exec_depend>
  <member_of_group>rosidl_interface_packages</member_of_group>
  <test_depend>ament_lint_auto</test_depend>
  <test_depend>ament_lint_common</test_depend>

  <export>
    <build_type>ament_cmake</build_type>
  </export>
</package>
</code>```

The command:

```<code>colcon build --packages-select agv_interfaces
</code>```

is able to build this package, however, there is no *.hpp file be generated. The official tutorial does not mention this neither. Follow the tutorial, I can use command:

```<code>ros2 interface show agv_interfaces/msg/AgvJoy
</code>```

to see how is my message defined, so far so good.
So I tried to use this interface in other packages joystick, I have CMakeLists.txt:

```<code>cmake_minimum_required(VERSION 3.5)
project(joystick)

# Default to C99
if(NOT CMAKE_C_STANDARD)
  set(CMAKE_C_STANDARD 99)
endif()

# Default to C++17
if(NOT CMAKE_CXX_STANDARD)
  set(CMAKE_CXX_STANDARD 17)
endif()

if(CMAKE_COMPILER_IS_GNUCXX OR CMAKE_CXX_COMPILER_ID MATCHES "Clang")
  add_compile_options(-Wall -Wextra -Wpedantic)
endif()

# find dependencies
find_package(ament_cmake REQUIRED)
find_package(rclcpp REQUIRED)
find_package(agv_interfaces REQUIRED)

include_directories(./include/)

# --------------------------------
add_executable(
  joy_node
  "src/joy.cpp"
  "src/joy-node.cpp"
)

ament_target_dependencies(
  joy_node
  rclcpp
  agv_interfaces
)

install(TARGETS joy_node
  DESTINATION lib/${PROJECT_NAME}
)

if(BUILD_TESTING)
  find_package(ament_lint_auto REQUIRED)
  ament_lint_auto_find_test_dependencies()
endif()

ament_package()
</code>```

and package.xml:

```<code><?xml version="1.0"?>
<?xml-model href="http://download.ros.org/schema/package_format3.xsd" schematypens="http://www.w3.org/2001/XMLSchema"?>
<package format="3">
  <name>joystick</name>
  <version>0.0.0</version>
  <description>AGV Joystick</description>
  <maintainer email="zhoudingjiang@gmail.com">ros2-agv</maintainer>
  <license>MIT</license>

  <buildtool_depend>ament_cmake</buildtool_depend>

  <depend>agv_interfaces</depend>
  <test_depend>ament_lint_auto</test_depend>
  <test_depend>ament_lint_common</test_depend>
  <member_of_group>rosidl_interface_packages</member_of_group>

  <export>
    <build_type>ament_cmake</build_type>
  </export>
</package>
</code>```

Then I use colon build, I see error:

```<code>In file included from /home/taipan/ros2-ws/src/joystick/src/joy.cpp:1:
/home/taipan/ros2-ws/src/joystick/./include/joystick/joy.h:3:10: fatal error: agv_interfaces/msg/agvjoy.hpp: No such file or directory
    3 | #include "agv_interfaces/msg/agvjoy.hpp"
      |          ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
compilation terminated.
make[2]: *** [CMakeFiles/joy_node.dir/build.make:63: CMakeFiles/joy_node.dir/src/joy.cpp.o] Error 1
make[2]: *** Waiting for unfinished jobs....
In file included from /home/taipan/ros2-ws/src/joystick/src/joy-node.cpp:1:
/home/taipan/ros2-ws/src/joystick/./include/joystick/joy.h:3:10: fatal error: agv_interfaces/msg/agvjoy.hpp: No such file or directory
    3 | #include "agv_interfaces/msg/agvjoy.hpp"
      |          ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
compilation terminated.
make[2]: *** [CMakeFiles/joy_node.dir/build.make:76: CMakeFiles/joy_node.dir/src/joy-node.cpp.o] Error 1
make[1]: *** [CMakeFiles/Makefile2:78: CMakeFiles/joy_node.dir/all] Error 2
make: *** [Makefile:141: all] Error 2
</code>```

Some official ROS2 document says I should use rosidl_generator_cpp instead of rosidl_default_generators, but how?

答:
Just complementing @zhoudingjang's answer, in case it helps someone, cause it took me forever.

In my case, I had a "custom_msgs/msg/RadarOdometry.msg" custom msg, but when trying to include it, I had to include it as

```<code>#include "custom_msgs/msg/radar_odometry.hpp"
</code>```

Apparently, ros2 does a renaming thingy when compiling messages.

Body:
I followed the tutorial: https://docs.ros.org/en/foxy/Tutorials/Custom-ROS2-Interfaces.html to create custom msg and srv, and use colcon build to compile the package, however, I found there is no hpp file generated to use in other packages. For example, I have package agv_interfaces to maintain custom msg and srv. I have CMakeLists.txt as:

cmake_minimum_required(VERSION 3.5)
project(agv_interfaces)

# Default to C99
if(NOT CMAKE_C_STANDARD)
  set(CMAKE_C_STANDARD 99)
endif()

# Default to C++14
if(NOT CMAKE_CXX_STANDARD)
  set(CMAKE_CXX_STANDARD 14)
endif()

if(CMAKE_COMPILER_IS_GNUCXX OR CMAKE_CXX_COMPILER_ID MATCHES "Clang")
  add_compile_options(-Wall -Wextra -Wpedantic)
endif()

# find dependencies
find_package(ament_cmake REQUIRED)
find_package(rosidl_default_generators REQUIRED)

rosidl_generate_interfaces(${PROJECT_NAME}
  "msg/AgvJoy.msg"
  "srv/JoyLimit.srv"
)

if(BUILD_TESTING)
  find_package(ament_lint_auto REQUIRED)
  # the following line skips the linter which checks for copyrights
  # uncomment the line when a copyright and license is not present in all source files
  #set(ament_cmake_copyright_FOUND TRUE)
  # the following line skips cpplint (only works in a git repo)
  # uncomment the line when this package is not in a git repo
  #set(ament_cmake_cpplint_FOUND TRUE)
  ament_lint_auto_find_test_dependencies()
endif()

ament_package()

and its package.xml is as:

<?xml version="1.0"?>
<?xml-model href="http://download.ros.org/schema/package_format3.xsd" schematypens="http://www.w3.org/2001/XMLSchema"?>
<package format="3">
  <name>agv_interfaces</name>
  <version>0.0.0</version>
  <description>TODO: Package description</description>
  <maintainer email="zhoudingjiang@gmail.com">taipan</maintainer>
  <license>TODO: License declaration</license>

  <buildtool_depend>ament_cmake</buildtool_depend>
  <build_depend>rosidl_default_generators</build_depend>
  <exec_depend>rosidl_default_runtime</exec_depend>
  <member_of_group>rosidl_interface_packages</member_of_group>
  <test_depend>ament_lint_auto</test_depend>
  <test_depend>ament_lint_common</test_depend>

  <export>
    <build_type>ament_cmake</build_type>
  </export>
</package>

The command:

colcon build --packages-select agv_interfaces

is able to build this package, however, there is no *.hpp file be generated. The official tutorial does not mention this neither. Follow the tutorial, I can use command:

ros2 interface show agv_interfaces/msg/AgvJoy

to see how is my message defined, so far so good.
So I tried to use this interface in other packages joystick, I have CMakeLists.txt:

cmake_minimum_required(VERSION 3.5)
project(joystick)

# Default to C99
if(NOT CMAKE_C_STANDARD)
  set(CMAKE_C_STANDARD 99)
endif()

# Default to C++17
if(NOT CMAKE_CXX_STANDARD)
  set(CMAKE_CXX_STANDARD 17)
endif()

if(CMAKE_COMPILER_IS_GNUCXX OR CMAKE_CXX_COMPILER_ID MATCHES "Clang")
  add_compile_options(-Wall -Wextra -Wpedantic)
endif()

# find dependencies
find_package(ament_cmake REQUIRED)
find_package(rclcpp REQUIRED)
find_package(agv_interfaces REQUIRED)

include_directories(./include/)

# --------------------------------
add_executable(
  joy_node
  "src/joy.cpp"
  "src/joy-node.cpp"
)

ament_target_dependencies(
  joy_node
  rclcpp
  agv_interfaces
)

install(TARGETS joy_node
  DESTINATION lib/${PROJECT_NAME}
)

if(BUILD_TESTING)
  find_package(ament_lint_auto REQUIRED)
  ament_lint_auto_find_test_dependencies()
endif()

ament_package()

and package.xml:

<?xml version="1.0"?>
<?xml-model href="http://download.ros.org/schema/package_format3.xsd" schematypens="http://www.w3.org/2001/XMLSchema"?>
<package format="3">
  <name>joystick</name>
  <version>0.0.0</version>
  <description>AGV Joystick</description>
  <maintainer email="zhoudingjiang@gmail.com">ros2-agv</maintainer>
  <license>MIT</license>

  <buildtool_depend>ament_cmake</buildtool_depend>

  <depend>agv_interfaces</depend>
  <test_depend>ament_lint_auto</test_depend>
  <test_depend>ament_lint_common</test_depend>
  <member_of_group>rosidl_interface_packages</member_of_group>

  <export>
    <build_type>ament_cmake</build_type>
  </export>
</package>

Then I use colon build, I see error:

In file included from /home/taipan/ros2-ws/src/joystick/src/joy.cpp:1:
/home/taipan/ros2-ws/src/joystick/./include/joystick/joy.h:3:10: fatal error: agv_interfaces/msg/agvjoy.hpp: No such file or directory
    3 | #include "agv_interfaces/msg/agvjoy.hpp"
      |          ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
compilation terminated.
make[2]: *** [CMakeFiles/joy_node.dir/build.make:63: CMakeFiles/joy_node.dir/src/joy.cpp.o] Error 1
make[2]: *** Waiting for unfinished jobs....
In file included from /home/taipan/ros2-ws/src/joystick/src/joy-node.cpp:1:
/home/taipan/ros2-ws/src/joystick/./include/joystick/joy.h:3:10: fatal error: agv_interfaces/msg/agvjoy.hpp: No such file or directory
    3 | #include "agv_interfaces/msg/agvjoy.hpp"
      |          ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
compilation terminated.
make[2]: *** [CMakeFiles/joy_node.dir/build.make:76: CMakeFiles/joy_node.dir/src/joy-node.cpp.o] Error 1
make[1]: *** [CMakeFiles/Makefile2:78: CMakeFiles/joy_node.dir/all] Error 2
make: *** [Makefile:141: all] Error 2

Some official ROS2 document says I should use rosidl_generator_cpp instead of rosidl_default_generators, but how?

Body:
Just complementing @zhoudingjang's answer, in case it helps someone, cause it took me forever.

In my case, I had a "custom_msgs/msg/RadarOdometry.msg" custom msg, but when trying to include it, I had to include it as

#include "custom_msgs/msg/radar_odometry.hpp"

Apparently, ros2 does a renaming thingy when compiling messages.


问:
Attempt to allocate character string giving me a segmentation fault
Screenshot of attempted code

This function is pretty simple and is just assigning string values to an array after allocating memory to the array, yet whenever the function is loaded the program gives me a segmentation fault? Can someone explain as to why that is?

Here is a copy of my code:

```<code>char* generateSent(char ** noun, char ** verb, char ** adjective, char ** preposition, char **
article, int nounsize, int verbsize, int adjsize, int prepositionsize, int articlesize)
{
  char *sent = malloc(sizeof(char *) * 100);
  strcpy(generateSent, article[(rand()%articlesize)]);
  strcat(generateSent, adjective[(rand()%adjsize)]);
  strcat(generateSent, noun[(rand()%nounsize)]);
  strcat(generateSent, verb[(rand()%verbsize)]);
  strcat(generateSent, preposition[(rand()%prepositionsize)]);
  strcat(generateSent, article[(rand()%articlesize)]);
  strcat(generateSent, adjective[(rand()%adjsize)]);
  strcat(generateSent, noun[(rand()%nounsize)]);
  strcpy(generateSent,sent);
  free(generateSent);
}
</code>```

Thanks for the input.

答:
You use function name in all strcats. Unlike visual basic, it is invalid in 'c'.
So, you did several mistakes:

writing data into address where your function is allocated by strcat. Probably causes segmentation fault.

pointer 'sent' is allocated but not used. It is a waste of memory.

your function does not return any data.

free in the function destroys data before return.

I will re-write your code in a correct but untested way.

```<code>char* generateSent(char ** noun, char ** verb, char ** adjective, char ** preposition, char **
article, int nounsize, int verbsize, int adjsize, int prepositionsize, int articlesize)
{
  char *sent = malloc(sizeof(char) * 100); // sizeof(char) makes more sense, you allocate an arry of characters.
</code>```

To do the very first write you either have to initialize the string:

```<code>  *sent = 0;
  strcat(sent, article[(rand()%articlesize)]);
</code>```

or use strcpy

```<code>  strcpy(sent, article[(rand()%articlesize)]);
</code>```

As for the rest you should do strcat into sent to add to the end of the
string.

```<code>  strcat(sent, adjective[(rand()%adjsize)]);
  strcat(sent, noun[(rand()%nounsize)]);

  ...
</code>```

At the end you need to return the sent

```<code>   return sent;
}
</code>```

The issue is that you cannot free it in the function. As soon as free is done, the data becomes invalid. As a result, freeing of the data is a function of the caller after the data is used. So, no free in the function.

Body:
Screenshot of attempted code

This function is pretty simple and is just assigning string values to an array after allocating memory to the array, yet whenever the function is loaded the program gives me a segmentation fault? Can someone explain as to why that is?

Here is a copy of my code:

char* generateSent(char ** noun, char ** verb, char ** adjective, char ** preposition, char **
article, int nounsize, int verbsize, int adjsize, int prepositionsize, int articlesize)
{
  char *sent = malloc(sizeof(char *) * 100);
  strcpy(generateSent, article[(rand()%articlesize)]);
  strcat(generateSent, adjective[(rand()%adjsize)]);
  strcat(generateSent, noun[(rand()%nounsize)]);
  strcat(generateSent, verb[(rand()%verbsize)]);
  strcat(generateSent, preposition[(rand()%prepositionsize)]);
  strcat(generateSent, article[(rand()%articlesize)]);
  strcat(generateSent, adjective[(rand()%adjsize)]);
  strcat(generateSent, noun[(rand()%nounsize)]);
  strcpy(generateSent,sent);
  free(generateSent);
}

Thanks for the input.

Body:
You use function name in all strcats. Unlike visual basic, it is invalid in 'c'.
So, you did several mistakes:

writing data into address where your function is allocated by strcat. Probably causes segmentation fault.

pointer 'sent' is allocated but not used. It is a waste of memory.

your function does not return any data.

free in the function destroys data before return.

I will re-write your code in a correct but untested way.

char* generateSent(char ** noun, char ** verb, char ** adjective, char ** preposition, char **
article, int nounsize, int verbsize, int adjsize, int prepositionsize, int articlesize)
{
  char *sent = malloc(sizeof(char) * 100); // sizeof(char) makes more sense, you allocate an arry of characters.

To do the very first write you either have to initialize the string:

  *sent = 0;
  strcat(sent, article[(rand()%articlesize)]);

or use strcpy

  strcpy(sent, article[(rand()%articlesize)]);

As for the rest you should do strcat into sent to add to the end of the
string.

  strcat(sent, adjective[(rand()%adjsize)]);
  strcat(sent, noun[(rand()%nounsize)]);

  ...

At the end you need to return the sent

   return sent;
}

The issue is that you cannot free it in the function. As soon as free is done, the data becomes invalid. As a result, freeing of the data is a function of the caller after the data is used. So, no free in the function.