问:
Regex returning different result on same input
I am checking for some results and passing two inputs from a document, two inputs looks same but why are they returning different output.
my regex is

```<code>(?<preandconjunct>(?:\b([Ss]ubsection|[Ss]ection|[Aa]rticle) +)(?<conjunct>(?:(?<level>(?:(?:[IVXivx]{1,5}(?![A-Z]))|(?:[A-Z]{1,2}(?![A-Z]))|(?:[0-9]+)))|(?<level>\((?:(?:[IVXivx]{1,5}(?![A-Z]))|(?:[A-Z]{1,2}(?![A-Z]))|(?:(?!in|or|if|of|to|as|at|it|no|an)[a-z]{1,2}(?![a-z]))|(?:[0-9]+))\))|(?<level>[\.-](?:(?:[IVXivx]{1,5}(?![A-Z]))|(?:[A-Z]{1,2}(?![A-Z]))|(?:[0-9]+))))+)(?=$|[ ,;.)]))
</code>```

and the two inputs are

a dispute under Section 3.1 (which shall be governed exclusively by Section 3.1) or as set forth in Section 11.3(b), the indemnification provisions of this Article XI and Article XII are the sole and exclusive remedies of the Parties pursuant to this Agreement or in connection with the transactions contemplated hereby.  From and after the Closing, to the maximum extent permitted by Law, except with respect to claims based on intentional fraud, a dispute under Section 3.1 (which shall be governed exclusively by Section 3.1),

and

a dispute under Section 3.1 (which shall be governed exclusively by Section 3.1) or as set forth in Section 11.3(b), the indemnification provisions of this Article XI and Article XII are the sole and exclusive remedies of the Parties pursuant to this Agreement or in connection with the transactions contemplated hereby.  From and after the Closing, to the maximum extent permitted by Law, except with respect to claims based on intentional fraud, a dispute under Section 3.1 (which shall be governed exclusively by Section 3.1),

also i am expecting

Section 3.1

Section 3.1

Section 11.3(b)

Article XI

Article XII

Section 3.1

Section 3.1

last one is not showing up in first input.

答:
last one is not showing up in first input

One way of getting all characters is to consume up to an anchor character. For example take the text blah blah Section 3.1 (governed by Section 3.1). We have three anchors, Section, ( and ). Let us create a pattern based off of those literal anchors.

I now will comment my regex pattern which needs IgnorePattnerWhiteSpace to work properly in the regex parser btw.

```<code>(((Sub)?Section)|Article)\s+    # Anchor of Section or Article or Subsection
(?<Number>[^\s]+)               # Number involved
\s+
   \(                           # Anchor of '('
      (?<Conjuct>[^)]+)         # Consume til next anchor
   \)                           # ')' anchor.
</code>```

By using the Not set [^ ] we can consume any funky characters which are not an ending ) anchor. Our match result looks like this

why are they returning different output.

You need to make the capturing less complex by maybe looking at the literal anchors as mentioned. Maybe even do a two pass regex by first creating general tokens of the text and upon the second regex pass, extract specific items from the tokens?

Also comment your pattern as I have done and work on individual pieces of it, once the individual items are working bring the whole pattern together.

Body:
I am checking for some results and passing two inputs from a document, two inputs looks same but why are they returning different output.
my regex is

(?<preandconjunct>(?:\b([Ss]ubsection|[Ss]ection|[Aa]rticle) +)(?<conjunct>(?:(?<level>(?:(?:[IVXivx]{1,5}(?![A-Z]))|(?:[A-Z]{1,2}(?![A-Z]))|(?:[0-9]+)))|(?<level>\((?:(?:[IVXivx]{1,5}(?![A-Z]))|(?:[A-Z]{1,2}(?![A-Z]))|(?:(?!in|or|if|of|to|as|at|it|no|an)[a-z]{1,2}(?![a-z]))|(?:[0-9]+))\))|(?<level>[\.-](?:(?:[IVXivx]{1,5}(?![A-Z]))|(?:[A-Z]{1,2}(?![A-Z]))|(?:[0-9]+))))+)(?=$|[ ,;.)]))

and the two inputs are

a dispute under Section 3.1 (which shall be governed exclusively by Section 3.1) or as set forth in Section 11.3(b), the indemnification provisions of this Article XI and Article XII are the sole and exclusive remedies of the Parties pursuant to this Agreement or in connection with the transactions contemplated hereby.  From and after the Closing, to the maximum extent permitted by Law, except with respect to claims based on intentional fraud, a dispute under Section 3.1 (which shall be governed exclusively by Section 3.1),

and

a dispute under Section 3.1 (which shall be governed exclusively by Section 3.1) or as set forth in Section 11.3(b), the indemnification provisions of this Article XI and Article XII are the sole and exclusive remedies of the Parties pursuant to this Agreement or in connection with the transactions contemplated hereby.  From and after the Closing, to the maximum extent permitted by Law, except with respect to claims based on intentional fraud, a dispute under Section 3.1 (which shall be governed exclusively by Section 3.1),

also i am expecting

Section 3.1

Section 3.1

Section 11.3(b)

Article XI

Article XII

Section 3.1

Section 3.1

last one is not showing up in first input.

Body:
last one is not showing up in first input

One way of getting all characters is to consume up to an anchor character. For example take the text blah blah Section 3.1 (governed by Section 3.1). We have three anchors, Section, ( and ). Let us create a pattern based off of those literal anchors.

I now will comment my regex pattern which needs IgnorePattnerWhiteSpace to work properly in the regex parser btw.

(((Sub)?Section)|Article)\s+    # Anchor of Section or Article or Subsection
(?<Number>[^\s]+)               # Number involved
\s+
   \(                           # Anchor of '('
      (?<Conjuct>[^)]+)         # Consume til next anchor
   \)                           # ')' anchor.

By using the Not set [^ ] we can consume any funky characters which are not an ending ) anchor. Our match result looks like this

why are they returning different output.

You need to make the capturing less complex by maybe looking at the literal anchors as mentioned. Maybe even do a two pass regex by first creating general tokens of the text and upon the second regex pass, extract specific items from the tokens?

Also comment your pattern as I have done and work on individual pieces of it, once the individual items are working bring the whole pattern together.


来源: stackexchange

问:
Adding flags using argparse to provide a list of options
I have written this program to provide a list of options using the flag --list. So, I want to use --list to provide all the options whereas when I am using --list --ex, I just want to provide a part of the list of options.

Here is the program -

```<code>import argparse
import sys
options = {
    'external': {
        },
    'internal': {
        }
}

def print_list(value):
    l1 = []
    l2 = []

    for k, v in options.iteritems():
        if k == "external":
            for opt, val in options["external"].iteritems():
                l1.append(opt)
        elif k == "internal":
            for opt,val in options["internal"].iteritems():
                l2.append(opt)
    if value == "external":
        return l1

    elif value == "internal":
        return l2
    elif value == "all":
        return l1 + l2

parser = argparse.ArgumentParser(
    description="Testing argparse"
    )

parser.add_argument("--list", action = "store_true")
parser.add_argument("--ex", action = "store_true")
parser.add_argument("--in", action = "store_true")
args = parser.parse_args(sys.argv[1:])

if args.list:
    val = print_list("all")
    for items in val:
        print items

if  not args.list and args.ex:
    parser.error("You need to provide list option")

if args.ex:
    val = print_list("external")
    for items in val:
        print items
</code>```

So when I do, --list --ex I get all the options, plus the external options. Whereas when I type --list --ex, I just want the external options.

Thanks in advance for any help.

答: Putting --list on the command line sets args.list to True and putting --ex on the command line makes args.ex True as well.  Your code checks args.list and sees that it's true so it prints out all options.  Then it checks args.ex which is also True so it prints out the external options.

ContentLicense: CC BY-SA 3.0

Body:
I have written this program to provide a list of options using the flag --list. So, I want to use --list to provide all the options whereas when I am using --list --ex, I just want to provide a part of the list of options.

Here is the program -

import argparse
import sys
options = {
    'external': {
        },
    'internal': {
        }
}

def print_list(value):
    l1 = []
    l2 = []

    for k, v in options.iteritems():
        if k == "external":
            for opt, val in options["external"].iteritems():
                l1.append(opt)
        elif k == "internal":
            for opt,val in options["internal"].iteritems():
                l2.append(opt)
    if value == "external":
        return l1

    elif value == "internal":
        return l2
    elif value == "all":
        return l1 + l2

parser = argparse.ArgumentParser(
    description="Testing argparse"
    )

parser.add_argument("--list", action = "store_true")
parser.add_argument("--ex", action = "store_true")
parser.add_argument("--in", action = "store_true")
args = parser.parse_args(sys.argv[1:])

if args.list:
    val = print_list("all")
    for items in val:
        print items

if  not args.list and args.ex:
    parser.error("You need to provide list option")

if args.ex:
    val = print_list("external")
    for items in val:
        print items

So when I do, --list --ex I get all the options, plus the external options. Whereas when I type --list --ex, I just want the external options.

Thanks in advance for any help.


问:
Linewidth increases when zooming in on vector drawing .NET
When zooming in on a vector drawing in Visual Basic .NET, after a certain point the lines get thicker with each zoom action.

App functionality is basically to draw some lines:

a graphics matrix is set using transformation and scaling to get the whole drawing fill the canvas (using g.Transform = myMatrix)

lines are drawn (using "g.DrawLine(...)")

... and when zooming in:

the transformation matrix is adjusted to zoom in on the mouse pointer location

the scalefactor for the matrix increases by a factor 1.1

The matrix is set in the PrepareDrawing method:

```<code>Private Function PrepareDrawing(ByRef g As Graphics) As Matrix
    'Create transformation matrix
    Dim myMatrix = New Matrix

    'Determine the zoom factor
    If zoomfactor > 10000 Then zoomfactor = 10000
    If zoomfactor < 0.001 Then zoomfactor = 0.001

    scaleFactor = zoomfactor * BORDERFACTOR * Math.Min(pb.Width / viewportModel.Width, pb.Height / viewportModel.Height)

    'Determine the offset to keep everything centered
    If panningOffset.IsEmpty Then
        ZoomToNetwork()
    End If

    myMatrix.Translate(panningOffset.X, panningOffset.Y)
    myMatrix.Scale(scaleFactor, -scaleFactor, MatrixOrder.Append)

    'transform current graphics
    g.Transform = myMatrix

    Return myMatrix
End Function
</code>```

And the zooming functionality is set in the ZoomInWithMouseWheel method:

```<code> Public Sub ZoomInWithMouseWheel(ByVal e As Point, ByVal delta As Single)
    Dim orgZoomfactor = zoomfactor
    Dim screenX As Double = e.X
    Dim screenY As Double = e.Y

    If delta > 0 Then
        zoomfactor = zoomfactor * 1.1
    Else
        zoomfactor = zoomfactor / 1.1
    End If

    scaleFactor = zoomfactor * BORDERFACTOR * Math.Min(pb.Width / viewportModel.Width, pb.Height / viewportModel.Height)

    Dim perc = zoomfactor / orgZoomfactor
    panningOffset.Offset(-(perc * screenX - screenX) / scaleFactor, (perc * screenY - screenY) / scaleFactor)

End Sub
</code>```

It turns out that when the first element of the matrix becomes larger than 1, the line width increases with this number.

Any thoughts on what is happening and how I can prevend the line width from increasing?

答:
Okay, found the answer. Line width should be compensated for the matrix element(0), e.g.:

```<code>g.DrawLines(New Pen(Color.Blue, lineWidth / g.Transform.Elements(0)), pnts)
</code>```

where lineWidth is 1 for example

Body:
When zooming in on a vector drawing in Visual Basic .NET, after a certain point the lines get thicker with each zoom action.

App functionality is basically to draw some lines:

a graphics matrix is set using transformation and scaling to get the whole drawing fill the canvas (using g.Transform = myMatrix)

lines are drawn (using "g.DrawLine(...)")

... and when zooming in:

the transformation matrix is adjusted to zoom in on the mouse pointer location

the scalefactor for the matrix increases by a factor 1.1

The matrix is set in the PrepareDrawing method:

Private Function PrepareDrawing(ByRef g As Graphics) As Matrix
    'Create transformation matrix
    Dim myMatrix = New Matrix

    'Determine the zoom factor
    If zoomfactor > 10000 Then zoomfactor = 10000
    If zoomfactor < 0.001 Then zoomfactor = 0.001

    scaleFactor = zoomfactor * BORDERFACTOR * Math.Min(pb.Width / viewportModel.Width, pb.Height / viewportModel.Height)

    'Determine the offset to keep everything centered
    If panningOffset.IsEmpty Then
        ZoomToNetwork()
    End If

    myMatrix.Translate(panningOffset.X, panningOffset.Y)
    myMatrix.Scale(scaleFactor, -scaleFactor, MatrixOrder.Append)

    'transform current graphics
    g.Transform = myMatrix

    Return myMatrix
End Function

And the zooming functionality is set in the ZoomInWithMouseWheel method:

 Public Sub ZoomInWithMouseWheel(ByVal e As Point, ByVal delta As Single)
    Dim orgZoomfactor = zoomfactor
    Dim screenX As Double = e.X
    Dim screenY As Double = e.Y

    If delta > 0 Then
        zoomfactor = zoomfactor * 1.1
    Else
        zoomfactor = zoomfactor / 1.1
    End If

    scaleFactor = zoomfactor * BORDERFACTOR * Math.Min(pb.Width / viewportModel.Width, pb.Height / viewportModel.Height)

    Dim perc = zoomfactor / orgZoomfactor
    panningOffset.Offset(-(perc * screenX - screenX) / scaleFactor, (perc * screenY - screenY) / scaleFactor)

End Sub

It turns out that when the first element of the matrix becomes larger than 1, the line width increases with this number.

Any thoughts on what is happening and how I can prevend the line width from increasing?

Body:
Okay, found the answer. Line width should be compensated for the matrix element(0), e.g.:

g.DrawLines(New Pen(Color.Blue, lineWidth / g.Transform.Elements(0)), pnts)

where lineWidth is 1 for example


问:
C# : Wait for n miliseconds, and test a boolean every n/m milliseconds
I have to test a boolean every 250ms, max 2 seconds, and stop when it's true.

Tried this, but Thread.Sleep isn't a good solution for me because it's freezing my software, and waiting for even more won't change anything because the boolean won't change while it's frozen.

```<code>bool onLine = false;
Stopwatch chrono = new Stopwatch();
chrono.Start();
while (chrono.ElapsedMilliseconds < 2000)
{
    if (!State().Equals(Online))
    {
        System.Threading.Thread.Sleep(250);
    }
    else
    {
        onLine = true;
        operationCompleted();
        break;
    }
}
if (!onLine)
{
    MessageBox.Show("Error");
}
</code>```

I don't know how to make the tests in an event raised by a timer if someone has a correct implementation?

答:
The currently accepted answer is not a particularly good use of the async await paradigm, and introduces a lot of noise for something that need not be complicated. Simply scheduling synchronous, blocking code onto the ThreadPool with Task.Run rather than upgrading to fully async code is a half-measure.

Rewriting that code without the blocking code and the spurious Task.Run, it could be as simple as:

```<code>private async void button1_Click(object sender, EventArgs e)
{
    bool onLine = false;
    Stopwatch chrono = new Stopwatch();
    chrono.Start();
    while (chrono.ElapsedMilliseconds < 2000)
    {
        if (!State().Equals(Online))
        {
            await Task.Delay(250);
        }
        else
        {
            onLine = true;
            break;
        }
    }

    if (onLine)
    {
        operationCompleted();
    }
    else
    {
        MessageBox.Show("Error");
    }
}
</code>```

Body:
I have to test a boolean every 250ms, max 2 seconds, and stop when it's true.

Tried this, but Thread.Sleep isn't a good solution for me because it's freezing my software, and waiting for even more won't change anything because the boolean won't change while it's frozen.

bool onLine = false;
Stopwatch chrono = new Stopwatch();
chrono.Start();
while (chrono.ElapsedMilliseconds < 2000)
{
    if (!State().Equals(Online))
    {
        System.Threading.Thread.Sleep(250);
    }
    else
    {
        onLine = true;
        operationCompleted();
        break;
    }
}
if (!onLine)
{
    MessageBox.Show("Error");
}

I don't know how to make the tests in an event raised by a timer if someone has a correct implementation?

Body:
The currently accepted answer is not a particularly good use of the async await paradigm, and introduces a lot of noise for something that need not be complicated. Simply scheduling synchronous, blocking code onto the ThreadPool with Task.Run rather than upgrading to fully async code is a half-measure.

Rewriting that code without the blocking code and the spurious Task.Run, it could be as simple as:

private async void button1_Click(object sender, EventArgs e)
{
    bool onLine = false;
    Stopwatch chrono = new Stopwatch();
    chrono.Start();
    while (chrono.ElapsedMilliseconds < 2000)
    {
        if (!State().Equals(Online))
        {
            await Task.Delay(250);
        }
        else
        {
            onLine = true;
            break;
        }
    }

    if (onLine)
    {
        operationCompleted();
    }
    else
    {
        MessageBox.Show("Error");
    }
}


问:
Using Linq to order lists within a list
I have a list of items (actually an IEnumerable). Each item has a list of values. For example:

```<code>Item1.Value[0] = "Health & Safety"
Item1.Value[1] = "Economic"
Item1.Value[2] = "Environment"

Item2.Value[0] = "Reputation"
Item2.Value[1] = "Environment"
Item2.Value[2] = "Regulatory"

...
</code>```

How can I order the list of values using linq? I know I can order the list of items using something like:

Items.Orderby(x => x.something)

...but how do I get to the list of values in each item?

答:
EDIT: Based off OP's comment, Value is a Dictionary<string, object>. You cannot sort a Dictionary as they are unordered by design.

Consider using a SortedDictionary<TKey, TValue>, and implement an IComparer<TKey> to fit your sorting needs:

Example:

```<code>Dictionary<string, object> values = new Dictionary<string, object>
{
    { "b", 1 }, { "a", 2 }, { "c", 3 }
};

// { { "a", 2 }, { "b", 1 }, { "c", 3 } }
SortedDictionary<string, object> keyAscending =
    new SortedDictionary<string, object>(values);

public class ReverseStringComparer : IComparer<string>
{
    int IComparer<string>.Compare(string x, string y)
    {
        return y.CompareTo(x);
    }
}

// { { "c", 3 }, { "b", 1 }, { "a", 2 } }
SortedDictionary<string, object> keyDescending =
    new SortedDictionary<string, object>(values, new ReverseStringComparer());
</code>```

Title: Using Linq to order lists within a list

Body:
I have a list of items (actually an IEnumerable). Each item has a list of values. For example:

Item1.Value[0] = "Health & Safety"
Item1.Value[1] = "Economic"
Item1.Value[2] = "Environment"

Item2.Value[0] = "Reputation"
Item2.Value[1] = "Environment"
Item2.Value[2] = "Regulatory"

...

How can I order the list of values using linq? I know I can order the list of items using something like:

Items.Orderby(x => x.something)

...but how do I get to the list of values in each item?

Body:
EDIT: Based off OP's comment, Value is a Dictionary<string, object>. You cannot sort a Dictionary as they are unordered by design.

Consider using a SortedDictionary<TKey, TValue>, and implement an IComparer<TKey> to fit your sorting needs:

Example:

Dictionary<string, object> values = new Dictionary<string, object>
{
    { "b", 1 }, { "a", 2 }, { "c", 3 }
};

// { { "a", 2 }, { "b", 1 }, { "c", 3 } }
SortedDictionary<string, object> keyAscending =
    new SortedDictionary<string, object>(values);

public class ReverseStringComparer : IComparer<string>
{
    int IComparer<string>.Compare(string x, string y)
    {
        return y.CompareTo(x);
    }
}

// { { "c", 3 }, { "b", 1 }, { "a", 2 } }
SortedDictionary<string, object> keyDescending =
    new SortedDictionary<string, object>(values, new ReverseStringComparer());


问:
Enum subset or subgroup in C#
I have an existing enum with numerous items in it.

I also have existing code which does certain things with this enum.

I would now like a way to view only a subset enum members.   What I'm looking for is a way to divide my enum into groups.  I need to preserve the (int) value of each member and I need to preserve the ability to view all enum members if needed.

The only thing I can think of is to just create a new enum for each subenum that only contain the items I want using the same name and value.

This works but violates the whole no repetition principle.

I don't expect anyone to have a better alternative but I thought I'd ask just in case someone had a fancy trick to show me.

Thanks, as always.

答:
If the enums don't have explicit values, give them one and use flags to define the "groupings":

```<code>[Flags]
enum MySuperEnumGroup
{
    Group1 = 1 << 0,
    Group2 = 1 << 1,
    Group3 = 1 << 2,

    Group1Item1 = 1 << 10 | Group1,
    Group1Item2 = 1 << 11 | Group1,
    Group1Item3 = 1 << 12 | Group1,

    Group2Item1 = 1 << 13 | Group2,
    Group2Item2 = 1 << 14 | Group2,
    Group2Item3 = 1 << 15 | Group2,

    Group3Item1 = 1 << 16 | Group3,
    Group3Item2 = 1 << 17 | Group3,
    Group3Item3 = 1 << 18 | Group3,
}
</code>```

Then you can use Enum.GetValues and HasFlag to get the values for a given "grouping":

```<code>var group1 = Enum.GetValues(typeof(MySuperEnumGroup))
                 .Cast<MySuperEnumGroup>()
                 .Where(value => value.HasFlag(MySuperEnumGroup.Group1))
                 .ToArray();
</code>```

OwnerDisplayName: Mr Grieves

ContentLicense: CC BY-SA 2.5

Title: Enum subset or subgroup in C#

Body:
If the enums don't have explicit values, give them one and use flags to define the "groupings":

[Flags]
enum MySuperEnumGroup
{
    Group1 = 1 << 0,
    Group2 = 1 << 1,
    Group3 = 1 << 2,

    Group1Item1 = 1 << 10 | Group1,
    Group1Item2 = 1 << 11 | Group1,
    Group1Item3 = 1 << 12 | Group1,

    Group2Item1 = 1 << 13 | Group2,
    Group2Item2 = 1 << 14 | Group2,
    Group2Item3 = 1 << 15 | Group2,

    Group3Item1 = 1 << 16 | Group3,
    Group3Item2 = 1 << 17 | Group3,
    Group3Item3 = 1 << 18 | Group3,
}

Then you can use Enum.GetValues and HasFlag to get the values for a given "grouping":

var group1 = Enum.GetValues(typeof(MySuperEnumGroup))
                 .Cast<MySuperEnumGroup>()
                 .Where(value => value.HasFlag(MySuperEnumGroup.Group1))
                 .ToArray();


问:
what is the purpose of using <html:text instead of <input type="text" in struts?
in struts programming we use <html:text instead of <input type="text" But we can use <input type="text" and it will work also what is the specific reason for using <html:text tag?
can any one answer me please?

答:
It will do magic. I.e. if your form has a field with a name of "bob", and you have an html:text with a name of "bob", the value you put in the bob field of the form within an action will cause the rendered html input to be populated. If you just did a nornal

On the other hand, html:button does (IIRC), the exact same thing as a normal button, but is just there so you can consistently put html: in front of everything. I think if you use internationalized labels you can get a small benefit out of html:button, but nothing I have ever done.


问:
Nested subqueries in Django
Getting into deep water with Subquery. I have a set of Carparks. Carparks have multiple Bookings. Bookings have many BarrierActivity records, which are the various coming and going events at the barriers. These are all simple FKs up the stack.

It is possible for a booking to arrive and the barrier cameras not recognise it. A member of staff will buzz them in but that means the system has failed for some reason. And that's what I'm trying to do here. Work out what percentage of my bookings got in via automated means. I know there are a number of other ways of doing this, but I'd like to do this with a single subquery-based queryset.

My aim reasonably simple. Annotate 0 or 1 to show whether or not an "entry" BarrierActivity exists for each Booking. Annotate an average of those values, per Carpark.

The first part is fine. I can do a simple Exists() between BarrierActivity and Booking and then each booking has the 0 or 1:

```<code>successful_bas = BarrierActivity.objects.order_by().filter(
    booking=OuterRef('pk'),
    activity_type=BarrierActivity.TYPE_ANPR_BOOKING,
    direction='entry'
).values('booking')

Booking.objects.order_by().annotate(
    entry_success=Exists(successful_bas)
)
</code>```

And again, that works fine. But as soon as I try to scale that up another layer (so looking at Carpark instead of Booking)...

```<code>successful_bas = BarrierActivity.objects.order_by().filter(
    booking=OuterRef('pk'),
    activity_type=BarrierActivity.TYPE_ANPR_BOOKING,
    direction='entry'
).values('booking')

bookings = Booking.objects.order_by().filter(
    carpark=OuterRef('pk')
).values('carpark').annotate(
    entry_success=Exists(successful_bas)
).values('entry_success')

Carpark.objects.order_by().annotate(
    entry_hitrate=ExpressionWrapper(
        Avg(Cast(Subquery(bookings), IntegerField())) * 100,
        output_field=FloatField()
    )
)
</code>```

... I get the Subquery-error-of-doom: more than one row returned by a subquery used as an expression. The bookings subquery it clearly returning too much but how do I aggregate that before it hits the outermost subquery?

I've tried many things, but here's a reorganisation of the average to within the subquery. Same error:

```<code>successful_bas = "... as before ..."

bookings = Booking.objects_standard.order_by().filter(
    carpark=OuterRef('pk')
).values('site').annotate(
    entry_success=Exists(successful_bas)
).annotate(
    entry_avg=Avg(Cast('entry_success', IntegerField()))
).values('entry_avg')

Carpark.objects.order_by().annotate(
    entry_hitrate=ExpressionWrapper(
        Subquery(bookings, output_field=FloatField()) * 100,
        output_field=FloatField()
    )
)
</code>```

答:
I was able to re-create part of this in one of my own projects and adding a distinct('<values_field_name>').order_by() to the outer subquery solved it.

The distinct call is needed to reduce the number of rows returned. The field name in the distinct call is required otherwise it tries to do the distinct call across another field. Then the order_by() call clears any ordering so that the query has the ordering on the distinct expression matching the initial expression's ordering.

This is what I'd try:

```<code>successful_bas = BarrierActivity.objects.order_by().filter(
    booking=OuterRef('pk'),
    activity_type=BarrierActivity.TYPE_ANPR_BOOKING,
    direction='entry'
).values('booking')

bookings = Booking.objects.order_by().filter(
    carpark=OuterRef('pk')
).annotate(
    entry_success=Exists(successful_bas)
).values('carpark').distinct('carpark').order_by()

Carpark.objects.order_by().annotate(
    entry_hitrate=ExpressionWrapper(
        Avg(Cast(Subquery(bookings), IntegerField())) * 100,
        output_field=FloatField()
    )
)
</code>```

Note that I removed one of the values call in the outer subquery.

Title: Nested subqueries in Django

Body:
Getting into deep water with Subquery. I have a set of Carparks. Carparks have multiple Bookings. Bookings have many BarrierActivity records, which are the various coming and going events at the barriers. These are all simple FKs up the stack.

It is possible for a booking to arrive and the barrier cameras not recognise it. A member of staff will buzz them in but that means the system has failed for some reason. And that's what I'm trying to do here. Work out what percentage of my bookings got in via automated means. I know there are a number of other ways of doing this, but I'd like to do this with a single subquery-based queryset.

My aim reasonably simple. Annotate 0 or 1 to show whether or not an "entry" BarrierActivity exists for each Booking. Annotate an average of those values, per Carpark.

The first part is fine. I can do a simple Exists() between BarrierActivity and Booking and then each booking has the 0 or 1:

successful_bas = BarrierActivity.objects.order_by().filter(
    booking=OuterRef('pk'),
    activity_type=BarrierActivity.TYPE_ANPR_BOOKING,
    direction='entry'
).values('booking')

Booking.objects.order_by().annotate(
    entry_success=Exists(successful_bas)
)

And again, that works fine. But as soon as I try to scale that up another layer (so looking at Carpark instead of Booking)...

successful_bas = BarrierActivity.objects.order_by().filter(
    booking=OuterRef('pk'),
    activity_type=BarrierActivity.TYPE_ANPR_BOOKING,
    direction='entry'
).values('booking')

bookings = Booking.objects.order_by().filter(
    carpark=OuterRef('pk')
).values('carpark').annotate(
    entry_success=Exists(successful_bas)
).values('entry_success')

Carpark.objects.order_by().annotate(
    entry_hitrate=ExpressionWrapper(
        Avg(Cast(Subquery(bookings), IntegerField())) * 100,
        output_field=FloatField()
    )
)

... I get the Subquery-error-of-doom: more than one row returned by a subquery used as an expression. The bookings subquery it clearly returning too much but how do I aggregate that before it hits the outermost subquery?

I've tried many things, but here's a reorganisation of the average to within the subquery. Same error:

successful_bas = "... as before ..."

bookings = Booking.objects_standard.order_by().filter(
    carpark=OuterRef('pk')
).values('site').annotate(
    entry_success=Exists(successful_bas)
).annotate(
    entry_avg=Avg(Cast('entry_success', IntegerField()))
).values('entry_avg')

Carpark.objects.order_by().annotate(
    entry_hitrate=ExpressionWrapper(
        Subquery(bookings, output_field=FloatField()) * 100,
        output_field=FloatField()
    )
)

Body:
I was able to re-create part of this in one of my own projects and adding a distinct('<values_field_name>').order_by() to the outer subquery solved it.

The distinct call is needed to reduce the number of rows returned. The field name in the distinct call is required otherwise it tries to do the distinct call across another field. Then the order_by() call clears any ordering so that the query has the ordering on the distinct expression matching the initial expression's ordering.

This is what I'd try:

successful_bas = BarrierActivity.objects.order_by().filter(
    booking=OuterRef('pk'),
    activity_type=BarrierActivity.TYPE_ANPR_BOOKING,
    direction='entry'
).values('booking')

bookings = Booking.objects.order_by().filter(
    carpark=OuterRef('pk')
).annotate(
    entry_success=Exists(successful_bas)
).values('carpark').distinct('carpark').order_by()

Carpark.objects.order_by().annotate(
    entry_hitrate=ExpressionWrapper(
        Avg(Cast(Subquery(bookings), IntegerField())) * 100,
        output_field=FloatField()
    )
)

Note that I removed one of the values call in the outer subquery.


问:
Migrating InfoPath from 2010 to 2013
How can I migrate my existing InfoPath form 2010 to InfoPath 2013? Will opening the form in IP 2013 and publish work?</p>

答: Opening the form in 2013 will work as it is backwards compatible with older versions. If you want to, you could always edit the form and change the compatability to the newest form type.</p>

Title: Migrating InfoPath from 2010 to 2013


问:
How to average the difference between 2 rows
No rush, this is pure curiosity as i've already finished the project but i want to know if there's a faster and cleaner way of averaging the difference between 2 rows.

I have 2 rows of data and i need to average the difference between the 2.

i.e.

```<code>Row1  5 6 8 4
Row2  4 7 8 9
</code>```

what i want to average

```<code>1,-1,0,-5
</code>```

I tried this formula but failed.

```<code>{=AVERAGE(G26:U26-G28:U28)}
</code>```

答:
You can use SUMPRODUCT:

```<code>=SUMPRODUCT(A1:D1-A2:D2)/COLUMNS(A1:D1)
</code>```

Body:
No rush, this is pure curiosity as i've already finished the project but i want to know if there's a faster and cleaner way of averaging the difference between 2 rows.

I have 2 rows of data and i need to average the difference between the 2.

i.e.

Row1  5 6 8 4
Row2  4 7 8 9

what i want to average

1,-1,0,-5

I tried this formula but failed.

{=AVERAGE(G26:U26-G28:U28)}

Body:
You can use SUMPRODUCT:

=SUMPRODUCT(A1:D1-A2:D2)/COLUMNS(A1:D1)


问:
Exclude specific rows in COPY command on RedShift
I'm using the COPY command to load a csv file from S3 into a Redshift table. It's a 5 million row file and I get a load error saying row 259123 has text instead of a number.

Is there an option to exclude that row when loading? I'm guessing there will be a few more like that so I'm looking for a way to exclude a set of specific rows from the import.

```<code>copy newtable from 's3://data.csv' credentials
'aws_access_key_id=ttt;aws_secret_access_key=ttt'
delimiter ',' IGNOREHEADER as 1
</code>```

答:
You can use "ESCAPE maxerror error_count". Let say you want to escape 1 error then:

```<code> copy newtable from 's3://data.csv' credentials
'aws_access_key_id=ttt;aws_secret_access_key=ttt'
 delimiter ',' IGNOREHEADER as 1`ESCAPE maxerror 1
</code>```

Amazon redshift documentation

Body:
I'm using the COPY command to load a csv file from S3 into a Redshift table. It's a 5 million row file and I get a load error saying row 259123 has text instead of a number.

Is there an option to exclude that row when loading? I'm guessing there will be a few more like that so I'm looking for a way to exclude a set of specific rows from the import.

copy newtable from 's3://data.csv' credentials
'aws_access_key_id=ttt;aws_secret_access_key=ttt'
delimiter ',' IGNOREHEADER as 1

Body:
You can use "ESCAPE maxerror error_count". Let say you want to escape 1 error then:

 copy newtable from 's3://data.csv' credentials
'aws_access_key_id=ttt;aws_secret_access_key=ttt'
 delimiter ',' IGNOREHEADER as 1`ESCAPE maxerror 1

Amazon redshift documentation


问:
Dynamically loads point to a Polygon constructed by FXML
In this answer a loader class is used to dynamically load a ComboBox while it is constructed (without post processing).

I wanted to use a similar technique to pre-process and reuse a Polygon , but a Polygon doesn't expose items property, or a similar one.
My solution was to extend Polygon and add such property:

```<code>public class DPolygon extends javafx.scene.shape.Polygon{

    public ObjectProperty<ObservableList<Double>> items =
            new SimpleObjectProperty<>(this, "items");

    public DPolygon() {
        items.addListener(new ChangeListener<ObservableList<Double>>() {
            @Override
            public void changed(ObservableValue<? extends ObservableList<Double>>
            observable, ObservableList<Double> oldValue,
            ObservableList<Double> newValue) {
                addPolyPoints();
            }
        });
    }

    private void addPolyPoints() { super.getPoints().setAll(items.get());}

    public ObjectProperty<ObservableList<Double>>itemsProperty() { return items; }

    public final ObservableList<Double> getItems() {return items.get(); }

    public final void setItems(ObservableList<Double> value) {items.set(value); }
}
</code>```

Have a loader class to supply the points:

```<code>public class PointsLoader5 {

    private ObservableList<Double> items;

    public ObservableList<Double> getItems() {

        items = FXCollections.observableArrayList(
                        new Double[] {100.,0.,100., 100., 0., 0.});
        return items;
    }
}
</code>```

Use both in the FXML file:

```<code><?xml version="1.0" encoding="UTF-8"?>
<?import java.lang.Double?>
<?import javafx.xml_polygon.DPolygon?>

<DPolygon fx:id="triangle" fill="GREEN" stroke="RED" strokeType="INSIDE"
     items="${pointsLoader.items}" xmlns:fx="http://javafx.com/fxml/1" >
</DPolygon>
</code>```

And put it all together to test:

```<code>public class DrawTrianle5 extends Application {

    @Override
    public void start(Stage primaryStage) throws IOException {

        primaryStage.setTitle("Set points using loader");
        Group group = new Group();
        GridPane grid = new GridPane();
        grid.setAlignment(Pos.CENTER);
        grid.setHgap(10);
        grid.setVgap(10);
        grid.setPadding(new Insets(25, 25, 25, 25));
        group.getChildren().add(grid);

        FXMLLoader loader = new FXMLLoader(getClass().getResource("triangle/Triangle5.fxml"));
        loader.getNamespace().put("pointsLoader", new PointsLoader5());
        DPolygon triangle = loader.load();

        grid.add(triangle, 0, 0);
        Scene scene = new Scene(group, 450, 175);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}
</code>```

It works with no problem.

My question is: is it the right approach, or is there a better way to dynamically loads point to a Polygon constructed byFXML, avoiding post-processing ?

答:
The only thing preventing you doing this with the current Polygon class is that there is no suitable constructor argument with a @NamedArg annotation.

So one way to do this would be:

```<code>import java.util.List;

import javafx.beans.NamedArg;
import javafx.scene.shape.Polygon;

public class DPolygon extends Polygon {

    public DPolygon(@NamedArg("points") List<Double> points) {
        super(points.stream().mapToDouble(Double::doubleValue).toArray());
    }
}
</code>```

Then you just need

<DPolygon xmlns:fx="http://javafx.com/fxml/1" points="$points" fill="GREEN" stroke="RED" strokeType="INSIDE" />
```

<p>Test:</p>

```import java.util.Arrays;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.shape.Polygon;
import javafx.stage.Stage;

public class PolygonTest extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception {
        FXMLLoader loader = new FXMLLoader(getClass().getResource("Polygon.fxml"));
        loader.getNamespace().put("points", Arrays.asList(100.0,0.0,100.0,100.0,0.0,0.0));
        Polygon poly = loader.load();
        Scene scene = new Scene(new Group(poly), 450, 175);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}
```

It feels like there should be an approach without the subclass at all, but I can't quite find one that works.

Body:
In this answer a loader class is used to dynamically load a ComboBox while it is constructed (without post processing).

I wanted to use a similar technique to pre-process and reuse a Polygon , but a Polygon doesn't expose items property, or a similar one.
My solution was to extend Polygon and add such property:

public class DPolygon extends javafx.scene.shape.Polygon{

    public ObjectProperty<ObservableList<Double>> items =
            new SimpleObjectProperty<>(this, "items");

    public DPolygon() {
        items.addListener(new ChangeListener<ObservableList<Double>>() {
            @Override
            public void changed(ObservableValue<? extends ObservableList<Double>>
            observable, ObservableList<Double> oldValue,
            ObservableList<Double> newValue) {
                addPolyPoints();
            }
        });
    }

    private void addPolyPoints() { super.getPoints().setAll(items.get());}

    public ObjectProperty<ObservableList<Double>>itemsProperty() { return items; }

    public final ObservableList<Double> getItems() {return items.get(); }

    public final void setItems(ObservableList<Double> value) {items.set(value); }
}

Have a loader class to supply the points:

public class PointsLoader5 {

    private ObservableList<Double> items;

    public ObservableList<Double> getItems() {

        items = FXCollections.observableArrayList(
                        new Double[] {100.,0.,100., 100., 0., 0.});
        return items;
    }
}

Use both in the FXML file:

<?xml version="1.0" encoding="UTF-8"?>
<?import java.lang.Double?>
<?import javafx.xml_polygon.DPolygon?>

<DPolygon fx:id="triangle" fill="GREEN" stroke="RED" strokeType="INSIDE"
     items="${pointsLoader.items}" xmlns:fx="http://javafx.com/fxml/1" >
</DPolygon>

And put it all together to test:

public class DrawTrianle5 extends Application {

    @Override
    public void start(Stage primaryStage) throws IOException {

        primaryStage.setTitle("Set points using loader");
        Group group = new Group();
        GridPane grid = new GridPane();
        grid.setAlignment(Pos.CENTER);
        grid.setHgap(10);
        grid.setVgap(10);
        grid.setPadding(new Insets(25, 25, 25, 25));
        group.getChildren().add(grid);

        FXMLLoader loader = new FXMLLoader(getClass().getResource("triangle/Triangle5.fxml"));
        loader.getNamespace().put("pointsLoader", new PointsLoader5());
        DPolygon triangle = loader.load();

        grid.add(triangle, 0, 0);
        Scene scene = new Scene(group, 450, 175);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

It works with no problem.

My question is: is it the right approach, or is there a better way to dynamically loads point to a Polygon constructed byFXML, avoiding post-processing ?

Body:
The only thing preventing you doing this with the current Polygon class is that there is no suitable constructor argument with a @NamedArg annotation.

So one way to do this would be:

import java.util.List;

import javafx.beans.NamedArg;
import javafx.scene.shape.Polygon;

public class DPolygon extends Polygon {

    public DPolygon(@NamedArg("points") List<Double> points) {
        super(points.stream().mapToDouble(Double::doubleValue).toArray());
    }
}

Then you just need

<DPolygon xmlns:fx="http://javafx.com/fxml/1" points="$points" fill="GREEN" stroke="RED" strokeType="INSIDE" />

Test:

import java.util.Arrays;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.shape.Polygon;
import javafx.stage.Stage;

public class PolygonTest extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception {
        FXMLLoader loader = new FXMLLoader(getClass().getResource("Polygon.fxml"));
        loader.getNamespace().put("points", Arrays.asList(100.0,0.0,100.0,100.0,0.0,0.0));
        Polygon poly = loader.load();
        Scene scene = new Scene(new Group(poly), 450, 175);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

It feels like there should be an approach without the subclass at all, but I can't quite find one that works.


问:
How do I connect to an existing CloudSearch domain in boto?
I'm just starting to work with boto to connect to Amazon CloudSearch.

I got the examples working, but I can't find any examples of connecting to an existing domain, all the examples create a new domain.

Poking around, I found get_domain, but that fails if I call it on the connection object.

```<code>>>> conn.get_domain('foo')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'Layer2' object has no attribute 'get_domain'
</code>```

Any suggestions as to how I can connect to an existing domain?

[edit]
I started from this: http://boto.cloudhackers.com/en/latest/cloudsearch_tut.html

So, all I'm doing this

```<code>import boto
conn = boto.connect_cloudsearch()
</code>```

答:
I initially implemented the connection using the Layer2 approach:

Layer2(region='region name').lookup('domain name').

However, after some profiling I found the latency in creating a connection to be very high.

When I say very high, I mean the time to create a connection was rivaling the time to actually perform the query and get a response (> 500ms in most cases).

My solution, therefore, was to create the Domain directly. Note: this solution is brittle, but it does decrease latency significantly

You can create the domain by doing something like (many of these values can be found by doing aws cloudsearch describe-domains):

```<code>        domain = Domain(boto.cloudsearch2.connect_to_region('region name'), {
            'Created': True,
            'Deleted': False,
            'Processing': False,
            'RequiresIndexDocuments': False,
            'DomainId': 'domain_id',
            'DomainName': 'domain_name',
            'SearchInstanceCount': 2,
            'SearchPartitionCount': 1,
            'DocService': {
                'Endpoint': 'doc_service_endpoint',
            },
            'ARN': 'domain_arn',
            'SearchService': {
                'Endpoint': 'search_service_endpoint'
            }
        })
</code>```

Body:
I'm just starting to work with boto to connect to Amazon CloudSearch.

I got the examples working, but I can't find any examples of connecting to an existing domain, all the examples create a new domain.

Poking around, I found get_domain, but that fails if I call it on the connection object.

>>> conn.get_domain('foo')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'Layer2' object has no attribute 'get_domain'

Any suggestions as to how I can connect to an existing domain?

[edit]
I started from this: http://boto.cloudhackers.com/en/latest/cloudsearch_tut.html

So, all I'm doing this

import boto
conn = boto.connect_cloudsearch()

Body:
I initially implemented the connection using the Layer2 approach:

Layer2(region='region name').lookup('domain name').

However, after some profiling I found the latency in creating a connection to be very high.

When I say very high, I mean the time to create a connection was rivaling the time to actually perform the query and get a response (> 500ms in most cases).

My solution, therefore, was to create the Domain directly. Note: this solution is brittle, but it does decrease latency significantly

You can create the domain by doing something like (many of these values can be found by doing aws cloudsearch describe-domains):

        domain = Domain(boto.cloudsearch2.connect_to_region('region name'), {
            'Created': True,
            'Deleted': False,
            'Processing': False,
            'RequiresIndexDocuments': False,
            'DomainId': 'domain_id',
            'DomainName': 'domain_name',
            'SearchInstanceCount': 2,
            'SearchPartitionCount': 1,
            'DocService': {
                'Endpoint': 'doc_service_endpoint',
            },
            'ARN': 'domain_arn',
            'SearchService': {
                'Endpoint': 'search_service_endpoint'
            }
        })


问:
Best practice for running a daily Python screen-scraping script 50 times (8.3 minutes total) per user?
On the front-end, I have a PHP webapp that allows users to create a list of their websites (5 max).

On the back-end, a Python script runs daily (and has ~10 iterations) for each website that the user registers. Each script per website takes about 10 seconds to run through all iterations and finish its scraping. It then makes a CSV file with its findings.

So, in total, that's up to (5 websites * 10 iterations =) 50 iterations at 8.3 total minutes per user.

Right now, the script works when I manually feed it a URL, so I'm wondering how to make it dynamically part of the webapp.

How do I programmatically add and remove scripts that run daily depending on the number of users and the websites each user has each day?

How would I schedule this script to run for each website of each user, passing in the appropriate parameters?

I'm somewhat acquainted with cronjobs, as it's the only thing I know of that is made for routine processes.

答: Assuming you're using a database to store the users' web sites, you can have just 1 script that runs as a daily cron job and queries the database for the list of sites to process.</p>


问:
Live Database for Marquee
I'm am in need of some assistance creating a live graph that will update in ms. I have App in C# that captures the Idle timer/CPU/Memory/etc on several PC's. I would like to send that information to a website and update a graph in a real time manner.

Ultimately I would like to live stream a JSON file to the main server(not sure how to go about that)

Now I use SQL to update but there is some latency between the constant update and select query.

My other thought is to create an HTML/Web server and pass the JSON directly through a data stream. think this may be overkill as each PC would have to run the Web Server.

I believe there is a simple way to do this.

Thanks

答: Anyone looking at this for an answer I was able to resolve this by opening a data stream using HTTPRequest to query the data. It is surprisingly low overhead.  </p>

Title: Live Database for Marquee


问:
Alternative to deprecated method ObjectMapper.setFilters()
I have the following part of code that helps me mask certain attributes of a json response,

ObjectMapper mapper = new ObjectMapper();
        mapper.setFilters(new SimpleFilterProvider().addFilter("sampleFilter", new SampleFilter())
                .addFilter("simpleFilter",new SimpleFilter()));

But I realized that the setFilters() method is deprecated...I would like to replace this with an alternate method. Any help greatly appreciated!

答:
Normally, the JavaDocs will provide you with a new way of archieving the behaviour. In your case it says:

Deprecated.
  Since 2.6, use setFilterProvider(com.fasterxml.jackson.databind.ser.FilterProvider) instead (allows chaining)

Source.

So you just need to change the method name, as the arguments stay the same. It now returns the ObjectMapper object so you can chain method calls (as described in the Javadoc)


问:
How to process Websocket messages from client in Java?
I am developing a client-server application in Java using Websocket. Currently, all the client messages are processed using switch-case as shown below.

```<code>@OnMessage
public String onMessage(String unscrambledWord, Session session) {
    switch (unscrambledWord) {
    case "start":
        logger.info("Starting the game by sending first word");
        String scrambledWord = WordRepository.getInstance().getRandomWord().getScrambledWord();
        session.getUserProperties().put("scrambledWord", scrambledWord);
        return scrambledWord;
    case "quit":
        logger.info("Quitting the game");
        try {
            session.close(new CloseReason(CloseCodes.NORMAL_CLOSURE, "Game finished"));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    String scrambledWord = (String) session.getUserProperties().get("scrambledWord");
    return checkLastWordAndSendANewWord(scrambledWord, unscrambledWord, session);
}
</code>```

The server has to process more than 50 different requests from client and that results in more than 50 case statements. And in future, I expect it to grow. Is there any better way to process Websocket messages from client? Or, is this how it is usually done?

I read somewhere about the use of hashtable to avoid long switch-case scenario by mapping to function pointers. Is this possible in Java? Or, is there any better solutions?

Thanks.

答:
As mentioned in the comments, one of websockets drawback is that you'll to specify the communication protocol yourself. AFAIK, the huge switch is the best option. To improve code readability and maintenance, I'll suggest to use encoders and decoders. Then, your problem becomes: how should I design my messages?

Your game looks like Scrabble. I don't know how to play Scrabble so let's take the example of card game with money. Let's assume you have three types of actions:

Global action (join table, leave table ...)

Money action (place bet, split bet, ...)

Card action (draw card, etc)

Then your messages can look like

```<code>public class AbstractAction{
    // not relevant for global action but let's put that aside for the example
    public abstract void endTurn();
}

public class GlobalAction{
    // ...
}

public class MoneyAction{

    enum Action{
        PLACE_BET, PLACE_MAX_BET, SPLIT_BET, ...;
    }

    private MoneyAction.Action action;
    // ...
}

public class CardAction{
    // ...
}
</code>```

Once your decoder and encoders are properly defined, your switch would be easier to read and easier to maintain. In my project, the code would look like this:

```<code>@ServerEndPoint(value = ..., encoders = {...}, decoders = {...})
public class ServerEndPoint{

    @OnOpen
    public void onOpen(Session session){
        // ...
    }

    @OnClose
    public void onClose(Session session){
        // ...
    }

    @OnMessage
    public void onMessage(Session session, AbstractAction action){

        // I'm checking the class here but you
        // can use different check such as a
        // specific attribute

        if(action instanceof GlobalAction){
            // do some stuff
        }

        else if (action instanceof CardAction){
            // do some stuff
        }

        else if (action instance of MoneyAction){
            MoneyAction moneyAction = (MoneyAction) action;
            switch(moneyAction.getAction()){
                case PLACE_BET:
                    double betValue = moneyAction.getValue();
                    // do some stuff here
                    break;
                case SPLIT_BET:
                    doSomeVeryComplexStuff(moneyAction);
                    break;
            }
        }

    }

    private void doSomeVeryComplexStuff(MoneyAction moneyAction){
        // ... do something very complex ...
    }

}
</code>```

I prefer this approach because:

The messages design can leverage your entities design (if you are using JPA behind)

As messages are not plain text anymore but objects, enumerations can be used and enumerations are very powerful in this kind of switch-case situation. With the same logic but in a lesser extend, class abstraction can be useful as well

The ServerEndPoint class only handles communication. The business logic is handled out of this class, either directly in Messages classes or in some EJB. Because of this split, code maintenance is much easier

Bonus: @OnMessage method can be read as a summary of the protocol but details should not be displayed here. Each case must contain few lines only.

I prefer avoid using Reflection: it'll ruin your code readability, in the specific scenario of websocket

To go further beyond code readability, maintenance and efficiency, you can use a SessionHandler to intercept some CDI event if this can improve your code. I gave an example in this answer. If you need a more advanced example, Oracle provides a great tutorial about it. It might help you to improve your code.

Body:
I am developing a client-server application in Java using Websocket. Currently, all the client messages are processed using switch-case as shown below.

@OnMessage
public String onMessage(String unscrambledWord, Session session) {
    switch (unscrambledWord) {
    case "start":
        logger.info("Starting the game by sending first word");
        String scrambledWord = WordRepository.getInstance().getRandomWord().getScrambledWord();
        session.getUserProperties().put("scrambledWord", scrambledWord);
        return scrambledWord;
    case "quit":
        logger.info("Quitting the game");
        try {
            session.close(new CloseReason(CloseCodes.NORMAL_CLOSURE, "Game finished"));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    String scrambledWord = (String) session.getUserProperties().get("scrambledWord");
    return checkLastWordAndSendANewWord(scrambledWord, unscrambledWord, session);
}

The server has to process more than 50 different requests from client and that results in more than 50 case statements. And in future, I expect it to grow. Is there any better way to process Websocket messages from client? Or, is this how it is usually done?

I read somewhere about the use of hashtable to avoid long switch-case scenario by mapping to function pointers. Is this possible in Java? Or, is there any better solutions?

Thanks.

Body:
As mentioned in the comments, one of websockets drawback is that you'll to specify the communication protocol yourself. AFAIK, the huge switch is the best option. To improve code readability and maintenance, I'll suggest to use encoders and decoders. Then, your problem becomes: how should I design my messages?

Your game looks like Scrabble. I don't know how to play Scrabble so let's take the example of card game with money. Let's assume you have three types of actions:

Global action (join table, leave table ...)

Money action (place bet, split bet, ...)

Card action (draw card, etc)

Then your messages can look like

public class AbstractAction{
    // not relevant for global action but let's put that aside for the example
    public abstract void endTurn();
}

public class GlobalAction{
    // ...
}

public class MoneyAction{

    enum Action{
        PLACE_BET, PLACE_MAX_BET, SPLIT_BET, ...;
    }

    private MoneyAction.Action action;
    // ...
}

public class CardAction{
    // ...
}

Once your decoder and encoders are properly defined, your switch would be easier to read and easier to maintain. In my project, the code would look like this:

@ServerEndPoint(value = ..., encoders = {...}, decoders = {...})
public class ServerEndPoint{

    @OnOpen
    public void onOpen(Session session){
        // ...
    }

    @OnClose
    public void onClose(Session session){
        // ...
    }

    @OnMessage
    public void onMessage(Session session, AbstractAction action){

        // I'm checking the class here but you
        // can use different check such as a
        // specific attribute

        if(action instanceof GlobalAction){
            // do some stuff
        }

        else if (action instanceof CardAction){
            // do some stuff
        }

        else if (action instance of MoneyAction){
            MoneyAction moneyAction = (MoneyAction) action;
            switch(moneyAction.getAction()){
                case PLACE_BET:
                    double betValue = moneyAction.getValue();
                    // do some stuff here
                    break;
                case SPLIT_BET:
                    doSomeVeryComplexStuff(moneyAction);
                    break;
            }
        }

    }

    private void doSomeVeryComplexStuff(MoneyAction moneyAction){
        // ... do something very complex ...
    }

}

I prefer this approach because:

The messages design can leverage your entities design (if you are using JPA behind)

As messages are not plain text anymore but objects, enumerations can be used and enumerations are very powerful in this kind of switch-case situation. With the same logic but in a lesser extend, class abstraction can be useful as well

The ServerEndPoint class only handles communication. The business logic is handled out of this class, either directly in Messages classes or in some EJB. Because of this split, code maintenance is much easier

Bonus: @OnMessage method can be read as a summary of the protocol but details should not be displayed here. Each case must contain few lines only.

I prefer avoid using Reflection: it'll ruin your code readability, in the specific scenario of websocket

To go further beyond code readability, maintenance and efficiency, you can use a SessionHandler to intercept some CDI event if this can improve your code. I gave an example in this answer. If you need a more advanced example, Oracle provides a great tutorial about it. It might help you to improve your code.


问:
Dijkstra's Algorithm modification
Let G (V, E) be a weighted, directed graph with non negative weight function
W : E -> {0, 1, 2... W } for some non negative integer W . How to modify Dijkstra’s algorithm to compute the shortest paths from a given source vertex s in O(V W + E) time.

答:
I have once done research on this topic and the algorithm you're looking for is Dial algorithm. There is also further optimization of Dijkstra Algorithm, so I also attach it below. On the very bottom I put my tests on performance on those three algorithms.

Dial algorithm

Pseudocode

Efficient algorithm for small weights. Instead of a priority queue we use buckets for each weight from 0 to max weight. The complexity is O(m+n*C) where n is number of vertex, C is max cost, m is number of edges.

Another approach is Radix algorithm.

Radix heap

Pseudocode

Now, we have ln(C) of buckets. ith bucket stores edges in range [2^i, 2^(i+1)]. The complexity becomes O(m+nln(n*C)).

Tests

Test 1

Test 2

Test 3

Test 4

Title: Dijkstra's Algorithm modification


问:
Passing URL Parameters to WordPress PHP Template Page
I am trying to pass URL parameters to a Wordpress template page:

```<code>www.mysite.com/my_wp_page_template/?city=Anytown&state=ST
</code>```

Based on some forum examples I have added the following code to the functions.php:

```<code>add_filter('query_vars', 'parameter_queryvars' );
function parameter_queryvars( $qvars )
{
  $qvars[] = 'City';
  $qvars[] .= 'State';
  return $qvars;
}
</code>```

And, I am trying to extract the variables in a PHP file that is included in a WP page using:

```<code>report_for_city.php
<?php
$strCity = $_GET["City"];
$strState = $_GET["State"];
$strCityState = $strCity . ' ' . $strState;
?>
<p>This page contains the report for <?php $strCityState ?>.</p>
</code>```

But, the variable is not getting inserted in the output HTML.  The HTML is being inserted into the WP page, so the PHP template is getting invoked from the WP page using the insert-php plugin:

```<code>[insert_php]include('wp-content/php/report_for_city.php');[/insert_php]
</code>```

What am I doing wrong?  How can this be fixed?

答:
The PHP code was missing echo in:

php $strCityState

The following code corrected the problem:

php echo $strCityState

Is there an easier way to output the value than this?

Body:
I am trying to pass URL parameters to a Wordpress template page:

www.mysite.com/my_wp_page_template/?city=Anytown&state=ST

Based on some forum examples I have added the following code to the functions.php:

add_filter('query_vars', 'parameter_queryvars' );
function parameter_queryvars( $qvars )
{
  $qvars[] = 'City';
  $qvars[] .= 'State';
  return $qvars;
}

And, I am trying to extract the variables in a PHP file that is included in a WP page using:

report_for_city.php
<?php
$strCity = $_GET["City"];
$strState = $_GET["State"];
$strCityState = $strCity . ' ' . $strState;
?>

This page contains the report for <?php $strCityState ?>.

But, the variable is not getting inserted in the output HTML.  The HTML is being inserted into the WP page, so the PHP template is getting invoked from the WP page using the insert-php plugin:

[insert_php]include('wp-content/php/report_for_city.php');[/insert_php]

What am I doing wrong?  How can this be fixed?


问:
NSObject - saving in loop vs outside loop
Is there any loss in data if I save outside the loop when adding objects vs when I do it inside the loop? Asking since saving outside is much faster.

Outside Loop:

```<code>for(NSMutableDictionary *result in data){
            [manager newManagedCaf];
            for (NSString *name in result){
                if ([name isEqualToString:@"contact"]){
                NSNumber *num = [NSNumber numberWithInteger:[[result valueForKey:name] integerValue]];
                    [[manager cafCards] setValue:num forKey:name];
                }
                else{
                    [[manager cafCards] setValue:[result valueForKey:name] forKey:name];
                }
            }
            [[manager cafCards] setValue:[NSNumber numberWithBool:YES] forKey:@"synced"];
            }
        }
    if(![[manager cafCards].managedObjectContext save:&error]){
        NSLog(@"Unable to save managed object context.");
        NSLog(@"%@, %@", error, error.localizedDescription);
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:[NSString stringWithFormat:@"Error: %@", [error localizedDescription]] message:@"Database not working, try again later or inform IT." delegate:self cancelButtonTitle:@"Back" otherButtonTitles:nil, nil];
        [alert show];
        [self getImages:0 con:con withManager:manager];
   }
</code>```

Inside Loop:

```<code> for(NSMutableDictionary *result in data){
                [manager newManagedCaf];
                for (NSString *name in result){
                    if ([name isEqualToString:@"contact"]){
                    NSNumber *num = [NSNumber numberWithInteger:[[result valueForKey:name] integerValue]];
                        [[manager cafCards] setValue:num forKey:name];
                    }
                    else{
                        [[manager cafCards] setValue:[result valueForKey:name] forKey:name];
                    }
                }

                [[manager cafCards] setValue:[NSNumber numberWithBool:YES] forKey:@"synced"];
                if(![[manager cafCards].managedObjectContext save:&error]){
                    NSLog(@"Unable to save managed object context.");
                    NSLog(@"%@, %@", error, error.localizedDescription);
                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:[NSString stringWithFormat:@"Error: %@", [error localizedDescription]] message:@"Database not working, try again later or inform IT." delegate:self cancelButtonTitle:@"Back" otherButtonTitles:nil, nil];
                    [alert show];
                }
            }
</code>```

get the following error when I put error handling outside:

```<code>[2664:3215894] Unable to save managed object context.
    2017-06-07 14:48:22.644 [2664:3215894] (null), (null)
    2017-06-07 14:48:22.778 [2664:3215894] This application is modifying the autolayout engine from a background thread, which can lead to engine corruption and weird crashes.  This will cause an exception in a future release.
</code>```

答:
No there is no data loss.

It's even the recommended way to commit the data (once) after batch operations.

But you should also move the error handling displaying Unable to save... out of the loop after the save line. (Btw: UIAlertView is deprecated for a long time).

Body:
Is there any loss in data if I save outside the loop when adding objects vs when I do it inside the loop? Asking since saving outside is much faster.

Outside Loop:

for(NSMutableDictionary *result in data){
            [manager newManagedCaf];
            for (NSString *name in result){
                if ([name isEqualToString:@"contact"]){
                NSNumber *num = [NSNumber numberWithInteger:[[result valueForKey:name] integerValue]];
                    [[manager cafCards] setValue:num forKey:name];
                }
                else{
                    [[manager cafCards] setValue:[result valueForKey:name] forKey:name];
                }
            }
            [[manager cafCards] setValue:[NSNumber numberWithBool:YES] forKey:@"synced"];
            }
        }
    if(![[manager cafCards].managedObjectContext save:&error]){
        NSLog(@"Unable to save managed object context.");
        NSLog(@"%@, %@", error, error.localizedDescription);
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:[NSString stringWithFormat:@"Error: %@", [error localizedDescription]] message:@"Database not working, try again later or inform IT." delegate:self cancelButtonTitle:@"Back" otherButtonTitles:nil, nil];
        [alert show];
        [self getImages:0 con:con withManager:manager];
   }

Inside Loop:

 for(NSMutableDictionary *result in data){
                [manager newManagedCaf];
                for (NSString *name in result){
                    if ([name isEqualToString:@"contact"]){
                    NSNumber *num = [NSNumber numberWithInteger:[[result valueForKey:name] integerValue]];
                        [[manager cafCards] setValue:num forKey:name];
                    }
                    else{
                        [[manager cafCards] setValue:[result valueForKey:name] forKey:name];
                    }
                }

                [[manager cafCards] setValue:[NSNumber numberWithBool:YES] forKey:@"synced"];
                if(![[manager cafCards].managedObjectContext save:&error]){
                    NSLog(@"Unable to save managed object context.");
                    NSLog(@"%@, %@", error, error.localizedDescription);
                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:[NSString stringWithFormat:@"Error: %@", [error localizedDescription]] message:@"Database not working, try again later or inform IT." delegate:self cancelButtonTitle:@"Back" otherButtonTitles:nil, nil];
                    [alert show];
                }
            }

get the following error when I put error handling outside:

[2664:3215894] Unable to save managed object context.
    2017-06-07 14:48:22.644 [2664:3215894] (null), (null)
    2017-06-07 14:48:22.778 [2664:3215894] This application is modifying the autolayout engine from a background thread, which can lead to engine corruption and weird crashes.  This will cause an exception in a future release.


问:
Commercial Use of a Recorded Output of Speech Synthesis made via Web Speech API
I know this is NOT the right forum, but I couldn't find a better one... It's a legal question intended for the MDN team members.

I use the Web Speech API via Chrome / Firefox to synthesize speech of my original text.
I record the output audio using some other software.

Do I own the copyrights to that recording? Can I sell the recorded audio file? Can I use it in my commercial YouTubes for instance?

It would seem to me - I am indeed the owner of the recording, as the speech api is given as one of the browser's services, which I can use to produce my own content. But - I would like to be sure.

The closest answer by Google I saw is here:
https://lists.w3.org/Archives/Public/public-speech-api/2013Jul/0001.html
Which says the web speech api can be used for commercial. My specific question is about the recorded audio file.

答:
We've asked a copyrights attorney - See full answer here.

Here's the summary:

You do own the copyrights.

Owning the copyrights does NOT necessarily grant permission for commercial use, as you might be bound to contractual obligations (as is the case for iOS voices for instance).


问:
CoreData: Ubiquity: Using local storage: 1 never becomes 0
I am working on upgrading an App with iOS6's CoreData+iCloud to iOS7. According to the Apple's WWDC video, "CoreData: Ubiquity: Using local storage: 1" shall become "CoreData: Ubiquity: Using local storage: 0", when CoreData get ready the iCloud Core Data store.

I have successfully tested this on the simulator. The funny thing is that this never happens to my iPhone 5. I have checked the iCloud Settings in Setting, but still have no luck.

Image attached below is the screenshot from xCode's iCloud Debugging panel. Interestingly, there is a baseline.zip file that I could never get it Current. This shall be the zombie file from iOS6's iCloud... Is it related?

Any help is appreciated.

Thank you.

答: I have this issue, when my iPhone is using cellular only. If I enable Wifi, then it works. That is very disappointing! </p>


问:
Character Width of Number Values in TSQL?
MSSSQL 2008.

I have 3 Ints, 1 BigInt, 1 Float, and 1 DateTime value.
I am trying to concatenate them all into a single Char value and not lose any precision, which should let me create a single unique long value.

What are would the total character width be if I could make all of the numbers Chars and then combine them? The DateTime should go to MMDDYYHHMMSS.

Thanks.

答:
INTs can be up to 10 digits.
BIGINTs can be up to 19 digits.
Floats could be anything.  They have 38 digits of precision, but could be an enormous number with limited precision (1.79E + 308).  You don't want that as a string.  If your application has knowledge of what the actual range of values the float could be, you could make an application decision for a specific number of digits.</p>


问:
Converting Node.js command line app to web app
So this is more of an open ended question: I've started working with node and I've been creating command line applications for practice. The majority of these apps take command line arguments and make http requests to an API and serve up the results based on the arguments passed. The thing is, I would like these programs to have useful front-end interfaces so that the results are not just display via the command line terminal. Is there an easy way to accomplish this? Is this what Express is useful for?</p>

答:
perhaps more fully, that's what express is for and that's what routes do for you - so that your browser can be directed to a default (e.g. index.html) page or a specific page or service. If you're rendering basic html pages, stored in an /HTML folder, to the user, then you might have the following kind of code in your app:

```<code>var express = require('express');
var app = express();
app.engine('html', require('ejs').renderFile);
app.use(express.static(__dirname + '/HTML'));
</code>```

followed by a series of app.get('path/from/browser') and/or app.post('path/from/broswer') statements which tell your nodejs server what to do when various get and post commands are sent to the app.

as your app gets more complex, you may want to consider the router service as a way to structure your application code and associated services.

you also need to start an http server, so the browser can actually talk to the server. You would do that in a very simple way by executing the following code:

```<code>var cfenv = require('cfenv');
var appEnv = cfenv.getAppEnv();
app.set('port', appEnv.port);
var server = app.listen(app.get('port'), function() {console.log('Listening on port %d', server.address().port);});
</code>```

In this simple example, your app is now using 3 new services: express, ejs, and cfenv. You would use the standard npm install process to get this into your local app so that you can use them. From your application root folder, you would execute npm install --save express, repeating for each of the three new services.

Body:
perhaps more fully, that's what express is for and that's what routes do for you - so that your browser can be directed to a default (e.g. index.html) page or a specific page or service. If you're rendering basic html pages, stored in an /HTML folder, to the user, then you might have the following kind of code in your app:

var express = require('express');
var app = express();
app.engine('html', require('ejs').renderFile);
app.use(express.static(__dirname + '/HTML'));

followed by a series of app.get('path/from/browser') and/or app.post('path/from/broswer') statements which tell your nodejs server what to do when various get and post commands are sent to the app.

as your app gets more complex, you may want to consider the router service as a way to structure your application code and associated services.

you also need to start an http server, so the browser can actually talk to the server. You would do that in a very simple way by executing the following code:

var cfenv = require('cfenv');
var appEnv = cfenv.getAppEnv();
app.set('port', appEnv.port);
var server = app.listen(app.get('port'), function() {console.log('Listening on port %d', server.address().port);});

In this simple example, your app is now using 3 new services: express, ejs, and cfenv. You would use the standard npm install process to get this into your local app so that you can use them. From your application root folder, you would execute npm install --save express, repeating for each of the three new services.


问:
when a css ul li item extends past ul, how to match dynamic width of an ul
JSFiddle of the problem: https://jsfiddle.net/td6szj3o/

/
i have an ul li with standard text items per each li. the list is dynamic, so sometimes each content li is smaller than the set width:100% of the container it sits in, but sometimes a li item has text that expands past the width:100% of the container. instead of forcing the text to the next line, i am wanting to keep the long text extending past the ul. currently that works fine with little extra css styling to the ul.

using this method, i see a bottom scroller that pops up under the ul and allows me to scroll to the right to view the rest of the li content. that is fine for me and i want to keep this.

however i am introduced to a problem trying to keep the alternate li background color that is so popular and often standard with most data output in an unordered list. since the css of the li that sits in the ul is width:100%, and the ul itself stops at the width:100%, the li extends only as far as the ul width. but the problem is while the text is extending past the li, it technically is outside of the width:100% of the ul itself, and thus the background color on the li stops wherever the ul width ends.

i am trying to come to a solution that would work in all browsers, that will allow the ul to have the li item extend to the full width of the longest content of any li. the closest i have gotten is using display:table-header-group, but unfortunately it does not expand to width:100% when i have small text content inside the li.

i could simply add a min-width:300px or something to the ul, and this would fix my problem. but that isn't going to cut it when user is on a smaller device or monitor size unfortunately. when i use min-width:100% that does not solve the issue either. i have used every combination of display:XXX that i can come up with, and when i float:left anything in the ul or li, that breaks the view either for the smaller text ul output, or the longer text ul output, or both at the same time.

any help or guidance on this would be greatly appreciated. i am looking for a solution that works in all latest versions of Chrome, FF, Safari, etc; and sticks to a css solution.

please note i intentionally have left word-wrapping off of the css. i do not want the text to go to the next line, but instead keep being displayed horizontally across the ul.

below is the html/css i am using:

```<code><ul>
<li>dynamic li item would be here; nothing crazy</li>
</ul>

.sidebar ul {
    position:relative;
    max-height:55vh;
    min-height:10em;
    margin:0;
    width:100%;
}
.node-list{
    white-space:nowrap;
    padding-bottom: 2em;
}
.node-list li{
    padding: .15em .5em .15em .35em;
    margin:0;
    border-left: solid 2px transparent;
    max-width:100%;
    width:auto;
}
.node-list li a{
    color: rgb(73,73,73);
    font-weight: bold;
    text-decoration: none;
}
.node-list li:nth-of-type(2n){
    background-color: rgb(242,242,242)
}
.node-list li:nth-of-type(2n-1){
    background-color: rgb(255,255,255)
}
</code>```

答:
Set sidebar ul to display: inline-block and change from width: 100% to min-width: 100%

Updated fiddle

Stack snippet

.sidebar ul {
  position: relative;
  max-height: 55vh;
  min-height: 10em;
  margin: 0;
  min-width: 100%;                 /*  changed property */
  display: inline-block;           /*  added property   */
}

.node-list {
  white-space: nowrap;
  padding-bottom: 2em;
}

.node-list li {
  padding: .15em .5em .15em .35em;
  margin: 0;
  border-left: solid 2px transparent;
  max-width: 100%;
  width: auto;
}

.node-list li a {
  color: rgb(73, 73, 73);
  font-weight: bold;
  text-decoration: none;
}

.node-list li:nth-of-type(2n) {
  background-color: rgb(242, 242, 242)
}

.node-list li:nth-of-type(2n-1) {
  background-color: rgb(255, 255, 255)
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="sidebar">
  <ul class="node-list">
    <li>Lorem</li>
    <li>Two of the nation's top intelligence officials repeatedly refused to say Wednesday whether President Donald Trump asked them to intervene in or downplay the FBI's ongoing Russia investigation, though they said they have never felt pressure to act</li>
    <li>Lorem</li>
    <li>Two of the nation's top intelligence officials repeatedly refused to say Wednesday whether President Donald Trump asked them to intervene in or downplay the FBI's ongoing Russia investigation, though they said they have never felt pressure to act</li>
    <li>Lorem</li>
    <li>Two of the nation's top intelligence officials repeatedly refused to say Wednesday whether President </li>
  </ul>
</div></code>```

Body:
JSFiddle of the problem: https://jsfiddle.net/td6szj3o/

/
i have an ul li with standard text items per each li. the list is dynamic, so sometimes each content li is smaller than the set width:100% of the container it sits in, but sometimes a li item has text that expands past the width:100% of the container. instead of forcing the text to the next line, i am wanting to keep the long text extending past the ul. currently that works fine with little extra css styling to the ul.

using this method, i see a bottom scroller that pops up under the ul and allows me to scroll to the right to view the rest of the li content. that is fine for me and i want to keep this.

however i am introduced to a problem trying to keep the alternate li background color that is so popular and often standard with most data output in an unordered list. since the css of the li that sits in the ul is width:100%, and the ul itself stops at the width:100%, the li extends only as far as the ul width. but the problem is while the text is extending past the li, it technically is outside of the width:100% of the ul itself, and thus the background color on the li stops wherever the ul width ends.

i am trying to come to a solution that would work in all browsers, that will allow the ul to have the li item extend to the full width of the longest content of any li. the closest i have gotten is using display:table-header-group, but unfortunately it does not expand to width:100% when i have small text content inside the li.

i could simply add a min-width:300px or something to the ul, and this would fix my problem. but that isn't going to cut it when user is on a smaller device or monitor size unfortunately. when i use min-width:100% that does not solve the issue either. i have used every combination of display:XXX that i can come up with, and when i float:left anything in the ul or li, that breaks the view either for the smaller text ul output, or the longer text ul output, or both at the same time.

any help or guidance on this would be greatly appreciated. i am looking for a solution that works in all latest versions of Chrome, FF, Safari, etc; and sticks to a css solution.

please note i intentionally have left word-wrapping off of the css. i do not want the text to go to the next line, but instead keep being displayed horizontally across the ul.

below is the html/css i am using:

dynamic li item would be here; nothing crazy

.sidebar ul {
    position:relative;
    max-height:55vh;
    min-height:10em;
    margin:0;
    width:100%;
}
.node-list{
    white-space:nowrap;
    padding-bottom: 2em;
}
.node-list li{
    padding: .15em .5em .15em .35em;
    margin:0;
    border-left: solid 2px transparent;
    max-width:100%;
    width:auto;
}
.node-list li a{
    color: rgb(73,73,73);
    font-weight: bold;
    text-decoration: none;
}
.node-list li:nth-of-type(2n){
    background-color: rgb(242,242,242)
}
.node-list li:nth-of-type(2n-1){
    background-color: rgb(255,255,255)
}

Body:
Set sidebar ul to display: inline-block and change from width: 100% to min-width: 100%

Updated fiddle

Stack snippet

.sidebar ul {
  position: relative;
  max-height: 55vh;
  min-height: 10em;
  margin: 0;
  min-width: 100%;                 /*  changed property */
  display: inline-block;           /*  added property   */
}

.node-list {
  white-space: nowrap;
  padding-bottom: 2em;
}

.node-list li {
  padding: .15em .5em .15em .35em;
  margin: 0;
  border-left: solid 2px transparent;
  max-width: 100%;
  width: auto;
}

.node-list li a {
  color: rgb(73, 73, 73);
  font-weight: bold;
  text-decoration: none;
}

.node-list li:nth-of-type(2n) {
  background-color: rgb(242, 242, 242)
}

.node-list li:nth-of-type(2n-1) {
  background-color: rgb(255, 255, 255)
}

<div class="sidebar">
  <ul class="node-list">
    <li>Lorem</li>
    <li>Two of the nation's top intelligence officials repeatedly refused to say Wednesday whether President Donald Trump asked them to intervene in or downplay the FBI's ongoing Russia investigation, though they said they have never felt pressure to act</li>
    <li>Lorem</li>
    <li>Two of the nation's top intelligence officials repeatedly refused to say Wednesday whether President Donald Trump asked them to intervene in or downplay the FBI's ongoing Russia investigation, though they said they have never felt pressure to act</li>
    <li>Lorem</li>
    <li>Two of the nation's top intelligence officials repeatedly refused to say Wednesday whether President </li>
  </ul>
</div>


问:
Specifications other than OpenAPI Specification to document a restful API
First to have a clear idea of the OpenAPI Specification itself is, let's see how it is defined on its official website (https://github.com/OAI/OpenAPI-Specification):

The goal of The OpenAPI Specification is to define a standard,
  language-agnostic interface to REST APIs which allows both humans and
  computers to discover and understand the capabilities of the service
  without access to source code, documentation, or through network
  traffic inspection

Question: OpenAPI defines a specification on how an API documentation needs to be written in YAML or JSON. Now the question arises if it is the only specification out there to do this job? Or there are other alternatives for the same?

I had my research online, but came to no conclusion.

Note: This question might be asked to software recommendation, but as "Specification" cannot be called "Software" I decided to ask it on stackoverflow.

答:
I got to an online course from Pluralsight, Five Essential Tools for Building REST APIs, and could find the following two tools as alternatives of OpenAPI Specifiations:

RAML (http://raml.org/)

API blueprint (https://apiblueprint.org/)

These are two alternatives for OpenAPI Specifications, and are to some extent newer and richer in their specifications. However, as they very new, they are not well recognized by organizations, and tooling support is limited. Most of their tools they currently support are cloud based.


问:
PHP Shouldnot Repeat and should be from an array
I'm trying to build a script that does two thing.
1) The Numbers should not repeat.
2) The numbers should be from an array called $id.

```<code><?php
$a = array(); // final array which will have our id's to display
$id = array(1, 3, 5, 7, 9); //final array should contain a number only from this list
$itemstoshow = 3; // how many items to display
for($i = 0; $i < $itemstoshow; $i++) {
    do {
        $a[$i] = assignid(9);
        $chkid = checkeer($a[$i], $i);
        $chkdata = chkdata($a[$i], $i);
    } while($chkdata == "nonexist" or $chkid == "repeatedid");
}

// display numbers in the array
for($i = 0; $i < $itemstoshow; $i++) {
    echo "Item " . $a[$i] . "--------";
}

// check for redundancy function
function checkeer($x, $y)
{  //first parameter is query aray second is counter
    global $a;
    $err = 0;
    // check if repeating number
    for($i = 0; $i <= $y - 1; $i++) {
        if($x == $a[$i]) {
            $err = 1;
        }
    }
    if($err == 1) {
        return "repeatedid";
    }
}

//check if array $a holds value from $id or not
function chkdata($x, $y)
{
    global $a;
    global $id;
    for($i = 0; $i <= $y - 1; $i++) {
        if($x !== $id[$i]) {
            return "nonexist";
        }
    }

}

//assign id function
function assignid($x)
{
    return rand(1, $x);
}
</code>```

problem number 1 solved problem number 2 still not solved please help me.
the code should show 3 numbers from 1 to 9 which donot repeat and are in the array $id

答:
You can use array_rand that selects random keys:

```<code>$id = array(1,3,5,7,9);
$result = array_intersect_key($id, array_flip(array_rand($id, 3)));
</code>```

Or you can shuffle the array and take for example the 3 first items:

```<code>$id = array(1,3,5,7,9);
$temp = $id;
shuffle($temp);
for ($i = 0; $i < 3; $i++) {
    $result[] = $temp[$i];
}
</code>```

Body:
I'm trying to build a script that does two thing.
1) The Numbers should not repeat.
2) The numbers should be from an array called $id.

<?php
$a = array(); // final array which will have our id's to display
$id = array(1, 3, 5, 7, 9); //final array should contain a number only from this list
$itemstoshow = 3; // how many items to display
for($i = 0; $i < $itemstoshow; $i++) {
    do {
        $a[$i] = assignid(9);
        $chkid = checkeer($a[$i], $i);
        $chkdata = chkdata($a[$i], $i);
    } while($chkdata == "nonexist" or $chkid == "repeatedid");
}

// display numbers in the array
for($i = 0; $i < $itemstoshow; $i++) {
    echo "Item " . $a[$i] . "--------";
}

// check for redundancy function
function checkeer($x, $y)
{  //first parameter is query aray second is counter
    global $a;
    $err = 0;
    // check if repeating number
    for($i = 0; $i <= $y - 1; $i++) {
        if($x == $a[$i]) {
            $err = 1;
        }
    }
    if($err == 1) {
        return "repeatedid";
    }
}

//check if array $a holds value from $id or not
function chkdata($x, $y)
{
    global $a;
    global $id;
    for($i = 0; $i <= $y - 1; $i++) {
        if($x !== $id[$i]) {
            return "nonexist";
        }
    }

}

//assign id function
function assignid($x)
{
    return rand(1, $x);
}

problem number 1 solved problem number 2 still not solved please help me.
the code should show 3 numbers from 1 to 9 which donot repeat and are in the array $id

Body:
You can use array_rand that selects random keys:

$id = array(1,3,5,7,9);
$result = array_intersect_key($id, array_flip(array_rand($id, 3)));

Or you can shuffle the array and take for example the 3 first items:

$id = array(1,3,5,7,9);
$temp = $id;
shuffle($temp);
for ($i = 0; $i < 3; $i++) {
    $result[] = $temp[$i];
}


问:
Update of jhipster generator won't work
Jhipster generator says that I should install the update:

JHipster update available: 4.5.2 (current: 4.3.0)

If I try to run yarn global upgrade generator-jhipster as suggested, everything works fine.

```<code>success Saved 1 new dependency.
└─ generator-jhipster@4.5.2
warning No license field
✨  Done in 3.18s.
</code>```

But if I try to generate a new project, I get the same update message again.
Would appreciate any help on this.

答:
There are several problems could happen here. In general, handling NPM/yarn modules depend very on a proper installation of npm and yarn. In e.g. I often ran into different issues, as I installed yo and generator-jhipster using npm, while used them later in yarn. A clean install of npm, then yarn, then yarn global add yo and yarn global add generator-jhipster solved my issues.

The first thing I would check, is if you get the "update available" message in other directories, rather the project root. JHipster always places a copy of the currently used version to the project as you generate it the first time, to make sure you don't break your code when using newer JHipster versions for new projects, but still use yo jhipster:entity and other post-generation commands.

Another thing is if you use jhipster instead of yo jhipster. There is an issue that the JHipster client doesn't recognize a newer version, while yo jhipster does.

if all that doesn't help:
if the "nice" ways of solving your issue don't help, there is a "crowbar style" solution I can suggest:

in a separate directory, run git clone https://github.com/jhipster/generator-jhipster

to specify the target version, check out a tag by git checkout v4.5.2

run yarn link

in your project root, run yarn link generator-jhipster

this will definitely will link the correct version into your project

Title: Update of jhipster generator won't work

Body:
Jhipster generator says that I should install the update:

JHipster update available: 4.5.2 (current: 4.3.0)

If I try to run yarn global upgrade generator-jhipster as suggested, everything works fine.

success Saved 1 new dependency.
└─ generator-jhipster@4.5.2
warning No license field
✨  Done in 3.18s.

But if I try to generate a new project, I get the same update message again.
Would appreciate any help on this.


问:
Replacing Path parts in Rust
Suppose I have the following three paths:

```<code>let file = path::Path::new("/home/meurer/test/a/01/foo.txt");
let src = path::Path::new("/home/meurer/test/a");
let dst = path::Path::new("/home/meurer/test/b");
</code>```

Now, I want to copy file into dst, but for that I need to correct the paths, so that I can have new_file with a path that resolves to /home/meurer/test/b/01/foo.txt. In other words, how do I remove src from file and then append the result to dst?

/home/meurer/test/a/01/foo.txt -> /home/meurer/test/b/01/foo.txt

Note that we can't assume that src will always be this similar to dst.

答:
You can use Path::strip_prefix and Path::join:

```<code>use std::path::Path;

fn main() {
    let file = Path::new("/home/meurer/test/a/01/foo.txt");
    let src = Path::new("/home/meurer/test/a");
    let dst = Path::new("/home/meurer/test/b");

    let relative = file.strip_prefix(src).expect("Not a prefix");
    let result = dst.join(relative);

    assert_eq!(result, Path::new("/home/meurer/test/b/01/foo.txt"));
}
</code>```

As usual, you probably don't want to use expect in your production code, it's only for terseness of the answer.

Title: Replacing Path parts in Rust

Body:
Suppose I have the following three paths:

let file = path::Path::new("/home/meurer/test/a/01/foo.txt");
let src = path::Path::new("/home/meurer/test/a");
let dst = path::Path::new("/home/meurer/test/b");

Now, I want to copy file into dst, but for that I need to correct the paths, so that I can have new_file with a path that resolves to /home/meurer/test/b/01/foo.txt. In other words, how do I remove src from file and then append the result to dst?

/home/meurer/test/a/01/foo.txt -> /home/meurer/test/b/01/foo.txt

Note that we can't assume that src will always be this similar to dst.

Body:
You can use Path::strip_prefix and Path::join:

use std::path::Path;

fn main() {
    let file = Path::new("/home/meurer/test/a/01/foo.txt");
    let src = Path::new("/home/meurer/test/a");
    let dst = Path::new("/home/meurer/test/b");

    let relative = file.strip_prefix(src).expect("Not a prefix");
    let result = dst.join(relative);

    assert_eq!(result, Path::new("/home/meurer/test/b/01/foo.txt"));
}

As usual, you probably don't want to use expect in your production code, it's only for terseness of the answer.


问:
Disable async Google Analytics loading
I have this code decorating urls with Analytics' cookie in my webpage.

```<code>var tracker = window[window.GoogleAnalyticsObject].getAll()[0];
new window.gaplugins.Linker(tracker).decorate("http://www.toto.com");
</code>```

This occurs an error :

window[window.GoogleAnalyticsObject].getAll is not a function

window.gaplugins is undefined

Like Google Analytics load its plugin asynchrously, i imagine getAll() and gaplugins.linker functions are not declared yet.
I can't wait the DOM ready, so i would like to force synchrously GA plugin loading.

Thanks for your help

答:
Instead of forcing it execute syncronously the best option is to use a callback function to execute your code.

Like this:

```<code>(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');

ga('create', 'UA-XXXXXX-1', 'auto');
ga('send', 'pageview');
ga(function(){
  // Code in here will only run after ga is loaded.
  window.tracker = window[window.GoogleAnalyticsObject].getAll()[0];
  new window.gaplugins.Linker(tracker).decorate("http://www.toto.com");
})
</code>```

Title: Disable async Google Analytics loading

Body:
I have this code decorating urls with Analytics' cookie in my webpage.

var tracker = window[window.GoogleAnalyticsObject].getAll()[0];
new window.gaplugins.Linker(tracker).decorate("http://www.toto.com");

This occurs an error :

window[window.GoogleAnalyticsObject].getAll is not a function

window.gaplugins is undefined

Like Google Analytics load its plugin asynchrously, i imagine getAll() and gaplugins.linker functions are not declared yet.
I can't wait the DOM ready, so i would like to force synchrously GA plugin loading.

Thanks for your help

Body:
Instead of forcing it execute syncronously the best option is to use a callback function to execute your code.

Like this:

(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');

ga('create', 'UA-XXXXXX-1', 'auto');
ga('send', 'pageview');
ga(function(){
  // Code in here will only run after ga is loaded.
  window.tracker = window[window.GoogleAnalyticsObject].getAll()[0];
  new window.gaplugins.Linker(tracker).decorate("http://www.toto.com");
})


问:
missing compilation references in Razor pages after adding model
I am creating a .NET Core web app using framework 4.6.2. I built my first view, testing throughout, until I added my view model and the page now errors out whenever I navigate to it. The errors are shown below. The ViewModel has all of the referenced properties on it. I don't even have a project.json given it's a brand new project on VS17.

答: This will happen if the properties you're using on your view model are not marked public. In my case, I had them marked internal and so was getting this error.