问:
IAsyncQueryProvider build errors after migrating to .Net Core v3.1
After migrating a project from .NET Core 2.2 to version 3.1 I got an error with IAsyncEnumerator & IAsyncQueryProvider:

The type 'IAsyncEnumerable' exists in both 'System.Interactive.Async, Version=3.0.3000.0, Culture=neutral, PublicKeyToken=94bc3704cddfc263' and 'System.Runtime, Version=4.2.2.0

'TestAsyncQueryProvider' does not implement interface member 'IAsyncQueryProvider.ExecuteAsync(Expression)'. 'TestAsyncQueryProvider.ExecuteAsync(Expression)' cannot implement 'IAsyncQueryProvider.ExecuteAsync(Expression)' because it does not have the matching return type of 'IAsyncEnumerable'.

I managed to resolve the first issue related to IAsyncEnumerable with this fix below which I found on google:

```<code>  <Target Name="ChangeAliasesOfReactiveExtensions" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences">
    <ItemGroup>
      <ReferencePath Condition="'%(FileName)' == 'System.Interactive.Async'">
        <Aliases>ix</Aliases>
      </ReferencePath>
    </ItemGroup>
  </Target>
</code>```

However, I cannot find any solutions for the second issue.

Code example where I am getting an error:

```<code>internal class TestAsyncQueryProvider<TEntity> : IAsyncQueryProvider
    {
        private readonly IQueryProvider _inner;

        internal TestAsyncQueryProvider(IQueryProvider inner)
        {
            _inner = inner;
        }

        public IQueryable CreateQuery(Expression expression)
        {
            return new TestAsyncEnumerable<TEntity>(expression);
        }

        public IQueryable<TElement> CreateQuery<TElement>(Expression expression)
        {
            return new TestAsyncEnumerable<TElement>(expression);
        }

        public object Execute(Expression expression)
        {
            return _inner.Execute(expression);
        }

        public TResult Execute<TResult>(Expression expression)
        {
            return _inner.Execute<TResult>(expression);
        }

        public IAsyncEnumerable<TResult> ExecuteAsync<TResult>(Expression expression)
        {
            return new TestAsyncEnumerable<TResult>(expression);
        }

        public Task<TResult> ExecuteAsync<TResult>(Expression expression, CancellationToken cancellationToken)
        {
            return Task.FromResult(Execute<TResult>(expression));
        }
    }
</code>```

I wonder if anyone had similar issues and managed to resolve them. Also, worth mentioning, that I am still using EF Core v2.x and haven't migrated it to version 3 yet.

答:
The interface for Execute was replaced with ExecuteAsync in the IdentityServer update.

There is a library that has successfully upgraded this mock implementation to .NET Core 3.0:

https://github.com/romantitov/MockQueryable/blob/master/src/MockQueryable/MockQueryable/TestAsyncEnumerable.cs

Body:
After migrating a project from .NET Core 2.2 to version 3.1 I got an error with IAsyncEnumerator & IAsyncQueryProvider:

The type 'IAsyncEnumerable' exists in both 'System.Interactive.Async, Version=3.0.3000.0, Culture=neutral, PublicKeyToken=94bc3704cddfc263' and 'System.Runtime, Version=4.2.2.0

'TestAsyncQueryProvider' does not implement interface member 'IAsyncQueryProvider.ExecuteAsync(Expression)'. 'TestAsyncQueryProvider.ExecuteAsync(Expression)' cannot implement 'IAsyncQueryProvider.ExecuteAsync(Expression)' because it does not have the matching return type of 'IAsyncEnumerable'.

I managed to resolve the first issue related to IAsyncEnumerable with this fix below which I found on google:

  <Target Name="ChangeAliasesOfReactiveExtensions" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences">
    <ItemGroup>
      <ReferencePath Condition="'%(FileName)' == 'System.Interactive.Async'">
        <Aliases>ix</Aliases>
      </ReferencePath>
    </ItemGroup>
  </Target>

However, I cannot find any solutions for the second issue.

Code example where I am getting an error:

internal class TestAsyncQueryProvider<TEntity> : IAsyncQueryProvider
    {
        private readonly IQueryProvider _inner;

        internal TestAsyncQueryProvider(IQueryProvider inner)
        {
            _inner = inner;
        }

        public IQueryable CreateQuery(Expression expression)
        {
            return new TestAsyncEnumerable<TEntity>(expression);
        }

        public IQueryable<TElement> CreateQuery<TElement>(Expression expression)
        {
            return new TestAsyncEnumerable<TElement>(expression);
        }

        public object Execute(Expression expression)
        {
            return _inner.Execute(expression);
        }

        public TResult Execute<TResult>(Expression expression)
        {
            return _inner.Execute<TResult>(expression);
        }

        public IAsyncEnumerable<TResult> ExecuteAsync<TResult>(Expression expression)
        {
            return new TestAsyncEnumerable<TResult>(expression);
        }

        public Task<TResult> ExecuteAsync<TResult>(Expression expression, CancellationToken cancellationToken)
        {
            return Task.FromResult(Execute<TResult>(expression));
        }
    }

I wonder if anyone had similar issues and managed to resolve them. Also, worth mentioning, that I am still using EF Core v2.x and haven't migrated it to version 3 yet.


来源: stackexchange

问:
Aligning mat-spinner in bootstrap row
I have a mat-spinner in a bootstrap row. I want to right align the mat-spinner in the row:

```<code><div class="row">
  <div class="col-3">
    <div class="spinner-wrapper">
      <mat-spinner [diameter]="30" value="indeterminate">
      </mat-spinner>
    </div>
  </div>
</div>
</code>```

I've tried following things individually on the spinner-wrapper class, but did not work:

margin: 0 auto;

text-align: right;

float: right;

None of these worked.

How can I right-align the mat-spinner?

答:
You have to add this css properties to each element:

```<code>.spinner-wrapper{
   text-align:right;
}

mat-spinner{
   display:inline-block;
}
</code>```

Hope it help.

ContentLicense: CC BY-SA 4.0

Title: Aligning mat-spinner in bootstrap row

Body:
I have a mat-spinner in a bootstrap row. I want to right align the mat-spinner in the row:

      <mat-spinner [diameter]="30" value="indeterminate">
      </mat-spinner>

I've tried following things individually on the spinner-wrapper class, but did not work:

margin: 0 auto;

text-align: right;

float: right;

None of these worked.

How can I right-align the mat-spinner?

Body:
You have to add this css properties to each element:

.spinner-wrapper{
   text-align:right;
}

mat-spinner{
   display:inline-block;
}

Hope it help.


问:
100% height on mobile browser using CSS
I'm working on my website and I want it to look really simple on mobile, basically there are just three sections, each one should fit window width and height

```<code><section style="width: 100%; min-height: 100%">

</section>
</code>```

It looks perfect on my computer browser in device mode, but when I open it on my mobile (iPhone), there is a problem with url bar, which gets smaller, as we slide down. On page load, min-height adapts to browser height including the bar, and it doesn't change when bar changes it's dimension. So it doesn't fit the screen anymore. I tried this:

```<code><meta name="viewport" content="height=device-height">
</code>```

But then, sections are to high, obviously. Probably I could do some workaround in jQuery, but I'd rather not. I hope there is some simple solutions in CSS.
Thank you for your time.

答:
This is not as easy as one may think.

Here are some extract from The trick to viewport units on mobile:

Case in point: should the scrollbar be taken into account for the vw unit? What about a site's navigation or page controls — should those count in the calculation? Then there are physical attributes of the devices themselves (hello, notch!) that can't be overlooked.

And then the solution propose:

.my-element {
  height: 100vh; /* Fallback for browsers that do not support Custom Properties */
  height: calc(var(--vh, 1vh) * 100);
}
```

<p>And some JS:</p>

<pre class="lang-js prettyprint-override"><code>// First we get the viewport height and we multiple it by 1% to get a value for a vh unit
let vh = window.innerHeight * 0.01;
// Then we set the value in the --vh custom property to the root of the document
document.documentElement.style.setProperty('--vh', `${vh}px`);
</code>```

And some more JS:

// We listen to the resize event
window.addEventListener('resize', () => {
  // We execute the same script as before
  let vh = window.innerHeight * 0.01;
  document.documentElement.style.setProperty('--vh', `${vh}px`);
});
```

Title: 100% height on mobile browser using CSS

Body:
I'm working on my website and I want it to look really simple on mobile, basically there are just three sections, each one should fit window width and height

It looks perfect on my computer browser in device mode, but when I open it on my mobile (iPhone), there is a problem with url bar, which gets smaller, as we slide down. On page load, min-height adapts to browser height including the bar, and it doesn't change when bar changes it's dimension. So it doesn't fit the screen anymore. I tried this:

<meta name="viewport" content="height=device-height">

But then, sections are to high, obviously. Probably I could do some workaround in jQuery, but I'd rather not. I hope there is some simple solutions in CSS.
Thank you for your time.

Body:
This is not as easy as one may think.

Here are some extract from The trick to viewport units on mobile:

Case in point: should the scrollbar be taken into account for the vw unit? What about a site's navigation or page controls — should those count in the calculation? Then there are physical attributes of the devices themselves (hello, notch!) that can't be overlooked.

And then the solution propose:

.my-element {
  height: 100vh; /* Fallback for browsers that do not support Custom Properties */
  height: calc(var(--vh, 1vh) * 100);
}

And some JS:

// First we get the viewport height and we multiple it by 1% to get a value for a vh unit
let vh = window.innerHeight * 0.01;
// Then we set the value in the --vh custom property to the root of the document
document.documentElement.style.setProperty('--vh', `${vh}px`);

And some more JS:

// We listen to the resize event
window.addEventListener('resize', () => {
  // We execute the same script as before
  let vh = window.innerHeight * 0.01;
  document.documentElement.style.setProperty('--vh', `${vh}px`);
});


问:
org.json.JSONException: Value Error Android
I am pulling the data from the array I have assigned in the php file. I get an error pulling data from the Array output. The output is as follows:

```<code>org.json.JSONException: Value [{"program_dosya":"..."},{"program_dosya":"https:..."}, `{"program_dosya":"https:\/\/..."}] of type org.json.JSONArray cannot be converted to JSONObject`
</code>```

I want to pull the "programfile" data assigned in array via android.
PHP

```<code> $results[] = Array("program_dosya" => $programdosya);
</code>```

Android

```<code>try {
        JSONObject jObj = new JSONObject(result);

        JSONArray resultArray = jObj.getJSONArray("");
        for(int i = 0; i < resultArray.length(); i++) {
            JSONObject obj = resultArray.getJSONObject(i);
            String name = obj.getString("programdosya");
        }

    } catch (JSONException e) {
        e.printStackTrace();
    }
</code>```

答:
As I understand you need to iterate over the json array -</p>

```<code>    // assuming you have string in this format, then all you have to do is
    String result = "[{\"program_dosya\":\"...\"},{\"program_dosya\":\"https:...\"}]";
    JSONArray array = new JSONArray(result);
    for (int i=0; i<array.length(); i++) {
        JSONObject js = array.getJSONObject(i);
        String link = js.getString("program_dosya");
        System.out.println(link);
    }
</code>```

Body:
I am pulling the data from the array I have assigned in the php file. I get an error pulling data from the Array output. The output is as follows:

org.json.JSONException: Value [{"program_dosya":"..."},{"program_dosya":"https:..."}, `{"program_dosya":"https:\/\/..."}] of type org.json.JSONArray cannot be converted to JSONObject`

I want to pull the "programfile" data assigned in array via android.
PHP

 $results[] = Array("program_dosya" => $programdosya);

Android

try {
        JSONObject jObj = new JSONObject(result);

        JSONArray resultArray = jObj.getJSONArray("");
        for(int i = 0; i < resultArray.length(); i++) {
            JSONObject obj = resultArray.getJSONObject(i);
            String name = obj.getString("programdosya");
        }

    } catch (JSONException e) {
        e.printStackTrace();
    }

Body:
As I understand you need to iterate over the json array -

    // assuming you have string in this format, then all you have to do is
    String result = "[{\"program_dosya\":\"...\"},{\"program_dosya\":\"https:...\"}]";
    JSONArray array = new JSONArray(result);
    for (int i=0; i<array.length(); i++) {
        JSONObject js = array.getJSONObject(i);
        String link = js.getString("program_dosya");
        System.out.println(link);
    }


问:
How to link homebrew installed python3.x version to python3 command?
I had on OSX High Sierra versions 2.7 and 3.6 and correspondingly pip and pip3 installed. The terminal commands python and pip were linked to Python2 while python3 and pip3 to python3`

I upgraded my Python3 version with homebrew. The installation was successful but now I have to link the command for python3. homebrew suggests:

Linking /usr/local/Cellar/python/3.7.6_1...

Error: Could not symlink Frameworks/Python.framework/Headers

Target /usr/local/Frameworks/Python.framework/Headers
  is a symlink belonging to python@2. You can unlink it:

brew unlink python@2

To force the link and overwrite all conflicting files:

brew link --overwrite python

To list all files that would be deleted:

brew link --overwrite --dry-run python

However this would link python3 to python terminal command while I want a separate python3 and pip3 commands.

How to do that?

答:
However this would link python3 to python terminal command

That’s not true. Homebrew links python to either its own Python 2 or the system Python. It never links it to Python 3:

Homebrew provides one formula for Python 3.x (python) and another for Python 2.7.x (python@2).

The executables are organised as follows so that Python 2 and Python 3 can both be installed without conflict:

python3 points to Homebrew’s Python 3.x (if installed)

python2 points to Homebrew’s Python 2.7.x (if installed)

python points to Homebrew’s Python 2.7.x (if installed) otherwise the macOS system Python. Check out brew info python if you wish to add Homebrew’s 3.x python to your PATH.

pip3 points to Homebrew’s Python 3.x’s pip (if installed)

pip and pip2 point to Homebrew’s Python 2.7.x’s pip (if installed)

Emphasis mine. Source: https://docs.brew.sh/Homebrew-and-Python#python-3x-or-python-2x

You should thus be fine linking python@3. If you can’t do so, you can add $(brew --prefix python)/bin to your PATH to get all python3 and similar binaries.


问:
Not Allowing Multiple Button Presses
I'm building a camera app with Camera2 API, relatively new to Android development. Everything is working just working out the bugs. But I have a switch camera button, going from the front camera to the back or vise-versa. If the user continuosly presses the button, the app will crash. Trying to set it up in a way that it finishes everything it needs to do before the button can be used again.

I have the button set to enabled, but after press, it disables the button until everyting finishes, then renables, but that doesn't seem to work:

```<code>//The button to switch the camera to front and back camera.
    mChangeCamera = (ImageButton) findViewById(R.id.change_camera);
    mChangeCamera.setEnabled(true);
    mChangeCamera.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
        mChangeCamera.setEnabled(false);
            closeCamera();
            //  stopBackgroundthread();
            if (mTextureView.isAvailable()) {
                setUpCamera(mTextureView.getWidth(), mTextureView.getHeight());
                transformImage(mTextureView.getWidth(), mTextureView.getHeight());
                connectCamera();

            } else {
                mTextureView.setSurfaceTextureListener(mSurfaceTextureListener);
            }

            mChangeCamera.setEnabled(true);
        }
    });
</code>```

there has to be a simple way to do this, but not finding anyting from searchs. Anyone know how I can set it up not to crash when the user smashes the button?

答:
i did this by calculate time between multiple button presses...
create global variable in your class first

```<code>private long mLastClickTime = 0;
</code>```

and a final int for duration between clicks

```<code> public static final int CLICK_TIME = 400;
</code>```

then paste this code in on click of button

```<code>if (SystemClock.elapsedRealtime() - mLastClickTime < CLICK_TIME) {
      return;  //button pressed repeatedly so do nothing
}
mLastClickTime = SystemClock.elapsedRealtime();

       // button is not pressed repeatedly so add your desired action
</code>```

and of course you can increase the CLICK_TIME value if error still occurs

Title: Not Allowing Multiple Button Presses

Body:
I'm building a camera app with Camera2 API, relatively new to Android development. Everything is working just working out the bugs. But I have a switch camera button, going from the front camera to the back or vise-versa. If the user continuosly presses the button, the app will crash. Trying to set it up in a way that it finishes everything it needs to do before the button can be used again.

I have the button set to enabled, but after press, it disables the button until everyting finishes, then renables, but that doesn't seem to work:

//The button to switch the camera to front and back camera.
    mChangeCamera = (ImageButton) findViewById(R.id.change_camera);
    mChangeCamera.setEnabled(true);
    mChangeCamera.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
        mChangeCamera.setEnabled(false);
            closeCamera();
            //  stopBackgroundthread();
            if (mTextureView.isAvailable()) {
                setUpCamera(mTextureView.getWidth(), mTextureView.getHeight());
                transformImage(mTextureView.getWidth(), mTextureView.getHeight());
                connectCamera();

            } else {
                mTextureView.setSurfaceTextureListener(mSurfaceTextureListener);
            }

            mChangeCamera.setEnabled(true);
        }
    });

there has to be a simple way to do this, but not finding anyting from searchs. Anyone know how I can set it up not to crash when the user smashes the button?

Body:
i did this by calculate time between multiple button presses...
create global variable in your class first

private long mLastClickTime = 0;

and a final int for duration between clicks

 public static final int CLICK_TIME = 400;

then paste this code in on click of button

if (SystemClock.elapsedRealtime() - mLastClickTime < CLICK_TIME) {
      return;  //button pressed repeatedly so do nothing
}
mLastClickTime = SystemClock.elapsedRealtime();

       // button is not pressed repeatedly so add your desired action

and of course you can increase the CLICK_TIME value if error still occurs


问:
I want to make a link where the href is dependent on a js variable
I figured out the whole innerhtml thing but I don't know how to add variables into the href. I want it to make a link with the title being the title you enter and with the javascript that you enter to be in the href when you click "create".

  Bookmarklet Maker

  <input size="13" onkeypress="return searchKeyPress(event);" name="getTitle" type="text" id="getTitle" style="background-color: #252525;  border: 2px;  border-style: double;  border-color: white;  color: white;  padding: 15px 32px;  text-align: left;  text-decoration: none;  display: inline-block;  font-size: 16px;  font-weight: bold;  margin: 4px 2px;  cursor:;"
    placeholder="Bookmarklet name" />

  <input size="40" onkeypress="return searchKeyPress(event);" name="geJs" type="text" id="getJs" style="background-color: #252525;  border: 2px;  border-style: double;  border-color: white;  color: white;  padding: 15px 32px;  text-align: left;  text-decoration: none;  display: inline-block;  font-size: 16px;  font-weight: bold;  margin: 4px 2px;  cursor:;"
    placeholder="Javascript" />

  <button style="background-color: #252525;
  border: 2px;
  border-style: solid;
  border-color: white;
  color: white;
  padding: 15px 32px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 16px;
  font-weight: bold;
  margin: 4px 2px;
  cursor: pointer;" id="bookmarkletbutton" onclick="createBookmarklet()">Create</button>

```

答:
You can set the href atrubite via <element>.setAttribute("href", <value>)

-> document.getElementById("title").setAttribute("href", js_input)

(As mentioned by David: <element>.title = <value> also works)


问:
How to calculate exact average using arrays in Java
Regardless of what I try, the program outputs the average as the integer "4" when the average should be "4.78". I have tried changing the integers to doubles, but to no avail.

The rest of the program works as intended, though. It is supposed to print how many times each value in the text files appears by putting an asterisk next to it and it is supposed to indicate when a number is larger than the average by having a ">" appear next to it in the output.

```<code>import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class Main {

    public static void main(String args[]) throws IOException {

        int i = 0, count = 0, sum = 0;

        Scanner file = new Scanner(new File("input3.txt"));

        int[] frequency = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};

        int[] arr = new int[50];

        int current_num;

        while (file.hasNext()) {

            current_num = file.nextInt();

            sum += current_num;

            arr[i++] = current_num;

            count++;

            frequency[current_num]++;

        }

        int average = sum / count;

        for(i=0; i<arr.length; i++){
            if(arr[i] > average){
                System.out.print(arr[i] + " > " );
            }
            else{
                System.out.print(arr[i] + " ");
            }

            if(i%5==4){
                System.out.println();
                }
            }

        System.out.println("\n***** Frequency Graph *****\n");
        for(i=0; i<frequency.length; i++){
        System.out.print(i + " = ");
        for(int j=0; j<frequency[i]; j++){
        System.out.print("*");
        }
        System.out.println();
        }

        System.out.println("\nAverage of the numbers in the text file is : " + average);

        }

    }
</code>```

The numbers in the "input3.txt" file are:

```<code>5
8
8
1
5
0
6
6
5
3
4
0
6
8
5
4
9
5
8
0
4
7
4
2
0
9
8
3
5
5
5
7
5
7
1
4
4
0
7
4
8
4
2
4
9
8
8
2
3
4
</code>```

Any help would be appreciated!

答:
Try the following:

```<code>double average = 1.0 * sum / count;
</code>```

This should explicitly convert the expression to double.

Body:
Regardless of what I try, the program outputs the average as the integer "4" when the average should be "4.78". I have tried changing the integers to doubles, but to no avail.

The rest of the program works as intended, though. It is supposed to print how many times each value in the text files appears by putting an asterisk next to it and it is supposed to indicate when a number is larger than the average by having a ">" appear next to it in the output.

import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class Main {

    public static void main(String args[]) throws IOException {

        int i = 0, count = 0, sum = 0;

        Scanner file = new Scanner(new File("input3.txt"));

        int[] frequency = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};

        int[] arr = new int[50];

        int current_num;

        while (file.hasNext()) {

            current_num = file.nextInt();

            sum += current_num;

            arr[i++] = current_num;

            count++;

            frequency[current_num]++;

        }

        int average = sum / count;

        for(i=0; i<arr.length; i++){
            if(arr[i] > average){
                System.out.print(arr[i] + " > " );
            }
            else{
                System.out.print(arr[i] + " ");
            }

            if(i%5==4){
                System.out.println();
                }
            }

        System.out.println("\n***** Frequency Graph *****\n");
        for(i=0; i<frequency.length; i++){
        System.out.print(i + " = ");
        for(int j=0; j<frequency[i]; j++){
        System.out.print("*");
        }
        System.out.println();
        }

        System.out.println("\nAverage of the numbers in the text file is : " + average);

        }

    }

The numbers in the "input3.txt" file are:

5
8
8
1
5
0
6
6
5
3
4
0
6
8
5
4
9
5
8
0
4
7
4
2
0
9
8
3
5
5
5
7
5
7
1
4
4
0
7
4
8
4
2
4
9
8
8
2
3
4

Any help would be appreciated!

Body:
Try the following:

double average = 1.0 * sum / count;

This should explicitly convert the expression to double.


问:
How to fix member Event from @ionic/angular error in Ionic 5
I have upgraded from Ionic 4 to Ionic 5, now getting following error:

ERROR in src/app/app.component.ts(4,10): error TS2305: Module '"/node_modules/@ionic/angular/ionic-angular"' has no exported member 'Events'.

Following import line is causing the issue:

```<code>import { Events, Platform } from '@ionic/angular';
</code>```

How can I fix member Event from @ionic/angular error in Ionic 5?

答:
Events have been removed.
You can do your own service as event as your own using observables,and subject behavior so you could publish to the ovserable and subscribe to get the value.</p>

Body:
I have upgraded from Ionic 4 to Ionic 5, now getting following error:

ERROR in src/app/app.component.ts(4,10): error TS2305: Module '"/node_modules/@ionic/angular/ionic-angular"' has no exported member 'Events'.

Following import line is causing the issue:

import { Events, Platform } from '@ionic/angular';

How can I fix member Event from @ionic/angular error in Ionic 5?


问:
Getting some device info before the main app view is loaded up
Objective-c is pretty new to me so I may well be asking an absurdly simple question but having been looking over the web and in some books I'm a bit stumped to some degree. Quite probably due to my severe lack of knowledge with obj-c. So... any help with this one will be really handy...

All I want to do is get some simple info about the device the app is running on (using [UIDevice currentDevice]) on the app launch but before the main app view is loaded up. Simple stuff huh but in all honesty I have not got the idea quite how to do this! I then want whatever info I have to be availiable (In a variable? Not too sure if thats the correct term with obj-c) throughout the app and its views. Again, I don't really have much of an idea how.

I come form a web dev background so this is very new to me to a large degree. So... yeah, any tips/pointers, help etc would be ridiculously useful!

Thanks in advance, sorry for my n00b question!

答:
You might be able to use the viewController method "viewWillAppear". it will want to be in the same area as the "viewDidUnload" method, which will be in whatever *ViewController.m file is connected to the main view.

Possibly you'll need to do it in the main() routine, before the call the UIApplicationMain.

ContentLicense: CC BY-SA 3.0


问:
javax.validation.ValidationException: HV000028: Unexpected exception during isValid in Test
I can't figure out how to write a Unit Test for a Custom Constraint Validator. I have the following Validator class :

```<code>@Slf4j
@AllArgsConstructor
@NoArgsConstructor
public class SchoolIdValidator implements ConstraintValidator<ValidSchoolId, String> {

    private SchoolService schoolService;

    @Override
    public void initialize(ValidSchoolId constraintAnnotation) {}

    @Override
    public boolean isValid(String s, ConstraintValidatorContext constraintValidatorContext) {
        return schoolService.isValidSchoolId(s);
    }
}
</code>```

The Validator is used by the following annotation :

```<code>@Target({ElementType.METHOD, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = SchoolIdValidator.class)
public @interface ValidSchoolId {

    String message() default "Must be a valid school. Found: ${validatedValue}";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};

}
</code>```

SchoolService is a class which calls the School Api by using ApiClient which is a Generic class with Generic restTemplate requests :

```<code>@Service
@AllArgsConstructor
public class SchoolService {

    private ApiClient apiSchoolClient;

    public Boolean isValidSchoolId(String schoolId){
        try {
            ResponseEntity res = apiSchoolClient.get(
                    String.format("/stores/%s", schoolId), Object.class, null);
            return res.getStatusCode().is2xxSuccessful();
        } catch (HttpClientErrorException e) {
            if(e.getStatusCode().value() == 404)
                return false;
            else
                throw new TechnicalException("Can't get response from school Api");
        } catch(RestClientException e) {
            throw new TechnicalException("Can't get response from School Api");
        }
    }
}
</code>```

And finally the Student class :

```<code>@Data
public class Student {

    private String id;
    private String firstName;
    private String lastName;
    @ValidSchoolId
    private String schoolId;
}
</code>```

When I run the app it works perfectly. But, it doesn't work at all with the following Test class :

```<code>@RunWith(MockitoJUnitRunner.class)
@ExtendWith(SpringExtension.class)
public class SchoolIdValidatorTest {

    Validator validator;

    @InjectMocks
    private SchoolService schoolService;

    @Mock
    private ApiClient apiSchoolClient;

    @Before
    public void setUp() throws Exception {
        validator = Validation.buildDefaultValidatorFactory().getValidator();
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void isValid_SchoolIdExists_ShouldValidate() {

        Mockito.when(this.apiSchoolClient.get(Mockito.eq("/schools/12"), Mockito.any(), Mockito.any()))
                .thenReturn(new ResponseEntity<>(HttpStatus.OK));
        //given
        Student student = new Student();
        simulation.setSchoolId("12");
        //when
        Set<ConstraintViolation<Student>> violations = validator.validate(student);

        //then
        assertEquals(0, violations.size());
    }
</code>```

When it comes in SchoolIdValidator schoolService is always null. So, it always throws a NPE on SchoolIdValidator.isValid. If somebody has a solution it will be really helpful.

Thx for reading and for your help.

答:
The @InjectMocks here is likely the issue.

```<code>@RunWith(MockitoJUnitRunner.class)
@ExtendWith(SpringExtension.class)
public class SchoolIdValidatorTest {

    Validator validator;

    @InjectMocks
    private SchoolService schoolService;
</code>```

along with

```<code>Validation.buildDefaultValidatorFactory().getValidator()
</code>```

I'm under the assumption that SchoolService is typically a Spring managed bean, and SchoolIdValidator would have it injected. By using @InjectMocks you are saying this isn't a Spring managed bean. This class is instantiated by Mockito, so it would never be injected to your validator.

I'm not sure what the correct solution here is, since you don't post any configuration classes. Most likely, you need an additional test configuration class that instantiates your validator, ApiClient and injects your SchoolService. You can also just mock ApiClient with @MockBean which will make it a Spring managed bean, but also allow mocking.

Somewhat related, you do have constructors here. There's no reason to use @InjectMocks. Just use new SchoolService(apiSchoolClient).

Body:
I can't figure out how to write a Unit Test for a Custom Constraint Validator. I have the following Validator class :

@Slf4j
@AllArgsConstructor
@NoArgsConstructor
public class SchoolIdValidator implements ConstraintValidator<ValidSchoolId, String> {

    private SchoolService schoolService;

    @Override
    public void initialize(ValidSchoolId constraintAnnotation) {}

    @Override
    public boolean isValid(String s, ConstraintValidatorContext constraintValidatorContext) {
        return schoolService.isValidSchoolId(s);
    }
}

The Validator is used by the following annotation :

@Target({ElementType.METHOD, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = SchoolIdValidator.class)
public @interface ValidSchoolId {

    String message() default "Must be a valid school. Found: ${validatedValue}";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};

}

SchoolService is a class which calls the School Api by using ApiClient which is a Generic class with Generic restTemplate requests :

@Service
@AllArgsConstructor
public class SchoolService {

    private ApiClient apiSchoolClient;

    public Boolean isValidSchoolId(String schoolId){
        try {
            ResponseEntity res = apiSchoolClient.get(
                    String.format("/stores/%s", schoolId), Object.class, null);
            return res.getStatusCode().is2xxSuccessful();
        } catch (HttpClientErrorException e) {
            if(e.getStatusCode().value() == 404)
                return false;
            else
                throw new TechnicalException("Can't get response from school Api");
        } catch(RestClientException e) {
            throw new TechnicalException("Can't get response from School Api");
        }
    }
}

And finally the Student class :

@Data
public class Student {

    private String id;
    private String firstName;
    private String lastName;
    @ValidSchoolId
    private String schoolId;
}

When I run the app it works perfectly. But, it doesn't work at all with the following Test class :

@RunWith(MockitoJUnitRunner.class)
@ExtendWith(SpringExtension.class)
public class SchoolIdValidatorTest {

    Validator validator;

    @InjectMocks
    private SchoolService schoolService;

    @Mock
    private ApiClient apiSchoolClient;

    @Before
    public void setUp() throws Exception {
        validator = Validation.buildDefaultValidatorFactory().getValidator();
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void isValid_SchoolIdExists_ShouldValidate() {

        Mockito.when(this.apiSchoolClient.get(Mockito.eq("/schools/12"), Mockito.any(), Mockito.any()))
                .thenReturn(new ResponseEntity<>(HttpStatus.OK));
        //given
        Student student = new Student();
        simulation.setSchoolId("12");
        //when
        Set<ConstraintViolation<Student>> violations = validator.validate(student);

        //then
        assertEquals(0, violations.size());
    }

When it comes in SchoolIdValidator schoolService is always null. So, it always throws a NPE on SchoolIdValidator.isValid. If somebody has a solution it will be really helpful.

Thx for reading and for your help.

Body:
The @InjectMocks here is likely the issue.

@RunWith(MockitoJUnitRunner.class)
@ExtendWith(SpringExtension.class)
public class SchoolIdValidatorTest {

    Validator validator;

    @InjectMocks
    private SchoolService schoolService;

along with

Validation.buildDefaultValidatorFactory().getValidator()

I'm under the assumption that SchoolService is typically a Spring managed bean, and SchoolIdValidator would have it injected. By using @InjectMocks you are saying this isn't a Spring managed bean. This class is instantiated by Mockito, so it would never be injected to your validator.

I'm not sure what the correct solution here is, since you don't post any configuration classes. Most likely, you need an additional test configuration class that instantiates your validator, ApiClient and injects your SchoolService. You can also just mock ApiClient with @MockBean which will make it a Spring managed bean, but also allow mocking.

Somewhat related, you do have constructors here. There's no reason to use @InjectMocks. Just use new SchoolService(apiSchoolClient).


答:
Edit 1: taking into account that all children tables may be empty

Edit 2: Accepted answer is inefficient and will result in temporary table being created by the union of the size of B + C, then grouping will be performed on that temporary table. An explain plan on that query reveals Using temporary; Using filesort, both being bad:

```<code>+------+-------------+------------+-------+---------------+------+---------+-----------------+------+---------------------------------+
| id   | select_type | table      | type  | possible_keys | key  | key_len | ref             | rows | Extra                           |
+------+-------------+------------+-------+---------------+------+---------+-----------------+------+---------------------------------+
|    1 | PRIMARY     | A          | ALL   | NULL          | NULL | NULL    | NULL            | 5    | Using temporary; Using filesort |
|    1 | PRIMARY     | <derived2> | ref   | key0          | key0 | 5       | A.id            | 2    |                                 |
|    2 | DERIVED     | B          | index | NULL          | a    | 4       | NULL            | 15   | Using index                     |
|    3 | UNION       | C          | index | NULL          | a    | 4       | NULL            | 14   | Using index                     |
+------+-------------+------------+-------+---------------+------+---------+-----------------+------+---------------------------------+
</code>```

While if you simply sum up the individual COUNT, you would only have the indexes being queried to know the amount of elements:

```<code>SELECT name,
  (SELECT COUNT(*) FROM B WHERE B.a = A.id) +
  (SELECT COUNT(*) FROM C WHERE C.a = A.id) AS count
FROM A;
</code>```

This would result in the following explain plan:

```<code>+------+--------------------+-------+------+---------------+------+---------+-----------------+------+-------------+
| id   | select_type        | table | type | possible_keys | key  | key_len | ref             | rows | Extra       |
+------+--------------------+-------+------+---------------+------+---------+-----------------+------+-------------+
|    1 | PRIMARY            | A     | ALL  | NULL          | NULL | NULL    | NULL            | 5    |             |
|    3 | DEPENDENT SUBQUERY | C     | ref  | a             | a    | 4       | A.id            | 1    | Using index |
|    2 | DEPENDENT SUBQUERY | B     | ref  | a             | a    | 4       | A.id            | 1    | Using index |
+------+--------------------+-------+------+---------------+------+---------+-----------------+------+-------------+
</code>```

Queries and explain plan of accepted answer + this one available in the demo.

Title: Count total amount of references from multiple foreign tables in MySQL

Body:
I have 3 tables:

A

B which has a foreign key to A

C same

How can I count the total number of relations that references a row in A?

ex.

A

+----+------+
| id | name |
+----+------+
|  1 |  foo |
|  2 |  bar |
+----+------+

B

+----+----+
| id |  a |
+----+----+
|  1 |  1 |
|  2 |  1 |
|  3 |  2 |
|  4 |  2 |
+----+----+

C

+----+----+
| id |  a |
+----+----+
|  1 |  1 |
|  2 |  1 |
+----+----+

I want to get this result:

+------+----+
| name |  a |
+------+----+
| foo  |  4 |
| bar  |  2 |
+------+----+

Thanks

Body:
Edit 1: taking into account that all children tables may be empty

Edit 2: Accepted answer is inefficient and will result in temporary table being created by the union of the size of B + C, then grouping will be performed on that temporary table. An explain plan on that query reveals Using temporary; Using filesort, both being bad:

+------+-------------+------------+-------+---------------+------+---------+-----------------+------+---------------------------------+
| id   | select_type | table      | type  | possible_keys | key  | key_len | ref             | rows | Extra                           |
+------+-------------+------------+-------+---------------+------+---------+-----------------+------+---------------------------------+
|    1 | PRIMARY     | A          | ALL   | NULL          | NULL | NULL    | NULL            | 5    | Using temporary; Using filesort |
|    1 | PRIMARY     | <derived2> | ref   | key0          | key0 | 5       | A.id            | 2    |                                 |
|    2 | DERIVED     | B          | index | NULL          | a    | 4       | NULL            | 15   | Using index                     |
|    3 | UNION       | C          | index | NULL          | a    | 4       | NULL            | 14   | Using index                     |
+------+-------------+------------+-------+---------------+------+---------+-----------------+------+---------------------------------+

While if you simply sum up the individual COUNT, you would only have the indexes being queried to know the amount of elements:

SELECT name,
  (SELECT COUNT(*) FROM B WHERE B.a = A.id) +
  (SELECT COUNT(*) FROM C WHERE C.a = A.id) AS count
FROM A;

This would result in the following explain plan:

+------+--------------------+-------+------+---------------+------+---------+-----------------+------+-------------+
| id   | select_type        | table | type | possible_keys | key  | key_len | ref             | rows | Extra       |
+------+--------------------+-------+------+---------------+------+---------+-----------------+------+-------------+
|    1 | PRIMARY            | A     | ALL  | NULL          | NULL | NULL    | NULL            | 5    |             |
|    3 | DEPENDENT SUBQUERY | C     | ref  | a             | a    | 4       | A.id            | 1    | Using index |
|    2 | DEPENDENT SUBQUERY | B     | ref  | a             | a    | 4       | A.id            | 1    | Using index |
+------+--------------------+-------+------+---------------+------+---------+-----------------+------+-------------+

Queries and explain plan of accepted answer + this one available in the demo.


问:
Pandas create additional data frames with for loop
For SO purposes, this is some made up times series data:

```<code>import pandas as pd
import numpy as np
from numpy.random import randint

np.random.seed(10)  # added for reproductibility

rng = pd.date_range('10/9/2018 00:00', periods=1000, freq='1H')
df = pd.DataFrame({'Random_Number':randint(1, 100, 1000)}, index=rng)
</code>```

Question, how do I create a function that can return re-sampled daily 97.5 & 2.5 percentiles values for each in day in pandas data frame? I know this code below isn't even close it will just return the upper & lower percentiles of the entire dataset. Ultimately Im trying to break this down per day and the dataframe returned the index would be the time stamp (date) of the day re sampled..

```<code>def createDfs(data):
    for day in df:
        dfDay = pd.DataFrame()

        hi = df.quantile(0.975)[0]
        low = df.quantile(0.025)[0]

        data = {'upper_97.5%': [hi],
                'lower_2.5%' : [low]}

        dfUpperLower = pd.DataFrame(data)
        #dfUpperLower.set_index('Date')

    return dfUpperLower
</code>```

Any tips greatly appreciated..

Body:
For SO purposes, this is some made up times series data:

import pandas as pd
import numpy as np
from numpy.random import randint

np.random.seed(10)  # added for reproductibility

rng = pd.date_range('10/9/2018 00:00', periods=1000, freq='1H')
df = pd.DataFrame({'Random_Number':randint(1, 100, 1000)}, index=rng)

Question, how do I create a function that can return re-sampled daily 97.5 & 2.5 percentiles values for each in day in pandas data frame? I know this code below isn't even close it will just return the upper & lower percentiles of the entire dataset. Ultimately Im trying to break this down per day and the dataframe returned the index would be the time stamp (date) of the day re sampled..

def createDfs(data):
    for day in df:
        dfDay = pd.DataFrame()

        hi = df.quantile(0.975)[0]
        low = df.quantile(0.025)[0]

        data = {'upper_97.5%': [hi],
                'lower_2.5%' : [low]}

        dfUpperLower = pd.DataFrame(data)
        #dfUpperLower.set_index('Date')

    return dfUpperLower

Any tips greatly appreciated..

Body:
I think you just want to use .resample with .quantile:

In [10]: df.resample('1D').quantile([0.025, 0.975]).unstack()
Out[10]:
           Random_Number
                   0.025   0.975
2018-10-09         5.600  91.700
2018-10-10        12.575  94.425
2018-10-11         5.575  92.400
2018-10-12         9.875  97.425
2018-10-13         2.725  87.550
2018-10-14        10.200  96.425
2018-10-15        10.725  96.425
...


问:
SharePoint 2010 - Client Object Model - Add attachment to ListItem
I have a SharePoint List to which I'm adding new ListItems using the Client Object Model.
Adding ListItems is not a problem and works great.

Now I want to add attachments.

I'm using the SaveBinaryDirect in the following manner:

```<code>File.SaveBinaryDirect(clientCtx, url.AbsolutePath + "/Attachments/31/" + fileName, inputStream, true);
</code>```

It works without any problem as long as the item that I'm trying to add the attachment to, already has an attachment that was added through the SharePoint site and not using the Client Object Model.

When I try to add an attachment to a item that doesnt have any attachments yet, I get the following errors (both happen but not with the same files - but those two messages appear consistently):

```The remote server returned an error: (409) Conflict```

```The remote server returned an error: (404) Not Found```

I figured that maybe I need to create the attachment folder first for this item.
When I try the following code:

```<code>clientCtx.Load(ticketList.RootFolder.Folders);
clientCtx.ExecuteQuery();
clientCtx.Load(ticketList.RootFolder.Folders[1]);             // 1 -> Attachment folder
clientCtx.Load(ticketList.RootFolder.Folders[1].Folders);
clientCtx.ExecuteQuery();
Folder folder = ticketList.RootFolder.Folders[1].Folders.Add("33");
clientCtx.ExecuteQuery();
</code>```

I receive an error message saying:
    ```Cannot create folder "Lists/Ticket System/Attachment/33"```

I have full administrator rights for the SharePoint site/list.

Any ideas what I could be doing wrong?

Thanks, Thorben

答:
It reflects rather poorly on the Microsoft SharePoint team for not coming forward with an acknowledgement of the issue and a usable suggestion on how to resolve it. Here is how I dealt with it:

I am using the new SharePoint 2010 managed client that ships with the product. Hence, I already have a SharePoint ClientContext with credentials. The following function adds an attachment to a list item:

```<code>private void SharePoint2010AddAttachment(ClientContext ctx,
                                     string listName, string itemId,
                                     string fileName, byte[] fileContent)
{
    var listsSvc = new sp2010.Lists();
    listsSvc.Credentials = _sharePointCtx.Credentials;
    listsSvc.Url = _sharePointCtx.Web.Context.Url + "_vti_bin/Lists.asmx";
    listsSvc.AddAttachment(listName, itemId, fileName, fileContent);
}
</code>```

The only prerequisite for the code above is to add to the project (I used Visual Studio 2008) a _web_reference_ I called sp2010 which is created from the URL of: http:///_vti_bin/Lists.asmx

Bon Chance...

ContentLicense: CC BY-SA 2.5

Body:
I have a SharePoint List to which I'm adding new ListItems using the Client Object Model.
Adding ListItems is not a problem and works great.

Now I want to add attachments.

I'm using the SaveBinaryDirect in the following manner:

File.SaveBinaryDirect(clientCtx, url.AbsolutePath + "/Attachments/31/" + fileName, inputStream, true);

It works without any problem as long as the item that I'm trying to add the attachment to, already has an attachment that was added through the SharePoint site and not using the Client Object Model.

When I try to add an attachment to a item that doesnt have any attachments yet, I get the following errors (both happen but not with the same files - but those two messages appear consistently):

The remote server returned an error: (409) Conflict

The remote server returned an error: (404) Not Found

I figured that maybe I need to create the attachment folder first for this item.
When I try the following code:

clientCtx.Load(ticketList.RootFolder.Folders);
clientCtx.ExecuteQuery();
clientCtx.Load(ticketList.RootFolder.Folders[1]);             // 1 -> Attachment folder
clientCtx.Load(ticketList.RootFolder.Folders[1].Folders);
clientCtx.ExecuteQuery();
Folder folder = ticketList.RootFolder.Folders[1].Folders.Add("33");
clientCtx.ExecuteQuery();

I receive an error message saying:

Cannot create folder "Lists/Ticket System/Attachment/33"

I have full administrator rights for the SharePoint site/list.

Any ideas what I could be doing wrong?

Thanks, Thorben

Body:
It reflects rather poorly on the Microsoft SharePoint team for not coming forward with an acknowledgement of the issue and a usable suggestion on how to resolve it. Here is how I dealt with it:

I am using the new SharePoint 2010 managed client that ships with the product. Hence, I already have a SharePoint ClientContext with credentials. The following function adds an attachment to a list item:

private void SharePoint2010AddAttachment(ClientContext ctx,
                                     string listName, string itemId,
                                     string fileName, byte[] fileContent)
{
    var listsSvc = new sp2010.Lists();
    listsSvc.Credentials = _sharePointCtx.Credentials;
    listsSvc.Url = _sharePointCtx.Web.Context.Url + "_vti_bin/Lists.asmx";
    listsSvc.AddAttachment(listName, itemId, fileName, fileContent);
}

The only prerequisite for the code above is to add to the project (I used Visual Studio 2008) a _web_reference_ I called sp2010 which is created from the URL of: http:///_vti_bin/Lists.asmx

Bon Chance...


问:
How to apply regex for multiple phrases on a dataframe column?
Hello I have a dataframe where I want to remove a specific set of characters 'fwd', 're', 'RE' from every row that starts with these phrases or contains these phrases. The issue I am facing is that I do not know how to apply regex for each case.

my dataframe looks like this:

```<code>      summary
0 Fwd: Please look at the attached documents and take action
1 NSN for the ones who care
2 News for all team members
3 Fwd:RE:Re: Please take action on the action needed items
4 Fix all the mistakes please
5 Fwd:Re: Take action on the attachments in this email
6 Fwd:RE: Action is required
</code>```

I want a result dataframe like this:

```<code>          summary
0 Please look at the attached documents and take action
1 NSN for the ones who care
2 News for all team members
3 Please take action on the action needed items
4 Fix all the mistakes please
5 Take action on the attachments in this email
6 Action is required
</code>```

To get rid of 'Fwd' I used df['msg'].str.replace(r'^Fwd: ','')

答:
If they can be anywhere in the string, you could use a repeating pattern:

```<code>^(?:(?:Fwd|R[eE]):)+\s*
</code>```

^ Start of string

(?: Non capturing group

(?:Fwd|R[eE]): match either Fwd, Re or RE

)+ Close non capturing group and repeat 1+ times

\s* Match trailing whitespaces

Regex demo

In the replacement use an empty string.

You could also make the pattern case insensitive using re.IGNORECASE and use (?:fwd|re) if you want to match all possible variations.

For example

```<code>str.replace(r'^(?:(?:Fwd|R[eE]):)+\s*','')
</code>```

Body:
Hello I have a dataframe where I want to remove a specific set of characters 'fwd', 're', 'RE' from every row that starts with these phrases or contains these phrases. The issue I am facing is that I do not know how to apply regex for each case.

my dataframe looks like this:

      summary
0 Fwd: Please look at the attached documents and take action
1 NSN for the ones who care
2 News for all team members
3 Fwd:RE:Re: Please take action on the action needed items
4 Fix all the mistakes please
5 Fwd:Re: Take action on the attachments in this email
6 Fwd:RE: Action is required

I want a result dataframe like this:

          summary
0 Please look at the attached documents and take action
1 NSN for the ones who care
2 News for all team members
3 Please take action on the action needed items
4 Fix all the mistakes please
5 Take action on the attachments in this email
6 Action is required

To get rid of 'Fwd' I used df['msg'].str.replace(r'^Fwd: ','')

Body:
If they can be anywhere in the string, you could use a repeating pattern:

^(?:(?:Fwd|R[eE]):)+\s*

^ Start of string

(?: Non capturing group

(?:Fwd|R[eE]): match either Fwd, Re or RE

)+ Close non capturing group and repeat 1+ times

\s* Match trailing whitespaces

Regex demo

In the replacement use an empty string.

You could also make the pattern case insensitive using re.IGNORECASE and use (?:fwd|re) if you want to match all possible variations.

For example

str.replace(r'^(?:(?:Fwd|R[eE]):)+\s*','')


问:
How to automatically close react-select menu once the last item has been selected? (empty list)
Is there a built-in option or easy trick to auto close a react-select input once the user has selected the last available item?

I use the option closeMenuOnSelect={false} so that I can keep selecting choice (no menu close between them), but there is no need to keep it displayed with a "No item" message once I've selected all of them, I'd like it to close automatically.

I could implement such a behaviour, but it's redundant boilerplate, so I'm looking for built-in solution, but didn't find any at https://github.com/JedWatson/react-select#props

I've created a feature request for this https://github.com/JedWatson/react-select/issues/3936

答:
Here are 2 ways to go about it:

First is to use the noOptionsMessage prop which will close the component when no options are left to select:

```<code><Select
    ...
    noOptionsMessage={() => null}
/>
</code>```

Second way is to achieve this by using the built-in menuIsOpen flag.

This way your select menu will remain open as long as you tell it there are options available:

```<code>// in your react component...

state = {
    isOptionsExist: /* code to determine if options are available  */
}

<Select
    ...
    /* pass in state param  */
    menuIsOpen={isOptionsExist}
/>
</code>```

Body:
Here are 2 ways to go about it:

First is to use the noOptionsMessage prop which will close the component when no options are left to select:

<Select
    ...
    noOptionsMessage={() => null}
/>

Second way is to achieve this by using the built-in menuIsOpen flag.

This way your select menu will remain open as long as you tell it there are options available:

// in your react component...

state = {
    isOptionsExist: /* code to determine if options are available  */
}

<Select
    ...
    /* pass in state param  */
    menuIsOpen={isOptionsExist}
/>


问:
How to concatenate indefinite number of arrays of Javascript objects
I have an array of Groups s.t. each Group has many Users

I want to return all (unique) Users for a given array of Groups.

So far, I have

```<code>  let actor = await User.query().findById(req.user.id).eager('groups') // find the actor requesting

let actor_groups = actor.groups // find all groups of actor

  if (actor_groups.length > 1)
    var actor_groups_users = actor_groups[0].user
    for (let i = 0; i < actor_groups.length; i++) {
      const actor_groups_users = actor_groups_users.concat(actor_groups[i]);
    }
    console.log('actor groups users is', actor_groups_users);
  else
    // return users from the first (only) group
</code>```

which returns the error: actor_groups_users is not defined

Feels like a roundabout way to do this. Is there a way to just combine actor_groups into a single combined group?

答:
Here we can cycle through, adding users if not already in the array, using .forEach() and .includes().

This is assuming that group.user is an Array of users.

```<code>let users = [];

// check that actor_groups has items in it
if (actor_groups && actor_groups.length > 1) {

   // cycle through each actor_group
   actor_groups.forEach( group => {

      // check if we have a 'user' array with items in it
      if (group.user && group.user.length > 1) {

         // cycle through each user in the group
         group.user.forEach( user => {

            // check if we already have this user
            // if not, add it to users
            if (!users.includes(user)) {
               users.push(user);
            }
         }
      }
   }
}
</code>```

Body:
I have an array of Groups s.t. each Group has many Users

I want to return all (unique) Users for a given array of Groups.

So far, I have

  let actor = await User.query().findById(req.user.id).eager('groups') // find the actor requesting

let actor_groups = actor.groups // find all groups of actor

  if (actor_groups.length > 1)
    var actor_groups_users = actor_groups[0].user
    for (let i = 0; i < actor_groups.length; i++) {
      const actor_groups_users = actor_groups_users.concat(actor_groups[i]);
    }
    console.log('actor groups users is', actor_groups_users);
  else
    // return users from the first (only) group

which returns the error: actor_groups_users is not defined

Feels like a roundabout way to do this. Is there a way to just combine actor_groups into a single combined group?

Body:
Here we can cycle through, adding users if not already in the array, using .forEach() and .includes().

This is assuming that group.user is an Array of users.

let users = [];

// check that actor_groups has items in it
if (actor_groups && actor_groups.length > 1) {

   // cycle through each actor_group
   actor_groups.forEach( group => {

      // check if we have a 'user' array with items in it
      if (group.user && group.user.length > 1) {

         // cycle through each user in the group
         group.user.forEach( user => {

            // check if we already have this user
            // if not, add it to users
            if (!users.includes(user)) {
               users.push(user);
            }
         }
      }
   }
}


问:
C# Get EIP the memory address
I'm trying to find the memory address of what the (EIP) Instruction Pointer is executing.
I have a very simple program:

```<code>internal class Program
{
    private static void Main(string[] args)
    {
        var sample = new Sample();
        var val = sample.GenericMethod("Nippies");
        Console.ReadLine();
    }
}

public class Sample
{
    public int GenericMethod<T>(T input)
    {
        //How can I get the current memory address
        var currentMemoryAddress = "";
        Console.WriteLine(currentMemoryAddress );
        return 5;
    }
}
</code>```

TBH I'm trying to obtain the address of the GenericMethod<T> but generic methods aren't stored conventionally in the method tables, they're built at runtime.

So I figured I if I could print out the address of one of the current lines being executed I would be a lot closer to figuring it out.

How can I obtain the memory address of the instructions at a specific line?

答:
The GetNativeOffset method of stackframe does it.
With the somewhat surprising result that values for string and integer specializations are the same, and different for Guid.

Here is a better method, which retrieves the actual EIP register value. I found the assembly bits here, and adjusted it for the question at hand.

```<code>using ByteToFunc;
using System;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;

namespace eip
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            var vals = Sample.GenericMethod("Nibbles");
            var valg = Sample.GenericMethod(Guid.NewGuid());
            var vali = Sample.GenericMethod(42);
            Console.ReadLine();
        }
    }

    public class Sample
    {
        /* trap values: bad beef is bad food */
        public static int[] EipEspEbpEsiEdiEbxHolder = new[] { 0xBADF00D, 0xBADBEEF, 0xBADF00D, 0xBADBEEF, 0xBADF00D, 0xBADBEEF };

        public static int GenericMethod<T>(T input)
        {
            //How can I get the current memory address
            var subjectAddress = GetAddress(nameof(Sample.SubjectMethod));
            var holderAddress = GetEipEspEbpEsiEdiEbxHolder();
            var captureRegisters = FuncGenerator.Generate<Action<int>, ActionInt>(
                new byte[0].Concat(new byte[]
                {
                    0xE8, 0x1C, 0x00, 0x00, 0x00  // call 28
                })
                .Concat(new byte[]
                {
                    // save EIP, ESP, EBP, ESI, EDI to temp array
                    0x83, 0xC0, 0x1B, // add eax,0x1B (27 bytes)
                    0x89, 0x02,       // mov DWORD PTR [edx],eax
                    0x89, 0x62, 0x04, // mov DWORD PTR [edx+0x4],esp
                    0x89, 0x6A, 0x08, // mov DWORD PTR [edx+0x8],ebp
                    0x89, 0x72, 0x0C, // mov DWORD PTR [edx+0xc],esi
                    0x89, 0x7A, 0x10, // mov DWORD PTR [edx+0x10],edi
                    0x89, 0x5A, 0x14, // mov DWORD PTR [edx+0x14],ebx
                })
                .Concat(new byte[]
                {
                    0xB8, // mov eax
                })
                .Concat(subjectAddress)
                .Concat(new byte[]
                {
                    0xFF, 0xD0 // call eax
                })
                .Concat(new byte[]
                {
                    0xC3 //retn
                })
                .Concat(new byte[]
                {
                    // Helper function for getting EIP as it is inaccessible directly on x86_32
                    0x8B, 0x04, 0x24, // mov eax,DWORD PTR [esp]
                    0xC3 //retn
                })
                .ToArray()
            );

            captureRegisters(holderAddress);
            Console.WriteLine($"EIP = { EipEspEbpEsiEdiEbxHolder[0].ToString("X") }");
            return 5;
        }

        public static int SubjectMethod()
        {
            return 5;
        }

        private static int GetEipEspEbpEsiEdiEbxHolder()
        {
            unsafe
            {
                var typedReference = __makeref(EipEspEbpEsiEdiEbxHolder);
                int* fieldAddress = (int*)*(int*)*(int*)&typedReference;
                return (int)fieldAddress + 8;
            }
        }

        private static byte[] GetAddress(string name)
        {
            return BitConverter.GetBytes((int)GetRawAddress(name)).ToArray();
        }

        private static IntPtr GetRawAddress(string name)
        {
            var methodHandle = typeof(Sample).GetMethod(name, BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance).MethodHandle;
            RuntimeHelpers.PrepareMethod(methodHandle);
            return methodHandle.GetFunctionPointer();
        }
    }
}

</code>```

To compile and run, you can use a simple Console project, and add the FuncGenerator class by afish from here: https://gist.github.com/afish/8fd6cf8f8c196901b5e1a5ee1000ee68

Result: three different values for EIP, which should be expected.

Title: C# Get EIP the memory address

Body:
I'm trying to find the memory address of what the (EIP) Instruction Pointer is executing.
I have a very simple program:

internal class Program
{
    private static void Main(string[] args)
    {
        var sample = new Sample();
        var val = sample.GenericMethod("Nippies");
        Console.ReadLine();
    }
}

public class Sample
{
    public int GenericMethod<T>(T input)
    {
        //How can I get the current memory address
        var currentMemoryAddress = "";
        Console.WriteLine(currentMemoryAddress );
        return 5;
    }
}

TBH I'm trying to obtain the address of the GenericMethod<T> but generic methods aren't stored conventionally in the method tables, they're built at runtime.

So I figured I if I could print out the address of one of the current lines being executed I would be a lot closer to figuring it out.

How can I obtain the memory address of the instructions at a specific line?

Body:
The GetNativeOffset method of stackframe does it.
With the somewhat surprising result that values for string and integer specializations are the same, and different for Guid.

Here is a better method, which retrieves the actual EIP register value. I found the assembly bits here, and adjusted it for the question at hand.

using ByteToFunc;
using System;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;

namespace eip
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            var vals = Sample.GenericMethod("Nibbles");
            var valg = Sample.GenericMethod(Guid.NewGuid());
            var vali = Sample.GenericMethod(42);
            Console.ReadLine();
        }
    }

    public class Sample
    {
        /* trap values: bad beef is bad food */
        public static int[] EipEspEbpEsiEdiEbxHolder = new[] { 0xBADF00D, 0xBADBEEF, 0xBADF00D, 0xBADBEEF, 0xBADF00D, 0xBADBEEF };

        public static int GenericMethod<T>(T input)
        {
            //How can I get the current memory address
            var subjectAddress = GetAddress(nameof(Sample.SubjectMethod));
            var holderAddress = GetEipEspEbpEsiEdiEbxHolder();
            var captureRegisters = FuncGenerator.Generate<Action<int>, ActionInt>(
                new byte[0].Concat(new byte[]
                {
                    0xE8, 0x1C, 0x00, 0x00, 0x00  // call 28
                })
                .Concat(new byte[]
                {
                    // save EIP, ESP, EBP, ESI, EDI to temp array
                    0x83, 0xC0, 0x1B, // add eax,0x1B (27 bytes)
                    0x89, 0x02,       // mov DWORD PTR [edx],eax
                    0x89, 0x62, 0x04, // mov DWORD PTR [edx+0x4],esp
                    0x89, 0x6A, 0x08, // mov DWORD PTR [edx+0x8],ebp
                    0x89, 0x72, 0x0C, // mov DWORD PTR [edx+0xc],esi
                    0x89, 0x7A, 0x10, // mov DWORD PTR [edx+0x10],edi
                    0x89, 0x5A, 0x14, // mov DWORD PTR [edx+0x14],ebx
                })
                .Concat(new byte[]
                {
                    0xB8, // mov eax
                })
                .Concat(subjectAddress)
                .Concat(new byte[]
                {
                    0xFF, 0xD0 // call eax
                })
                .Concat(new byte[]
                {
                    0xC3 //retn
                })
                .Concat(new byte[]
                {
                    // Helper function for getting EIP as it is inaccessible directly on x86_32
                    0x8B, 0x04, 0x24, // mov eax,DWORD PTR [esp]
                    0xC3 //retn
                })
                .ToArray()
            );

            captureRegisters(holderAddress);
            Console.WriteLine($"EIP = { EipEspEbpEsiEdiEbxHolder[0].ToString("X") }");
            return 5;
        }

        public static int SubjectMethod()
        {
            return 5;
        }

        private static int GetEipEspEbpEsiEdiEbxHolder()
        {
            unsafe
            {
                var typedReference = __makeref(EipEspEbpEsiEdiEbxHolder);
                int* fieldAddress = (int*)*(int*)*(int*)&typedReference;
                return (int)fieldAddress + 8;
            }
        }

        private static byte[] GetAddress(string name)
        {
            return BitConverter.GetBytes((int)GetRawAddress(name)).ToArray();
        }

        private static IntPtr GetRawAddress(string name)
        {
            var methodHandle = typeof(Sample).GetMethod(name, BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance).MethodHandle;
            RuntimeHelpers.PrepareMethod(methodHandle);
            return methodHandle.GetFunctionPointer();
        }
    }
}

To compile and run, you can use a simple Console project, and add the FuncGenerator class by afish from here: https://gist.github.com/afish/8fd6cf8f8c196901b5e1a5ee1000ee68

Result: three different values for EIP, which should be expected.


问:
Optimization of Google Sheets loading speed
Maybe someone can shed any light, personal experience or reference to official documentation.

Suppose, I have a Google Spreadsheet, which I connected to other Spreadsheets by using IMPORTRANGE. I noticed that my receiving Spreadsheet started loading slower than normal. Are there any tricks for optimizing the loading speed? For example, does it make any difference if I:

Use IMPORTRANGE less frequently by loading the data (let's say, once) to a separate tab, and then query that tab internally from within the same spreadsheet?

or

Use IMPORTRANGE frequently in multiple cells and run Query for each cell individually, and avoid having a large dedicated tab that gets all the info first?

答:
Use IMPORTRANGE less frequently by loading the data (let's say, once) to a separate tab, and then query that tab internally from within the same spreadsheet?

definitely the right approach to gain performance speed


问:
syntax for ancestor:: in Xpath expression
xpath -e '//attribute::vo/../text()' books.xml

returns the content of each element having an attribute named vo.

For example, with this book.xml :

```<code><bookstore>
<book category="cooking">
  <title lang="en" vo="it">Everyday Italian</title>
  <author>Giada De Laurentiis</author>
  <year>2005</year>
  <price>30.00</price>
</book>
<book category="children">
  <title lang="en">Harry Potter</title>
  <author>J K. Rowling</author>
  <year>2005</year>
  <price>29.99</price>
</book>
<book category="web">
  <title lang="en" vo="fr">XQuery Kick Start</title>
  <author>James McGovern</author>
  <author>Per Bothner</author>
  <author>Kurt Cagle</author>
  <author>James Linn</author>
  <author>Vaidyanathan Nagarajan</author>
  <year>2003</year>
  <price>49.99</price>
</book>
<book category="web">
  <title lang="en">Learning XML</title>
  <author>Erik T. Ray</author>
  <year>2003</year>
  <price>39.95</price>
</book>
</bookstore>
</code>```

then the request :

xpath -e '//attribute::vo/../text()' books.xml

gives :

```<code>Found 2 nodes in /tmp/books.xml:
-- NODE --
Everyday Italian
-- NODE --
XQuery Kick Start
</code>```

What should be the syntax of the request having the same result, but with ancestor:: in place of .. ?

答:
I understand that //attribute::vo/../text() is not an natural Xpath expression.

//*[@vo]/text() is better.

So no need to introduce ancestor:: or parent:: in place of ...

Body:
xpath -e '//attribute::vo/../text()' books.xml

returns the content of each element having an attribute named vo.

For example, with this book.xml :

<bookstore>
<book category="cooking">
  <title lang="en" vo="it">Everyday Italian</title>
  <author>Giada De Laurentiis</author>
  <year>2005</year>
  <price>30.00</price>
</book>
<book category="children">
  <title lang="en">Harry Potter</title>
  <author>J K. Rowling</author>
  <year>2005</year>
  <price>29.99</price>
</book>
<book category="web">
  <title lang="en" vo="fr">XQuery Kick Start</title>
  <author>James McGovern</author>
  <author>Per Bothner</author>
  <author>Kurt Cagle</author>
  <author>James Linn</author>
  <author>Vaidyanathan Nagarajan</author>
  <year>2003</year>
  <price>49.99</price>
</book>
<book category="web">
  <title lang="en">Learning XML</title>
  <author>Erik T. Ray</author>
  <year>2003</year>
  <price>39.95</price>
</book>
</bookstore>

then the request :

xpath -e '//attribute::vo/../text()' books.xml

gives :

Found 2 nodes in /tmp/books.xml:
-- NODE --
Everyday Italian
-- NODE --
XQuery Kick Start

What should be the syntax of the request having the same result, but with ancestor:: in place of .. ?


问:
How do I get all the values from one table
I am using Microsoft SQL Server. I have two tables

Cost Center - A list of all our production processes.

Scheduled Process - A list of jobs that are scheduled to go through each Cost Center

My table Cost Center looks as below

```<code>CostCenterCode  CostCenterDesc
------------------------------
123             Print
456             Stich
789             Fold
999             Ship
</code>```

My table Process Schedule looks as below

```<code>JobNumber   StartDate   ScheduledHours  CostCenterCode
------------------------------------------------------
12345   2020-01-01      33               123
12345   2020-01-01      33               456
12345   2020-01-01      33               999
</code>```

Now based on my above dataset, cost center 789 does not have anything scheduled. I want to write a query that will show what is scheduled for each cost center each day. Cost Center 789 does not have anything scheduled but it should still show that cost center with 0 hours.

答:
You can try this using Aggregate Functions (Transact-SQL)
 and the SQL Server join.

```<code>create table CostCenter (CostCenterCode int, CostCenterDesc varchar(120))
insert into CostCenter Values(123, 'Print'), (456, 'Stich'), (789, 'Fold'), (999, 'Ship')

Create table ProcessSchedule (JobNumber int, StartDate Date, ScheduledHours int,
CostCenterCode int)
Insert into ProcessSchedule Values (12345, '2020-01-01', 33, 123),
(12345 , '2020-01-01', 33, 456), (12345, '2020-01-01', 33, 999)

;WITH cte
AS (
    SELECT CostCenter.CostCenterCode
        ,CostCenter.CostCenterDesc
        ,ProcessSchedule.StartDate
        ,ISNULL(ProcessSchedule.ScheduledHours, 0) AS ScheduledHours
    FROM CostCenter
    LEFT JOIN ProcessSchedule ON CostCenter.CostCenterCode = ProcessSchedule.CostCenterCode
    )
SELECT CostCenterCode
    ,CostCenterDesc
    ,StartDate
    ,SUM(ScheduledHours) AS TotalScheduledHours
FROM cte
GROUP BY CostCenterCode
    ,CostCenterDesc
    ,StartDate
</code>```

Live Demo Here

Body:
I am using Microsoft SQL Server. I have two tables

Cost Center - A list of all our production processes.

Scheduled Process - A list of jobs that are scheduled to go through each Cost Center

My table Cost Center looks as below

CostCenterCode  CostCenterDesc
------------------------------
123             Print
456             Stich
789             Fold
999             Ship

My table Process Schedule looks as below

JobNumber   StartDate   ScheduledHours  CostCenterCode
------------------------------------------------------
12345   2020-01-01      33               123
12345   2020-01-01      33               456
12345   2020-01-01      33               999

Now based on my above dataset, cost center 789 does not have anything scheduled. I want to write a query that will show what is scheduled for each cost center each day. Cost Center 789 does not have anything scheduled but it should still show that cost center with 0 hours.

Body:
You can try this using Aggregate Functions (Transact-SQL)
 and the SQL Server join.

create table CostCenter (CostCenterCode int, CostCenterDesc varchar(120))
insert into CostCenter Values(123, 'Print'), (456, 'Stich'), (789, 'Fold'), (999, 'Ship')

Create table ProcessSchedule (JobNumber int, StartDate Date, ScheduledHours int,
CostCenterCode int)
Insert into ProcessSchedule Values (12345, '2020-01-01', 33, 123),
(12345 , '2020-01-01', 33, 456), (12345, '2020-01-01', 33, 999)

;WITH cte
AS (
    SELECT CostCenter.CostCenterCode
        ,CostCenter.CostCenterDesc
        ,ProcessSchedule.StartDate
        ,ISNULL(ProcessSchedule.ScheduledHours, 0) AS ScheduledHours
    FROM CostCenter
    LEFT JOIN ProcessSchedule ON CostCenter.CostCenterCode = ProcessSchedule.CostCenterCode
    )
SELECT CostCenterCode
    ,CostCenterDesc
    ,StartDate
    ,SUM(ScheduledHours) AS TotalScheduledHours
FROM cte
GROUP BY CostCenterCode
    ,CostCenterDesc
    ,StartDate

Live Demo Here


问:
How to add headers in Java Websocket client
I am connecting to a websocket server in Java using javax.websocket classes.

```<code>import javax.websocket.DeploymentException;
import javax.websocket.Session;
import javax.websocket.WebSocketContainer;
import java.io.IOException;
import java.net.URI;

public class WSClient {
    private WebSocketContainer webSocketContainer;

    public void sendMessage(URI endpointURI, String message) throws IOException, DeploymentException {
        Session session = webSocketContainer.connectToServer(MyClientEndpoint.class, endpointURI);
        session.getAsyncRemote().sendText(message);
    }
}
</code>```

For the initial HTTP handshake I want to add extra HTTP Headers to the request on the Client side

Is this possible?

I know that this is possible on server side using ServerEndpointConfig.Configurator.modifyHandshake. Is there a similar solution on client side?

答:
```<code>Builder configBuilder = ClientEndpointConfig.Builder.create();
configBuilder.configurator(new Configurator() {
    @Override
    public void beforeRequest(Map<String, List<String>> headers) {
    headers.put("Cookie", Arrays.asList("JSESSIONID=" + sessionID));
    }
});
ClientEndpointConfig clientConfig = configBuilder.build();
webSocketContainer.connectToServer(MyClientEndpoint.class, clientConfig, new URI(uri));
</code>```

Body:
I am connecting to a websocket server in Java using javax.websocket classes.

import javax.websocket.DeploymentException;
import javax.websocket.Session;
import javax.websocket.WebSocketContainer;
import java.io.IOException;
import java.net.URI;

public class WSClient {
    private WebSocketContainer webSocketContainer;

    public void sendMessage(URI endpointURI, String message) throws IOException, DeploymentException {
        Session session = webSocketContainer.connectToServer(MyClientEndpoint.class, endpointURI);
        session.getAsyncRemote().sendText(message);
    }
}

For the initial HTTP handshake I want to add extra HTTP Headers to the request on the Client side

Is this possible?

I know that this is possible on server side using ServerEndpointConfig.Configurator.modifyHandshake. Is there a similar solution on client side?


问:
Getting a typeerror: cannot read property find of undefined
I have copied the code from another application, and that is working fine. but this one is giving me a Typeerror: cannot read property find of undefined when I am making the request to the database using the api.
here is my server.js

```<code>const express = require("express");
const app = express();
const bodyParser = require("body-parser");
const cors = require("cors");
const mongoose = require("mongoose");
const userRoutes = express.Router();
const PORT = 4000;

let { User } = require("./models/User");

app.use(cors());
app.use(bodyParser.json());

mongoose.connect("mongodb://127.0.0.1:27017/school", { useNewUrlParser: true });
const connection = mongoose.connection;

connection.once("open", function() {
  console.log("MongoDB database connection established successfully");
});

userRoutes.route("/").get(function(req, res) {
  User.find(function(err, users) {
    if (err) {
      console.log(err);
    } else {
      res.json(users);
    }
  });
});
app.use("/users", userRoutes);
app.listen(PORT, function() {
  console.log("Server is running on Port: " + PORT);
});
</code>```

here is my User Model:

```<code>const mongoose = require("mongoose");
const Schema = mongoose.Schema;

let User = new Schema({
  firstName: {
    type: String,
    required: "First name is required"
  },
  lastName: {
    type: String,
    required: "Last name is required"
  },
  emailAddress: {
    type: String,
    required: "Email address is required",
    match: [
      /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,
      "A valid email address is required"
    ]
  },
  password: {
    type: String,
    required: "Password is required"
  }
});

module.exports = mongoose.model("User", User);
</code>```

答:
Your problem is the wrong way of importing User Schema , you can fix it like so :

```<code>let User = require("./models/User");

</code>```

now your functions will work fine :)

Body:
I have copied the code from another application, and that is working fine. but this one is giving me a Typeerror: cannot read property find of undefined when I am making the request to the database using the api.
here is my server.js

const express = require("express");
const app = express();
const bodyParser = require("body-parser");
const cors = require("cors");
const mongoose = require("mongoose");
const userRoutes = express.Router();
const PORT = 4000;

let { User } = require("./models/User");

app.use(cors());
app.use(bodyParser.json());

mongoose.connect("mongodb://127.0.0.1:27017/school", { useNewUrlParser: true });
const connection = mongoose.connection;

connection.once("open", function() {
  console.log("MongoDB database connection established successfully");
});

userRoutes.route("/").get(function(req, res) {
  User.find(function(err, users) {
    if (err) {
      console.log(err);
    } else {
      res.json(users);
    }
  });
});
app.use("/users", userRoutes);
app.listen(PORT, function() {
  console.log("Server is running on Port: " + PORT);
});

here is my User Model:

const mongoose = require("mongoose");
const Schema = mongoose.Schema;

let User = new Schema({
  firstName: {
    type: String,
    required: "First name is required"
  },
  lastName: {
    type: String,
    required: "Last name is required"
  },
  emailAddress: {
    type: String,
    required: "Email address is required",
    match: [
      /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,
      "A valid email address is required"
    ]
  },
  password: {
    type: String,
    required: "Password is required"
  }
});

module.exports = mongoose.model("User", User);

Body:
Your problem is the wrong way of importing User Schema , you can fix it like so :

let User = require("./models/User");

now your functions will work fine :)


问:
How to get a Jest custom matcher working in typescript?
I regularly have unit tests where I need to compare two moment objects. I'd us moment's built-in function moment.isSame(moment) to compare them. However, this means my assertion will look like this:

expect(moment1.isSame(moment2)).toBeTrue();

I didn't quite like this, especially because the failure message will be less informative. Hence, I wanted to write a custom jest matcher "toBeSameMoment". The following code seems to compile at least:

```<code>import moment from "moment";

declare global {
  namespace jest {
    interface MomentMatchers extends Matchers<moment.Moment> {
      toBeSameMoment: (expected: moment.Moment) => CustomMatcherResult;
    }
  }
}

expect.extend({
  toBeSameMoment(received: moment.Moment, expected: moment.Moment): jest.CustomMatcherResult {
    const pass: boolean = received.isSame(expected);
    const message: () => string = () => pass ? "" : `Received moment (${received.toISOString()}) is not the same as expected (${expected.toISOString()})`;

    return {
      message,
      pass,
    };
  },
});
</code>```

However, I can't really get it to work in my unit test...
When I try the following test code:

```<code>import moment from "moment";
import "../jest-matchers/moment";

describe("Moment matcher", () => {

  test("should fail", () => {
    const moment1 = moment.utc();
    const moment2 = moment();

    expect(moment1).toBeSameMoment(moment2);
  });

});
</code>```

...then I get the following error:

```<code>error TS2339: Property 'toBeSameMoment' does not exist on type 'JestMatchersShape<Matchers<void, Moment>, Matchers<Promise<void>, Moment>>'.
</code>```

I don't quite get this error, though. For example, what is the void type this is referring to? I've tried googling about it, but didn't really find a good guide or so. I did take notice of this question: How to let know typescript compiler about jest custom matchers?, which seems to basically be a duplicate, but apparently not clear enough, yet.

I have jest types included in my tsconfig

答:
The other question and answer you linked to were correct, and you can also find a very succinct example for how to extend jest in this github comment on react-testing-library.

To implement their solution for your code, just change:

```<code>declare global {
  namespace jest {
    interface MomentMatchers extends Matchers<moment.Moment> {
      toBeSameMoment: (expected: moment.Moment) => CustomMatcherResult;
    }
  }
}
</code>```

To:

```<code>declare global {
  namespace jest {
    interface Matchers<R> {
      toBeSameMoment(expected: moment.Moment): CustomMatcherResult;
    }
  }
}
</code>```

Body:
I regularly have unit tests where I need to compare two moment objects. I'd us moment's built-in function moment.isSame(moment) to compare them. However, this means my assertion will look like this:

expect(moment1.isSame(moment2)).toBeTrue();

I didn't quite like this, especially because the failure message will be less informative. Hence, I wanted to write a custom jest matcher "toBeSameMoment". The following code seems to compile at least:

import moment from "moment";

declare global {
  namespace jest {
    interface MomentMatchers extends Matchers<moment.Moment> {
      toBeSameMoment: (expected: moment.Moment) => CustomMatcherResult;
    }
  }
}

expect.extend({
  toBeSameMoment(received: moment.Moment, expected: moment.Moment): jest.CustomMatcherResult {
    const pass: boolean = received.isSame(expected);
    const message: () => string = () => pass ? "" : `Received moment (${received.toISOString()}) is not the same as expected (${expected.toISOString()})`;

    return {
      message,
      pass,
    };
  },
});

However, I can't really get it to work in my unit test...
When I try the following test code:

import moment from "moment";
import "../jest-matchers/moment";

describe("Moment matcher", () => {

  test("should fail", () => {
    const moment1 = moment.utc();
    const moment2 = moment();

    expect(moment1).toBeSameMoment(moment2);
  });

});

...then I get the following error:

error TS2339: Property 'toBeSameMoment' does not exist on type 'JestMatchersShape<Matchers<void, Moment>, Matchers<Promise<void>, Moment>>'.

I don't quite get this error, though. For example, what is the void type this is referring to? I've tried googling about it, but didn't really find a good guide or so. I did take notice of this question: How to let know typescript compiler about jest custom matchers?, which seems to basically be a duplicate, but apparently not clear enough, yet.

I have jest types included in my tsconfig

Body:
The other question and answer you linked to were correct, and you can also find a very succinct example for how to extend jest in this github comment on react-testing-library.

To implement their solution for your code, just change:

declare global {
  namespace jest {
    interface MomentMatchers extends Matchers<moment.Moment> {
      toBeSameMoment: (expected: moment.Moment) => CustomMatcherResult;
    }
  }
}

To:

declare global {
  namespace jest {
    interface Matchers<R> {
      toBeSameMoment(expected: moment.Moment): CustomMatcherResult;
    }
  }
}


问:
Count numbers that are lower by constant from current number
Imagine that I have a list of numbers (i.e. numbers column in data.table/data.frame).

```<code>1
5
5
10
11
12
</code>```

for each number in a list a want to count how many unique numbers are there which are lower than that particular number + 5.

The explanation for upper case, first number = 1, search range is 1+5 = 6, so three numbers are in range, less than or equal to: c(1,5,5), and then count unique is 2.
This is all by assuming we've got the additional condition, that the number must not only be lower than current_number + 5, but also its index in the list must be >= that of current_number.

The result in this case would be:

```<code>2
2
2
3
2
1
</code>```

Note: Is there a fast solution for huge dataset, in data.frame or data.table? My dataset is rather huge, 10+M rows.

答:
The fastest way I can think of in base R (works if x is sorted):

```<code>findInterval(x + 5, unique(x)) - cumsum(!duplicated(x)) + 1L
#[1] 2 2 2 3 2 1
</code>```

edit: no problem with the sorting because with data.table, sorting integers is trivial:

```<code>nr <- 1e7
nn <- nr/2
set.seed(0L)
DT <- data.table(X=sample(nn, nr, TRUE))
#DT <- data.table(X=c(1,5,5,10,11,12))

system.time(
    DT[order(X),
        COUNT := findInterval(X + 5L, unique(X)) - cumsum(!duplicated(X)) + 1L
    ]
)
#   user  system elapsed
#   1.73    0.17    1.53
</code>```

2s for 10million rows.

Body:
Imagine that I have a list of numbers (i.e. numbers column in data.table/data.frame).

1
5
5
10
11
12

for each number in a list a want to count how many unique numbers are there which are lower than that particular number + 5.

The explanation for upper case, first number = 1, search range is 1+5 = 6, so three numbers are in range, less than or equal to: c(1,5,5), and then count unique is 2.
This is all by assuming we've got the additional condition, that the number must not only be lower than current_number + 5, but also its index in the list must be >= that of current_number.

The result in this case would be:

2
2
2
3
2
1

Note: Is there a fast solution for huge dataset, in data.frame or data.table? My dataset is rather huge, 10+M rows.

Body:
The fastest way I can think of in base R (works if x is sorted):

findInterval(x + 5, unique(x)) - cumsum(!duplicated(x)) + 1L
#[1] 2 2 2 3 2 1

edit: no problem with the sorting because with data.table, sorting integers is trivial:

nr <- 1e7
nn <- nr/2
set.seed(0L)
DT <- data.table(X=sample(nn, nr, TRUE))
#DT <- data.table(X=c(1,5,5,10,11,12))

system.time(
    DT[order(X),
        COUNT := findInterval(X + 5L, unique(X)) - cumsum(!duplicated(X)) + 1L
    ]
)
#   user  system elapsed
#   1.73    0.17    1.53

2s for 10million rows.


问:
XAML markup error when binding List<string> to a ComboBox ItemSource in a WPF
I'm trying to implement MVVM in a WPF app but am hitting a weird issue where List<string> is apparently being treated as a string and breaks the XAML designer.

from the XAML:

<ComboBox Grid.Row="0"
          Grid.Column="1"
          Name="ServerListComboBox"
          HorizontalAlignment="Stretch"
          VerticalAlignment="Top"
          Margin="10"
          Padding="5"
          ItemsSource="Bind ServerList"/>
```

<p>from the ViewModel:</p>

```public List<string> ServerList
{
    get { return model.ServerList; }
    set
    {
        model.ServerList = value;
        OnPropertyChange(nameof(ServerList));
    }
}
```

<p>from the model:</p>

``` public List<string> ServerList { get; set; }
```

The designer says Invalid Markup and produces this error:

Error XDG0028 The TypeConverter for "IEnumerable" does not support
  converting from a string.

Clearly it's a List<string> not a string and compilation is fine, but I can't use the XAML Designer anymore. Is there something simple I'm overlooking to make the designer work again? Thanks for any advice, tips, or help

答:
Change:

```<code>ItemsSource="Bind ServerList"
</code>```

to:

```<code>ItemsSource="{Binding ServerList}"
</code>```

Body:
I'm trying to implement MVVM in a WPF app but am hitting a weird issue where List<string> is apparently being treated as a string and breaks the XAML designer.

from the XAML:

<ComboBox Grid.Row="0"
          Grid.Column="1"
          Name="ServerListComboBox"
          HorizontalAlignment="Stretch"
          VerticalAlignment="Top"
          Margin="10"
          Padding="5"
          ItemsSource="Bind ServerList"/>

from the ViewModel:

public List<string> ServerList
{
    get { return model.ServerList; }
    set
    {
        model.ServerList = value;
        OnPropertyChange(nameof(ServerList));
    }
}

from the model:

 public List<string> ServerList { get; set; }

The designer says Invalid Markup and produces this error:

Error XDG0028 The TypeConverter for "IEnumerable" does not support
  converting from a string.

Clearly it's a List<string> not a string and compilation is fine, but I can't use the XAML Designer anymore. Is there something simple I'm overlooking to make the designer work again? Thanks for any advice, tips, or help

Body:
Change:

ItemsSource="Bind ServerList"

to:

ItemsSource="{Binding ServerList}"


问:
How to merge two lists based on object indices - keeping attributes?
I want to merge two lists keeping the index of each object:

```<code>mylist<-list(1,NULL,2)
otherlist<-list(NULL,3,NULL,4,5,6)

# Desired

list(1,3,2,4,5,6)

# my try:

suppressWarnings(mapply(c, mylist, otherlist) )
</code>```

Answer should be universal

EDIT: In order to avoid proliferation of similar questions. I decided to request here also the possibility of keeping attributes (preferably with base).

```<code>mylist<-list(1,NULL,2)
attr(mylist[[1]],"at")<-"a"
attr(mylist[[3]],"at")<-"c"

otherlist<-list(NULL,3,NULL,4,5,6)

attr(otherlist[[2]],"at")<-"b"
attr(otherlist[[4]],"at")<-"d"
attr(otherlist[[5]],"at")<-"e"
attr(otherlist[[6]],"at")<-"f"
</code>```

Body:
I want to merge two lists keeping the index of each object:

mylist<-list(1,NULL,2)
otherlist<-list(NULL,3,NULL,4,5,6)

# Desired

list(1,3,2,4,5,6)

# my try:

suppressWarnings(mapply(c, mylist, otherlist) )

Answer should be universal

EDIT: In order to avoid proliferation of similar questions. I decided to request here also the possibility of keeping attributes (preferably with base).

mylist<-list(1,NULL,2)
attr(mylist[[1]],"at")<-"a"
attr(mylist[[3]],"at")<-"c"

otherlist<-list(NULL,3,NULL,4,5,6)

attr(otherlist[[2]],"at")<-"b"
attr(otherlist[[4]],"at")<-"d"
attr(otherlist[[5]],"at")<-"e"
attr(otherlist[[6]],"at")<-"f"

Body:
foo <- function(l1, l2) {
  out <- vector(mode = "list", length = max(length(l1), length(l2)))
  out[seq_along(l1)] <- l1
  out[!lengths(out)] <- l2[!lengths(out)]
  out
}

foo(mylist, otherlist2)

# [[1]]
# [1] 1
# attr(,"at")
# [1] "a"
#
# [[2]]
# [1] 3
# attr(,"at")
# [1] "b"
#
# [[3]]
# [1] 2
# attr(,"at")
# [1] "c"
#
# [[4]]
# [1] 5
# attr(,"at")
# [1] "e"
#
# [[5]]
# [1] 6
# attr(,"at")
# [1] "f"