问:
C# WPF - Tasks vs Multithreading, and updating UI components from them
So basically I'm using C# to write a port scanning WPF application, that will scan over a thousand combinations of ports and IPs (x.x.x.x:xx). As a result, I have to split this process up into multiple threads to quicken the process and avoid making the UI freeze. Shown below is my code for the MainWindow:

```<code>namespace PortScannerTool
{
    public partial class MainWindow : Window
    {

        public MainWindow()
        {
            InitializeComponent();
            tb_portstatus.Text = "Click the button to query ports";
            dns_info.Text = tb_portstatus.Text;
        }

        private void Btn1_Click(object sender, RoutedEventArgs e)
        {

            CmdExec cmdobj = new CmdExec("127.0.0.0","8080");
            Thread query_status = new Thread(cmdobj.Runcmd);
            query_status.Start();
            tb_portstatus.Text = "Done!";
        }
    }
}
</code>```

```<code>namespace PortQueryApp
{
    class CmdExec
    {

        string command;
        public string dnsText;
        public string querystatusText;

        public CmdExec(string ip, string port)
        {
           this.command = $"-n {ip} -o {port}";
        }

        public void Runcmd()
        {
            Process proc = new Process();
            proc.StartInfo.FileName = "PortQry.exe";
            proc.StartInfo.Arguments = this.command;
            proc.StartInfo.CreateNoWindow = true;
            proc.StartInfo.UseShellExecute = false;
            proc.StartInfo.RedirectStandardOutput = true;
            proc.Start();
            string query_output = proc.StandardOutput.ReadToEnd();
            proc.WaitForExit();

            string resolve_pass = "Name resolved";
            string resolve_fail = "Failed to resolve IP address to name";

            if (query_output.Contains(resolve_pass))
            {
                this.dnsText = "Resolved!";
            }
            if (query_output.Contains(resolve_fail))
            {
                this.dnsText = "Resolve Failed!";
            }

            this.querystatusText = "Done!";

        }
    }
}
</code>```

dns_info and tb_portstatus are XAML Textboxes. CmdExec.Rumcmd is the method that does the actual port scanning itself. If you look at the CmdExec class, PortQry.exe is the microsoft port query tool.

So I want to get the cmdobj.Runcmd method to update the UI once it's done running. But I don't know how to do so, I've Googled this extensively, and I'm getting some people suggesting using delegates, Tasks and BackgroundWorkers, not sure which method would be best for my case.

Could anyone give some suggestions or point me to any guides? That'd be awesome! Thanks!

Edit: Most examples have their Multithreaded method within the same class as well. I'm not sure if this is required, but should I use:

```<code> class CmdExec : MainWindow
{
   //Do stuff
}
</code>```

instead?

答:
I think BackgroundWorker is better choice. In WPF, you are not allowed to make changes to the UI from another thread. So, simply moving code in the event handler method causes a problem when reflecting process result on UI (e.g. showing message "done").

It is still the same in BackgroundWorker.DoWork, but BackgroundWorker's ReportProgress and RunWorkerCompleted can help you to have your code simple. Have a look at the answer here. I think you can get the point easily.

Body:
So basically I'm using C# to write a port scanning WPF application, that will scan over a thousand combinations of ports and IPs (x.x.x.x:xx). As a result, I have to split this process up into multiple threads to quicken the process and avoid making the UI freeze. Shown below is my code for the MainWindow:

namespace PortScannerTool
{
    public partial class MainWindow : Window
    {

        public MainWindow()
        {
            InitializeComponent();
            tb_portstatus.Text = "Click the button to query ports";
            dns_info.Text = tb_portstatus.Text;
        }

        private void Btn1_Click(object sender, RoutedEventArgs e)
        {

            CmdExec cmdobj = new CmdExec("127.0.0.0","8080");
            Thread query_status = new Thread(cmdobj.Runcmd);
            query_status.Start();
            tb_portstatus.Text = "Done!";
        }
    }
}

namespace PortQueryApp
{
    class CmdExec
    {

        string command;
        public string dnsText;
        public string querystatusText;

        public CmdExec(string ip, string port)
        {
           this.command = $"-n {ip} -o {port}";
        }

        public void Runcmd()
        {
            Process proc = new Process();
            proc.StartInfo.FileName = "PortQry.exe";
            proc.StartInfo.Arguments = this.command;
            proc.StartInfo.CreateNoWindow = true;
            proc.StartInfo.UseShellExecute = false;
            proc.StartInfo.RedirectStandardOutput = true;
            proc.Start();
            string query_output = proc.StandardOutput.ReadToEnd();
            proc.WaitForExit();

            string resolve_pass = "Name resolved";
            string resolve_fail = "Failed to resolve IP address to name";

            if (query_output.Contains(resolve_pass))
            {
                this.dnsText = "Resolved!";
            }
            if (query_output.Contains(resolve_fail))
            {
                this.dnsText = "Resolve Failed!";
            }

            this.querystatusText = "Done!";

        }
    }
}

dns_info and tb_portstatus are XAML Textboxes. CmdExec.Rumcmd is the method that does the actual port scanning itself. If you look at the CmdExec class, PortQry.exe is the microsoft port query tool.

So I want to get the cmdobj.Runcmd method to update the UI once it's done running. But I don't know how to do so, I've Googled this extensively, and I'm getting some people suggesting using delegates, Tasks and BackgroundWorkers, not sure which method would be best for my case.

Could anyone give some suggestions or point me to any guides? That'd be awesome! Thanks!

Edit: Most examples have their Multithreaded method within the same class as well. I'm not sure if this is required, but should I use:

 class CmdExec : MainWindow
{
   //Do stuff
}

instead?


来源: stackexchange

问:
How to hide the paste option from menu in UITextField in Swift 3.0?
I tried with every answer posted for this similar question, but it is not working in Swift 3.

```<code>  override func canPerformAction(action: Selector, withSender sender: AnyObject?) -> Bool {
   if action == #selector(paste(_:)) {
        return false
    }
   return super.canPerformAction(action, withSender: sender)
}
</code>```

Thanks

答:
In case anyone looking for swift 4.2</p>

```<code> override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
        OperationQueue.main.addOperation {
            UIMenuController.shared.setMenuVisible(false, animated: false)
        }

        return super.canPerformAction(action, withSender: sender)
    }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I tried with every answer posted for this similar question, but it is not working in Swift 3.

  override func canPerformAction(action: Selector, withSender sender: AnyObject?) -> Bool {
   if action == #selector(paste(_:)) {
        return false
    }
   return super.canPerformAction(action, withSender: sender)
}

Thanks

Body:
In case anyone looking for swift 4.2

 override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
        OperationQueue.main.addOperation {
            UIMenuController.shared.setMenuVisible(false, animated: false)
        }

        return super.canPerformAction(action, withSender: sender)
    }


问:
For statement and range function with indexes
For my assignment, I have to use a for loop and a range function for a program to print out the following, each on a separate line so it looks like a list.

```<code>Hello 0
Hello 1
Hello 3
Hello 6
Hello 10
</code>```

I know that you have to create two variables, one that keeps track of the number of indexes and another that prints that, because the question states:
 (the number corresponds to the accumulated summation over the successive indexes). My problem is creating the function that does so keeping track of the indexes. Any guidance would be great. Thanks again in advance.

```<code>count_indexes = ?
print_statement = count_indexes + 1
for i in range(0,11,count_indexes):
    print("Hello",print_statement)
</code>```

The expected result should print hello 5 times, each on different lines, each with different numbers on them, and the numbers should be 0,1,3,6,10.

答:
The numbers are the triangle numbers. There is a closed form for calculating them so you don't need the keep track of an extra variable.</p>

```<code>>>> for i in range(5):
...     print('Hello', (i+1)*i//2)
Hello 0
Hello 1
Hello 3
Hello 6
Hello 10
</code>```

Body:
For my assignment, I have to use a for loop and a range function for a program to print out the following, each on a separate line so it looks like a list.

Hello 0
Hello 1
Hello 3
Hello 6
Hello 10

I know that you have to create two variables, one that keeps track of the number of indexes and another that prints that, because the question states:
 (the number corresponds to the accumulated summation over the successive indexes). My problem is creating the function that does so keeping track of the indexes. Any guidance would be great. Thanks again in advance.

count_indexes = ?
print_statement = count_indexes + 1
for i in range(0,11,count_indexes):
    print("Hello",print_statement)

The expected result should print hello 5 times, each on different lines, each with different numbers on them, and the numbers should be 0,1,3,6,10.

Body:
The numbers are the triangle numbers. There is a closed form for calculating them so you don't need the keep track of an extra variable.

>>> for i in range(5):
...     print('Hello', (i+1)*i//2)
Hello 0
Hello 1
Hello 3
Hello 6
Hello 10


问:
Is there a better way to write a Regex to match the case,
I'm trying to build a Regex which will discard the string if matched.

Case study: Discard the string if it starts with a literal square brackets []

I've tried reading multiple articles on the web for solving the problem, and made a Regex that actually works for me

I've the following paragraph:

```<code>[Hello] How are you
Doing
 Hope you have a nice day!
[goodbye] cya
Take care
</code>```

The regex I'm using is /^(?!\[.?\])/

The result is as expected, I wanna know is there a better way to match it ?

答:
The  ^[^\[.?\]] pattern is a wrong pattern here because the sequence of patterns is enclosed in a character class. ^[^\[.?\]] matches any char but [, ., ?, ] at the start of a string. You need to match any line that starts with a sequence of chars, [, then any number of chars up to a ].

To match a line in Ruby that does not start with [...] substring you may use

```<code>^(?!\[[^\]\[]*]).*
^(?!\[.*?]).*
</code>```

See the Rubular demo and the latter regex graph:

Details

^ - start of a line

(?!\[.*?]) - a negative lookahead that fails the match if, immediately to the right there is [, any 0+ chars other than line break chars as few as possilble and then ] (note [^\]\[]* matches 0+ chars other than [ and ] and may be preferable if there cannot be any [ and ] between the [...])

.* - any 0+ chars other than line break chars.

Body:
I'm trying to build a Regex which will discard the string if matched.

Case study: Discard the string if it starts with a literal square brackets []

I've tried reading multiple articles on the web for solving the problem, and made a Regex that actually works for me

I've the following paragraph:

[Hello] How are you
Doing
 Hope you have a nice day!
[goodbye] cya
Take care

The regex I'm using is /^(?!\[.?\])/

The result is as expected, I wanna know is there a better way to match it ?

Body:
The  ^[^\[.?\]] pattern is a wrong pattern here because the sequence of patterns is enclosed in a character class. ^[^\[.?\]] matches any char but [, ., ?, ] at the start of a string. You need to match any line that starts with a sequence of chars, [, then any number of chars up to a ].

To match a line in Ruby that does not start with [...] substring you may use

^(?!\[[^\]\[]*]).*
^(?!\[.*?]).*

See the Rubular demo and the latter regex graph:

Details

^ - start of a line

(?!\[.*?]) - a negative lookahead that fails the match if, immediately to the right there is [, any 0+ chars other than line break chars as few as possilble and then ] (note [^\]\[]* matches 0+ chars other than [ and ] and may be preferable if there cannot be any [ and ] between the [...])

.* - any 0+ chars other than line break chars.


问:
http-server -p 8082 showing ERR_INVALID_REDIRECT
I am working on angular project . I want to apply PWA (Progressive web app) to my application. Here are the commands I followed.

```<code>ng build --prod
cd dist/appname
http-server -p 8082
</code>```

when I open the 127.0.0.1:8082/#/ or localhost:8082/#/ it is showing following error

This page isn’t working localhost sent an invalid response.
ERR_INVALID_REDIRECT

How to fix it?

答:
Had the same problem a week or so ago. I thought i did something wrong and reinstalled http-server, tried different ports and so on. Nothing worked.

I ended up finding this package https://www.npmjs.com/package/serve that's similar to http-server.

It solved the problem for me, i think there is some bug on http-server latest release or on pwa / service-worker.

Hope it helps.

Body:
I am working on angular project . I want to apply PWA (Progressive web app) to my application. Here are the commands I followed.

ng build --prod
cd dist/appname
http-server -p 8082

when I open the 127.0.0.1:8082/#/ or localhost:8082/#/ it is showing following error

This page isn’t working localhost sent an invalid response.
ERR_INVALID_REDIRECT

How to fix it?


问:
Angular 2 - how to display the array object inside an array of objects
This is my example of json file

```<code>{
    "id": 5,
    "url": "http://localhost:8000/api/v1/users/5/",
    "username": "Najmuddin",
    "email": "",
    "groups": [
      {
        "id": 1,
        "url": "http://localhost:8000/api/v1/groups/1/",
        "name": "KETUA UNIT SEKSYEN",
        "permissions": [
          "Can add level",
          "Can change level",
          "Can delete level"
        ]
      }
    ]
  },
</code>```

and this is my code

```<code>public getUser(){
  this.jobService.getUsers().subscribe(
    user => {
      for (let i = 0; i < user.length; i++) {
        this.user = user;
        let username = user[i].username; --> i can get id,url,username,...
        let group = user[i].groups; --> i only get the [object] but i want
         to get the id, url, and name instead
      }
    },
  );
}
</code>```

I only can get and display object for User and not be able to get groups id, url and name and permission[object]`. Is it something that i missing?

答:
my json data is this </p>

<pre class="lang-js prettyprint-override"><code> "orders": [
        {
            "totalPrice": 1200,
            "_id": "5cf0b8fd245b7904440aa4b7",
            "products": [
                {
                    "quantity": 1,
                    "_id": "5cf0b8fd245b7904440aa4b8",
                    "product": {
                        "reviews": [
                            "5cf0b8a8245b7904440aa4b6"
                        ],
                        "_id": "5ce83a9c16bec823d4bddff9",
                        "crated": "2019-05-24T18:40:28.253Z",
                        "owner": "5cc2f1c195d5a13018080651",
                        "category": "5cc62714304f84437059eada",
                        "title": "book",
                        "price": 12,
                        "description": "aaaaaaaa",
                        "image": "uploads\\1558723228216-direct-to-other-schema.png",
                        "__v": 1,
                        "averageRating": null,
                        "id": "5ce83a9c16bec823d4bddff9"
                    }
                }
            ],
</code>```

<p>and in an angular template, I get data like this</p>

<pre class="lang-html prettyprint-override"><code><div *ngFor="let order of orders" class="order">
  <div *ngFor="let product of order.products" class="orders">
    <div class="row">
      <div class="col-4 col-md-2">

          <img src="http://localhost:3030/{{ product.product.image }}" alt="image" class="img-fluid img-thumbnail">

      </div>
      <div class="col-5 col-md-8">
        <h5>
          {{ product.product.title }}
          <p class="m-0">
            <small class="text-muted">{{ product.product.category }}</small>
          </p>
        </h5>
      </div>
      <div class="col-2">
        <h6 class="font-weight-bold text-danger">{{ order.totalPrice | currency }}</h6>

      </div>
    </div>
  </div>
  <hr>
</div>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
This is my example of json file

{
    "id": 5,
    "url": "http://localhost:8000/api/v1/users/5/",
    "username": "Najmuddin",
    "email": "",
    "groups": [
      {
        "id": 1,
        "url": "http://localhost:8000/api/v1/groups/1/",
        "name": "KETUA UNIT SEKSYEN",
        "permissions": [
          "Can add level",
          "Can change level",
          "Can delete level"
        ]
      }
    ]
  },

and this is my code

public getUser(){
  this.jobService.getUsers().subscribe(
    user => {
      for (let i = 0; i < user.length; i++) {
        this.user = user;
        let username = user[i].username; --> i can get id,url,username,...
        let group = user[i].groups; --> i only get the [object] but i want
         to get the id, url, and name instead
      }
    },
  );
}

I only can get and display object for User and not be able to get groups id, url and name and permission[object]`. Is it something that i missing?

Body:
my json data is this

 "orders": [
        {
            "totalPrice": 1200,
            "_id": "5cf0b8fd245b7904440aa4b7",
            "products": [
                {
                    "quantity": 1,
                    "_id": "5cf0b8fd245b7904440aa4b8",
                    "product": {
                        "reviews": [
                            "5cf0b8a8245b7904440aa4b6"
                        ],
                        "_id": "5ce83a9c16bec823d4bddff9",
                        "crated": "2019-05-24T18:40:28.253Z",
                        "owner": "5cc2f1c195d5a13018080651",
                        "category": "5cc62714304f84437059eada",
                        "title": "book",
                        "price": 12,
                        "description": "aaaaaaaa",
                        "image": "uploads\\1558723228216-direct-to-other-schema.png",
                        "__v": 1,
                        "averageRating": null,
                        "id": "5ce83a9c16bec823d4bddff9"
                    }
                }
            ],

and in an angular template, I get data like this

<div *ngFor="let order of orders" class="order">
  <div *ngFor="let product of order.products" class="orders">
    <div class="row">
      <div class="col-4 col-md-2">
        <a routerLink="/order/{{ order.id }}">
          <img src="http://localhost:3030/{{ product.product.image }}" alt="image" class="img-fluid img-thumbnail">
        </a>
      </div>
      <div class="col-5 col-md-8">
        <h5>
          <a routerLink="/orders/{{ order.id }}">{{ product.product.title }}</a>
          <p class="m-0">
            <small class="text-muted">{{ product.product.category }}</small>
          </p>
        </h5>
      </div>
      <div class="col-2">
        <h6 class="font-weight-bold text-danger">{{ order.totalPrice | currency }}</h6>

      </div>
    </div>
  </div>
  <hr>
</div>


问:
MSIL: Why does Array initializer use dup
I'm learning MSIL recently, and got some confusing about array:
Below 2 method:

```<code>private static void FormatTest3()
{
    string s = string.Format("{0}{1}{2}", 1, 2,3);
}

private static void FormatTest4()
{
    string s = string.Format("{0}{1}{2}{3}", 1, 2,3,4);
    /*
    equal to
    object[] obj = new object[4];
    obj[0] = 1;
    obj[1] = 2;
    obj[2] = 3;
    obj[3] = 4;
    string text = string.Format("{0}{1}{2}{3}", obj);
    */
}
</code>```

And here is the IL:

```<code>.class private auto ansi '<Module>'
{
} // end of class <Module>

.class private auto ansi beforefieldinit Program
    extends [System.Private.CoreLib]System.Object
{
    // Methods
    .method private hidebysig static
        void FormatTest3 () cil managed
    {
        // Method begins at RVA 0x2050
        // Code size 31 (0x1f)
        .maxstack 4
        .locals init (
            [0] string
        )

        IL_0000: nop
        IL_0001: ldstr "{0}{1}{2}"
        IL_0006: ldc.i4.1
        IL_0007: box [System.Private.CoreLib]System.Int32
        IL_000c: ldc.i4.2
        IL_000d: box [System.Private.CoreLib]System.Int32
        IL_0012: ldc.i4.3
        IL_0013: box [System.Private.CoreLib]System.Int32
        IL_0018: call string [System.Private.CoreLib]System.String::Format(string, object, object, object)
        IL_001d: stloc.0
        IL_001e: ret
    } // end of method Program::FormatTest3

    .method private hidebysig static
        void FormatTest4 () cil managed
    {
        // Method begins at RVA 0x207c
        // Code size 55 (0x37)
        .maxstack 5
        .locals init (
            [0] string
        )

        IL_0000: nop
        IL_0001: ldstr "{0}{1}{2}{3}"
        IL_0006: ldc.i4.4
        IL_0007: newarr [System.Private.CoreLib]System.Object
        IL_000c: dup
        IL_000d: ldc.i4.0
        IL_000e: ldc.i4.1
        IL_000f: box [System.Private.CoreLib]System.Int32
        IL_0014: stelem.ref
        IL_0015: dup
        IL_0016: ldc.i4.1
        IL_0017: ldc.i4.2
        IL_0018: box [System.Private.CoreLib]System.Int32
        IL_001d: stelem.ref
        IL_001e: dup
        IL_001f: ldc.i4.2
        IL_0020: ldc.i4.3
        IL_0021: box [System.Private.CoreLib]System.Int32
        IL_0026: stelem.ref
        IL_0027: dup
        IL_0028: ldc.i4.3
        IL_0029: ldc.i4.4
        IL_002a: box [System.Private.CoreLib]System.Int32
        IL_002f: stelem.ref
        IL_0030: call string [System.Private.CoreLib]System.String::Format(string, object[])
        IL_0035: stloc.0
        IL_0036: ret
    } // end of method Program::FormatTest4

    .method public hidebysig specialname rtspecialname
        instance void .ctor () cil managed
    {
        // Method begins at RVA 0x20bf
        // Code size 8 (0x8)
        .maxstack 8

        IL_0000: ldarg.0
        IL_0001: call instance void [System.Private.CoreLib]System.Object::.ctor()
        IL_0006: nop
        IL_0007: ret
    } // end of method Program::.ctor

} // end of class Program
</code>```

My questions is:

Why string.Format() with 4 or more parameter use arrays?

Why FormatTest4()'s MSIL use dup (I know what dup do)？

答:
That's a performance optimization for the most common cases. By having separate overloads for common numbers of parameters they don't have to create the params array argument, thus saving an allocation (although may still need boxing, but that's cheaper than an array). Theoretically the overloads for 0, 1, 2, and 3 parameters don't need to exist, as the method that takes a params object[] can handle all of them too. It's just more expensive.

dup duplicates the current item on the stack. stelem.ref takes three items from the stack, the array, the index, and the value for that array index, and stores the value at the index in the array. That means that the array reference is no longer on the stack afterwards. Thus the dup. We want to retain that array reference on top of the stack since we need to pass it to the method being called, so we create an array, duplicate it, push the index and first item, use stelem.ref to store the item in the array, and still have that array reference, which otherwise would be gone.

There are alternative ways to do this. If you take the code you've copied from the decompiled C# you end up with different IL where the array reference is taken from a local variable each time:

```<code>IL_0036: ldc.i4.4
IL_0037: newarr [System.Private.CoreLib]System.Object
IL_003c: stloc.1
IL_003d: ldloc.1
IL_003e: ldc.i4.0
IL_003f: ldc.i4.1
IL_0040: box [System.Private.CoreLib]System.Int32
IL_0045: stelem.ref
IL_0046: ldloc.1
IL_0047: ldc.i4.1
IL_0048: ldc.i4.2
IL_0049: box [System.Private.CoreLib]System.Int32
IL_004e: stelem.ref
</code>```

I would believe that to be less efficient than dup, but perhaps the JIT doesn't really care either way. The real decompiled C# code would actually be something like this, though:

```<code>string text = string.Format("{0}{1}{2}{3}", new object[] { 1, 2, 3, 4 });
</code>```

which results in the same IL as

```<code>string text = string.Format("{0}{1}{2}{3}", 1, 2, 3, 4);
</code>```

Body:
I'm learning MSIL recently, and got some confusing about array:
Below 2 method:

private static void FormatTest3()
{
    string s = string.Format("{0}{1}{2}", 1, 2,3);
}

private static void FormatTest4()
{
    string s = string.Format("{0}{1}{2}{3}", 1, 2,3,4);
    /*
    equal to
    object[] obj = new object[4];
    obj[0] = 1;
    obj[1] = 2;
    obj[2] = 3;
    obj[3] = 4;
    string text = string.Format("{0}{1}{2}{3}", obj);
    */
}

And here is the IL:

.class private auto ansi '<Module>'
{
} // end of class <Module>

.class private auto ansi beforefieldinit Program
    extends [System.Private.CoreLib]System.Object
{
    // Methods
    .method private hidebysig static
        void FormatTest3 () cil managed
    {
        // Method begins at RVA 0x2050
        // Code size 31 (0x1f)
        .maxstack 4
        .locals init (
            [0] string
        )

        IL_0000: nop
        IL_0001: ldstr "{0}{1}{2}"
        IL_0006: ldc.i4.1
        IL_0007: box [System.Private.CoreLib]System.Int32
        IL_000c: ldc.i4.2
        IL_000d: box [System.Private.CoreLib]System.Int32
        IL_0012: ldc.i4.3
        IL_0013: box [System.Private.CoreLib]System.Int32
        IL_0018: call string [System.Private.CoreLib]System.String::Format(string, object, object, object)
        IL_001d: stloc.0
        IL_001e: ret
    } // end of method Program::FormatTest3

    .method private hidebysig static
        void FormatTest4 () cil managed
    {
        // Method begins at RVA 0x207c
        // Code size 55 (0x37)
        .maxstack 5
        .locals init (
            [0] string
        )

        IL_0000: nop
        IL_0001: ldstr "{0}{1}{2}{3}"
        IL_0006: ldc.i4.4
        IL_0007: newarr [System.Private.CoreLib]System.Object
        IL_000c: dup
        IL_000d: ldc.i4.0
        IL_000e: ldc.i4.1
        IL_000f: box [System.Private.CoreLib]System.Int32
        IL_0014: stelem.ref
        IL_0015: dup
        IL_0016: ldc.i4.1
        IL_0017: ldc.i4.2
        IL_0018: box [System.Private.CoreLib]System.Int32
        IL_001d: stelem.ref
        IL_001e: dup
        IL_001f: ldc.i4.2
        IL_0020: ldc.i4.3
        IL_0021: box [System.Private.CoreLib]System.Int32
        IL_0026: stelem.ref
        IL_0027: dup
        IL_0028: ldc.i4.3
        IL_0029: ldc.i4.4
        IL_002a: box [System.Private.CoreLib]System.Int32
        IL_002f: stelem.ref
        IL_0030: call string [System.Private.CoreLib]System.String::Format(string, object[])
        IL_0035: stloc.0
        IL_0036: ret
    } // end of method Program::FormatTest4

    .method public hidebysig specialname rtspecialname
        instance void .ctor () cil managed
    {
        // Method begins at RVA 0x20bf
        // Code size 8 (0x8)
        .maxstack 8

        IL_0000: ldarg.0
        IL_0001: call instance void [System.Private.CoreLib]System.Object::.ctor()
        IL_0006: nop
        IL_0007: ret
    } // end of method Program::.ctor

} // end of class Program

My questions is:

Why string.Format() with 4 or more parameter use arrays?

Why FormatTest4()'s MSIL use dup (I know what dup do)？

Body:
That's a performance optimization for the most common cases. By having separate overloads for common numbers of parameters they don't have to create the params array argument, thus saving an allocation (although may still need boxing, but that's cheaper than an array). Theoretically the overloads for 0, 1, 2, and 3 parameters don't need to exist, as the method that takes a params object[] can handle all of them too. It's just more expensive.

dup duplicates the current item on the stack. stelem.ref takes three items from the stack, the array, the index, and the value for that array index, and stores the value at the index in the array. That means that the array reference is no longer on the stack afterwards. Thus the dup. We want to retain that array reference on top of the stack since we need to pass it to the method being called, so we create an array, duplicate it, push the index and first item, use stelem.ref to store the item in the array, and still have that array reference, which otherwise would be gone.

There are alternative ways to do this. If you take the code you've copied from the decompiled C# you end up with different IL where the array reference is taken from a local variable each time:

IL_0036: ldc.i4.4
IL_0037: newarr [System.Private.CoreLib]System.Object
IL_003c: stloc.1
IL_003d: ldloc.1
IL_003e: ldc.i4.0
IL_003f: ldc.i4.1
IL_0040: box [System.Private.CoreLib]System.Int32
IL_0045: stelem.ref
IL_0046: ldloc.1
IL_0047: ldc.i4.1
IL_0048: ldc.i4.2
IL_0049: box [System.Private.CoreLib]System.Int32
IL_004e: stelem.ref

I would believe that to be less efficient than dup, but perhaps the JIT doesn't really care either way. The real decompiled C# code would actually be something like this, though:

string text = string.Format("{0}{1}{2}{3}", new object[] { 1, 2, 3, 4 });

which results in the same IL as

string text = string.Format("{0}{1}{2}{3}", 1, 2, 3, 4);


问:
show full version of thumbnail on rollover with jQuery?
WordPress creates a new image at a reduced size when I specify the dimensions I want it to display, so when I choose 300 x 230 it produces this file as the image source:

http://example.com/myphoto-300x230.jpg

from this full-size version:

http://example.com/myphoto.jpg

I'm using a plugin to expand the 300x230 on rollover. The expanded view is the 300x230 blown up, which is blurry. Is there a way to show the full-size version on rollover, so that it's myphoto-300x230.jpg by default but myphoto.jpg on rollover? Would I need to regex the filename to get rid of the numbers for the dimensions?

答:
A regex for this would look something like:

s/-\d+x\d+././

Assuming your img element has the ID fixme...

```<code>var src = $("#fixme").attr('src');
console.log("old image: " + src);

var newimage = src.replace(/-\d+x\d+./, ".");
console.log("new image: " + newimage);

$("#fixme").attr('src', newimage);
</code>```

See, e.g.: http://jsfiddle.net/entropo/pyww7/

To avoid awkward transitions, you want to ensure that your full-size image is preloaded.

Body:
A regex for this would look something like:

s/-\d+x\d+././

Assuming your img element has the ID fixme...

var src = $("#fixme").attr('src');
console.log("old image: " + src);

var newimage = src.replace(/-\d+x\d+./, ".");
console.log("new image: " + newimage);

$("#fixme").attr('src', newimage);

See, e.g.: http://jsfiddle.net/entropo/pyww7/

To avoid awkward transitions, you want to ensure that your full-size image is preloaded.


问:
Usage of React Redux in Modal
I am learning Redux in React. I am using Redux in React for Modal development. My code is like below

```<code>render() {
    return (
      <Modal id="addressModal" open={this.props.controlModal} onClose={this.props.action}>
        <Provider store={store}>
          {this.props.addresObj ? (
            <Modal.Header>Address Details</Modal.Header>
          ) : (
            <Modal.Header>Insert Address</Modal.Header>
          )}
          <Modal.Content>
              <ModalElement
                update={this.update}
                element={this.props.addresObj}
                errors = {this.state.errors}
                update_state_photo={this.update_state_photo}
                address={this.props.address}
                action={this.props.action}
              />
          </Modal.Content>

          <Modal.Actions>
            {this.props.addresObj ? (
              <Button
                positive
                icon="checkmark"
                labelPosition="right"
                onClick={this.closeModal}
                content="OK"
              />
            ) : (
              <Button
                positive
                icon="checkmark"
                labelPosition="right"
                onClick={this.insertAddress}
                content="Save"
              />
            )}
          </Modal.Actions>
        </Provider>
      </Modal>
    );
  }
}
</code>```

(Did I use <Provider store={store}> properly ?) In child component I can't use Redux syntax. Like if I use this export default connect()(EditableRow); I am getting error (component execution is not finish at that component, execution forwared). If I use this syntax export default EditableRow; I am not getting any error.

May be I could not express my issue properly.

Here is my repo    https://github.com/afoysal/mern/blob/master/client/src/components/ModalBody.js

I am getting below error.

How to use Redux in React Modal ?

答:
i hope you didn't wrap everything inside  properly,

once wrapped, its accessible throughout the app,

as redux states there must be single source of truth,

do try to follow principles.

```<code>// ModelBody.js
import { Provider, ReactReduxContext } from 'react-redux';

//...
render() {
    return (

        <ReactReduxContext.Consumer>
            {((ctx) => (
         <Provider store={ctx.store}>
                <Modal id="addressModal" open={this.props.controlModal} onClose={this.props.action}>
                      /* make store available in Portal */
                        {this.props.addresObj ? (
                            <Modal.Header>Address Details</Modal.Header>
                        ) : (
                            <Modal.Header>Insert Address</Modal.Header>
                        )}
                    /* other code from Model.js */

                </Modal>
           </Provider>
           )).bind(this) // Dont forget to bind this
       }
   </ReactReduxContext.Consumer>
</code>```

or try to wrap your whole app, index.jsx

```<code>import React from 'react'
import { render } from 'react-dom'
import { Provider } from 'react-redux'
import { createStore } from 'redux'
import rootReducer from './reducers'
import App from './components/App'

const store = createStore(rootReducer)

render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById('root')
)
</code>```

Title: Usage of React Redux in Modal

Body:
I am learning Redux in React. I am using Redux in React for Modal development. My code is like below

render() {
    return (
      <Modal id="addressModal" open={this.props.controlModal} onClose={this.props.action}>
        <Provider store={store}>
          {this.props.addresObj ? (
            <Modal.Header>Address Details</Modal.Header>
          ) : (
            <Modal.Header>Insert Address</Modal.Header>
          )}
          <Modal.Content>
              <ModalElement
                update={this.update}
                element={this.props.addresObj}
                errors = {this.state.errors}
                update_state_photo={this.update_state_photo}
                address={this.props.address}
                action={this.props.action}
              />
          </Modal.Content>

          <Modal.Actions>
            {this.props.addresObj ? (
              <Button
                positive
                icon="checkmark"
                labelPosition="right"
                onClick={this.closeModal}
                content="OK"
              />
            ) : (
              <Button
                positive
                icon="checkmark"
                labelPosition="right"
                onClick={this.insertAddress}
                content="Save"
              />
            )}
          </Modal.Actions>
        </Provider>
      </Modal>
    );
  }
}

(Did I use <Provider store={store}> properly ?) In child component I can't use Redux syntax. Like if I use this export default connect()(EditableRow); I am getting error (component execution is not finish at that component, execution forwared). If I use this syntax export default EditableRow; I am not getting any error.

May be I could not express my issue properly.

Here is my repo    https://github.com/afoysal/mern/blob/master/client/src/components/ModalBody.js

I am getting below error.

How to use Redux in React Modal ?

Body:
i hope you didn't wrap everything inside  properly,

once wrapped, its accessible throughout the app,

as redux states there must be single source of truth,

do try to follow principles.

// ModelBody.js
import { Provider, ReactReduxContext } from 'react-redux';

//...
render() {
    return (

        <ReactReduxContext.Consumer>
            {((ctx) => (
         <Provider store={ctx.store}>
                <Modal id="addressModal" open={this.props.controlModal} onClose={this.props.action}>
                      /* make store available in Portal */
                        {this.props.addresObj ? (
                            <Modal.Header>Address Details</Modal.Header>
                        ) : (
                            <Modal.Header>Insert Address</Modal.Header>
                        )}
                    /* other code from Model.js */

                </Modal>
           </Provider>
           )).bind(this) // Dont forget to bind this
       }
   </ReactReduxContext.Consumer>

or try to wrap your whole app, index.jsx

import React from 'react'
import { render } from 'react-dom'
import { Provider } from 'react-redux'
import { createStore } from 'redux'
import rootReducer from './reducers'
import App from './components/App'

const store = createStore(rootReducer)

render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById('root')
)


问:
Why are Angular apps called Single-Page Applications when they still make use of hyperlinks to different pages?
This is a question I've found myself asking a number of times since starting to work with Angular. I've heard time after time that Angular is a great framework for developing Single-Page Applications.

Now to me, the idea that an application is single-page suggests to me that all aspects of the web app are loaded in a single page on the internet, at a single address. Surely then this would mean that an app loaded at http://myapp.com/index.html/ should never need to navigate away from index.html?

But in reality within Angular we use a RoutingModule which allows the user to navigate to different hyperlinks using html elements present within the webpage. The router enables access to other links such as contact.html, about.html etc.

So why exactly are SPAs named as such when they don't have a single page within their application, but actually have multiple?

The same can be said of Vue or React apps.

答:
You're getting confused, let me explain.

When you deploy an Angular application on a server, you deploy it on a specific domain. For the example, let's say mydomain.com.

When you build the angular application, it generates a single index.html file. This file imports all the required scripts to make your final application work.

From there, Angular's job is done. At this point, it's up to the server to manage the routing.

You have two different ways of the server managing the routing : the usual, known one, where the server manages the whole URL, and the HashLocationStrategy.

For the first one, every request made to mydomain.com will be redirected to the root of the domain.

That means that mydomain.com/user/37 will redirect to mydomain.com, and Angular will manage the routing back to the page.

In the second solution, the URL becomes mydomain.com/#/user/37. In this case, only the root of the domain is exposed, and everything after the pound sign will be managed by Angular.

In both cases, you only have a single index.html file : this is why it's called a single page application.

In a SPA, the index file will display, thanks to JS, the content related to the request made by the user. In a non-SPA page, it's the server that displasy the required page.

Do not confuse the URL, which is simply a string, with a web application, which is a server, a client, a language ... And many more things.


问:
Transitive dependencies not resolved using gradle 3.0.0
My own library define in build.gradle

```<code>dependencies {
    api 'com.android.support:support-v4:26.0.1'
    api 'com.squareup.okhttp3:okhttp:3.9.0'
}
</code>```

When i include the library into another module in the same project :

```<code>implementation project(':myLib')
</code>```

support-v4 and okhttp are available in this other module

But when i include myLib into another project via an external dependency

```<code>implementation 'com.personnal.library:myLib:1.2.4'
</code>```

support-v4 and okhttp are NOT available in this other module while i'm using "api" rather then "implementation"

And I get the error : package android.support.v4.app does not exist

How does myLib dependencies can be exported in the project ?

Here is my library build.gradle

```<code>buildscript {
    repositories {
        maven { url 'http://jenkins.greaturl.com:8080/nexus/content/groups/public/' }
    }

    dependencies {
        classpath 'com.github.dcendents:android-maven-gradle-plugin:1.5'
    }
}

apply plugin: 'com.android.library'
apply plugin: 'com.github.dcendents.android-maven'

android {
    compileSdkVersion 26
    buildToolsVersion "26.0.1"

    defaultConfig {
        minSdkVersion 16
        targetSdkVersion 26
        consumerProguardFiles 'proguard-lib.pro'
    }
}

configurations {
    deployerJars
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])

    api "com.android.support:support-v4:26.0.1"
    api 'com.squareup.okhttp3:okhttp:3.9.0'
}

def groupName = 'com.personnal.library'
def versionName = '1.2.4'
def artifactName = 'myLib'

group = groupName
version = versionName
project.archivesBaseName = artifactName

uploadArchives {
    repositories {
        mavenDeployer {
            configuration = configurations.deployerJars

            repository(url: 'http://jenkins.greaturl.com:8080/nexus/content/repositories/releases')
            snapshotRepository(url: 'http://jenkins.greaturl.com:8080/nexus/content/repositories/snapshots')

            pom.artifactId = artifactName
            pom.groupId = groupName
            pom.version = versionName
        }

    }
}
</code>```

And my project build.gradle

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    buildToolsVersion "26.0.1"
    defaultConfig {
        applicationId "com.example.test"
        minSdkVersion 16
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])

    implementation 'com.personnal.library:myLib:1.2.4'
}
</code>```

答:
Use transitive = true while declaring your dependency in other projects, like this:-

```<code>implementation 'com.personnal.library:myLib:1.2.4',{
 transitive = true
}
</code>```

Body:
My own library define in build.gradle

dependencies {
    api 'com.android.support:support-v4:26.0.1'
    api 'com.squareup.okhttp3:okhttp:3.9.0'
}

When i include the library into another module in the same project :

implementation project(':myLib')

support-v4 and okhttp are available in this other module

But when i include myLib into another project via an external dependency

implementation 'com.personnal.library:myLib:1.2.4'

support-v4 and okhttp are NOT available in this other module while i'm using "api" rather then "implementation"

And I get the error : package android.support.v4.app does not exist

How does myLib dependencies can be exported in the project ?

Here is my library build.gradle

buildscript {
    repositories {
        maven { url 'http://jenkins.greaturl.com:8080/nexus/content/groups/public/' }
    }

    dependencies {
        classpath 'com.github.dcendents:android-maven-gradle-plugin:1.5'
    }
}

apply plugin: 'com.android.library'
apply plugin: 'com.github.dcendents.android-maven'

android {
    compileSdkVersion 26
    buildToolsVersion "26.0.1"

    defaultConfig {
        minSdkVersion 16
        targetSdkVersion 26
        consumerProguardFiles 'proguard-lib.pro'
    }
}

configurations {
    deployerJars
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])

    api "com.android.support:support-v4:26.0.1"
    api 'com.squareup.okhttp3:okhttp:3.9.0'
}

def groupName = 'com.personnal.library'
def versionName = '1.2.4'
def artifactName = 'myLib'

group = groupName
version = versionName
project.archivesBaseName = artifactName

uploadArchives {
    repositories {
        mavenDeployer {
            configuration = configurations.deployerJars

            repository(url: 'http://jenkins.greaturl.com:8080/nexus/content/repositories/releases')
            snapshotRepository(url: 'http://jenkins.greaturl.com:8080/nexus/content/repositories/snapshots')

            pom.artifactId = artifactName
            pom.groupId = groupName
            pom.version = versionName
        }

    }
}

And my project build.gradle

apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    buildToolsVersion "26.0.1"
    defaultConfig {
        applicationId "com.example.test"
        minSdkVersion 16
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])

    implementation 'com.personnal.library:myLib:1.2.4'
}

Body:
Use transitive = true while declaring your dependency in other projects, like this:-

implementation 'com.personnal.library:myLib:1.2.4',{
 transitive = true
}


问:
C++/CLI: Cannot see referenced assemblies without using #include
We have two C++/CLI projects, a pure CLR project and a mixed-mode project that exists to provide our unmanaged codebase access to the pure CLR project. We are having trouble getting the mixed-mode project to see symbols defined in the pure CLR project.

Specifically we have a form, call it MainForm, defined in the purely-managed project. It's a typical C++/CLI Windows Form:

MainForm.h:

```<code>public ref class MainForm : public System::Windows::Forms::Form
{
public:
    MainForm(void)
    {
        InitializeComponent();
        //
        //TODO: Add the constructor code here

    }
    ...
};
</code>```

Our mixed-mode "wrapper" project tries to use it, like so:

ManagedDialogProvider.h:

```<code>namespace ManagedWrapper
{
    public ref class ManagedDialogProvider
    {
        static void ShowDialog()
        {
             OurManagedComponents::MainForm^ form = gcnew OurManagedComponents::MainForm();
        }
    };
}
</code>```

(We then have a C++/MFC class in the mixed-mode project, CManagedDialogProvider, that calls ManagedDialogProvider so that our unmanaged code can use it. The error isn't occurring there, however.)

When I try building the mixed-mode project, it tells me that MainForm is not a member of OurManagedComponents. (Error in ManagedWrapper::ManagedDialogProvider::ShowDialog().)

Notes:

The mixed-mode project has a reference to the managed project.

I have tried using an #include at the top of the managed wrapper class instead of a reference, and while this compiled, I then couldn't load the form due to its resources not being found. I backed out of this solution as it's not accepted practice if I understand correctly; .NET projects should reference each other via assembly references only.

I've verified that the managed class is accessible (public).

I've checked the Object Browser to ensure that OurManagedComponents is visible and contains MainForm.

Any ideas?  The same mixed-mode project has no trouble wrapping C# managed components, but when I tried using that same approach for this C++/CLI managed component, these issues appeared.

答:
It turned out that OurManagedComponents::MainForm had no implementation file (.cpp); it only had a .h file. So naturally, MainForm was never actually built or linked in to the project. (Interestingly, the object browser still showed OurManagedComponents::MainForm and the project still built just fine; it must see declared types regardless of whether they are implemented).  What can I say, I've been using C# too long :-)

Once I created a MainForm.cpp (empty but for include "MainForm.h") and rebuilt, everything worked.

Body:
We have two C++/CLI projects, a pure CLR project and a mixed-mode project that exists to provide our unmanaged codebase access to the pure CLR project. We are having trouble getting the mixed-mode project to see symbols defined in the pure CLR project.

Specifically we have a form, call it MainForm, defined in the purely-managed project. It's a typical C++/CLI Windows Form:

MainForm.h:

public ref class MainForm : public System::Windows::Forms::Form
{
public:
    MainForm(void)
    {
        InitializeComponent();
        //
        //TODO: Add the constructor code here

    }
    ...
};

Our mixed-mode "wrapper" project tries to use it, like so:

ManagedDialogProvider.h:

namespace ManagedWrapper
{
    public ref class ManagedDialogProvider
    {
        static void ShowDialog()
        {
             OurManagedComponents::MainForm^ form = gcnew OurManagedComponents::MainForm();
        }
    };
}

(We then have a C++/MFC class in the mixed-mode project, CManagedDialogProvider, that calls ManagedDialogProvider so that our unmanaged code can use it. The error isn't occurring there, however.)

When I try building the mixed-mode project, it tells me that MainForm is not a member of OurManagedComponents. (Error in ManagedWrapper::ManagedDialogProvider::ShowDialog().)

Notes:

The mixed-mode project has a reference to the managed project.

I have tried using an #include at the top of the managed wrapper class instead of a reference, and while this compiled, I then couldn't load the form due to its resources not being found. I backed out of this solution as it's not accepted practice if I understand correctly; .NET projects should reference each other via assembly references only.

I've verified that the managed class is accessible (public).

I've checked the Object Browser to ensure that OurManagedComponents is visible and contains MainForm.

Any ideas?  The same mixed-mode project has no trouble wrapping C# managed components, but when I tried using that same approach for this C++/CLI managed component, these issues appeared.


问:
How to remove the decimal place when number before decimal is 0
Im trying to remove the decimal places from certain values

for example, my current code is

```<code>select po_id, AVG(price*quantity) * count(*) AS 'Total Cost'
from po_items natural join items
group by po_id;
</code>```

this is the output im getting

```<code>po_id       Total Cost
----------  ----------
AAA         2217.5
BBB         255.0
CCC         5787.5
DDD         10000.0
GGG         1000.0
</code>```

and the output im trying to get is

```<code>po_id       Total Cost
----------  ----------
AAA         2217.5
BBB         255
CCC         5787.5
DDD         10000
GGG         1000
</code>```

Body:
Im trying to remove the decimal places from certain values

for example, my current code is

select po_id, AVG(price*quantity) * count(*) AS 'Total Cost'
from po_items natural join items
group by po_id;

this is the output im getting

po_id       Total Cost
----------  ----------
AAA         2217.5
BBB         255.0
CCC         5787.5
DDD         10000.0
GGG         1000.0

and the output im trying to get is

po_id       Total Cost
----------  ----------
AAA         2217.5
BBB         255
CCC         5787.5
DDD         10000
GGG         1000

Body:
Use printf() with the %g format specifier:

sqlite> select printf('%g', 5.0), printf('%g', 5.5);
printf('%g', 5.0)  printf('%g', 5.5)
-----------------  -----------------
5                  5.5


问:
How test input onChange event with enzyme?
I made TextInput component, here is code:

```<code>export const TextInput = (props: ITextInputProps): TReactElement => {
  const {
    errorMessage,
    hasError,
    ...restProps
  } = props;

  return (
    <div>
      <input
        { ...restProps }
        type="text"
        className={ mergeClassNames([
          textInputStyles["text-input"],
          hasError ? textInputStyles["text-input--error"] : "",
        ]) }
      />
      {
        hasError &&
        <p className={ textInputStyles["text-input__error-message"] }>{ errorMessage }</p>
      }
    </div>
    );
};
</code>```

Now I wont test that onChange work correctly, I do it like this:

```<code>test("TextInput: should change value", () => {
  let actualInputValue;

  const textInputProps = {
    onChange: (event: ChangeEvent<HTMLInputElement>): void => {
      actualInputValue = event.currentTarget.value;
    },
  };

  const textInputWrapper = shallow(<TextInput { ...textInputProps } />);

  textInputWrapper.find(".text-input")
    .simulate("change", {
      currentTarget: {
        value: "Hello, world!",
      },
    });

  expect(actualInputValue)
    .toBe("Hello, world!");
});
</code>```

I feel that actualInputValue and onChange handler is excess because I can get value directly from .text-input

I tried read value like this (but got undefined):

```<code>test("TextInput: should change value", () => {
  const textInputWrapper = shallow(<TextInput />);

  textInputWrapper.find(".text-input")
    .simulate("change", {
      currentTarget: {
        value: "Hello, world!",
      },
    });

  expect(textInputWrapper.find(".text-input").props().value)
    .toBe("Hello, world!");
});

</code>```

Then I tried update textInputWrapper like this (but got undefined):

```<code>test("TextInput: should change value", () => {
  const textInputWrapper = shallow(<TextInput />);

  textInputWrapper.find(".text-input")
    .simulate("change", {
      currentTarget: {
        value: "Hello, world!",
      },
    });

  textInputWrapper.update();

  expect(textInputWrapper.find(".text-input").props().value)
    .toBe("Hello, world!");
});
</code>```

Then I also tried use done callback (but got undefined):

```<code>test("TextInput: should change value", (done: () => void) => {
  const textInputWrapper = shallow(<TextInput />);

  textInputWrapper.find(".text-input")
    .simulate("change", {
      currentTarget: {
        value: "Hello, world!",
      },
    });

  textInputWrapper.update();

  expect(textInputWrapper.find(".text-input").props().value)
    .toBe("Hello, world!");

  done();
});
</code>```

I also used mount instead shallow and got same results...

Then I used actualInputValue and onChange handler :(

It's my questions: how to get actual value from textInputWrapper.find(".text-input") ?

Thank you so much!!!

答:
I think the main issue you're having is within your expect statement (below)

```<code>expect(textInputWrapper.find(".text-input").props().value)
.toBe("Hello, world!");
</code>```

You're running .props() on an array instead of a single node, assuming you know there will be only one ".text-input" replace it with the below.

```<code>expect(textInputWrapper.find(".text-input").at(0).props().value)
.toBe("Hello, world!");
</code>```

You could also use .prop("value") instead of .props().value although that's more personal preference.

Also you don't need to use the done callback for this test, that's only for async functions such as MockApi calls

Body:
I made TextInput component, here is code:

export const TextInput = (props: ITextInputProps): TReactElement => {
  const {
    errorMessage,
    hasError,
    ...restProps
  } = props;

  return (

      <input
        { ...restProps }
        type="text"
        className={ mergeClassNames([
          textInputStyles["text-input"],
          hasError ? textInputStyles["text-input--error"] : "",
        ]) }
      />
      {
        hasError &&

{ errorMessage }

      }

    );
};

Now I wont test that onChange work correctly, I do it like this:

test("TextInput: should change value", () => {
  let actualInputValue;

  const textInputProps = {
    onChange: (event: ChangeEvent<HTMLInputElement>): void => {
      actualInputValue = event.currentTarget.value;
    },
  };

  const textInputWrapper = shallow(<TextInput { ...textInputProps } />);

  textInputWrapper.find(".text-input")
    .simulate("change", {
      currentTarget: {
        value: "Hello, world!",
      },
    });

  expect(actualInputValue)
    .toBe("Hello, world!");
});

I feel that actualInputValue and onChange handler is excess because I can get value directly from .text-input

I tried read value like this (but got undefined):

test("TextInput: should change value", () => {
  const textInputWrapper = shallow(<TextInput />);

  textInputWrapper.find(".text-input")
    .simulate("change", {
      currentTarget: {
        value: "Hello, world!",
      },
    });

  expect(textInputWrapper.find(".text-input").props().value)
    .toBe("Hello, world!");
});

Then I tried update textInputWrapper like this (but got undefined):

test("TextInput: should change value", () => {
  const textInputWrapper = shallow(<TextInput />);

  textInputWrapper.find(".text-input")
    .simulate("change", {
      currentTarget: {
        value: "Hello, world!",
      },
    });

  textInputWrapper.update();

  expect(textInputWrapper.find(".text-input").props().value)
    .toBe("Hello, world!");
});

Then I also tried use done callback (but got undefined):

test("TextInput: should change value", (done: () => void) => {
  const textInputWrapper = shallow(<TextInput />);

  textInputWrapper.find(".text-input")
    .simulate("change", {
      currentTarget: {
        value: "Hello, world!",
      },
    });

  textInputWrapper.update();

  expect(textInputWrapper.find(".text-input").props().value)
    .toBe("Hello, world!");

  done();
});

I also used mount instead shallow and got same results...

Then I used actualInputValue and onChange handler :(

It's my questions: how to get actual value from textInputWrapper.find(".text-input") ?

Thank you so much!!!

Body:
I think the main issue you're having is within your expect statement (below)

expect(textInputWrapper.find(".text-input").props().value)
.toBe("Hello, world!");

You're running .props() on an array instead of a single node, assuming you know there will be only one ".text-input" replace it with the below.

expect(textInputWrapper.find(".text-input").at(0).props().value)
.toBe("Hello, world!");

You could also use .prop("value") instead of .props().value although that's more personal preference.

Also you don't need to use the done callback for this test, that's only for async functions such as MockApi calls


问:
Django Admin Page missing CSS
I saw this question and recommendation from Django Projects here but still can't get this to work. My Django Admin pages are not displaying the CSS at all.

This is my current configuration.

settings.py

```<code>ADMIN_MEDIA_PREFIX = '/media/admin/'
</code>```

httpd.conf

```<code><VirtualHost *:80>
    DocumentRoot /home/django/sgel
    ServerName ec2-***-**-***-***.ap-**********-1.compute.amazonaws.com
    ErrorLog /home/django/sgel/logs/apache_error.log
    CustomLog /home/django/sgel/logs/apache_access.log combined
    WSGIScriptAlias / /home/django/sgel/apache/django.wsgi

    <Directory /home/django/sgel/media>
        Order deny,allow
        Allow from all
    </Directory>

    <Directory /home/django/sgel/apache>
        Order deny,allow
        Allow from all
    </Directory>

    LogLevel warn

    Alias /media/ /home/django/sgel/media/

</VirtualHost>

<VirtualHost *:80>
   ServerName sgel.com
   Redirect permanent / http://www.sgel.com/
</VirtualHost>
</code>```

In addition, I also ran the following to create (I think) the symbolic link
ln -s /home/djangotest/sgel/media/admin/ /usr/lib/python2.6/site-packages/django/contrib/admin/media/

UPDATE

In my httpd.conf file,

```<code>User django
Group django
</code>```

When I run ls -l in my /media directory

```<code>drwxr-xr-x 2 root root 4096 Apr  4 11:03 admin
-rw-r--r-- 1 root root    9 Apr  8 09:02 test.txt
</code>```

Should that root user be django instead?

UPDATE 2
When I enter ls -la in my /media/admin folder

```<code>total 12
drwxr-xr-x 2 root root 4096 Apr 13 03:33 .
drwxr-xr-x 3 root root 4096 Apr  8 09:02 ..
lrwxrwxrwx 1 root root   60 Apr 13 03:33 media -> /usr/lib/python2.6/site-packages/django/contrib/admin/media/
</code>```

The thing is, when I navigate to /usr/lib/python2.6/site-packages/django/contrib/admin/media/, the folder was empty. So I copied the CSS, IMG and JS folders from my Django installation into /usr/lib/python2.6/site-packages/django/contrib/admin/media/ and it still didn't work

答:
Try to add

```<code>Options FollowSymLinks
</code>```

to your

```<code><Directory /home/django/sgel/media>
    Order deny,allow
    Allow from all
</Directory>
</code>```

so that you end up with

```<code><Directory /home/django/sgel/media>
    Options FollowSymLinks
    Order deny,allow
    Allow from all
</Directory>
</code>```

Title: Django Admin Page missing CSS

Body:
I saw this question and recommendation from Django Projects here but still can't get this to work. My Django Admin pages are not displaying the CSS at all.

This is my current configuration.

settings.py

ADMIN_MEDIA_PREFIX = '/media/admin/'

httpd.conf

<VirtualHost *:80>
    DocumentRoot /home/django/sgel
    ServerName ec2-***-**-***-***.ap-**********-1.compute.amazonaws.com
    ErrorLog /home/django/sgel/logs/apache_error.log
    CustomLog /home/django/sgel/logs/apache_access.log combined
    WSGIScriptAlias / /home/django/sgel/apache/django.wsgi

    <Directory /home/django/sgel/media>
        Order deny,allow
        Allow from all
    </Directory>

    <Directory /home/django/sgel/apache>
        Order deny,allow
        Allow from all
    </Directory>

    LogLevel warn

    Alias /media/ /home/django/sgel/media/

</VirtualHost>

<VirtualHost *:80>
   ServerName sgel.com
   Redirect permanent / http://www.sgel.com/
</VirtualHost>

In addition, I also ran the following to create (I think) the symbolic link
ln -s /home/djangotest/sgel/media/admin/ /usr/lib/python2.6/site-packages/django/contrib/admin/media/

UPDATE

In my httpd.conf file,

User django
Group django

When I run ls -l in my /media directory

drwxr-xr-x 2 root root 4096 Apr  4 11:03 admin
-rw-r--r-- 1 root root    9 Apr  8 09:02 test.txt

Should that root user be django instead?

UPDATE 2
When I enter ls -la in my /media/admin folder

total 12
drwxr-xr-x 2 root root 4096 Apr 13 03:33 .
drwxr-xr-x 3 root root 4096 Apr  8 09:02 ..
lrwxrwxrwx 1 root root   60 Apr 13 03:33 media -> /usr/lib/python2.6/site-packages/django/contrib/admin/media/

The thing is, when I navigate to /usr/lib/python2.6/site-packages/django/contrib/admin/media/, the folder was empty. So I copied the CSS, IMG and JS folders from my Django installation into /usr/lib/python2.6/site-packages/django/contrib/admin/media/ and it still didn't work

Body:
Try to add

Options FollowSymLinks

to your

<Directory /home/django/sgel/media>
    Order deny,allow
    Allow from all
</Directory>

so that you end up with

<Directory /home/django/sgel/media>
    Options FollowSymLinks
    Order deny,allow
    Allow from all
</Directory>


问:
Type Observable<{} | AppUser> is not assignable to <AppUser> RxJS Of operator
Using Angular 6.1 and RxJs 6, I'm trying to implement a resolver for a component on an individual user.

My userService http call is this:

```<code>getUserById(id: string): Observable<AppUser> {
    return this.http.get<AppUser>(this.baseURL + id, httpOptions);
}
</code>```

And my resolver:

```<code>import { Injectable } from "@angular/core";
import { Resolve, Router, ActivatedRouteSnapshot } from "@angular/router";
import { AppUser } from "../models/User/IAppUser";
import { UserService } from "../services/users/user.service";
import { AlertifyService } from "../../coreModule/alertify/alertify.service";
import { Observable, of } from "rxjs";
import { catchError } from "rxjs/operators";

@Injectable()
export class UserDetailResolver implements Resolve<AppUser> {
  constructor(
    private userService: UserService,
    private router: Router,
    private alertify: AlertifyService
  ) { }

  resolve(route: ActivatedRouteSnapshot): Observable<AppUser> {
    return this.userService.getUserById(route.params['id'])
      .pipe(
        catchError(error => {
          this.alertify.error('Problem retrieving data');
          this.router.navigate(['/home']);
          return of(null)
        })
      );
  }
</code>```

But because I'm trying to return null instead of an AppUser typescript is throwing an error. Not sure what I'm doing wrong since I thought rxjs of was supposed to handle this.

答:
I might be missing something, but you have a method that is declared to return a stream of AppUser, which implements interface Resolve<AppUser>. And with catchError + of(null) that method is effectively returning a stream of either null or AppUser. As the TS compiler is rightfully complaining about.

To fix this you may either return an EMPTY observable. It emits no values and immediately completes. NEVER is another constant observable that will never emit and never complete. Pick the one you need. E.g.

catchError(()=>{
  // ...
  return EMPTY;
})
```

NOTE: with this approach you might need to do type casting, e.g. EMPTY as Observable<AppUser>. Though it will be an honest casting — as empty observable can be of any type of observable.

Or if you do need to emit a null value on the stream — declare the method as returning Observable<AppUser | null>, which is the actual type that it currently returns. And you'll have to also update the Resolve<AppUser> to Resolve<AppUser | null>.

==

TO EMPHASIZE THIS:

In most cases you don't want to lie to your typing system and force cast a Observable<null | AppUser> type to a Observable<AppUser>.

==

Hope it helps

Body:
Using Angular 6.1 and RxJs 6, I'm trying to implement a resolver for a component on an individual user.

My userService http call is this:

getUserById(id: string): Observable<AppUser> {
    return this.http.get<AppUser>(this.baseURL + id, httpOptions);
}

And my resolver:

import { Injectable } from "@angular/core";
import { Resolve, Router, ActivatedRouteSnapshot } from "@angular/router";
import { AppUser } from "../models/User/IAppUser";
import { UserService } from "../services/users/user.service";
import { AlertifyService } from "../../coreModule/alertify/alertify.service";
import { Observable, of } from "rxjs";
import { catchError } from "rxjs/operators";

@Injectable()
export class UserDetailResolver implements Resolve<AppUser> {
  constructor(
    private userService: UserService,
    private router: Router,
    private alertify: AlertifyService
  ) { }

  resolve(route: ActivatedRouteSnapshot): Observable<AppUser> {
    return this.userService.getUserById(route.params['id'])
      .pipe(
        catchError(error => {
          this.alertify.error('Problem retrieving data');
          this.router.navigate(['/home']);
          return of(null)
        })
      );
  }

But because I'm trying to return null instead of an AppUser typescript is throwing an error. Not sure what I'm doing wrong since I thought rxjs of was supposed to handle this.

Body:
I might be missing something, but you have a method that is declared to return a stream of AppUser, which implements interface Resolve<AppUser>. And with catchError + of(null) that method is effectively returning a stream of either null or AppUser. As the TS compiler is rightfully complaining about.

To fix this you may either return an EMPTY observable. It emits no values and immediately completes. NEVER is another constant observable that will never emit and never complete. Pick the one you need. E.g.

catchError(()=>{
  // ...
  return EMPTY;
})

NOTE: with this approach you might need to do type casting, e.g. EMPTY as Observable<AppUser>. Though it will be an honest casting — as empty observable can be of any type of observable.

Or if you do need to emit a null value on the stream — declare the method as returning Observable<AppUser | null>, which is the actual type that it currently returns. And you'll have to also update the Resolve<AppUser> to Resolve<AppUser | null>.

==

TO EMPHASIZE THIS:

In most cases you don't want to lie to your typing system and force cast a Observable<null | AppUser> type to a Observable<AppUser>.

==

Hope it helps


问:
Adjust div width according to child element
In this fiddle: https://jsfiddle.net/7d84Laxr/1/

```<code><div class="textCenter">
    <div class="wrapper">
        <input type="text" class="inputNoBorder">
        <p style="display: inline-block;">/Some Text.</p>
    </div>
</div>
</code>```

I want to underline (border-bottom) the input and p only. But as the width of parent div is same as window width, it draws a full line.

How can I reduce wrapper div's width to only contain two elements so that border will be only below those two elements?

I prefer no JavaScript.

答:
You can achieve the same thing by Flex, and try the commented property for content horizontal alignment

and Yes please use label in place of P tag, I think that would be more suitable for you and semantic also.

.textCenter{
  text-align : center;
  display: flex;
  /*justify-content: flex-end; */
  /* justify-content: center; */
}

.inputNoBorder{
 border: 0px;
  display: -webkit-inline-box;
  padding: 0px;
  margin: 0rem 0.2rem;
  width: 15rem;
}

.wrapper{
  border-bottom: 1px solid;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="textCenter">
 <div class="wrapper">
  <input type="text" class="inputNoBorder">
  <p style="display: inline-block;">/DENSPRI, LLC.</p>
 </div>
</div></code>```

Body:
In this fiddle: https://jsfiddle.net/7d84Laxr/1/

        <input type="text" class="inputNoBorder">

/Some Text.

I want to underline (border-bottom) the input and p only. But as the width of parent div is same as window width, it draws a full line.

How can I reduce wrapper div's width to only contain two elements so that border will be only below those two elements?

I prefer no JavaScript.

Body:
You can achieve the same thing by Flex, and try the commented property for content horizontal alignment

and Yes please use label in place of P tag, I think that would be more suitable for you and semantic also.

.textCenter{
  text-align : center;
  display: flex;
  /*justify-content: flex-end; */
  /* justify-content: center; */
}

.inputNoBorder{
 border: 0px;
  display: -webkit-inline-box;
  padding: 0px;
  margin: 0rem 0.2rem;
  width: 15rem;
}

.wrapper{
  border-bottom: 1px solid;
}

<div class="textCenter">
 <div class="wrapper">
  <input type="text" class="inputNoBorder">
  <p style="display: inline-block;">/DENSPRI, LLC.</p>
 </div>
</div>


问:
UUIDV4 in for loop not changing value
I am trying to create a function to generate an array of objects with a UUID as the key, as well as a UUID for some of the nested object ids.

Each game will be based on a mock object which I import into the file.

The function expects a sport (string) which will get assigned to a key and a quantity (number) which will determine the for loop iterations.

When using a for loop the UUID for the nested object ids are getting overridden on each iteration.

```<code>const mockGame = require('../mock-game');
const uuidv4 = require('uuid/v4');

function generateMockGames(sport, quantity) {
    let games = []

    for (let i = 0; i < quantity; i++) {
        let game = {}
        let id = uuidv4()

        game[id] = {
            search: mockGame.search,
            query: mockGame.query,
            variables: mockGame.variables,
        }

        game[id].search.eventId = id
        game[id].search.competition.categoryName = sport

        game[id].search.id = id
        game[id].search.competition.categoryName = sport;

        games.push(game);
    }

    return games;
}

const mockFootballGame = generateMockGames('football', 3);
</code>```

Expected result:

```<code>[
  {
    '286c1911-b155-4197-bbde-64dba0b304fe': {
       search: {
           eventId: '286c1911-b155-4197-bbde-64dba0b304fe',
           name: 'test name',
           competition: {
               categoryName: 'football'
           }
      },
      query: {
           id: '286c1911-b155-4197-bbde-64dba0b304fe',
           competition: {
               categoryName: 'football'
           }
      },
      variables: {
           name: 'test name'
      }
  },
  {
    '082a46a6-4dde-433d-8011-9e94a5ee79ff': {
       search: {
           eventId: '082a46a6-4dde-433d-8011-9e94a5ee79ff',
           name: 'test name',
           competition: {
               categoryName: 'football'
           }
      },
      query: {
           id: '082a46a6-4dde-433d-8011-9e94a5ee79ff',
           competition: {
               categoryName: 'football'
           }
      },
      variables: {
           name: 'test name'
      }
  },
  {
    'ba911751-3ea3-40ab-9bec-c525ab2a07b9': {
       search: {
           eventId: 'ba911751-3ea3-40ab-9bec-c525ab2a07b9',
           name: 'test name',
           competition: {
               categoryName: 'football'
           }
      },
      query: {
           id: 'ba911751-3ea3-40ab-9bec-c525ab2a07b9',
           competition: {
               categoryName: 'football'
           }
      },
      variables: {
           name: 'test name'
      }
  }
]
</code>```

Output is:

```<code>[
  {
    '286c1911-b155-4197-bbde-64dba0b304fe': {
       search: {
           eventId: 'ba911751-3ea3-40ab-9bec-c525ab2a07b9',
           name: 'test name',
           competition: {
               categoryName: 'football'
           }
      },
      query: {
           id: 'ba911751-3ea3-40ab-9bec-c525ab2a07b9',
           competition: {
               categoryName: 'football'
           }
      },
      variables: {
           name: 'test name'
      }
  },
  {
    '082a46a6-4dde-433d-8011-9e94a5ee79ff': {
       search: {
           eventId: 'ba911751-3ea3-40ab-9bec-c525ab2a07b9',
           name: 'test name',
           competition: {
               categoryName: 'football'
           }
      },
      query: {
           id: 'ba911751-3ea3-40ab-9bec-c525ab2a07b9',
           competition: {
               categoryName: 'football'
           }
      },
      variables: {
           name: 'test name'
      }
  },
  {
    'ba911751-3ea3-40ab-9bec-c525ab2a07b9': {
       search: {
           eventId: 'ba911751-3ea3-40ab-9bec-c525ab2a07b9',
           name: 'test name',
           competition: {
               categoryName: 'football'
           }
      },
      query: {
           id: 'ba911751-3ea3-40ab-9bec-c525ab2a07b9',
           competition: {
               categoryName: 'football'
           }
      },
      variables: {
           name: 'test name'
      }
  }
]

</code>```

答: You are assigning subobjects of mockGame in your loop to the entries, without copying them. So you keep overwriting mockGame.query.id etc, with a new uuid in your loop, but then assign the mockGame.query object as a whole to your output.

Title: UUIDV4 in for loop not changing value

Body:
I am trying to create a function to generate an array of objects with a UUID as the key, as well as a UUID for some of the nested object ids.

Each game will be based on a mock object which I import into the file.

The function expects a sport (string) which will get assigned to a key and a quantity (number) which will determine the for loop iterations.

When using a for loop the UUID for the nested object ids are getting overridden on each iteration.

const mockGame = require('../mock-game');
const uuidv4 = require('uuid/v4');

function generateMockGames(sport, quantity) {
    let games = []

    for (let i = 0; i < quantity; i++) {
        let game = {}
        let id = uuidv4()

        game[id] = {
            search: mockGame.search,
            query: mockGame.query,
            variables: mockGame.variables,
        }

        game[id].search.eventId = id
        game[id].search.competition.categoryName = sport

        game[id].search.id = id
        game[id].search.competition.categoryName = sport;

        games.push(game);
    }

    return games;
}

const mockFootballGame = generateMockGames('football', 3);

Expected result:

[
  {
    '286c1911-b155-4197-bbde-64dba0b304fe': {
       search: {
           eventId: '286c1911-b155-4197-bbde-64dba0b304fe',
           name: 'test name',
           competition: {
               categoryName: 'football'
           }
      },
      query: {
           id: '286c1911-b155-4197-bbde-64dba0b304fe',
           competition: {
               categoryName: 'football'
           }
      },
      variables: {
           name: 'test name'
      }
  },
  {
    '082a46a6-4dde-433d-8011-9e94a5ee79ff': {
       search: {
           eventId: '082a46a6-4dde-433d-8011-9e94a5ee79ff',
           name: 'test name',
           competition: {
               categoryName: 'football'
           }
      },
      query: {
           id: '082a46a6-4dde-433d-8011-9e94a5ee79ff',
           competition: {
               categoryName: 'football'
           }
      },
      variables: {
           name: 'test name'
      }
  },
  {
    'ba911751-3ea3-40ab-9bec-c525ab2a07b9': {
       search: {
           eventId: 'ba911751-3ea3-40ab-9bec-c525ab2a07b9',
           name: 'test name',
           competition: {
               categoryName: 'football'
           }
      },
      query: {
           id: 'ba911751-3ea3-40ab-9bec-c525ab2a07b9',
           competition: {
               categoryName: 'football'
           }
      },
      variables: {
           name: 'test name'
      }
  }
]

Output is:

[
  {
    '286c1911-b155-4197-bbde-64dba0b304fe': {
       search: {
           eventId: 'ba911751-3ea3-40ab-9bec-c525ab2a07b9',
           name: 'test name',
           competition: {
               categoryName: 'football'
           }
      },
      query: {
           id: 'ba911751-3ea3-40ab-9bec-c525ab2a07b9',
           competition: {
               categoryName: 'football'
           }
      },
      variables: {
           name: 'test name'
      }
  },
  {
    '082a46a6-4dde-433d-8011-9e94a5ee79ff': {
       search: {
           eventId: 'ba911751-3ea3-40ab-9bec-c525ab2a07b9',
           name: 'test name',
           competition: {
               categoryName: 'football'
           }
      },
      query: {
           id: 'ba911751-3ea3-40ab-9bec-c525ab2a07b9',
           competition: {
               categoryName: 'football'
           }
      },
      variables: {
           name: 'test name'
      }
  },
  {
    'ba911751-3ea3-40ab-9bec-c525ab2a07b9': {
       search: {
           eventId: 'ba911751-3ea3-40ab-9bec-c525ab2a07b9',
           name: 'test name',
           competition: {
               categoryName: 'football'
           }
      },
      query: {
           id: 'ba911751-3ea3-40ab-9bec-c525ab2a07b9',
           competition: {
               categoryName: 'football'
           }
      },
      variables: {
           name: 'test name'
      }
  }
]


问:
Optimize/faster choice than "not all" in LINQ
I'm using EF 6 and .NET Framework 4.6.1. I have a scenario where I need to exclude a parent record if all of its child records meet a certain condition.

This is a generic version of what I've done so far:

public ParentRecords GetParentRecordsExceptWhereSpecificStringOnAllChildren(string aSpecificString){
        return ParentRecords
            .Where(parent => !parent.ChildRecords
                .Select(child => child.SomeStringProperty)
                .All(c => c.Equals(aSpecificString))
        );
    }
```

This takes a little too much time to run (on the scale of one second per child record), and the generated SQL from EF contains n-1 UNION ALL statements, where n is the number of child records.

I suspect I'm missing an obvious way to write this that would improve performance dramatically, but I'm not seeing it (but I'm not a LINQ/EF master by any means).

I wrote a stored procedure that returns the same data, but much faster, and not exactly in the same layout (one flat row versus a row for each child record). We're trying to avoid stored procedures, though, so I'm back to the grindstone on figuring out how to make this LINQ faster.

Any suggestions would be greatly appreciated. If I haven't explained this clearly, please let me know. I tried to make it generic for the sake of re-use, in case anyone else is in this situation.

答:
You can remove the select of SomeStringProperty from your code.

Using Any

```<code>        ParentRecords.Where(parent =>
            parent.ChildRecords.Any(child => !child.SomeStringProperty.Equals(aSpecificString)));
</code>```

Using All

```<code>       ParentRecords.Where(parent =>
            !parent.ChildRecords.All(child => child.SomeStringProperty.Equals(aSpecificString)));
</code>```

Body:
I'm using EF 6 and .NET Framework 4.6.1. I have a scenario where I need to exclude a parent record if all of its child records meet a certain condition.

This is a generic version of what I've done so far:

public ParentRecords GetParentRecordsExceptWhereSpecificStringOnAllChildren(string aSpecificString){
        return ParentRecords
            .Where(parent => !parent.ChildRecords
                .Select(child => child.SomeStringProperty)
                .All(c => c.Equals(aSpecificString))
        );
    }

This takes a little too much time to run (on the scale of one second per child record), and the generated SQL from EF contains n-1 UNION ALL statements, where n is the number of child records.

I suspect I'm missing an obvious way to write this that would improve performance dramatically, but I'm not seeing it (but I'm not a LINQ/EF master by any means).

I wrote a stored procedure that returns the same data, but much faster, and not exactly in the same layout (one flat row versus a row for each child record). We're trying to avoid stored procedures, though, so I'm back to the grindstone on figuring out how to make this LINQ faster.

Any suggestions would be greatly appreciated. If I haven't explained this clearly, please let me know. I tried to make it generic for the sake of re-use, in case anyone else is in this situation.

Body:
You can remove the select of SomeStringProperty from your code.

Using Any

        ParentRecords.Where(parent =>
            parent.ChildRecords.Any(child => !child.SomeStringProperty.Equals(aSpecificString)));

Using All

       ParentRecords.Where(parent =>
            !parent.ChildRecords.All(child => child.SomeStringProperty.Equals(aSpecificString)));


问:
How to implement Web API with many databases depending on client calling
I have to create a RESTful Web API (I'm using ASP.NET Core 1.1) for a system which is maybe a bit unusual in the sense that each client using this system has their own database. (A client is like a company, with many users in it). So there is a master database which specifies, for each client, which database it must connect to. All clients databases are identical (except for the data of course).

I'm wondering how I should handle this... Normally, when an app consumes a Web API, you might have something like this:

```<code>public class AccountsController : Controller
{
    private readonly SomeContext _context;

    public FilesController(SomeContext context)
    {
        _context = context;
    }

    // GET: api/Files
    [HttpGet)]
    public IEnumerable<Account> GetAccounts()
    {
            return _context.Accounts;
    }
}
</code>```

Now, in the above example, the problem is that the Context has to point to different databases, depending on which client is requesting the list of Accounts. I'm not sure how to best tackle this. Would it be OK if the front end sends, with every API call, a client identifier in a query string? So every single controller action would have a ClientId parameter. And based on this parameter, the action would modify the Context's connection string on the fly, just before calling it? It just sounds terrible though - both from an implementation and a security point of view. The problem is that, as far as I'm aware, ASP.NET is stateless, so every time the API is called, the API will have no idea who this is?

Or how else could I do this?

答:
@Srivaishnav

What I did is, each client sends a tenantId in the header of each request to the Web API. Then, the Web API reads this tenantId in some middleware, and saves it in the HttpContext so that it's readable anywhere in the API. Then, in my DbContext, in the OnConfiguring method, I read the tenantId from the HttpContext, and use it to create the connection string for that DbContext. The code:

TenantIdentifier.cs middleware:

```<code>public class TenantIdentifier
{
    private readonly RequestDelegate _next;
    private readonly IMemoryCache _memoryCache;
    private DbContext _dbContext;

    public TenantIdentifier(RequestDelegate next, IMemoryCache memoryCache)
    {
        _next = next;
        _memoryCache = memoryCache;
    }

    public async Task Invoke(HttpContext httpContext, DbContext dbContext)
    {
        _dbContext = dbContext;

        string clientIdHeader = httpContext.Request.Headers["clientId"].FirstOrDefault();
        if (string.IsNullOrEmpty(clientIdHeader))
        {
            await _next.Invoke(httpContext);
            return;
        }

        int clientId = int.Parse(clientIdHeader);

        httpContext.Items["CLIENT"] = clientId;

        await _next.Invoke(httpContext);
    }

public static class TenantIdentifierExtension
{
    public static IApplicationBuilder UseTenantIdentifier(this IApplicationBuilder app)
    {
        app.UseMiddleware<TenantIdentifier>();
        return app;
    }
}
</code>```

DbContext.cs:

```<code>    private readonly IHttpContextAccessor _httpContextAccessor;

    public TenantContext(DbContextOptions<DbContext> options, IHttpContextAccessor httpContextAccessor)
        : base(options)
    {
        _httpContextAccessor = httpContextAccessor;
    }

    protected override async void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        if (_httpContextAccessor == null)
            return;

        int? clientId = (int?)_httpContextAccessor.HttpContext.Items["CLIENT"];
        if (!client.HasValue)
        {
            optionsBuilder = null;
            return;
        }

        string connectionString = null;

        switch (tenantId.Value)
        {
            case 1:
                connectionString = "some connection string";
                break;

            case 2:
                connectionString = "some other connection string";
                break;
        }

        optionsBuilder.UseMySql(connectionString);
    }
</code>```

Startup.cs

```<code>    public void Configure(IApplicationBuilder app)
    {
        app.UseTenantIdentifier();
        app.UseMvc();
    }
</code>```

I've simplified the example a bit, but that's pretty much the crux of it. Let me know if you have any questions... Good luck!

Body:
I have to create a RESTful Web API (I'm using ASP.NET Core 1.1) for a system which is maybe a bit unusual in the sense that each client using this system has their own database. (A client is like a company, with many users in it). So there is a master database which specifies, for each client, which database it must connect to. All clients databases are identical (except for the data of course).

I'm wondering how I should handle this... Normally, when an app consumes a Web API, you might have something like this:

public class AccountsController : Controller
{
    private readonly SomeContext _context;

    public FilesController(SomeContext context)
    {
        _context = context;
    }

    // GET: api/Files
    [HttpGet)]
    public IEnumerable<Account> GetAccounts()
    {
            return _context.Accounts;
    }
}

Now, in the above example, the problem is that the Context has to point to different databases, depending on which client is requesting the list of Accounts. I'm not sure how to best tackle this. Would it be OK if the front end sends, with every API call, a client identifier in a query string? So every single controller action would have a ClientId parameter. And based on this parameter, the action would modify the Context's connection string on the fly, just before calling it? It just sounds terrible though - both from an implementation and a security point of view. The problem is that, as far as I'm aware, ASP.NET is stateless, so every time the API is called, the API will have no idea who this is?

Or how else could I do this?

Body:
@Srivaishnav

What I did is, each client sends a tenantId in the header of each request to the Web API. Then, the Web API reads this tenantId in some middleware, and saves it in the HttpContext so that it's readable anywhere in the API. Then, in my DbContext, in the OnConfiguring method, I read the tenantId from the HttpContext, and use it to create the connection string for that DbContext. The code:

TenantIdentifier.cs middleware:

public class TenantIdentifier
{
    private readonly RequestDelegate _next;
    private readonly IMemoryCache _memoryCache;
    private DbContext _dbContext;

    public TenantIdentifier(RequestDelegate next, IMemoryCache memoryCache)
    {
        _next = next;
        _memoryCache = memoryCache;
    }

    public async Task Invoke(HttpContext httpContext, DbContext dbContext)
    {
        _dbContext = dbContext;

        string clientIdHeader = httpContext.Request.Headers["clientId"].FirstOrDefault();
        if (string.IsNullOrEmpty(clientIdHeader))
        {
            await _next.Invoke(httpContext);
            return;
        }

        int clientId = int.Parse(clientIdHeader);

        httpContext.Items["CLIENT"] = clientId;

        await _next.Invoke(httpContext);
    }

public static class TenantIdentifierExtension
{
    public static IApplicationBuilder UseTenantIdentifier(this IApplicationBuilder app)
    {
        app.UseMiddleware<TenantIdentifier>();
        return app;
    }
}

DbContext.cs:

    private readonly IHttpContextAccessor _httpContextAccessor;

    public TenantContext(DbContextOptions<DbContext> options, IHttpContextAccessor httpContextAccessor)
        : base(options)
    {
        _httpContextAccessor = httpContextAccessor;
    }

    protected override async void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        if (_httpContextAccessor == null)
            return;

        int? clientId = (int?)_httpContextAccessor.HttpContext.Items["CLIENT"];
        if (!client.HasValue)
        {
            optionsBuilder = null;
            return;
        }

        string connectionString = null;

        switch (tenantId.Value)
        {
            case 1:
                connectionString = "some connection string";
                break;

            case 2:
                connectionString = "some other connection string";
                break;
        }

        optionsBuilder.UseMySql(connectionString);
    }

Startup.cs

    public void Configure(IApplicationBuilder app)
    {
        app.UseTenantIdentifier();
        app.UseMvc();
    }

I've simplified the example a bit, but that's pretty much the crux of it. Let me know if you have any questions... Good luck!