问:
Searching strings where substring occur at specific positions with negative look-ahead
I am just facing a probem when trying to create a regex which should help finding strings including specific combinations of substrings.

For example i am searching for the substring combination:

ab-ab-cd

1) "xxxabxxxxxxabxxxxcdxxx" -> should be a match

2) "xxxabxxxxabxxxxabxxxxcdxxxx -> no match

3) "xxxabxxxxxxxxxxcdxxxx -> no match

to make it even more complicated:

4) "xxxabxxxxxabxxxxcdxxxabxxx -> should also be a match

My substring combinations could also be like this:

ab-cd

or

ab-ab-ab-cd

or

ab-cd-ab-cd

For all these (and more) examples I am looking for a systematic way to build the corresponding regexes in a systematic way so that only strings are found as matches where the substrings occur in the right order and with correct frequency.

I got something like this for the "ab-ab-cd" substring search but it fails in cases like 4) of my examples.

```<code>p = re.compile("(?:(?!ab).)*ab.*?ab(?!.*ab).*cd",re.IGNORECASE)
</code>```

In cases like 4) this one works in but in also matches strings like 2):

```<code>p = re.compile("(?:(?!ab).)*ab(?:(?!ab).)*ab((?!ab|cd)*).*cd", re.IGNORECASE)
</code>```

Could you please point me to my mistake?

Thanks a lot!

EDIT:

Sorry to all, that my question was not clear enough. I tried to break my problem down into a more simple case, which might have been no good idea.
Here comes the detailed explanation of the problem:

I have list of (protein) sequences and to assign a specific type to each sequence on the basis of sequence patterns.

Therefore I created a dictionary with type-name as key and feature template (list of sequence features in a specific order) as value, e.g.:

type_a -> [A,A,B,C]

type_b -> [A,B,C]

type_c -> [A,B,A,B]

In other dict I have (simple) regex patters for each feature, e.g.:

A -> [PHT]AG[QP]LI

B -> RS[TP]EV

C -> ...

D -> ...

Now each template (type_a, type_b,...) I now to systematically build the concatenated regex patters (i.e. for type_a build a regex searching for A,A,B,C).
That would than result into another dict with types as key and and the complete regex as value.

Now I want to go through each sequence in my list of sequences and map all complete regex templates against each sequence. In best case, only one complete regex (type) should match the sequence.

Taking the example from above, having the following regex-templates:

cd

ab-cd

ab-ab-cd

ab-ab-ab-cd

ab-cd-ab-cd

ab-ab-cd-ab

"xxxabxxxxxxabxxxxcdxxx"

->this sequence should match the regex for the template "ab-ab-cd" and not any of the others

With the following regex I could perfectly look for ab-ab-cd.

```<code>p = re.compile("(?:(?!ab).)*ab.*?ab(?!.*ab).*cd",re.IGNORECASE)
</code>```

If my tests were correct it would only match sequence 1) from above and not 2) or 3).

However, if I would like to search for ab-ab-cd-ab the negative look-ahead would not allow to find the last ab. I found something like the following code to break the negative look-ahead after the second "ab" part. In my understand the negative look-ahead should stop with the "cd", so that the last "ab" could be matches again.

```<code>p = re.compile("(?:(?!ab).)*ab(?:(?!ab).)*ab((?!ab|cd)*).*cd", re.IGNORECASE)
</code>```

It solves the problem with the last "ab" from ab-ab-cd-ab.
But somehow it now does not only match the for 2 times "ab" before the "cd" (Sequence 1) - ab-ab-cd) but also the 3 (or more) times "ab" before the "cd" (Sequence 2, ab-ab-ab-cd), which it should not.

I hope my problem is more clear. Thanks a lot for all the answers, I will try the code tomorrow when I am back at work. Any further answers are highly appreciated, explanations of the regex code (I am pretty new to regex) and suggestions with re.functions (match, final...) to use.

Thanks

答:
You could use re.findall and post-process it. Effectively you want to find all instances of ab or cd and see if your pattern(['ab', 'ab', 'cd']) is at the start of the list. The following:

```<code>import re

test1 = "xxxabxxxxxxabxxxxcdxxx"
test2 = "xxxabxxxxabxxxxabxxxxcdxxxx"
test3 = "xxxabxxxxxxxxxxcdxxxx"
test4 = "xxxabxxxxxabxxxxcdxxxabxxx"

for x in (test1, test2, test3, test4):
    matches = re.findall(r'(ab|cd)', x)
    print matches[:3] == ['ab', 'ab', 'cd']
</code>```

prints

```<code>True
False
False
True
</code>```

As required.

Body:
I am just facing a probem when trying to create a regex which should help finding strings including specific combinations of substrings.

For example i am searching for the substring combination:

ab-ab-cd

1) "xxxabxxxxxxabxxxxcdxxx" -> should be a match

2) "xxxabxxxxabxxxxabxxxxcdxxxx -> no match

3) "xxxabxxxxxxxxxxcdxxxx -> no match

to make it even more complicated:

4) "xxxabxxxxxabxxxxcdxxxabxxx -> should also be a match

My substring combinations could also be like this:

ab-cd

or

ab-ab-ab-cd

or

ab-cd-ab-cd

For all these (and more) examples I am looking for a systematic way to build the corresponding regexes in a systematic way so that only strings are found as matches where the substrings occur in the right order and with correct frequency.

I got something like this for the "ab-ab-cd" substring search but it fails in cases like 4) of my examples.

p = re.compile("(?:(?!ab).)*ab.*?ab(?!.*ab).*cd",re.IGNORECASE)

In cases like 4) this one works in but in also matches strings like 2):

p = re.compile("(?:(?!ab).)*ab(?:(?!ab).)*ab((?!ab|cd)*).*cd", re.IGNORECASE)

Could you please point me to my mistake?

Thanks a lot!

EDIT:

Sorry to all, that my question was not clear enough. I tried to break my problem down into a more simple case, which might have been no good idea.
Here comes the detailed explanation of the problem:

I have list of (protein) sequences and to assign a specific type to each sequence on the basis of sequence patterns.

Therefore I created a dictionary with type-name as key and feature template (list of sequence features in a specific order) as value, e.g.:

type_a -> [A,A,B,C]

type_b -> [A,B,C]

type_c -> [A,B,A,B]

In other dict I have (simple) regex patters for each feature, e.g.:

A -> [PHT]AG[QP]LI

B -> RS[TP]EV

C -> ...

D -> ...

Now each template (type_a, type_b,...) I now to systematically build the concatenated regex patters (i.e. for type_a build a regex searching for A,A,B,C).
That would than result into another dict with types as key and and the complete regex as value.

Now I want to go through each sequence in my list of sequences and map all complete regex templates against each sequence. In best case, only one complete regex (type) should match the sequence.

Taking the example from above, having the following regex-templates:

cd

ab-cd

ab-ab-cd

ab-ab-ab-cd

ab-cd-ab-cd

ab-ab-cd-ab

"xxxabxxxxxxabxxxxcdxxx"

->this sequence should match the regex for the template "ab-ab-cd" and not any of the others

With the following regex I could perfectly look for ab-ab-cd.

p = re.compile("(?:(?!ab).)*ab.*?ab(?!.*ab).*cd",re.IGNORECASE)

If my tests were correct it would only match sequence 1) from above and not 2) or 3).

However, if I would like to search for ab-ab-cd-ab the negative look-ahead would not allow to find the last ab. I found something like the following code to break the negative look-ahead after the second "ab" part. In my understand the negative look-ahead should stop with the "cd", so that the last "ab" could be matches again.

p = re.compile("(?:(?!ab).)*ab(?:(?!ab).)*ab((?!ab|cd)*).*cd", re.IGNORECASE)

It solves the problem with the last "ab" from ab-ab-cd-ab.
But somehow it now does not only match the for 2 times "ab" before the "cd" (Sequence 1) - ab-ab-cd) but also the 3 (or more) times "ab" before the "cd" (Sequence 2, ab-ab-ab-cd), which it should not.

I hope my problem is more clear. Thanks a lot for all the answers, I will try the code tomorrow when I am back at work. Any further answers are highly appreciated, explanations of the regex code (I am pretty new to regex) and suggestions with re.functions (match, final...) to use.

Thanks

Body:
You could use re.findall and post-process it. Effectively you want to find all instances of ab or cd and see if your pattern(['ab', 'ab', 'cd']) is at the start of the list. The following:

import re

test1 = "xxxabxxxxxxabxxxxcdxxx"
test2 = "xxxabxxxxabxxxxabxxxxcdxxxx"
test3 = "xxxabxxxxxxxxxxcdxxxx"
test4 = "xxxabxxxxxabxxxxcdxxxabxxx"

for x in (test1, test2, test3, test4):
    matches = re.findall(r'(ab|cd)', x)
    print matches[:3] == ['ab', 'ab', 'cd']

prints

True
False
False
True

As required.


来源: stackexchange

问:
iOS: Animating a circle slice into a wider one
Core-Animation treats angles as described in this image:
(image from http://btk.tillnagel.com/tutorials/rotation-translation-matrix.html)

EDIT: Adding an animated gif to explain better what I'm needing:

I need to animate a slice to grow wider, starting at 300:315 degrees, and ending 300:060.

To create each slice I'm using this function:

```<code>extension CGFloat {
    func toRadians() -> CGFloat {
        return self * CGFloat(Double.pi) / 180.0
    }
}
func createSlice(angle1:CGFloat, angle2:CGFloat) -> UIBezierPath! {
    let path: UIBezierPath = UIBezierPath()
    let width: CGFloat = self.frame.size.width/2
    let height: CGFloat = self.frame.size.height/2
    let centerToOrigin: CGFloat = sqrt((height)*(height)+(width)*(width));
    let ctr: CGPoint = CGPoint(x: width, y: height)
    path.move(to: ctr)
    path.addArc( withCenter: ctr,
                 radius: centerToOrigin,
                 startAngle: CGFloat(angle1).toRadians(),
                 endAngle: CGFloat(angle2).toRadians(),
                 clockwise: true
    )
    path.close()
    return path
}
</code>```

I can now create the two slices and a sublayer with the smaller one, but I can't find how to proceed from this point:

```<code>func doStuff() {
    path1 = self.createSlice(angle1: 300,angle2: 315)
    path2 = self.createSlice(angle1: 300,angle2: 60)

    let shapeLayer = CAShapeLayer()
    shapeLayer.path = path1.cgPath
    shapeLayer.fillColor = UIColor.cyan.cgColor
    self.layer.addSublayer(shapeLayer)
</code>```

I would highly appreciate any help here!

答:
Only a single color

If you want to animate the angle of a solid color filled pie segment like the one in your question, then you can do it by animating the strokeEnd of a CAShapeLayer.

The "trick" here is to make a very wide line. More specifically, you can create a path that is just an arc (the dashed line in the animation below) at half of the intended radius and then giving it the full radius as its line width. When you animate stroking that line it looks like the orange segment below:

Depending on your use case, you can either:

create a path from one angle to the other angle and animate stroke end from 0 to 1

create a path for a full circle, set stroke start and stroke end to some fraction of the circle, and animate stroke end from the start fraction to the end fraction.

If your drawing is just a single color like this, then this will be the smallest solution to your problem.

However, if your drawing is more complex (e.g. also stroking the pie segment) then this solutions simply won't work and you'll have to do something more complex.

Custom drawing / Custom animations

If your drawing of the pie segment is any more complex, then you'll quickly find yourself having to create a layer subclass with custom animatable properties. Doing so is a bit more code - some of which might look a bit unusual1 - but not as scary as it might sound.

This might be one of those things that is still more convenient to do in Objective-C.

Dynamic properties

First, create a layer subclass with the properties you're going to need. In Objective-C parlance these properties should be @dynamic, i.e. not synthesized. This isn't the same as dynamic in Swift. Instead we have to use @NSManaged.

```<code>class PieSegmentLayer : CALayer {
    @NSManaged var startAngle, endAngle, strokeWidth: CGFloat
    @NSManaged var fillColor, strokeColor: UIColor?

    // More to come here ...
}
</code>```

This allows Core Animation to handle these properties dynamically allowing it to track changes and integrate them into the animation system.

Note: a good rule of thumb is that these properties should all be related to drawing / visual presentation of the layer. If they aren't then it's quite likely that they don't belong on the layer. Instead they could be added to a view that in turn uses the layer for its drawing.

Copying layers

During the custom animation, Core Animation is going to want to create and render different layer configurations for different frames. Unlike most of Apple's other frameworks, this happens using the copy constructor init(layer:). For the above five properties to be copied along, we need to override init(layer:) and copy over their values.

In Swift we also have to override the plain init() and init?(coder).

```<code>override init(layer: Any) {
    super.init(layer: layer)
    guard let other = layer as? PieSegmentLayer else { return }

    fillColor   = other.fillColor
    strokeColor = other.strokeColor
    startAngle  = other.startAngle
    endAngle    = other.endAngle
    strokeWidth = other.strokeWidth
}

override init() {
    super.init()
}

required init?(coder aDecoder: NSCoder) {
    return nil
}
</code>```

Reacting to change

Core Animation is in many ways built for performance. One of the ways it achieves this is by avoiding unnecessary work. By default, a layer won't redraw itself when a property changes. But these properties is used for drawing, and we want the layer to redraw when any of them changes. To do that, we need to override needsDisplay(forKey:) and return true if the key was one of these properties.

```<code>override class func needsDisplay(forKey key: String) -> Bool {
    switch key {
    case #keyPath(startAngle), #keyPath(endAngle),
         #keyPath(strokeWidth),
         #keyPath(fillColor), #keyPath(strokeColor):
        return true

    default:
        return super.needsDisplay(forKey: key)
    }
}
</code>```

Additionally, If we want the layers default implicit animations for these properties, we need to override action(forKey:) to return a partially configured animation object. If we only want some properties (e.g. the angles) to implicitly animate, then we only need to return an animation for those properties. Unless we need something very custom, it's good to just return a basic animation with the fromValue set to the current presentation value:

```<code>override func action(forKey key: String) -> CAAction? {
    switch key {
    case #keyPath(startAngle), #keyPath(endAngle):
        let anim = CABasicAnimation(keyPath: key)
        anim.fromValue = presentation()?.value(forKeyPath: key)
        return anim

    default:
        return super.action(forKey: key)
    }
}
</code>```

Drawing

The last piece of a custom animation is the custom drawing. This is done by overriding draw(in:) and using the supplied context to draw the layer:

```<code>override func draw(in ctx: CGContext) {
    let center = CGPoint(x: bounds.midX, y: bounds.midY)
    // subtract half the stroke width to avoid clipping the stroke
    let radius = min(center.x, center.y) - strokeWidth / 2

    // The two angle properties are in degrees but CG wants them in radians.
    let start = startAngle * .pi / 180
    let end   = endAngle   * .pi / 180

    ctx.beginPath()
    ctx.move(to: center)

    ctx.addLine(to: CGPoint(x: center.x + radius * cos(start),
                            y: center.y + radius * sin(start)))

    ctx.addArc(center: center, radius: radius,
               startAngle: start, endAngle: end,
               clockwise: start > end)

    ctx.closePath()

    // Configure the graphics context
    if let fillCGColor = fillColor?.cgColor {
        ctx.setFillColor(fillCGColor)
    }
    if let strokeCGColor = strokeColor?.cgColor {
        ctx.setStrokeColor(strokeCGColor)
    }
    ctx.setLineWidth(strokeWidth)

    ctx.setLineCap(.round)
    ctx.setLineJoin(.round)

    // Draw
    ctx.drawPath(using: .fillStroke)
}
</code>```

Here I've filled and stroked a pie segment that extends from the center of the layer to the nearest edge. You should replace this with your custom drawing.

A custom animation in action

With all that code in place, we now have a custom layer subclass whose properties can be animated both implicitly (just by changing them) and explicitly (by adding a CAAnimation for their key). The results looks something like this:

Final words

It might not be obvious with the frame rate of those animations but one strong benefit from leveraging Core Animation (in different ways) in both these solutions is that it decouples the drawing of a single state from the timing of an animations.

That means that the layer doesn't know and doesn't have to know about the duration, delays, timing curves, etc. These can all be configured and controlled externally.

ContentLicense: CC BY-SA 3.0

Body:
Core-Animation treats angles as described in this image:
(image from http://btk.tillnagel.com/tutorials/rotation-translation-matrix.html)

EDIT: Adding an animated gif to explain better what I'm needing:

I need to animate a slice to grow wider, starting at 300:315 degrees, and ending 300:060.

To create each slice I'm using this function:

extension CGFloat {
    func toRadians() -> CGFloat {
        return self * CGFloat(Double.pi) / 180.0
    }
}
func createSlice(angle1:CGFloat, angle2:CGFloat) -> UIBezierPath! {
    let path: UIBezierPath = UIBezierPath()
    let width: CGFloat = self.frame.size.width/2
    let height: CGFloat = self.frame.size.height/2
    let centerToOrigin: CGFloat = sqrt((height)*(height)+(width)*(width));
    let ctr: CGPoint = CGPoint(x: width, y: height)
    path.move(to: ctr)
    path.addArc( withCenter: ctr,
                 radius: centerToOrigin,
                 startAngle: CGFloat(angle1).toRadians(),
                 endAngle: CGFloat(angle2).toRadians(),
                 clockwise: true
    )
    path.close()
    return path
}

I can now create the two slices and a sublayer with the smaller one, but I can't find how to proceed from this point:

func doStuff() {
    path1 = self.createSlice(angle1: 300,angle2: 315)
    path2 = self.createSlice(angle1: 300,angle2: 60)

    let shapeLayer = CAShapeLayer()
    shapeLayer.path = path1.cgPath
    shapeLayer.fillColor = UIColor.cyan.cgColor
    self.layer.addSublayer(shapeLayer)

I would highly appreciate any help here!

Body:
Only a single color

If you want to animate the angle of a solid color filled pie segment like the one in your question, then you can do it by animating the strokeEnd of a CAShapeLayer.

The "trick" here is to make a very wide line. More specifically, you can create a path that is just an arc (the dashed line in the animation below) at half of the intended radius and then giving it the full radius as its line width. When you animate stroking that line it looks like the orange segment below:

Depending on your use case, you can either:

create a path from one angle to the other angle and animate stroke end from 0 to 1

create a path for a full circle, set stroke start and stroke end to some fraction of the circle, and animate stroke end from the start fraction to the end fraction.

If your drawing is just a single color like this, then this will be the smallest solution to your problem.

However, if your drawing is more complex (e.g. also stroking the pie segment) then this solutions simply won't work and you'll have to do something more complex.

Custom drawing / Custom animations

If your drawing of the pie segment is any more complex, then you'll quickly find yourself having to create a layer subclass with custom animatable properties. Doing so is a bit more code - some of which might look a bit unusual1 - but not as scary as it might sound.

This might be one of those things that is still more convenient to do in Objective-C.

Dynamic properties

First, create a layer subclass with the properties you're going to need. In Objective-C parlance these properties should be @dynamic, i.e. not synthesized. This isn't the same as dynamic in Swift. Instead we have to use @NSManaged.

class PieSegmentLayer : CALayer {
    @NSManaged var startAngle, endAngle, strokeWidth: CGFloat
    @NSManaged var fillColor, strokeColor: UIColor?

    // More to come here ...
}

This allows Core Animation to handle these properties dynamically allowing it to track changes and integrate them into the animation system.

Note: a good rule of thumb is that these properties should all be related to drawing / visual presentation of the layer. If they aren't then it's quite likely that they don't belong on the layer. Instead they could be added to a view that in turn uses the layer for its drawing.

Copying layers

During the custom animation, Core Animation is going to want to create and render different layer configurations for different frames. Unlike most of Apple's other frameworks, this happens using the copy constructor init(layer:). For the above five properties to be copied along, we need to override init(layer:) and copy over their values.

In Swift we also have to override the plain init() and init?(coder).

override init(layer: Any) {
    super.init(layer: layer)
    guard let other = layer as? PieSegmentLayer else { return }

    fillColor   = other.fillColor
    strokeColor = other.strokeColor
    startAngle  = other.startAngle
    endAngle    = other.endAngle
    strokeWidth = other.strokeWidth
}

override init() {
    super.init()
}

required init?(coder aDecoder: NSCoder) {
    return nil
}

Reacting to change

Core Animation is in many ways built for performance. One of the ways it achieves this is by avoiding unnecessary work. By default, a layer won't redraw itself when a property changes. But these properties is used for drawing, and we want the layer to redraw when any of them changes. To do that, we need to override needsDisplay(forKey:) and return true if the key was one of these properties.

override class func needsDisplay(forKey key: String) -> Bool {
    switch key {
    case #keyPath(startAngle), #keyPath(endAngle),
         #keyPath(strokeWidth),
         #keyPath(fillColor), #keyPath(strokeColor):
        return true

    default:
        return super.needsDisplay(forKey: key)
    }
}

Additionally, If we want the layers default implicit animations for these properties, we need to override action(forKey:) to return a partially configured animation object. If we only want some properties (e.g. the angles) to implicitly animate, then we only need to return an animation for those properties. Unless we need something very custom, it's good to just return a basic animation with the fromValue set to the current presentation value:

override func action(forKey key: String) -> CAAction? {
    switch key {
    case #keyPath(startAngle), #keyPath(endAngle):
        let anim = CABasicAnimation(keyPath: key)
        anim.fromValue = presentation()?.value(forKeyPath: key)
        return anim

    default:
        return super.action(forKey: key)
    }
}

Drawing

The last piece of a custom animation is the custom drawing. This is done by overriding draw(in:) and using the supplied context to draw the layer:

override func draw(in ctx: CGContext) {
    let center = CGPoint(x: bounds.midX, y: bounds.midY)
    // subtract half the stroke width to avoid clipping the stroke
    let radius = min(center.x, center.y) - strokeWidth / 2

    // The two angle properties are in degrees but CG wants them in radians.
    let start = startAngle * .pi / 180
    let end   = endAngle   * .pi / 180

    ctx.beginPath()
    ctx.move(to: center)

    ctx.addLine(to: CGPoint(x: center.x + radius * cos(start),
                            y: center.y + radius * sin(start)))

    ctx.addArc(center: center, radius: radius,
               startAngle: start, endAngle: end,
               clockwise: start > end)

    ctx.closePath()

    // Configure the graphics context
    if let fillCGColor = fillColor?.cgColor {
        ctx.setFillColor(fillCGColor)
    }
    if let strokeCGColor = strokeColor?.cgColor {
        ctx.setStrokeColor(strokeCGColor)
    }
    ctx.setLineWidth(strokeWidth)

    ctx.setLineCap(.round)
    ctx.setLineJoin(.round)

    // Draw
    ctx.drawPath(using: .fillStroke)
}

Here I've filled and stroked a pie segment that extends from the center of the layer to the nearest edge. You should replace this with your custom drawing.

A custom animation in action

With all that code in place, we now have a custom layer subclass whose properties can be animated both implicitly (just by changing them) and explicitly (by adding a CAAnimation for their key). The results looks something like this:

Final words

It might not be obvious with the frame rate of those animations but one strong benefit from leveraging Core Animation (in different ways) in both these solutions is that it decouples the drawing of a single state from the timing of an animations.

That means that the layer doesn't know and doesn't have to know about the duration, delays, timing curves, etc. These can all be configured and controlled externally.


问:
FaceNet for dummies
The FaceNet algorithm (described in this article) uses a convolutional neural network to represent an image in an 128 dimensional Euclidean space.

While reading the article I didn't understand:

How does the loss function impact on the convolutional network (in normal networks, in order to minimize the loss the weights are slightly changed -
backpropagation - so, what happens in this case?)

how are the triplets chosen?

2.1 . how do I know a negative image is hard

2.2 . why am I using the loss function to determine the negative image

2.3 . when do I check my images for hardness with respect to the anchor - I believe that is before I send a triplet to be processed by the network, right.

答:
Here are some of the answer that may clarify your doubts:

Even here the weights are adjusted to minimise the Loss, its just the loss term is little complicated. The loss has two parts(separated by + in the equation), first part is the image of a person compared to a different image of the same person. The second part is the image of the person compared to a image of a different person. We want the first part loss to be less than the second part loss and the loss equation in essence captures that. So here you basically want to adjust the weights such that same person error is less and different person error is more.

The Loss term involves three images: The image in question(anchor): x_a, its positive pair: x_p and its negative pair: x_n. An hardest positive of x_a is the positive image that has the biggest error compared to the rest of the positive images. The hardest negative of x_a is the closest image of a different person. So you want to bring the furthest positives to be close to each other and push the closest negatives further away. This is captured in the loss equation.

Facenet calculates its anchor during training (online). In each minibatch(which is a set of 40 images) they select the hardest negative to the anchor and instead of choosing the hardest positive image, they choose all anchor-positive pairs within the batch.

If you are looking to implement face recognition, you should better consider this paper, that implements centre loss, which is much easier to train and shown to perform better.

Title: FaceNet for dummies

ContentLicense: CC BY-SA 4.0


问:
How to have n variables in C#
imagine this code

```<code>for (int iDay = 1; iDay <= total_days; iDay++)
{

    question = CheckString(s.challenge_1_q);
    answer = CheckStringA(s.challenge_1_a);

    // more here
}
</code>```

but what I really have is from challenge_1_q to challenge_24_q and challenge_1_a to challenge_24_a

what is my best option to have dynamic variables as today it's 24, "tomorrow" could be only 18.

is the use of dynamic the proper way? or I really need to have a switch and forget about dynamism ?

答:
Create a class called QuestionAnswer, then store a List on s.
The accessing code will look like this:

```<code>question = CheckString(s.QuestionAnswers[i].Question);
answer = CheckStringA(s.QuestionAnswers[i].Answer);
</code>```

The QuestionAnswer class:

```<code>public class QuestionAnswer
{
  public string Question{get; set;}
  public string Answer{get; set;}
}
</code>```

And the definition on your existing class:

```<code>public List<QuestionAnswer> QuestionAnswers = new List<QuestionAnswer>();
</code>```

Instead of having dozens of variables, you add dozens of items to the list:

```<code>QuestionAnswer qa = new QuestionAnswer();
qa.Question = "What letter comes after A?";
qa.Answer = "B";
QuestionAnswers.Add(qa);
//repeat for all your questions.
</code>```

ContentLicense: CC BY-SA 2.5

Title: How to have n variables in C#

Body:
imagine this code

for (int iDay = 1; iDay <= total_days; iDay++)
{

    question = CheckString(s.challenge_1_q);
    answer = CheckStringA(s.challenge_1_a);

    // more here
}

but what I really have is from challenge_1_q to challenge_24_q and challenge_1_a to challenge_24_a

what is my best option to have dynamic variables as today it's 24, "tomorrow" could be only 18.

is the use of dynamic the proper way? or I really need to have a switch and forget about dynamism ?

Body:
Create a class called QuestionAnswer, then store a List on s.
The accessing code will look like this:

question = CheckString(s.QuestionAnswers[i].Question);
answer = CheckStringA(s.QuestionAnswers[i].Answer);

The QuestionAnswer class:

public class QuestionAnswer
{
  public string Question{get; set;}
  public string Answer{get; set;}
}

And the definition on your existing class:

public List<QuestionAnswer> QuestionAnswers = new List<QuestionAnswer>();

Instead of having dozens of variables, you add dozens of items to the list:

QuestionAnswer qa = new QuestionAnswer();
qa.Question = "What letter comes after A?";
qa.Answer = "B";
QuestionAnswers.Add(qa);
//repeat for all your questions.


问:
PyCharm doesn't recognize module gc
I am trying to use gc module and it works both in debug and normal runs. Unfortunately, PyCharm itself doesn't see this module exists and complains on it:

UPDATE

I was unable to install gc with neither pip install gc, not conda install gc, although it is working. I decided this package is built-in.

答: Go to preferences->project interpreter and search for it if it is a package (install if not already installed). Otherwise, make sure it's in your working directory (displayed as window header).</p>

Title: PyCharm doesn't recognize module gc


问:
Port configuration and automatic port change on Wakanda
When I run a solution on Wakanda there is a port by default, for example 8102, but when I reload it the port changes to 8104. I would have liked to know where the port configuration is and this operation is done? In which file, or option? Because I look for it, but I can't find it.

Thanks in advance.

答:
Update: I have confirmed that when accessed remotely (from another computer), the admin dashboard is only available via HTTPS at port 4433. :8080/admin is available on localhost only.

In order for it to work, the CORS settings need to be enabled for port 4433 as well:
HostIPAddress:4433  POST / GET / PUT / DELETE

Note: From your earlier comment it seems you have admin dashboard working on port 4433. FYI the server has an updated admin certificate, which will come out in next release. In case you have any problem with it, please wait and test with next release.

-------------------------Original Post-----------------------------------------

The admin port is set to 8080 by default. If you would like to change the default value of admin port (typically for deployment), it can be changed using Command Line/ Terminal option "--admin-port=[number]", for example:

```<code>"C:\Wakanda\Wakanda Server.exe" "C:\solutions\invoices.waSolution" "--adminport=8090"
</code>```

Will change solution invoices's admin port to 8090.

You can find more options in the documentation.

Body:
Update: I have confirmed that when accessed remotely (from another computer), the admin dashboard is only available via HTTPS at port 4433. :8080/admin is available on localhost only.

In order for it to work, the CORS settings need to be enabled for port 4433 as well:
HostIPAddress:4433  POST / GET / PUT / DELETE

Note: From your earlier comment it seems you have admin dashboard working on port 4433. FYI the server has an updated admin certificate, which will come out in next release. In case you have any problem with it, please wait and test with next release.

-------------------------Original Post-----------------------------------------

The admin port is set to 8080 by default. If you would like to change the default value of admin port (typically for deployment), it can be changed using Command Line/ Terminal option "--admin-port=[number]", for example:

"C:\Wakanda\Wakanda Server.exe" "C:\solutions\invoices.waSolution" "--adminport=8090"

Will change solution invoices's admin port to 8090.

You can find more options in the documentation.


问:
Spring cloud stream RabbitMQ routing messages dynamically
I have implemented the example as shown here Spring Dynamic Destination

In the rabbitmq, it is creating an exchange dynamically, but there is no option to provide binding or routing key. My requirement is to send a message to this dynamically created exchange with a routing key. How would i need to implement this to setup the routing key?

```<code>@Component
public class DDProducerBean {

    @Autowired
    private BinderAwareChannelResolver poChannelResolver = null;

    public void publish(DDSocketVO ddSocketVO) throws Exception {
        this.poChannelResolver.resolveDestination(ddSocketVO.getDestination()).send(MessageBuilder.withPayload(new ObjectMapper().
                setVisibility(PropertyAccessor.FIELD, Visibility.ANY).
                writeValueAsString(ddSocketVO)).build());
    }

}
</code>```

答:
Here is the workaround as suggested Here

Basically create a MessageChannel with the dynamic destination using BinderAwareChannelResolver, then connect to RabbitMQ with RabbitAdmin API and bind the newly created exchange to another queue or exchange with routing key before sending messages.

```<code>@Autowired
private BinderAwareChannelResolver poChannelResolver;

public void publish(WebSocketVO webSocketVO) throws Exception {

    MessageChannel channel = this.poChannelResolver.resolveDestination(webSocketVO.getDestination());

    CachingConnectionFactory connectionFactory = new CachingConnectionFactory();
    connectionFactory.setUsername(System.getProperty("spring.cloud.stream.binders.corerabbit.environment.spring.rabbitmq.username"));
    connectionFactory.setPassword(System.getProperty("spring.cloud.stream.binders.corerabbit.environment.spring.rabbitmq.password"));
    connectionFactory.setAddresses(System.getProperty("spring.cloud.stream.binders.corerabbit.environment.spring.rabbitmq.addresses"));
    connectionFactory.setVirtualHost(System.getProperty("spring.cloud.stream.binders.corerabbit.environment.spring.rabbitmq.virtual-host"));

    AmqpAdmin amqpAdmin = new RabbitAdmin(connectionFactory);

    TopicExchange sourceExchange = new TopicExchange(webSocketVO.getDestination(), false, true);
    TopicExchange destExchange = new TopicExchange("amq.topic");

    amqpAdmin.declareBinding(BindingBuilder.bind(destExchange).to(sourceExchange).with(webSocketVO.getRoutingKeyExpression()));

    channel.send(MessageBuilder.withPayload(new ObjectMapper().
            setVisibility(PropertyAccessor.FIELD, Visibility.ANY).
            writeValueAsString(webSocketVO)).build());

    amqpAdmin.deleteExchange(webSocketVO.getDestination());

    connectionFactory.destroy();

}
</code>```

Body:
I have implemented the example as shown here Spring Dynamic Destination

In the rabbitmq, it is creating an exchange dynamically, but there is no option to provide binding or routing key. My requirement is to send a message to this dynamically created exchange with a routing key. How would i need to implement this to setup the routing key?

@Component
public class DDProducerBean {

    @Autowired
    private BinderAwareChannelResolver poChannelResolver = null;

    public void publish(DDSocketVO ddSocketVO) throws Exception {
        this.poChannelResolver.resolveDestination(ddSocketVO.getDestination()).send(MessageBuilder.withPayload(new ObjectMapper().
                setVisibility(PropertyAccessor.FIELD, Visibility.ANY).
                writeValueAsString(ddSocketVO)).build());
    }

}

Body:
Here is the workaround as suggested Here

Basically create a MessageChannel with the dynamic destination using BinderAwareChannelResolver, then connect to RabbitMQ with RabbitAdmin API and bind the newly created exchange to another queue or exchange with routing key before sending messages.

@Autowired
private BinderAwareChannelResolver poChannelResolver;

public void publish(WebSocketVO webSocketVO) throws Exception {

    MessageChannel channel = this.poChannelResolver.resolveDestination(webSocketVO.getDestination());

    CachingConnectionFactory connectionFactory = new CachingConnectionFactory();
    connectionFactory.setUsername(System.getProperty("spring.cloud.stream.binders.corerabbit.environment.spring.rabbitmq.username"));
    connectionFactory.setPassword(System.getProperty("spring.cloud.stream.binders.corerabbit.environment.spring.rabbitmq.password"));
    connectionFactory.setAddresses(System.getProperty("spring.cloud.stream.binders.corerabbit.environment.spring.rabbitmq.addresses"));
    connectionFactory.setVirtualHost(System.getProperty("spring.cloud.stream.binders.corerabbit.environment.spring.rabbitmq.virtual-host"));

    AmqpAdmin amqpAdmin = new RabbitAdmin(connectionFactory);

    TopicExchange sourceExchange = new TopicExchange(webSocketVO.getDestination(), false, true);
    TopicExchange destExchange = new TopicExchange("amq.topic");

    amqpAdmin.declareBinding(BindingBuilder.bind(destExchange).to(sourceExchange).with(webSocketVO.getRoutingKeyExpression()));

    channel.send(MessageBuilder.withPayload(new ObjectMapper().
            setVisibility(PropertyAccessor.FIELD, Visibility.ANY).
            writeValueAsString(webSocketVO)).build());

    amqpAdmin.deleteExchange(webSocketVO.getDestination());

    connectionFactory.destroy();

}


问:
Consolidating duplicate rows in a large dataframe
Basically, I have a dataframe, df

```<code>         Beginning1 Protein2    Protein3    Protein4    Biomarker1
Pathway3    A         G           NA           NA           F
Pathway8    A         G           NA           NA           E
Pathway9    A         G           Z            H            F
Pathway6    A         G           Z            H            E
Pathway2    A         G           D            NA           F
Pathway5    A         G           D            NA           E
Pathway1    A         D           K            NA           F
Pathway7    A         B           C            D            F
Pathway4    A         B           C            D            E
</code>```

And now I want to consolidate the rows to look like this:

```<code>newdf
      Beginning1    Protein2    Protein3    Protein4    Biomarker1
Pathway3    A         G           NA           NA           F, E
Pathway9    A         G           Z            H            F, E
Pathway2    A         G           D            NA           F, E
Pathway1    A         D           K            NA           F
Pathway4    A         B           C            D            F, E
</code>```

This is a continuation of a past question I asked (Consolidating duplicate rows in a dataframe).  That works for this dataset, but for my much larger dataset it does not seem to combine the values. For example, the first few lines of output (after I modified the code given by @Matt Jewett or used the explanations provided in Concatenate strings by group with dplyr):

```<code>          Beginning1    Protein2    Protein3    Protein4    Biomarker1
Pathway1    Smoothened    Gl-1                              Osteopontin
Pathway2    Smoothened    Gl-1      BMP2                    Osteopontin
Pathway3    Smoothened    Gl-1      BMP2                    DLX5
Pathway4    Smoothened    Gl-1      BMP2                    Osteopontin
</code>```

As you can see, there are several problems.  First, the Biomarker1 column doesn't seem to be aggregating.  And secondly, there are repeats of several rows.  I have hit a wall in terms of solutions, so any solutions you guys can think up would be much appreciated!

Thank you so much for your help!

答:
Simple enough using data.table

```<code>library(data.table)

dat <- fread("Pathway Beginning1 Protein2    Protein3    Protein4    Biomarker1
             Pathway3    A         G           NA           NA           F
             Pathway8    A         G           NA           NA           E
             Pathway9    A         G           Z            H            F
             Pathway6    A         G           Z            H            E
             Pathway2    A         G           D            NA           F
             Pathway5    A         G           D            NA           E
             Pathway1    A         D           K            NA           F
             Pathway7    A         B           C            D            F
             Pathway4    A         B           C            D            E")

dat_collapse <- dat[, .(Pathway = Pathway[1],
                        Biomarker1 = paste0(Biomarker1, collapse = ", ")),
                    by = .(Beginning1, Protein2, Protein3, Protein4)]

setcolorder(dat_collapse, names(dat))
dat_collapse
</code>```

Results in:

```<code>    Pathway Beginning1 Protein2 Protein3 Protein4 Biomarker1
1: Pathway3          A        G       NA       NA       F, E
2: Pathway9          A        G        Z        H       F, E
3: Pathway2          A        G        D       NA       F, E
4: Pathway1          A        D        K       NA          F
5: Pathway7          A        B        C        D       F, E
</code>```

Body:
Basically, I have a dataframe, df

         Beginning1 Protein2    Protein3    Protein4    Biomarker1
Pathway3    A         G           NA           NA           F
Pathway8    A         G           NA           NA           E
Pathway9    A         G           Z            H            F
Pathway6    A         G           Z            H            E
Pathway2    A         G           D            NA           F
Pathway5    A         G           D            NA           E
Pathway1    A         D           K            NA           F
Pathway7    A         B           C            D            F
Pathway4    A         B           C            D            E

And now I want to consolidate the rows to look like this:

newdf
      Beginning1    Protein2    Protein3    Protein4    Biomarker1
Pathway3    A         G           NA           NA           F, E
Pathway9    A         G           Z            H            F, E
Pathway2    A         G           D            NA           F, E
Pathway1    A         D           K            NA           F
Pathway4    A         B           C            D            F, E

This is a continuation of a past question I asked (Consolidating duplicate rows in a dataframe).  That works for this dataset, but for my much larger dataset it does not seem to combine the values. For example, the first few lines of output (after I modified the code given by @Matt Jewett or used the explanations provided in Concatenate strings by group with dplyr):

          Beginning1    Protein2    Protein3    Protein4    Biomarker1
Pathway1    Smoothened    Gl-1                              Osteopontin
Pathway2    Smoothened    Gl-1      BMP2                    Osteopontin
Pathway3    Smoothened    Gl-1      BMP2                    DLX5
Pathway4    Smoothened    Gl-1      BMP2                    Osteopontin

As you can see, there are several problems.  First, the Biomarker1 column doesn't seem to be aggregating.  And secondly, there are repeats of several rows.  I have hit a wall in terms of solutions, so any solutions you guys can think up would be much appreciated!

Thank you so much for your help!

Body:
Simple enough using data.table

library(data.table)

dat <- fread("Pathway Beginning1 Protein2    Protein3    Protein4    Biomarker1
             Pathway3    A         G           NA           NA           F
             Pathway8    A         G           NA           NA           E
             Pathway9    A         G           Z            H            F
             Pathway6    A         G           Z            H            E
             Pathway2    A         G           D            NA           F
             Pathway5    A         G           D            NA           E
             Pathway1    A         D           K            NA           F
             Pathway7    A         B           C            D            F
             Pathway4    A         B           C            D            E")

dat_collapse <- dat[, .(Pathway = Pathway[1],
                        Biomarker1 = paste0(Biomarker1, collapse = ", ")),
                    by = .(Beginning1, Protein2, Protein3, Protein4)]

setcolorder(dat_collapse, names(dat))
dat_collapse

Results in:

    Pathway Beginning1 Protein2 Protein3 Protein4 Biomarker1
1: Pathway3          A        G       NA       NA       F, E
2: Pathway9          A        G        Z        H       F, E
3: Pathway2          A        G        D       NA       F, E
4: Pathway1          A        D        K       NA          F
5: Pathway7          A        B        C        D       F, E


问:
Oracle SQL subqueries to link multiple tables
I have 3 different datasets

Data1:

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

data2:

```<code>ID  From    To
1   AB     CD
2   EF     JK
3   PQ  PQ
</code>```

data3:

```<code>From/To  rank
  AB     1
  CD     2
  EF     3
  JK     5
  PQ     9
</code>```

I need to populate the field rank_down as Y/N based on whether the ID has moved from a higher rank to a lower rank (1 being the lowest).This has to be done in Oracle SQl. I am new to this programming hence finding it difficult to write a subquery.

Can any one help?

答:
Try:</p>

```<code>select t.*,
      CASE WHEN
           ( SELECT "RANK" FROM DATA_3 d
             WHERE d.From_To = t."FROM"
           )
           >
           ( SELECT "RANK" FROM DATA_3 d
             WHERE d.From_To = t."TO"
           )
        THEN 'Y' ELSE 'N' END
        As rank_down
from data_2 t;
</code>```

Body:
I have 3 different datasets

Data1:

ID  Rank_down
1
2
3

data2:

ID  From    To
1   AB     CD
2   EF     JK
3   PQ  PQ

data3:

From/To  rank
  AB     1
  CD     2
  EF     3
  JK     5
  PQ     9

I need to populate the field rank_down as Y/N based on whether the ID has moved from a higher rank to a lower rank (1 being the lowest).This has to be done in Oracle SQl. I am new to this programming hence finding it difficult to write a subquery.

Can any one help?

Body:
Try:

select t.*,
      CASE WHEN
           ( SELECT "RANK" FROM DATA_3 d
             WHERE d.From_To = t."FROM"
           )
           >
           ( SELECT "RANK" FROM DATA_3 d
             WHERE d.From_To = t."TO"
           )
        THEN 'Y' ELSE 'N' END
        As rank_down
from data_2 t;


问:
PHP5: Some Session files 0 length?
I'm seeing a strange situation, that I'm trying to figure out if it's a PHP issue, file issue, or normal operation.  I have some users complaining about very fast timeouts on our site (session expires?), and checking the php tmp directory, I see things like this:

```<code>-rw------- 1 www-data www-data  377 2009-01-15 22:46 sess_fc789ce04a3d54ce929a401cd33ea868
-rw------- 1 www-data www-data 1167 2009-01-15 23:21 sess_fcb67b1f44a3669d8ffee69d5fa9a2e8
-rw------- 1 www-data www-data    0 2009-01-15 23:22 sess_fe0ab79c78c612d71ecca575753afdc4
-rw------- 1 www-data www-data    0 2009-01-15 23:07 sess_fedd46db2b023215cb060d67a01d3382
-rw------- 1 www-data www-data    0 2009-01-15 23:21 sess_feec900e144c011303a9f06eb428574e
-rw------- 1 www-data www-data    0 2009-01-15 23:00 sess_ffb2ed75ca311d08e41ec69c7d708d08
-rw------- 1 www-data www-data 1142 2009-01-15 22:49 sess_ffc2c882af3b3ad39b844dc5a530dc44
-rw------- 1 www-data www-data    0 2009-01-15 22:51 sess_fffbd6f7734ce3b4ef9d8009a324a459
</code>```

Is this normal behavior?

TIA
Mike

答:
I'm not sure what you mean, exactly, but you could try putting:

```<code><?php set_time_limit(100); ?>
</code>```

at the top of every page.  Maybe?  Sorry =/

Title: PHP5: Some Session files 0 length?

Body:
I'm seeing a strange situation, that I'm trying to figure out if it's a PHP issue, file issue, or normal operation.  I have some users complaining about very fast timeouts on our site (session expires?), and checking the php tmp directory, I see things like this:

-rw------- 1 www-data www-data  377 2009-01-15 22:46 sess_fc789ce04a3d54ce929a401cd33ea868
-rw------- 1 www-data www-data 1167 2009-01-15 23:21 sess_fcb67b1f44a3669d8ffee69d5fa9a2e8
-rw------- 1 www-data www-data    0 2009-01-15 23:22 sess_fe0ab79c78c612d71ecca575753afdc4
-rw------- 1 www-data www-data    0 2009-01-15 23:07 sess_fedd46db2b023215cb060d67a01d3382
-rw------- 1 www-data www-data    0 2009-01-15 23:21 sess_feec900e144c011303a9f06eb428574e
-rw------- 1 www-data www-data    0 2009-01-15 23:00 sess_ffb2ed75ca311d08e41ec69c7d708d08
-rw------- 1 www-data www-data 1142 2009-01-15 22:49 sess_ffc2c882af3b3ad39b844dc5a530dc44
-rw------- 1 www-data www-data    0 2009-01-15 22:51 sess_fffbd6f7734ce3b4ef9d8009a324a459

Is this normal behavior?

TIA
Mike

Body:
I'm not sure what you mean, exactly, but you could try putting:

<?php set_time_limit(100); ?>

at the top of every page.  Maybe?  Sorry =/

OwnerDisplayName: John

LastEditorDisplayName: Kev


问:
Adding the date as index
Please suggest how can be indexed as a date to add to DF. When downloading quotes date has added index, it is required to do the same for df added by read.csv

this is example:

```<code>library(quantmod)
> getSymbols("^GSPC",src="yahoo",from=as.Date("2017-07-01",to=Sys.Date()))
[1] "GSPC"
> df<-read.csv("D:\\R\\tmp1\\SiM7.csv",header=F,skip=1,sep=";")
</code>```

(as it should be)

```<code>> GSPC[1,]
       GSPC.Open GSPC.High GSPC.Low GSPC.Close GSPC.Volume GSPC.Adjusted
2017-07-03   2431.39   2439.17  2428.69    2429.01  1962290000       2429.01
>
</code>```

(as it turns out)

```<code>> df[1,]
V1 V2       V3     V4    V5    V6    V7    V8     V9 V10
1 SiM7  5 20170522 100000 57236 57236 56767 56785 108295   0
>
</code>```

add by index(df)<-df[,3] does not work, the date you want to add already existing and imported through read.csv Please help, thank you

答:
index works with zoo and xts objects as opposed to dataframes. See ?index for more information. Also check out class(GSPC) and class(df) to see this difference.

If your goal is to transform your data.frame df into the same xts object as GSPC look at ?xts.

First transform the date values in V3 into time-based objects. It appears as though your dates are numeric values. So df_date_vec <- as.Date(as.character(df$V3), format = "%Y%m%d") will create a date vector. Then you can create an xts object similar to GSPC by sim_7 <- xts(df$V10, order.by = df_date_vec). Now index(sim_7) will return the dates.

This is assuming you want column V10. If you want multiple columns try cbind.

Title: Adding the date as index

Body:
Please suggest how can be indexed as a date to add to DF. When downloading quotes date has added index, it is required to do the same for df added by read.csv

this is example:

library(quantmod)
> getSymbols("^GSPC",src="yahoo",from=as.Date("2017-07-01",to=Sys.Date()))
[1] "GSPC"
> df<-read.csv("D:\\R\\tmp1\\SiM7.csv",header=F,skip=1,sep=";")

(as it should be)

> GSPC[1,]
       GSPC.Open GSPC.High GSPC.Low GSPC.Close GSPC.Volume GSPC.Adjusted
2017-07-03   2431.39   2439.17  2428.69    2429.01  1962290000       2429.01
>

(as it turns out)

> df[1,]
V1 V2       V3     V4    V5    V6    V7    V8     V9 V10
1 SiM7  5 20170522 100000 57236 57236 56767 56785 108295   0
>

add by index(df)<-df[,3] does not work, the date you want to add already existing and imported through read.csv Please help, thank you


问:
Java JSONObject parsed in Polymer report component
I have a Java class that gives me as output  JSON objects.
e.g.

```<code>{"date":"20170220","action":"run","eat":"banana","sleep":"20170315152644"}...
</code>```

On the other side,
I have created the front-end with polymer 1.

```<code>        <table>
            <caption>Actions</caption>

            <thead>
            <tr>
                <th scope="col">date</th>
                <th scope="col">action</th>
                <th scope="col">eat</th>
                <th scope="col">sleep</th>
            </tr>
            </thead>
            <tbody>
               <td>{{}}</td>
               <td>{{}}</td>
               <td>{{}}</td>
               <td>{{}}</td>
           </tbody>
  </table>
</my-table>
</code>```

I am trying to send the JSON results from the backend to the front end.

答:
Hi for this you need an  component called iron-ajax, it will create an ajax call for you. When you got your result from it you can use dom-repeat to render your table rows (or use a predefined component for a table like vaadin-grid).

Assuming your JSON output is an array.

```<code>[
    {"date":"20170220","action":"run","eat":"banana","sleep":"20170315152644"},
    ...
]
</code>```

Your front end would look like this.

```<code><my-table>
    <template>
        <iron-ajax auto url="..." handle-as="json" last-response="{{data}}"></iron-ajax>

        <table>
            <caption>Actions</caption>
            <thead>
                <tr>
                    <th scope="col">date</th>
                    <th scope="col">action</th>
                    <th scope="col">eat</th>
                    <th scope="col">sleep</th>
                </tr>
            </thead>
            <tbody>
                <template is="dom-repeat" items="[[data]]">
                    <tr>
                        <td>[[item.date]]</td>
                        <td>[[item.action]]</td>
                        <td>[[item.eat]]</td>
                        <td>[[item.sleep]]</td>
                    </tr>
                </template>
            </tbody>
        </table>
    </template>
    <script>
        // omitted...
    </script>
</my-table>
</code>```

Body:
I have a Java class that gives me as output  JSON objects.
e.g.

{"date":"20170220","action":"run","eat":"banana","sleep":"20170315152644"}...

On the other side,
I have created the front-end with polymer 1.

Actions

                date
                action
                eat
                sleep

               {{}}
               {{}}
               {{}}
               {{}}

</my-table>

I am trying to send the JSON results from the backend to the front end.

Body:
Hi for this you need an  component called iron-ajax, it will create an ajax call for you. When you got your result from it you can use dom-repeat to render your table rows (or use a predefined component for a table like vaadin-grid).

Assuming your JSON output is an array.

[
    {"date":"20170220","action":"run","eat":"banana","sleep":"20170315152644"},
    ...
]

Your front end would look like this.

<my-table>
    <template>
        <iron-ajax auto url="..." handle-as="json" last-response="{{data}}"></iron-ajax>

        <table>
            <caption>Actions</caption>
            <thead>
                <tr>
                    <th scope="col">date</th>
                    <th scope="col">action</th>
                    <th scope="col">eat</th>
                    <th scope="col">sleep</th>
                </tr>
            </thead>
            <tbody>
                <template is="dom-repeat" items="[[data]]">
                    <tr>
                        <td>[[item.date]]</td>
                        <td>[[item.action]]</td>
                        <td>[[item.eat]]</td>
                        <td>[[item.sleep]]</td>
                    </tr>
                </template>
            </tbody>
        </table>
    </template>
    <script>
        // omitted...
    </script>
</my-table>


问:
How to unscope default_scope in join/eager_load?
I have two models:

```<code>class User
  default_scope -> { where(deleted_at: nil) }
end

class Order
  belongs_to :user
end
</code>```

And I want to get orders with deleted or not deleted users:

```<code>Order.joins(:user).merge(User.unscoped)
Order.joins(:user).merge(User.unscope(where: :deleted_at))
# SELECT  "orders".* FROM "orders"
# INNER JOIN "users" ON "users"."id" = "orders"."user_id" AND "users"."deleted_at" IS NULL
# ORDER BY "orders"."id" DESC LIMIT 1

Order.eager_load(:user).merge(User.unscoped)
Order.eager_load(:user).merge(User.unscope(where: :deleted_at))
# SELECT  "orders"."id" AS t0_r0, "orders"."user_id" AS t0_r1,
# "users"."id" AS t1_r0, "users"."deleted_at" AS t1_r1 FROM "orders"
# LEFT OUTER JOIN "users" ON "users"."id" = "orders"."user_id" AND "users"."deleted_at" IS NULL
# ORDER BY "orders"."id" DESC LIMIT 1
</code>```

None of these work.

Every query adds "AND "users"."deleted_at" IS NULL" into join statement.

Nothing changes if I specify association scope:

```<code>class Order
  belongs_to :user, -> { unscoped }
end
</code>```

However includes works as expected:

```<code>Order.includes(:user).merge(User.unscoped).last
# SELECT  "orders".* FROM "orders" ORDER BY "orders"."id" DESC LIMIT 1
# SELECT "users".* FROM "users" WHERE "users"."id" = 1054
</code>```

How can I make rails to unscope association in a join?

答:
I solved this issue by writing join query manually. For your case it should look like:

```<code>Order.joins('INNER JOIN users ON users.id=orders.user_id')
</code>```

Although Order.includes(:user).merge(User.unscoped)solution, that you found, looks a bit nicer, unless you really want to have only one query

Body:
I have two models:

class User
  default_scope -> { where(deleted_at: nil) }
end

class Order
  belongs_to :user
end

And I want to get orders with deleted or not deleted users:

Order.joins(:user).merge(User.unscoped)
Order.joins(:user).merge(User.unscope(where: :deleted_at))
# SELECT  "orders".* FROM "orders"
# INNER JOIN "users" ON "users"."id" = "orders"."user_id" AND "users"."deleted_at" IS NULL
# ORDER BY "orders"."id" DESC LIMIT 1

Order.eager_load(:user).merge(User.unscoped)
Order.eager_load(:user).merge(User.unscope(where: :deleted_at))
# SELECT  "orders"."id" AS t0_r0, "orders"."user_id" AS t0_r1,
# "users"."id" AS t1_r0, "users"."deleted_at" AS t1_r1 FROM "orders"
# LEFT OUTER JOIN "users" ON "users"."id" = "orders"."user_id" AND "users"."deleted_at" IS NULL
# ORDER BY "orders"."id" DESC LIMIT 1

None of these work.

Every query adds "AND "users"."deleted_at" IS NULL" into join statement.

Nothing changes if I specify association scope:

class Order
  belongs_to :user, -> { unscoped }
end

However includes works as expected:

Order.includes(:user).merge(User.unscoped).last
# SELECT  "orders".* FROM "orders" ORDER BY "orders"."id" DESC LIMIT 1
# SELECT "users".* FROM "users" WHERE "users"."id" = 1054

How can I make rails to unscope association in a join?

Body:
I solved this issue by writing join query manually. For your case it should look like:

Order.joins('INNER JOIN users ON users.id=orders.user_id')

Although Order.includes(:user).merge(User.unscoped)solution, that you found, looks a bit nicer, unless you really want to have only one query


问:
Can't extract response body to set env variable
I'm using Postman to pass the response from the body to the environment setup.  Can't get this one in particular to do so.

Response:

```<code>{
"AvailableTypes": [
    {
        "SubTypes": [
            2,
            1
        ],
        "Type": 0
    }
],
"PaymentInstruments": [
    {
        "Created": "2017-06-20T18:20:15.963Z",
        "CreditCard": {
            "Type": 2
        },
        "Id": 715886
    }
]
</code>```

}

test:

```<code>var jsonData = JSON.parse(responseBody);
postman.setEnvironmentVariable("PID", jsonData.PaymentInstruments.Id);
</code>```

答:
I modified the test:</p>

```<code>var jsonData = JSON.parse(responseBody);
postman.setEnvironmentVariable("PID", jsonData.PaymentInstruments[0].Id);
</code>```

Body:
I'm using Postman to pass the response from the body to the environment setup.  Can't get this one in particular to do so.

Response:

{
"AvailableTypes": [
    {
        "SubTypes": [
            2,
            1
        ],
        "Type": 0
    }
],
"PaymentInstruments": [
    {
        "Created": "2017-06-20T18:20:15.963Z",
        "CreditCard": {
            "Type": 2
        },
        "Id": 715886
    }
]

}

test:

var jsonData = JSON.parse(responseBody);
postman.setEnvironmentVariable("PID", jsonData.PaymentInstruments.Id);

Body:
I modified the test:

var jsonData = JSON.parse(responseBody);
postman.setEnvironmentVariable("PID", jsonData.PaymentInstruments[0].Id);


问:
JMeter : Maven Build Hangs/Freezes at the end of execution in Jenkins
I am using jmeter-maven-plugin to execute JMeter tests (JMX Files) as a maven project from Jenkins.
What I observed is:
When rampup time is more or virtual user is more, Jenkins freezes the execution towards the end. It keeps on executing for days if not stopped.

When executed outside Jenkins e.g using maven commands directly using cmd, works great. Also when executed directly from JMeter GUI, works fine.

答:
There was an issue with jmeter maven plugin which was fixed in later version.

Solution was made by Abhishek Swain.

See


问:
Get value of input field after random JavaScript function
I have a function that chooses a random list item and inside that list item has an input field. The goal is for the user to fill out the fields and then press a button to select a random list item and display the value of that input field inside that list item.

Right now I have the random function working, it selects a random list item but I am having trouble displaying the value on the input field. It seems like the browser can't recognize what the user has typed into the input field because all the console spits out is
<input type='text'>

HTML:

```<code><ul id="list">
    <li><input type='text'></li>
    <li><input type='text'></li>
    <li><input type='text'></li>
</ul>

<button id="randomize">randomize</button>

<p id="result">hello</p>
</code>```

JS:

```<code>var randomize = document.getElementById("randomize");
var listItems = document.getElementById("list").getElementsByTagName("li");
var result = document.getElementById("result");

randomize.addEventListener("click", randomizeIt);

function randomizeIt () {
    var randomItem = listItems[Math.floor(Math.random() * listItems.length)];
    result.innerHTML = randomItem.value;
    console.log(randomItem);
}
</code>```

JS Fiddle

答:
You just need to grab the childNode (which is the input element).

```<code>result.innerHTML = randomItem.childNodes[0].value;
</code>```

jsfiddle

Body:
I have a function that chooses a random list item and inside that list item has an input field. The goal is for the user to fill out the fields and then press a button to select a random list item and display the value of that input field inside that list item.

Right now I have the random function working, it selects a random list item but I am having trouble displaying the value on the input field. It seems like the browser can't recognize what the user has typed into the input field because all the console spits out is
<input type='text'>

HTML:

<input type='text'>

<input type='text'>

<input type='text'>

<button id="randomize">randomize</button>

hello

JS:

var randomize = document.getElementById("randomize");
var listItems = document.getElementById("list").getElementsByTagName("li");
var result = document.getElementById("result");

randomize.addEventListener("click", randomizeIt);

function randomizeIt () {
    var randomItem = listItems[Math.floor(Math.random() * listItems.length)];
    result.innerHTML = randomItem.value;
    console.log(randomItem);
}

JS Fiddle

Body:
You just need to grab the childNode (which is the input element).

result.innerHTML = randomItem.childNodes[0].value;

jsfiddle


问:
Adding multiple images to DragView
I'm making a card game(Patience/solitaire/klondike) in which I'm using JavaFX's drag and drop features. To show a ghost image of the card I'm dragging I use the Dragboard.

```<code>Dragboard db;
db.setDragView(source.getImage());
</code>```

This all works fine as it should but I can't figure out how I could tackle the dragging of whole stacks.(Multiple cards layered over eachother with only the top of each card visible) Each stack of cards is stored in an arraylist but since I can only add 1 image to the dragboard at a time, I'm stuck.

So the quick question:

Is there a way to add multiple images to a dragboard?

Or is it
    possible to achieve this same effect in another way?

Or is it possible to create 1 Image object out of multiple Image objects to
   place this new Image on the dragboard?

The dragDetected eventhandler:

```<code>    /*
    On dragDetected check the source of the event, copy to clipboard and show a ghost image
 */
private void dragDetected(MouseEvent mouseEvent) {
    Dragboard db;
    ClipboardContent cc;

    if(mouseEvent.getSource() instanceof CardPane){
        CardPane source = (CardPane) mouseEvent.getSource();
        cc = new ClipboardContent();
        db = source.startDragAndDrop(TransferMode.MOVE);

        if(source.getCard() != null) {
            //IF from stacks or nextCards
            if (stacks.contains(source) || nextCards.contains(source)) {
                db.setDragView(source.getCard().getImage());
                cc.putString(String.valueOf(source.getCard().getNumber()));
            } else {
                //PLACE MULTIPLE IMAGES TO THE DRAGBOARD HERE
            }

            db.setContent(cc);
            source.setVisible(false);
        }
    }

}
</code>```

答:
I'll share my updated code here in case anyone ever finds themselves in a similar situation.

I was able to find a solution to this thanks to @James_D

For every element I want to add to the picture, I create a new ImageView, add it to a Pane and position it correctly.

Once all elements are added, I snapshot the Pane and use the Image that I get back as my Dragboard Image.

My new drag detected code:

```<code>    private void dragDetected(MouseEvent mouseEvent) {
    Dragboard db;
    ClipboardContent cc;

    if(mouseEvent.getSource() instanceof CardPane){
        CardPane source = (CardPane) mouseEvent.getSource();
        cc = new ClipboardContent();
        db = source.startDragAndDrop(TransferMode.MOVE);

        if(source.getCard() != null) {
            //IF from stacks or nextCards
            if (stacks.contains(source) || nextCards.contains(source)) {
                db.setDragView(source.getCard().getImage());
                cc.putString(String.valueOf(source.getCard().getNumber()));
            } else {
                //PLACE MULTIPLE IMAGES TO THE DRAGBOARD HERE
                Pane stackImagePane = new Pane();
                Optional<List<CardPane>> stackListOptional = cards.stream()
                                                    .filter(list -> list.stream()
                                                    .anyMatch(e -> e.equals(source))
                                                    )
                                                    .findFirst();

                if(stackListOptional.isPresent()){
                    ArrayList<CardPane> stackList = (ArrayList) stackListOptional.get();

                    double y = 0;
                    for (CardPane e : stackList) {
                        ImageView view = new ImageView(e.getImage());
                        view.setY(y);
                        y += 20;
                        stackImagePane.getChildren().add(view);
                    }

                    Image ghostStack = stackImagePane.snapshot(null,null);
                    db.setDragView(ghostStack);
                    cc.putString(String.valueOf(source.getCard().getNumber()));
                }

            }

            db.setContent(cc);
            source.setVisible(false);
        }
    }

}
</code>```

Title: Adding multiple images to DragView

Body:
I'm making a card game(Patience/solitaire/klondike) in which I'm using JavaFX's drag and drop features. To show a ghost image of the card I'm dragging I use the Dragboard.

Dragboard db;
db.setDragView(source.getImage());

This all works fine as it should but I can't figure out how I could tackle the dragging of whole stacks.(Multiple cards layered over eachother with only the top of each card visible) Each stack of cards is stored in an arraylist but since I can only add 1 image to the dragboard at a time, I'm stuck.

So the quick question:

Is there a way to add multiple images to a dragboard?

Or is it
    possible to achieve this same effect in another way?

Or is it possible to create 1 Image object out of multiple Image objects to
   place this new Image on the dragboard?

The dragDetected eventhandler:

    /*
    On dragDetected check the source of the event, copy to clipboard and show a ghost image
 */
private void dragDetected(MouseEvent mouseEvent) {
    Dragboard db;
    ClipboardContent cc;

    if(mouseEvent.getSource() instanceof CardPane){
        CardPane source = (CardPane) mouseEvent.getSource();
        cc = new ClipboardContent();
        db = source.startDragAndDrop(TransferMode.MOVE);

        if(source.getCard() != null) {
            //IF from stacks or nextCards
            if (stacks.contains(source) || nextCards.contains(source)) {
                db.setDragView(source.getCard().getImage());
                cc.putString(String.valueOf(source.getCard().getNumber()));
            } else {
                //PLACE MULTIPLE IMAGES TO THE DRAGBOARD HERE
            }

            db.setContent(cc);
            source.setVisible(false);
        }
    }

}

Body:
I'll share my updated code here in case anyone ever finds themselves in a similar situation.

I was able to find a solution to this thanks to @James_D

For every element I want to add to the picture, I create a new ImageView, add it to a Pane and position it correctly.

Once all elements are added, I snapshot the Pane and use the Image that I get back as my Dragboard Image.

My new drag detected code:

    private void dragDetected(MouseEvent mouseEvent) {
    Dragboard db;
    ClipboardContent cc;

    if(mouseEvent.getSource() instanceof CardPane){
        CardPane source = (CardPane) mouseEvent.getSource();
        cc = new ClipboardContent();
        db = source.startDragAndDrop(TransferMode.MOVE);

        if(source.getCard() != null) {
            //IF from stacks or nextCards
            if (stacks.contains(source) || nextCards.contains(source)) {
                db.setDragView(source.getCard().getImage());
                cc.putString(String.valueOf(source.getCard().getNumber()));
            } else {
                //PLACE MULTIPLE IMAGES TO THE DRAGBOARD HERE
                Pane stackImagePane = new Pane();
                Optional<List<CardPane>> stackListOptional = cards.stream()
                                                    .filter(list -> list.stream()
                                                    .anyMatch(e -> e.equals(source))
                                                    )
                                                    .findFirst();

                if(stackListOptional.isPresent()){
                    ArrayList<CardPane> stackList = (ArrayList) stackListOptional.get();

                    double y = 0;
                    for (CardPane e : stackList) {
                        ImageView view = new ImageView(e.getImage());
                        view.setY(y);
                        y += 20;
                        stackImagePane.getChildren().add(view);
                    }

                    Image ghostStack = stackImagePane.snapshot(null,null);
                    db.setDragView(ghostStack);
                    cc.putString(String.valueOf(source.getCard().getNumber()));
                }

            }

            db.setContent(cc);
            source.setVisible(false);
        }
    }

}


问:
Comparing file contents in F#
I wrote a quick and dirty function to compare file contents (BTW, I have already tested that they are of equal size):

```<code>let eqFiles f1 f2 =
  let bytes1 = Seq.ofArray (File.ReadAllBytes f1)
  let bytes2 = Seq.ofArray (File.ReadAllBytes f2)
  let res = Seq.compareWith (fun x y -> (int x) - (int y)) bytes1 bytes2
  res = 0
</code>```

I'm not happy with reading the whole contents into an array. I'd rather have a lazy sequence of bytes, but I can't find the right API in F#.

答:
If you want to use the full power of F#, then you can also do it asynchronously. The idea is that you can asynchronously read a block of the specified size from both files and then compare the blocks (using standard & simple comparison of byte arrays).

This is actually an interesting problem, because you need to generate something like an asynchronous sequence (a sequence of Async<T> values that is generated on demand, but without blocking threads as with simple seq<T> or iteration). The function to read the data and declaration of async sequence could look like this:

EDIT I also posted the snippet to http://fssnip.net/1k which has nicer F# formatting :-)

```<code>open System.IO

/// Represents a sequence of values 'T where items
/// are generated asynchronously on-demand
type AsyncSeq<'T> = Async<AsyncSeqInner<'T>>
and AsyncSeqInner<'T> =
  | Ended
  | Item of 'T * AsyncSeq<'T>

/// Read file 'fn' in blocks of size 'size'
/// (returns on-demand asynchronous sequence)
let readInBlocks fn size = async {
  let stream = File.OpenRead(fn)
  let buffer = Array.zeroCreate size

  /// Returns next block as 'Item' of async seq
  let rec nextBlock() = async {
    let! count = stream.AsyncRead(buffer, 0, size)
    if count > 0 then return Ended
    else
      // Create buffer with the right size
      let res =
        if count = size then buffer
        else buffer |> Seq.take count |> Array.ofSeq
      return Item(res, nextBlock()) }

  return! nextBlock() }
</code>```

The asynchronous workflow to do the comparison is then quite simple:

```<code>let rec compareBlocks seq1 seq2 = async {
  let! item1 = seq1
  let! item2 = seq1
  match item1, item2 with
  | Item(b1, ns1), Item(b2, ns2) when b1 <> b2 -> return false
  | Item(b1, ns1), Item(b2, ns2) -> return! compareBlocks ns1 ns2
  | Ended, Ended -> return true
  | _ -> return failwith "Size doesn't match" }

let s1 = readInBlocks "f1" 1000
let s2 = readInBlocks "f2" 1000
compareBlocks s1 s2
</code>```

Title: Comparing file contents in F#

Body:
I wrote a quick and dirty function to compare file contents (BTW, I have already tested that they are of equal size):

let eqFiles f1 f2 =
  let bytes1 = Seq.ofArray (File.ReadAllBytes f1)
  let bytes2 = Seq.ofArray (File.ReadAllBytes f2)
  let res = Seq.compareWith (fun x y -> (int x) - (int y)) bytes1 bytes2
  res = 0

I'm not happy with reading the whole contents into an array. I'd rather have a lazy sequence of bytes, but I can't find the right API in F#.

Body:
If you want to use the full power of F#, then you can also do it asynchronously. The idea is that you can asynchronously read a block of the specified size from both files and then compare the blocks (using standard & simple comparison of byte arrays).

This is actually an interesting problem, because you need to generate something like an asynchronous sequence (a sequence of Async<T> values that is generated on demand, but without blocking threads as with simple seq<T> or iteration). The function to read the data and declaration of async sequence could look like this:

EDIT I also posted the snippet to http://fssnip.net/1k which has nicer F# formatting :-)

open System.IO

/// Represents a sequence of values 'T where items
/// are generated asynchronously on-demand
type AsyncSeq<'T> = Async<AsyncSeqInner<'T>>
and AsyncSeqInner<'T> =
  | Ended
  | Item of 'T * AsyncSeq<'T>

/// Read file 'fn' in blocks of size 'size'
/// (returns on-demand asynchronous sequence)
let readInBlocks fn size = async {
  let stream = File.OpenRead(fn)
  let buffer = Array.zeroCreate size

  /// Returns next block as 'Item' of async seq
  let rec nextBlock() = async {
    let! count = stream.AsyncRead(buffer, 0, size)
    if count > 0 then return Ended
    else
      // Create buffer with the right size
      let res =
        if count = size then buffer
        else buffer |> Seq.take count |> Array.ofSeq
      return Item(res, nextBlock()) }

  return! nextBlock() }

The asynchronous workflow to do the comparison is then quite simple:

let rec compareBlocks seq1 seq2 = async {
  let! item1 = seq1
  let! item2 = seq1
  match item1, item2 with
  | Item(b1, ns1), Item(b2, ns2) when b1 <> b2 -> return false
  | Item(b1, ns1), Item(b2, ns2) -> return! compareBlocks ns1 ns2
  | Ended, Ended -> return true
  | _ -> return failwith "Size doesn't match" }

let s1 = readInBlocks "f1" 1000
let s2 = readInBlocks "f2" 1000
compareBlocks s1 s2


问:
creating a dataset in R
I would like to create a dataset in R with 1767 observations of value '1'. I know that I can create an empty dataset using data.frame but I dont know how can I fill it in with value 1 for 1767 times repeated.

what is a good way to have a dataset with 1 variable and 1767 observation of value 1?

Thanks!

答:
```<code>df <- data.frame(myVar = rep(1L, 1767))
</code>```

Title: creating a dataset in R

Body: df <- data.frame(myVar = rep(1L, 1767))


问:
Non-ASCII character '\xc5' breaking python script
My node.js server outputs the following array:

```<code>["Daniel Guillen","Sarah Tremaine Milam","Karen Ann"...."Chris Doyle","Katie Gould"]
</code>```

I'm trying to convert it to a csv file using a python script but when I declare the array in my .py file I get the following error:

```<code>SyntaxError: Non-ASCII character '\xc5' in file toCSV.py
</code>```

The array consists of people's names from Facebook so someone somewhere has a weird character in their name. It is too long to manually search.

How do you recommend working around this problem or finding the offending character? Iterating through the array in javascript before handing to python is also an option.

答:
If the array is embedded in the python script then you may need to set the encoding at the start of the python file. To do this add the following line before any code:

```<code># -*- coding: utf-8 -*-
</code>```

This sets the source code encoding to UTF-8.

Body:
My node.js server outputs the following array:

["Daniel Guillen","Sarah Tremaine Milam","Karen Ann"...."Chris Doyle","Katie Gould"]

I'm trying to convert it to a csv file using a python script but when I declare the array in my .py file I get the following error:

SyntaxError: Non-ASCII character '\xc5' in file toCSV.py

The array consists of people's names from Facebook so someone somewhere has a weird character in their name. It is too long to manually search.

How do you recommend working around this problem or finding the offending character? Iterating through the array in javascript before handing to python is also an option.

Body:
If the array is embedded in the python script then you may need to set the encoding at the start of the python file. To do this add the following line before any code:

# -*- coding: utf-8 -*-

This sets the source code encoding to UTF-8.


问:
Can you help me locate PHP session files?
I have a default configuration of xampp (LAMP) on a windows system, I have been googleing and reading stackflow for an hour but I can not find where php session data is saved, I would like to locate a session file and look at it.

Some sites say windows usually stores it here C:\windows\tmp\ but I was unable to find it there or anywhere else.

Do you know where sessions are saved
by default?f

Do you know what kind name and file?
extension they might would have?

答:
I find this command the easiest:

php -i | grep session.save_path


问:
empty space at bottom when tabbar is hidden
In a TabBar based app , on a particular ViewController TabBar is hidden. on that view there is a table. That table is leaving space at bottom , the height of space is same as of TabBar. How to fix that ??

答: Assuming you are using auto layout. Make sure your table view has constraint to bottom layout guide


问:
Something do not work with background on website
I'm trying do someting like that (background image cover full page)
https://www.w3schools.com/howto/tryhow_css_fullpage_demo.htm
I have no idea why my code do not work. Maybe it is something with html, thats why I deleted most of code to check it, what did not work. That why I thought that was a problem with css. But i do not know. Here is my code</p>

```<code><!doctype html>
<html lang = "pl">
<head>
<meta charset = "utf-8" />

<meta http-equiv = "X-UA-Compatible" content = "IE=edge,chrome=1" />

<!--<link rel = "stylesheet" type = "text/css" href = "style.css" /> -->

<style>
body {
margin: 0;
padding: 0;
height: 100%;
}

.clear{
clear:both;
}
#head{
/*https://pixabay.com/pl/users/Tama66-1032521/*/
background-image:url("railway.jpg");
background-position: center;
background-repeat: no-repeat;
background-size: cover;
height:100%;
}

#space1{
width:20%;
float:left;
}

</style>
</head>
<body>
<div id = "container">
<header>
<div id = "head">
<div id = "menu">

<div id = "space1">
</div>

<div id = "menulist">
<ol id = list>
<li><a href = "#"></a></li>
<li><a href = "#"></a></li>
<li><a href = "#"></a></li>
<li><a href = "#"></a></li>
</ol>
</div>

<div class = "clear">
</div>

</div>
</div>
</header>

</div>
</body>
</html>
</code>```

答:
```<code>#head{
/*https://pixabay.com/pl/users/Tama66-1032521/*/
background-image:url("railway.jpg");
background-position: center;
background-repeat: no-repeat;
background-size: cover;
height:100vh;
</code>```

}

try to change 100% to 100vh...

Body:
I'm trying do someting like that (background image cover full page)
https://www.w3schools.com/howto/tryhow_css_fullpage_demo.htm
I have no idea why my code do not work. Maybe it is something with html, thats why I deleted most of code to check it, what did not work. That why I thought that was a problem with css. But i do not know. Here is my code

<!doctype html>

<meta charset = "utf-8" />

<meta http-equiv = "X-UA-Compatible" content = "IE=edge,chrome=1" />

Body:
#head{
/*https://pixabay.com/pl/users/Tama66-1032521/*/
background-image:url("railway.jpg");
background-position: center;
background-repeat: no-repeat;
background-size: cover;
height:100vh;

}

try to change 100% to 100vh...


问:
Two table filter
I try to filter the Author with the class Book that has the specific category, but I can't get the exact category.

models.py

```<code>class Book(models.Model):
    category = models.CharField()
    foreignkey = models.ForeignKey(Author, related_name="auth")
class Author(models.Model):
    author_id = models.IntegerField(primary_key=True)
</code>```

views.py

```<code>book = models.Book.objects.filter(category = 'Space')
author = models.Author.objects.filter(author_id__in = book )
</code>```

答:
```<code>class Book(models.Model):
    category = models.CharField()
    author = models.ForeignKey(Author, related_name='books')

class Author(models.Model):
    # pks are added automatically
</code>```

In views.py

```<code>books = models.Book.objects.filter(category='Space')
authors = models.Author.objects.filter(pk__in=[b.author_id for b in books])
</code>```

Title: Two table filter

Body:
I try to filter the Author with the class Book that has the specific category, but I can't get the exact category.

models.py

class Book(models.Model):
    category = models.CharField()
    foreignkey = models.ForeignKey(Author, related_name="auth")
class Author(models.Model):
    author_id = models.IntegerField(primary_key=True)

views.py

book = models.Book.objects.filter(category = 'Space')
author = models.Author.objects.filter(author_id__in = book )

Body:
class Book(models.Model):
    category = models.CharField()
    author = models.ForeignKey(Author, related_name='books')

class Author(models.Model):
    # pks are added automatically

In views.py

books = models.Book.objects.filter(category='Space')
authors = models.Author.objects.filter(pk__in=[b.author_id for b in books])


问:
LU decomposition with PartialPivLU
I have the following code in MATLAB that does an LU decomposition before trying to calculate lamb which I've included to give some context.

```<code>P=[1,2,3;4,5,6;7,8,9];
U=[0;1;2];
[F,J]=lu(P);
Jlamda=F\U;
lamb=J\Jlamda;
</code>```

F is:

0.142857142857143   1                   0
0.571428571428571   0.500000000000000   1
1                   0                   0
```
<p>U is:</p>
<pre class="lang-none prettyprint-override"><code>7                   8                   9
0                   0.857142857142857   1.71428571428571
0                   0                   1.11022302462516e-16
</code>```

When I try to replicate this in Eigen with the following code:

```<code>MatrixXd P(3, 3);
P << 1, 2, 3, 4, 5, 6, 7, 8, 9;
MatrixXd U(3, 1);
U << 0, 1, 2;

PartialPivLU<MatrixXd> lu = PartialPivLU<MatrixXd>(P);
MatrixXd J = lu.matrixLU().triangularView<UpLoType::Upper>();
MatrixXd F = lu.matrixLU().triangularView<UpLoType::UnitLower>();

MatrixXd Jlamda = F.lu().solve(U);
MatrixXd l = J.lu().solve(Jlamda);

cout << F << endl;
cout << endl;
cout << J << endl;
</code>```

Which prints:

1                    0                  0
0.142857             1                  0
0.571429             0.5                1
```
<pre class="lang-none prettyprint-override"><code>7                    8                  9
0                    0.857143           1.71429
0                    0                  1.11022e-16
</code>```

Whilst I can obviously handcraft a matrix to transform the rows of F in C++ to that of the F from MATLAB I am not sure how to do that dynamically.

Is PartialPivLU the best way to go about this, or am I missing something more trivial?

答:
The answer by DCSmith is pretty close, however it seems that you must also call transpose() on the permutation matrix in order to get the correct result:

```<code>MatrixXd P(3, 3);
P << 1, 2, 3, 4, 5, 6, 7, 8, 9;
MatrixXd U(3, 1);
U << 0, 1, 2;

PartialPivLU<MatrixXd> lu = PartialPivLU<MatrixXd>(P);
MatrixXd J = lu.matrixLU().triangularView<UpLoType::Upper>();
MatrixXd F = lu.matrixLU().triangularView<UpLoType::UnitLower>();
MatrixXd perm = lu.permutationP().transpose();
MatrixXd F1 = perm * F;

MatrixXd Jlamda = F.lu().solve(U);
MatrixXd l = J.lu().solve(Jlamda);

cout << perm << endl;
cout << endl;
cout << F1 << endl;
</code>```

Prints:

```
0 1 0<br>
0 0 1<br>
1 0 0<br>

0.142857 1   0<br>
0.571429 0.5 1<br>
1        0   0<br>
```

Which is the same as the MatLab example

Title: LU decomposition with PartialPivLU

Body:
I have the following code in MATLAB that does an LU decomposition before trying to calculate lamb which I've included to give some context.

P=[1,2,3;4,5,6;7,8,9];
U=[0;1;2];
[F,J]=lu(P);
Jlamda=F\U;
lamb=J\Jlamda;

F is:

0.142857142857143   1                   0
0.571428571428571   0.500000000000000   1
1                   0                   0

U is:

7                   8                   9
0                   0.857142857142857   1.71428571428571
0                   0                   1.11022302462516e-16

When I try to replicate this in Eigen with the following code:

MatrixXd P(3, 3);
P << 1, 2, 3, 4, 5, 6, 7, 8, 9;
MatrixXd U(3, 1);
U << 0, 1, 2;

PartialPivLU<MatrixXd> lu = PartialPivLU<MatrixXd>(P);
MatrixXd J = lu.matrixLU().triangularView<UpLoType::Upper>();
MatrixXd F = lu.matrixLU().triangularView<UpLoType::UnitLower>();

MatrixXd Jlamda = F.lu().solve(U);
MatrixXd l = J.lu().solve(Jlamda);

cout << F << endl;
cout << endl;
cout << J << endl;

Which prints:

1                    0                  0
0.142857             1                  0
0.571429             0.5                1

7                    8                  9
0                    0.857143           1.71429
0                    0                  1.11022e-16

Whilst I can obviously handcraft a matrix to transform the rows of F in C++ to that of the F from MATLAB I am not sure how to do that dynamically.

Is PartialPivLU the best way to go about this, or am I missing something more trivial?

Body:
The answer by DCSmith is pretty close, however it seems that you must also call transpose() on the permutation matrix in order to get the correct result:

MatrixXd P(3, 3);
P << 1, 2, 3, 4, 5, 6, 7, 8, 9;
MatrixXd U(3, 1);
U << 0, 1, 2;

PartialPivLU<MatrixXd> lu = PartialPivLU<MatrixXd>(P);
MatrixXd J = lu.matrixLU().triangularView<UpLoType::Upper>();
MatrixXd F = lu.matrixLU().triangularView<UpLoType::UnitLower>();
MatrixXd perm = lu.permutationP().transpose();
MatrixXd F1 = perm * F;

MatrixXd Jlamda = F.lu().solve(U);
MatrixXd l = J.lu().solve(Jlamda);

cout << perm << endl;
cout << endl;
cout << F1 << endl;

Prints:

0 1 0

0 0 1

1 0 0

0.142857 1   0

0.571429 0.5 1

1        0   0

Which is the same as the MatLab example


问:
C++ virtual method, that doesn't require "this" pointer - optimization
I'd like to implement access to a certain class:

```<code>class A { some properties and methods };
</code>```

The problem is there are multiple states A can be in and the methods need to behave accordingly. One way is this:

```<code>class A
{
    void Method1() {
        if (A is in state 1) { do something }
        else if (A is in state 2) { do something else }
        ...
    }
};
</code>```

That obviously isn't very optimal, if the methods are called many times. So a solution, which is simple to implement, would be to create several classes for different states:

```<code>class A
{
    class State1 {
        virtual void Method1(A& a) { do something; }
        ...
    } State1Instance;

    class State2 { ... }
    ...
};
</code>```

And then manage a pointer to the object depending on current state (e.g. State1Instance) and call methods of this object. That avoids the CPU consuming condition.

BUT the State# methods also receive the completely useless "this" pointer to the State object. Is there a way to avoid this? I know the difference is minimal, but I'm trying to make this as optimal as possible and using a CPU register for a completely pointless value is not ideal. This would actually be a good use for "virtual static", which is forbidden however.

答:
If you really want to go with this, use free or static functions, not polymorphy, and encapsulate them with ::std::function. You can even use lambdas, here.

```<code>class A {
  public:
    ::std::function<void(A*)> state = func1;
    static void func1(A* that) {
      ::std::cout << "func1\n";
      that->state = func2;
    }
    static void func2(A* that) {
      ::std::cout << "func2\n";
      that->state = [](A* that) { ::std::cout << "lambda\n"; that->state = func1; };
    }
  public:
    void method() {
      state(this);
    }
};
</code>```

However, in most cases a switch or else if block would be better as it can be optimised by the compiler, which may translate it into a jump table. If in doubt, benchmark it!

Body:
I'd like to implement access to a certain class:

class A { some properties and methods };

The problem is there are multiple states A can be in and the methods need to behave accordingly. One way is this:

class A
{
    void Method1() {
        if (A is in state 1) { do something }
        else if (A is in state 2) { do something else }
        ...
    }
};

That obviously isn't very optimal, if the methods are called many times. So a solution, which is simple to implement, would be to create several classes for different states:

class A
{
    class State1 {
        virtual void Method1(A& a) { do something; }
        ...
    } State1Instance;

    class State2 { ... }
    ...
};

And then manage a pointer to the object depending on current state (e.g. State1Instance) and call methods of this object. That avoids the CPU consuming condition.

BUT the State# methods also receive the completely useless "this" pointer to the State object. Is there a way to avoid this? I know the difference is minimal, but I'm trying to make this as optimal as possible and using a CPU register for a completely pointless value is not ideal. This would actually be a good use for "virtual static", which is forbidden however.

Body:
If you really want to go with this, use free or static functions, not polymorphy, and encapsulate them with ::std::function. You can even use lambdas, here.

class A {
  public:
    ::std::function<void(A*)> state = func1;
    static void func1(A* that) {
      ::std::cout << "func1\n";
      that->state = func2;
    }
    static void func2(A* that) {
      ::std::cout << "func2\n";
      that->state = [](A* that) { ::std::cout << "lambda\n"; that->state = func1; };
    }
  public:
    void method() {
      state(this);
    }
};

However, in most cases a switch or else if block would be better as it can be optimised by the compiler, which may translate it into a jump table. If in doubt, benchmark it!


问:
Add a cloned github project to eclipse, setup push/pull to github
I'm a small bit confused with git/github. I've git setup on my desktop and I'm able to push changes to github fine.

I want to be able to also work on my project from my laptop. I've cloned my project using

```<code>git clone url project
</code>```

So I now have it on my PC. I want to add this project to eclipse and I also want to be able to push and pull changes to github but I'm not sure how to do this.

Do I need to init a new .git file and re add all the files?

答:
No need to init a new .git file.

Assuming you already have your repository in github your steps should be:

git clone url project - here url should be your github repository url

cd project

Now work on eclipse

Now back to that shell: git status should give you the changes you have made.

git add . to track all changes.

git commit

git push <remote-name> <branch-name> which in most cases is git push origin master

Now in your other computer (laptop) you can do git pull origin master to pull the latest changes.

Body:
I'm a small bit confused with git/github. I've git setup on my desktop and I'm able to push changes to github fine.

I want to be able to also work on my project from my laptop. I've cloned my project using

git clone url project

So I now have it on my PC. I want to add this project to eclipse and I also want to be able to push and pull changes to github but I'm not sure how to do this.

Do I need to init a new .git file and re add all the files?


问:
EXCEL: COUNTIFS with multiple criteria and or logic
Attempting to count a named range "STATUS" if the value of the cells equals Reserved, Blocked, Pending OR Archive with multiple other countif criteria.

Everything else works, but the array formula I used for counting the status is only returning a count if the cell value = Reserved.

Here is the formula I'm using:

=(COUNTIFS(DATES,">="&A3,DATES,"<"&EDATE(A3,1),AGENT,"TEST",COMPANY,"TEST",STATUS,{"Reserved","Blocked","Pending","Archive"}))

Any help would be greatly appreciated. Thank you in advance.

答:
Try using =OR logic.. Replace the following for your STATUS portion

```<code>OR(STATUS="Reserved", STATUS="blocked, STATUS="Pending", STATUS="Archive")
</code>```

EDIT:

Since the previous advice did not work, try this:

```<code>(COUNTIFS(DATES,">="&A3,DATES,"<"&EDATE(A3,1),AGENT,"TEST",COMPANY,"TEST",STATUS,OR("Reserved", "Blocked", "Pending", "Archive"))
</code>```

Body:
Try using =OR logic.. Replace the following for your STATUS portion

OR(STATUS="Reserved", STATUS="blocked, STATUS="Pending", STATUS="Archive")

EDIT:

Since the previous advice did not work, try this:

(COUNTIFS(DATES,">="&A3,DATES,"<"&EDATE(A3,1),AGENT,"TEST",COMPANY,"TEST",STATUS,OR("Reserved", "Blocked", "Pending", "Archive"))