问:
SSRS tablix visibility
I have a multi-parameter report in SSRS where I want to display or hide a report depending on the parameter selection.  If the user selects only one facility from a multi-value facility parameter then I want a second report to display along with the main report(it would be a separate tab).  If multiple facilities are chosen then I only want the main report to display.

I've been playing with the visibility expressions on the second report but I can't seem to get it to work.

I've tried:

```<code>   =IFF(Parameters!entity.IsMultiValue, "True", "False")
</code>```

but that returns an error "The hidden expression used in tablix returned a data type that is not valid.

I've also tried:

```<code>   =IIF(Parameters!entity.Count = 1), "False", "True")
</code>```

But I get the same error.  I'm using SSRS 2016.

答:
True and False are not strings, they are booleans. The Visibility property looks for a boolean, but in the expressions you gave (assuming your syntax was correct when testing it), you are passing strings since you have them enclosed in double quotes. Remove the double quotes and that will clear that error.

You also don't need to use IIf here -- you can simply use the first argument of the IIf, since that by itself will evaluate to True or False. I doubt there is any appreciable performance difference, but just a small thing to note.

Title: SSRS tablix visibility

Body:
I have a multi-parameter report in SSRS where I want to display or hide a report depending on the parameter selection.  If the user selects only one facility from a multi-value facility parameter then I want a second report to display along with the main report(it would be a separate tab).  If multiple facilities are chosen then I only want the main report to display.

I've been playing with the visibility expressions on the second report but I can't seem to get it to work.

I've tried:

   =IFF(Parameters!entity.IsMultiValue, "True", "False")

but that returns an error "The hidden expression used in tablix returned a data type that is not valid.

I've also tried:

   =IIF(Parameters!entity.Count = 1), "False", "True")

But I get the same error.  I'm using SSRS 2016.


来源: stackexchange

问:
Thread freezes program
I have a function:

```<code>def threaded(fn):
    def wrapper(*args, **kwargs):
        thread = threading.Thread(target=fn, args=args, kwargs=kwargs)
        thread.start()
        return thread
    return wrapper
</code>```

And a class:

```<code>class someclass(somestuff):
    def __init__(self, parent=None):
        super(thing)
        .
        .
        .

    @threaded
    def start_thread(self):
        while True:
            self.update_watchers()

    def update_watchers(self):
        .
        .
        .

    def otherfunctions(self):
        .
        .
        .
        .
</code>```

And in my main:

```<code>obj = someclass()
handle = obj.start_thread()
handle.join()
</code>```

Now, if I take the while loop out of start_thread, everything works fine. I suspect I am using forever-threads long (a forever thread is a thread that runs as long as the program is running, of course).

As an FYI, this program occupies a list. Not a Python list, a GUI list. It looks into a file that is constantly being updated. update_watchers() updates the watchers I have running over the file, extracts information when (for example) the program is paused (which is one of the several reasons why I need a thread).

Can someone explain to me what is going on? It keeps breaking when I get to handle's definition. I know I must be using the While loop wrong and there is a correct way to do it. I need start_thread to run all the time because I need update_watchers to be running all the time.

I cant really post more code than that.

Thank you

Edit: threaded function taken from this post

答:
The call to handle.join() waits until the thread represented by handle completes.  Since it has a while True it will never complete, and thus the join will never terminate.
You almost certainly don't want to join on a thread you intend to run forever.
Solving your problem is likely as simple as removing handle.join().

ContentLicense: CC BY-SA 3.0

Title: Thread freezes program

Body:
I have a function:

def threaded(fn):
    def wrapper(*args, **kwargs):
        thread = threading.Thread(target=fn, args=args, kwargs=kwargs)
        thread.start()
        return thread
    return wrapper

And a class:

class someclass(somestuff):
    def __init__(self, parent=None):
        super(thing)
        .
        .
        .

    @threaded
    def start_thread(self):
        while True:
            self.update_watchers()

    def update_watchers(self):
        .
        .
        .

    def otherfunctions(self):
        .
        .
        .
        .

And in my main:

obj = someclass()
handle = obj.start_thread()
handle.join()

Now, if I take the while loop out of start_thread, everything works fine. I suspect I am using forever-threads long (a forever thread is a thread that runs as long as the program is running, of course).

As an FYI, this program occupies a list. Not a Python list, a GUI list. It looks into a file that is constantly being updated. update_watchers() updates the watchers I have running over the file, extracts information when (for example) the program is paused (which is one of the several reasons why I need a thread).

Can someone explain to me what is going on? It keeps breaking when I get to handle's definition. I know I must be using the While loop wrong and there is a correct way to do it. I need start_thread to run all the time because I need update_watchers to be running all the time.

I cant really post more code than that.

Thank you

Edit: threaded function taken from this post


问:
InstaPy - Python - how to give a specific insta account 500 followers
I have a Ubuntu server and i installed / setup InstaPy on it:
https://github.com/timgrossmann/InstaPy

Everything works fine on the server.
But how can i give a specific insta account +500 followers?

I don't have the password of the account and the account is open for public.

I can execute quickstart.py with python quickstart.py

I tried this but how can i give up a specific account without password to give that account 500 followers?

```<code>from instapy import InstaPy

insta_username = 'SpecificAccountName'
insta_password = ''

# if you want to run this script on a server,
# simply add nogui=True to the InstaPy() constructor
session = InstaPy(username=insta_username, password=insta_password,nogui=True)
session.login()

# set up all the settings
session.set_upper_follower_count(limit=500)

# do the actual liking
session.like_by_tags(['natgeo', 'world'], amount=100)

# end the bot session
session.end()
</code>```

答:
You can't simply give an account 500 followers, that is not how InstaPy works.
The idea is to interact with other users content and get interaction back.

You also need the username and password of the account to be used, I'm sorry.

You might need to try one of the "Buy Instagram xyz" services.

Thank you

Body:
I have a Ubuntu server and i installed / setup InstaPy on it:
https://github.com/timgrossmann/InstaPy

Everything works fine on the server.
But how can i give a specific insta account +500 followers?

I don't have the password of the account and the account is open for public.

I can execute quickstart.py with python quickstart.py

I tried this but how can i give up a specific account without password to give that account 500 followers?

from instapy import InstaPy

insta_username = 'SpecificAccountName'
insta_password = ''

# if you want to run this script on a server,
# simply add nogui=True to the InstaPy() constructor
session = InstaPy(username=insta_username, password=insta_password,nogui=True)
session.login()

# set up all the settings
session.set_upper_follower_count(limit=500)

# do the actual liking
session.like_by_tags(['natgeo', 'world'], amount=100)

# end the bot session
session.end()


问:
changing arrowhead type in networkx
I am plotting directed graph using networkx in python. However, I found that arrow head of edge is thick from one end instead of pointed arrow. I want to change the thick edge to pointed arrow. Here is my code, actual output, and desired output:

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

G=nx.DiGraph()

item = [1,2]

G.add_edge(*item) #color = item[-1], weight = 2)

pos = nx.circular_layout(G)
nx.draw(G, pos, with_labels = True, edge_color = 'b')
plt.show()
</code>```

Output

Desired output:

Any suggestion would be really helpful?

答:
This is not possible with nx.draw for now. According to https://github.com/networkx/networkx/blob/master/networkx/drawing/nx_pylab.py#L584 , it hasn't been implemented yet.

However, you can try to use graphviz to plot your graph. Networkx has an interface to convert your graph to graphviz object easily. See https://networkx.github.io/documentation/stable/reference/drawing.html#module-networkx.drawing.nx_agraph.

Title: changing arrowhead type in networkx

Body:
I am plotting directed graph using networkx in python. However, I found that arrow head of edge is thick from one end instead of pointed arrow. I want to change the thick edge to pointed arrow. Here is my code, actual output, and desired output:

import networkx as nx
import matplotlib.pyplot as plt

G=nx.DiGraph()

item = [1,2]

G.add_edge(*item) #color = item[-1], weight = 2)

pos = nx.circular_layout(G)
nx.draw(G, pos, with_labels = True, edge_color = 'b')
plt.show()

Output

Desired output:

Any suggestion would be really helpful?


问:
Correlation of two arrays in C#
Having two arrays of double values, I want to compute correlation coefficient (single double value, just like the CORREL function in MS Excel). Is there some simple one-line solution in C#?

I already discovered math lib called Meta Numerics. According to this SO question, it should do the job. Here is docs for Meta Numerics correlation method, which I don't get.

Could pls somebody provide me with simple code snippet or example how to use the library?

Note: At the end, I was forced to use one of custom implementations.
  But if someone reading this question knows good, well documented C#
  math library/framework to do this, please don't hesitate and post a link in
  answer.

答:
In my tests, both @Dmitry Bychenko's and @keyboardP's code postings above resulted in generally the same correlations as Microsoft Excel over a handful of manual tests I did, and did not need any external libraries.

e.g. Running this once (data for this run listed at the bottom):

@Dmitry Bychenko: -0.00418479432051121

@keyboardP:______-0.00418479432051131

MS Excel:_________-0.004184794

Here is a test harness:

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TestCorrel {
    class Program {

        static void Main(string[] args) {

            Random rand = new Random(DateTime.Now.Millisecond);

            List<double> x = new List<double>();
            List<double> y = new List<double>();

            for (int i = 0; i < 100; i++) {

                x.Add(rand.Next(1000) * rand.NextDouble());
                y.Add(rand.Next(1000) * rand.NextDouble());

                Console.WriteLine(x[i] + "," + y[i]);
            }

            Console.WriteLine("Correl1: " + Correl1(x, y));
            Console.WriteLine("Correl2: " + Correl2(x, y));
        }

        public static double Correl1(List<double> x, List<double> y) {

            //https://stackoverflow.com/questions/17447817/correlation-of-two-arrays-in-c-sharp
            if (x.Count != y.Count)
                return (double.NaN); //throw new ArgumentException("values must be the same length");

            double sumX = 0;
            double sumX2 = 0;
            double sumY = 0;
            double sumY2 = 0;
            double sumXY = 0;

            int n = x.Count < y.Count ? x.Count : y.Count;

            for (int i = 0; i < n; ++i) {

                Double xval = x[i];
                Double yval = y[i];

                sumX += xval;
                sumX2 += xval * xval;
                sumY += yval;
                sumY2 += yval * yval;
                sumXY += xval * yval;
            }

            Double stdX = Math.Sqrt(sumX2 / n - sumX * sumX / n / n);
            Double stdY = Math.Sqrt(sumY2 / n - sumY * sumY / n / n);
            Double covariance = (sumXY / n - sumX * sumY / n / n);

            return covariance / stdX / stdY;
        }

        public static double Correl2(List<double> x, List<double> y) {

            double[] array_xy = new double[x.Count];
            double[] array_xp2 = new double[x.Count];
            double[] array_yp2 = new double[x.Count];

            for (int i = 0; i < x.Count; i++)
                array_xy[i] = x[i] * y[i];
            for (int i = 0; i < x.Count; i++)
                array_xp2[i] = Math.Pow(x[i], 2.0);
            for (int i = 0; i < x.Count; i++)
                array_yp2[i] = Math.Pow(y[i], 2.0);
            double sum_x = 0;
            double sum_y = 0;
            foreach (double n in x)
                sum_x += n;
            foreach (double n in y)
                sum_y += n;
            double sum_xy = 0;
            foreach (double n in array_xy)
                sum_xy += n;
            double sum_xpow2 = 0;
            foreach (double n in array_xp2)
                sum_xpow2 += n;
            double sum_ypow2 = 0;
            foreach (double n in array_yp2)
                sum_ypow2 += n;
            double Ex2 = Math.Pow(sum_x, 2.00);
            double Ey2 = Math.Pow(sum_y, 2.00);

            double Correl =
            (x.Count * sum_xy - sum_x * sum_y) /
            Math.Sqrt((x.Count * sum_xpow2 - Ex2) * (x.Count * sum_ypow2 - Ey2));

            return (Correl);
        }
    }
}
</code>```

Data for the example numbers above:

```<code>287.688269702572,225.610842817282
618.9313498167,177.955550192835
25.7778882802361,27.6549569366756
140.847984766051,714.618547504125
438.618761728806,533.48764902702
481.347431274758,214.381256273194
21.6406916848573,393.559209519792
135.30397563209,158.419851317732
334.314685154853,814.275162949821
764.614904770914,50.1435267264692
42.8179292282173,47.8631582287434
237.216836650491,370.488416981179
388.849658539449,134.961087643151
305.903013161804,441.926902444068
10.6625048679591,369.567569480076
36.9316453891488,24.8947204607049
2.10067253471383,491.941975629861
7.94887068492774,573.037801189831
341.738006353722,653.497146697015
98.8424873439793,475.215988045193
272.248712629196,36.1088809138671
122.336823399801,169.158256422336
9.32281673202422,631.076001565473
201.118425176068,803.724831627554
415.514343714115,64.248651454341
227.791637123,230.512133914284
25.3438658925443,396.854282886188
596.238994411304,72.543763144195
230.239735877253,933.983901697669
796.060099040186,689.952468971234
9.30882684202344,269.22063744125
16.5005430148451,8.96549091859045
536.324005148524,358.829873788557
519.694526420764,17.3212184707267
552.628357889423,12.5541588051962
210.516099897454,388.57537739937
141.341571405689,268.082028986924
503.880356335491,753.447006912645
515.494990213539,444.451280259737
973.8670776076,168.922799013985
85.7111146094795,36.3784999169309
37.2147129193017,108.040356312432
504.590177939548,50.3934166889607
482.821039277511,888.984586256083
5.52549206350255,156.717087003271
405.833169031345,394.099059180868
459.249365587835,11.68776424494
429.421127440604,314.216759666901
126.908422469584,331.907062556551
62.1416232716952,3.19765723645578
4.16058817699579,604.04046284223
484.262182311277,220.177370167886
58.6774453314382,339.09660232677
463.482149892246,199.181594849183
344.128297473829,268.531428258182
0.883430369609702,209.346384477963
77.9462970131758,255.221325168955
583.629439312792,235.557751925922
358.409186083083,376.046612200349
81.2148325150902,10.7696774717279
53.7315618049966,274.171515094196
111.284646992239,130.174321939319
317.280491961763,338.077288461885
177.454564264722,7.53587801919127
69.2239431670047,233.693477620228
823.419546454875,0.111916855029723
23.7174749401014,200.989081544331
44.9598299125022,102.633862571155
74.1602278468945,292.485449988155
130.11182449251,23.4682153367755
243.088760058903,335.807090202722
13.3974915991526,436.983231269281
73.3900805168739,252.352352472186
592.144630201228,92.3395205570103
57.7306153447044,47.1416798900541
522.649018382024,584.427794722108
15.3662010204821,60.1693953262499
16.8335716728277,851.401980430541
33.9869734449251,0.930781653584345
116.66608504982,146.126050951949
92.8896130355492,711.765618208687
317.91980889529,322.186540377413
44.8574470732629,209.275617858058
751.201537871362,37.935519233316
161.817758424588,2.83156183493862
531.64078452142,79.1750782491523
114.803219681048,283.106988439852
123.472725123853,154.125248027558
89.9276725453919,63.4626924192825
105.623296753328,111.234188702067
435.72981759707,23.7058234576629
259.324810619152,69.3535200857341
719.885234421531,381.086239833891
24.2674900099018,198.408173349876
57.7761600361095,146.52277489124
77.4594609157459,710.746080866431
636.671781979814,538.894185951396
56.6035279932448,58.2563265684323
485.16099039333,427.849954283261
91.9552873247095,576.92944263617
</code>```

Title: Correlation of two arrays in C#

Body:
In my tests, both @Dmitry Bychenko's and @keyboardP's code postings above resulted in generally the same correlations as Microsoft Excel over a handful of manual tests I did, and did not need any external libraries.

e.g. Running this once (data for this run listed at the bottom):

@Dmitry Bychenko: -0.00418479432051121

@keyboardP:______-0.00418479432051131

MS Excel:_________-0.004184794

Here is a test harness:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TestCorrel {
    class Program {

        static void Main(string[] args) {

            Random rand = new Random(DateTime.Now.Millisecond);

            List<double> x = new List<double>();
            List<double> y = new List<double>();

            for (int i = 0; i < 100; i++) {

                x.Add(rand.Next(1000) * rand.NextDouble());
                y.Add(rand.Next(1000) * rand.NextDouble());

                Console.WriteLine(x[i] + "," + y[i]);
            }

            Console.WriteLine("Correl1: " + Correl1(x, y));
            Console.WriteLine("Correl2: " + Correl2(x, y));
        }

        public static double Correl1(List<double> x, List<double> y) {

            //https://stackoverflow.com/questions/17447817/correlation-of-two-arrays-in-c-sharp
            if (x.Count != y.Count)
                return (double.NaN); //throw new ArgumentException("values must be the same length");

            double sumX = 0;
            double sumX2 = 0;
            double sumY = 0;
            double sumY2 = 0;
            double sumXY = 0;

            int n = x.Count < y.Count ? x.Count : y.Count;

            for (int i = 0; i < n; ++i) {

                Double xval = x[i];
                Double yval = y[i];

                sumX += xval;
                sumX2 += xval * xval;
                sumY += yval;
                sumY2 += yval * yval;
                sumXY += xval * yval;
            }

            Double stdX = Math.Sqrt(sumX2 / n - sumX * sumX / n / n);
            Double stdY = Math.Sqrt(sumY2 / n - sumY * sumY / n / n);
            Double covariance = (sumXY / n - sumX * sumY / n / n);

            return covariance / stdX / stdY;
        }

        public static double Correl2(List<double> x, List<double> y) {

            double[] array_xy = new double[x.Count];
            double[] array_xp2 = new double[x.Count];
            double[] array_yp2 = new double[x.Count];

            for (int i = 0; i < x.Count; i++)
                array_xy[i] = x[i] * y[i];
            for (int i = 0; i < x.Count; i++)
                array_xp2[i] = Math.Pow(x[i], 2.0);
            for (int i = 0; i < x.Count; i++)
                array_yp2[i] = Math.Pow(y[i], 2.0);
            double sum_x = 0;
            double sum_y = 0;
            foreach (double n in x)
                sum_x += n;
            foreach (double n in y)
                sum_y += n;
            double sum_xy = 0;
            foreach (double n in array_xy)
                sum_xy += n;
            double sum_xpow2 = 0;
            foreach (double n in array_xp2)
                sum_xpow2 += n;
            double sum_ypow2 = 0;
            foreach (double n in array_yp2)
                sum_ypow2 += n;
            double Ex2 = Math.Pow(sum_x, 2.00);
            double Ey2 = Math.Pow(sum_y, 2.00);

            double Correl =
            (x.Count * sum_xy - sum_x * sum_y) /
            Math.Sqrt((x.Count * sum_xpow2 - Ex2) * (x.Count * sum_ypow2 - Ey2));

            return (Correl);
        }
    }
}

Data for the example numbers above:

287.688269702572,225.610842817282
618.9313498167,177.955550192835
25.7778882802361,27.6549569366756
140.847984766051,714.618547504125
438.618761728806,533.48764902702
481.347431274758,214.381256273194
21.6406916848573,393.559209519792
135.30397563209,158.419851317732
334.314685154853,814.275162949821
764.614904770914,50.1435267264692
42.8179292282173,47.8631582287434
237.216836650491,370.488416981179
388.849658539449,134.961087643151
305.903013161804,441.926902444068
10.6625048679591,369.567569480076
36.9316453891488,24.8947204607049
2.10067253471383,491.941975629861
7.94887068492774,573.037801189831
341.738006353722,653.497146697015
98.8424873439793,475.215988045193
272.248712629196,36.1088809138671
122.336823399801,169.158256422336
9.32281673202422,631.076001565473
201.118425176068,803.724831627554
415.514343714115,64.248651454341
227.791637123,230.512133914284
25.3438658925443,396.854282886188
596.238994411304,72.543763144195
230.239735877253,933.983901697669
796.060099040186,689.952468971234
9.30882684202344,269.22063744125
16.5005430148451,8.96549091859045
536.324005148524,358.829873788557
519.694526420764,17.3212184707267
552.628357889423,12.5541588051962
210.516099897454,388.57537739937
141.341571405689,268.082028986924
503.880356335491,753.447006912645
515.494990213539,444.451280259737
973.8670776076,168.922799013985
85.7111146094795,36.3784999169309
37.2147129193017,108.040356312432
504.590177939548,50.3934166889607
482.821039277511,888.984586256083
5.52549206350255,156.717087003271
405.833169031345,394.099059180868
459.249365587835,11.68776424494
429.421127440604,314.216759666901
126.908422469584,331.907062556551
62.1416232716952,3.19765723645578
4.16058817699579,604.04046284223
484.262182311277,220.177370167886
58.6774453314382,339.09660232677
463.482149892246,199.181594849183
344.128297473829,268.531428258182
0.883430369609702,209.346384477963
77.9462970131758,255.221325168955
583.629439312792,235.557751925922
358.409186083083,376.046612200349
81.2148325150902,10.7696774717279
53.7315618049966,274.171515094196
111.284646992239,130.174321939319
317.280491961763,338.077288461885
177.454564264722,7.53587801919127
69.2239431670047,233.693477620228
823.419546454875,0.111916855029723
23.7174749401014,200.989081544331
44.9598299125022,102.633862571155
74.1602278468945,292.485449988155
130.11182449251,23.4682153367755
243.088760058903,335.807090202722
13.3974915991526,436.983231269281
73.3900805168739,252.352352472186
592.144630201228,92.3395205570103
57.7306153447044,47.1416798900541
522.649018382024,584.427794722108
15.3662010204821,60.1693953262499
16.8335716728277,851.401980430541
33.9869734449251,0.930781653584345
116.66608504982,146.126050951949
92.8896130355492,711.765618208687
317.91980889529,322.186540377413
44.8574470732629,209.275617858058
751.201537871362,37.935519233316
161.817758424588,2.83156183493862
531.64078452142,79.1750782491523
114.803219681048,283.106988439852
123.472725123853,154.125248027558
89.9276725453919,63.4626924192825
105.623296753328,111.234188702067
435.72981759707,23.7058234576629
259.324810619152,69.3535200857341
719.885234421531,381.086239833891
24.2674900099018,198.408173349876
57.7761600361095,146.52277489124
77.4594609157459,710.746080866431
636.671781979814,538.894185951396
56.6035279932448,58.2563265684323
485.16099039333,427.849954283261
91.9552873247095,576.92944263617


问:
Continuous to discrete legend on ggplot2 R

I am trying to plot curves with ggplot2 and group them by maturities. In my dataset maturities are expressed in remaining time in years.

My problem is that in my whole dataset I only have two maturities (0.15 and 0.2) but the legend displays color for 0.15, 0.16, 0.17...

Here is a screenshot :

Here is my code :

```<code>    call_vol_plot = ggplot(data=df[df$type=="C",],
       aes(x=strike,
           y=impliedVol,
           group = time_to_expiry,
           colour = time_to_expiry)) + geom_line() + geom_point(size=4, shape=21, fill="white")

    call_vol_plot = call_vol_plot + labs(title="Call Implied Volatility",
                           subtitle="Options on future contracts",
                           y="Implied Volatility",
                           x="Strike") + guides(color=guide_legend("Maturity in year"))
</code>```

I tried scale_color_discrete but it didn't work. Thank you !

答:
Within aes, convert the time_to_expiry to factor as.factor(time_to_expiry)

and

```<code>+ scale_color_manual(values = c(0.15, 0.2))
</code>```

Body:
I am trying to plot curves with ggplot2 and group them by maturities. In my dataset maturities are expressed in remaining time in years.

My problem is that in my whole dataset I only have two maturities (0.15 and 0.2) but the legend displays color for 0.15, 0.16, 0.17...

Here is a screenshot :

Here is my code :

    call_vol_plot = ggplot(data=df[df$type=="C",],
       aes(x=strike,
           y=impliedVol,
           group = time_to_expiry,
           colour = time_to_expiry)) + geom_line() + geom_point(size=4, shape=21, fill="white")

    call_vol_plot = call_vol_plot + labs(title="Call Implied Volatility",
                           subtitle="Options on future contracts",
                           y="Implied Volatility",
                           x="Strike") + guides(color=guide_legend("Maturity in year"))

I tried scale_color_discrete but it didn't work. Thank you !

Body:
Within aes, convert the time_to_expiry to factor as.factor(time_to_expiry)

and

+ scale_color_manual(values = c(0.15, 0.2))


问:
Haskell : convert Either ParseError a to a
I'm actually using Parsec to make an Expression Parser and I have a little question (I'm french also sorry for my english ).

I have this code :

```<code>data Expression ... -- Recursive type Expression

type Store [(String, Float)] -- variable's storage

type Parser a = Parsec String () a
parseExpr :: [Char] -> Either ParseError Expression
parseExpr string = parse expr "" stream
    where
        stream = filter (not . isSpace) string

-- Parser's rules ...

raiseError a = Nothing

evalParser :: [Char] -> Store -> Float
evalParser expr store = fromMaybe 0 (either raiseError (eval store)(parseExpr expr))
</code>```

This code works really well, but i need this function :

```<code>parseExpression :: String -> Maybe Expression
</code>```

And I have no ideas of the right syntax to use.

Someone can help me please ?

答:
I'll start it for you, and you can finish it:

```<code>eitherToMaybe :: Either a b -> Maybe b
eitherToMaybe (Left a) = ???
eitherToMaybe (Right b) = ???
</code>```

A severe over-generalization looks like this (you can find this function with a less direct implementation in the monadplus package):

```<code>import Control.Applicative (Alternative (..))
import Data.Profunctor.Unsafe ((#.))
import Data.Monoid (Alt (..))

afold :: (Foldable f, Alternative g)
                      => f a -> g a
afold = getAlt . foldMap (Alt #. pure)
</code>```

But you don't really need to get into that business just yet.

Body:
I'm actually using Parsec to make an Expression Parser and I have a little question (I'm french also sorry for my english ).

I have this code :

data Expression ... -- Recursive type Expression

type Store [(String, Float)] -- variable's storage

type Parser a = Parsec String () a
parseExpr :: [Char] -> Either ParseError Expression
parseExpr string = parse expr "" stream
    where
        stream = filter (not . isSpace) string

-- Parser's rules ...

raiseError a = Nothing

evalParser :: [Char] -> Store -> Float
evalParser expr store = fromMaybe 0 (either raiseError (eval store)(parseExpr expr))

This code works really well, but i need this function :

parseExpression :: String -> Maybe Expression

And I have no ideas of the right syntax to use.

Someone can help me please ?

Body:
I'll start it for you, and you can finish it:

eitherToMaybe :: Either a b -> Maybe b
eitherToMaybe (Left a) = ???
eitherToMaybe (Right b) = ???

A severe over-generalization looks like this (you can find this function with a less direct implementation in the monadplus package):

import Control.Applicative (Alternative (..))
import Data.Profunctor.Unsafe ((#.))
import Data.Monoid (Alt (..))

afold :: (Foldable f, Alternative g)
                      => f a -> g a
afold = getAlt . foldMap (Alt #. pure)

But you don't really need to get into that business just yet.


问:
Setup Azure API management as proxy to forward and cache API calls
In the project I'm working on, we have a system where we have a back-end application which will handle the authentication/authorization, and through this the front-end clients will send requests and receive responses to/from other services.

Now we are also contemplating adding Azure API management to the mix, placing it in-between the back-end and other services, as a passthrough, solely because we want to take advantage of the API caching feature.

Does this sound like a good idea? Is this actually an use-case for Azure API management or should I reconsider my project's architecture.

答:
If all you are looking for is an intermediary cache for a single region, you might find API Management overkill for your needs.  Although, it would be an easy way to get started.

Consider if you might want add in rate limiting, request/response logging and analytics in the future. Or if you might want an intermediary to handle routing for versioning.  Or if you need to do geo-distributed caching.  If some of those features may be useful in the future, then putting Azure API Management in might be a quick way to get started and prepare you for the future.


问:
Join loop on multiple files, filling empty fields
I have 28 files I'd like to join on column 1, keeping all results from both files with each iterative join, and filling empty columns with 0. There are two columns total. The expected input and output for the first 3 files:

File1

```<code>a   1
b   2
c   1
d   4
</code>```

File2

```<code>a   2
b   3

</code>```

File3

```<code>c   2
d   2
e   1

</code>```

joined

```<code>a   1   2   0
b   2   3   0
c   1   0   2
d   4   0   2
e   0   0   1
</code>```

I've written out the entire join using a pipe on my actual files, and it works but is obviously messy. I've shortened it with ellipses here for clarity:

```<code>join -t $'\t' -a 1 -a 2 -e '0' -o 0 1.2 2.2 -1 1 -2 1 *D3-E-N-1*/*matrix.txt.cut *D3-E-N-2*/*matrix.txt.cut | join -t $'\t' -a 1 -a 2 -e '0' -o 0 1.2 1.3 2.2 -1 1 -2 1 - *D3-E-N-3*/*matrix.txt.cut | join -t $'\t' -a 1 -a 2 -e '0' -o 0 1.2 1.3 1.4 2.2 -1 1 -2 1 - *D3-E-N-4*/*matrix.txt.cut | join -t $'\t' -a 1 -a 2 -e '0' -o 0 1.2 1.3 1.4 1.5 2.2 -1 1 -2 1 - *D3-E-N-5*/*matrix.txt.cut | ... > final.matrix.txt
</code>```

I know this can be looped to add the new fields, but I'm new to programming and loops are not my forte. I've tried this (from here bash join multiple files with empty replacement (-e option)):

```<code>i=3
orderl='0,1.2'
orderr=',2.2'
for k in UNITAS*/*seq_cut
do
    if [ -a final.results ]
    then
        join -a1 -a2 -e "0" -o "$orderl$orderr" final.results $k  > tmp.res
        orderl="$orderl,1.$i"
        i=$((i+1))
        mv tmp.res final.results
    else
        cp $k final.results
    fi
done
</code>```

which gives me the error

[: too many arguments

[: too many arguments

cp: overwrite ‘final.results’?

Does anyone have suggestions on a script to recursively join files, or a program better suited for this task?

Much appreciated!

答:
I am quite amazed that your pipe-line worked; I couldn't get it to work myself. Also, your input-files and output-files do not seem to match. But that aside:

Join will only join two columns: a key and a field.This means that you need to need some way to separate the key from the fields, otherwise you will loose previously joined columns.

example:
f1:

```<code>a   1
b   2
c   1
d   4
</code>```

f2:

```<code>a   2
b   3
</code>```

f3:

c    2
   d    2
   e    1

```<code>$ join -a1 -a2 -e "0" -t'       ' -o "0,1.2,2.2" f1 f2
a   1   2
b   2   3
c   1   0
d   4   0
$ join -a1 -a2 -e "0" -t'       ' -o "0,1.2,2.2" f1 f2 > f4
$ join -a1 -a2 -e "0" -t'       ' -o "0,1.2,2.2" f4 f3
a   1   0
b   2   0
c   1   2
d   4   2
e   0   1
</code>```

Which is not what you want.

You could change the first tab to ; and join and then change back, but if the later files introduce new keys, it would give you half lines for the keys that are not present in the first file.

Adding a file to the joins with just the keys will create a column wit zeroes which must also be removed.

You probably have some wild-card to list all your files, in my example that could be f?, but yours could be file.* or *.cols etc. Try the wild-card with ls to be sure.

So, putting that together:

```<code>#first make a key-file k0
cat f?  | cut -f1  | sort -u > k0
# change the separator to ';' and back
for f in f? ; do
    sed 's/\t/;/' k0 > t0
    sed 's/\t/;/' $f > t1
    join -a1 -a2 -e "0" -t';' -o "0,1.2,2.2" t0 t1 | sed 's/;/\t/g' > k0
done
# remove the '0' column from the key-file
sed 's/\t0\t/\t/' k0
</code>```

or have a look at awk.

Body:
I have 28 files I'd like to join on column 1, keeping all results from both files with each iterative join, and filling empty columns with 0. There are two columns total. The expected input and output for the first 3 files:

File1

a   1
b   2
c   1
d   4

File2

a   2
b   3

File3

c   2
d   2
e   1

joined

a   1   2   0
b   2   3   0
c   1   0   2
d   4   0   2
e   0   0   1

I've written out the entire join using a pipe on my actual files, and it works but is obviously messy. I've shortened it with ellipses here for clarity:

join -t $'\t' -a 1 -a 2 -e '0' -o 0 1.2 2.2 -1 1 -2 1 *D3-E-N-1*/*matrix.txt.cut *D3-E-N-2*/*matrix.txt.cut | join -t $'\t' -a 1 -a 2 -e '0' -o 0 1.2 1.3 2.2 -1 1 -2 1 - *D3-E-N-3*/*matrix.txt.cut | join -t $'\t' -a 1 -a 2 -e '0' -o 0 1.2 1.3 1.4 2.2 -1 1 -2 1 - *D3-E-N-4*/*matrix.txt.cut | join -t $'\t' -a 1 -a 2 -e '0' -o 0 1.2 1.3 1.4 1.5 2.2 -1 1 -2 1 - *D3-E-N-5*/*matrix.txt.cut | ... > final.matrix.txt

I know this can be looped to add the new fields, but I'm new to programming and loops are not my forte. I've tried this (from here bash join multiple files with empty replacement (-e option)):

i=3
orderl='0,1.2'
orderr=',2.2'
for k in UNITAS*/*seq_cut
do
    if [ -a final.results ]
    then
        join -a1 -a2 -e "0" -o "$orderl$orderr" final.results $k  > tmp.res
        orderl="$orderl,1.$i"
        i=$((i+1))
        mv tmp.res final.results
    else
        cp $k final.results
    fi
done

which gives me the error

[: too many arguments

[: too many arguments

cp: overwrite ‘final.results’?

Does anyone have suggestions on a script to recursively join files, or a program better suited for this task?

Much appreciated!

Body:
I am quite amazed that your pipe-line worked; I couldn't get it to work myself. Also, your input-files and output-files do not seem to match. But that aside:

Join will only join two columns: a key and a field.This means that you need to need some way to separate the key from the fields, otherwise you will loose previously joined columns.

example:
f1:

a   1
b   2
c   1
d   4

f2:

a   2
b   3

f3:

c    2
   d    2
   e    1

$ join -a1 -a2 -e "0" -t'       ' -o "0,1.2,2.2" f1 f2
a   1   2
b   2   3
c   1   0
d   4   0
$ join -a1 -a2 -e "0" -t'       ' -o "0,1.2,2.2" f1 f2 > f4
$ join -a1 -a2 -e "0" -t'       ' -o "0,1.2,2.2" f4 f3
a   1   0
b   2   0
c   1   2
d   4   2
e   0   1

Which is not what you want.

You could change the first tab to ; and join and then change back, but if the later files introduce new keys, it would give you half lines for the keys that are not present in the first file.

Adding a file to the joins with just the keys will create a column wit zeroes which must also be removed.

You probably have some wild-card to list all your files, in my example that could be f?, but yours could be file.* or *.cols etc. Try the wild-card with ls to be sure.

So, putting that together:

#first make a key-file k0
cat f?  | cut -f1  | sort -u > k0
# change the separator to ';' and back
for f in f? ; do
    sed 's/\t/;/' k0 > t0
    sed 's/\t/;/' $f > t1
    join -a1 -a2 -e "0" -t';' -o "0,1.2,2.2" t0 t1 | sed 's/;/\t/g' > k0
done
# remove the '0' column from the key-file
sed 's/\t0\t/\t/' k0

or have a look at awk.


问:
JavaFX textfield backspace not working
I have a textfield  in java

```<code>    TextField addTask = new TextField();
    addTask.setPromptText("Task");
    addTask.addEventHandler(KeyEvent.KEY_PRESSED, new EventHandler<KeyEvent>(){
        public void handle(KeyEvent event) {
            System.out.println(event.getCode());
         }
     });
</code>```

Everything here works,except the backspace button.When i click it BACK_SPACE is being shown in the console,but nothing gets deleted from the field.Why is that?

答:
Try this</p>

```<code>TextField addTask = new TextField();
addTask.setPromptText("Task");
addTask.setOnKeyPressed(ke-> System.out.println(ke.getCode()));
</code>```

Title: JavaFX textfield backspace not working

Body:
I have a textfield  in java

    TextField addTask = new TextField();
    addTask.setPromptText("Task");
    addTask.addEventHandler(KeyEvent.KEY_PRESSED, new EventHandler<KeyEvent>(){
        public void handle(KeyEvent event) {
            System.out.println(event.getCode());
         }
     });

Everything here works,except the backspace button.When i click it BACK_SPACE is being shown in the console,but nothing gets deleted from the field.Why is that?

Body:
Try this

TextField addTask = new TextField();
addTask.setPromptText("Task");
addTask.setOnKeyPressed(ke-> System.out.println(ke.getCode()));


问:
Laravel 5.0.* middleware to remove prefix locale from url before routes are processed
I am looking for a way to make all app route's have multiple locales without using route groups. This is because I use an external extensions package, which means routes are registered in many places.

Essentially I want to have /foo/bar as well as /en/foo/bar, /de/foor/bar, /es/foo/bar etc all to be recognised and processed by the /foot/bar route

```<code> Route::get('foo/bar', function () {
     return App::getLocale() . ' result';
 });
</code>```

So the above would give me 'en result' or 'de result' or 'es result'.

I already have middleware that sets the locale based on the path segment. I have tried the following with no luck.

```<code>   ...
   $newPath =  str_replace($locale,'',$request->path());

   $request->server->set('REQUEST_URI',$new_path);

 }

 return $next($request);
</code>```

Hopefully this is possible, or there is some other way of achieving it.

EDIT------

Based on a comment below I quickly hacked it by adding the following code into public/index.php. Hopefully this will give a better idea of what i'm trying to achieve by editing the request object.

```<code>$application_url_segments = explode( '/', trim( $_SERVER["REQUEST_URI"], '/' ) );

$application_locale = $application_url_segments[0];

$application_locales = ['en' => 'English', 'de' => 'German'];

if ( array_key_exists( $application_locale, $application_locales ) ) {

    $_SERVER["REQUEST_URI"] = str_replace( '/' . $application_locale,'',$_SERVER["REQUEST_URI"] );

}
</code>```

答:
none of this actually worked for me with 5.5. The approach is good, but for me the request-argument did not get injected into the register method, likewise instance() is not a static method and should not be called as such.

However, using the service container to aquire an instance of Request made it possible to change the request-path before it is parsed inside the ServiceProviders register method:

```<code>public function register()
{
  $this->app->make('Illuminate\Http\Request')->instance()->server->set('REQUEST_URI',"/what/ever/");
}
</code>```

I hope this helps somebody!

Cheers

edit: Pastor's answer is technically more correct as he uses the Facade instead of the actual Class. However, the injection of neither works on register but you can alternatively use:

```<code>use \Illuminate\Support\Facades\Request
//...
public function register()
{
  Request::instance()->server->set('REQUEST_URI',"/what/ever/");
}
</code>```

Body:
I am looking for a way to make all app route's have multiple locales without using route groups. This is because I use an external extensions package, which means routes are registered in many places.

Essentially I want to have /foo/bar as well as /en/foo/bar, /de/foor/bar, /es/foo/bar etc all to be recognised and processed by the /foot/bar route

 Route::get('foo/bar', function () {
     return App::getLocale() . ' result';
 });

So the above would give me 'en result' or 'de result' or 'es result'.

I already have middleware that sets the locale based on the path segment. I have tried the following with no luck.

   ...
   $newPath =  str_replace($locale,'',$request->path());

   $request->server->set('REQUEST_URI',$new_path);

 }

 return $next($request);

Hopefully this is possible, or there is some other way of achieving it.

EDIT------

Based on a comment below I quickly hacked it by adding the following code into public/index.php. Hopefully this will give a better idea of what i'm trying to achieve by editing the request object.

$application_url_segments = explode( '/', trim( $_SERVER["REQUEST_URI"], '/' ) );

$application_locale = $application_url_segments[0];

$application_locales = ['en' => 'English', 'de' => 'German'];

if ( array_key_exists( $application_locale, $application_locales ) ) {

    $_SERVER["REQUEST_URI"] = str_replace( '/' . $application_locale,'',$_SERVER["REQUEST_URI"] );

}

Body:
none of this actually worked for me with 5.5. The approach is good, but for me the request-argument did not get injected into the register method, likewise instance() is not a static method and should not be called as such.

However, using the service container to aquire an instance of Request made it possible to change the request-path before it is parsed inside the ServiceProviders register method:

public function register()
{
  $this->app->make('Illuminate\Http\Request')->instance()->server->set('REQUEST_URI',"/what/ever/");
}

I hope this helps somebody!

Cheers

edit: Pastor's answer is technically more correct as he uses the Facade instead of the actual Class. However, the injection of neither works on register but you can alternatively use:

use \Illuminate\Support\Facades\Request
//...
public function register()
{
  Request::instance()->server->set('REQUEST_URI',"/what/ever/");
}


问:
How to get the last dir from a path in a string
I am trying to get the last folder name from a path that i store in a string.

e.g: Home/new_folder/test

```<code>result = test
</code>```

答:
Explode turns the string into an array, you can then choose the last value in that array to be your result.</p>

```<code>$result = end((explode('/', $path)));
</code>```

Body:
I am trying to get the last folder name from a path that i store in a string.

e.g: Home/new_folder/test

result = test

Body:
Explode turns the string into an array, you can then choose the last value in that array to be your result.

$result = end((explode('/', $path)));


问:
EXEC sp_executesql is slow
I have a stored procedure like this:

declare @where nvarchar(max)

```<code>set @where=' where 1=1 '
if(@IsSimNha is not null)
    set @where+=' and s.IsSimNha=@IsSimNha'
if(@IsSearchSimPSC is not null)
    set @where+=' and s.HanPhaiPhatSinhLai<=@HanPhaiPhatSinhLai'
if(@GiaTu is not null)
    set @where+=' and s.AgentPrice>=@GiaTu'
if(@GiaDen is not null)
    set @where+=' and s.AgentPrice<=@GiaDen'
if(@AgentID is not null)
    set @where+=' and s.AgentId=@AgentID'
if(@NhaMangId is not null)
    set @where+=' and s.NhaMangId=@NhaMangId'
if(@TinhTrangID is not null)
    set @where+=' and s.StatusId=@TinhTrangID'
if(@NgayNhapTu is not null)
    set @where+=' and s.NgayNhapSim>=@NgayNhapTu'
if(@NgayNhapDen is not null)
    set @where+=' and s.NgayNhapSim<=@NgayNhapDen'

if(@NgayPscTu is not null)
    set @where+=' and s.NgayPhatSinhCuoc>=@NgayPscTu'
if(@NgayPscDen is not null)
    set @where+=' and s.NgayPhatSinhCuoc<=@NgayPscDen'

if(@HanPSCTu is not null)
    set @where+=' and s.HanPhaiPhatSinhLai>=@HanPSCTu'
if(@HanPSCDen is not null)
    set @where+=' and s.HanPhaiPhatSinhLai<=@HanPSCDen'

if(@HanSuDungTu is not null)
    set @where+=' and s.HanSuDung>=@HanSuDungTu'
if(@HanSuDungDen is not null)
    set @where+=' and s.HanSuDung<=@HanSuDungDen'
if(@SoSeri is not null)
    set @where+=' and s.SoSeri<=@SoSeri'
if(@Lenght is not null)
    set @where+=' and LEN(s.Number) = @Lenght'
if(@SearchDau is not null)
    set @where+=' and s.Number like @SearchDau+''%'''
if(@SearchGiua is not null)
    set @where+=' and s.Number like ''%''+@SearchGiua+''%'''
if(@SearchCuoi is not null)
    set @where+=' and s.Number like ''%''+@SearchCuoi'

set @sql = 'declare @TotalItemCount int;'
set @sql+= ' select  @TotalItemCount=count(1)
            from sims s with (NOLOCK) '
            +@where
set @sql+=' select @TotalItemCount TotalItemCount, s.SimId,s.Number, s.DisplayNumber, s.AgentId,ag.Email,ag.Mobile2,s.NhaMangId,s.StatusId,s.SalelPrice,
s.SaleOffPrice,s.Commisions,s.AgentPrice,s.HoaHong,s.IsShow,s.DateCreated,ag.AgentName,s.SoSeri,s.SimTypeId,
s.NgayPhatSinhCuoc,s.HanPhaiPhatSinhLai,s.MaCaNhan,s.SoPhatSinhCuoc,s.HanSuDung,s.GhiChu,s.SoTienCamKet,s.SoThangCamKet,
s.NgayKichHoat, s.NgayNhapSim,s.IsSimNha,s.CoHoTroTraGop,s.GhiChuTraGop,s.ViTriId
from sims s with (NOLOCK) left join Agents ag with (NOLOCK) on s.AgentID=ag.AgentID ' +@where

declare @orderbysql nvarchar(max);

if(@OrderBy='SalelPrice')
begin
    if(@SortBy=1)
        set @orderbysql= N' ORDER BY s.SalelPrice asc '
    else set @orderbysql= N' ORDER BY s.SalelPrice desc '
end
else if(@OrderBy='SaleOffPrice')
begin
    if(@SortBy=1)
        set @orderbysql= N' ORDER BY s.SaleOffPrice asc '
    else set @orderbysql= N' ORDER BY s.SaleOffPrice desc '
end
else if(@OrderBy='AgentPrice')
begin
    if(@SortBy=1)
        set @orderbysql= N' ORDER BY s.AgentPrice asc '
    else set @orderbysql= N' ORDER BY s.AgentPrice desc '
end
else if(@OrderBy='NgayPSC')
begin
    if(@SortBy=1)
        set @orderbysql= N' ORDER BY s.NgayPSC asc '
    else set @orderbysql= N' ORDER BY s.NgayPSC desc '
end
else if(@OrderBy='HanPhatSinhCuoc')
begin
    if(@SortBy=1)
        set @orderbysql= N' ORDER BY s.HanPhatSinhCuoc asc '
    else set @orderbysql= N' ORDER BY s.HanPhatSinhCuoc desc '
end
else if(@OrderBy='HanSuDung')
begin
    if(@SortBy=1)
        set @orderbysql= N' ORDER BY s.HanSuDung asc '
    else set @orderbysql= N' ORDER BY s.HanSuDung desc '
end
else if(@OrderBy='NgayNhapSim')
begin
    if(@SortBy=1)
        set @orderbysql= N' ORDER BY s.NgayNhapSim asc '
    else set @orderbysql= N' ORDER BY s.NgayNhapSim desc '
end
else if(@OrderBy='Number')
begin
    if(@SortBy=1)
        set @orderbysql= N' ORDER BY s.Number asc '
    else set @orderbysql= N' ORDER BY s.Number desc '
end
else if(@OrderBy='TenDaiLy')
begin
    if(@SortBy=1)
        set @orderbysql= N' ORDER BY s.TenDaiLy asc '
    else set @orderbysql= N' ORDER BY s.TenDaiLy desc '
end
else if(@OrderBy='SoSeri')
begin
    if(@SortBy=1)
        set @orderbysql= N' ORDER BY s.SoSeri asc '
    else set @orderbysql= N' ORDER BY s.SoSeri desc '
end
else
begin
    if(@SortBy=1)
    begin
        if(@IsSimNha=1)
            set @orderbysql= N' ORDER BY s.HanPhatSinhCuoc asc '
        else set @orderbysql= N' ORDER BY s.SimId asc '
    end
    else
    begin
        if(@IsSimNha=1)
            set @orderbysql= N' ORDER BY s.HanPhatSinhCuoc desc '
        else set @orderbysql= N' ORDER BY s.SimId desc '
    end

end
set @orderbysql+=' OFFSET (@PageNum-1)* @PageSize ROWS FETCH NEXT @PageSize ROWS ONLY'
set @sql+=@orderbysql

print @sql
EXEC sp_executesql @sql,N'@IsSimNha bit,@IsSearchSimPSC bit, @HanPhaiPhatSinhLai datetime,@GiaTu decimal(18,0),@GiaDen decimal(18,0),@NhaMangId int,@AgentID int,
@TinhTrangID int,@NgayNhapTu datetime,@NgayNhapDen datetime,@NgayPscTu datetime,@NgayPscDen datetime,@HanPSCTu datetime,@HanPSCDen datetime,@HanSuDungTu datetime,
@HanSuDungDen datetime,@SoSeri nvarchar(30),@Lenght int,@SearchDau nvarchar(30),@SearchGiua nvarchar(30),@SearchCuoi nvarchar(30),@PageNum int,@PageSize int ',@IsSimNha ,@IsSearchSimPSC , @HanPhaiPhatSinhLai ,@GiaTu ,@GiaDen,@NhaMangId ,@AgentID ,
@TinhTrangID ,@NgayNhapTu ,@NgayNhapDen ,@NgayPscTu ,@NgayPscDen ,@HanPSCTu ,@HanPSCDen ,@HanSuDungTu ,
@HanSuDungDen ,@SoSeri ,@Lenght ,@SearchDau ,@SearchGiua ,@SearchCuoi,@PageNum,@PageSize
</code>```

It takes more than 3 seconds to complete.

But when I take script result to run like this:

```<code>select
    @TotalItemCount TotalItemCount, s.SimId,s.Number, s.DisplayNumber,
    s.AgentId, ag.Email, ag.Mobile2, s.NhaMangId, s.StatusId, s.SalelPrice,
    s.SaleOffPrice, s.Commisions, s.AgentPrice, s.HoaHong, s.IsShow,
    s.DateCreated, ag.AgentName, s.SoSeri, s.SimTypeId,
    s.NgayPhatSinhCuoc, s.HanPhaiPhatSinhLai, s.MaCaNhan, s.SoPhatSinhCuoc,
    s.HanSuDung, s.GhiChu, s.SoTienCamKet, s.SoThangCamKet,
    s.NgayKichHoat, s.NgayNhapSim, s.IsSimNha, s.CoHoTroTraGop,
    s.GhiChuTraGop, s.ViTriId
from
    sims s with (NOLOCK)
left join
    Agents ag with (NOLOCK) on s.AgentID = ag.AgentID
where
    s.Number like '0973688639'+'%'
order by
    s.SimId desc
    OFFSET 0 ROWS FETCH NEXT 50 ROWS ONLY
</code>```

and runs, it's take only 0.02s

I don't know why it's slow like that.

Note: @sql variable = second script.

Somebody can help me?

Thanks all

答:
I suggest that you take a deep look to your data types, specially nvarchar, I recall multiple issues with execution plans that utilize index scan instead of index seek just because the data types do not match your indexes.

EG (ASP.NET C#):

```<code>SqlCommand command = new SqlCommand();
command.CommandText = "SELECT [COLUMN2] FROM [TABLE] WHERE COLUMN1 = @value";
command.Parameters.AddWithValue("@value", orderNumber);

exec sp_executesql N'SELECT [COLUMN2] FROM [TABLE] WHERE COLUMN1 = @Value',N'@Value nvarchar(32)',@Value=N'b12af2381c8a40e7aaf6f682e209b2ed'
</code>```

this is wrong because our table use varchar[32] for the COLUMN1 and this generate by default a query with NVARCHAR[32] type. The right way is to specify the type:

```<code>SqlCommand command = new SqlCommand();
command.CommandText = "SELECT [COLUMN2] FROM [TABLE] WHERE COLUMN1 = @value";
command.Parameters.Add("@value", SqlDbType.VarChar, 32);
command.Parameters["@value"].Value = orderNumber; enter code here

exec sp_executesql N'SELECT [COLUMN2] FROM [TABLE] WHERE COLUMN1 = @Value',N'@Value varchar(32)',@Value=N'b12af2381c8a40e7aaf6f682e209b2ed'
</code>```

believe it or not this make a huge difference in performance depending on your table size and indexes.

Hope it helps,

Title: EXEC sp_executesql is slow

Body:
I have a stored procedure like this:

declare @where nvarchar(max)

set @where=' where 1=1 '
if(@IsSimNha is not null)
    set @where+=' and s.IsSimNha=@IsSimNha'
if(@IsSearchSimPSC is not null)
    set @where+=' and s.HanPhaiPhatSinhLai<=@HanPhaiPhatSinhLai'
if(@GiaTu is not null)
    set @where+=' and s.AgentPrice>=@GiaTu'
if(@GiaDen is not null)
    set @where+=' and s.AgentPrice<=@GiaDen'
if(@AgentID is not null)
    set @where+=' and s.AgentId=@AgentID'
if(@NhaMangId is not null)
    set @where+=' and s.NhaMangId=@NhaMangId'
if(@TinhTrangID is not null)
    set @where+=' and s.StatusId=@TinhTrangID'
if(@NgayNhapTu is not null)
    set @where+=' and s.NgayNhapSim>=@NgayNhapTu'
if(@NgayNhapDen is not null)
    set @where+=' and s.NgayNhapSim<=@NgayNhapDen'

if(@NgayPscTu is not null)
    set @where+=' and s.NgayPhatSinhCuoc>=@NgayPscTu'
if(@NgayPscDen is not null)
    set @where+=' and s.NgayPhatSinhCuoc<=@NgayPscDen'

if(@HanPSCTu is not null)
    set @where+=' and s.HanPhaiPhatSinhLai>=@HanPSCTu'
if(@HanPSCDen is not null)
    set @where+=' and s.HanPhaiPhatSinhLai<=@HanPSCDen'

if(@HanSuDungTu is not null)
    set @where+=' and s.HanSuDung>=@HanSuDungTu'
if(@HanSuDungDen is not null)
    set @where+=' and s.HanSuDung<=@HanSuDungDen'
if(@SoSeri is not null)
    set @where+=' and s.SoSeri<=@SoSeri'
if(@Lenght is not null)
    set @where+=' and LEN(s.Number) = @Lenght'
if(@SearchDau is not null)
    set @where+=' and s.Number like @SearchDau+''%'''
if(@SearchGiua is not null)
    set @where+=' and s.Number like ''%''+@SearchGiua+''%'''
if(@SearchCuoi is not null)
    set @where+=' and s.Number like ''%''+@SearchCuoi'

set @sql = 'declare @TotalItemCount int;'
set @sql+= ' select  @TotalItemCount=count(1)
            from sims s with (NOLOCK) '
            +@where
set @sql+=' select @TotalItemCount TotalItemCount, s.SimId,s.Number, s.DisplayNumber, s.AgentId,ag.Email,ag.Mobile2,s.NhaMangId,s.StatusId,s.SalelPrice,
s.SaleOffPrice,s.Commisions,s.AgentPrice,s.HoaHong,s.IsShow,s.DateCreated,ag.AgentName,s.SoSeri,s.SimTypeId,
s.NgayPhatSinhCuoc,s.HanPhaiPhatSinhLai,s.MaCaNhan,s.SoPhatSinhCuoc,s.HanSuDung,s.GhiChu,s.SoTienCamKet,s.SoThangCamKet,
s.NgayKichHoat, s.NgayNhapSim,s.IsSimNha,s.CoHoTroTraGop,s.GhiChuTraGop,s.ViTriId
from sims s with (NOLOCK) left join Agents ag with (NOLOCK) on s.AgentID=ag.AgentID ' +@where

declare @orderbysql nvarchar(max);

if(@OrderBy='SalelPrice')
begin
    if(@SortBy=1)
        set @orderbysql= N' ORDER BY s.SalelPrice asc '
    else set @orderbysql= N' ORDER BY s.SalelPrice desc '
end
else if(@OrderBy='SaleOffPrice')
begin
    if(@SortBy=1)
        set @orderbysql= N' ORDER BY s.SaleOffPrice asc '
    else set @orderbysql= N' ORDER BY s.SaleOffPrice desc '
end
else if(@OrderBy='AgentPrice')
begin
    if(@SortBy=1)
        set @orderbysql= N' ORDER BY s.AgentPrice asc '
    else set @orderbysql= N' ORDER BY s.AgentPrice desc '
end
else if(@OrderBy='NgayPSC')
begin
    if(@SortBy=1)
        set @orderbysql= N' ORDER BY s.NgayPSC asc '
    else set @orderbysql= N' ORDER BY s.NgayPSC desc '
end
else if(@OrderBy='HanPhatSinhCuoc')
begin
    if(@SortBy=1)
        set @orderbysql= N' ORDER BY s.HanPhatSinhCuoc asc '
    else set @orderbysql= N' ORDER BY s.HanPhatSinhCuoc desc '
end
else if(@OrderBy='HanSuDung')
begin
    if(@SortBy=1)
        set @orderbysql= N' ORDER BY s.HanSuDung asc '
    else set @orderbysql= N' ORDER BY s.HanSuDung desc '
end
else if(@OrderBy='NgayNhapSim')
begin
    if(@SortBy=1)
        set @orderbysql= N' ORDER BY s.NgayNhapSim asc '
    else set @orderbysql= N' ORDER BY s.NgayNhapSim desc '
end
else if(@OrderBy='Number')
begin
    if(@SortBy=1)
        set @orderbysql= N' ORDER BY s.Number asc '
    else set @orderbysql= N' ORDER BY s.Number desc '
end
else if(@OrderBy='TenDaiLy')
begin
    if(@SortBy=1)
        set @orderbysql= N' ORDER BY s.TenDaiLy asc '
    else set @orderbysql= N' ORDER BY s.TenDaiLy desc '
end
else if(@OrderBy='SoSeri')
begin
    if(@SortBy=1)
        set @orderbysql= N' ORDER BY s.SoSeri asc '
    else set @orderbysql= N' ORDER BY s.SoSeri desc '
end
else
begin
    if(@SortBy=1)
    begin
        if(@IsSimNha=1)
            set @orderbysql= N' ORDER BY s.HanPhatSinhCuoc asc '
        else set @orderbysql= N' ORDER BY s.SimId asc '
    end
    else
    begin
        if(@IsSimNha=1)
            set @orderbysql= N' ORDER BY s.HanPhatSinhCuoc desc '
        else set @orderbysql= N' ORDER BY s.SimId desc '
    end

end
set @orderbysql+=' OFFSET (@PageNum-1)* @PageSize ROWS FETCH NEXT @PageSize ROWS ONLY'
set @sql+=@orderbysql

print @sql
EXEC sp_executesql @sql,N'@IsSimNha bit,@IsSearchSimPSC bit, @HanPhaiPhatSinhLai datetime,@GiaTu decimal(18,0),@GiaDen decimal(18,0),@NhaMangId int,@AgentID int,
@TinhTrangID int,@NgayNhapTu datetime,@NgayNhapDen datetime,@NgayPscTu datetime,@NgayPscDen datetime,@HanPSCTu datetime,@HanPSCDen datetime,@HanSuDungTu datetime,
@HanSuDungDen datetime,@SoSeri nvarchar(30),@Lenght int,@SearchDau nvarchar(30),@SearchGiua nvarchar(30),@SearchCuoi nvarchar(30),@PageNum int,@PageSize int ',@IsSimNha ,@IsSearchSimPSC , @HanPhaiPhatSinhLai ,@GiaTu ,@GiaDen,@NhaMangId ,@AgentID ,
@TinhTrangID ,@NgayNhapTu ,@NgayNhapDen ,@NgayPscTu ,@NgayPscDen ,@HanPSCTu ,@HanPSCDen ,@HanSuDungTu ,
@HanSuDungDen ,@SoSeri ,@Lenght ,@SearchDau ,@SearchGiua ,@SearchCuoi,@PageNum,@PageSize

It takes more than 3 seconds to complete.

But when I take script result to run like this:

select
    @TotalItemCount TotalItemCount, s.SimId,s.Number, s.DisplayNumber,
    s.AgentId, ag.Email, ag.Mobile2, s.NhaMangId, s.StatusId, s.SalelPrice,
    s.SaleOffPrice, s.Commisions, s.AgentPrice, s.HoaHong, s.IsShow,
    s.DateCreated, ag.AgentName, s.SoSeri, s.SimTypeId,
    s.NgayPhatSinhCuoc, s.HanPhaiPhatSinhLai, s.MaCaNhan, s.SoPhatSinhCuoc,
    s.HanSuDung, s.GhiChu, s.SoTienCamKet, s.SoThangCamKet,
    s.NgayKichHoat, s.NgayNhapSim, s.IsSimNha, s.CoHoTroTraGop,
    s.GhiChuTraGop, s.ViTriId
from
    sims s with (NOLOCK)
left join
    Agents ag with (NOLOCK) on s.AgentID = ag.AgentID
where
    s.Number like '0973688639'+'%'
order by
    s.SimId desc
    OFFSET 0 ROWS FETCH NEXT 50 ROWS ONLY

and runs, it's take only 0.02s

I don't know why it's slow like that.

Note: @sql variable = second script.

Somebody can help me?

Thanks all

Body:
I suggest that you take a deep look to your data types, specially nvarchar, I recall multiple issues with execution plans that utilize index scan instead of index seek just because the data types do not match your indexes.

EG (ASP.NET C#):

SqlCommand command = new SqlCommand();
command.CommandText = "SELECT [COLUMN2] FROM [TABLE] WHERE COLUMN1 = @value";
command.Parameters.AddWithValue("@value", orderNumber);

exec sp_executesql N'SELECT [COLUMN2] FROM [TABLE] WHERE COLUMN1 = @Value',N'@Value nvarchar(32)',@Value=N'b12af2381c8a40e7aaf6f682e209b2ed'

this is wrong because our table use varchar[32] for the COLUMN1 and this generate by default a query with NVARCHAR[32] type. The right way is to specify the type:

SqlCommand command = new SqlCommand();
command.CommandText = "SELECT [COLUMN2] FROM [TABLE] WHERE COLUMN1 = @value";
command.Parameters.Add("@value", SqlDbType.VarChar, 32);
command.Parameters["@value"].Value = orderNumber; enter code here

exec sp_executesql N'SELECT [COLUMN2] FROM [TABLE] WHERE COLUMN1 = @Value',N'@Value varchar(32)',@Value=N'b12af2381c8a40e7aaf6f682e209b2ed'

believe it or not this make a huge difference in performance depending on your table size and indexes.

Hope it helps,


问:
SQL - Returning combinations of ID from tables if combination not found in another
I have four tables of interest: users, models, questions and labels.

"Labels" contains rows that describes a user's answer to a question on a model. e.g username TEXT, mid INT, qid INT, answer TEXT

I am interested in finding out what model-question pairs the user is still required to provide. A user is asked to provide an answer for every combination of model and questions that appear in their respective tables. So for a given username, I can have rows of model ids and question ids.

Users:

Bacon, XXXX, XXXX, XXXX, ...

Mark, XXXX, XXXX, XXXX, ...

Models:

1, climateOne, XXXX, ....

2, climateTwo, XXXX, ....

3, climateTwo, XXXX, ....

Questions:

1, "Is this a question?"

2, "And another?"

labels:

Bacon, 1, 2, "Yes is was..."

Bacon, 3, 2, "Another what?!"

So the result of asking "what model question pairs has 'Bacon' not completed" would be the return of:

(1,1)(2,1)(2,2)(3,1)

答:
To get all possible combinations of models and questions, use a cross join:

```<code>SELECT models.id,
       questions.id
FROM models
CROSS JOIN questions
</code>```

Then filter out those that have been completed:

```<code>...
WHERE (models.id, questions.id) NOT IN (SELECT mid, qid
                                        FROM labels);
</code>```

Body:
To get all possible combinations of models and questions, use a cross join:

SELECT models.id,
       questions.id
FROM models
CROSS JOIN questions

Then filter out those that have been completed:

...
WHERE (models.id, questions.id) NOT IN (SELECT mid, qid
                                        FROM labels);


问:
Two different colour edges in directed graph networkx in python
I am trying to compare two graphs and draw a third directed graph in which blue edges represent that these edges are present in both graph, red edges represent that edges present in former graph were no more exist in the latter graph, and green edges represent the edges present in latter graph were not exist in the former graph.

Problem:
In the attached figure, I marked (with black colour) the edge between nodes 'New' and 'Assigned', which is composed of two colours (blue and green) which  composed of two colours which means edge between 'New' to 'Assigned' exist in both graphs. However, an edge between 'Assigned' to 'New' exist in latter graph only. Is there any way I can draw two different colour edges between same nodes. Here is my part of my code I used for drawing this graph.

def multi_draw_circle(list1):

```<code>outerloop = 0

while(outerloop < len(list1)):

    for item in list1[outerloop][:-1]:

        colo = list1[outerloop][-1]
        G.add_edge(*item,color = colo)

    outerloop = outerloop + 1

edges = G.edges()
colors = [G[u][v]['color'] for u,v in edges]
pos = nx.circular_layout(G)
nx.draw(G, pos, with_labels = True, edge_color = colors)

plt.show()

return
</code>```

Any help would be really appreciated. Thanks

答: Besides the comment I had, you might want to try to use graphviz to plot your graph. Networkx has an interface to convert your graph to graphviz object easily. See https://networkx.github.io/documentation/stable/reference/drawing.html#module-networkx.drawing.nx_agraph. The edges are not overlapped there.</p>

Body:
I am trying to compare two graphs and draw a third directed graph in which blue edges represent that these edges are present in both graph, red edges represent that edges present in former graph were no more exist in the latter graph, and green edges represent the edges present in latter graph were not exist in the former graph.

Problem:
In the attached figure, I marked (with black colour) the edge between nodes 'New' and 'Assigned', which is composed of two colours (blue and green) which  composed of two colours which means edge between 'New' to 'Assigned' exist in both graphs. However, an edge between 'Assigned' to 'New' exist in latter graph only. Is there any way I can draw two different colour edges between same nodes. Here is my part of my code I used for drawing this graph.

def multi_draw_circle(list1):

outerloop = 0

while(outerloop < len(list1)):

    for item in list1[outerloop][:-1]:

        colo = list1[outerloop][-1]
        G.add_edge(*item,color = colo)

    outerloop = outerloop + 1

edges = G.edges()
colors = [G[u][v]['color'] for u,v in edges]
pos = nx.circular_layout(G)
nx.draw(G, pos, with_labels = True, edge_color = colors)

plt.show()

return

Any help would be really appreciated. Thanks


问:
Insert Data from old SQL table, to new one with columns changed to rows
I currently have a table that looks similar to this:

Old Table(example only)

I need to import the data to a new table, but making the column headers into rows and value for each one. Similar to this.

New Table(example only)

Would I use a Pivot or an Unpivot to do this? I have a lot of columns with about 700 rows that need to be converted this way.

答:
You should go with unpivot, try the query below. Generally speaking, Pivot reduces the total number of rows while Unpivot increases it, instead.

```<code>select SN,Property,Value

from tbl

unpivot

(Value for Property in (Property1,Property2,Property3,Property4) ) as tblunpvt
</code>```

Body:
You should go with unpivot, try the query below. Generally speaking, Pivot reduces the total number of rows while Unpivot increases it, instead.

select SN,Property,Value

from tbl

unpivot

(Value for Property in (Property1,Property2,Property3,Property4) ) as tblunpvt


问:
Angular 2 external lib error
I generate my angular 2 lib with yeoman generator and added to main angular project. If i compile app in dev mode i haven't error, but if i run prod mode, i get many errors:

```<code>WARNING in ./src/$$_gendir/app/services/main/main.component.ngfactory.ts
142:86-92 "export 'ɵb' (imported as 'i15') was not found in 'ngx-tel-input'
at HarmonyImportSpecifierDependency._getErrors (/Users/franke/projects/work/jsapp/node_modules/webpack/lib/dependencies/HarmonyImportSpecifierDependency.js:65:15)
at HarmonyImportSpecifierDependency.getWarnings (/Users/franke/projects/work/jsapp/node_modules/webpack/lib/dependencies/HarmonyImportSpecifierDependency.js:39:15)
at Compilation.reportDependencyErrorsAndWarnings (/Users/franke/projects/work/jsapp/node_modules/webpack/lib/Compilation.js:677:24)
at Compilation.finish (/Users/franke/projects/work/jsapp/node_modules/webpack/lib/Compilation.js:535:9)
at applyPluginsParallel.err (/Users/franke/projects/work/jsapp/node_modules/webpack/lib/Compiler.js:512:17)
at /Users/franke/projects/work/jsapp/node_modules/tapable/lib/Tapable.js:271:11
at _addModuleChain (/Users/franke/projects/work/jsapp/node_modules/webpack/lib/Compilation.js:481:11)
at processModuleDependencies.err (/Users/franke/projects/work/jsapp/node_modules/webpack/lib/Compilation.js:452:13)
at _combinedTickCallback (internal/process/next_tick.js:73:7)
at process._tickCallback (internal/process/next_tick.js:104:9)

WARNING in ./src/$$_gendir/app/services/main/main.component.ngfactory.ts
144:12-18 "export 'ɵb' (imported as 'i15') was not found in 'ngx-tel-input'
at HarmonyImportSpecifierDependency._getErrors (/Users/franke/projects/work/jsapp/node_modules/webpack/lib/dependencies/HarmonyImportSpecifierDependency.js:65:15)
at HarmonyImportSpecifierDependency.getWarnings (/Users/franke/projects/work/jsapp/node_modules/webpack/lib/dependencies/HarmonyImportSpecifierDependency.js:39:15)
at Compilation.reportDependencyErrorsAndWarnings (/Users/franke/projects/work/jsapp/node_modules/webpack/lib/Compilation.js:677:24)
at Compilation.finish (/Users/franke/projects/work/jsapp/node_modules/webpack/lib/Compilation.js:535:9)
at applyPluginsParallel.err (/Users/franke/projects/work/jsapp/node_modules/webpack/lib/Compiler.js:512:17)
at /Users/franke/projects/work/jsapp/node_modules/tapable/lib/Tapable.js:271:11
at _addModuleChain (/Users/franke/projects/work/jsapp/node_modules/webpack/lib/Compilation.js:481:11)
at processModuleDependencies.err (/Users/franke/projects/work/jsapp/node_modules/webpack/lib/Compilation.js:452:13)
at _combinedTickCallback (internal/process/next_tick.js:73:7)
at process._tickCallback (internal/process/next_tick.js:104:9)

WARNING in ./src/$$_gendir/node_modules/ngx-tel-input/ngx-tel-input.ngfactory.ts
148:12-17 "export 'ɵb' (imported as 'i1') was not found in 'ngx-tel-input'
at HarmonyImportSpecifierDependency._getErrors (/Users/franke/projects/work/jsapp/node_modules/webpack/lib/dependencies/HarmonyImportSpecifierDependency.js:65:15)
at HarmonyImportSpecifierDependency.getWarnings (/Users/franke/projects/work/jsapp/node_modules/webpack/lib/dependencies/HarmonyImportSpecifierDependency.js:39:15)
at Compilation.reportDependencyErrorsAndWarnings (/Users/franke/projects/work/jsapp/node_modules/webpack/lib/Compilation.js:677:24)
at Compilation.finish (/Users/franke/projects/work/jsapp/node_modules/webpack/lib/Compilation.js:535:9)
at applyPluginsParallel.err (/Users/franke/projects/work/jsapp/node_modules/webpack/lib/Compiler.js:512:17)
at /Users/franke/projects/work/jsapp/node_modules/tapable/lib/Tapable.js:271:11
at _addModuleChain (/Users/franke/projects/work/jsapp/node_modules/webpack/lib/Compilation.js:481:11)
at processModuleDependencies.err (/Users/franke/projects/work/jsapp/node_modules/webpack/lib/Compilation.js:452:13)
at _combinedTickCallback (internal/process/next_tick.js:73:7)
at process._tickCallback (internal/process/next_tick.js:104:9)

WARNING in ./src/$$_gendir/node_modules/ngx-tel-input/ngx-tel-input.ngfactory.ts
148:46-51 "export 'ɵb' (imported as 'i1') was not found in 'ngx-tel-input'
at HarmonyImportSpecifierDependency._getErrors (/Users/franke/projects/work/jsapp/node_modules/webpack/lib/dependencies/HarmonyImportSpecifierDependency.js:65:15)
at HarmonyImportSpecifierDependency.getWarnings (/Users/franke/projects/work/jsapp/node_modules/webpack/lib/dependencies/HarmonyImportSpecifierDependency.js:39:15)
at Compilation.reportDependencyErrorsAndWarnings (/Users/franke/projects/work/jsapp/node_modules/webpack/lib/Compilation.js:677:24)
at Compilation.finish (/Users/franke/projects/work/jsapp/node_modules/webpack/lib/Compilation.js:535:9)
at applyPluginsParallel.err (/Users/franke/projects/work/jsapp/node_modules/webpack/lib/Compiler.js:512:17)
at /Users/franke/projects/work/jsapp/node_modules/tapable/lib/Tapable.js:271:11
at _addModuleChain (/Users/franke/projects/work/jsapp/node_modules/webpack/lib/Compilation.js:481:11)
at processModuleDependencies.err (/Users/franke/projects/work/jsapp/node_modules/webpack/lib/Compilation.js:452:13)
at _combinedTickCallback (internal/process/next_tick.js:73:7)
at process._tickCallback (internal/process/next_tick.js:104:9)

WARNING in ./src/$$_gendir/node_modules/ngx-tel-input/ngx-tel-input.ngfactory.ts
152:46-51 "export 'ɵb' (imported as 'i1') was not found in 'ngx-tel-input'
at HarmonyImportSpecifierDependency._getErrors (/Users/franke/projects/work/jsapp/node_modules/webpack/lib/dependencies/HarmonyImportSpecifierDependency.js:65:15)
at HarmonyImportSpecifierDependency.getWarnings (/Users/franke/projects/work/jsapp/node_modules/webpack/lib/dependencies/HarmonyImportSpecifierDependency.js:39:15)
at Compilation.reportDependencyErrorsAndWarnings (/Users/franke/projects/work/jsapp/node_modules/webpack/lib/Compilation.js:677:24)
at Compilation.finish (/Users/franke/projects/work/jsapp/node_modules/webpack/lib/Compilation.js:535:9)
at applyPluginsParallel.err (/Users/franke/projects/work/jsapp/node_modules/webpack/lib/Compiler.js:512:17)
at /Users/franke/projects/work/jsapp/node_modules/tapable/lib/Tapable.js:271:11
at _addModuleChain (/Users/franke/projects/work/jsapp/node_modules/webpack/lib/Compilation.js:481:11)
at processModuleDependencies.err (/Users/franke/projects/work/jsapp/node_modules/webpack/lib/Compilation.js:452:13)
at _combinedTickCallback (internal/process/next_tick.js:73:7)
at process._tickCallback (internal/process/next_tick.js:104:9)

ERROR in ng:///Users/franke/projects/work/jsapp/node_modules/ngx-tel-input/ngx-tel-input.d.ts.ɵb.html (4,6): Property 'number' does not exist on type 'TelInputComponent'.
</code>```

What's the problem and how i can solve it?

PS
My lib: https://github.com/LPgenerator/ngx-tel-input

答: Your intent was probably to export just what is needed, but you need to export everything from your src/index.ts file, including all the services, directives, and pipes.

Title: Angular 2 external lib error

Body:
I generate my angular 2 lib with yeoman generator and added to main angular project. If i compile app in dev mode i haven't error, but if i run prod mode, i get many errors:

WARNING in ./src/$$_gendir/app/services/main/main.component.ngfactory.ts
142:86-92 "export 'ɵb' (imported as 'i15') was not found in 'ngx-tel-input'
at HarmonyImportSpecifierDependency._getErrors (/Users/franke/projects/work/jsapp/node_modules/webpack/lib/dependencies/HarmonyImportSpecifierDependency.js:65:15)
at HarmonyImportSpecifierDependency.getWarnings (/Users/franke/projects/work/jsapp/node_modules/webpack/lib/dependencies/HarmonyImportSpecifierDependency.js:39:15)
at Compilation.reportDependencyErrorsAndWarnings (/Users/franke/projects/work/jsapp/node_modules/webpack/lib/Compilation.js:677:24)
at Compilation.finish (/Users/franke/projects/work/jsapp/node_modules/webpack/lib/Compilation.js:535:9)
at applyPluginsParallel.err (/Users/franke/projects/work/jsapp/node_modules/webpack/lib/Compiler.js:512:17)
at /Users/franke/projects/work/jsapp/node_modules/tapable/lib/Tapable.js:271:11
at _addModuleChain (/Users/franke/projects/work/jsapp/node_modules/webpack/lib/Compilation.js:481:11)
at processModuleDependencies.err (/Users/franke/projects/work/jsapp/node_modules/webpack/lib/Compilation.js:452:13)
at _combinedTickCallback (internal/process/next_tick.js:73:7)
at process._tickCallback (internal/process/next_tick.js:104:9)

WARNING in ./src/$$_gendir/app/services/main/main.component.ngfactory.ts
144:12-18 "export 'ɵb' (imported as 'i15') was not found in 'ngx-tel-input'
at HarmonyImportSpecifierDependency._getErrors (/Users/franke/projects/work/jsapp/node_modules/webpack/lib/dependencies/HarmonyImportSpecifierDependency.js:65:15)
at HarmonyImportSpecifierDependency.getWarnings (/Users/franke/projects/work/jsapp/node_modules/webpack/lib/dependencies/HarmonyImportSpecifierDependency.js:39:15)
at Compilation.reportDependencyErrorsAndWarnings (/Users/franke/projects/work/jsapp/node_modules/webpack/lib/Compilation.js:677:24)
at Compilation.finish (/Users/franke/projects/work/jsapp/node_modules/webpack/lib/Compilation.js:535:9)
at applyPluginsParallel.err (/Users/franke/projects/work/jsapp/node_modules/webpack/lib/Compiler.js:512:17)
at /Users/franke/projects/work/jsapp/node_modules/tapable/lib/Tapable.js:271:11
at _addModuleChain (/Users/franke/projects/work/jsapp/node_modules/webpack/lib/Compilation.js:481:11)
at processModuleDependencies.err (/Users/franke/projects/work/jsapp/node_modules/webpack/lib/Compilation.js:452:13)
at _combinedTickCallback (internal/process/next_tick.js:73:7)
at process._tickCallback (internal/process/next_tick.js:104:9)

WARNING in ./src/$$_gendir/node_modules/ngx-tel-input/ngx-tel-input.ngfactory.ts
148:12-17 "export 'ɵb' (imported as 'i1') was not found in 'ngx-tel-input'
at HarmonyImportSpecifierDependency._getErrors (/Users/franke/projects/work/jsapp/node_modules/webpack/lib/dependencies/HarmonyImportSpecifierDependency.js:65:15)
at HarmonyImportSpecifierDependency.getWarnings (/Users/franke/projects/work/jsapp/node_modules/webpack/lib/dependencies/HarmonyImportSpecifierDependency.js:39:15)
at Compilation.reportDependencyErrorsAndWarnings (/Users/franke/projects/work/jsapp/node_modules/webpack/lib/Compilation.js:677:24)
at Compilation.finish (/Users/franke/projects/work/jsapp/node_modules/webpack/lib/Compilation.js:535:9)
at applyPluginsParallel.err (/Users/franke/projects/work/jsapp/node_modules/webpack/lib/Compiler.js:512:17)
at /Users/franke/projects/work/jsapp/node_modules/tapable/lib/Tapable.js:271:11
at _addModuleChain (/Users/franke/projects/work/jsapp/node_modules/webpack/lib/Compilation.js:481:11)
at processModuleDependencies.err (/Users/franke/projects/work/jsapp/node_modules/webpack/lib/Compilation.js:452:13)
at _combinedTickCallback (internal/process/next_tick.js:73:7)
at process._tickCallback (internal/process/next_tick.js:104:9)

WARNING in ./src/$$_gendir/node_modules/ngx-tel-input/ngx-tel-input.ngfactory.ts
148:46-51 "export 'ɵb' (imported as 'i1') was not found in 'ngx-tel-input'
at HarmonyImportSpecifierDependency._getErrors (/Users/franke/projects/work/jsapp/node_modules/webpack/lib/dependencies/HarmonyImportSpecifierDependency.js:65:15)
at HarmonyImportSpecifierDependency.getWarnings (/Users/franke/projects/work/jsapp/node_modules/webpack/lib/dependencies/HarmonyImportSpecifierDependency.js:39:15)
at Compilation.reportDependencyErrorsAndWarnings (/Users/franke/projects/work/jsapp/node_modules/webpack/lib/Compilation.js:677:24)
at Compilation.finish (/Users/franke/projects/work/jsapp/node_modules/webpack/lib/Compilation.js:535:9)
at applyPluginsParallel.err (/Users/franke/projects/work/jsapp/node_modules/webpack/lib/Compiler.js:512:17)
at /Users/franke/projects/work/jsapp/node_modules/tapable/lib/Tapable.js:271:11
at _addModuleChain (/Users/franke/projects/work/jsapp/node_modules/webpack/lib/Compilation.js:481:11)
at processModuleDependencies.err (/Users/franke/projects/work/jsapp/node_modules/webpack/lib/Compilation.js:452:13)
at _combinedTickCallback (internal/process/next_tick.js:73:7)
at process._tickCallback (internal/process/next_tick.js:104:9)

WARNING in ./src/$$_gendir/node_modules/ngx-tel-input/ngx-tel-input.ngfactory.ts
152:46-51 "export 'ɵb' (imported as 'i1') was not found in 'ngx-tel-input'
at HarmonyImportSpecifierDependency._getErrors (/Users/franke/projects/work/jsapp/node_modules/webpack/lib/dependencies/HarmonyImportSpecifierDependency.js:65:15)
at HarmonyImportSpecifierDependency.getWarnings (/Users/franke/projects/work/jsapp/node_modules/webpack/lib/dependencies/HarmonyImportSpecifierDependency.js:39:15)
at Compilation.reportDependencyErrorsAndWarnings (/Users/franke/projects/work/jsapp/node_modules/webpack/lib/Compilation.js:677:24)
at Compilation.finish (/Users/franke/projects/work/jsapp/node_modules/webpack/lib/Compilation.js:535:9)
at applyPluginsParallel.err (/Users/franke/projects/work/jsapp/node_modules/webpack/lib/Compiler.js:512:17)
at /Users/franke/projects/work/jsapp/node_modules/tapable/lib/Tapable.js:271:11
at _addModuleChain (/Users/franke/projects/work/jsapp/node_modules/webpack/lib/Compilation.js:481:11)
at processModuleDependencies.err (/Users/franke/projects/work/jsapp/node_modules/webpack/lib/Compilation.js:452:13)
at _combinedTickCallback (internal/process/next_tick.js:73:7)
at process._tickCallback (internal/process/next_tick.js:104:9)

ERROR in ng:///Users/franke/projects/work/jsapp/node_modules/ngx-tel-input/ngx-tel-input.d.ts.ɵb.html (4,6): Property 'number' does not exist on type 'TelInputComponent'.

What's the problem and how i can solve it?

PS
My lib: https://github.com/LPgenerator/ngx-tel-input


问:
How to run linux daemon in container linked to another container with docker-compose?
I have the following docker-compose.yml file which runs nginx with PHP support:

```<code>version: '3'
services:
  nginx:
    container_name: my-app-nginx
    image: nginx:1.13.6
    ports:
      - 8080:80
    volumes:
      - ./nginx-default.conf:/etc/nginx/conf.d/default.conf
      - ./my-app:/var/www/my-app
    restart: always
    depends_on:
      - php
  php:
    container_name: my-app-php
    image: php:7.1-fpm
    volumes:
      - ./my-app:/var/www/my-app
    restart: always
</code>```

The PHP application inside /var/www/my-app needs to communicate with a linux daemon (let's call it myappd).

The way I see it, I need to either:

Copy the myappd into the nginx container to /usr/local/bin, make it executable with chmod +x and run it in the background.

Create a different container, copy myappd to /usr/local/bin, make it executable with chmod +x and run it in the foreground.

Now, I'm new to Docker and I'm researching and learning about it but my best guess, given that I'm using Docker Composer, is that option 2 is probably the recommended one? Given my limited knowledge about Docker, I'd have to guess that this container would require some sort of linux-based image (like Ubuntu or something) to run this binary. So maybe option 1 is preferred? Or maybe option 2 is possible with a minimal Ubuntu image or maybe it's possible without such image?

Either way, I have no idea how would I implement that on the composer file. Especially option 2, how would the PHP application communicate with the daemon in a different container? Just "sharing" a volume (where the binary is located) like I did for nginx/php services would suffice? Or something else is required?

答:
Simple answer is adding command entry to php service in docker-compose.yml.

Given that myappd is at ./my-app/ on host machine and at /var/www/my-app/, updated docker-compose.yml is something like following.

```<code>version: '3'
services:
  nginx:
    container_name: my-app-nginx
    image: nginx:1.13.6
    ports:
       - 8080:80
    volumes:
      - ./nginx-default.conf:/etc/nginx/conf.d/default.conf
      - ./my-app:/var/www/my-app
    restart: always
    depends_on:
       - php
  php:
    container_name: my-app-php
    image: php:7.1-fpm
    volumes:
      - ./my-app:/var/www/my-app
    restart: always
    command: ["/bin/sh", "/var/www/my-app/mappd", "&&", "php-fpm"]
</code>```

Better answer is to create the third container which runs linux daemon.

New Dockerfile is something like following.

```<code>FROM debian:jessie

COPY ./myappd /usr/src/app/

EXPOSE 44444

ENTRYPOINT ['/bin/sh']
CMD ['/usr/src/app/myappd']
</code>```

Build image and name it myapp/myappd.

Updated docker-compose.yml is something like following.

```<code>version: '3'
services:
  nginx:
    container_name: my-app-nginx
    image: nginx:1.13.6
    ports:
       - 8080:80
    volumes:
      - ./nginx-default.conf:/etc/nginx/conf.d/default.conf
      - ./my-app:/var/www/my-app
    restart: always
    depends_on:
       - php
  php:
    container_name: my-app-php
    image: php:7.1-fpm
    volumes:
      - ./my-app:/var/www/my-app
    restart: always
    networks:
      - network1
    depends_on:
       - daemon
  daemon:
    container_name: my-app-daemon
    image: myapp/myappd
    restart: always
    networks:
      - network1
networks:
  network1:
</code>```

You can send request with hostname daemon from inside php. Docker container has capability to resolve hostname of another container in the same network.

Body:
I have the following docker-compose.yml file which runs nginx with PHP support:

version: '3'
services:
  nginx:
    container_name: my-app-nginx
    image: nginx:1.13.6
    ports:
      - 8080:80
    volumes:
      - ./nginx-default.conf:/etc/nginx/conf.d/default.conf
      - ./my-app:/var/www/my-app
    restart: always
    depends_on:
      - php
  php:
    container_name: my-app-php
    image: php:7.1-fpm
    volumes:
      - ./my-app:/var/www/my-app
    restart: always

The PHP application inside /var/www/my-app needs to communicate with a linux daemon (let's call it myappd).

The way I see it, I need to either:

Copy the myappd into the nginx container to /usr/local/bin, make it executable with chmod +x and run it in the background.

Create a different container, copy myappd to /usr/local/bin, make it executable with chmod +x and run it in the foreground.

Now, I'm new to Docker and I'm researching and learning about it but my best guess, given that I'm using Docker Composer, is that option 2 is probably the recommended one? Given my limited knowledge about Docker, I'd have to guess that this container would require some sort of linux-based image (like Ubuntu or something) to run this binary. So maybe option 1 is preferred? Or maybe option 2 is possible with a minimal Ubuntu image or maybe it's possible without such image?

Either way, I have no idea how would I implement that on the composer file. Especially option 2, how would the PHP application communicate with the daemon in a different container? Just "sharing" a volume (where the binary is located) like I did for nginx/php services would suffice? Or something else is required?

Body:
Simple answer is adding command entry to php service in docker-compose.yml.

Given that myappd is at ./my-app/ on host machine and at /var/www/my-app/, updated docker-compose.yml is something like following.

version: '3'
services:
  nginx:
    container_name: my-app-nginx
    image: nginx:1.13.6
    ports:
       - 8080:80
    volumes:
      - ./nginx-default.conf:/etc/nginx/conf.d/default.conf
      - ./my-app:/var/www/my-app
    restart: always
    depends_on:
       - php
  php:
    container_name: my-app-php
    image: php:7.1-fpm
    volumes:
      - ./my-app:/var/www/my-app
    restart: always
    command: ["/bin/sh", "/var/www/my-app/mappd", "&&", "php-fpm"]

Better answer is to create the third container which runs linux daemon.

New Dockerfile is something like following.

FROM debian:jessie

COPY ./myappd /usr/src/app/

EXPOSE 44444

ENTRYPOINT ['/bin/sh']
CMD ['/usr/src/app/myappd']

Build image and name it myapp/myappd.

Updated docker-compose.yml is something like following.

version: '3'
services:
  nginx:
    container_name: my-app-nginx
    image: nginx:1.13.6
    ports:
       - 8080:80
    volumes:
      - ./nginx-default.conf:/etc/nginx/conf.d/default.conf
      - ./my-app:/var/www/my-app
    restart: always
    depends_on:
       - php
  php:
    container_name: my-app-php
    image: php:7.1-fpm
    volumes:
      - ./my-app:/var/www/my-app
    restart: always
    networks:
      - network1
    depends_on:
       - daemon
  daemon:
    container_name: my-app-daemon
    image: myapp/myappd
    restart: always
    networks:
      - network1
networks:
  network1:

You can send request with hostname daemon from inside php. Docker container has capability to resolve hostname of another container in the same network.


问:
Asp.Net GridView Remove Html Styling
When I'm using a grid view in Asp.Net, its auto-generated this ugly Html style : cellspacing="0" rules="all" border="1"
style="border-collapse:collapse;

Is there a way to not have this styling at all ?

UPDATE

Presently what I got is :

```<code><table cellspacing="0" rules="all" border="1" id="ctl00_cphMain_gvTest" style="border-collapse:collapse;">
</code>```

What I want :

```<code><table id="ctl00_cphMain_gvTest">
</code>```

So, no Html style at all. I want clean Html, I'll use CSS if I want to add style...

答:
Adding:

```<code>CellSpacing="-1" GridLines="None"
</code>```

Will clean the markup considerably generating this in the web page:

```<code><table border="0" id="GridView1">
</code>```

There currently is no way to get rid of the final Border="0" but the above technique does clean up the table considerably.

ContentLicense: CC BY-SA 2.5

Title: Asp.Net GridView Remove Html Styling

Body:
When I'm using a grid view in Asp.Net, its auto-generated this ugly Html style : cellspacing="0" rules="all" border="1"
style="border-collapse:collapse;

Is there a way to not have this styling at all ?

UPDATE

Presently what I got is :

What I want :

So, no Html style at all. I want clean Html, I'll use CSS if I want to add style...

Body:
Adding:

CellSpacing="-1" GridLines="None"

Will clean the markup considerably generating this in the web page:

<table border="0" id="GridView1">

There currently is no way to get rid of the final Border="0" but the above technique does clean up the table considerably.


问:
Is it possible to use express-handlebars tags inside an HTML script tag on the client side?
I have been struggling with this issue for quite some time now. I'm creating an application using express-handlebars and the biggest part of the application works well. Most of the data I want to display on the webpages I'm making is displayed well and I am taking good use of the Helper functions of the express-handlebars module to do so.

Now, the part where I'm stuck is the following. In one of the HTML templates I use in my application, I am using a  tag to display a map with several locations on it using the Google Maps JS API. These locations are coming out of a MongoDB database, just like all of the other template-data I am showing on this page.
The data is coming to the client side here as an array of objects over which I want to iterate, filter out the addresses, geocode them to the correct format and display them in the Map. The problem here is that I can get this array into the page just fine, but I can't get inside of the  as an object through which I can iterate.

Is there any way I can get this array of locations inside the script tags, so I can iterate over them to display them inside of the Map view?

答:
You should be able to do something like this within the template itself:

var data = JSON.stringify(location_data)

var script = 'var data = ' + data

And then inside of your script tag:

include the 'script' variable

write the rest of your client-side code

I'm not super familiar with handlebars syntax, but I know that you can do something similar using express and pug :)

That said, it might just be easier (and cleaner) to request the map data on the client side using an xmlhttp request/ajax?


答:
You can use basename() function:</p>

```<code>$last = basename("Home/new_folder/test");
</code>```

Title: How to get the last dir from a path in a string

Body:
You can use basename() function:

$last = basename("Home/new_folder/test");


问:
Issue with alias in TypeScript and Webpack 3
UPDATE: Solved! Thanks to @JulesRandolph for pointing out the circular dependency issue.

I got a quite stupid-ish situation in the project I am developing at the moment. The project is built around latest version of TypeScript, webpack and awesome-typescript-loader.

The tsconfig contains the following aliases:

```<code>"paths": {
  "~actions" : [
    "app/actions/index.ts"
  ],
  "~components" : [
    "app/components/index.ts"
  ],
  "~helpers" : [
    "app/helpers/index.ts"
  ],
  "~middlewares" : [
    "app/middlewares/index.ts"
  ],
  "~redux" : [
    "app/redux/index.ts"
  ],
  "~styles/*" : [
    "app/styles/*"
  ],
  "~types" : [
    "app/types/index.ts"
  ]
</code>```

The Webpack aliases config shows like this (please note that i also tried without $ and adapting tsconfig for that usage (with/*)):

```<code>{
  '~actions$': '/Users/user/Workspace/prj-name/app/actions/index.ts',
  '~components$': '/Users/user/Workspace/prj-name/app/components/index.ts',
  '~helpers$': '/Users/user/Workspace/prj-name/app/helpers/index.ts',
  '~middlewares$': '/Users/user/Workspace/prj-name/app/middlewares/index.ts',
  '~redux$': '/Users/user/Workspace/prj-name/app/redux/index.ts',
  '~styles': '/Users/user/Workspace/prj-name/app/styles',
  '~types$': '/Users/user/Workspace/prj-name/app/types/index.ts'
}
</code>```

My problem is that, specifically and only for the "app/redux/app.ts" file, I cannot import using the following syntax:

```<code>import {
  imp1,
  imp2
} from '~redux';
</code>```

The imports are coming as undefined. I can, however do this:

```<code>import {
  imp1
} from './[comp-name]';
</code>```

In the other folders I can call using the same syntax (and same folder name). Also, from other folders I can call imports from ~redux.

I tried almost everything I knew and nothing changed.

If anyone is interested, here is the (almost) entire Webpack config: https://pastebin.com/gBabDjH9

答:
The fact an export is resolved as undefined at runtime might well be orthogonal to your webpack config, and instead be caused by circular dependencies.

To inspect this issue, you could

confirm the same bug occurs with importing from ./index. If it does, there is a good chance it's a circular dependency bug.

run madge on your project to identify this circular dep. Something like madge <myTranspiledFolder> --circular. Make sure the files madge run onto are modularized (madge supports AMD, CommonJS, and ES6 modules) and not yet bundled.

Body:
UPDATE: Solved! Thanks to @JulesRandolph for pointing out the circular dependency issue.

I got a quite stupid-ish situation in the project I am developing at the moment. The project is built around latest version of TypeScript, webpack and awesome-typescript-loader.

The tsconfig contains the following aliases:

"paths": {
  "~actions" : [
    "app/actions/index.ts"
  ],
  "~components" : [
    "app/components/index.ts"
  ],
  "~helpers" : [
    "app/helpers/index.ts"
  ],
  "~middlewares" : [
    "app/middlewares/index.ts"
  ],
  "~redux" : [
    "app/redux/index.ts"
  ],
  "~styles/*" : [
    "app/styles/*"
  ],
  "~types" : [
    "app/types/index.ts"
  ]

The Webpack aliases config shows like this (please note that i also tried without $ and adapting tsconfig for that usage (with/*)):

{
  '~actions$': '/Users/user/Workspace/prj-name/app/actions/index.ts',
  '~components$': '/Users/user/Workspace/prj-name/app/components/index.ts',
  '~helpers$': '/Users/user/Workspace/prj-name/app/helpers/index.ts',
  '~middlewares$': '/Users/user/Workspace/prj-name/app/middlewares/index.ts',
  '~redux$': '/Users/user/Workspace/prj-name/app/redux/index.ts',
  '~styles': '/Users/user/Workspace/prj-name/app/styles',
  '~types$': '/Users/user/Workspace/prj-name/app/types/index.ts'
}

My problem is that, specifically and only for the "app/redux/app.ts" file, I cannot import using the following syntax:

import {
  imp1,
  imp2
} from '~redux';

The imports are coming as undefined. I can, however do this:

import {
  imp1
} from './[comp-name]';

In the other folders I can call using the same syntax (and same folder name). Also, from other folders I can call imports from ~redux.

I tried almost everything I knew and nothing changed.

If anyone is interested, here is the (almost) entire Webpack config: https://pastebin.com/gBabDjH9


问:
Possible to use Math.min to get second smallest number from array?
I am using Math.min to get the smallest number out of an array of numbers. However, I also need to get the second smallest number as well. Wondering if there is a way to do this using Math.min as well, otherwise looking for the best way to get this number.

Here's what I have:

var arr = [15, 37, 9, 21, 55];
var min = Math.min.apply(null, arr.filter(Boolean));
var secondMin; // Get second smallest number from array here

console.log('Smallest number: ' + min);
console.log('Second smallest number: ' + secondMin);```

答:
@skyboyer provides what is probably the fastest algorithm for finding the two smallest elements. Another type algorithm that runs in O(n) time is selection (in the general comp-sci definition, not how it is normally used in JavaScript), which will find the kth smallest element of an array and separate the elements into those larger and those smaller than the kth.

Even though most partitioning selection algorithms (quickselect, Floyd-Rivest, introselect) run in O(n) time, @skyboyer's answer will be faster because of the specific nature of the partition you are looking for, and because all those algorithms come with a heavy constant factor.

There is a javascript library implementing Floyd-Rivest, but named quickselect that can do the partitioning for you, in place:

```<code>quickselect(arr, 1)
</code>```

arr will be rearranged so that arr[0] is the minimum, arr[1] is the second smallest element, and the remaining elements are in some arbitrary order.

Body:
@skyboyer provides what is probably the fastest algorithm for finding the two smallest elements. Another type algorithm that runs in O(n) time is selection (in the general comp-sci definition, not how it is normally used in JavaScript), which will find the kth smallest element of an array and separate the elements into those larger and those smaller than the kth.

Even though most partitioning selection algorithms (quickselect, Floyd-Rivest, introselect) run in O(n) time, @skyboyer's answer will be faster because of the specific nature of the partition you are looking for, and because all those algorithms come with a heavy constant factor.

There is a javascript library implementing Floyd-Rivest, but named quickselect that can do the partitioning for you, in place:

quickselect(arr, 1)

arr will be rearranged so that arr[0] is the minimum, arr[1] is the second smallest element, and the remaining elements are in some arbitrary order.


问:
Updating rows in laravel mysql database
I've set up a database and want to update the column status for each row in my UsersController:

I started with this:

```<code>User::where('id', '=', 1)->update(['status' => $status]);
</code>```

This is working, but I need some loop to change all the rows, something like this:

foreach $id from the table

run some code to change individual $status variable

set individual $status value in the 'status' column in each row:

```<code>User::where('id', '=', $id)->update(['status' => $status])
</code>```

end foreach

So for me its unclear how to go through the table via the foreach. Then save the calculated status from my code to each individual id?

答:
Unless the table contains millions of rows... a simple procedural way of doing it is... </p>

```<code>$users = Users::get(); // Gets a collection of all users...
foreach ( $users as $user ) {
    //compute your status
    $user->status = get_your_user_status($user->id);
    $user->save();
}
</code>```

<p>You could also consider using a more functional approach with map for example... </p>

Title: Updating rows in laravel mysql database

Body:
I've set up a database and want to update the column status for each row in my UsersController:

I started with this:

User::where('id', '=', 1)->update(['status' => $status]);

This is working, but I need some loop to change all the rows, something like this:

foreach $id from the table

run some code to change individual $status variable

set individual $status value in the 'status' column in each row:

User::where('id', '=', $id)->update(['status' => $status])

end foreach

So for me its unclear how to go through the table via the foreach. Then save the calculated status from my code to each individual id?

Body:
Unless the table contains millions of rows... a simple procedural way of doing it is...

$users = Users::get(); // Gets a collection of all users...
foreach ( $users as $user ) {
    //compute your status
    $user->status = get_your_user_status($user->id);
    $user->save();
}

You could also consider using a more functional approach with map for example...