问:
WPF - View model updating property via background worker, but view is not updating some elements until focused
View model is loading data asynchronously using background worker thread in model. All properties in the model and view model raise the property changed events, and all properties are being updated in the view as expected, except 2 buttons whose IsEnabled state depends on the outcome of some properties that are loaded.

The frustrating part is that as soon as I focus on any part of the view, or set a breakpoint after the properties are updated (create a delay), then the buttons IsEnabled state is updated as expected. So it appears to be a timing issue.

Any clues as to how to the best way to solve this? I'm using mvvm-light framework, but that shouldn't matter.

I've tried binding IsEnabled to the button instead of just relying on the Command property, but that made no difference. I've confirmed via logging that view model properties are set and the PropertyChanged event is being raised for the properties associated with the buttons.

Considering sending a message using mvvm-light messenger from the view model to the view on the async completed event and then somehow? triggering a view refresh, but that seems like a kludge.

Update

Thanks to blindmeis' answer, I tested the button behaviour without the Command binding set, i.e. just binding IsEnabled property, and it works as expected!

```<code><Button
    Grid.Column="2" Content="{Binding LoadProjectsLabel}"
    VerticalAlignment="Top" HorizontalAlignment="Right"
    IsEnabled="{Binding CanLoadProjects}" />
</code>```

Obviously it's not great because I can no longer execute the command :) but as soon as I add the command back, it stops behaving:

```<code><Button
    Grid.Column="2" Content="{Binding LoadProjectsLabel}"
    VerticalAlignment="Top" HorizontalAlignment="Right"
    Command="{Binding LoadProjectsCommand}" />
</code>```

Leaving IsEnabled binding doesn't solve the problem, but that seems like a good clue.

The view model command code:

```<code>public ICommand LoadProjectsCommand
{
    get
    {
        if (_loadProjectsCommand == null)
        {
            _loadProjectsCommand = new RelayCommand(loadProjects, () => CanLoadProjects);
        }
        return _loadProjectsCommand;
    }
}
</code>```

Workaround

Wire up the Click event and avoid Command. Would be nice to solve it from the view model, but this works:

```<code><Button
    Grid.Column="2" Content="{Binding LoadProjectsLabel}"
    VerticalAlignment="Top" HorizontalAlignment="Right"
    IsEnabled="{Binding CanLoadProjects}"
    Click="loadProjects_Click"/>
</code>```

Code behind:

```<code>void loadProjects_Click(object sender, RoutedEventArgs e)
{
    SettingsViewModel vm = (SettingsViewModel)DataContext;
    vm.LoadProjectsCommand.Execute(null);
}
</code>```

答:
Answer from other thread:

When your BackgroundWorker completes, call CommandManager.InvalidateRequerySuggested();

By default, Commands are only requeried occasionally by WPF. Otherwise, there would be a huge amount of overhead in constantly calling "CanExecute" on every ICommand implementation. Calling the above method forces the CommandManager to update immediately.

This will force the Commands to re-enable/disable appropriately.

EDIT:

i use a simpler but not so beautiful workaround. i simply call OnPropertyChanged("MyICommand") for my commands in my BackgroundWorker Completed Event.

EDIT:

here is another nice solution.

Body:
View model is loading data asynchronously using background worker thread in model. All properties in the model and view model raise the property changed events, and all properties are being updated in the view as expected, except 2 buttons whose IsEnabled state depends on the outcome of some properties that are loaded.

The frustrating part is that as soon as I focus on any part of the view, or set a breakpoint after the properties are updated (create a delay), then the buttons IsEnabled state is updated as expected. So it appears to be a timing issue.

Any clues as to how to the best way to solve this? I'm using mvvm-light framework, but that shouldn't matter.

I've tried binding IsEnabled to the button instead of just relying on the Command property, but that made no difference. I've confirmed via logging that view model properties are set and the PropertyChanged event is being raised for the properties associated with the buttons.

Considering sending a message using mvvm-light messenger from the view model to the view on the async completed event and then somehow? triggering a view refresh, but that seems like a kludge.

Update

Thanks to blindmeis' answer, I tested the button behaviour without the Command binding set, i.e. just binding IsEnabled property, and it works as expected!

<Button
    Grid.Column="2" Content="{Binding LoadProjectsLabel}"
    VerticalAlignment="Top" HorizontalAlignment="Right"
    IsEnabled="{Binding CanLoadProjects}" />

Obviously it's not great because I can no longer execute the command :) but as soon as I add the command back, it stops behaving:

<Button
    Grid.Column="2" Content="{Binding LoadProjectsLabel}"
    VerticalAlignment="Top" HorizontalAlignment="Right"
    Command="{Binding LoadProjectsCommand}" />

Leaving IsEnabled binding doesn't solve the problem, but that seems like a good clue.

The view model command code:

public ICommand LoadProjectsCommand
{
    get
    {
        if (_loadProjectsCommand == null)
        {
            _loadProjectsCommand = new RelayCommand(loadProjects, () => CanLoadProjects);
        }
        return _loadProjectsCommand;
    }
}

Workaround

Wire up the Click event and avoid Command. Would be nice to solve it from the view model, but this works:

<Button
    Grid.Column="2" Content="{Binding LoadProjectsLabel}"
    VerticalAlignment="Top" HorizontalAlignment="Right"
    IsEnabled="{Binding CanLoadProjects}"
    Click="loadProjects_Click"/>

Code behind:

void loadProjects_Click(object sender, RoutedEventArgs e)
{
    SettingsViewModel vm = (SettingsViewModel)DataContext;
    vm.LoadProjectsCommand.Execute(null);
}


来源: stackexchange

问:
When clicking on the child don't consider the parent
I want some method to convince CSS that when I click on one of the children inside the parent element don't consider that I clicked also on the parent element.
I want you to try clicking on one of the children inside the parent.

  .parent{
    background: blue;
    padding:20px;
    text-align: center;
    margin: 0 auto;
    height: 300px;
    width: 300px;
  }
  .parent:active{
    background: #ddd;
  }
  .child{
    background: red;
    float: left;
    padding: 5px;
    height: 150px;
    width: 150px;
    font-size: 4em;
  }
  .child:nth-child(odd){
    background: pink;
  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="parent">
  <div class="child">Click me</div>
   <div class="child">Click me</div>
</div></code>```

答:
Give the parent div

```<code>pointer-events: none;
</code>```

No javascript needed.

ContentLicense: CC BY-SA 4.0

Body:
I want some method to convince CSS that when I click on one of the children inside the parent element don't consider that I clicked also on the parent element.
I want you to try clicking on one of the children inside the parent.

  .parent{
    background: blue;
    padding:20px;
    text-align: center;
    margin: 0 auto;
    height: 300px;
    width: 300px;
  }
  .parent:active{
    background: #ddd;
  }
  .child{
    background: red;
    float: left;
    padding: 5px;
    height: 150px;
    width: 150px;
    font-size: 4em;
  }
  .child:nth-child(odd){
    background: pink;
  }

Click me

Click me

Body:
Give the parent div

pointer-events: none;

No javascript needed.


问:
Regex / JavaScript: Split string to separate lines by max characters per line with looking n chars backwards for a possible whitespace?
This is similar question to How to split a string at every n characters or to nearest previous space, however, on the contrary to what I was expecting based on the title, that solution does not work if there is just one long word without any whitespace.

So I need a Regex which splits a string to separate lines (multiple times if needed) by max characters per line, and looking backwards n characters for a possible whitespace (break there if found, otherwise at max length)?

Edit 1: For example, with max line length 30 characters with 15 characters backwards whitespace lookup:

Loremipsumissimplydummytextofthe printing and typesetting industry.

That sentence's first word has a length of 32 characters. So the output should be:

```<code>Loremipsumissimplydummytextoft  # Line has length of 30 char
he printing and typesetting     # Cut before the word at otherwise 30 char
industry.
</code>```

So the first word should be force-cut after 30th character, as there was no whitespace.

The remaining string has a length of 28 (or 29 with the dash) before word 'industry', so at the place of 30th character there's a word, so the solution looks up for the previous whitespace within 15 characters range. That line is broken before 'industry' word.

Edit 2: Second example of text:

Loremipsumissimplydummytextofthe printing and typesetting industry. Loremipsumis simply dummytext ofthe printing and typesetting industry. Loremipsumissimplydummytextofthe printing and typesetting industry. Loremipsumis simply dummytext ofthe printing and typesetting industry.

Should output:

Loremipsumissimplydummytextoft
he printing and typesetting
industry. Loremipsumis simply
dummytext ofthe printing and
typesetting industry.
Loremipsumissimplydummytextoft
he printing and typesetting
industry. Loremipsumis simply
dummytext ofthe printing and
typesetting industry.
```

<p><strong>Use case for this regex is to format a long string into readable text with max line length enforced and lines starting with a character and not a whitespace.</strong></p>

<p><strong>Optional requirement:</strong> When after initial posting I added that example in Edit 1, I also added an optional requirement for adding a dash '-' character at start of the next line, if a word was cut at max line length. I'm removing that from the example now and adding it as a separate optional requirement here.</p>

<p>So an optional requirement: If a line is broken mid-word at max-length and not at a whitespace, then a dash should be appended at the end of that line (and not at start of the next line, as I had originally described).</p>

```Loremipsumissimplydummytextoft-  # Line length 30+1 char with an appended a dash
he printing and typesetting     # Cut before the word at otherwise 30 char
industry.
```

答:
You may use

var s = "Loremipsumissimplydummytextofthe printing and typesetting industry. Loremipsumis simply dummytext ofthe printing and typesetting industry. Loremipsumissimplydummytextofthe printing and typesetting industry. Loremipsumis simply dummytext ofthe printing and typesetting industry.";
var regex = /\s*(?:(\S{30})|([\s\S]{1,30})(?!\S))/g;
console.log(
  s.replace(regex, function($0,$1,$2) { return $1 ? $1 + "-\n" : $2 + "\n"; } )
)```
</div>
</div>
</p>

<p><strong>Details</strong></p>

<ul>
<li><code>\s*</code> - 0 or more whitespace chars.</li>
<li><code>(?:</code> - start of the non-capturing group:

<ul>
<li><code>(\S{30})</code> - Group 1 (referred to with the <code>$1</code> variable in the callback method): thirty (<code>n</code>) non-whitespace chars</li>
<li><code>|</code> - or</li>
<li><code>([\s\S]{1,30})(?!\S))</code> - Group 2 (referred to with the <code>$2</code> variable in the callback method): any one to thirty (<code>n</code>)  chars, as many as possible, but not immediately followed with a non-whitespace char.</li>
</ul></li>
</ul>

<p>The <code>function($0,$1,$2) { return $1 ? $1 + "-\n" : $2 + "\n"; }</code> part means that if Group 1 matched (that is, we matched a very long word that is cut into two parts), we replace the match with Group 1 value + hyphen and a newline. Else, if Group 2 matches, we replace with Group 2 value + a newline.</p>

<p><strong>ES6+ compliant code snippet</strong>:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const text = "Loremipsumissimplydummytextofthe printing and typesetting industry. Loremipsumis simply dummytext ofthe printing and typesetting industry. Loremipsumissimplydummytextofthe printing and typesetting industry. Loremipsumis simply dummytext ofthe printing and typesetting industry.";
const lineMaxLen = 30;
const wsLookup = 15; // Look backwards n characters for a whitespace
const regex = new RegExp(String.raw`\s*(?:(\S{${lineMaxLen}})|([\s\S]{${lineMaxLen - wsLookup},${lineMaxLen}})(?!\S))`, 'g');
console.log(
  text.replace(regex, (_, x, y) => x ? `${x}-\n` : `${y}\n`)
);</code>```

Body:
This is similar question to How to split a string at every n characters or to nearest previous space, however, on the contrary to what I was expecting based on the title, that solution does not work if there is just one long word without any whitespace.

So I need a Regex which splits a string to separate lines (multiple times if needed) by max characters per line, and looking backwards n characters for a possible whitespace (break there if found, otherwise at max length)?

Edit 1: For example, with max line length 30 characters with 15 characters backwards whitespace lookup:

Loremipsumissimplydummytextofthe printing and typesetting industry.

That sentence's first word has a length of 32 characters. So the output should be:

Loremipsumissimplydummytextoft  # Line has length of 30 char
he printing and typesetting     # Cut before the word at otherwise 30 char
industry.

So the first word should be force-cut after 30th character, as there was no whitespace.

The remaining string has a length of 28 (or 29 with the dash) before word 'industry', so at the place of 30th character there's a word, so the solution looks up for the previous whitespace within 15 characters range. That line is broken before 'industry' word.

Edit 2: Second example of text:

Loremipsumissimplydummytextofthe printing and typesetting industry. Loremipsumis simply dummytext ofthe printing and typesetting industry. Loremipsumissimplydummytextofthe printing and typesetting industry. Loremipsumis simply dummytext ofthe printing and typesetting industry.

Should output:

Loremipsumissimplydummytextoft
he printing and typesetting
industry. Loremipsumis simply
dummytext ofthe printing and
typesetting industry.
Loremipsumissimplydummytextoft
he printing and typesetting
industry. Loremipsumis simply
dummytext ofthe printing and
typesetting industry.

Use case for this regex is to format a long string into readable text with max line length enforced and lines starting with a character and not a whitespace.

Optional requirement: When after initial posting I added that example in Edit 1, I also added an optional requirement for adding a dash '-' character at start of the next line, if a word was cut at max line length. I'm removing that from the example now and adding it as a separate optional requirement here.

So an optional requirement: If a line is broken mid-word at max-length and not at a whitespace, then a dash should be appended at the end of that line (and not at start of the next line, as I had originally described).

Loremipsumissimplydummytextoft-  # Line length 30+1 char with an appended a dash
he printing and typesetting     # Cut before the word at otherwise 30 char
industry.

Body:
You may use

var s = "Loremipsumissimplydummytextofthe printing and typesetting industry. Loremipsumis simply dummytext ofthe printing and typesetting industry. Loremipsumissimplydummytextofthe printing and typesetting industry. Loremipsumis simply dummytext ofthe printing and typesetting industry.";
var regex = /\s*(?:(\S{30})|([\s\S]{1,30})(?!\S))/g;
console.log(
  s.replace(regex, function($0,$1,$2) { return $1 ? $1 + "-\n" : $2 + "\n"; } )
)

Details

\s* - 0 or more whitespace chars.

(?: - start of the non-capturing group:

(\S{30}) - Group 1 (referred to with the $1 variable in the callback method): thirty (n) non-whitespace chars

| - or

([\s\S]{1,30})(?!\S)) - Group 2 (referred to with the $2 variable in the callback method): any one to thirty (n)  chars, as many as possible, but not immediately followed with a non-whitespace char.

The function($0,$1,$2) { return $1 ? $1 + "-\n" : $2 + "\n"; } part means that if Group 1 matched (that is, we matched a very long word that is cut into two parts), we replace the match with Group 1 value + hyphen and a newline. Else, if Group 2 matches, we replace with Group 2 value + a newline.

ES6+ compliant code snippet:

const text = "Loremipsumissimplydummytextofthe printing and typesetting industry. Loremipsumis simply dummytext ofthe printing and typesetting industry. Loremipsumissimplydummytextofthe printing and typesetting industry. Loremipsumis simply dummytext ofthe printing and typesetting industry.";
const lineMaxLen = 30;
const wsLookup = 15; // Look backwards n characters for a whitespace
const regex = new RegExp(String.raw`\s*(?:(\S{${lineMaxLen}})|([\s\S]{${lineMaxLen - wsLookup},${lineMaxLen}})(?!\S))`, 'g');
console.log(
  text.replace(regex, (_, x, y) => x ? `${x}-\n` : `${y}\n`)
);


问:
enable_if on conversion constructor (static cast, is_base_of)
I am working on an implementation of a shared pointer. (using C++17, in case it matters)

The only issue is the conversion constructor. I want to be able to static cast a smart_ptr to a smart_ptr of base type.

```<code>template<typename U>
inline smart_ptr(const smart_ptr<U>& rhs)
{
    ...
}
</code>```

It works, but it will also try to cast a smart_ptr to a smart_ptr of any other type. For example, if I have an overloaded function that can take different kinds of smart_ptr's of unrelated type, I get a compiler error about ambiguous overload. So, I only want the conversion from smart_ptr -> smart_ptr if U is a derived class of T.

This looks like it should work. It compiles, but it does the opposite. It prevents the valid static upcasts from working, but still allows the casting to unrelated types:

```<code>template<typename U>
inline local_shared_ptr(typename enable_if<is_base_of<T,U>::value, const  local_shared_ptr<U>&>::type rhs)
{
    ...
}
</code>```

EDIT:

Got it working, thanks for the help. I choose jarod's solution, since I find template <typename U, enable_if_t<is_base_of<T,U>::value, int> = 0> the most concise. I didn't realize SFINAE could be that concise.

Also, since it was mentioned by Nathan:

Funnily enough, one of the issues I encountered is that I expected the template copy constructor to be called when the right-hand-side is the same type. Apparently, the compiler doesn't consider it an implementation of the copy constructor, and instead the auto-generated copy constructor was being called instead. Same issue for the move constructor and operator=. Not sure if that's a bug with MSVC2019.

答:
Put the enable_if in the template parameter list like

```<code>template<typename U, std::enable_if_t<std::is_base_of_v<T, U>, bool> = true>
inline smart_ptr(const smart_ptr<U>& rhs)
{

}
</code>```

And now this will only be called if U is T, or is derived from T.  If you don't want to use this if U == T then you can use

```<code>template<typename U, std::enable_if_t<std::is_base_of_v<T, U> && !std::is_same_v<T, U>, bool> = true>
inline smart_ptr(const smart_ptr<U>& rhs)
{

}
</code>```

Body:
I am working on an implementation of a shared pointer. (using C++17, in case it matters)

The only issue is the conversion constructor. I want to be able to static cast a smart_ptr to a smart_ptr of base type.

template<typename U>
inline smart_ptr(const smart_ptr& rhs)
{
    ...
}

It works, but it will also try to cast a smart_ptr to a smart_ptr of any other type. For example, if I have an overloaded function that can take different kinds of smart_ptr's of unrelated type, I get a compiler error about ambiguous overload. So, I only want the conversion from smart_ptr -> smart_ptr if U is a derived class of T.

This looks like it should work. It compiles, but it does the opposite. It prevents the valid static upcasts from working, but still allows the casting to unrelated types:

template<typename U>
inline local_shared_ptr(typename enable_if<is_base_of<T,U>::value, const  local_shared_ptr&>::type rhs)
{
    ...
}

EDIT:

Got it working, thanks for the help. I choose jarod's solution, since I find template <typename U, enable_if_t<is_base_of<T,U>::value, int> = 0> the most concise. I didn't realize SFINAE could be that concise.

Also, since it was mentioned by Nathan:

Funnily enough, one of the issues I encountered is that I expected the template copy constructor to be called when the right-hand-side is the same type. Apparently, the compiler doesn't consider it an implementation of the copy constructor, and instead the auto-generated copy constructor was being called instead. Same issue for the move constructor and operator=. Not sure if that's a bug with MSVC2019.

Body:
Put the enable_if in the template parameter list like

template<typename U, std::enable_if_t<std::is_base_of_v<T, U>, bool> = true>
inline smart_ptr(const smart_ptr<U>& rhs)
{

}

And now this will only be called if U is T, or is derived from T.  If you don't want to use this if U == T then you can use

template<typename U, std::enable_if_t<std::is_base_of_v<T, U> && !std::is_same_v<T, U>, bool> = true>
inline smart_ptr(const smart_ptr<U>& rhs)
{

}


问:
PHP version on phpinfo() older than the one on terminal
So I have a versioning problem with my php on my macOSX. The version showed on my terminal is correct and shows PHP 7.4.2. However, when I open up phpinfo() on my project I get PHP 7.1.23

All the posts I keep finding on this subject is how the terminal is behind what is shown on phpinfo(), while I get the opposite. I installed php using homebrew since I needed to work with 7.4. However, I feel like php 7.1 was there prior to me installing 7.4, maybe it's the built-n php version on my mac?

Things I tried that did not work:

Putting "export PATH="/usr/local/opt/php@7.4/sbin:$PATH"" in my .bash_profile

Removing and reinstalling php using homebrew

Restarting Apache server thousands of times using "apachectl restart"

Removed XCode and it's developer folder

Cried in a corner in a fetal position

Anyone has other suggestions?

答:
You have multiple versions of php installed and you should change the one used by apache. First you disable old module sudo a2dismod php7.1, then you enable new module sudo a2enmod php7.4.
Don't forget to restart apache after this operation.


问:
Javascript: Pass include method to filter array
Filtering arrays in Javascript is possible by passing a custom function to the filter method:

```<code>const bigArray = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const filteredArray = bigArray.filter(item => item < 5);
</code>```

It's also possible to pass the function as a "reference":

```<code>function largerThanFive(item) {
  return item => item < 5;
}

const bigArray = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const filteredArray = bigArray.filter(largerThanFive);
</code>```

I tried to use this to intersect two arrays via:

```<code>const bigArray = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const smallArray = [0, 1, 2];
const filteredArray = bigArray.filter(smallArray.includes);
</code>```

But I get the error:
TypeError: Cannot convert undefined or null to object

I don't understand why. Can someone elaborate on that?

答:
By using a prototype function, you are loosing the reference to the object smallArray. In this case you need either to bind the object with Function#bind,

const bigArray = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const smallArray = [0, 1, 2];
const filteredArray = bigArray.filter(Array.prototype.includes.bind(smallArray));

console.log(filteredArray);```
</div>
</div>
</p>

<p>or use <code>thisArg</code> parameter of <code>Array#filter</code>.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const bigArray = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const smallArray = [2, 1, 0];
const filteredArray = bigArray.filter(Array.prototype.includes, smallArray);

console.log(filteredArray); // 2 is missing</code>```

But both above approaches do not work, because Array#includes uses a second parameter fromIndex, which is handed over from the calling function as index and omits values to be checked whoes indices are smaller.

As result, you need a function which supports the same function signature as the api of the methods supplies or which is smaller as the callback is using.

For example a working approach would be to use a Set as thisArg along with Set#has as callback. This method uses only one parameter, which fits perfectly.

const bigArray = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const smallArray = [2, 1, 0];
const filteredArray = bigArray.filter(Set.prototype.has, new Set(smallArray));

console.log(filteredArray);```

Body:
Filtering arrays in Javascript is possible by passing a custom function to the filter method:

const bigArray = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const filteredArray = bigArray.filter(item => item < 5);

It's also possible to pass the function as a "reference":

function largerThanFive(item) {
  return item => item < 5;
}

const bigArray = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const filteredArray = bigArray.filter(largerThanFive);

I tried to use this to intersect two arrays via:

const bigArray = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const smallArray = [0, 1, 2];
const filteredArray = bigArray.filter(smallArray.includes);

But I get the error:
TypeError: Cannot convert undefined or null to object

I don't understand why. Can someone elaborate on that?

Body:
By using a prototype function, you are loosing the reference to the object smallArray. In this case you need either to bind the object with Function#bind,

const bigArray = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const smallArray = [0, 1, 2];
const filteredArray = bigArray.filter(Array.prototype.includes.bind(smallArray));

console.log(filteredArray);

or use thisArg parameter of Array#filter.

const bigArray = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const smallArray = [2, 1, 0];
const filteredArray = bigArray.filter(Array.prototype.includes, smallArray);

console.log(filteredArray); // 2 is missing

But both above approaches do not work, because Array#includes uses a second parameter fromIndex, which is handed over from the calling function as index and omits values to be checked whoes indices are smaller.

As result, you need a function which supports the same function signature as the api of the methods supplies or which is smaller as the callback is using.

For example a working approach would be to use a Set as thisArg along with Set#has as callback. This method uses only one parameter, which fits perfectly.

const bigArray = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const smallArray = [2, 1, 0];
const filteredArray = bigArray.filter(Set.prototype.has, new Set(smallArray));

console.log(filteredArray);


问:
In Node.js, how can I return a Promise from vm2?
I have some asynchronous JavaScript code, which I'd like to run using vm2 / NodeVM.

The code tests two functions: a user-submitted function evenAndOdd and a pre-defined function solution using Node's built-in assert library.

My question is, how can I get the my resolved Promise out of vm.run()?

The Aynchronous Code

This is the test code I want to turn into a string and run using vm2:

```<code>const assert = require('assert');

function evenAndOdd(arr) {
  return [arr.filter(el => el % 2 === 0).sort(), arr.filter(el => el % 2 === 1).sort()];
};

function solution(arr) {
  return [arr.filter(el => el % 2 === 0).sort(), arr.filter(el => el % 2 === 1).sort()];
};

const runTest = async () => {

  return new Promise((resolve, reject) => {

    const map = new Map();
    const tests = 10;

    for (let i = 0; i < tests; i++) {

      let randLength = parseInt(Math.random() * 19 + 1);
      let randArray = [...Array(randLength)].map(e => ~~(Math.random() * randLength));

      const test = async () => {
        return assert.deepEqual(evenAndOdd(randArray), solution(randArray));
      }

      const description = "TEST CASE: evenAndOdd([" + randArray + "}]) EXPECT: [[" + solution(randArray)[0] + "], [" + solution(randArray)[1] + "]] GOT: [[" + evenAndOdd(randArray)[0] + "], [" + evenAndOdd(randArray)[1] + "]]";

      test()
        .then(() => {
          map.set(description, true);
          if (map.size === tests) {
            resolve(map);
          };
        })
        .catch(() => {
          map.set(description, false);
          if (map.size === tests) {
            resolve(map);
          };
        })
    }
  })
}
</code>```

If I append the following code, I get exactly what I want logged to the console:

```<code>runTest().then((result) => {
  console.log(result)
});
</code>```

The vm Code

My question is, how do I get the resolved promise from vm.run()?

```<code>const { NodeVM } = require('vm2');

  const vm = new NodeVM({
    console: 'inherit',
    sandbox: {},
    require: {
      external: true,
      builtin: ['assert'],
      import: ['assert'],
      root: "./",
    },
  });

const result = vm.run(stringifiedJavaScript, 'vm.js');
</code>```

Right now, the result variable above is undefined.

答:
NodeVM.run() executes the code and returns the module created by the execution, which can then be accessed by the host code. In order to access the result of the computation in the processed code, you should assign it to module.exports.

Consider the following example:

```<code>const {NodeVM} = require("vm2");
const vm = new NodeVM();

const vmExports = vm.run('module.exports.pr = Promise.resolve(42);');

vmExports.pr.then(x => console.log(x));
</code>```

The variable vmExports holds the module exported by the run call, and the field vmExports.pr holds the promise produced by the sandboxed script. The exported promise is thenable or can be awaited to access the resolved values.

Body:
I have some asynchronous JavaScript code, which I'd like to run using vm2 / NodeVM.

The code tests two functions: a user-submitted function evenAndOdd and a pre-defined function solution using Node's built-in assert library.

My question is, how can I get the my resolved Promise out of vm.run()?

The Aynchronous Code

This is the test code I want to turn into a string and run using vm2:

const assert = require('assert');

function evenAndOdd(arr) {
  return [arr.filter(el => el % 2 === 0).sort(), arr.filter(el => el % 2 === 1).sort()];
};

function solution(arr) {
  return [arr.filter(el => el % 2 === 0).sort(), arr.filter(el => el % 2 === 1).sort()];
};

const runTest = async () => {

  return new Promise((resolve, reject) => {

    const map = new Map();
    const tests = 10;

    for (let i = 0; i < tests; i++) {

      let randLength = parseInt(Math.random() * 19 + 1);
      let randArray = [...Array(randLength)].map(e => ~~(Math.random() * randLength));

      const test = async () => {
        return assert.deepEqual(evenAndOdd(randArray), solution(randArray));
      }

      const description = "TEST CASE: evenAndOdd([" + randArray + "}]) EXPECT: [[" + solution(randArray)[0] + "], [" + solution(randArray)[1] + "]] GOT: [[" + evenAndOdd(randArray)[0] + "], [" + evenAndOdd(randArray)[1] + "]]";

      test()
        .then(() => {
          map.set(description, true);
          if (map.size === tests) {
            resolve(map);
          };
        })
        .catch(() => {
          map.set(description, false);
          if (map.size === tests) {
            resolve(map);
          };
        })
    }
  })
}

If I append the following code, I get exactly what I want logged to the console:

runTest().then((result) => {
  console.log(result)
});

The vm Code

My question is, how do I get the resolved promise from vm.run()?

const { NodeVM } = require('vm2');

  const vm = new NodeVM({
    console: 'inherit',
    sandbox: {},
    require: {
      external: true,
      builtin: ['assert'],
      import: ['assert'],
      root: "./",
    },
  });

const result = vm.run(stringifiedJavaScript, 'vm.js');

Right now, the result variable above is undefined.

Body:
NodeVM.run() executes the code and returns the module created by the execution, which can then be accessed by the host code. In order to access the result of the computation in the processed code, you should assign it to module.exports.

Consider the following example:

const {NodeVM} = require("vm2");
const vm = new NodeVM();

const vmExports = vm.run('module.exports.pr = Promise.resolve(42);');

vmExports.pr.then(x => console.log(x));

The variable vmExports holds the module exported by the run call, and the field vmExports.pr holds the promise produced by the sandboxed script. The exported promise is thenable or can be awaited to access the resolved values.


问:
Angular Form nested objects
I have a form where the user enters some data, then sends a POST. Now I am working on a feature to allow editing of previously entered information. Some of the inputs in the fields have nested objects, as:

```<code>export class Transfer {
    constructor(
        public id: number,
        public destination: string,
        public market: string,
        public project: Project,
        public workstream: Workstream,
        public contact: Contact
    )
}
</code>```

```<code>export class Workstream {
    constructor(
        public id: number,
        public workStream: string
    ) { }
}
</code>```

```<code>export class Contact {
    constructor(
        public id: number,
        public name: string
    ) { }
}
</code>```

When loading the information to the form, fields containing strings or numbers work well, but objects don't show the correct information. The field for Contact gives me a [object Object], while Workstream does not preselect the right option from a drop down.

```<code>            <!-- Workstream -->
            <mat-form-field class="example-full-width">
                <mat-label>Workstream</mat-label>
                <mat-select [(ngModel)]="transfer.workstream" name="workstream" [(value)]="transfer.workstream">
                    <mat-option *ngFor="let workstream of workstreams$ | async" [value]="workstream">
                        {{workstream.workStream}}
                    </mat-option>
                </mat-select>
            </mat-form-field>

            <!-- Contact -->
            <mat-form-field class="example-full-width">
            <input matInput placeholder="Contact" [(ngModel)]="transfer.contact" name="contact" value="transfer.contact.name"
                #contactSearchBox (input)="searchContact(contactSearchBox.value)" [matAutocomplete]="auto">
            </mat-form-field>

            <mat-autocomplete #auto="matAutocomplete">
                <mat-option *ngFor="let contact of contacts$ | async" [value]="contact.name"
                    (click)="selectContact(contact)">
                    {{contact.name}}
                </mat-option>
            </mat-autocomplete>
</code>```

In the contact field the user is able to search by name, which works.
Any clues on how to implement this? Thanks!

答: mat-option should have a string value. So the binding[value]="workstream", should be changed to [value]="workstream.workStream". This should work. However, if you need an entire object to be stored, then you should go with autocomplete component to store the entire object as a model in the form, and use viewFormatter function to display only the fields that you want (in the autocomplete results or the shown selected object).

Title: Angular Form nested objects

Body:
I have a form where the user enters some data, then sends a POST. Now I am working on a feature to allow editing of previously entered information. Some of the inputs in the fields have nested objects, as:

export class Transfer {
    constructor(
        public id: number,
        public destination: string,
        public market: string,
        public project: Project,
        public workstream: Workstream,
        public contact: Contact
    )
}

export class Workstream {
    constructor(
        public id: number,
        public workStream: string
    ) { }
}

export class Contact {
    constructor(
        public id: number,
        public name: string
    ) { }
}

When loading the information to the form, fields containing strings or numbers work well, but objects don't show the correct information. The field for Contact gives me a [object Object], while Workstream does not preselect the right option from a drop down.

            <mat-form-field class="example-full-width">
                <mat-label>Workstream</mat-label>
                <mat-select [(ngModel)]="transfer.workstream" name="workstream" [(value)]="transfer.workstream">
                    <mat-option *ngFor="let workstream of workstreams$ | async" [value]="workstream">
                        {{workstream.workStream}}
                    </mat-option>
                </mat-select>
            </mat-form-field>

            <mat-form-field class="example-full-width">
            <input matInput placeholder="Contact" [(ngModel)]="transfer.contact" name="contact" value="transfer.contact.name"
                #contactSearchBox (input)="searchContact(contactSearchBox.value)" [matAutocomplete]="auto">
            </mat-form-field>

            <mat-autocomplete #auto="matAutocomplete">
                <mat-option *ngFor="let contact of contacts$ | async" [value]="contact.name"
                    (click)="selectContact(contact)">
                    {{contact.name}}
                </mat-option>
            </mat-autocomplete>

In the contact field the user is able to search by name, which works.
Any clues on how to implement this? Thanks!


问:
matching regex in awk/gawk
Can someone make the awk line below work in awk please. The syntax uses the standard PCRE regex standard (and i need to expect that some non-numeric characters are preceded to the first number, that is the string can look like "++3.59  ±   0.04* "). (note that I tried [0-9] and [:digit:] instead of \d) also note that I did read https://www.gnu.org/software/gawk/manual/gawk.html#Regexp

```<code>gawk 'BEGIN{test="3.59 ± 0.04";match(test, /^.*?(\d+?\.\d+?)\s*?±\s*?(\d+?\.\d+?)$/, arr);print arr[1];}'
</code>```

答:
you add to many ? and I think you need to use [0-9]
Also when you start with ^[^0-9] only non-numeric characters are "eaten away".
so in summary I think you want:

```<code>gawk 'BEGIN{test="3.59 ± 0.04";match(test, /^[^0-9.]*([0-9]+\.[0-9]+)\s*±\s*([0-9]+\.[0-9]+)$/, arr);print arr[1];}
</code>```

That matches any non-numeric character up to the first numeric one and then captures the first number as group 1.

Thanks @Ed Morton for the corrections. I did miss the + after the first digit in the original regex.

Title: matching regex in awk/gawk

Body:
Can someone make the awk line below work in awk please. The syntax uses the standard PCRE regex standard (and i need to expect that some non-numeric characters are preceded to the first number, that is the string can look like "++3.59  ±   0.04* "). (note that I tried [0-9] and [:digit:] instead of \d) also note that I did read https://www.gnu.org/software/gawk/manual/gawk.html#Regexp

gawk 'BEGIN{test="3.59 ± 0.04";match(test, /^.*?(\d+?\.\d+?)\s*?±\s*?(\d+?\.\d+?)$/, arr);print arr[1];}'

Body:
you add to many ? and I think you need to use [0-9]
Also when you start with ^[^0-9] only non-numeric characters are "eaten away".
so in summary I think you want:

gawk 'BEGIN{test="3.59 ± 0.04";match(test, /^[^0-9.]*([0-9]+\.[0-9]+)\s*±\s*([0-9]+\.[0-9]+)$/, arr);print arr[1];}

That matches any non-numeric character up to the first numeric one and then captures the first number as group 1.

Thanks @Ed Morton for the corrections. I did miss the + after the first digit in the original regex.


问:
Apache Solr search query when user made a TYPO in text
I have added the data to solr.

Name field values are: "batman","bat man","bat-man"

so if a user searched for "btman" the result should show all the above values in search.

I found the query like: localhost:8983/solr/test/select?q=Name%3Abtman~2

but it won't work in all cases.

I need suggession for the Solr query which fetch the result with typos and recomendations.

答:
Solr comes with SpellCheck Compponent. The SpellCheck component is designed to provide inline query suggestions based on other, similar, terms. The basis for these suggestions can be terms in a field in Solr, externally created text files, or fields in other Lucene indexes.

In your case the spellcheck component will help you to achieve the same.

Please refer the solr documentation for configuring the spellcheck component.

Solr SpellCheck Compenent

If you query to the below url :

```<code>http://localhost:8986/solr/upgrade1/spell?q=retil&spellcheck.build=true&spellcheck=on&wt=xml
</code>```

The result page :

Body:
Solr comes with SpellCheck Compponent. The SpellCheck component is designed to provide inline query suggestions based on other, similar, terms. The basis for these suggestions can be terms in a field in Solr, externally created text files, or fields in other Lucene indexes.

In your case the spellcheck component will help you to achieve the same.

Please refer the solr documentation for configuring the spellcheck component.

Solr SpellCheck Compenent

If you query to the below url :

http://localhost:8986/solr/upgrade1/spell?q=retil&spellcheck.build=true&spellcheck=on&wt=xml

The result page :


问:
HR SCHEMA ORACLE
HR SCHEMA ORACLE

Create Function “GET_EMPLOYEE_SUMMARY” that receives an Employee ID and that returns, through an output parameter, a data structure with the following information:
 - Employee ID
 - First Name
 - Last Name
 - Manager Name
 - Department Name

So, the manager_name is baseade on employee_id..

Query:

```<code>select

      e.first_name as first_name,
      e.last_name,
      e.employee_id,
      e.manager_id as Name,
      d.department_name

      from employees e
      Cross join departments d
</code>```

but i have some mistakes... idk

答:
Since this looks very much like homework, here is a rough guide and you'll need to fill in the blanks:

The first part of your question is to:

create Function GET_EMPLOYEE_SUMMARY

so you should not be starting by writing a SQL query but should be writing a PL/SQL statement:

CREATE FUNCTION GET_EMPLOYEE_SUMMARY ...
```

<p>You can look up the complete syntax in the Oracle documentation.</p>

<blockquote>
  <p>that receives an Employee ID</p>
</blockquote>

<p>So one of the arguments to the function should be something like:</p>

<pre class="lang-sql prettyprint-override"><code>i_employee_id IN EMPLOYEE.EMPLOYEE_ID%TYPE
</code>```

and that returns, through an output parameter, a data structure with the following information ...

So your return type should be a custom type created with a statement like:

CREATE TYPE <your_type_name> AS OBJECT(
  <list_of_properties _and_data_types>
)
```

<p>and then you can use that return type in your function declaration.</p>

<p>When it comes to write the PL/SQL block for your function then you can include your query which should look something like:</p>

<pre class="lang-sql prettyprint-override"><code>CREATE FUNCTION <your_function_signature>
IS
  <declare your local variables>
BEGIN
  SELECT E.FIRST_NAME,
         E.LAST_NAME,
         M.FIRST_NAME || ' ' || M.LAST_NAME
         D.DEPARTMENT_NAME
  INTO   <your_first_name_variable>,
         <your_last_name_variable>,
         <your_manager_name_variable>,
         <your_department_name_variable>
  FROM   EMPLOYEES E
         LEFT OUTER JOIN EMPLOYEES M
         ON ( E.MANAGER_ID = M.EMPLOYEE_ID )
         INNER JOIN DEPARTMENTS D
         ON ( D.DEPARTMENT_ID = E.DEPARTMENT_ID )
  WHERE  E.EMPLOYEE_ID = i_employee_id;

  <do stuff>

  RETURN <your_custom_type>
EXCEPTION
  WHEN NO_DATA_FOUND THEN
    <handle the exception>
END;
/
</code>```

Title: HR SCHEMA ORACLE

Body:
HR SCHEMA ORACLE

Create Function “GET_EMPLOYEE_SUMMARY” that receives an Employee ID and that returns, through an output parameter, a data structure with the following information:
 - Employee ID
 - First Name
 - Last Name
 - Manager Name
 - Department Name

So, the manager_name is baseade on employee_id..

Query:

select

      e.first_name as first_name,
      e.last_name,
      e.employee_id,
      e.manager_id as Name,
      d.department_name

      from employees e
      Cross join departments d

but i have some mistakes... idk

Body:
Since this looks very much like homework, here is a rough guide and you'll need to fill in the blanks:

The first part of your question is to:

create Function GET_EMPLOYEE_SUMMARY

so you should not be starting by writing a SQL query but should be writing a PL/SQL statement:

CREATE FUNCTION GET_EMPLOYEE_SUMMARY ...

You can look up the complete syntax in the Oracle documentation.

that receives an Employee ID

So one of the arguments to the function should be something like:

i_employee_id IN EMPLOYEE.EMPLOYEE_ID%TYPE

and that returns, through an output parameter, a data structure with the following information ...

So your return type should be a custom type created with a statement like:

CREATE TYPE <your_type_name> AS OBJECT(
  <list_of_properties _and_data_types>
)

and then you can use that return type in your function declaration.

When it comes to write the PL/SQL block for your function then you can include your query which should look something like:

CREATE FUNCTION <your_function_signature>
IS
  <declare your local variables>
BEGIN
  SELECT E.FIRST_NAME,
         E.LAST_NAME,
         M.FIRST_NAME || ' ' || M.LAST_NAME
         D.DEPARTMENT_NAME
  INTO   <your_first_name_variable>,
         <your_last_name_variable>,
         <your_manager_name_variable>,
         <your_department_name_variable>
  FROM   EMPLOYEES E
         LEFT OUTER JOIN EMPLOYEES M
         ON ( E.MANAGER_ID = M.EMPLOYEE_ID )
         INNER JOIN DEPARTMENTS D
         ON ( D.DEPARTMENT_ID = E.DEPARTMENT_ID )
  WHERE  E.EMPLOYEE_ID = i_employee_id;

  <do stuff>

  RETURN <your_custom_type>
EXCEPTION
  WHEN NO_DATA_FOUND THEN
    <handle the exception>
END;
/


答:
The answer above transforms your list into a PIL Image. If you just want to see the image, you can do this:

```<code>import matplotlib.pyplot as plt

plt.imshow(pix)
</code>```

Title: How to convert pixels stored in a list into an image with python?

Body:
pix = [
    [[90, 94, 6], [126, 108, 24], [180, 116, 42], [166, 116, 46], [72, 94, 31]],
    [[101, 96, 14], [190, 165, 84], [202, 134, 63], [170, 115, 50], [40, 50, 0]],
    [[145, 125, 53], [150, 112, 40], [148, 73, 6], [156, 90, 31], [25, 11, 1]],
    [[133, 124, 57], [165, 142, 75], [195, 142, 77], [169, 120, 62], [82, 74, 28]],
    [[73, 105, 40], [56, 77, 10], [138, 135, 67], [97, 95, 34], [45, 69, 21]],
]

I have a bunch of pixels stored in the list and now I want to convert it to an image. How can I turn that list into an image? Thank you

Body:
The answer above transforms your list into a PIL Image. If you just want to see the image, you can do this:

import matplotlib.pyplot as plt

plt.imshow(pix)


问:
Python Converting List of Objects to JSON String
I am trying to parse a List of Python Objects to a Json String. I have a list of a Python objects called "list_mitarbeiter". In this List are Objects of Mitarbeiter:

```<code>class Mitarbeiter:
    def __init__(self, _id, name, nachname):
        self._id = _id
        self.name = name
        self.nachname = nachname
</code>```

i try to parse the list_mitarbeiter to a JSON String with:

```<code>x = json.dumps(z.__dict__ for z in list_mitarbeiter)
</code>```

Everytime i try this, i am getting an Error: Object of type generator is not JSON serializable

I already did it with only 1 object of the list and it worked, i dont understand why it isnt working when i am doing it with the for Loop for each Object in list_mitarbeiter.

x = json.dumps(list_mitarbeiter[1].dict)
^^
this is working

Here is my whole Code:

```<code>rom pymongo import MongoClient
from flask import Flask
import json

app = Flask(__name__)

class Mitarbeiter:
    def __init__(self, _id, name, nachname):
        self._id = _id
        self.name = name
        self.nachname = nachname

@app.route('/getallmitarbeiter')
def index():
    cluster = MongoClient("<CONNECTON STRING>")
    db = cluster["DP_0001"]
    collection = db["Mitarbeiter"]

    mitarbeiter = collection.find({})

    list_mitarbeiter = []

    for worker in mitarbeiter:
        test1 = Mitarbeiter(worker["_id"], worker["name"], worker["nachname"])
        list_mitarbeiter.append(test1)

    x = json.dumps(z.__dict__ for z in list_mitarbeiter)
    return x

if __name__ == '__main__':
    app.run(debug=True)
</code>```

答:
JSON can't encode generators, it needs strings, numbers, bools, None, tuples, lists, or dictionaries. Just convert your generator comprehension into a list comprehension and it will work:</p>

```<code>x = json.dumps([z.__dict__ for z in list_mitarbeiter])
</code>```

Body:
I am trying to parse a List of Python Objects to a Json String. I have a list of a Python objects called "list_mitarbeiter". In this List are Objects of Mitarbeiter:

class Mitarbeiter:
    def __init__(self, _id, name, nachname):
        self._id = _id
        self.name = name
        self.nachname = nachname

i try to parse the list_mitarbeiter to a JSON String with:

x = json.dumps(z.__dict__ for z in list_mitarbeiter)

Everytime i try this, i am getting an Error: Object of type generator is not JSON serializable

I already did it with only 1 object of the list and it worked, i dont understand why it isnt working when i am doing it with the for Loop for each Object in list_mitarbeiter.

x = json.dumps(list_mitarbeiter[1].dict)
^^
this is working

Here is my whole Code:

rom pymongo import MongoClient
from flask import Flask
import json

app = Flask(__name__)

class Mitarbeiter:
    def __init__(self, _id, name, nachname):
        self._id = _id
        self.name = name
        self.nachname = nachname

@app.route('/getallmitarbeiter')
def index():
    cluster = MongoClient("<CONNECTON STRING>")
    db = cluster["DP_0001"]
    collection = db["Mitarbeiter"]

    mitarbeiter = collection.find({})

    list_mitarbeiter = []

    for worker in mitarbeiter:
        test1 = Mitarbeiter(worker["_id"], worker["name"], worker["nachname"])
        list_mitarbeiter.append(test1)

    x = json.dumps(z.__dict__ for z in list_mitarbeiter)
    return x

if __name__ == '__main__':
    app.run(debug=True)

Body:
JSON can't encode generators, it needs strings, numbers, bools, None, tuples, lists, or dictionaries. Just convert your generator comprehension into a list comprehension and it will work:

x = json.dumps([z.__dict__ for z in list_mitarbeiter])


问:
"ssl module in Python is not available" when installing package with pip3
I've install Python 3.4 and Python 3.6 on my local machine successfully, but am unable to install packages with pip3.

When I execute pip3 install <package>, I get the following SSL related error:

```<code>pip is configured with locations that require TLS/SSL, however the ssl module in Python is not available.
Collecting <package>
  Could not fetch URL https://pypi.python.org/simple/<package>/: There was a problem confirming the ssl certificate: Can't connect to HTTPS URL because the SSL module is not available. - skipping
  Could not find a version that satisfies the requirement <package> (from versions: )
No matching distribution found for <package>
</code>```

How can I fix my Python3.x install so that I can install packages with pip install <package>?

答:
for osx brew users

my issue appeared related to my python installation and was quickly resolved by re-installing python3 and pip. i think it started misbehaving after an OS update but who knows (at this time I am on Mac OS 10.14.6)

```<code>brew reinstall python3 --force
# setup pip
curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
python3 get-pip.py
# installa pkg successfully
pip install pandas
</code>```

Body:
I've install Python 3.4 and Python 3.6 on my local machine successfully, but am unable to install packages with pip3.

When I execute pip3 install <package>, I get the following SSL related error:

pip is configured with locations that require TLS/SSL, however the ssl module in Python is not available.
Collecting <package>
  Could not fetch URL https://pypi.python.org/simple/<package>/: There was a problem confirming the ssl certificate: Can't connect to HTTPS URL because the SSL module is not available. - skipping
  Could not find a version that satisfies the requirement <package> (from versions: )
No matching distribution found for <package>

How can I fix my Python3.x install so that I can install packages with pip install <package>?

Body:
for osx brew users

my issue appeared related to my python installation and was quickly resolved by re-installing python3 and pip. i think it started misbehaving after an OS update but who knows (at this time I am on Mac OS 10.14.6)

brew reinstall python3 --force
# setup pip
curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
python3 get-pip.py
# installa pkg successfully
pip install pandas


问:
Install ipdb to tox environment for development
I'm looking for a neat way to install ipdb in tox environments, when I'm using them for development. They're often recreated, so I need something other than single installation.

Any hints?

答:
One solution would be to have your own personal customization plugin for tox that would inject ipdb as dependency in the tox environments.

Such a plugin could look like this:

tox_ipdb.py

```<code>import tox

@tox.hookimpl
def tox_configure(config):
    for envconfig in config.envconfigs.values():
        envconfig.deps.append(tox.config.DepConfig('ipdb'))
</code>```

setup.py

```<code>#!/usr/bin/env python3

import setuptools

setuptools.setup(
    name='tox-ipdb',
    version='0.0.0.dev0',
    py_modules=[
        'tox_ipdb',
    ],
    entry_points={
        'tox': 'ipdb = tox_ipdb',
    },
)
</code>```

This would instruct tox to install ipdb in all the environments it creates. As long as it is installed only in your local environment alongside your tox installation, it will have no influence on others.

Body:
One solution would be to have your own personal customization plugin for tox that would inject ipdb as dependency in the tox environments.

Such a plugin could look like this:

tox_ipdb.py

import tox

@tox.hookimpl
def tox_configure(config):
    for envconfig in config.envconfigs.values():
        envconfig.deps.append(tox.config.DepConfig('ipdb'))

setup.py

#!/usr/bin/env python3

import setuptools

setuptools.setup(
    name='tox-ipdb',
    version='0.0.0.dev0',
    py_modules=[
        'tox_ipdb',
    ],
    entry_points={
        'tox': 'ipdb = tox_ipdb',
    },
)

This would instruct tox to install ipdb in all the environments it creates. As long as it is installed only in your local environment alongside your tox installation, it will have no influence on others.


问:
How do I set the class path on Linux?
I need an answer for the question in the title.

Thanks.

答:
Here are two good tutorials I found via Google:

http://www.linuxheadquarters.com/howto/basic/classpath.shtml

http://java.sun.com/j2se/1.5.0/docs/tooldocs/solaris/classpath.html

ContentLicense: CC BY-SA 2.5

Title: How do I set the class path on Linux?

LastEditorDisplayName: Andrew Hare

OwnerDisplayName: Andrew Hare


问:
What is a paragraph (when referring to memory)
I feel silly for asking something that seems like it should be so easy to look up, but as you might guess, searching for paragraph gets a lot results that have nothing to do with what I want to know.

I've been learning assembly these past few days (writing a tiny bootloader, that sort of practice stuff) and I've seen a few references to chunks of memory called a paragraph. I have a distant memory that a paragraph is two words, but I'm really not sure. What exactly is a paragraph and what is its significance?

答: A paragraph is 16 bytes. It's relevant primarily (if not exclusively) in x86 real mode, where it's the distance between two addresses you get when you increment/decrement a segment register by one.</p>

ContentLicense: CC BY-SA 3.0


问:
Error - TypeError: Cannot read property 'then' of null - Node js
I have below code snippet which is giving me an error. I am getting a response back from getFilteredList which is of lenght 1 and it has a proper json data. But not sure why its giving error.

TypeError: Cannot read property 'then' of null

```<code>getFilteredList(group, feature).then(r=>{ //here I am getting error.
    if(r.data.response_code == "1")
    {
      const columnName = "ColumnName";
      const Codes = r.data.response_message.map(x => x[columnName]);
      Codes.forEach(code=> {
        let store = getStoreValue(code);
        getDetailsById(id, datastore)
        .then(r=>{
          res.status(200).send(r.data);
        }).catch(e=>{
          parseError(e, res);
        });
      })
    }
  }).catch(e=>{
      parseError(e, res);
    });
}
</code>```

Could someone help please.

getFilteredList() is another node js service which itself returns json data and I can see that data in logs. Below is the data it returns.

{"CODE":"AGR","GRP":"LEND","FEAT_CODE":"SRC_AGREE","GROUP_NAME":"Prop","FEA_NAME":"Property","DISPLAY_NAME":"Property","ROLE_CODE":"LE"}

Thanks.

答: I have resolved an error on myself. It was an issue in code which was not calling a appropriate web service and hence getting a null response from service which was not exist itself. I have change the code to call the exact web service and now its working fine. Thanks for support.</p>

Body:
I have below code snippet which is giving me an error. I am getting a response back from getFilteredList which is of lenght 1 and it has a proper json data. But not sure why its giving error.

TypeError: Cannot read property 'then' of null

getFilteredList(group, feature).then(r=>{ //here I am getting error.
    if(r.data.response_code == "1")
    {
      const columnName = "ColumnName";
      const Codes = r.data.response_message.map(x => x[columnName]);
      Codes.forEach(code=> {
        let store = getStoreValue(code);
        getDetailsById(id, datastore)
        .then(r=>{
          res.status(200).send(r.data);
        }).catch(e=>{
          parseError(e, res);
        });
      })
    }
  }).catch(e=>{
      parseError(e, res);
    });
}

Could someone help please.

getFilteredList() is another node js service which itself returns json data and I can see that data in logs. Below is the data it returns.

{"CODE":"AGR","GRP":"LEND","FEAT_CODE":"SRC_AGREE","GROUP_NAME":"Prop","FEA_NAME":"Property","DISPLAY_NAME":"Property","ROLE_CODE":"LE"}

Thanks.


问:
Can we use env variable as a value for a ENV variable in container of openshift deployment?
I have to login to Openshift with api and I am mentioning apikey in the deployment.yaml file like below:

```<code>    apiVersion: extensions/v1beta1
kind: Deployment
metadata:
 name: abc
spec:
 replicas: 1
 template:
   metadata:
     labels:
       app: abc
       version: v1
   spec:
     containers:
      - name: chaos
        image: abcusr/abc:v1
        imagePullPolicy: Always
        env:
         - name: HOST
           value: $host
         - name: NAMESPACE
           value: $namespace
         - name: APIKEY
           value: $apikey
</code>```

These 3 env variables are set in travis as a env variables. But when I run the build my deployment was not successful. It was giving error:

```<code> error: --server and passing the server URL as an argument are mutually exclusive
</code>```

But when I hard code all these values it works.

答:
The env variables ($host etc) aren't previously defined because value in env variable is described as:

Variable references $(VAR_NAME) are expanded using the previous defined environment variables in the container and any service environment variables. If a variable cannot be resolved, the reference in the input string will be unchanged. The $(VAR_NAME) syntax can be escaped with a double $$, ie: $$(VAR_NAME). Escaped references will never be expanded, regardless of whether the variable exists or not. Defaults to "".

However, it's a better approach to use a template with the deployment (and all other objects for you application) and all such variables as template's parameters. So you can set that parameters in process-template phase.

Body:
I have to login to Openshift with api and I am mentioning apikey in the deployment.yaml file like below:

    apiVersion: extensions/v1beta1
kind: Deployment
metadata:
 name: abc
spec:
 replicas: 1
 template:
   metadata:
     labels:
       app: abc
       version: v1
   spec:
     containers:
      - name: chaos
        image: abcusr/abc:v1
        imagePullPolicy: Always
        env:
         - name: HOST
           value: $host
         - name: NAMESPACE
           value: $namespace
         - name: APIKEY
           value: $apikey

These 3 env variables are set in travis as a env variables. But when I run the build my deployment was not successful. It was giving error:

 error: --server and passing the server URL as an argument are mutually exclusive

But when I hard code all these values it works.


问:
What is the canonical way to check for approximate zeros in Catch2?
What is the canonical way to compare to approximate zeros in Catch2?

I found this way given a tolerance of 1e-12, but it is not clear it is the best way:

```<code>TEST("a approx. equal to b", "[test]"){
    REQUIRE( a - b == (0_a).margin(1e-12) );
}
</code>```

I am not asking how to compare floats in general. I know that is not a simple problem. I am asking how to use Catch2 given a certain tolerance known in advance.

What follows didn't work, because relative (epsilon) errors do not behave well near zero:

```<code>TEST("a approx. equal to b", "[test]"){
    REQUIRE( a - b == (0_a).epsilon(1e-5) );
}
</code>```

Other possible (not so nice)( alternatives seem to be

```<code>TEST("a approx. equal to b", "[test]"){
    REQUIRE( std::abs( a - b ) < 1e-12 );
}
</code>```

```<code>TEST("a approx. equal to b", "[test]"){
    REQUIRE_THAT( a - b, WithinULP(0., ???));
}
</code>```

```<code>TEST("a approx. equal to b", "[test]"){
    REQUIRE_THAT( a, WithinULP(b, ???));
}
</code>```

答:
```<code>(a == Approx(b).margin(1e-12))
</code>```

From the Catch2 GitHub

Body:
What is the canonical way to compare to approximate zeros in Catch2?

I found this way given a tolerance of 1e-12, but it is not clear it is the best way:

TEST("a approx. equal to b", "[test]"){
    REQUIRE( a - b == (0_a).margin(1e-12) );
}

I am not asking how to compare floats in general. I know that is not a simple problem. I am asking how to use Catch2 given a certain tolerance known in advance.

What follows didn't work, because relative (epsilon) errors do not behave well near zero:

TEST("a approx. equal to b", "[test]"){
    REQUIRE( a - b == (0_a).epsilon(1e-5) );
}

Other possible (not so nice)( alternatives seem to be

TEST("a approx. equal to b", "[test]"){
    REQUIRE( std::abs( a - b ) < 1e-12 );
}

TEST("a approx. equal to b", "[test]"){
    REQUIRE_THAT( a - b, WithinULP(0., ???));
}

TEST("a approx. equal to b", "[test]"){
    REQUIRE_THAT( a, WithinULP(b, ???));
}

Body:
(a == Approx(b).margin(1e-12))

From the Catch2 GitHub


问:
How to join two different databases' tables in C# with Linq?
I try to join two different databases tables in c# but it gives me an error  how can I handle that ?

this is my query:

```<code> var list = (from h in db.database1.AsEnumerable()
                        join j in NV_DB.database2.AsEnumerable()
                        on h.Creation_Date equals j.Creation_Date
                        where j.Ship_Status == 3 && h.CustomerNo == CustomerNo
                        select new
                        {
                            shipName = h.ShipName,
                            creationDate = j.Creation_Date,
                            endingDate = j.Ending_Date
                        }
                        ).ToList();
</code>```

if I do like this it gives me System.OverflowException error. But when I run this in sql, it gives me just 30 records*

答:
To debug this, start dividing your statements into smaller steps:

```<code>var list1 = db.database1.AsEnumerable().ToList();
var list2 = NV_DB.database2.AsEnumerable().ToList();

var joinResult = list1.Join(list2,        // join list1 and list2
    list1Row => list1Row.CreationDate,    // from every row in list1 take the CreationDate
    list2Row => list2Row.CreationDate,    // from every row in list2 take the CreationDate

    (list1Row, list2Row) => new           // when they match, make one new object
    {
        // You only need the following properties:
        ShipName = list1Item.ShipName,
        CreationDate = list2Item.CreationDate,
        EndingDate = list2Item.EndingDate,

        ShipStatus = list2Item.ShipStatus,
        CustomerNo = list1Item.CustomerNo,
    })
    .ToList();

var whereResult = joinResult
    .Where(joinedRow => joinedRow.ShipStatus == 3
                     && joinedRow.CustomerNo == customerNo)
    .ToList();

var selectResult = whereResult.Select(whereResultRow => new
{
    ShipName = whereResultRow.ShipName,
    CreationDate = whereResultRow.CreationDate,
    EndingDate = whereResultRow.Ending_Date,
})
.ToList();
</code>```

This is executed completely as enumerable (in your local process, not by the database management system). My guess would be that this runs smoothly.

Now combine thw first few statements:

```<code>var joinResult = db.database1.AsEnumerable()
    .Join(NV_DB.database2.AsEnumerable(),    // join list1 and list2
    list1Row => list1Row.CreationDate,       // from every row in list1 take the CreationDate
    list2Row => list2Row.CreationDate,       // from every row in list2 take the CreationDate

    (list1Row, list2Row) => new              // when they match, make one new object
    {
        // You only need the following properties:
        ShipName = list1Item.ShipName,
        CreationDate = list2Item.CreationDate,
        EndingDate = list2Item.EndingDate,

        ShipStatus = list2Item.ShipStatus,
        CustomerNo = list1Item.CustomerNo,
    })
    .ToList();
</code>```

When this works, add the Where:

```<code>var whereResult = db.database1.AsEnumerable()
    .Join(NV_DB.database2.AsEnumerable(), ...)
    .Where(joinedRow => joinedRow.ShipStatus == 3
                     && joinedRow.CustomerNo == customerNo)
    .ToList();
</code>```

Etc.

Using your debugger, you'll find the problem within a few minutes (depending on your compilation time). My guess is that it is within your join.

Body:
I try to join two different databases tables in c# but it gives me an error  how can I handle that ?

this is my query:

 var list = (from h in db.database1.AsEnumerable()
                        join j in NV_DB.database2.AsEnumerable()
                        on h.Creation_Date equals j.Creation_Date
                        where j.Ship_Status == 3 && h.CustomerNo == CustomerNo
                        select new
                        {
                            shipName = h.ShipName,
                            creationDate = j.Creation_Date,
                            endingDate = j.Ending_Date
                        }
                        ).ToList();

if I do like this it gives me System.OverflowException error. But when I run this in sql, it gives me just 30 records*

Body:
To debug this, start dividing your statements into smaller steps:

var list1 = db.database1.AsEnumerable().ToList();
var list2 = NV_DB.database2.AsEnumerable().ToList();

var joinResult = list1.Join(list2,        // join list1 and list2
    list1Row => list1Row.CreationDate,    // from every row in list1 take the CreationDate
    list2Row => list2Row.CreationDate,    // from every row in list2 take the CreationDate

    (list1Row, list2Row) => new           // when they match, make one new object
    {
        // You only need the following properties:
        ShipName = list1Item.ShipName,
        CreationDate = list2Item.CreationDate,
        EndingDate = list2Item.EndingDate,

        ShipStatus = list2Item.ShipStatus,
        CustomerNo = list1Item.CustomerNo,
    })
    .ToList();

var whereResult = joinResult
    .Where(joinedRow => joinedRow.ShipStatus == 3
                     && joinedRow.CustomerNo == customerNo)
    .ToList();

var selectResult = whereResult.Select(whereResultRow => new
{
    ShipName = whereResultRow.ShipName,
    CreationDate = whereResultRow.CreationDate,
    EndingDate = whereResultRow.Ending_Date,
})
.ToList();

This is executed completely as enumerable (in your local process, not by the database management system). My guess would be that this runs smoothly.

Now combine thw first few statements:

var joinResult = db.database1.AsEnumerable()
    .Join(NV_DB.database2.AsEnumerable(),    // join list1 and list2
    list1Row => list1Row.CreationDate,       // from every row in list1 take the CreationDate
    list2Row => list2Row.CreationDate,       // from every row in list2 take the CreationDate

    (list1Row, list2Row) => new              // when they match, make one new object
    {
        // You only need the following properties:
        ShipName = list1Item.ShipName,
        CreationDate = list2Item.CreationDate,
        EndingDate = list2Item.EndingDate,

        ShipStatus = list2Item.ShipStatus,
        CustomerNo = list1Item.CustomerNo,
    })
    .ToList();

When this works, add the Where:

var whereResult = db.database1.AsEnumerable()
    .Join(NV_DB.database2.AsEnumerable(), ...)
    .Where(joinedRow => joinedRow.ShipStatus == 3
                     && joinedRow.CustomerNo == customerNo)
    .ToList();

Etc.

Using your debugger, you'll find the problem within a few minutes (depending on your compilation time). My guess is that it is within your join.


问:
Which element should handle data in React?
For example, there are 2 components:

```<code>class App extends React.Component {
  state = {
    comments=[1, 2, 3, 4]
  }
  render() {
    return (
      <Comments />
    )
  }
}

class Comments extends React.Component {
  render() {
    return (
        /* show comments */
    )
  }
}
</code>```

and I want to show only even comments. Should I put sorting function into App and send prepared array to Comments or send entire array and let Comments sort it by itself?

答:
It depends on how you want your Comments Component to reacts. If there aren't many function to perform and you want to make App component to react as container and comments as controlled component, you go do it like this:

```<code>import React from "react";

class Comments extends React.Component {
  render() {
    const { comments } = this.props;
    return comments.map(comment => <h1>{comment}</h1>);
  }
}

class App extends React.Component {
  state = {
    comments: [1, 2, 3, 4]
  };
  render() {
    const { comments } = this.state;
    let evenComments = comments.filter(item => item % 2 === 0);
    return <Comments comments={evenComments} />;
  }
}

export default App;
</code>```

Body:
For example, there are 2 components:

class App extends React.Component {
  state = {
    comments=[1, 2, 3, 4]
  }
  render() {
    return (
      <Comments />
    )
  }
}

class Comments extends React.Component {
  render() {
    return (
        /* show comments */
    )
  }
}

and I want to show only even comments. Should I put sorting function into App and send prepared array to Comments or send entire array and let Comments sort it by itself?

Body:
It depends on how you want your Comments Component to reacts. If there aren't many function to perform and you want to make App component to react as container and comments as controlled component, you go do it like this:

import React from "react";

class Comments extends React.Component {
  render() {
    const { comments } = this.props;
    return comments.map(comment => <h1>{comment}</h1>);
  }
}

class App extends React.Component {
  state = {
    comments: [1, 2, 3, 4]
  };
  render() {
    const { comments } = this.state;
    let evenComments = comments.filter(item => item % 2 === 0);
    return <Comments comments={evenComments} />;
  }
}

export default App;


问:
Return html as string from rendered/processed Razor Page in Class Library in Core 3
I have a solution with a few projects, where one of them is an Azure Function App, which calls a method in a .Net Core Class Library that is responsible for generating HTML that I can use with the IronPdf library to generate a PDF file.
The HTML consists a a lot of tables, which can vary in number of rows, values and so on, which the Class Library method will make sure shows as expected.

The problem I am having is that I would like to utilize Razor Pages to generate the HTML from templates, so that I can reuse HTML snippets and put logic inside the HTML.

I have looked for ways to render a Razor Page to a string and the most promising approaches I have found requires Dependecy Injection and more importantly a context.
These are the articles I have found (They show the same solution to the problem):

https://www.learnrazorpages.com/advanced/render-partial-to-string

https://www.mikesdotnetting.com/article/332/rendering-a-partial-to-a-string-in-razor-pages

As I understand it, they only work if they live in a Web App. I want all the "rendering" to happen solely in the Class Library.

What I would like to have is:

Create an instance of a model with some properties.

Render a Razor Page (or Partial) with the values from the instance.

I don't understand why this have to be so difficult, or why I need Dependency Injection, several providers, an injected View Engine and an action context.
Why can't I simply just have a method where I just say: "Please take these values and use them for the variables inside this .cshtml file, solve it, and give me back the result as a string".

I am looking for solutions for .Net Core 3, and any guidance or links to material that shows a solution or an explanation on the complexity is very welcome.

Regards, Matthias

答: Is this what you are looking for RazorLight?</p>


问:
ERROR: more than one row returned by a subquery used as an expression - POSTGRES
I'm having an issue while inserting a data to postgres table..

Here  is my query:

```<code>INSERT INTO products (product_id, user_id)
SELECT id, (SELECT id FROM users WHERE c_id = _c_id) FROM product_badge WHERE comp_id = _comp_id;
</code>```

Issue I'm receiving is

ERROR: more than one row returned by a subquery used as an expression
  CONTEXT

Thanks in advance

答:
MateuszRek,

As long as

```<code>SELECT id FROM product_badge inner join users WHERE c_id = _c_i
</code>```

returns more than one row you will have a problem.
Using a subquery as selected field implies the engine get the result as the value of that field.
having more rows poses problem as the engine can pick a value

You can us limit to pick one value. However, even if that solves the technical part of the problem,it might leave a functional/business one because maybe something is missing, for example, for to choose that id. using limit doesnt garantee its the right value

Body:
I'm having an issue while inserting a data to postgres table..

Here  is my query:

INSERT INTO products (product_id, user_id)
SELECT id, (SELECT id FROM users WHERE c_id = _c_id) FROM product_badge WHERE comp_id = _comp_id;

Issue I'm receiving is

ERROR: more than one row returned by a subquery used as an expression
  CONTEXT

Thanks in advance

Body:
MateuszRek,

As long as

SELECT id FROM product_badge inner join users WHERE c_id = _c_i

returns more than one row you will have a problem.
Using a subquery as selected field implies the engine get the result as the value of that field.
having more rows poses problem as the engine can pick a value

You can us limit to pick one value. However, even if that solves the technical part of the problem,it might leave a functional/business one because maybe something is missing, for example, for to choose that id. using limit doesnt garantee its the right value


问:
SQLite, ASCII Characters 0x20 to 0x7E Check Constraint
I have the following table where I'm trying to limit the column "name" to ASCII characters ranging from 0x20 to 0x7E (all printable ASCII characters). Why is my check constraint not working?

CREATE TABLE test
(
    id INTEGER NOT NULL,
    name TEXT NOT NULL CHECK(name NOT GLOB '*[^\x20-\x7E]*'),
    PRIMARY KEY(id)
)
```

<p>For instance: </p>

<pre class="lang-sql prettyprint-override"><code>INSERT INTO test (name) VALUES("Tom");
</code>```

Expected: Should add a touple with name: "Tom" to the table (as the inserted name only consists of printable ASCII characters). Result: CHECK constaint failed: test

答: Backslashes are not special in SQL strings. '\x20' is 4 individual characters, not an escaped single character, for example. So your GLOB pattern always matches (Because T is not a character in the set), and the NOT makes it, and thus the constraint, fail.

Body:
I have the following table where I'm trying to limit the column "name" to ASCII characters ranging from 0x20 to 0x7E (all printable ASCII characters). Why is my check constraint not working?

CREATE TABLE test
(
    id INTEGER NOT NULL,
    name TEXT NOT NULL CHECK(name NOT GLOB '*[^\x20-\x7E]*'),
    PRIMARY KEY(id)
)

For instance:

INSERT INTO test (name) VALUES("Tom");

Expected: Should add a touple with name: "Tom" to the table (as the inserted name only consists of printable ASCII characters). Result: CHECK constaint failed: test


答:
You can first the problem with limit:

```<code>INSERT INTO products (product_id, user_id)
    SELECT id, (SELECT u.id FROM users u WHERE u.c_id = _c_id LIMIT 1)
    FROM product_badge
    WHERE comp_id = _comp_id;
</code>```

However, that is a work-around.  Normally in this case, you might want all combinations, and that suggests a JOIN:

```<code>INSERT INTO products (product_id, user_id)
    SELECT pb.id, u.id
    FROM product_badge pb CROSS JOIN
         users u
    WHERE pb.comp_id = _comp_id AND
          u.c_id = _c_id;
</code>```

Title: ERROR: more than one row returned by a subquery used as an expression - POSTGRES

Body:
You can first the problem with limit:

INSERT INTO products (product_id, user_id)
    SELECT id, (SELECT u.id FROM users u WHERE u.c_id = _c_id LIMIT 1)
    FROM product_badge
    WHERE comp_id = _comp_id;

However, that is a work-around.  Normally in this case, you might want all combinations, and that suggests a JOIN:

INSERT INTO products (product_id, user_id)
    SELECT pb.id, u.id
    FROM product_badge pb CROSS JOIN
         users u
    WHERE pb.comp_id = _comp_id AND
          u.c_id = _c_id;


问:
Cannot find the code definition for "Email Purchase Order" Action In Purchase Order Screen
I would like to Customize "Email Purchase Order" action in Action folder of Purchase Order Screen.
I don't find the code where it is located.

And suppose if it is presented in dll, Can we customize that?

答:
I don't find the code where it is located.

It is not a standard action, some trickery is involved in the way it redirects the action.

It goes through the POOrderEntry.Action event handler first before it is routed to POOrderEntry.Notification event handler to send the email.

You can customize it by creating a graph extension on POOrderEntry and overriding the Notification method.

In the Notification method override you can use the condition adapter.Menu == "Email Purchase Order" to determine if the call to Notification method originated from the Email Purchase Order action menu item.


问:
multer uploading multiple files
So, I have two properties in my schema. 1) ImageCover (single file) and 2) Images (array of images)

I am using multer's upload.fields method to upload both of these files. when I upload both, it works.But when I try to upload only either of them I am getting error that the other field is not defined. How can I fix this?

1) multer.js

```<code>module.exports = () => {
    let multer = require('multer')

    let myStorage = multer.diskStorage({
        destination: (req, file, cb) => {
            cb(null, './uploads/')
        },
        filename: (req, file, cb) => {
            cb(null, `${Date.now()}-${file.originalname}`)
        }
    })

    filter = (req, file, cb) => {
        let mimeType = file.mimetype.split('/')[0]
        if (mimeType !== 'image') {
            req.fileError = true
            cb(null, false)
        } else {
            cb(null, true)
        }
    }

    let upload = multer({
        storage: myStorage,
        fileFilter: filter
    })
    return upload
}
</code>```

2) uploading photo file

```<code>module.exports = function Check(req) {
    if (req.files.images) {
        req.body.images = []
        let allFiles = req.files.images
        allFiles.forEach(file => {
            let mimeType = file.mimetype.split('/')[0]
            if (mimeType !== 'image') {
                fs.unlink(path.join(process.cwd(), 'uploads/'), (err, done) => {
                    if (err) console.log(err)
                })
            }
            req.body.images.push(file.filename)
        })
    }
    if (req.files.imageCover[0]) {
        let file = req.files.imageCover[0]
        let mimeType = file.mimetype.split('/')[0]
        if (mimeType !== 'image') {
            fs.unlink(path.join(process.cwd(), 'uploads/'), (err, done) => {
                if (err) console.log(err)
            })
        }
        req.body.imageCover = file.filename
    }
}
</code>```

3) create controller (check is the function that I have exported above)

```<code>exports.createTour = (req, res, next) => {
    check(req)
    if (req.fileError) { return next({ error: 'invalid file format dude' }) }
    Tour.create({
        ...req.body,
        owner: req.user._id
    }).then(result => {
        res.status(201).json({
            status: 'success',
            total: result.length,
            result
        })
    }).catch(err => next(err))
}
</code>```

4) Route handler

```<code>Router.route('/')
.post(authController.protect,
    upload.fields([
        {
            name: 'imageCover', maxCount: 1,
        },
        {
            name: 'images', maxCount: 10
        }
    ]),
    tourController.createTour)
</code>```

response in postman when I only select images

答:
I think you get this error because you are trying to access first element of array, and array is empty or not defined.

For example:

```<code> if (req.files.imageCover[0])
</code>```

try to refactor to look like this:

```<code>if (req.files.hasOwnProperty("imageCover") && req.files.imageCover.length > 0)
</code>```

you should do validations like this on all places where objects/arrays can be optional

Title: multer uploading multiple files

Body:
So, I have two properties in my schema. 1) ImageCover (single file) and 2) Images (array of images)

I am using multer's upload.fields method to upload both of these files. when I upload both, it works.But when I try to upload only either of them I am getting error that the other field is not defined. How can I fix this?

1) multer.js

module.exports = () => {
    let multer = require('multer')

    let myStorage = multer.diskStorage({
        destination: (req, file, cb) => {
            cb(null, './uploads/')
        },
        filename: (req, file, cb) => {
            cb(null, `${Date.now()}-${file.originalname}`)
        }
    })

    filter = (req, file, cb) => {
        let mimeType = file.mimetype.split('/')[0]
        if (mimeType !== 'image') {
            req.fileError = true
            cb(null, false)
        } else {
            cb(null, true)
        }
    }

    let upload = multer({
        storage: myStorage,
        fileFilter: filter
    })
    return upload
}

2) uploading photo file

module.exports = function Check(req) {
    if (req.files.images) {
        req.body.images = []
        let allFiles = req.files.images
        allFiles.forEach(file => {
            let mimeType = file.mimetype.split('/')[0]
            if (mimeType !== 'image') {
                fs.unlink(path.join(process.cwd(), 'uploads/'), (err, done) => {
                    if (err) console.log(err)
                })
            }
            req.body.images.push(file.filename)
        })
    }
    if (req.files.imageCover[0]) {
        let file = req.files.imageCover[0]
        let mimeType = file.mimetype.split('/')[0]
        if (mimeType !== 'image') {
            fs.unlink(path.join(process.cwd(), 'uploads/'), (err, done) => {
                if (err) console.log(err)
            })
        }
        req.body.imageCover = file.filename
    }
}

3) create controller (check is the function that I have exported above)

exports.createTour = (req, res, next) => {
    check(req)
    if (req.fileError) { return next({ error: 'invalid file format dude' }) }
    Tour.create({
        ...req.body,
        owner: req.user._id
    }).then(result => {
        res.status(201).json({
            status: 'success',
            total: result.length,
            result
        })
    }).catch(err => next(err))
}

4) Route handler

Router.route('/')
.post(authController.protect,
    upload.fields([
        {
            name: 'imageCover', maxCount: 1,
        },
        {
            name: 'images', maxCount: 10
        }
    ]),
    tourController.createTour)

response in postman when I only select images

Body:
I think you get this error because you are trying to access first element of array, and array is empty or not defined.

For example:

 if (req.files.imageCover[0])

try to refactor to look like this:

if (req.files.hasOwnProperty("imageCover") && req.files.imageCover.length > 0)

you should do validations like this on all places where objects/arrays can be optional


问:
Logstash Codec - Avro Schema Registry: avro_schema_registry fails due to undefined local variable or method `esponse'
I have a Logstash conf which reads from a Kafka topic in json format, it uses avro_schema_registry to serialize output to avro.
Here is the conf file:

```<code>input {
  kafka{
    group_id => "test_group"
    topics => ["logs_json"]
    bootstrap_servers => "server2:9094, server1:9094, server3:9094"
    codec => "json"
    consumer_threads => 1
  }
}

output {
  kafka {
    codec => avro_schema_registry {
      endpoint => "http://host_schema_registry:port"
      schema_id  => 1
    }
    value_serializer => "org.apache.kafka.common.serialization.ByteArraySerializer"
    bootstrap_servers => "server1:9094, server1:9094, server1:9094"
    topic_id => "logs_avro"
  }
}
</code>```

But I'm getting this error:

```<code>org.jruby.exceptions.NameError: (NameError) undefined local variable or method `esponse' for #<SchemaRegistry::Client:0x3c5ad39>
        at usr.share.logstash.vendor.bundle.jruby.$2_dot_5_dot_0.gems.schema_registry_minus_0_dot_1_dot_0.lib.schema_registry.client.request(/usr/share/logstash/vendor/bundle/jruby/2.5.0/gems/schema_registry-0.1.0/lib/schema_registry/cli
ent.rb:127) ~[?:?]
        at uri_3a_classloader_3a_.META_minus_INF.jruby_dot_home.lib.ruby.stdlib.net.http.start(uri:classloader:/META-INF/jruby.home/lib/ruby/stdlib/net/http.rb:914) ~[?:?]
        at uri_3a_classloader_3a_.META_minus_INF.jruby_dot_home.lib.ruby.stdlib.net.http.start(uri:classloader:/META-INF/jruby.home/lib/ruby/stdlib/net/http.rb:609) ~[?:?]
        at usr.share.logstash.vendor.bundle.jruby.$2_dot_5_dot_0.gems.schema_registry_minus_0_dot_1_dot_0.lib.schema_registry.client.request(/usr/share/logstash/vendor/bundle/jruby/2.5.0/gems/schema_registry-0.1.0/lib/schema_registry/cli
ent.rb:101) ~[?:?]
        at usr.share.logstash.vendor.bundle.jruby.$2_dot_5_dot_0.gems.schema_registry_minus_0_dot_1_dot_0.lib.schema_registry.client.schema(/usr/share/logstash/vendor/bundle/jruby/2.5.0/gems/schema_registry-0.1.0/lib/schema_registry/clie
nt.rb:40) ~[?:?]
        at usr.share.logstash.vendor.bundle.jruby.$2_dot_5_dot_0.gems.logstash_minus_codec_minus_avro_schema_registry_minus_1_dot_1_dot_1.lib.logstash.codecs.avro_schema_registry.get_schema(/usr/share/logstash/vendor/bundle/jruby/2.5.0/g
ems/logstash-codec-avro_schema_registry-1.1.1/lib/logstash/codecs/avro_schema_registry.rb:158) ~[?:?]
        at usr.share.logstash.vendor.bundle.jruby.$2_dot_5_dot_0.gems.logstash_minus_codec_minus_avro_schema_registry_minus_1_dot_1_dot_1.lib.logstash.codecs.avro_schema_registry.encode(/usr/share/logstash/vendor/bundle/jruby/2.5.0/gems/
logstash-codec-avro_schema_registry-1.1.1/lib/logstash/codecs/avro_schema_registry.rb:246) ~[?:?]
        at usr.share.logstash.vendor.bundle.jruby.$2_dot_5_dot_0.gems.logstash_minus_integration_minus_kafka_minus_10_dot_0_dot_0_minus_java.lib.logstash.outputs.kafka.multi_receive(/usr/share/logstash/vendor/bundle/jruby/2.5.0/gems/logs
tash-integration-kafka-10.0.0-java/lib/logstash/outputs/kafka.rb:219) ~[?:?]
        at org.jruby.RubyArray.each(org/jruby/RubyArray.java:1800) ~[jruby-complete-9.2.8.0.jar:?]
        at usr.share.logstash.vendor.bundle.jruby.$2_dot_5_dot_0.gems.logstash_minus_integration_minus_kafka_minus_10_dot_0_dot_0_minus_java.lib.logstash.outputs.kafka.multi_receive(/usr/share/logstash/vendor/bundle/jruby/2.5.0/gems/logs
tash-integration-kafka-10.0.0-java/lib/logstash/outputs/kafka.rb:217) ~[?:?]
        at org.logstash.config.ir.compiler.OutputStrategyExt$AbstractOutputStrategyExt.multi_receive(org/logstash/config/ir/compiler/OutputStrategyExt.java:118) ~[logstash-core.jar:?]
        at org.logstash.config.ir.compiler.AbstractOutputDelegatorExt.multi_receive(org/logstash/config/ir/compiler/AbstractOutputDelegatorExt.java:101) ~[logstash-core.jar:?]
        at usr.share.logstash.logstash_minus_core.lib.logstash.java_pipeline.start_workers(/usr/share/logstash/logstash-core/lib/logstash/java_pipeline.rb:262) ~[?:?]
[2020-02-11T13:11:41,720][ERROR][org.logstash.execution.WorkerLoop][main] Exception in pipelineworker, the pipeline stopped processing new events, please check your filter configuration and restart Logstash.
</code>```

答:
After debugging more the code, I understood the Internal Server error was due to a line in client.rb to set 'Accept' in the GET request header.

```<code>/usr/share/logstash/vendor/bundle/jruby/2.5.0/gems/schema_registry-0.1.0/lib/schema_registry/client.rb:112
        request['Accept'] = "application/vnd.schemaregistry.v1+json"
</code>```

by either commenting or changing the value to request['Accept'] = "application/json", the GET request went through successfully.

Body:
I have a Logstash conf which reads from a Kafka topic in json format, it uses avro_schema_registry to serialize output to avro.
Here is the conf file:

input {
  kafka{
    group_id => "test_group"
    topics => ["logs_json"]
    bootstrap_servers => "server2:9094, server1:9094, server3:9094"
    codec => "json"
    consumer_threads => 1
  }
}

output {
  kafka {
    codec => avro_schema_registry {
      endpoint => "http://host_schema_registry:port"
      schema_id  => 1
    }
    value_serializer => "org.apache.kafka.common.serialization.ByteArraySerializer"
    bootstrap_servers => "server1:9094, server1:9094, server1:9094"
    topic_id => "logs_avro"
  }
}

But I'm getting this error:

org.jruby.exceptions.NameError: (NameError) undefined local variable or method `esponse' for #<SchemaRegistry::Client:0x3c5ad39>
        at usr.share.logstash.vendor.bundle.jruby.$2_dot_5_dot_0.gems.schema_registry_minus_0_dot_1_dot_0.lib.schema_registry.client.request(/usr/share/logstash/vendor/bundle/jruby/2.5.0/gems/schema_registry-0.1.0/lib/schema_registry/cli
ent.rb:127) ~[?:?]
        at uri_3a_classloader_3a_.META_minus_INF.jruby_dot_home.lib.ruby.stdlib.net.http.start(uri:classloader:/META-INF/jruby.home/lib/ruby/stdlib/net/http.rb:914) ~[?:?]
        at uri_3a_classloader_3a_.META_minus_INF.jruby_dot_home.lib.ruby.stdlib.net.http.start(uri:classloader:/META-INF/jruby.home/lib/ruby/stdlib/net/http.rb:609) ~[?:?]
        at usr.share.logstash.vendor.bundle.jruby.$2_dot_5_dot_0.gems.schema_registry_minus_0_dot_1_dot_0.lib.schema_registry.client.request(/usr/share/logstash/vendor/bundle/jruby/2.5.0/gems/schema_registry-0.1.0/lib/schema_registry/cli
ent.rb:101) ~[?:?]
        at usr.share.logstash.vendor.bundle.jruby.$2_dot_5_dot_0.gems.schema_registry_minus_0_dot_1_dot_0.lib.schema_registry.client.schema(/usr/share/logstash/vendor/bundle/jruby/2.5.0/gems/schema_registry-0.1.0/lib/schema_registry/clie
nt.rb:40) ~[?:?]
        at usr.share.logstash.vendor.bundle.jruby.$2_dot_5_dot_0.gems.logstash_minus_codec_minus_avro_schema_registry_minus_1_dot_1_dot_1.lib.logstash.codecs.avro_schema_registry.get_schema(/usr/share/logstash/vendor/bundle/jruby/2.5.0/g
ems/logstash-codec-avro_schema_registry-1.1.1/lib/logstash/codecs/avro_schema_registry.rb:158) ~[?:?]
        at usr.share.logstash.vendor.bundle.jruby.$2_dot_5_dot_0.gems.logstash_minus_codec_minus_avro_schema_registry_minus_1_dot_1_dot_1.lib.logstash.codecs.avro_schema_registry.encode(/usr/share/logstash/vendor/bundle/jruby/2.5.0/gems/
logstash-codec-avro_schema_registry-1.1.1/lib/logstash/codecs/avro_schema_registry.rb:246) ~[?:?]
        at usr.share.logstash.vendor.bundle.jruby.$2_dot_5_dot_0.gems.logstash_minus_integration_minus_kafka_minus_10_dot_0_dot_0_minus_java.lib.logstash.outputs.kafka.multi_receive(/usr/share/logstash/vendor/bundle/jruby/2.5.0/gems/logs
tash-integration-kafka-10.0.0-java/lib/logstash/outputs/kafka.rb:219) ~[?:?]
        at org.jruby.RubyArray.each(org/jruby/RubyArray.java:1800) ~[jruby-complete-9.2.8.0.jar:?]
        at usr.share.logstash.vendor.bundle.jruby.$2_dot_5_dot_0.gems.logstash_minus_integration_minus_kafka_minus_10_dot_0_dot_0_minus_java.lib.logstash.outputs.kafka.multi_receive(/usr/share/logstash/vendor/bundle/jruby/2.5.0/gems/logs
tash-integration-kafka-10.0.0-java/lib/logstash/outputs/kafka.rb:217) ~[?:?]
        at org.logstash.config.ir.compiler.OutputStrategyExt$AbstractOutputStrategyExt.multi_receive(org/logstash/config/ir/compiler/OutputStrategyExt.java:118) ~[logstash-core.jar:?]
        at org.logstash.config.ir.compiler.AbstractOutputDelegatorExt.multi_receive(org/logstash/config/ir/compiler/AbstractOutputDelegatorExt.java:101) ~[logstash-core.jar:?]
        at usr.share.logstash.logstash_minus_core.lib.logstash.java_pipeline.start_workers(/usr/share/logstash/logstash-core/lib/logstash/java_pipeline.rb:262) ~[?:?]
[2020-02-11T13:11:41,720][ERROR][org.logstash.execution.WorkerLoop][main] Exception in pipelineworker, the pipeline stopped processing new events, please check your filter configuration and restart Logstash.

Body:
After debugging more the code, I understood the Internal Server error was due to a line in client.rb to set 'Accept' in the GET request header.

/usr/share/logstash/vendor/bundle/jruby/2.5.0/gems/schema_registry-0.1.0/lib/schema_registry/client.rb:112
        request['Accept'] = "application/vnd.schemaregistry.v1+json"

by either commenting or changing the value to request['Accept'] = "application/json", the GET request went through successfully.


问:
iPhone : Problem while fetching the twits from twitter
In my iphone app, I am trying to fetch twits from twitter.

And I got one example coding from following link :

http://mobile.tutsplus.com/tutorials/iphone/iphone-json-twitter-api/

But when i implemented this example I got following warning:

Directory not found for option '-L/Volumes/MacShare/Ankit/Twitter Search/JSON/iphoneos.sdk/usr/local/lib'

What can be done?

答:
I think you are forgetting the step of copying the JSON framework in your project -

```<code># Drag the JSON folder from the DMG and drop it in your Xcode project. You can add it to the “Other Sources” group if you would like.
# Select the ‘Copy items into destination group’s folder’ option when prompted.
</code>```

I just downloaded the code from http://mobiletuts.s3.amazonaws.com/14_iPhoneJSONFramework/JSONTwitterSearch.zip and its working great!!

follow the steps carefully!!

You can do one more thing.. download their source code and drag the Json folder from their project to your project..

Body:
I think you are forgetting the step of copying the JSON framework in your project -

# Drag the JSON folder from the DMG and drop it in your Xcode project. You can add it to the “Other Sources” group if you would like.
# Select the ‘Copy items into destination group’s folder’ option when prompted.

I just downloaded the code from http://mobiletuts.s3.amazonaws.com/14_iPhoneJSONFramework/JSONTwitterSearch.zip and its working great!!

follow the steps carefully!!

You can do one more thing.. download their source code and drag the Json folder from their project to your project..


问:
codemirror - line numbers overlapped with code
I'm using codemirror latest (v5.49.0). for my electron text editor app, sometimes line numbers are rendered overlapped with the text. cannot reproduce the bug because it doesn't happen always. easily it can reproduce by refreshing the app several times. Anyone have an idea? or may be this is a known issue for you?

答:
I was having this issue as well but what worked for me was this answer from Github.

const Editor = CodeMirror.fromTextArea(element, { lineNumbers: true });
Editor.refresh();
```


问:
How to put axios data into v-select by v-for?
I used axios to get multiple lines of data,
and then I wanted to put the data in v-select so that others could choose,
I thought of using v-for to make him print out line by line.
But the result shows no data available.

my code

```<code><template>
  <div>
     <v-select :item="desserts.name"></v-select>
  </div>
</template>

<script>
export default {
  data: () => ({
    desserts: [
      {
        id: "",
        name: ""
      }
    ]
  }),
  created() {
    this.getprotifile();
  },
  methods: {
    getprotifile() {
      this.axios
        .get("/api/admin/categories")
        .then(res => {
          //console.table(res.data);
          this.desserts = res.data;
          //console.log(this.desserts);
        })
        .catch(error => {
          console.error(error);
        })
        .finally(() => {});
    }
  }
};
</script>
</code>```

答:
desserts is an array, so it doesn't have the name property, as written in your template.

Probably <v-select :item="desserts"></v-select> is just fine.

Please, look at the official vuetify doc in order to understand which props pass to v-select to make it work correctly: https://vuetifyjs.com/en/components/selects/

Body:
I used axios to get multiple lines of data,
and then I wanted to put the data in v-select so that others could choose,
I thought of using v-for to make him print out line by line.
But the result shows no data available.

my code

<template>

     <v-select :item="desserts.name"></v-select>

</template>