问:
how to position row in the middle react semantic ui
how would i position the row to be in the middle using react semantic ui grid row? Wondering if there is another way besides increasing the padding-top until it reaches the middle</p>

```<code><Container>
        <Grid columns={4} divided>
          <Grid.Row>TITLE</Grid.Row>
          <Grid.Row>
            <Grid.Column width={4} color="violet" textAlign="center">
              <h3>Content</h3>
            </Grid.Column>
            <Grid.Column textAlign="center" width={4} color="violet">
              <h3>Content</h3>
            </Grid.Column>
            <Grid.Column textAlign="center" width={4} color="violet">
              <h3>Content</h3>
            </Grid.Column>
            <Grid.Column textAlign="center" width={4} color="violet">
              <h3>Content</h3>
            </Grid.Column>
          </Grid.Row>
        </Grid>
      </Container>
</code>```

答:
You can use verticalAlign prop and provide a value middle to the Grid.Row to solve your issue. Also make sure to provide a height to the grid.

As per documentation:

A grid can specify its vertical alignment to have all its columns vertically centered.

A row can specify its vertical alignment to have all its columns vertically centered.

Working demo is here

<Container style={{ height: "100vh", background: "lightblue" }}>
    <Grid
      style={{ height: "400px", background: "gray" }}
      columns={4}
      divided
      padded={false}
    >
      <Grid.Row verticalAlign="middle">
        <Grid.Column width={4} color="violet" textAlign="center">

Content

        </Grid.Column>
        <Grid.Column textAlign="center" width={4} color="violet">

Content

        </Grid.Column>
        <Grid.Column textAlign="center" width={4} color="violet">

Content

        </Grid.Column>
        <Grid.Column textAlign="center" width={4} color="violet">

Content

        </Grid.Column>
      </Grid.Row>
    </Grid>
  </Container>
```

Body:
how would i position the row to be in the middle using react semantic ui grid row? Wondering if there is another way besides increasing the padding-top until it reaches the middle

<Container>
        <Grid columns={4} divided>
          <Grid.Row>TITLE</Grid.Row>
          <Grid.Row>
            <Grid.Column width={4} color="violet" textAlign="center">

Content

            </Grid.Column>
            <Grid.Column textAlign="center" width={4} color="violet">

Content

            </Grid.Column>
            <Grid.Column textAlign="center" width={4} color="violet">

Content

            </Grid.Column>
            <Grid.Column textAlign="center" width={4} color="violet">

Content

            </Grid.Column>
          </Grid.Row>
        </Grid>
      </Container>

Body:
You can use verticalAlign prop and provide a value middle to the Grid.Row to solve your issue. Also make sure to provide a height to the grid.

As per documentation:

A grid can specify its vertical alignment to have all its columns vertically centered.

A row can specify its vertical alignment to have all its columns vertically centered.

Working demo is here

<Container style={{ height: "100vh", background: "lightblue" }}>
    <Grid
      style={{ height: "400px", background: "gray" }}
      columns={4}
      divided
      padded={false}
    >
      <Grid.Row verticalAlign="middle">
        <Grid.Column width={4} color="violet" textAlign="center">
          <h3>Content</h3>
        </Grid.Column>
        <Grid.Column textAlign="center" width={4} color="violet">
          <h3>Content</h3>
        </Grid.Column>
        <Grid.Column textAlign="center" width={4} color="violet">
          <h3>Content</h3>
        </Grid.Column>
        <Grid.Column textAlign="center" width={4} color="violet">
          <h3>Content</h3>
        </Grid.Column>
      </Grid.Row>
    </Grid>
  </Container>


来源: stackexchange

问:
Remove duplicate values in each column in every row pandas python
I have 4 columns ( Name, Area, State, Email). In column Email has duplicate email after i group by and join the value. The output turns out to be:

```<code>Area    Group   Shift         Email
KM      MFG     A1,A2,A3      a@gmail.com,a@gmail.com,b@gmail.com
RIM     TEST    A1,B1         c@gmail.com,b@gmail.com,c@gmail.com
PNG    FINISH   C1,C2,C3      a@gmail.com,c@gmail.com,a@gmail.com
KL     Manager  NORMAL,B1,B1  b@gmail.com,a@gmail.com,c@gmail.com,a@gmail.com
</code>```

I need to remove the duplicate email in column 'Email'. Anyone can help me?

答:
IIUC, you need this:

```<code>df['Email'] = df['Email'].str.split(',').apply(lambda x: ','.join(set(x)))
</code>```

Output:

```<code>  Area    Group         Shift                                Email
0   KM      MFG      A1,A2,A3              a@gmail.com,b@gmail.com
1  RIM     TEST         A1,B1              c@gmail.com,b@gmail.com
2  PNG   FINISH      C1,C2,C3              a@gmail.com,c@gmail.com
3   KL  Manager  NORMAL,B1,B1  a@gmail.com,c@gmail.com,b@gmail.com
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have 4 columns ( Name, Area, State, Email). In column Email has duplicate email after i group by and join the value. The output turns out to be:

Area    Group   Shift         Email
KM      MFG     A1,A2,A3      a@gmail.com,a@gmail.com,b@gmail.com
RIM     TEST    A1,B1         c@gmail.com,b@gmail.com,c@gmail.com
PNG    FINISH   C1,C2,C3      a@gmail.com,c@gmail.com,a@gmail.com
KL     Manager  NORMAL,B1,B1  b@gmail.com,a@gmail.com,c@gmail.com,a@gmail.com

I need to remove the duplicate email in column 'Email'. Anyone can help me?

Body:
IIUC, you need this:

df['Email'] = df['Email'].str.split(',').apply(lambda x: ','.join(set(x)))

Output:

  Area    Group         Shift                                Email
0   KM      MFG      A1,A2,A3              a@gmail.com,b@gmail.com
1  RIM     TEST         A1,B1              c@gmail.com,b@gmail.com
2  PNG   FINISH      C1,C2,C3              a@gmail.com,c@gmail.com
3   KL  Manager  NORMAL,B1,B1  a@gmail.com,c@gmail.com,b@gmail.com


问:
RichText WYSIWYG editor without UI (JavaScript API only)
I am looking for a very clean project to add cross-browser JavaScript API to contenteditable div.

If it has UI, then it should be possible not to load it (as opposed to disabling it) or completely remove from sources.

I am looking for basic features really without huge focus on backward-compatibility but rather a cleaner code.

Some of the features, I would expect from this API would be:

Insert HTML snippet at the position of the cursor

Clean up contents after paste (such as spans and font sizes)

Return node, where cursor currently is positioned

Add new item to item list

I suppose I could code them with some jQuery, but if someone have it, why not re-use it.

答:
What about WYMEditor?

http://www.wymeditor.org/

https://github.com/wymeditor/wymeditor

http://files.wymeditor.org/wymeditor/trunk/src/examples/12-custom-layout.html

http://files.wymeditor.org/wymeditor/trunk/src/examples/

ContentLicense: CC BY-SA 3.0


问:
How to normalize working tree line endings in Git?
I have cloned a repository that had inconsistend line endings. I have added a .gitattributes that sets the text attribute for the files I want to normalize. Now when I commit changes I get the message:

```<code>warning: CRLF will be replaced by LF in FILE.
The file will have its original line endings in your working directory.
</code>```

How can I make git normalize my working copy of the file for me? Preferably I would like git to normalize the entire working tree.

答: The merge.renormalize configuration setting may be useful.

Body:
I have cloned a repository that had inconsistend line endings. I have added a .gitattributes that sets the text attribute for the files I want to normalize. Now when I commit changes I get the message:

warning: CRLF will be replaced by LF in FILE.
The file will have its original line endings in your working directory.

How can I make git normalize my working copy of the file for me? Preferably I would like git to normalize the entire working tree.


问:
Python: How do I sum integer values in a dictionary?
I am trying to write a simple program that takes a dictionary (inventory) of {item: integer}, and then sums the integer values of all the keys.

Currently, this is what I have, and it isn't working:

```<code>inventory = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 125, 'bow': 1}

def displayInventory(inventory):
    print('Welcome to your pack. Currently you have:\n')
    total_items = 0
    for k,v in inventory.items():
        total_items = total_items + v.get(v, 0)
    return total_items
    print(total_items)
</code>```

This is the error which I get:

Traceback (most recent call last):
  File "C:\Users\Kyle\Documents\displayInventory.py", line 16, in
    displayInventory(inventory)
  File "C:\Users\Kyle\Documents\displayInventory.py", line 7, in displayInventory
    total_items = total_items + v.get(v, 0)
AttributeError: 'int' object has no attribute 'get'

I am looking for someone to walk me through what I am missing, not simply give the right code to make this happen, as I can't learn this if I don't understand what is going on.

Any insight/guidance is greatly appreciated.

Thanks in advance.

答:
In your for loop, you are already destructuring each pair "k, v" stands for key and value. Hence, you're getting that error because you're trying to get your value, from the value.

Just change the body of your for loop to total_items += v and you should get what you're looking for.

Body:
I am trying to write a simple program that takes a dictionary (inventory) of {item: integer}, and then sums the integer values of all the keys.

Currently, this is what I have, and it isn't working:

inventory = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 125, 'bow': 1}

def displayInventory(inventory):
    print('Welcome to your pack. Currently you have:\n')
    total_items = 0
    for k,v in inventory.items():
        total_items = total_items + v.get(v, 0)
    return total_items
    print(total_items)

This is the error which I get:

Traceback (most recent call last):
  File "C:\Users\Kyle\Documents\displayInventory.py", line 16, in
    displayInventory(inventory)
  File "C:\Users\Kyle\Documents\displayInventory.py", line 7, in displayInventory
    total_items = total_items + v.get(v, 0)
AttributeError: 'int' object has no attribute 'get'

I am looking for someone to walk me through what I am missing, not simply give the right code to make this happen, as I can't learn this if I don't understand what is going on.

Any insight/guidance is greatly appreciated.

Thanks in advance.


问:
Clojure function not returning a map
I am new to Clojure and functional programming. I have a basic idea about the data structures in Clojure such as maps, lists, and vectors.

I am trying to write a function that returns a nested map. The map is correctly displayed inside the function. The below code is from the read-customer-file function

```<code>([input-list new-map place-holder]
        (if (not-empty input-list)
            (do
                (def string-input (str (first input-list)))
                (def cust-id (get (first input-list) 0))
                (def cust-name (get (first input-list) 1))
                (def cust-address (get (first input-list) 2))
                (def cust-phone (get (first input-list) 3))
                (def temp-map (conj new-map {(keyword cust-id) {:cust-name cust-name, :cust-address cust-address, :cust-phone cust-phone}}))
                (read-customer-file (rest input-list) temp-map ())
            )
            (do
                (map str new-map)
                ;(print (get-in new-map [:1 :cust-name]))
                (print new-map)
            )
        )
    )
</code>```

This takes an input of list of vectors as below:

```<code>([3 Fan Yuhong 165 Happy Lane 345-4533] [2 Sue Jones 43 Rose Court Street 345-7867] [1 John Smith 123 Here Street 456-4567])
</code>```

and returns  a nested-map as below:

```<code>{:3 {:cust-name Fan Yuhong, :cust-address 165 Happy Lane, :cust-phone 345-4533}, :2 {:cust-name Sue Jones, :cust-address 43 Rose Court Street, :cust-phone 345-7867}, :1 {:cust-name John Smith, :cust-address 123 Here Street, :cust-phone 456-4567}}
</code>```

This is what I am trying to achieve and is working perfectly fine within the function. However, if I try to define a variable outside the function with the value of the return type, I do not get a nested-map but a list of strings. For this, I just remove the (print new-map) part.

```<code>(do
    (map str new-map)
)
</code>```

And call it from outside the function definition as follows:

```<code>(def customer-info-list read-customer-file)
(println (customer-info-list))
</code>```

The result I get is different from what I expected and cannot perform the map-related functionalities such as get and get-in.

```<code>([:3 {:cust-name Fan Yuhong, :cust-address 165 Happy Lane, :cust-phone 345-4533}] [:2 {:cust-name Sue Jones, :cust-address 43 Rose Court Street, :cust-phone 345-7867}] [:1 {:cust-name John Smith, :cust-address 123 Here Street, :cust-phone 456-4567}])
</code>```

I would very much appreciate any kind of help with this. I am aware that my code is a bit messy and I should use let instead of def for variable names. But I am just starting Clojure and this is my first program.

UPDATE

I solved the problem. What I did is change the map into a sorted-map inside the function. So the last return from the function will be a sorted map.

```<code>(do
    (into (sorted-map) new-map)
)
</code>```

However, the returned value will still be a string if assigned to a variable., so I converted it to a sorted-map once again. Then it finally got converted to a nested-map.

```<code>(def customer-info-list read-customer-file)
(def cust-map (into (sorted-map) (customer-info-list)))
(println cust-map)
(println (get-in cust-map [:1 :cust-name]))
(println (get cust-map :2))
</code>```

The output from the above three print statements is as expected.

```<code>{:1 {:cust-name John Smith, :cust-address 123 Here Street, :cust-phone 456-4567}, :2 {:cust-name Sue Jones, :cust-address 43 Rose Court Street, :cust-phone 345-7867}, :3 {:cust-name Fan Yuhong, :cust-address 165 Happy Lane, :cust-phone 345-4533}}
John Smith
{:cust-name Sue Jones, :cust-address 43 Rose Court Street, :cust-phone 345-7867}
</code>```

答: I was able to solve the problem by converting it to a sorted-map while returning. Also, the returned value was again converted to a sorted-map which did the trick. Please check the update section.</p>

Title: Clojure function not returning a map

Body:
I am new to Clojure and functional programming. I have a basic idea about the data structures in Clojure such as maps, lists, and vectors.

I am trying to write a function that returns a nested map. The map is correctly displayed inside the function. The below code is from the read-customer-file function

([input-list new-map place-holder]
        (if (not-empty input-list)
            (do
                (def string-input (str (first input-list)))
                (def cust-id (get (first input-list) 0))
                (def cust-name (get (first input-list) 1))
                (def cust-address (get (first input-list) 2))
                (def cust-phone (get (first input-list) 3))
                (def temp-map (conj new-map {(keyword cust-id) {:cust-name cust-name, :cust-address cust-address, :cust-phone cust-phone}}))
                (read-customer-file (rest input-list) temp-map ())
            )
            (do
                (map str new-map)
                ;(print (get-in new-map [:1 :cust-name]))
                (print new-map)
            )
        )
    )

This takes an input of list of vectors as below:

([3 Fan Yuhong 165 Happy Lane 345-4533] [2 Sue Jones 43 Rose Court Street 345-7867] [1 John Smith 123 Here Street 456-4567])

and returns  a nested-map as below:

{:3 {:cust-name Fan Yuhong, :cust-address 165 Happy Lane, :cust-phone 345-4533}, :2 {:cust-name Sue Jones, :cust-address 43 Rose Court Street, :cust-phone 345-7867}, :1 {:cust-name John Smith, :cust-address 123 Here Street, :cust-phone 456-4567}}

This is what I am trying to achieve and is working perfectly fine within the function. However, if I try to define a variable outside the function with the value of the return type, I do not get a nested-map but a list of strings. For this, I just remove the (print new-map) part.

(do
    (map str new-map)
)

And call it from outside the function definition as follows:

(def customer-info-list read-customer-file)
(println (customer-info-list))

The result I get is different from what I expected and cannot perform the map-related functionalities such as get and get-in.

([:3 {:cust-name Fan Yuhong, :cust-address 165 Happy Lane, :cust-phone 345-4533}] [:2 {:cust-name Sue Jones, :cust-address 43 Rose Court Street, :cust-phone 345-7867}] [:1 {:cust-name John Smith, :cust-address 123 Here Street, :cust-phone 456-4567}])

I would very much appreciate any kind of help with this. I am aware that my code is a bit messy and I should use let instead of def for variable names. But I am just starting Clojure and this is my first program.

UPDATE

I solved the problem. What I did is change the map into a sorted-map inside the function. So the last return from the function will be a sorted map.

(do
    (into (sorted-map) new-map)
)

However, the returned value will still be a string if assigned to a variable., so I converted it to a sorted-map once again. Then it finally got converted to a nested-map.

(def customer-info-list read-customer-file)
(def cust-map (into (sorted-map) (customer-info-list)))
(println cust-map)
(println (get-in cust-map [:1 :cust-name]))
(println (get cust-map :2))

The output from the above three print statements is as expected.

{:1 {:cust-name John Smith, :cust-address 123 Here Street, :cust-phone 456-4567}, :2 {:cust-name Sue Jones, :cust-address 43 Rose Court Street, :cust-phone 345-7867}, :3 {:cust-name Fan Yuhong, :cust-address 165 Happy Lane, :cust-phone 345-4533}}
John Smith
{:cust-name Sue Jones, :cust-address 43 Rose Court Street, :cust-phone 345-7867}


问:
How to limit the number of opened documents and auto close the oldest ones in Visual Studio?
I often open too many documents (source files) in Visual Studio, and end up with a long list of tabs and couldn't find the latest one I need. It also eats a lot of memory, while I don't really need the old files open. Only the recent opened files

I wonder if Visual Studio (or an extension, free one preferred) could limit the max number of open documents, and auto close the oldest (least recent unused) ones?

I am using VS 2019 16.1.6, but willing to update to newer version if that helps.

答:
Use Tidy Tabs extension. It does exactly what I expected.

Tidy Tabs is a Visual Studio extension that keeps your document well organized by closing document tabs you are no longer using.

It has an option called "Maximum Open Tabs".

If this value is greater than 0 then Tidy Tabs will close the oldest tabs until the number of open tabs is equal to this value. The oldest tabs will be closed even if they have not exceeded the timeout value.

However the version on Marketplace only supports up to VS 2015. It is open source on Github and it supports up to VS 2017. Another fork by AndrueCope supports up to VS 2019. You need to compile them from source.


问:
Dotted border around ASP.NET Button

I have a problem with asp:button styling. I added following style:

```<code>.myAspButton    {
        background-image: url("image for button");
        width: 110px;
        height: 25px;
        color: white;
        font-weight: bold;
        vertical-align: middle;
    }
<asp:Button ID="btnAsp" runat="server" Text="hhh" CssClass="myAspButton" BackColor="Transparent" BorderStyle="None" />
</code>```

Problem is when I press button it gets that dotted border around how to remove this?

And also what property to use to change button style when button is pressed down?

答:
Have you tried adding this to the css style?</p>

```<code>border: none;
</code>```

Title: Dotted border around ASP.NET Button

Body:
I have a problem with asp:button styling. I added following style:

.myAspButton    {
        background-image: url("image for button");
        width: 110px;
        height: 25px;
        color: white;
        font-weight: bold;
        vertical-align: middle;
    }
<asp:Button ID="btnAsp" runat="server" Text="hhh" CssClass="myAspButton" BackColor="Transparent" BorderStyle="None" />

Problem is when I press button it gets that dotted border around how to remove this?

And also what property to use to change button style when button is pressed down?

Body:
Have you tried adding this to the css style?

border: none;


问:
trying to get a nested array work with react native flat list
so i got this object that i pass as data to my react native flatlist

```<code><FlatList
  extraData = {this.state}
  data = {this.state.data_n1}>
  renderItem = {({item, index}) => {
    this.state.data_n2.forEach(aux => {
      if(item.id == aux.id) {
        return(<View><Text>Display first stuff</Text></View>);
      } else {
        return(<View><Text>Display second stuff</Text></View>);
      }
    }
  }
/>
</code>```

the whole idea is compare both objects, if the data_n2 contains the same id from the data_n1, the display the data from the data_n2, if not, just display from data_n1, problem is, i'm displaying this whenever i click on a calendar strip, so if i click on day june 1st, that day should display data_n2, if i click on day june 2nd, THAT one should display the data_n1.

does this work with flatlist or virtualizedlist (if i had to swap), or i need to render a flatlist for each data?

Edit: tested hao wu answer, but got this

Edit n2: i'll post the code, but keep in mind data_n1 is this.state.listaImputacionDia and this.state.listaImputacionDia is data_n2

this is the calendar strip code

```<code><CalendarStrip
  calendarHeaderStyle={{
    fontSize: rfv(18),
    fontWeight: "normal",
    fontStyle: "normal",
    letterSpacing: 0,
    textAlign: "left",
    color: "#707070",
    paddingBottom: hp('4.5%')
  }}
  selectedDate={this.state.selectedDate}
  onDateSelected={async (date) => {
    await HoursReportHistoryBusiness.GetInstance().getListHoursReportRequest();
    this.setState({ selectedDate: moment(date).format('YYYY-MM-DD') });
    this.setViewHourHistory();
    console.log(this.state.listaImputacionDia);
  }}
  minDate={moment().subtract(3, 'days')}
  maxDate={moment().add(3,'days')}
  startingDate={moment().subtract(3, 'days')}
  useIsoWeekday={false}
  style={{paddingTop: hp('1.5%'), paddingBottom: hp('2.7%'), backgroundColor: '#ffffff'}}
  highlightDateNameStyle={{color: '#1062cc'}}
  highlightDateNumberStyle={{color: '#1062cc'}}
  disabledDateNumberStyle={{color: '#f21927'}}
  disabledDateNameStyle={{color: '#f21927'}}
  customDatesStyles={this.customDatesStyle}
  dateNameStyle={{color: '#c4c4c4'}}
  dateNumberStyle={{color: '#c4c4c4'}}
  disabledDateOpacity={1}
/>
</code>```

this is the flatlist

```<code><FlatList
  extraData={this.state.listaImputacionDia}
  data={this.state.dataSource}//{DataManager.FavoriteList[moment(this.state.selectedDate).format('YYYY-MM-DD')]}
  renderItem={({ item, index }) => {
    if (this.state.listaImputacionDia.length != 0) {
      const found = this.state.listaImputacionDia.filter(aux => item.id == aux.IdProyecto);
      //this.state.listaImputacionDia.forEach(aux => {
      if (found/*item.id == aux.IdProyecto*/) {
        console.log('la wea' + found);
        return (
          <View style={{ marginTop: hp('2%') }}>
            <TouchableOpacity style={} onPress={() => this.toggleExpanded()}>
              <View style={{ flex: 1, flexDirection: 'row', justifyContent: 'space-between' }}>
                <View style={{ flexDirection: 'column', justifyContent: 'center' }}>
                  <Text numberOfLines={2} ellipsizeMode="tail" style={}>{found.Title}</Text>
                  <Text style={}>{`ID ${found.Id} - ${found.Cliente}`}</Text>
                  {
                    !found.fav ?
                      <Text style={}>No favorito</Text>
                      : null
                  }
                </View>
                <View style={{ flexDirection: 'column', justifyContent: 'center' }}>
                  <View style={{ flexDirection: 'row', marginRight: wp('3.4%') }}>
                    <Text style={}>{`${found.HorasTrabajadas}h`}</Text>
                    <Image style={{ marginTop: hp('1%'), marginLeft: wp('3.7%') }} source={this.state.isCollapsed ? Images.expandible : Images.collapsible} />
                  </View>
                </View>
              </View>
            </TouchableOpacity>
            <Collapsible style={{
              alignSelf: 'center',
              width: wp('95.7%'),
              backgroundColor: "#ffffff",
            }} collapsed={this.state.isCollapsed}>
              <View>
                <View style={{ flexDirection: 'row' }}>
                  <Text style={}>Etapa</Text>
                  <Text style={}>Horas</Text>
                </View>
                <View style={{ flexDirection: 'row' }}>
                  <ModalDropdown
                    adjustFrame={style => {
                      style.top = (Platform.OS === 'ios' ? style.top : style.top - StatusBar.currentHeight);
                      return style;
                    }}
                    dropdownTextStyle={styles.dropdownTextStyle}
                    dropdownTextHighlightStyle={styles.dropdownTextHighlightStyle}
                    dropdownStyle={styles.dropdownStageStyle}
                    defaultValue={'Seleccionar'}
                    style={styles.dropStageStyle}
                    textStyle={{
                      padding: 0,
                      margin: 0,
                      fontSize: rfv(16),
                      paddingVertical: hp('1.2%'),
                      fontWeight: 'normal',
                      fontStyle: 'normal',
                      textAlign: 'left',
                      color: found.etapa != '' ? '#1a1a1a' : '#c4c4c4',
                    }}
                    //onSelect={(index, value) => this.setState({SeleccionClientes: value})}
                    //options={Object.keys(this.state.items)}
                    onSelect={(index, value) => this.setState({ SeleccionClientes: value })}
                    options={DataManager.ListEtapa}
                  />
                  <View style={styles.InputContainerHours}>
                    <Text style={styles.InputTextHours}>{found.HorasTrabajadas}</Text>
                  </View>
                  <TouchableOpacity style={{ marginTop: hp('0.5%'), marginLeft: wp('5.5%') }} onPress={() => this.props.onSubstract}>
                    <Image source={Images.menos_hora} />
                  </TouchableOpacity>
                  <TouchableOpacity style={{ marginTop: hp('0.5%'), marginLeft: wp('2%') }} onPress={() => this.props.onAdd}>
                    <Image source={Images.mas_hora} />
                  </TouchableOpacity>
                </View>
                <Text style={}>Observaciones</Text>
                <Input
                  autoCapitalize="none"
                  maxLength={100}
                  inputContainerStyle={styles.InputContainerComentarioOnBlur}
                  containerStyle={styles.InputComentario}
                  inputStyle={styles.InputTextHoursRInput}
                  placeholderTextColor={'#c4c4c4'}
                  placeholder="(Opcional)"
                  onChangeText={value => this.setState({})}
                />
                <TouchableOpacity style={{ alignItems: 'flex-end', alignSelf: 'flex-end' }}>
                  <Text style={}>Agregar etapa</Text>
                </TouchableOpacity>
              </View>
            </Collapsible>
          </View>
        )
      }
      else {
        console.log('no encontro un favorito');
        return (
          <View style={{ marginTop: hp('2%') }}>
            <TouchableOpacity style={{
              alignSelf: 'center',
              width: wp('95.7%'),
              height: hp('10%'),
              backgroundColor: "#ffffff",
            }} onPress={() => this.toggleExpanded()}>
              <View style={{ flex: 1, flexDirection: 'row', justifyContent: 'space-between' }}>
                <View style={{ flexDirection: 'column', justifyContent: 'center' }}>
                  <Text numberOfLines={2} ellipsizeMode="tail" style={} >{found.title}</Text>
                  <Text style={}>{`ID ${found.id} - ${found.cliente}`}</Text>
                  {
                    !item.fav ?
                      <Text style={}>No favorito</Text>
                      : null
                  }
                </View>
                <View style={{ flexDirection: 'column', justifyContent: 'center' }}>
                  <View style={{ flexDirection: 'row', marginRight: wp('3.4%') }}>
                    <Text style={}>{`${20}h`}</Text>
                    <Image style={{ marginTop: hp('1%'), marginLeft: wp('3.7%') }} source={this.state.isCollapsed ? Images.expandible : Images.collapsible} />
                  </View>
                </View>
              </View>
            </TouchableOpacity>
            <Collapsible style={{
              alignSelf: 'center',
              width: wp('95.7%'),
              backgroundColor: "#ffffff",
            }} collapsed={this.state.isCollapsed}>
              <View>
                <View style={{ flexDirection: 'row' }}>
                  <Text style={}>Etapa</Text>
                  <Text style={}>Horas</Text>
                </View>
                <View style={{ flexDirection: 'row' }}>
                  <ModalDropdown
                    adjustFrame={style => {
                      style.top = (Platform.OS === 'ios' ? style.top : style.top - StatusBar.currentHeight);
                      return style;
                    }}
                    dropdownTextStyle={styles.dropdownTextStyle}
                    dropdownTextHighlightStyle={styles.dropdownTextHighlightStyle}
                    dropdownStyle={styles.dropdownStageStyle}
                    defaultValue={'Seleccionar'}
                    style={styles.dropStageStyle}
                    textStyle={}
                    //onSelect={(index, value) => this.setState({SeleccionClientes: value})}
                    //options={Object.keys(this.state.items)}
                    onSelect={(index, value) => this.setState({ SeleccionClientes: value })}
                    options={DataManager.ListEtapa}
                  />
                  <View style={styles.InputContainerHours}>
                    <Text style={styles.InputTextHours}>{found.horas}</Text>
                  </View>
                  <TouchableOpacity style={{ marginTop: hp('0.5%'), marginLeft: wp('5.5%') }} onPress={() => this.props.onSubstract}>
                    <Image source={Images.menos_hora} />
                  </TouchableOpacity>
                  <TouchableOpacity style={{ marginTop: hp('0.5%'), marginLeft: wp('2%') }} onPress={() => this.props.onAdd}>
                    <Image source={Images.mas_hora} />
                  </TouchableOpacity>
                </View>
                <Text style={}>Observaciones</Text>
                <Input
                  autoCapitalize="none"
                  maxLength={100}
                  inputContainerStyle={styles.InputContainerComentarioOnBlur}
                  containerStyle={styles.InputComentario}
                  inputStyle={styles.InputTextHoursRInput}
                  placeholderTextColor={'#c4c4c4'}
                  placeholder="(Opcional)"
                  onChangeText={value => this.setState({})}
                />
                <TouchableOpacity style={{ alignItems: 'flex-end', alignSelf: 'flex-end' }}>
                  <Text style={}>Agregar etapa</Text>
                </TouchableOpacity>
              </View>
            </Collapsible>
          </View>
        );
      }
      //})
    }
    else {
      console.log('imputacion por dia esta vacio');
      return (
        <View style={{ marginTop: hp('2%') }}>
          <TouchableOpacity style={{
            alignSelf: 'center',
            width: wp('95.7%'),
            height: hp('10%'),
            backgroundColor: "#ffffff",
          }} onPress={() => this.toggleExpanded()}>
            <View style={{ flex: 1, flexDirection: 'row', justifyContent: 'space-between' }}>
              <View style={{ flexDirection: 'column', justifyContent: 'center' }}>
                <Text numberOfLines={2} ellipsizeMode="tail" style={}>{item.title}</Text>
                <Text style={}>{`ID ${item.id} - ${item.cliente}`}</Text>
                {
                  !item.fav ?
                    <Text style={}>No favorito</Text>
                    : null
                }
              </View>
              <View style={{ flexDirection: 'column', justifyContent: 'center' }}>
                <View style={{ flexDirection: 'row', marginRight: wp('3.4%') }}>
                  <Text style={}>{`${10}h`}</Text>
                  <Image style={{ marginTop: hp('1%'), marginLeft: wp('3.7%') }} source={this.state.isCollapsed ? Images.expandible : Images.collapsible} />
                </View>
              </View>
            </View>
          </TouchableOpacity>
          <Collapsible style={{
            alignSelf: 'center',
            width: wp('95.7%'),
            backgroundColor: "#ffffff",
          }} collapsed={this.state.isCollapsed}>
            <View>
              <View style={{ flexDirection: 'row' }}>
                <Text style={}>Etapa</Text>
                <Text style={}>Horas</Text>
              </View>
              <View style={{ flexDirection: 'row' }}>
                <ModalDropdown
                  adjustFrame={style => {
                    style.top = (Platform.OS === 'ios' ? style.top : style.top - StatusBar.currentHeight);
                    return style;
                  }}
                  dropdownTextStyle={styles.dropdownTextStyle}
                  dropdownTextHighlightStyle={styles.dropdownTextHighlightStyle}
                  dropdownStyle={styles.dropdownStageStyle}
                  defaultValue={'Seleccionar'}
                  style={styles.dropStageStyle}
                  textStyle={}
                  //onSelect={(index, value) => this.setState({SeleccionClientes: value})}
                  //options={Object.keys(this.state.items)}
                  onSelect={(index, value) => this.setState({ SeleccionClientes: value })}
                  options={DataManager.ListEtapa}
                />
                <View style={styles.InputContainerHours}>
                  <Text style={styles.InputTextHours}>{item.horas}</Text>
                </View>
                <TouchableOpacity style={{ marginTop: hp('0.5%'), marginLeft: wp('5.5%') }} onPress={() => this.props.onSubstract}>
                  <Image source={Images.menos_hora} />
                </TouchableOpacity>
                <TouchableOpacity style={{ marginTop: hp('0.5%'), marginLeft: wp('2%') }} onPress={() => this.props.onAdd}>
                  <Image source={Images.mas_hora} />
                </TouchableOpacity>
              </View>
              <Text style={}>Observaciones</Text>
              <Input
                autoCapitalize="none"
                maxLength={100}
                inputContainerStyle={styles.InputContainerComentarioOnBlur}
                containerStyle={styles.InputComentario}
                inputStyle={styles.InputTextHoursRInput}
                placeholderTextColor={'#c4c4c4'}
                placeholder="(Opcional)"
                onChangeText={value => this.setState({})}
              />
              <TouchableOpacity style={{ alignItems: 'flex-end', alignSelf: 'flex-end' }}>
                <Text style={}>Agregar etapa</Text>
              </TouchableOpacity>
            </View>
          </Collapsible>
        </View>
      );
    }
  }}
/>
</code>```

答:
forEach only returns undefined, no matter what you return in the function.

You could find the element first, and then render it conditionally:

<FlatList
    extraData={this.state.data_n2}
    data={this.state.data_n1}>
    renderItem = {({ item, index }) => {
        const found = this.state.data_n2.find(aux => item.id == aux.id);
        if (found) {
            return (<View><Text>Display first stuff: {found.id}</Text></View>);
        } else {
            return (<View><Text>Display second stuff: {item.id}</Text></View>);
        }
    }}
/>
```

<hr>

<p>If there are possibly multiple matches:</p>

<pre class="lang-js prettyprint-override"><code><FlatList
    extraData={this.state}
    data={this.state.data_n1}>
    renderItem = {({ item, index }) => {
        const found = this.state.data_n2.filter(aux => item.id == aux.id);
        if (found.length > 0) {
            return (
                <View>{
                    found.map(e => (<View><Text>Display first stuff: {e.id}</Text></View>))
                }</View>
            );
        } else {
            return (<View><Text>Display second stuff</Text></View>);
        }
    }}
/>
</code>```

Body:
so i got this object that i pass as data to my react native flatlist

<FlatList
  extraData = {this.state}
  data = {this.state.data_n1}>
  renderItem = {({item, index}) => {
    this.state.data_n2.forEach(aux => {
      if(item.id == aux.id) {
        return(<View><Text>Display first stuff</Text></View>);
      } else {
        return(<View><Text>Display second stuff</Text></View>);
      }
    }
  }
/>

the whole idea is compare both objects, if the data_n2 contains the same id from the data_n1, the display the data from the data_n2, if not, just display from data_n1, problem is, i'm displaying this whenever i click on a calendar strip, so if i click on day june 1st, that day should display data_n2, if i click on day june 2nd, THAT one should display the data_n1.

does this work with flatlist or virtualizedlist (if i had to swap), or i need to render a flatlist for each data?

Edit: tested hao wu answer, but got this

Edit n2: i'll post the code, but keep in mind data_n1 is this.state.listaImputacionDia and this.state.listaImputacionDia is data_n2

this is the calendar strip code

<CalendarStrip
  calendarHeaderStyle={{
    fontSize: rfv(18),
    fontWeight: "normal",
    fontStyle: "normal",
    letterSpacing: 0,
    textAlign: "left",
    color: "#707070",
    paddingBottom: hp('4.5%')
  }}
  selectedDate={this.state.selectedDate}
  onDateSelected={async (date) => {
    await HoursReportHistoryBusiness.GetInstance().getListHoursReportRequest();
    this.setState({ selectedDate: moment(date).format('YYYY-MM-DD') });
    this.setViewHourHistory();
    console.log(this.state.listaImputacionDia);
  }}
  minDate={moment().subtract(3, 'days')}
  maxDate={moment().add(3,'days')}
  startingDate={moment().subtract(3, 'days')}
  useIsoWeekday={false}
  style={{paddingTop: hp('1.5%'), paddingBottom: hp('2.7%'), backgroundColor: '#ffffff'}}
  highlightDateNameStyle={{color: '#1062cc'}}
  highlightDateNumberStyle={{color: '#1062cc'}}
  disabledDateNumberStyle={{color: '#f21927'}}
  disabledDateNameStyle={{color: '#f21927'}}
  customDatesStyles={this.customDatesStyle}
  dateNameStyle={{color: '#c4c4c4'}}
  dateNumberStyle={{color: '#c4c4c4'}}
  disabledDateOpacity={1}
/>

this is the flatlist

<FlatList
  extraData={this.state.listaImputacionDia}
  data={this.state.dataSource}//{DataManager.FavoriteList[moment(this.state.selectedDate).format('YYYY-MM-DD')]}
  renderItem={({ item, index }) => {
    if (this.state.listaImputacionDia.length != 0) {
      const found = this.state.listaImputacionDia.filter(aux => item.id == aux.IdProyecto);
      //this.state.listaImputacionDia.forEach(aux => {
      if (found/*item.id == aux.IdProyecto*/) {
        console.log('la wea' + found);
        return (
          <View style={{ marginTop: hp('2%') }}>
            <TouchableOpacity style={} onPress={() => this.toggleExpanded()}>
              <View style={{ flex: 1, flexDirection: 'row', justifyContent: 'space-between' }}>
                <View style={{ flexDirection: 'column', justifyContent: 'center' }}>
                  <Text numberOfLines={2} ellipsizeMode="tail" style={}>{found.Title}</Text>
                  <Text style={}>{`ID ${found.Id} - ${found.Cliente}`}</Text>
                  {
                    !found.fav ?
                      <Text style={}>No favorito</Text>
                      : null
                  }
                </View>
                <View style={{ flexDirection: 'column', justifyContent: 'center' }}>
                  <View style={{ flexDirection: 'row', marginRight: wp('3.4%') }}>
                    <Text style={}>{`${found.HorasTrabajadas}h`}</Text>
                    <Image style={{ marginTop: hp('1%'), marginLeft: wp('3.7%') }} source={this.state.isCollapsed ? Images.expandible : Images.collapsible} />
                  </View>
                </View>
              </View>
            </TouchableOpacity>
            <Collapsible style={{
              alignSelf: 'center',
              width: wp('95.7%'),
              backgroundColor: "#ffffff",
            }} collapsed={this.state.isCollapsed}>
              <View>
                <View style={{ flexDirection: 'row' }}>
                  <Text style={}>Etapa</Text>
                  <Text style={}>Horas</Text>
                </View>
                <View style={{ flexDirection: 'row' }}>
                  <ModalDropdown
                    adjustFrame={style => {
                      style.top = (Platform.OS === 'ios' ? style.top : style.top - StatusBar.currentHeight);
                      return style;
                    }}
                    dropdownTextStyle={styles.dropdownTextStyle}
                    dropdownTextHighlightStyle={styles.dropdownTextHighlightStyle}
                    dropdownStyle={styles.dropdownStageStyle}
                    defaultValue={'Seleccionar'}
                    style={styles.dropStageStyle}
                    textStyle={{
                      padding: 0,
                      margin: 0,
                      fontSize: rfv(16),
                      paddingVertical: hp('1.2%'),
                      fontWeight: 'normal',
                      fontStyle: 'normal',
                      textAlign: 'left',
                      color: found.etapa != '' ? '#1a1a1a' : '#c4c4c4',
                    }}
                    //onSelect={(index, value) => this.setState({SeleccionClientes: value})}
                    //options={Object.keys(this.state.items)}
                    onSelect={(index, value) => this.setState({ SeleccionClientes: value })}
                    options={DataManager.ListEtapa}
                  />
                  <View style={styles.InputContainerHours}>
                    <Text style={styles.InputTextHours}>{found.HorasTrabajadas}</Text>
                  </View>
                  <TouchableOpacity style={{ marginTop: hp('0.5%'), marginLeft: wp('5.5%') }} onPress={() => this.props.onSubstract}>
                    <Image source={Images.menos_hora} />
                  </TouchableOpacity>
                  <TouchableOpacity style={{ marginTop: hp('0.5%'), marginLeft: wp('2%') }} onPress={() => this.props.onAdd}>
                    <Image source={Images.mas_hora} />
                  </TouchableOpacity>
                </View>
                <Text style={}>Observaciones</Text>
                <Input
                  autoCapitalize="none"
                  maxLength={100}
                  inputContainerStyle={styles.InputContainerComentarioOnBlur}
                  containerStyle={styles.InputComentario}
                  inputStyle={styles.InputTextHoursRInput}
                  placeholderTextColor={'#c4c4c4'}
                  placeholder="(Opcional)"
                  onChangeText={value => this.setState({})}
                />
                <TouchableOpacity style={{ alignItems: 'flex-end', alignSelf: 'flex-end' }}>
                  <Text style={}>Agregar etapa</Text>
                </TouchableOpacity>
              </View>
            </Collapsible>
          </View>
        )
      }
      else {
        console.log('no encontro un favorito');
        return (
          <View style={{ marginTop: hp('2%') }}>
            <TouchableOpacity style={{
              alignSelf: 'center',
              width: wp('95.7%'),
              height: hp('10%'),
              backgroundColor: "#ffffff",
            }} onPress={() => this.toggleExpanded()}>
              <View style={{ flex: 1, flexDirection: 'row', justifyContent: 'space-between' }}>
                <View style={{ flexDirection: 'column', justifyContent: 'center' }}>
                  <Text numberOfLines={2} ellipsizeMode="tail" style={} >{found.title}</Text>
                  <Text style={}>{`ID ${found.id} - ${found.cliente}`}</Text>
                  {
                    !item.fav ?
                      <Text style={}>No favorito</Text>
                      : null
                  }
                </View>
                <View style={{ flexDirection: 'column', justifyContent: 'center' }}>
                  <View style={{ flexDirection: 'row', marginRight: wp('3.4%') }}>
                    <Text style={}>{`${20}h`}</Text>
                    <Image style={{ marginTop: hp('1%'), marginLeft: wp('3.7%') }} source={this.state.isCollapsed ? Images.expandible : Images.collapsible} />
                  </View>
                </View>
              </View>
            </TouchableOpacity>
            <Collapsible style={{
              alignSelf: 'center',
              width: wp('95.7%'),
              backgroundColor: "#ffffff",
            }} collapsed={this.state.isCollapsed}>
              <View>
                <View style={{ flexDirection: 'row' }}>
                  <Text style={}>Etapa</Text>
                  <Text style={}>Horas</Text>
                </View>
                <View style={{ flexDirection: 'row' }}>
                  <ModalDropdown
                    adjustFrame={style => {
                      style.top = (Platform.OS === 'ios' ? style.top : style.top - StatusBar.currentHeight);
                      return style;
                    }}
                    dropdownTextStyle={styles.dropdownTextStyle}
                    dropdownTextHighlightStyle={styles.dropdownTextHighlightStyle}
                    dropdownStyle={styles.dropdownStageStyle}
                    defaultValue={'Seleccionar'}
                    style={styles.dropStageStyle}
                    textStyle={}
                    //onSelect={(index, value) => this.setState({SeleccionClientes: value})}
                    //options={Object.keys(this.state.items)}
                    onSelect={(index, value) => this.setState({ SeleccionClientes: value })}
                    options={DataManager.ListEtapa}
                  />
                  <View style={styles.InputContainerHours}>
                    <Text style={styles.InputTextHours}>{found.horas}</Text>
                  </View>
                  <TouchableOpacity style={{ marginTop: hp('0.5%'), marginLeft: wp('5.5%') }} onPress={() => this.props.onSubstract}>
                    <Image source={Images.menos_hora} />
                  </TouchableOpacity>
                  <TouchableOpacity style={{ marginTop: hp('0.5%'), marginLeft: wp('2%') }} onPress={() => this.props.onAdd}>
                    <Image source={Images.mas_hora} />
                  </TouchableOpacity>
                </View>
                <Text style={}>Observaciones</Text>
                <Input
                  autoCapitalize="none"
                  maxLength={100}
                  inputContainerStyle={styles.InputContainerComentarioOnBlur}
                  containerStyle={styles.InputComentario}
                  inputStyle={styles.InputTextHoursRInput}
                  placeholderTextColor={'#c4c4c4'}
                  placeholder="(Opcional)"
                  onChangeText={value => this.setState({})}
                />
                <TouchableOpacity style={{ alignItems: 'flex-end', alignSelf: 'flex-end' }}>
                  <Text style={}>Agregar etapa</Text>
                </TouchableOpacity>
              </View>
            </Collapsible>
          </View>
        );
      }
      //})
    }
    else {
      console.log('imputacion por dia esta vacio');
      return (
        <View style={{ marginTop: hp('2%') }}>
          <TouchableOpacity style={{
            alignSelf: 'center',
            width: wp('95.7%'),
            height: hp('10%'),
            backgroundColor: "#ffffff",
          }} onPress={() => this.toggleExpanded()}>
            <View style={{ flex: 1, flexDirection: 'row', justifyContent: 'space-between' }}>
              <View style={{ flexDirection: 'column', justifyContent: 'center' }}>
                <Text numberOfLines={2} ellipsizeMode="tail" style={}>{item.title}</Text>
                <Text style={}>{`ID ${item.id} - ${item.cliente}`}</Text>
                {
                  !item.fav ?
                    <Text style={}>No favorito</Text>
                    : null
                }
              </View>
              <View style={{ flexDirection: 'column', justifyContent: 'center' }}>
                <View style={{ flexDirection: 'row', marginRight: wp('3.4%') }}>
                  <Text style={}>{`${10}h`}</Text>
                  <Image style={{ marginTop: hp('1%'), marginLeft: wp('3.7%') }} source={this.state.isCollapsed ? Images.expandible : Images.collapsible} />
                </View>
              </View>
            </View>
          </TouchableOpacity>
          <Collapsible style={{
            alignSelf: 'center',
            width: wp('95.7%'),
            backgroundColor: "#ffffff",
          }} collapsed={this.state.isCollapsed}>
            <View>
              <View style={{ flexDirection: 'row' }}>
                <Text style={}>Etapa</Text>
                <Text style={}>Horas</Text>
              </View>
              <View style={{ flexDirection: 'row' }}>
                <ModalDropdown
                  adjustFrame={style => {
                    style.top = (Platform.OS === 'ios' ? style.top : style.top - StatusBar.currentHeight);
                    return style;
                  }}
                  dropdownTextStyle={styles.dropdownTextStyle}
                  dropdownTextHighlightStyle={styles.dropdownTextHighlightStyle}
                  dropdownStyle={styles.dropdownStageStyle}
                  defaultValue={'Seleccionar'}
                  style={styles.dropStageStyle}
                  textStyle={}
                  //onSelect={(index, value) => this.setState({SeleccionClientes: value})}
                  //options={Object.keys(this.state.items)}
                  onSelect={(index, value) => this.setState({ SeleccionClientes: value })}
                  options={DataManager.ListEtapa}
                />
                <View style={styles.InputContainerHours}>
                  <Text style={styles.InputTextHours}>{item.horas}</Text>
                </View>
                <TouchableOpacity style={{ marginTop: hp('0.5%'), marginLeft: wp('5.5%') }} onPress={() => this.props.onSubstract}>
                  <Image source={Images.menos_hora} />
                </TouchableOpacity>
                <TouchableOpacity style={{ marginTop: hp('0.5%'), marginLeft: wp('2%') }} onPress={() => this.props.onAdd}>
                  <Image source={Images.mas_hora} />
                </TouchableOpacity>
              </View>
              <Text style={}>Observaciones</Text>
              <Input
                autoCapitalize="none"
                maxLength={100}
                inputContainerStyle={styles.InputContainerComentarioOnBlur}
                containerStyle={styles.InputComentario}
                inputStyle={styles.InputTextHoursRInput}
                placeholderTextColor={'#c4c4c4'}
                placeholder="(Opcional)"
                onChangeText={value => this.setState({})}
              />
              <TouchableOpacity style={{ alignItems: 'flex-end', alignSelf: 'flex-end' }}>
                <Text style={}>Agregar etapa</Text>
              </TouchableOpacity>
            </View>
          </Collapsible>
        </View>
      );
    }
  }}
/>

Body:
forEach only returns undefined, no matter what you return in the function.

You could find the element first, and then render it conditionally:

<FlatList
    extraData={this.state.data_n2}
    data={this.state.data_n1}>
    renderItem = {({ item, index }) => {
        const found = this.state.data_n2.find(aux => item.id == aux.id);
        if (found) {
            return (<View><Text>Display first stuff: {found.id}</Text></View>);
        } else {
            return (<View><Text>Display second stuff: {item.id}</Text></View>);
        }
    }}
/>

If there are possibly multiple matches:

<FlatList
    extraData={this.state}
    data={this.state.data_n1}>
    renderItem = {({ item, index }) => {
        const found = this.state.data_n2.filter(aux => item.id == aux.id);
        if (found.length > 0) {
            return (
                <View>{
                    found.map(e => (<View><Text>Display first stuff: {e.id}</Text></View>))
                }</View>
            );
        } else {
            return (<View><Text>Display second stuff</Text></View>);
        }
    }}
/>


问:
API for message recognition (text not speech)
I am looking for an API to detect commands in messages, similar to Google Assistant but instead of speech being just message, like a String.

I simply want to implement things like "Remind me to do x at x time", I've been searching around but every API I find is always for speech.

答:
I would suggest experimenting with Google's Dialogue Flow. Once you wrap your brain around your use-case specific intents, entities, and contexts, you can hit the DialogueFlow API with a workflow like this:

The end-user types an expression.

Your service sends this end-user expression to Dialogflow in a
detect intent request message.

Dialogflow sends a detect intent response message to your service.
This message contains information about the matched intent, the
action, the parameters, and the response defined for the intent.

Your service performs actions as needed, like database queries or
external API calls.

Your service sends a response to the end-user.

The end-user sees the response.

Read more here.


问:
how do you separate the lines of each branch on git?
I want to separate each line in the branch to make it easier for me to read it. How do you change one image to make it look like Figure 2?

答:
The problem is: each of the remote tracking branches are part of the same history, they are direct descendant of the master branch.

So there is no "separate line" to see here, unless you create one by switching to each branch and pushing an empty artifical commit:

```<code>git switch register # creates the register branch tracking origin/register
git commit --allow-empty -m "artificial empty commit"
git push -u origin register
</code>```

But again, you should not need that in your case (linear history)

Body:
The problem is: each of the remote tracking branches are part of the same history, they are direct descendant of the master branch.

So there is no "separate line" to see here, unless you create one by switching to each branch and pushing an empty artifical commit:

git switch register # creates the register branch tracking origin/register
git commit --allow-empty -m "artificial empty commit"
git push -u origin register

But again, you should not need that in your case (linear history)


问:
Regular expression to match non-ASCII characters?
What is the easiest way to match non-ASCII characters in a regex? I would like to match all words individually in an input string, but the language may not be English, so I will need to match things like ü, ö, ß, and ñ. Also, this is in Javascript/jQuery, so any solution will need to apply to that. </p>

答:
I had a problem with \p working as expected, so I just used a different strategy like:

```<code>([^\t]+)\t
</code>```

Find anything that is not a tab character until the next tab character... obviously this depends on your search source, but you get the idea. Now I don't have to figure out what unicode characters work and don't work etc.

OwnerDisplayName: Paul Wicks

Body:
I had a problem with \p working as expected, so I just used a different strategy like:

([^\t]+)\t

Find anything that is not a tab character until the next tab character... obviously this depends on your search source, but you get the idea. Now I don't have to figure out what unicode characters work and don't work etc.


问:
How to determine how many times '0' to '9' have been used in a specific range instantly
I want to count how many times '0' to '9' have been used in a specific range

e.g. 112 has two '1' and one '2'

Thanks for your advices, I changed my code now.

But it is not efficient as I want.

```<code>num = int(input('n : '))
start_time = time.time()
num_arr = [0] * 10
progress_arr = ['%d' % (num * (i / 100)) for i in range(1, 101)]

for i in range(1, num + 1):
    if str(i) in progress_arr:
        print(str(progress_arr.index(str(i)) + 1) + '%')
    for digit in str(i):
        num_arr[int(digit)] += 1

print('Time : %.2f' % (time.time() - start_time))
print(num_arr)
</code>```

When I input 1000 as n, my program will print this arr instantly

[192, 301, 300, 300, 300, 300, 300, 300, 300, 300]

It means for 1 to 1000,
'0' has been used 192 times and '1' has been used 301 times and ···

But when I input 2,000,000,000 as n, my program will print the result after
11 minutes(Using pypy3, Ryzen 2600).

So I want to change my code as efficient to get the result of a very large number instantly.

And in my previous question, I mentioned the time complexity of O(N), which confused you because of my poor understanding of algorithm and time complexity. So I deleted it.

What I want to know is just the efficient algorithm.

I'm trying to find a specific rule by analyzing the difference in the results of increment, but it's not easy.

答:
Well, I have a way that will take about 30-40 minutes for an input of 2,000,000,000, is that fast enough? Hopefully that's long before you are dead! It processes about 1,000,000 numbers per second on my machine. The key is that you are calling count() 10 times on each number, once for each digit. But if you just went through the number once and incremented based on what digit you see at each position, then you just run through each number once. My method also doesn't keep much in memory, so it won't run out of space (I chose to use a dict instead of a list of digits, but it should be about the same). My code:

```<code>num = 2 * (10**9) # 2 billion
num_dict = {}
for i in range(10):       # Dict to keep track of counts
    num_dict[str(i)] = 0

for i in range(1, num + 1):
    if i%1000000 == 0:           # print progress every Million
        print(f'Processed {i/1000000}M numbers')
    for digit in str(i):
        num_dict[digit] += 1

>>> print(num_dict)
{
    '0': 1688888898,
    '1': 2800000000,
    '2': 1800000001,
    '3': 1800000000,
    '4': 1800000000,
    '5': 1800000000,
    '6': 1800000000,
    '7': 1800000000,
    '8': 1800000000,
    '9': 1800000000
}
</code>```

<s>I'll update with the answer in 40 minutes if you want</s>

Answer for n : 2billion is above! ;D

Happy Coding!

Body:
I want to count how many times '0' to '9' have been used in a specific range

e.g. 112 has two '1' and one '2'

Thanks for your advices, I changed my code now.

But it is not efficient as I want.

num = int(input('n : '))
start_time = time.time()
num_arr = [0] * 10
progress_arr = ['%d' % (num * (i / 100)) for i in range(1, 101)]

for i in range(1, num + 1):
    if str(i) in progress_arr:
        print(str(progress_arr.index(str(i)) + 1) + '%')
    for digit in str(i):
        num_arr[int(digit)] += 1

print('Time : %.2f' % (time.time() - start_time))
print(num_arr)

When I input 1000 as n, my program will print this arr instantly

[192, 301, 300, 300, 300, 300, 300, 300, 300, 300]

It means for 1 to 1000,
'0' has been used 192 times and '1' has been used 301 times and ···

But when I input 2,000,000,000 as n, my program will print the result after
11 minutes(Using pypy3, Ryzen 2600).

So I want to change my code as efficient to get the result of a very large number instantly.

And in my previous question, I mentioned the time complexity of O(N), which confused you because of my poor understanding of algorithm and time complexity. So I deleted it.

What I want to know is just the efficient algorithm.

I'm trying to find a specific rule by analyzing the difference in the results of increment, but it's not easy.

Body:
Well, I have a way that will take about 30-40 minutes for an input of 2,000,000,000, is that fast enough? Hopefully that's long before you are dead! It processes about 1,000,000 numbers per second on my machine. The key is that you are calling count() 10 times on each number, once for each digit. But if you just went through the number once and incremented based on what digit you see at each position, then you just run through each number once. My method also doesn't keep much in memory, so it won't run out of space (I chose to use a dict instead of a list of digits, but it should be about the same). My code:

num = 2 * (10**9) # 2 billion
num_dict = {}
for i in range(10):       # Dict to keep track of counts
    num_dict[str(i)] = 0

for i in range(1, num + 1):
    if i%1000000 == 0:           # print progress every Million
        print(f'Processed {i/1000000}M numbers')
    for digit in str(i):
        num_dict[digit] += 1

>>> print(num_dict)
{
    '0': 1688888898,
    '1': 2800000000,
    '2': 1800000001,
    '3': 1800000000,
    '4': 1800000000,
    '5': 1800000000,
    '6': 1800000000,
    '7': 1800000000,
    '8': 1800000000,
    '9': 1800000000
}

<s>I'll update with the answer in 40 minutes if you want</s>

Answer for n : 2billion is above! ;D

Happy Coding!


问:
Improper validation when installing Oracle Fusion Middleware
I installed Oracle JDeveloper 11g (11.1.1.4.0). I also installed IBM Websphere 7.0.0.15 without any profile as suggested in the documentation. Next I wanted to install Oracle Fusion Middleware 11g. But during installation, I was asked Application Server Location for which I gave

C:\Program
  Files\IBM\SDP\runtimes\base_v7

When I click next, I am getting this error

INST-07004: Application Server
  Location location contains one or more
  invalid characters. The directory name
  may only contain alphanumeric,
  underscore(_), hyphen(-), or dot(.)
  characters, and it must begin with an
  alphanumeric charater. Provide a
  different directory name.

Server location is proper and link specified satisfies condition. I dont understand why I am getting that error. If it is because of : in the location, how else do I specify the path ? Any solution to this ?

答: The issue was that I was using WAS Test Environment. After I tried with standalone WAS, it succeeded but I am not able to configure after install. The changes are not being saved to WAS.</p>


问:
binding a Guid parameter in asp.net mvc core
I want to bind a Guid parameter to my ASP.NET MVC Core API:

```<code>[FromHeader] Guid id
</code>```

but it's always null.  If I change the parameter to a string and parse the Guid from the string manually it works, so I think it's not detecting Guid as a convertable type.

In the documentation it says

In MVC simple types are any .NET primitive type or type with a string type converter.

There is a type converter for Guids (GuidConverter) but maybe ASP.NET MVC Core doesn't know about it.

Does anyone know how to bind a Guid parameter with ASP.NET MVC Core or how to tell it to use GuidConverter?

答:
The easiest way to do this is to remove the attribute before your parameter of type Guid in your controller action like this:

public async Task<IActionResult> UpdateAsync(Guid ApplicantId, [FromBody]UpdateApplicantRequest request)
        {}

Plain and simple, hope this helps.

Body:
I want to bind a Guid parameter to my ASP.NET MVC Core API:

[FromHeader] Guid id

but it's always null.  If I change the parameter to a string and parse the Guid from the string manually it works, so I think it's not detecting Guid as a convertable type.

In the documentation it says

In MVC simple types are any .NET primitive type or type with a string type converter.

There is a type converter for Guids (GuidConverter) but maybe ASP.NET MVC Core doesn't know about it.

Does anyone know how to bind a Guid parameter with ASP.NET MVC Core or how to tell it to use GuidConverter?


问:
How to use LIKE in SQLDF in R for searching text in multiple dataframes
I have 2 dataframes with text and want to compare partial string.
What I am looking for is Id, t1.mo and monthid from table 2.

```<code>t1 <- data.frame("id"=1:4,"mo"=c("Jan","Feb","Apr","Mar"))
t2 <- data.frame("id"=1:4, "nt"= c("January","Jan Feb","February","Mar"),"monthid" = 5:8)

sqldf("select t1.mo,t2.nt,t2.monthid from t1, t2 where t1.mo like '%' || t2.nt || '%'")
</code>```

I have tried,
sqldf("select t1.mo,t2.mo from t1, t2 where t1.mo like '%Feb%'") and its working
But when referencing t2 it is not working.

```<code>T1.id  t1.mo  t2.monthid
1       Jan    5
2       Feb    6
4       Mar    8
</code>```

Any help is appreciated.

Edited the output as Tim Biegeleisen pointed out.

答:
You are doing the LIKE comparsion backwards, and you should be checking that the mo column from t1 appears as a substring of the nt column in t2:

```<code>sql <- "SELECT t1.mo, t2.nt, t2.monthid
        FROM t1
        INNER JOIN t2 ON t2.nt like '%' || t1.mo || '%' AND t1.id = t2.id"
result <- sqldf(sql)
</code>```

Also note that I have refactored your query to use a proper explicit join, which is the preferred way of writing SQL.

Demo

Note that I am getting an extra record in the result set beyond what you expect, but this is because Feb in the first table matches both Jan Feb and February in the second table.  If you only expected one match there, you should state why.

Body:
I have 2 dataframes with text and want to compare partial string.
What I am looking for is Id, t1.mo and monthid from table 2.

t1 <- data.frame("id"=1:4,"mo"=c("Jan","Feb","Apr","Mar"))
t2 <- data.frame("id"=1:4, "nt"= c("January","Jan Feb","February","Mar"),"monthid" = 5:8)

sqldf("select t1.mo,t2.nt,t2.monthid from t1, t2 where t1.mo like '%' || t2.nt || '%'")

I have tried,
sqldf("select t1.mo,t2.mo from t1, t2 where t1.mo like '%Feb%'") and its working
But when referencing t2 it is not working.

T1.id  t1.mo  t2.monthid
1       Jan    5
2       Feb    6
4       Mar    8

Any help is appreciated.

Edited the output as Tim Biegeleisen pointed out.

Body:
You are doing the LIKE comparsion backwards, and you should be checking that the mo column from t1 appears as a substring of the nt column in t2:

sql <- "SELECT t1.mo, t2.nt, t2.monthid
        FROM t1
        INNER JOIN t2 ON t2.nt like '%' || t1.mo || '%' AND t1.id = t2.id"
result <- sqldf(sql)

Also note that I have refactored your query to use a proper explicit join, which is the preferred way of writing SQL.

Demo

Note that I am getting an extra record in the result set beyond what you expect, but this is because Feb in the first table matches both Jan Feb and February in the second table.  If you only expected one match there, you should state why.


问:
maxDequeueCount config setting not working for Azure Function
I have an an Azure Function which I want to fail and sent to the poison queue if it errors once or twice. I've set the maxDequeueCount property in my host.json file to 1, but it still retries 5 times. Based on all the doco I've read this seems to be correct. Does anyone have any suggestions? Below is a sample of my hosts.json.</p>

```<code>{
  "version": "2.0",
  "logging": {
    "fileLoggingMode": "debugOnly",
    "logLevel": {
      // For all functions
      "Function": "Trace",
      // Default settings, e.g. for host
      "default": "Trace"
    },
    "extensions": {
      "queues": {
        "visibilityTimeout": "00:01:00",
        "maxDequeueCount": 1
      }
    }
  }
}
</code>```

答:
For storage queue trigger, to change frequency of the retry, we just need to change the value of maxDequeueCount. Please go to azure portal to check the host.json file.

```<code>{
  "version": "2.0",
  "extensionBundle": {
    "id": "Microsoft.Azure.Functions.ExtensionBundle",
    "version": "[1.*, 2.0.0)"
  },
  "extensions": {
    "queues": {
      "maxDequeueCount": 1
    }
  }
}
</code>```

If the feature still doesn't work after restarting the function, I afraid that you need to raise a support ticket on azure portal, they will check the backend logs for you.

Body:
I have an an Azure Function which I want to fail and sent to the poison queue if it errors once or twice. I've set the maxDequeueCount property in my host.json file to 1, but it still retries 5 times. Based on all the doco I've read this seems to be correct. Does anyone have any suggestions? Below is a sample of my hosts.json.

{
  "version": "2.0",
  "logging": {
    "fileLoggingMode": "debugOnly",
    "logLevel": {
      // For all functions
      "Function": "Trace",
      // Default settings, e.g. for host
      "default": "Trace"
    },
    "extensions": {
      "queues": {
        "visibilityTimeout": "00:01:00",
        "maxDequeueCount": 1
      }
    }
  }
}

Body:
For storage queue trigger, to change frequency of the retry, we just need to change the value of maxDequeueCount. Please go to azure portal to check the host.json file.

{
  "version": "2.0",
  "extensionBundle": {
    "id": "Microsoft.Azure.Functions.ExtensionBundle",
    "version": "[1.*, 2.0.0)"
  },
  "extensions": {
    "queues": {
      "maxDequeueCount": 1
    }
  }
}

If the feature still doesn't work after restarting the function, I afraid that you need to raise a support ticket on azure portal, they will check the backend logs for you.


问:
webdriver hangs for some url on .get (IE)
I have Selenium 3.14.4
IEDriver 3.15

For some url when I call driver.get(), webdriver just sits there even though the page is done loading. In the end we get the error "Command line server for IE driver has stopped working"

I've tried both 32bit and 64bit of the IEdriver - same issue

When I downgrade the IE driver back to 2.53.1 it works fine with no error.

Any one know if this is a known defect for IEdriver 3.X ?

答: I haven't found this as a known defect for IEDriver 3.X. But you could try the latest stable version of Selenium Server which is 3.141.59 and the recommended Internet Explorer Driver Server version 3.150.1 in this page. Besides, please try to check if you have meet the required configuration for IEDriver in this page.


问:
pygame.error: Couldn't open images/ship.bmp
Screenshot of Error Text

Error Text:

```<code>Traceback (most recent call last):
  File "C:\Users\Sean Takei\Desktop\python_work\alien_invasion\alien_invasion3.py", line 40, in <module>
    ai= AlienInvasion()
  File "C:\Users\Sean Takei\Desktop\python_work\alien_invasion\alien_invasion3.py", line 21, in _init__
    self.ship= Ship(self)
  File "C:\Users\Sean Takei\Desktop\python_work\alien_invasion\shiptest.py", line 23, in _init__
    self.image = pygame.image.load('images/ship.bmp' )
pygame.error: Couldn't open images/ship.bmp
</code>```

First post here, Im new to python and been going through the Python Crash Course book and been stuck on  chapter12 "Drawing the Ship to the Screen" part. At first I have the ship.bmp in images folder in the alien_invasion folder, which is where the this code below is running. Now I have the images both in images folder and also the alien_invasion folder and it is showing this error. Please tell me what I'm doing wrong

alien_invasion3.py

```<code>import sys

import pygame

from settings import Settings
from shiptest import Ship

class AlienInvasion:
"""Overall class to manage game assets and behavior."""

    def __init__(self):
        """Initialize the game, and create game resources."""
        pygame.init()
        self.settings= Settings()

        self.screen= pygame.display.set_mode(
            (self.settings.screen_width, self.settings.screen_height))
        pygame.display.set_caption("Alien Invasion")

        self.ship= Ship(self)

    def run_game(self):
    """Start the main loop for the game."""
        while True:
        #Watch for keyboard and mouse events.
            for event in pygame.event.get():
                if event.type== pygame.QUIT:
                    sys.exit()

        #Redraw the screen during each pass through the loop.
            self.screen.fill(self.settings.bg_color)
            self.ship.blitme()

        #Make the most recently drawn screen visible.
            pygame.display.flip()

if __name__== '__main__':
#Make a game instance, and run the game.
    ai= AlienInvasion()
    ai.run_game()
</code>```

Ship.py

```<code>import pygame

class Ship:
"""A class to manage the ship."""

    def __init__(self, ai_game):
    """Initialize the ship and set its staring position."""
        self.screen= ai_game.screen
        self.screen_rect= ai_game.screen.get_rect()

    #Load the ship image and get its rect.
        self.image= pygame.image.load('images/ship.bmp')
        self.rect= self.image.get_rect()

    #Start each new ship at the bottom center of the screen.
        self.rect.midbottom= self.screen_rect.midbottom

    def blitme(self):
    """Draw the ship at its current location."""
        self.screen.blit(self.image, self.rect)
</code>```

settings.py

```<code>class Settings:
"""A class to store all settings for Alien Invasion."""

    def __init__(self):
    """Initialize the game's settings."""
    #Screen settings
        self.screen_width= 1200
        self.screen_height= 800
        self.bg_color= (0, 0, 255)
</code>```

答:
Use the absolute path. For example:

```<code>self.image = pygame.image.load("F:/python_projects/AlienInvasion/images/ship.bmp")
</code>```

I don’t know why it doesn’t work with a relative path.

Body:
Screenshot of Error Text

Error Text:

Traceback (most recent call last):
  File "C:\Users\Sean Takei\Desktop\python_work\alien_invasion\alien_invasion3.py", line 40, in <module>
    ai= AlienInvasion()
  File "C:\Users\Sean Takei\Desktop\python_work\alien_invasion\alien_invasion3.py", line 21, in _init__
    self.ship= Ship(self)
  File "C:\Users\Sean Takei\Desktop\python_work\alien_invasion\shiptest.py", line 23, in _init__
    self.image = pygame.image.load('images/ship.bmp' )
pygame.error: Couldn't open images/ship.bmp

First post here, Im new to python and been going through the Python Crash Course book and been stuck on  chapter12 "Drawing the Ship to the Screen" part. At first I have the ship.bmp in images folder in the alien_invasion folder, which is where the this code below is running. Now I have the images both in images folder and also the alien_invasion folder and it is showing this error. Please tell me what I'm doing wrong

alien_invasion3.py

import sys

import pygame

from settings import Settings
from shiptest import Ship

class AlienInvasion:
"""Overall class to manage game assets and behavior."""

    def __init__(self):
        """Initialize the game, and create game resources."""
        pygame.init()
        self.settings= Settings()

        self.screen= pygame.display.set_mode(
            (self.settings.screen_width, self.settings.screen_height))
        pygame.display.set_caption("Alien Invasion")

        self.ship= Ship(self)

    def run_game(self):
    """Start the main loop for the game."""
        while True:
        #Watch for keyboard and mouse events.
            for event in pygame.event.get():
                if event.type== pygame.QUIT:
                    sys.exit()

        #Redraw the screen during each pass through the loop.
            self.screen.fill(self.settings.bg_color)
            self.ship.blitme()

        #Make the most recently drawn screen visible.
            pygame.display.flip()

if __name__== '__main__':
#Make a game instance, and run the game.
    ai= AlienInvasion()
    ai.run_game()

Ship.py

import pygame

class Ship:
"""A class to manage the ship."""

    def __init__(self, ai_game):
    """Initialize the ship and set its staring position."""
        self.screen= ai_game.screen
        self.screen_rect= ai_game.screen.get_rect()

    #Load the ship image and get its rect.
        self.image= pygame.image.load('images/ship.bmp')
        self.rect= self.image.get_rect()

    #Start each new ship at the bottom center of the screen.
        self.rect.midbottom= self.screen_rect.midbottom

    def blitme(self):
    """Draw the ship at its current location."""
        self.screen.blit(self.image, self.rect)

settings.py

class Settings:
"""A class to store all settings for Alien Invasion."""

    def __init__(self):
    """Initialize the game's settings."""
    #Screen settings
        self.screen_width= 1200
        self.screen_height= 800
        self.bg_color= (0, 0, 255)

Body:
Use the absolute path. For example:

self.image = pygame.image.load("F:/python_projects/AlienInvasion/images/ship.bmp")

I don’t know why it doesn’t work with a relative path.


问:
Oracle command line to export table data to csv using spool having issues when data has double quotes(") in it
I am having ORACLE 11 version installed on my linux machine. I am trying to export data using below. It is working fine for all the tables except for tables having double quotes(") as data in any of column. Below is my code

```<code>set echo off
set feedback off
set linesize 30000
set recsep off
set trimspool off
set verify off
set pagesize off
spool "/home/rsau12/file.csv";
SELECT  '"'||COLUMN_1||'"'||','
'"'||COLUMN_2||'"'||','
'"'||COLUMN_3||'"'||','
        ...
'"'||COLUMN_N||'"'
FROM TABLE;
spool off;
</code>```

Please let me know how to handle if data has (") in it

答:
You need to replace double quotes(") with two double quotes(""):

```<code>select        chr(34)||replace(COLUMN_1,chr(34),chr(34)||chr(34))||chr(34)
       ||','||chr(34)||replace(COLUMN_2,chr(34),chr(34)||chr(34))||chr(34)
       ||','||chr(34)||replace(COLUMN_3,chr(34),chr(34)||chr(34))||chr(34) as data
from table_1
</code>```

Example:

if some columns are numeric you don't need doble quotes (").

```<code>"Los Angeles","California, USA","""Hello World"" say John"
</code>```

Body:
I am having ORACLE 11 version installed on my linux machine. I am trying to export data using below. It is working fine for all the tables except for tables having double quotes(") as data in any of column. Below is my code

set echo off
set feedback off
set linesize 30000
set recsep off
set trimspool off
set verify off
set pagesize off
spool "/home/rsau12/file.csv";
SELECT  '"'||COLUMN_1||'"'||','
'"'||COLUMN_2||'"'||','
'"'||COLUMN_3||'"'||','
        ...
'"'||COLUMN_N||'"'
FROM TABLE;
spool off;

Please let me know how to handle if data has (") in it

Body:
You need to replace double quotes(") with two double quotes(""):

select        chr(34)||replace(COLUMN_1,chr(34),chr(34)||chr(34))||chr(34)
       ||','||chr(34)||replace(COLUMN_2,chr(34),chr(34)||chr(34))||chr(34)
       ||','||chr(34)||replace(COLUMN_3,chr(34),chr(34)||chr(34))||chr(34) as data
from table_1

Example:

if some columns are numeric you don't need doble quotes (").

"Los Angeles","California, USA","""Hello World"" say John"


问:
Can I use a collection initializer with LINQ to return a fully populated collection?
I would like to rewrite the following code in one line, using LINQ. Is it possible?

```<code>var to = new MailAddressCollection();

foreach(string recipient in recipients)
{
    to.Add(new MailAddress(recipient));
}
</code>```

Something like the following would be ideal. As written it returns multiple MailAddressCollections:

```<code>var to = recipients.Select(r => new MailAddressCollection() {new MailAddress(r)});
</code>```

Note that these are framework classes, so I cannot rewrite MailAddressCollection to include a constructor argument.

答:
A LINQ expression would return an IEnumerable<MailAddress>, which cannot be directly converted into a MailAddressCollection.

An alternative would be to Join() the addresses and pass the result to MailAddressCollection's Add() method:

```<code>var to = new MailAddressCollection();
to.Add(String.Join(",", recipients));
</code>```

Body:
I would like to rewrite the following code in one line, using LINQ. Is it possible?

var to = new MailAddressCollection();

foreach(string recipient in recipients)
{
    to.Add(new MailAddress(recipient));
}

Something like the following would be ideal. As written it returns multiple MailAddressCollections:

var to = recipients.Select(r => new MailAddressCollection() {new MailAddress(r)});

Note that these are framework classes, so I cannot rewrite MailAddressCollection to include a constructor argument.

Body:
A LINQ expression would return an IEnumerable<MailAddress>, which cannot be directly converted into a MailAddressCollection.

An alternative would be to Join() the addresses and pass the result to MailAddressCollection's Add() method:

var to = new MailAddressCollection();
to.Add(String.Join(",", recipients));


问:
Adaptive frame (widget) size with swiftui shape
I'd like to adapt my widget's size to the widget contents overall size. The problem is, that the standard shape (background of the widget) defaults to the available space and I don't want to hardcode the frame of it. Any suggestions e.g. using GeometryReader?</p>

```<code>struct WidgetView: View {
    var body: some View {

        ZStack {

            RoundedRectangle(cornerRadius: 40, style: .continuous)
                .foregroundColor(.gray)

            Text("TestingText")

        }
    }
}
</code>```

答:
I assume you wanted this

```<code>struct WidgetView: View {
    var body: some View {

        Text("TestingText")
           .background(RoundedRectangle(cornerRadius: 40, style: .continuous)
            .foregroundColor(.gray))
    }
}
</code>```

Update: I think your concern is due to large corner radius that might cut some internal content.

Here is some approach

```<code>struct WidgetView<V: View>: View {   // more generic view
    var content: () -> V
    var body: some View {
        content()
           .background(RoundedRectangle(cornerRadius: 40, style: .continuous)
            .foregroundColor(.gray).padding(-20))  // compensation !!
    }
}
</code>```

Testing (Xcode 11.4 / iOS 13.4)

```<code>WidgetView {
    VStack {
        Image(systemName: "car")
            .resizable().frame(width: 80, height: 80)
        Text("Some Label")
    }
}
</code>```

Output

Body:
I'd like to adapt my widget's size to the widget contents overall size. The problem is, that the standard shape (background of the widget) defaults to the available space and I don't want to hardcode the frame of it. Any suggestions e.g. using GeometryReader?

struct WidgetView: View {
    var body: some View {

        ZStack {

            RoundedRectangle(cornerRadius: 40, style: .continuous)
                .foregroundColor(.gray)

            Text("TestingText")

        }
    }
}

Body:
I assume you wanted this

struct WidgetView: View {
    var body: some View {

        Text("TestingText")
           .background(RoundedRectangle(cornerRadius: 40, style: .continuous)
            .foregroundColor(.gray))
    }
}

Update: I think your concern is due to large corner radius that might cut some internal content.

Here is some approach

struct WidgetView<V: View>: View {   // more generic view
    var content: () -> V
    var body: some View {
        content()
           .background(RoundedRectangle(cornerRadius: 40, style: .continuous)
            .foregroundColor(.gray).padding(-20))  // compensation !!
    }
}

Testing (Xcode 11.4 / iOS 13.4)

WidgetView {
    VStack {
        Image(systemName: "car")
            .resizable().frame(width: 80, height: 80)
        Text("Some Label")
    }
}

Output