问:
How to linkify @usernames and #hashtags with jquery.linkify Plugin
I'm using this jquery plugin: https://github.com/maranomynet/linkify/blob/master/1.0/jquery.linkify-1.0.js

With this REGEX plugins I'm trying to linkify @usernames and #hashtags...

```<code>  linkify.plugins = {
  tUser: {
      re: /(^|\s)@(\w+)/gi,
      tmpl: '$1@<a href="http://domain.com/$2">$2</a>'
  },
  tHashtag: {
      re: /(^|["'(]|<|\s)(#.+?)((?:[:?]|\.+)?(?:\s|$)|>|[)"',])/gi,
      tmpl: function (match, pre, hashTag, post) {
            return pre+'<a href="http://domain.com/search.php?q='+ encodeURIComponent(hashTag) +'">'+hashTag+'</a>'+post;
      }
  }
};
</code>```

... but I'm having some troubles with odd combinations:

(In BOLD what should be linkified but is not)

#hash #hash) (#hash) /#hash

@user @user) (@user) /@user

Any idea on how could I fix the REGEX to match this variations?

Thanks!

答:
I'm not very familiar with linkify, but I'll give this a shot.

The problem with the first regex (@user) is that it isn't matching because it requires leading whitespace or newline -- that's the (^|\s) part. As for the #hash regex, well... that seems unnecessarily complex. Try the following:

```<code>linkify.plugins = {
  tUser: {
    re: /(^|\s|[^\w\d])@(\w+)/gi,
    tmpl: '$1@<a href="http://domain.com/$2">$2</a>'
  },
  tHashtag: {
    re: /(^|\s|[^\w\d])#(\w+)/gi,
    tmpl: function (match, pre, hashTag) {
            return pre+'<a href="http://domain.com/search.php?q='+
                   encodeURIComponent(hashTag) +'">#'+hashTag+'</a>';
    }
  }
};
</code>```

This will match either the @user or #hash so long as they are preceded by a newline, whitespace or a non-word, non-digit character (not a-z, A-Z or 0-9). So your parenthesis won't interfere, but most email addresses won't be picked up either.

Note that the hash symbol won't be included on your search on the linkified hash-tags either.

Body:
I'm using this jquery plugin: https://github.com/maranomynet/linkify/blob/master/1.0/jquery.linkify-1.0.js

With this REGEX plugins I'm trying to linkify @usernames and #hashtags...

  linkify.plugins = {
  tUser: {
      re: /(^|\s)@(\w+)/gi,
      tmpl: '$1@$2'
  },
  tHashtag: {
      re: /(^|["'(]|<|\s)(#.+?)((?:[:?]|\.+)?(?:\s|$)|>|[)"',])/gi,
      tmpl: function (match, pre, hashTag, post) {
            return pre+''+hashTag+''+post;
      }
  }
};

... but I'm having some troubles with odd combinations:

(In BOLD what should be linkified but is not)

#hash #hash) (#hash) /#hash

@user @user) (@user) /@user

Any idea on how could I fix the REGEX to match this variations?

Thanks!

Body:
I'm not very familiar with linkify, but I'll give this a shot.

The problem with the first regex (@user) is that it isn't matching because it requires leading whitespace or newline -- that's the (^|\s) part. As for the #hash regex, well... that seems unnecessarily complex. Try the following:

linkify.plugins = {
  tUser: {
    re: /(^|\s|[^\w\d])@(\w+)/gi,
    tmpl: '$1@<a href="http://domain.com/$2">$2</a>'
  },
  tHashtag: {
    re: /(^|\s|[^\w\d])#(\w+)/gi,
    tmpl: function (match, pre, hashTag) {
            return pre+'<a href="http://domain.com/search.php?q='+
                   encodeURIComponent(hashTag) +'">#'+hashTag+'</a>';
    }
  }
};

This will match either the @user or #hash so long as they are preceded by a newline, whitespace or a non-word, non-digit character (not a-z, A-Z or 0-9). So your parenthesis won't interfere, but most email addresses won't be picked up either.

Note that the hash symbol won't be included on your search on the linkified hash-tags either.


来源: stackexchange

问:
add data from firestore query to array object and map them into Picker react native
my constructor has:

this.ActiveDelegation = {
  cityArr: [],
  name: '',
  expiration: '',
}
```

<p>this is how i get the data from firestore into the object and i assume it add the name inside the <code>cittyArr[]</code> i've created</p>

<pre class="lang-js prettyprint-override"><code>getDelegationList = (querySnapshot) => {
  console.log("snapshot")
  querySnapshot.forEach((res) => {
    const {name, expiration} = res.data();
    console.log('res is =>', res.data())
    this.ActiveDelegation.cityArr.push({
      key: res.id,
      res,
      name,
      expiration,
    });
    //return  <Picker.Item value={name} label={name} />
  });
  console.log('test2: ', this.ActiveDelegation.cityArr)
  //console.log('test12312: ',this.ActiveDelegation.cityArr.city)

  delegList = () => {
    return (this.ActiveDelegation.cityArr.map((c, i) => {
        return (
          <Picker.Item label = {c.name} value = {c.name} key = {i}/>
        )
      }
    ))
  }
}
</code>```

this is inside render:

```<code><Item picker>
  <Picker
    mode="dropdown"
    style={{ width: 20 }}
    placeholder="choose destination"
    placeholderStyle={{ color: "#bfc6ea" }}
    placeholderIconColor="#007aff"
    // selectedValue={this.state.Destination}
    // onValueChange={this.onValueChangeG.bind(this)}
    selectedValue={this.state.selectedDest}
    onValueChange={ (value) => ( this.setState({selectedDest: value}) ) } >
    {this.delegList}
    {/*{cityItems}*/}
    <Picker.Item label="select" value="" />
  </Picker>
</Item>
</code>```

but nothing happen inside my picker..
can anyone help?

答:
i found a solution. just used the map inside the render itself under the picker scope:

```<code><Item picker>
  <Picker
    mode="dropdown"
    style={{ width: 20 }}
    placeholder="choose destination"
    placeholderStyle={{ color: "#bfc6ea" }}
    placeholderIconColor="#007aff"
    selectedValue={this.state.Destination}
    onValueChange={ (value) => ( this.setState({Destination: value}) ) } >
    {/* onValueChange={this.onValueChangeG.bind(this)} >*/}
    {/*<Picker.Item label="choose" value="" />*/}
    {
      this.state.destinationArr.map( (city, i) => {
        return (
          <Picker.Item label={city.name} value={city.name} key={i} />
        )
      })
    }
  </Picker>
</Item>
</code>```

fixed*

ContentLicense: CC BY-SA 4.0

Body:
my constructor has:

this.ActiveDelegation = {
  cityArr: [],
  name: '',
  expiration: '',
}

this is how i get the data from firestore into the object and i assume it add the name inside the cittyArr[] i've created

getDelegationList = (querySnapshot) => {
  console.log("snapshot")
  querySnapshot.forEach((res) => {
    const {name, expiration} = res.data();
    console.log('res is =>', res.data())
    this.ActiveDelegation.cityArr.push({
      key: res.id,
      res,
      name,
      expiration,
    });
    //return  <Picker.Item value={name} label={name} />
  });
  console.log('test2: ', this.ActiveDelegation.cityArr)
  //console.log('test12312: ',this.ActiveDelegation.cityArr.city)

  delegList = () => {
    return (this.ActiveDelegation.cityArr.map((c, i) => {
        return (
          <Picker.Item label = {c.name} value = {c.name} key = {i}/>
        )
      }
    ))
  }
}

this is inside render:

<Item picker>
  <Picker
    mode="dropdown"
    style={{ width: 20 }}
    placeholder="choose destination"
    placeholderStyle={{ color: "#bfc6ea" }}
    placeholderIconColor="#007aff"
    // selectedValue={this.state.Destination}
    // onValueChange={this.onValueChangeG.bind(this)}
    selectedValue={this.state.selectedDest}
    onValueChange={ (value) => ( this.setState({selectedDest: value}) ) } >
    {this.delegList}
    {/*{cityItems}*/}
    <Picker.Item label="select" value="" />
  </Picker>
</Item>

but nothing happen inside my picker..
can anyone help?

Body:
i found a solution. just used the map inside the render itself under the picker scope:

<Item picker>
  <Picker
    mode="dropdown"
    style={{ width: 20 }}
    placeholder="choose destination"
    placeholderStyle={{ color: "#bfc6ea" }}
    placeholderIconColor="#007aff"
    selectedValue={this.state.Destination}
    onValueChange={ (value) => ( this.setState({Destination: value}) ) } >
    {/* onValueChange={this.onValueChangeG.bind(this)} >*/}
    {/*<Picker.Item label="choose" value="" />*/}
    {
      this.state.destinationArr.map( (city, i) => {
        return (
          <Picker.Item label={city.name} value={city.name} key={i} />
        )
      })
    }
  </Picker>
</Item>

fixed*


答: I figured it out, it was because there were some NaN in Y_Train... </p>

Title: I am getting an error that I can't figure out when I run my neural network in Keras as soon as I introduce a class weight

Body:
Model: "sequential"
_________________________________________________________________
Layer (type)                 Output Shape              Param #
=================================================================
conv1d (Conv1D)              (None, 35, 32)            96
_________________________________________________________________
batch_normalization (BatchNo (None, 35, 32)            128
_________________________________________________________________
dropout (Dropout)            (None, 35, 32)            0
_________________________________________________________________
conv1d_1 (Conv1D)            (None, 34, 64)            4160
_________________________________________________________________
batch_normalization_1 (Batch (None, 34, 64)            256
_________________________________________________________________
dropout_1 (Dropout)          (None, 34, 64)            0
_________________________________________________________________
flatten (Flatten)            (None, 2176)              0
_________________________________________________________________
dense (Dense)                (None, 64)                139328
_________________________________________________________________
dropout_2 (Dropout)          (None, 64)                0
_________________________________________________________________
dense_1 (Dense)              (None, 1)                 65
=================================================================
Total params: 144,033
Trainable params: 143,841
Non-trainable params: 192

InvalidArgumentError                      Traceback (most recent call last)
<ipython-input-14-09a8a255f317> in <module>()
----> 1 history = model.fit(X_Train,Y_Train, epochs = epochs, validation_data =(X_Test,Y_Test), verbose=1,class_weight=class_weights1)

8 frames
/usr/local/lib/python3.6/dist-packages/tensorflow/python/eager/execute.py in quick_execute(op_name, num_outputs, inputs, attrs, ctx, name)
     58     ctx.ensure_initialized()
     59     tensors = pywrap_tfe.TFE_Py_Execute(ctx._handle, device_name, op_name,
---> 60                                         inputs, attrs, num_outputs)
     61   except core._NotOkStatusException as e:
     62     if name is not None:

InvalidArgumentError: 2 root error(s) found.
  (0) Invalid argument:  indices[31] = -9223372036854775808 is not in [0, 2)
     [[{{node GatherV2}}]]
     [[IteratorGetNext]]
     [[IteratorGetNext/_2]]
  (1) Invalid argument:  indices[31] = -9223372036854775808 is not in [0, 2)
     [[{{node GatherV2}}]]
     [[IteratorGetNext]]
0 successful operations.
0 derived errors ignored. [Op:__inference_train_function_6381]

Function call stack:
train_function -> train_function

Somehow I'm getting a massive negative number? My dataset is all percentile data so numbers between 0 and 1.

Also here is the code to set up the model:

class_weights1 = {0: 1.,
                1: 50.}

epochs = 1
model = Sequential()
model.add(Conv1D(filters = 32, kernel_size = 2, activation='relu',input_shape=(36,1)))
model.add(BatchNormalization())
model.add(Dropout(0.2))

model.add(Conv1D(filters = 64, kernel_size = 2, activation='relu'))
model.add(BatchNormalization())
model.add(Dropout(0.5))

model.add(Flatten())
model.add(Dense(64,activation='relu'))
model.add(Dropout(0.5))

model.add(Dense(1,activation='sigmoid'))

And then the code to compile and run it:

model.compile(optimizer=Adam(lr=0.005),loss='binary_crossentropy',metrics=['accuracy'])

history = model.fit(X_Train,Y_Train, epochs = epochs, validation_data =(X_Test,Y_Test), verbose=1,class_weight=class_weights1)

I know this is a problem with my class_weight because when I remove it, everything works (but the model is terrible because the data is imbalanced and I need to increase the weight of the minority class to adjust for this).


问:
I can't disable relative numbering from vimrc?
this is driving me insane, i've tried set nonu and set nornu thousands of times in my .vimrc and nothing changes, deleting the numbers.vim plugin made me no difference, does anyone know why this would be happening to me?

edited:

as @Harish said, i did

verbose set nornu?
and this showed me the path to a session.vim that was created in every single directory where i was working on, all these session.vim files were created by this code i have in my .vimrc, which i use to reopen the last file i was working with as soon as i open vim in that same directory

```<code>fu! SaveSess()
    execute 'mksession! ' . getcwd() . '/.session.vim'
endfunction

fu! RestoreSess()
if filereadable(getcwd() . '/.session.vim')
    execute 'so ' . getcwd() . '/.session.vim'
    if bufexists(1)
        for l in range(1, bufnr('$'))
            if bufwinnr(l) == -1
                exec 'sbuffer ' . l
            endif
        endfor
    endif
endif
endfunction

autocmd VimLeave * call SaveSess()
autocmd VimEnter * nested call RestoreSess()
</code>```

it seems that these session.vim files were not being updated with the new changes done in vimrc. what has fixed my issue so far was deleting every single session.vim file created in each directory in order for the changes in vimrc to take effect

答:
```<code>verbose set <option>?
</code>```

This will say where an option was last set.

```<code>verbose set nornu?
</code>```

Body:
this is driving me insane, i've tried set nonu and set nornu thousands of times in my .vimrc and nothing changes, deleting the numbers.vim plugin made me no difference, does anyone know why this would be happening to me?

edited:

as @Harish said, i did

verbose set nornu?
and this showed me the path to a session.vim that was created in every single directory where i was working on, all these session.vim files were created by this code i have in my .vimrc, which i use to reopen the last file i was working with as soon as i open vim in that same directory

fu! SaveSess()
    execute 'mksession! ' . getcwd() . '/.session.vim'
endfunction

fu! RestoreSess()
if filereadable(getcwd() . '/.session.vim')
    execute 'so ' . getcwd() . '/.session.vim'
    if bufexists(1)
        for l in range(1, bufnr('$'))
            if bufwinnr(l) == -1
                exec 'sbuffer ' . l
            endif
        endfor
    endif
endif
endfunction

autocmd VimLeave * call SaveSess()
autocmd VimEnter * nested call RestoreSess()

it seems that these session.vim files were not being updated with the new changes done in vimrc. what has fixed my issue so far was deleting every single session.vim file created in each directory in order for the changes in vimrc to take effect

Body:
verbose set <option>?

This will say where an option was last set.

verbose set nornu?


问:
How can I untar multiple tar files over ssh?
I am attempting to untar multiple tar files over ssh:

```<code>ssh user@hostname "cat /dir/file*.tgz" | tar xvzf -
</code>```

The above only works on the first file match on the remote server. The local (dest) server only receives one file. The wildcard has been verified to match multiple files though.

Is there another way to do this?

答:
```<code>mkdir /tmp/tars
scp 'user@hostname:/dir/file*.tgz' /tmp/tars/
foreach tarname in /tmp/tars/*.tgz; do tar xzvf "$tarname"; done
</code>```

If you absolutely cannot store temp copies:

```<code>ssh user@hostname 'ls /dir/file*.tgz' | while read tarname;
do
    ssh user@hostname "cat '/dir/$tarname'" | tar xzvf -
done
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am attempting to untar multiple tar files over ssh:

ssh user@hostname "cat /dir/file*.tgz" | tar xvzf -

The above only works on the first file match on the remote server. The local (dest) server only receives one file. The wildcard has been verified to match multiple files though.

Is there another way to do this?

Body:
mkdir /tmp/tars
scp 'user@hostname:/dir/file*.tgz' /tmp/tars/
foreach tarname in /tmp/tars/*.tgz; do tar xzvf "$tarname"; done

If you absolutely cannot store temp copies:

ssh user@hostname 'ls /dir/file*.tgz' | while read tarname;
do
    ssh user@hostname "cat '/dir/$tarname'" | tar xzvf -
done


问:
How can I make part of the text in the Entry bold and change its background color?
I am creating a Tkinter-based GUI, and it has an Entry widget. I want to make a part of its text bold and change its background color. But I can't figure out how can I do that. If I use the Text widget I can just use tags but it looks like they can't be used with Entry widget:

This code is using the Text widget:

```<code>import tkinter as tk
from tkinter.font import Font

root = tk.Tk()
text = tk.Text(root, font=Font(size=12))
text.insert("1.0", "I want THIS PART to be bold and have red background")
text.tag_configure("bold-and-red", font=Font(size=12, weight="bold"), background="red")
text.tag_add("bold-and-red", "1.7", "1.16")
text.pack()
root.mainloop()
</code>```

Everything works fine (the Text widget is shown and "THIS PART" is bold and has a red background)

And this code is using the Entry widget:

```<code>import tkinter as tk
from tkinter.font import Font

root = tk.Tk()
entry = tk.Entry(root, font=Font(size=12))
entry.insert(0, "I want THIS PART to be bold and have red background")
entry.tag_configure("bold-and-red", font=Font(size=12, weight="bold"), background="red")
entry.tag_add("bold-and-red", 7, 16)
entry.pack()
root.mainloop()
</code>```

I just get the error:

AttributeError: 'Entry' object has no attribute 'tag_configure'

Is there a way to do what I want for Entry widget?

答:
As @BryanOakley said, the only way to change the appearance of only certain characters is to use a custom Text widget.

Here is an example implementation:

```<code>import tkinter as tk
from tkinter.font import Font

class OneLineText(tk.Text):
    def __init__(self, master, *args, **kwargs):
        super().__init__(master, *args, height=1, wrap="none", **kwargs)

        self.bind("<Return>", lambda event: "break")
        self.bind("<Key>", self.on_keypress)
        self.bind("<Control-a>", self.select_all)
        self.bind("<Control-A>", self.select_all)
        self.bind("<Control-v>", lambda event: self.see("end"))
        self.bind("<Control-V>", lambda event: self.see("end"))

    def on_keypress(self, event):
        self.see("end-1c")

    def select_all(self, event):
        self.tag_add("sel", "1.0", "end-1c")
        return "break"

    def insert(self, index, string):
        string = string.replace("\n", "")
        if isinstance(index, int):
            super().insert("1.{}".format(index), string)
            return
        if index == "end":
            super().insert("end-1c", string)
            return
        super().insert(index, string)

    def get(self):
        return super().get("1.0", "end-1c")

root = tk.Tk()
entry = OneLineText(root, font=Font(size=12))
entry.insert(0, "I want THIS PART to be bold and have red background")
entry.tag_configure("bold-and-red", font=Font(size=12, weight="bold"), background="red")
entry.tag_add("bold-and-red", "1.7", "1.16")
entry.pack()
root.mainloop()
</code>```

insert and get methods of the Text widget are modified to work like they do in the Entry widget.

Body:
I am creating a Tkinter-based GUI, and it has an Entry widget. I want to make a part of its text bold and change its background color. But I can't figure out how can I do that. If I use the Text widget I can just use tags but it looks like they can't be used with Entry widget:

This code is using the Text widget:

import tkinter as tk
from tkinter.font import Font

root = tk.Tk()
text = tk.Text(root, font=Font(size=12))
text.insert("1.0", "I want THIS PART to be bold and have red background")
text.tag_configure("bold-and-red", font=Font(size=12, weight="bold"), background="red")
text.tag_add("bold-and-red", "1.7", "1.16")
text.pack()
root.mainloop()

Everything works fine (the Text widget is shown and "THIS PART" is bold and has a red background)

And this code is using the Entry widget:

import tkinter as tk
from tkinter.font import Font

root = tk.Tk()
entry = tk.Entry(root, font=Font(size=12))
entry.insert(0, "I want THIS PART to be bold and have red background")
entry.tag_configure("bold-and-red", font=Font(size=12, weight="bold"), background="red")
entry.tag_add("bold-and-red", 7, 16)
entry.pack()
root.mainloop()

I just get the error:

AttributeError: 'Entry' object has no attribute 'tag_configure'

Is there a way to do what I want for Entry widget?

Body:
As @BryanOakley said, the only way to change the appearance of only certain characters is to use a custom Text widget.

Here is an example implementation:

import tkinter as tk
from tkinter.font import Font

class OneLineText(tk.Text):
    def __init__(self, master, *args, **kwargs):
        super().__init__(master, *args, height=1, wrap="none", **kwargs)

        self.bind("<Return>", lambda event: "break")
        self.bind("<Key>", self.on_keypress)
        self.bind("<Control-a>", self.select_all)
        self.bind("<Control-A>", self.select_all)
        self.bind("<Control-v>", lambda event: self.see("end"))
        self.bind("<Control-V>", lambda event: self.see("end"))

    def on_keypress(self, event):
        self.see("end-1c")

    def select_all(self, event):
        self.tag_add("sel", "1.0", "end-1c")
        return "break"

    def insert(self, index, string):
        string = string.replace("\n", "")
        if isinstance(index, int):
            super().insert("1.{}".format(index), string)
            return
        if index == "end":
            super().insert("end-1c", string)
            return
        super().insert(index, string)

    def get(self):
        return super().get("1.0", "end-1c")

root = tk.Tk()
entry = OneLineText(root, font=Font(size=12))
entry.insert(0, "I want THIS PART to be bold and have red background")
entry.tag_configure("bold-and-red", font=Font(size=12, weight="bold"), background="red")
entry.tag_add("bold-and-red", "1.7", "1.16")
entry.pack()
root.mainloop()

insert and get methods of the Text widget are modified to work like they do in the Entry widget.


问:
React. TypeError: Cannot read property 'id' of undefined
this is my first question, i'm a newbie dev and i've been working on my first web app for a week. I'm stuck because i'm trying to make a simple mobile e commerce, i've made 8 cards and i've put a plus icon that needs to add the item in the cart when it is clicked, also it has to flip and become a cart icon.

I guess i can't access what it is inside the map method?! and i get the error: TypeError: Cannot read property 'id' of undefined. The problem is inside the some method, I can't come up with any different solution. Any suggestion? Can you help me please? Thanks.

```<code>function Mobile() {
const [hovered, setHovered] = useState(false)
const [cartItems, setCartItems] = useState([])

const mobiles = data.map(mobile => (
    <div className='card' key={mobile.id}
         onMouseEnter = {() => setHovered(true)}
         onMouseLeave = {() => setHovered(false)}

    >
            {cartIcon()}
            <img src= {mobile.img}  alt='Mobile phones' className='mobile-img' />
            <h3 className='mobile-title'>{mobile.title}</h3>
            <p className='mobile-info'>{mobile.info}</p>
            <p className='mobile-price'>€ {mobile.price}</p>
    </div>

))

function addToCart(newItem) {
setCartItems(prevItems => [...prevItems, newItem])
</code>```

}

```<code>function cartIcon() {
const alreadyInCart = cartItems.some(item => item ===  item.id)
if(alreadyInCart) {
    return <i className="ri-shopping-cart-fill cart"></i>
} else if(hovered) {
    return <i className="ri-add-circle-line cart" onClick = {() => addToCart()}></i>
}
</code>```

}

答:
Your function declaration for adding to cart: function addToCart(newItem) expects the item to be passed in as an argument. However, you are passing it nothing:

 addToCart()}>
```

<p>So when it attempts to add the item to the cart here:</p>

<pre class="lang-js prettyprint-override"><code>setCartItems(prevItems => [...prevItems, newItem])
</code>```

newItem is undefined.

Then you attempt to access the property id of undefined and ... error.

cartItems.some(item => item ===  item.id) // <- item is not an object
```

<p>Pass in the <code>item</code> you want to add and it will solve your issue. You will have to add it both to the <code>cartIcon</code> call, and its definition, and then pass it to the <code>addToCart</code> after that.</p>

<p>The final result will include something like the following:</p>

<pre class="lang-js prettyprint-override"><code>{cartIcon(mobile)} // Pass the item

...

function cartIcon(item) { // Expect the item

...

// Add the item
return <i className="ri-add-circle-line cart" onClick = {() => addToCart(item)}></i>
</code>```

Body:
this is my first question, i'm a newbie dev and i've been working on my first web app for a week. I'm stuck because i'm trying to make a simple mobile e commerce, i've made 8 cards and i've put a plus icon that needs to add the item in the cart when it is clicked, also it has to flip and become a cart icon.

I guess i can't access what it is inside the map method?! and i get the error: TypeError: Cannot read property 'id' of undefined. The problem is inside the some method, I can't come up with any different solution. Any suggestion? Can you help me please? Thanks.

function Mobile() {
const [hovered, setHovered] = useState(false)
const [cartItems, setCartItems] = useState([])

const mobiles = data.map(mobile => (

 setHovered(true)}
         onMouseLeave = {() => setHovered(false)}

    >
            {cartIcon()}

{mobile.title}

{mobile.info}

€ {mobile.price}

))

function addToCart(newItem) {
setCartItems(prevItems => [...prevItems, newItem])

}

function cartIcon() {
const alreadyInCart = cartItems.some(item => item ===  item.id)
if(alreadyInCart) {
    return
} else if(hovered) {
    return  addToCart()}>
}

}

Body:
Your function declaration for adding to cart: function addToCart(newItem) expects the item to be passed in as an argument. However, you are passing it nothing:

<i className="ri-add-circle-line cart" onClick = {() => addToCart()}></i>

So when it attempts to add the item to the cart here:

setCartItems(prevItems => [...prevItems, newItem])

newItem is undefined.

Then you attempt to access the property id of undefined and ... error.

cartItems.some(item => item ===  item.id) // <- item is not an object

Pass in the item you want to add and it will solve your issue. You will have to add it both to the cartIcon call, and its definition, and then pass it to the addToCart after that.

The final result will include something like the following:

{cartIcon(mobile)} // Pass the item

...

function cartIcon(item) { // Expect the item

...

// Add the item
return <i className="ri-add-circle-line cart" onClick = {() => addToCart(item)}></i>


问:
How to correctly manage workers in nativescript?
I am currently working on a project involving nativescript-vue and typescript and I must work with workers (im not much familiar with NS and workers). I've read the doc and tried the implementation given in the NS documentation and adapted it to the project but I can't seem to get it right... Indeed it works at first but after calling a few times the method that instantiate and manage the worker, the app crashes without an error... I don't know if its due to the fact that the worker doesn't really close after finishing its task or if there is an issue with the script itself...

this is a part of the code of the main.ts

```<code>import "tns-core-modules/globals"

export class Main extends Vue {
   worker: Worker

 onTaskReceived(task){
   this.manageWorker(task, this.worker)
 }

 manageWorker(task: any, worker: Worker){
   const NewWorker = require('nativescript-worker-loader!./worker.ts')
   worker = new Worker()
   worker.postMessage({
                type: "task",
                value: task
   })
   worker.onerror = await function (err) {
                console.log(`An unhandled error occurred in worker: ${err.filename}, line: ${err.lineno} :`);
                console.log(err.message);
                worker.terminate()
   }
   worker.onmessage = function (message) {
                console.log('{onmessage}')
                worker.terminate()
   }
 }
}

</code>```

and this is the code of one of the worker (worker.ts)

```<code>import "tns-core-modules/globals"
import { error } from "tns-core-modules/trace";

const context: Worker = self as any;

context.onmessage = function(task) {
    const request = task.data
    console.log('[WORKER]: data from main received')
    console.log(request)
    # Here is the code that the worker execute when triggered
    if (result.state === 'done') {
        console.log('[WORKER]: work done - sending data back')
        context.postMessage({
            type: 'result',
            succeed: true,
            value: result
        })
    }

}

context.onerror = function (error) {
    console.log('[WORKER]{ERROR} '+error)
}

export default {} as typeof Worker & (new () => Worker)
</code>```

thank you in advance for your help :)

答:
I see a few errors in your source.

You're importing NewWorker, but then instantiating Worker.

You're importing with a .ts extension.

You call postMessage before assigning onmessage.

You're terminating your worker after one single message is received. It will take longer to boot the worker than to just execute the function in your existing JavaScript context.

Your worker export is different from mine (maybe it isn't an issue?).

In worker.ts:

import 'globals';

const context: Worker = self as any;

context.onmessage = (msg: MessageEvent): any => {
    (global as any).postMessage({output: `rx: ${msg.message}`});
};
```

<p>In wherever else:</p>

<pre class="lang-js prettyprint-override"><code>import * as MyWorker from 'nativescript-worker-loader!./worker';

const worker: MyWorker = new MyWorker();
worker.onmessage((m: MessageEvent) => { console.log(`(out) ${m.output}`) });
worker.postMessage({ message: 'Hello, world!' });

// later: worker.terminate();
</code>```

Body:
I am currently working on a project involving nativescript-vue and typescript and I must work with workers (im not much familiar with NS and workers). I've read the doc and tried the implementation given in the NS documentation and adapted it to the project but I can't seem to get it right... Indeed it works at first but after calling a few times the method that instantiate and manage the worker, the app crashes without an error... I don't know if its due to the fact that the worker doesn't really close after finishing its task or if there is an issue with the script itself...

this is a part of the code of the main.ts

import "tns-core-modules/globals"

export class Main extends Vue {
   worker: Worker

 onTaskReceived(task){
   this.manageWorker(task, this.worker)
 }

 manageWorker(task: any, worker: Worker){
   const NewWorker = require('nativescript-worker-loader!./worker.ts')
   worker = new Worker()
   worker.postMessage({
                type: "task",
                value: task
   })
   worker.onerror = await function (err) {
                console.log(`An unhandled error occurred in worker: ${err.filename}, line: ${err.lineno} :`);
                console.log(err.message);
                worker.terminate()
   }
   worker.onmessage = function (message) {
                console.log('{onmessage}')
                worker.terminate()
   }
 }
}

and this is the code of one of the worker (worker.ts)

import "tns-core-modules/globals"
import { error } from "tns-core-modules/trace";

const context: Worker = self as any;

context.onmessage = function(task) {
    const request = task.data
    console.log('[WORKER]: data from main received')
    console.log(request)
    # Here is the code that the worker execute when triggered
    if (result.state === 'done') {
        console.log('[WORKER]: work done - sending data back')
        context.postMessage({
            type: 'result',
            succeed: true,
            value: result
        })
    }

}

context.onerror = function (error) {
    console.log('[WORKER]{ERROR} '+error)
}

export default {} as typeof Worker & (new () => Worker)

thank you in advance for your help :)

Body:
I see a few errors in your source.

You're importing NewWorker, but then instantiating Worker.

You're importing with a .ts extension.

You call postMessage before assigning onmessage.

You're terminating your worker after one single message is received. It will take longer to boot the worker than to just execute the function in your existing JavaScript context.

Your worker export is different from mine (maybe it isn't an issue?).

In worker.ts:

import 'globals';

const context: Worker = self as any;

context.onmessage = (msg: MessageEvent): any => {
    (global as any).postMessage({output: `rx: ${msg.message}`});
};

In wherever else:

import * as MyWorker from 'nativescript-worker-loader!./worker';

const worker: MyWorker = new MyWorker();
worker.onmessage((m: MessageEvent) => { console.log(`(out) ${m.output}`) });
worker.postMessage({ message: 'Hello, world!' });

// later: worker.terminate();


问:
How to produce a sectional view of 3d-mesh by CGAL
I am running CGAL's 3d mesh examples and modifying them in my own way. But I want to have cut views of those generated meshes just like what CGAL website displays, but CGAL doesn't seem to have given any suggestion of software or code examples to do so. Any ideas to help me out?</p>

答: When you compile the polyhedron demo and run the tetrahedral mesh generator in there, it will provide you a cut plane that you can move around.</p>


问:
how do I center two rows inside a column using css?
hello sorry if this is a basic question, I have 3 columns made using bootstrap, and the image below is the 2nd column I'm trying to center these two rows to the middle of the div (or 2nd col) or make the height of the 2nd column responsive, how can I do this with CSS?

答:
Check this out.

.container {
  display: flex; /* or inline-flex */
  width: 25rem;
  height: 25rem;
  background: grey;
  align-items: center;
  flex-direction: column;
}

.column {
  border: 1px solid black;
  width: 60%;
  height: 3rem;
  background: white;
  margin: 0.5rem;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="column"></div>
  <div class="column"></div>
</div></code>```

Body:
Check this out.

.container {
  display: flex; /* or inline-flex */
  width: 25rem;
  height: 25rem;
  background: grey;
  align-items: center;
  flex-direction: column;
}

.column {
  border: 1px solid black;
  width: 60%;
  height: 3rem;
  background: white;
  margin: 0.5rem;
}

<div class="container">
  <div class="column"></div>
  <div class="column"></div>
</div>


问:
how to get the values of one array of objects key based on values of another array of objects?
```<code>   data = {
{'uid': 12, 'amount': 100},
{'uid': 23, 'amount': 250}
}
object = {12:{'name':'Paul', 'id':12}, 20:{'name':'Mike', 'id':20}, 41:{'name':'Jack', 'id':41}, 23:{'name':'Luke', 'id':23}}
</code>```

the output expected is

```<code>const result = {{'name':'Paul', 'id': 12, 'amount':100}, {'name':'Luke', 'id': 12, 'amount': 250}}
</code>```

I tried mapping the uids to get and array of values like

```<code>uids = [12, 23]
</code>```

then

```<code>        names = uids.map(key => object[key].name);
</code>```

so that I could use them to map the keys and the names in the other object but couldn't figure it out
I know it is basic javascript but I am new to this

答:
You could simply map the object with the given keys.

var array = [12, 23],
    object = { 12: { name: 'Paul', id: 12 }, 20: { name: 'Mike', id: 20 }, 41: { name: 'Jack', id: 41 }, 23: { name: 'Luke', id: 23 } },
    result = array.map(key => object[key]);

console.log(result);```

Body:
   data = {
{'uid': 12, 'amount': 100},
{'uid': 23, 'amount': 250}
}
object = {12:{'name':'Paul', 'id':12}, 20:{'name':'Mike', 'id':20}, 41:{'name':'Jack', 'id':41}, 23:{'name':'Luke', 'id':23}}

the output expected is

const result = {{'name':'Paul', 'id': 12, 'amount':100}, {'name':'Luke', 'id': 12, 'amount': 250}}

I tried mapping the uids to get and array of values like

uids = [12, 23]

then

        names = uids.map(key => object[key].name);

so that I could use them to map the keys and the names in the other object but couldn't figure it out
I know it is basic javascript but I am new to this


问:
How can i set "FILES_ROOT" to a folder on server?
I want to use RoxyFileMan to manage uploaded images and files. But I should save them on the server. As you know, RoxyFileMan Upload uploads files and images in a folder named Uploads in a fileman directory. We can change FILES_ROOT to another local path to change the directory files get uploaded to.

But, I want to upload files on the server and then read them from the server after they've been uploaded so that they can be edited in ckeditor.

Can anyone please provide advice/guidance on how to achive this outcome?

答:
It's not very clear how your question is meant, but if I understand you correctly, you are using RoxyFileMan on a local server and want to upload files to a remote online server, right?

Roxy uploads files to a directory on the server it is run from. Which means if run from localhost, it will use directory on your localhost. If run from a server, it will use a directory on server.

As far as my knowledge goes, you cannot upload from a localhost to an online server directly.

You could maybe achieve that using some custom script to open an FTP connection, but then you would have to also remake all the code to also load images from there... which would be rather silly.


问:
How do I deal with namespaces in XSLT?
I am new to XSL and would like to transform a NewML G2 format XML into another XML.

For example I have:

```<code><?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!--
- Structure: NML2 SNI Text
-->
<!-- ========================================================= -->
<newsMessage xmlns="http://iptc.org/std/nar/2006-10-01/" xmlns:rtr="http://www.reuters.com/ns/2003/08/content" xmlns:x="http://www.w3.org/1999/xhtml" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <header>
    <transmitId>tag:123.com,0000:newsml_N19279043:609406403</transmitId>
    <priority>3</priority>
    <destination>ABX</destination>
  </header>
  <itemSet>
    <newsItem conformance="power" guid="tag:reuters.com,0000:newsml_N19279043" standard="NewsML-G2" standardversion="2.1" version="609406403" xml:lang="en">
      <itemMeta>
        <itemClass qcode="icls:text" rtr:msgType="S"/>
        <provider literal="reuters.com"/>
        <versionCreated>2011-05-20T05:00:27.000Z</versionCreated>
      </itemMeta>
      <contentMeta>
        <urgency>3</urgency>
        <infoSource literal="Reuters" role="cRole:origProv"/>
        <subject qcode="N2:BNK"/>
        <headline>My Headline</headline>
        <by>ABC</by>
      </contentMeta>
      <contentSet>
        <inlineXML contenttype="application/xhtml+html" wordcount="881">
          <html xmlns="http://www.w3.org/1999/xhtml">
            <head>
              <title/>
            </head>
            <body>
              <p>Paragraph A</p>
              <p>* Paragraph A</p>
            </body>
          </html>
        </inlineXML>
      </contentSet>
    </newsItem>
  </itemSet>
</newsMessage>
</code>```

I would like my result XML to be something like:

```<code><?xml version="1.0" encoding="UTF-8"?>
<MyData>
        <MyTransmitId>tag:123.com,0000:newsml_N19279043:609406403</MyTransmitId>
        <MyHeadline>My Headline</MyHeadline>
        <MyContent>
          <html xmlns="http://www.w3.org/1999/xhtml">
            <head>
              <title/>
            </head>
            <body>
              <p>Paragraph A</p>
              <p>* Paragraph A</p>
            </body>
          </html>
        </MyContent>
</MyData>
</code>```

I come out with the following XSL:

```<code><?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:ms="urn:schemas-microsoft-com:xslt">
    <xsl:output method="xml" indent="yes" encoding="utf-8" />
    <xsl:template match="/newsMessage">
    <MyTransmitId>
      <xsl:value-of select="header/transmitId"/>
        </MyTransmitId>
    <MyHeadline>
      <xsl:value-of select="itemSet/newsItem/contentMeta/headline"/>
    </MyHeadline>
    <MyContent>
      <xsl:value-of select="itemSet/newsItem/contentSet/inlineXML"/>
    </MyContent>
  </xsl:template>
</xsl:stylesheet>
</code>```

However it transforms to something not quite right. And I noticed it is because of the element

```<code><newsMessage xmlns="http://iptc.org/std/nar/2006-10-01/" xmlns:rtr="http://www.reuters.com/ns/2003/08/content" xmlns:x="http://www.w3.org/1999/xhtml" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
</code>```

If I change it to the below then my XSL will work:

```<code><newsMessage>
</code>```

How do I transform the element newsMessage with the namespaces properly?

Thank you very much.

答:
I found another solution to this one, posting here for the benefits of others :)</p>

```<code><?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <xsl:output method="xml" encoding="UTF-8" indent="yes" omit-xml-declaration="yes" media-type="text/html"/>
    <xsl:template match="/">
        <xsl:element name="MyData">
            <xsl:element name="MyTransmitId">
                <xsl:value-of select="//*[name()='transmitId']"/>
            </xsl:element>
            <xsl:element name="MyHeadline">
                <xsl:value-of select="//*[name()='headline']"/>
            </xsl:element>
            <xsl:element name="MyContent">
                <xsl:copy-of select="//*[name()='inlineXML']/*"/>
            </xsl:element>
        </xsl:element>
    </xsl:template>
</xsl:stylesheet>
</code>```

Title: How do I deal with namespaces in XSLT?

Body:
I am new to XSL and would like to transform a NewML G2 format XML into another XML.

For example I have:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>

<newsMessage xmlns="http://iptc.org/std/nar/2006-10-01/" xmlns:rtr="http://www.reuters.com/ns/2003/08/content" xmlns:x="http://www.w3.org/1999/xhtml" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

    <transmitId>tag:123.com,0000:newsml_N19279043:609406403</transmitId>
    <priority>3</priority>
    <destination>ABX</destination>

  <itemSet>
    <newsItem conformance="power" guid="tag:reuters.com,0000:newsml_N19279043" standard="NewsML-G2" standardversion="2.1" version="609406403" xml:lang="en">
      <itemMeta>
        <itemClass qcode="icls:text" rtr:msgType="S"/>
        <provider literal="reuters.com"/>
        <versionCreated>2011-05-20T05:00:27.000Z</versionCreated>
      </itemMeta>
      <contentMeta>
        <urgency>3</urgency>
        <infoSource literal="Reuters" role="cRole:origProv"/>
        <subject qcode="N2:BNK"/>
        <headline>My Headline</headline>
        <by>ABC</by>
      </contentMeta>
      <contentSet>
        <inlineXML contenttype="application/xhtml+html" wordcount="881">

              <title/>

Paragraph A

* Paragraph A

        </inlineXML>
      </contentSet>
    </newsItem>
  </itemSet>
</newsMessage>

I would like my result XML to be something like:

<?xml version="1.0" encoding="UTF-8"?>
<MyData>
        <MyTransmitId>tag:123.com,0000:newsml_N19279043:609406403</MyTransmitId>
        <MyHeadline>My Headline</MyHeadline>
        <MyContent>

              <title/>

Paragraph A

* Paragraph A

        </MyContent>
</MyData>

I come out with the following XSL:

<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:ms="urn:schemas-microsoft-com:xslt">
    <xsl:output method="xml" indent="yes" encoding="utf-8" />
    <xsl:template match="/newsMessage">
    <MyTransmitId>
      <xsl:value-of select="header/transmitId"/>
        </MyTransmitId>
    <MyHeadline>
      <xsl:value-of select="itemSet/newsItem/contentMeta/headline"/>
    </MyHeadline>
    <MyContent>
      <xsl:value-of select="itemSet/newsItem/contentSet/inlineXML"/>
    </MyContent>
  </xsl:template>
</xsl:stylesheet>

However it transforms to something not quite right. And I noticed it is because of the element

<newsMessage xmlns="http://iptc.org/std/nar/2006-10-01/" xmlns:rtr="http://www.reuters.com/ns/2003/08/content" xmlns:x="http://www.w3.org/1999/xhtml" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

If I change it to the below then my XSL will work:

<newsMessage>

How do I transform the element newsMessage with the namespaces properly?

Thank you very much.

Body:
I found another solution to this one, posting here for the benefits of others :)

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <xsl:output method="xml" encoding="UTF-8" indent="yes" omit-xml-declaration="yes" media-type="text/html"/>
    <xsl:template match="/">
        <xsl:element name="MyData">
            <xsl:element name="MyTransmitId">
                <xsl:value-of select="//*[name()='transmitId']"/>
            </xsl:element>
            <xsl:element name="MyHeadline">
                <xsl:value-of select="//*[name()='headline']"/>
            </xsl:element>
            <xsl:element name="MyContent">
                <xsl:copy-of select="//*[name()='inlineXML']/*"/>
            </xsl:element>
        </xsl:element>
    </xsl:template>
</xsl:stylesheet>


问:
Dynamically cast to a proper subclass from parent class in a method
I have a Java interface PlatformConfigurable. I also have two classes PlatformProducerConfig and PlatformConsumerConfig.

Later on, I need to add a common config to both that sets a property to an empty string:

```<code>    private PlatformConfigurable disableHostNameVerificationConfig(PlatformConfigurable platformConfig) {
        if (platformConfig instanceof PlatformProducerConfig) {
            PlatformProducerConfig oldConfig = (PlatformProducerConfig) platformConfig;
            Map<String, String> additionalConfig = oldConfig.additionalProperties();
            Map<String, String> newConfig = new HashMap<>(Optional.ofNullable(additionalConfig).orElseGet(ImmutableMap::of));
            newConfig.put(SslConfigs.SSL_ENDPOINT_IDENTIFICATION_ALGORITHM_CONFIG, "");
            return oldConfig.toBuilder().additionalProperties(newConfig).build();
        }
        else if (platformConfig instanceof PlatformConsumerConfig) {
            PlatformConsumerConfig oldConfig = (PlatformConsumerConfig) platformConfig;
            Map<String, String> additionalConfig = platformConfig.additionalProperties();
            Map<String, String> newConfig = new HashMap<>(Optional.ofNullable(additionalConfig).orElseGet(ImmutableMap::of));
            newConfig.put(SslConfigs.SSL_ENDPOINT_IDENTIFICATION_ALGORITHM_CONFIG, "");
            return oldConfig.toBuilder().additionalProperties(newConfig).build();
        }
        return platformConfig;
    }
</code>```

I am casting to producer or consumer config because the PlatformConfigurable interface doesn't have .toBuilder() or .build() methods declared in it, and I don't have access to modify the interface, as I can only implement it.

I would want to get rid of the duplicate code:

```<code>Map<String, String> additionalConfig = platformConfig.additionalProperties();
            Map<String, String> newConfig = new HashMap<>(Optional.ofNullable(additionalConfig).orElseGet(ImmutableMap::of));
            newConfig.put(SslConfigs.SSL_ENDPOINT_IDENTIFICATION_ALGORITHM_CONFIG, "");
            return oldConfig.toBuilder().additionalProperties(newConfig).build();
</code>```

I was thinking of using lambdas, but I am not 100% sure how to do it.

答:
You could just refactor existing code like this:

```<code>private PlatfromConfigurable disableHostNameVerificationConfig(Platfromonfigurable platfromConfig) {
    if (!(platformConfig instanceof PlatformProducerConfig) && !(platformConfig instanceof PlatformConsumerConfig)) {
        return platformConfig;
    }

    Map<String, String> additionalConfig = platformConfig.additionalProperties();
    Map<String, String> newConfig = new HashMap<>(Optional.ofNullable(additionalConfig).orElseGet(ImmutableMap::of));
    newConfig.put(SslConfigs.SSL_ENDPOINT_IDENTIFICATION_ALGORITHM_CONFIG, "");

    if (platformConfig instanceof PlatformProducerConfig) {
        return ((PlatformProducerConfig)platformConfig).toBuilder().additionalProperties(newConfig).build();
    }
    return ((PlatformConsumerConfig)platformConfig).toBuilder().additionalProperties(newConfig).build();
}
</code>```

Update

Another approach could be to extract functionality related to the builder to separate interfaces and use them in this way:

```<code>// 1. extend existing `PlatformConfigurable`
public interface BuilderedPlatformConfigurable extends PlatformConfigurable {
    ConfigPlatformBuilder toBuilder();
}

// 2. provide builder interface with common implementation
public interface ConfigPlatformBuilder {
    Map<String, String> additionalProperties = new HashMap<>();

    BuilderedPlatformConfigurable build();

    default ConfigPlatformBuilder additionalProperties(Map<String, String> properties) {
        this.additionalProperties.clear();
        this.additionalProperties.putAll(properties);
        return this;
    }
}

// 3. update PlatformConsumerConfig class (similarly, PlatformProducerConfig)
public class PlatformConsumerConfig implements BuilderedPlatformConfigurable {
    private Map<String, String> additionalProperties = new HashMap<>();

    @Override
    public Map<String, String> additionalProperties() {
        return additionalProperties;
    }

    public ConfigPlatformBuilder toBuilder() {
        return new Builder();
    }

    public static class Builder implements ConfigPlatformBuilder {
        public PlatformConsumerConfig build() {
            PlatformConsumerConfig config = new PlatformConsumerConfig();
            config.additionalPropertie.putAll(this.additionalProperties);
            return config;
        }
    }
}

// 4. provide overloaded method
private PlatformConfigurable disableHostNameVerificationConfig(PlatformConfigurable platformConfig) {
    return platformConfig;
}

private PlatformConfigurable disableHostNameVerificationConfig(BuilderedPlatformConfigurable platformConfig) {
    Map<String, String> additionalConfig = platformConfig.additionalProperties();
    Map<String, String> newConfig = new HashMap<>(Optional.ofNullable(additionalConfig).orElseGet(Map::of));
    newConfig.put(SslConfigs.SSL_ENDPOINT_IDENTIFICATION_ALGORITHM_CONFIG, "");

    return platformConfig.toBuilder().additionalProperties(newConfig).build();
}

</code>```

Body:
I have a Java interface PlatformConfigurable. I also have two classes PlatformProducerConfig and PlatformConsumerConfig.

Later on, I need to add a common config to both that sets a property to an empty string:

    private PlatformConfigurable disableHostNameVerificationConfig(PlatformConfigurable platformConfig) {
        if (platformConfig instanceof PlatformProducerConfig) {
            PlatformProducerConfig oldConfig = (PlatformProducerConfig) platformConfig;
            Map<String, String> additionalConfig = oldConfig.additionalProperties();
            Map<String, String> newConfig = new HashMap<>(Optional.ofNullable(additionalConfig).orElseGet(ImmutableMap::of));
            newConfig.put(SslConfigs.SSL_ENDPOINT_IDENTIFICATION_ALGORITHM_CONFIG, "");
            return oldConfig.toBuilder().additionalProperties(newConfig).build();
        }
        else if (platformConfig instanceof PlatformConsumerConfig) {
            PlatformConsumerConfig oldConfig = (PlatformConsumerConfig) platformConfig;
            Map<String, String> additionalConfig = platformConfig.additionalProperties();
            Map<String, String> newConfig = new HashMap<>(Optional.ofNullable(additionalConfig).orElseGet(ImmutableMap::of));
            newConfig.put(SslConfigs.SSL_ENDPOINT_IDENTIFICATION_ALGORITHM_CONFIG, "");
            return oldConfig.toBuilder().additionalProperties(newConfig).build();
        }
        return platformConfig;
    }

I am casting to producer or consumer config because the PlatformConfigurable interface doesn't have .toBuilder() or .build() methods declared in it, and I don't have access to modify the interface, as I can only implement it.

I would want to get rid of the duplicate code:

Map<String, String> additionalConfig = platformConfig.additionalProperties();
            Map<String, String> newConfig = new HashMap<>(Optional.ofNullable(additionalConfig).orElseGet(ImmutableMap::of));
            newConfig.put(SslConfigs.SSL_ENDPOINT_IDENTIFICATION_ALGORITHM_CONFIG, "");
            return oldConfig.toBuilder().additionalProperties(newConfig).build();

I was thinking of using lambdas, but I am not 100% sure how to do it.

Body:
You could just refactor existing code like this:

private PlatfromConfigurable disableHostNameVerificationConfig(Platfromonfigurable platfromConfig) {
    if (!(platformConfig instanceof PlatformProducerConfig) && !(platformConfig instanceof PlatformConsumerConfig)) {
        return platformConfig;
    }

    Map<String, String> additionalConfig = platformConfig.additionalProperties();
    Map<String, String> newConfig = new HashMap<>(Optional.ofNullable(additionalConfig).orElseGet(ImmutableMap::of));
    newConfig.put(SslConfigs.SSL_ENDPOINT_IDENTIFICATION_ALGORITHM_CONFIG, "");

    if (platformConfig instanceof PlatformProducerConfig) {
        return ((PlatformProducerConfig)platformConfig).toBuilder().additionalProperties(newConfig).build();
    }
    return ((PlatformConsumerConfig)platformConfig).toBuilder().additionalProperties(newConfig).build();
}

Update

Another approach could be to extract functionality related to the builder to separate interfaces and use them in this way:

// 1. extend existing `PlatformConfigurable`
public interface BuilderedPlatformConfigurable extends PlatformConfigurable {
    ConfigPlatformBuilder toBuilder();
}

// 2. provide builder interface with common implementation
public interface ConfigPlatformBuilder {
    Map<String, String> additionalProperties = new HashMap<>();

    BuilderedPlatformConfigurable build();

    default ConfigPlatformBuilder additionalProperties(Map<String, String> properties) {
        this.additionalProperties.clear();
        this.additionalProperties.putAll(properties);
        return this;
    }
}

// 3. update PlatformConsumerConfig class (similarly, PlatformProducerConfig)
public class PlatformConsumerConfig implements BuilderedPlatformConfigurable {
    private Map<String, String> additionalProperties = new HashMap<>();

    @Override
    public Map<String, String> additionalProperties() {
        return additionalProperties;
    }

    public ConfigPlatformBuilder toBuilder() {
        return new Builder();
    }

    public static class Builder implements ConfigPlatformBuilder {
        public PlatformConsumerConfig build() {
            PlatformConsumerConfig config = new PlatformConsumerConfig();
            config.additionalPropertie.putAll(this.additionalProperties);
            return config;
        }
    }
}

// 4. provide overloaded method
private PlatformConfigurable disableHostNameVerificationConfig(PlatformConfigurable platformConfig) {
    return platformConfig;
}

private PlatformConfigurable disableHostNameVerificationConfig(BuilderedPlatformConfigurable platformConfig) {
    Map<String, String> additionalConfig = platformConfig.additionalProperties();
    Map<String, String> newConfig = new HashMap<>(Optional.ofNullable(additionalConfig).orElseGet(Map::of));
    newConfig.put(SslConfigs.SSL_ENDPOINT_IDENTIFICATION_ALGORITHM_CONFIG, "");

    return platformConfig.toBuilder().additionalProperties(newConfig).build();
}


问:
What is the idiomatic Haskell-way to act on predicates in IO?
For some file operation, I need to check if the file exists, if it has been modified, and only then perform some operation on it. My newbie Haskell code looks as follows (simplified):

```<code>someFileOp ::FileContents -> FilePath -> IO (FileOpResult)
someFileOp contents absFilePath = do
    fileExists <- DIR.doesFileExist absFilePath
    if fileExists
        then do
            isMod <- isModified contents absFilePath
            if isMod
                then return FileModified
            else return $ doSomethingWithFile
        else return FileNotFound
</code>```

It does work. However, the nested if-expressions look wrong to me - not FP-like. What would be an idiomatic way to check several Boolean conditions in IO and then take some action depending on their result?

答:
Ignoring Daniel's good point on races and why checking for files is often just not done, the more Haskell solution is usually a monad transformer.  This is a typical case where an ExceptT transformer makes sense.  I've also included a (mis)use of ContT in case you're curious and want to explore:</p>

```<code>import System.Directory as DIR
import Control.Monad.Trans.Cont
import Control.Monad
import Control.Monad.IO.Class
import Control.Monad.Trans.Except

isModified :: a -> b -> IO Bool
isModified _ _ = pure False

type FileOpResult = Either String String

someFileOp_cont :: String -> FilePath -> IO FileOpResult
someFileOp_cont contents absFilePath = evalContT $ callCC $ \exit -> do
    fileExists <- liftIO $ DIR.doesFileExist absFilePath
    unless fileExists (exit (Left "FileNotFound"))
    isMod <- liftIO $ isModified contents absFilePath
    when isMod (exit (Left "FileModified"))
    return (Right "doSomethingWithFile")

someFileOp_except :: String -> FilePath -> IO FileOpResult
someFileOp_except contents absFilePath = runExceptT $ do
    fileExists <- liftIO $ DIR.doesFileExist absFilePath
    unless fileExists (throwE "FileNotFound")
    isMod <- liftIO $ isModified contents absFilePath
    when isMod (throwE "FileModified")
    return "doSomethingWithFile"
</code>```

Body:
For some file operation, I need to check if the file exists, if it has been modified, and only then perform some operation on it. My newbie Haskell code looks as follows (simplified):

someFileOp ::FileContents -> FilePath -> IO (FileOpResult)
someFileOp contents absFilePath = do
    fileExists <- DIR.doesFileExist absFilePath
    if fileExists
        then do
            isMod <- isModified contents absFilePath
            if isMod
                then return FileModified
            else return $ doSomethingWithFile
        else return FileNotFound

It does work. However, the nested if-expressions look wrong to me - not FP-like. What would be an idiomatic way to check several Boolean conditions in IO and then take some action depending on their result?

Body:
Ignoring Daniel's good point on races and why checking for files is often just not done, the more Haskell solution is usually a monad transformer.  This is a typical case where an ExceptT transformer makes sense.  I've also included a (mis)use of ContT in case you're curious and want to explore:

import System.Directory as DIR
import Control.Monad.Trans.Cont
import Control.Monad
import Control.Monad.IO.Class
import Control.Monad.Trans.Except

isModified :: a -> b -> IO Bool
isModified _ _ = pure False

type FileOpResult = Either String String

someFileOp_cont :: String -> FilePath -> IO FileOpResult
someFileOp_cont contents absFilePath = evalContT $ callCC $ \exit -> do
    fileExists <- liftIO $ DIR.doesFileExist absFilePath
    unless fileExists (exit (Left "FileNotFound"))
    isMod <- liftIO $ isModified contents absFilePath
    when isMod (exit (Left "FileModified"))
    return (Right "doSomethingWithFile")

someFileOp_except :: String -> FilePath -> IO FileOpResult
someFileOp_except contents absFilePath = runExceptT $ do
    fileExists <- liftIO $ DIR.doesFileExist absFilePath
    unless fileExists (throwE "FileNotFound")
    isMod <- liftIO $ isModified contents absFilePath
    when isMod (throwE "FileModified")
    return "doSomethingWithFile"


答:
The code you posted looks fine to me. Another possibility would be to act in a short-circuiting monad like ExceptT Err IO.

```<code>data Err = FileNotFound | FileModified

getFileContents :: FilePath -> ExceptT Err IO FileContents
getFileContents fp = do
    exists <- doesFileExist fp
    if exists then {- ... -} else throwError FileNotFound

someFileOp :: FileContents -> FilePath -> ExceptT Err IO FileOpResult
someFileOp fc fp = do
    fc' <- getFileContents fp
    when (fc /= fc') (throwError FileModified)
    doSomethingWithFile
</code>```

Title: What is the idiomatic Haskell-way to act on predicates in IO?

Body:
The code you posted looks fine to me. Another possibility would be to act in a short-circuiting monad like ExceptT Err IO.

data Err = FileNotFound | FileModified

getFileContents :: FilePath -> ExceptT Err IO FileContents
getFileContents fp = do
    exists <- doesFileExist fp
    if exists then {- ... -} else throwError FileNotFound

someFileOp :: FileContents -> FilePath -> ExceptT Err IO FileOpResult
someFileOp fc fp = do
    fc' <- getFileContents fp
    when (fc /= fc') (throwError FileModified)
    doSomethingWithFile


问:
A very big sum - Hacker Rank
I am trying to solve "A very big sum" challenge on Hacker Rank: https://www.hackerrank.com/challenges/a-very-big-sum/problem

In there I have to sum all the numbers in the array given so I came up with two solutions:

First solution

```<code>function aVeryBigSum(ar){
  let sum = 0;
  for(let i = 0; i < ar.length; i++){
     sum += i;
   }
}
</code>```

Second Solution

```<code>function(ar){
 let sum = ar.reduce((accumulator, currentValue) => {
  accumulator + currentValue;
    });
}
</code>```

But none of them work and I don´t know why, I am thiniking maybe I am not writing it as Hacker Rank wants me to but I am not sure

答:
In your first solution, you should index the array instead of just adding up the indexes:

```<code>function aVeryBigSum(ar){
  let sum = 0;
  for(let i = 0; i < ar.length; i++){
     sum += ar[i];
  }
  return sum;
}
</code>```

To sum the array with reduce:

```<code>function aVeryBigSum(ar){
  return ar.reduce((a, b) => a + b, 0);
}
</code>```

Also, note that you should return values in the functions.
Although this works for arrays with small numbers, you should think about what can happen if the sum gets very large. (See the note section on HackerRank.)

Title: A very big sum - Hacker Rank

Body:
I am trying to solve "A very big sum" challenge on Hacker Rank: https://www.hackerrank.com/challenges/a-very-big-sum/problem

In there I have to sum all the numbers in the array given so I came up with two solutions:

First solution

function aVeryBigSum(ar){
  let sum = 0;
  for(let i = 0; i < ar.length; i++){
     sum += i;
   }
}

Second Solution

function(ar){
 let sum = ar.reduce((accumulator, currentValue) => {
  accumulator + currentValue;
    });
}

But none of them work and I don´t know why, I am thiniking maybe I am not writing it as Hacker Rank wants me to but I am not sure

Body:
In your first solution, you should index the array instead of just adding up the indexes:

function aVeryBigSum(ar){
  let sum = 0;
  for(let i = 0; i < ar.length; i++){
     sum += ar[i];
  }
  return sum;
}

To sum the array with reduce:

function aVeryBigSum(ar){
  return ar.reduce((a, b) => a + b, 0);
}

Also, note that you should return values in the functions.
Although this works for arrays with small numbers, you should think about what can happen if the sum gets very large. (See the note section on HackerRank.)


答:
I'd use whenM :: Monad m => m Bool -> m () -> m() or ifM :: Monad m => m Bool -> m a -> m a -> m a, available for example in extra:

-- | Like 'when', but where the test can be monadic.
whenM :: Monad m => m Bool -> m () -> m ()
whenM mb mt = mb >>= \b ->
  if b
    then mt
    else return ()

-- | Like @if@, but where the test can be monadic.
ifM :: Monad m => m Bool -> m a -> m a -> m a
ifM mb mt me = mb >>= \b ->
  if b
    then mt
    else me
```


问:
Can't create [id] attribute in Grakn
I'm trying to define a new attribute id like so:

```<code>define
id sub attribute, datatype double;
</code>```

However when I try this, I get this syntax error:

```<code>define id sub attribute, datatype double;
       ^
no viable alternative at input 'id'
syntax error at line 1:
define id sub attribute, datatype double;
       ^
mismatched input 'id' expecting {'match', 'define', 'undefine', 'insert', 'compute'}
All uncommitted data is cleared
</code>```

Is it not possible to create an attribute called id?

答:
id is a reserved keyword in Graql.

Therefore, you cannot have a user-defined type called id, I suggest using identifier instead.

id is used for matching concepts in Grakn by their Grakn-generated id, like so:

```<code>match $x id V12345; get;
</code>```

although the recommended approach is instead to match using a user-defined key.

Title: Can't create [id] attribute in Grakn

Body:
I'm trying to define a new attribute id like so:

define
id sub attribute, datatype double;

However when I try this, I get this syntax error:

define id sub attribute, datatype double;
       ^
no viable alternative at input 'id'
syntax error at line 1:
define id sub attribute, datatype double;
       ^
mismatched input 'id' expecting {'match', 'define', 'undefine', 'insert', 'compute'}
All uncommitted data is cleared

Is it not possible to create an attribute called id?

Body:
id is a reserved keyword in Graql.

Therefore, you cannot have a user-defined type called id, I suggest using identifier instead.

id is used for matching concepts in Grakn by their Grakn-generated id, like so:

match $x id V12345; get;

although the recommended approach is instead to match using a user-defined key.


问:
How can I add a Drop Down List into every cell for a specific column in a DataGridView in C#
I am trying to add a drop down list into all cells for a column in a datagridView in my Winforms Application. I have created the view programatically by dragging the dgv into the form, and adding columns upon the creation of the class.

The drop down list appears in my DGV column, however when I click on the list nothing opens up - i am unsure if the ComboBox is populated and not opening, or if it simply does not contain values for user to select. Hovering over the object when adding the comboBox to the cell, i can see the item array populated with my values..

Please advise on how I can allow the user to select values in the cell that are populated from my list

```<code>            DataGridViewTextBoxColumn diffKey = new DataGridViewTextBoxColumn();
            DataGridViewComboBoxColumn matchDesc = new DataGridViewComboBoxColumn();
            DataGridViewTextBoxColumn permDiff = new DataGridViewTextBoxColumn();

        grdEditAnnot.Columns.Add(diffKey);
        grdEditAnnot.Columns.Add(matchDesc);
        grdEditAnnot.Columns.Add(permDiff);

        DataGridViewComboBoxCell matchDescDropbox = new DataGridViewComboBoxCell();

        List<string> lstMatchDesc = new List<string>();

        LoadMatchDescriptions(out lstMatchDesc);

        foreach (string ddlItem in lstMatchDesc)
        {
            matchDescDropbox.Items.Add(ddlItem);
        }

        grdEditAnnot.Rows.Add(2);

        matchDescDropbox.DataSource = GetMatchDescDDL(); // Bind combobox with datasource.
        matchDescDropbox.ValueMember = "Description";
        matchDescDropbox.DisplayMember = "Description";

        grdEditAnnot.Rows[0].Cells[1] = matchDescDropbox;

    }

    private DataTable GetMatchDescDDL()
    {
        DataTable l_dtDescription = new DataTable();
        l_dtDescription.Columns.Add("Description", typeof(string));

        List<string> matchDescLst;

        if (LoadMatchDescriptions(out matchDescLst) == 0)
        {
            foreach(string matchDesc in matchDescLst)
            {
                l_dtDescription.Rows.Add(matchDesc);
            }
        }

        return l_dtDescription;
    }

    private int LoadMatchDescriptions(out List<string> matchDscLst)
    {
        //string SQL = SQL USED TO POPULATE MY LIST
        //a temporary list of test strings would work to show how to get this to work... ex: list of test1, test2, test3 etc

        try
        {
            matchDscLst = new List<string>();
            rdr.ExecuteSQL(SQL);
            while ((rec = rdr.FetchNextRecord()) != null)
            {
                matchDscLst.Add(rec.GetStringVal(0));
            }

            return 0;
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, "Error Loading Match Descriptions", MessageBoxButtons.OK, MessageBoxIcon.Error);

            matchDscLst = new List<string>();
            return -1;
        }
    }
</code>```

This is my first post on StackOverflow; apologies if this is not in best format or if we need more info..

Result of code:
Grid that is created; user cannot open up comboBox or type into textbox columns

答:
use  DataGridViewComboBoxCell

look this  example :
https://www.aspsnippets.com/Articles/Add-ComboBox-to-DataGridView-in-Windows-Forms-Application-using-C-and-VBNet.aspx

Body:
I am trying to add a drop down list into all cells for a column in a datagridView in my Winforms Application. I have created the view programatically by dragging the dgv into the form, and adding columns upon the creation of the class.

The drop down list appears in my DGV column, however when I click on the list nothing opens up - i am unsure if the ComboBox is populated and not opening, or if it simply does not contain values for user to select. Hovering over the object when adding the comboBox to the cell, i can see the item array populated with my values..

Please advise on how I can allow the user to select values in the cell that are populated from my list

            DataGridViewTextBoxColumn diffKey = new DataGridViewTextBoxColumn();
            DataGridViewComboBoxColumn matchDesc = new DataGridViewComboBoxColumn();
            DataGridViewTextBoxColumn permDiff = new DataGridViewTextBoxColumn();

        grdEditAnnot.Columns.Add(diffKey);
        grdEditAnnot.Columns.Add(matchDesc);
        grdEditAnnot.Columns.Add(permDiff);

        DataGridViewComboBoxCell matchDescDropbox = new DataGridViewComboBoxCell();

        List<string> lstMatchDesc = new List<string>();

        LoadMatchDescriptions(out lstMatchDesc);

        foreach (string ddlItem in lstMatchDesc)
        {
            matchDescDropbox.Items.Add(ddlItem);
        }

        grdEditAnnot.Rows.Add(2);

        matchDescDropbox.DataSource = GetMatchDescDDL(); // Bind combobox with datasource.
        matchDescDropbox.ValueMember = "Description";
        matchDescDropbox.DisplayMember = "Description";

        grdEditAnnot.Rows[0].Cells[1] = matchDescDropbox;

    }

    private DataTable GetMatchDescDDL()
    {
        DataTable l_dtDescription = new DataTable();
        l_dtDescription.Columns.Add("Description", typeof(string));

        List<string> matchDescLst;

        if (LoadMatchDescriptions(out matchDescLst) == 0)
        {
            foreach(string matchDesc in matchDescLst)
            {
                l_dtDescription.Rows.Add(matchDesc);
            }
        }

        return l_dtDescription;
    }

    private int LoadMatchDescriptions(out List<string> matchDscLst)
    {
        //string SQL = SQL USED TO POPULATE MY LIST
        //a temporary list of test strings would work to show how to get this to work... ex: list of test1, test2, test3 etc

        try
        {
            matchDscLst = new List<string>();
            rdr.ExecuteSQL(SQL);
            while ((rec = rdr.FetchNextRecord()) != null)
            {
                matchDscLst.Add(rec.GetStringVal(0));
            }

            return 0;
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, "Error Loading Match Descriptions", MessageBoxButtons.OK, MessageBoxIcon.Error);

            matchDscLst = new List<string>();
            return -1;
        }
    }

This is my first post on StackOverflow; apologies if this is not in best format or if we need more info..

Result of code:
Grid that is created; user cannot open up comboBox or type into textbox columns


问:
Find all integers that multiplied gives X?
If I have a number, let's say 12, how can I calculate all integers that multiplied will give 12?

Example: If 12, then the solution would be 1x12, 2x6, 3x4.

How would that be done?

答:
Christian's Works for a brute force method, to be more elegant try to implement some integer factorization algorithm.

EDIT:

After digging though CPAN (you always should) I found Math::Factor::XS, here is an example (also I mocked up a pure Perl example using grep/map):

```<code>#!/usr/bin/perl
use strict;
use warnings;
use 5.10.0;

use Math::Factor::XS qw/factors matches/;

my $num = 12;

say "Factors:";
my @factors = factors $num;
say for @factors;

say "Matches:";
say $_->[0] . "x" . $_->[1] for ( [ 1, $num ] , matches($num, \@factors));

# using grep
say "Grep:";
my @grep_factors = map { [ $_ , $num / $_ ] } grep { !($num % $_) } (1 .. int sqrt $num);
say $_->[0] . "x" . $_->[1] for @grep_factors;
</code>```

Body:
Christian's Works for a brute force method, to be more elegant try to implement some integer factorization algorithm.

EDIT:

After digging though CPAN (you always should) I found Math::Factor::XS, here is an example (also I mocked up a pure Perl example using grep/map):

#!/usr/bin/perl
use strict;
use warnings;
use 5.10.0;

use Math::Factor::XS qw/factors matches/;

my $num = 12;

say "Factors:";
my @factors = factors $num;
say for @factors;

say "Matches:";
say $_->[0] . "x" . $_->[1] for ( [ 1, $num ] , matches($num, \@factors));

# using grep
say "Grep:";
my @grep_factors = map { [ $_ , $num / $_ ] } grep { !($num % $_) } (1 .. int sqrt $num);
say $_->[0] . "x" . $_->[1] for @grep_factors;


问:
In Google Sheets, count a row when date is in a certain range while range is in two different columns
In Google Sheets I would like to:

count the number of rows in a column

where a given date

is greater than or equal to the date in column "in progress"

is smaller than or equal to the date in column "closed"

A dataset example:

```<code>In progress Closed
09/02/2019  10/02/2019
10/02/2019  11/02/2019
11/02/2019  11/02/2019
11/02/2019  12/02/2019
12/02/2019  13/02/2019
05/02/2019  18/02/2019
</code>```

I would like to set a certain date and count the rows that are within that range.

E.g. date = 11/02/2019 would give the following output:

```<code>In progress Closed      Expected Outcome
09/02/2019  10/02/2019  0
10/02/2019  11/02/2019  1
11/02/2019  11/02/2019  1
11/02/2019  12/02/2019  1
12/02/2019  13/02/2019  0
05/02/2019  18/02/2019  1
</code>```

In my sheet I have two columns and I expect something like this based on above data:

```<code>Date         Work in Progress
10/02/2019   3
11/02/2019   4
12/02/2019   3
13/02/2019   2
20/02/2019   0
</code>```

How can I achieve this in Google Sheets?

I've tried a lot of different functions and aggregates, but nothing gives me the desired result. COUNT only works for one row, COUNTIF only seems to accept a range within 1 column and combinations of IF, SUM, AND, COUNT, COUNTIF all don't return the right values.

答:
Provided A is your "in progress" column, B is your "Closed" column, and C is your "Date" column, I think this will give you what you want

```<code>=countifs(A:A,"<="&C6,B:B,">="&C6)
</code>```

Body:
In Google Sheets I would like to:

count the number of rows in a column

where a given date

is greater than or equal to the date in column "in progress"

is smaller than or equal to the date in column "closed"

A dataset example:

In progress Closed
09/02/2019  10/02/2019
10/02/2019  11/02/2019
11/02/2019  11/02/2019
11/02/2019  12/02/2019
12/02/2019  13/02/2019
05/02/2019  18/02/2019

I would like to set a certain date and count the rows that are within that range.

E.g. date = 11/02/2019 would give the following output:

In progress Closed      Expected Outcome
09/02/2019  10/02/2019  0
10/02/2019  11/02/2019  1
11/02/2019  11/02/2019  1
11/02/2019  12/02/2019  1
12/02/2019  13/02/2019  0
05/02/2019  18/02/2019  1

In my sheet I have two columns and I expect something like this based on above data:

Date         Work in Progress
10/02/2019   3
11/02/2019   4
12/02/2019   3
13/02/2019   2
20/02/2019   0

How can I achieve this in Google Sheets?

I've tried a lot of different functions and aggregates, but nothing gives me the desired result. COUNT only works for one row, COUNTIF only seems to accept a range within 1 column and combinations of IF, SUM, AND, COUNT, COUNTIF all don't return the right values.

Body:
Provided A is your "in progress" column, B is your "Closed" column, and C is your "Date" column, I think this will give you what you want

=countifs(A:A,"<="&C6,B:B,">="&C6)


问:
pushing a new remote branch gives error committer e-mail address does not match
With a command similar to

```<code>git checkout -b a7e4767 new-branch
git push origin new-branch
</code>```

I get the following error

```<code>remote: ERROR:  In commit a7e4767a80e9b0730c8708973918c990af308a45
remote: ERROR:  committer email address someone.else@xyz.com
remote: ERROR:  does not match your user account.
remote: ERROR:
remote: ERROR:  The following addresses are currently registered:
remote: ERROR:    my.self@sap.com
</code>```

All my search turns up suggestions for amending the commit, but I don't think I want to amend that old commit.

答:
I experienced the same error when our corporate  email address changed and for me was easily fixed with :

```<code>#!/bin/sh

git filter-branch --env-filter '

OLD_EMAIL="your-old-email@example.com"
CORRECT_NAME="Your Correct Name"
CORRECT_EMAIL="your-correct-email@example.com"

if [ "$GIT_COMMITTER_EMAIL" = "$OLD_EMAIL" ]
then
export GIT_COMMITTER_NAME="$CORRECT_NAME"
export GIT_COMMITTER_EMAIL="$CORRECT_EMAIL"
fi
if [ "$GIT_AUTHOR_EMAIL" = "$OLD_EMAIL" ]
then
export GIT_AUTHOR_NAME="$CORRECT_NAME"
export GIT_AUTHOR_EMAIL="$CORRECT_EMAIL"
fi
' --tag-name-filter cat -- --branches --tags
</code>```

Run in the root of the git repo.

Based on :
https://help.github.com/en/github/using-git/changing-author-info

I also edited the repo's .git/config to add the user stanza :

```<code>[user]
  name = Your Correct Name
  email = your-correct-email@example.com
</code>```

Then

```<code>git commit --amend --reset-author
git push
</code>```

PS: This is on a Gerrit Server

Body:
With a command similar to

git checkout -b a7e4767 new-branch
git push origin new-branch

I get the following error

remote: ERROR:  In commit a7e4767a80e9b0730c8708973918c990af308a45
remote: ERROR:  committer email address someone.else@xyz.com
remote: ERROR:  does not match your user account.
remote: ERROR:
remote: ERROR:  The following addresses are currently registered:
remote: ERROR:    my.self@sap.com

All my search turns up suggestions for amending the commit, but I don't think I want to amend that old commit.

Body:
I experienced the same error when our corporate  email address changed and for me was easily fixed with :

#!/bin/sh

git filter-branch --env-filter '

OLD_EMAIL="your-old-email@example.com"
CORRECT_NAME="Your Correct Name"
CORRECT_EMAIL="your-correct-email@example.com"

if [ "$GIT_COMMITTER_EMAIL" = "$OLD_EMAIL" ]
then
export GIT_COMMITTER_NAME="$CORRECT_NAME"
export GIT_COMMITTER_EMAIL="$CORRECT_EMAIL"
fi
if [ "$GIT_AUTHOR_EMAIL" = "$OLD_EMAIL" ]
then
export GIT_AUTHOR_NAME="$CORRECT_NAME"
export GIT_AUTHOR_EMAIL="$CORRECT_EMAIL"
fi
' --tag-name-filter cat -- --branches --tags

Run in the root of the git repo.

Based on :
https://help.github.com/en/github/using-git/changing-author-info

I also edited the repo's .git/config to add the user stanza :

[user]
  name = Your Correct Name
  email = your-correct-email@example.com

Then

git commit --amend --reset-author
git push

PS: This is on a Gerrit Server


问:
TRY_PARSE but faster
What would be the quickest way of transforming a large number (almost 100) of nvarchar columns to floats?

At the moment I have a bunch of TRY_PARSE(column-name AS FLOAT) statements, one per column.

Where a column does not parse to float, I want NULL. No error notifications, no extra intelligence.

Is there a quicker way? If so, what would it be?

SQL Server 2012

答:
Unfortunately, the general answer is that TRY_PARSE can't be replaced by TRY_CAST or TRY_CONVERT in cases where the user requires the field parsed with a particular culture.

If you're doing simple, straightforward conversions like '... AS INT' then use TRY_CAST or TRY_CONVERT. If you require a translation with a culture, you'll have to stick with TRY_PARSE.

Title: TRY_PARSE but faster


问:
How to put assert into release builds in C/C++
I need to only run ship build and I need to assert on certain condition in release build to see if the problem is fixed. How do I do it?</p>

答:
Undefine the NDEBUG macro - you can do this locally around the asserts you want to remain in the build:

```<code>#undef NDEBUG
#include <assert.h>   // reinclude the header to update the definition of assert()
</code>```

or do whatever you need to do so your build process does not define the NDEBUG macro in the first place.

OwnerDisplayName: pra che

ContentLicense: CC BY-SA 2.5

Body:
Undefine the NDEBUG macro - you can do this locally around the asserts you want to remain in the build:

#undef NDEBUG
#include <assert.h>   // reinclude the header to update the definition of assert()

or do whatever you need to do so your build process does not define the NDEBUG macro in the first place.

OwnerDisplayName: Michael Burr


问:
Django - Render the  of a single form field
I'm selectively rendering fields on a form.

```<code>class SomeForm(forms.Form):
    foo = forms.ChoiceField(label='Some Foo', ...)
    bar = forms.BooleanField(label='Some Bar', ...)
    ...
</code>```

I've got a custom tag that, based on some other logic, lets me iterate over the fields of the form that I need using the FIELD context variable in the tag:

```<code>{% fieldsineed %}
  {% if FIELD.field.widget|klass == "CheckboxInput" %}
    <li>{{ FIELD }} {{ FIELD.field.label }}</li>
  {% else %}
    <li>{{ FIELD.label }}: {{ FIELD }}</li>
  {% endif %}
{% endfieldsineed %}
</code>```

(klass is a filter I got from here which returns the class name of the filtered value.)

Unfortunately, FIELD.label is only a string. Is there an easy way to render a  tag for a given form field?

答:
https://docs.djangoproject.com/en/dev/topics/forms/#s-looping-over-the-form-s-fields

Shows you can do

```<code>{{ FIELD.label_tag }}
</code>```

Should render something like

```<code><label for="id_fieldName">Fieldlabel:</label>
</code>```

Title: Django - Render the <label> of a single form field

Body:
I'm selectively rendering fields on a form.

class SomeForm(forms.Form):
    foo = forms.ChoiceField(label='Some Foo', ...)
    bar = forms.BooleanField(label='Some Bar', ...)
    ...

I've got a custom tag that, based on some other logic, lets me iterate over the fields of the form that I need using the FIELD context variable in the tag:

{% fieldsineed %}
  {% if FIELD.field.widget|klass == "CheckboxInput" %}

{{ FIELD }} {{ FIELD.field.label }}

  {% else %}

{{ FIELD.label }}: {{ FIELD }}

  {% endif %}
{% endfieldsineed %}

(klass is a filter I got from here which returns the class name of the filtered value.)

Unfortunately, FIELD.label is only a string. Is there an easy way to render a  tag for a given form field?

Body:
https://docs.djangoproject.com/en/dev/topics/forms/#s-looping-over-the-form-s-fields

Shows you can do

{{ FIELD.label_tag }}

Should render something like

<label for="id_fieldName">Fieldlabel:</label>


问:
Change dropdown values based on a selection of another dropdown using Jexcel
I'm using Jexcel spreadsheet to catalog some data from a survey.

In a column I have a dropdown with vehicle manufacturers as options (Toyota, Honda ...).

In another column I have another dropdown with vehicle models.

How do I filter the models only from the manufacturer selected in the first dropdown?

The data structure is something like:

```<code>var manufacturers = [
  { id: 1, name: 'Toyota' },
  { id: 2, name: 'Honda' }
];

var models = [
  { id: 8, manufacturer_id: 1, name: 'Corolla' },
  { id: 9, manufacturer_id: 2, name: 'Civic' }
];
</code>```

答:
set the column sources.

point the filter property of the "model" column to a function that will be used to filter the content dropdownFilter

in that function we filter the source using the id, manufacturer_id and source.filter()

Here's a Working Pen

```<code>var manufacturers = [
  { id: 1, name: "Toyota" },
  { id: 2, name: "Honda" }
];

var models = [
  { id: 8, manufacturer_id: 1, name: "Corolla" },
  { id: 9, manufacturer_id: 2, name: "Civic" },
  { id: 10, manufacturer_id: 2, name: "Accord" }
];

var options = {
  minDimensions: [2, 5],
  columns: [
    {
      type: "dropdown",
      title: "Manufacturer",
      width: "150",
      source: manufacturers
    },
    {
      type: "dropdown",
      title: "Model",
      width: "150",
      source: models,
      // this is where the magic happens :)
      filter: dropdownFilter
    }
  ],
};

var mySpreadsheet = $("#spreadsheet").jexcel(options);

function dropdownFilter(instance, cell, c, r, source) {
  //get the manufacturer_id from the previus column
  var manufacturer_id = instance.jexcel.getValueFromCoords(c - 1, r);

  if (manufacturer_id !== "") {
    // if a manufacturer is selected filter source using its id
    return source.filter(function (item) {
      if (item.manufacturer_id == manufacturer_id) return true;
    })
  } else {
    //if no manufacturer is selected return an empty array
    return [];
    // or uncomment the following line to return the full source
    // return source
  }
}
</code>```

Body:
I'm using Jexcel spreadsheet to catalog some data from a survey.

In a column I have a dropdown with vehicle manufacturers as options (Toyota, Honda ...).

In another column I have another dropdown with vehicle models.

How do I filter the models only from the manufacturer selected in the first dropdown?

The data structure is something like:

var manufacturers = [
  { id: 1, name: 'Toyota' },
  { id: 2, name: 'Honda' }
];

var models = [
  { id: 8, manufacturer_id: 1, name: 'Corolla' },
  { id: 9, manufacturer_id: 2, name: 'Civic' }
];

Body:
set the column sources.

point the filter property of the "model" column to a function that will be used to filter the content dropdownFilter

in that function we filter the source using the id, manufacturer_id and source.filter()

Here's a Working Pen

var manufacturers = [
  { id: 1, name: "Toyota" },
  { id: 2, name: "Honda" }
];

var models = [
  { id: 8, manufacturer_id: 1, name: "Corolla" },
  { id: 9, manufacturer_id: 2, name: "Civic" },
  { id: 10, manufacturer_id: 2, name: "Accord" }
];

var options = {
  minDimensions: [2, 5],
  columns: [
    {
      type: "dropdown",
      title: "Manufacturer",
      width: "150",
      source: manufacturers
    },
    {
      type: "dropdown",
      title: "Model",
      width: "150",
      source: models,
      // this is where the magic happens :)
      filter: dropdownFilter
    }
  ],
};

var mySpreadsheet = $("#spreadsheet").jexcel(options);

function dropdownFilter(instance, cell, c, r, source) {
  //get the manufacturer_id from the previus column
  var manufacturer_id = instance.jexcel.getValueFromCoords(c - 1, r);

  if (manufacturer_id !== "") {
    // if a manufacturer is selected filter source using its id
    return source.filter(function (item) {
      if (item.manufacturer_id == manufacturer_id) return true;
    })
  } else {
    //if no manufacturer is selected return an empty array
    return [];
    // or uncomment the following line to return the full source
    // return source
  }
}


问:
How to change json of default settings in vscode?
I tried to add wordpress at intelephense.stubs in defaultSettings.json. But, I couldn't edit it. It showed:

I am not expert at it. I have added it at settings.json like this way:

Did I do it correctly? Will the entire intelephense.stubs be replaced with just that single value? or it will work like this way (which I tried to achieve)?:

```<code>"intelephense.stubs": [
    "apache",
    "bcmath",
    ..........
    "zlib",
    "wordpress"
]
</code>```

答:
Yes. You've done right.

Just put it in your settings and it will overwrite default settings.

To be completely sure, copy the default settings and paste them in settings, adding the ones you want to.

Body:
I tried to add wordpress at intelephense.stubs in defaultSettings.json. But, I couldn't edit it. It showed:

I am not expert at it. I have added it at settings.json like this way:

Did I do it correctly? Will the entire intelephense.stubs be replaced with just that single value? or it will work like this way (which I tried to achieve)?:

"intelephense.stubs": [
    "apache",
    "bcmath",
    ..........
    "zlib",
    "wordpress"
]