问:
Checking if float is equivalent to an integer value in python
In Python 3, I am checking whether a given value is triangular, that is, it can be represented as n * (n + 1) / 2 for some positive integer n.

Can I just write:

```<code>import math

def is_triangular1(x):
    num = (1 / 2) * (math.sqrt(8 * x + 1) - 1)
    return int(num) == num
</code>```

Or do I need to do check within a tolerance instead?

```<code>epsilon = 0.000000000001
def is_triangular2(x):
    num = (1 / 2) * (math.sqrt(8 * x + 1) - 1)
    return abs(int(num) - num) < epsilon
</code>```

I checked that both of the functions return same results for x up to 1,000,000. But I am not sure if generally speaking int(x) == x will always correctly determine whether a number is integer, because of the cases when for example 5 is represented as 4.99999999999997 etc.

As far as I know, the second way is the correct one if I do it in C, but I am not sure about Python 3.

答:
Under the hood, Python's float type is a C double.

The most robust way would be to get the nearest integer to num, then test if that integers satisfies the property you're after:

```<code>import math
def is_triangular1(x):
    num = (1/2) * (math.sqrt(8*x+1)-1 )
    inum = int(round(num))
    return inum*(inum+1) == 2*x  # This line uses only integer arithmetic
</code>```

Body:
In Python 3, I am checking whether a given value is triangular, that is, it can be represented as n * (n + 1) / 2 for some positive integer n.

Can I just write:

import math

def is_triangular1(x):
    num = (1 / 2) * (math.sqrt(8 * x + 1) - 1)
    return int(num) == num

Or do I need to do check within a tolerance instead?

epsilon = 0.000000000001
def is_triangular2(x):
    num = (1 / 2) * (math.sqrt(8 * x + 1) - 1)
    return abs(int(num) - num) < epsilon

I checked that both of the functions return same results for x up to 1,000,000. But I am not sure if generally speaking int(x) == x will always correctly determine whether a number is integer, because of the cases when for example 5 is represented as 4.99999999999997 etc.

As far as I know, the second way is the correct one if I do it in C, but I am not sure about Python 3.

Body:
Under the hood, Python's float type is a C double.

The most robust way would be to get the nearest integer to num, then test if that integers satisfies the property you're after:

import math
def is_triangular1(x):
    num = (1/2) * (math.sqrt(8*x+1)-1 )
    inum = int(round(num))
    return inum*(inum+1) == 2*x  # This line uses only integer arithmetic


来源: stackexchange

问:
Does RTMP support the Display Orientation SEI Message in h264 streams?
I'm streaming video h264 video and AAC audio over RTMP on Android using the native MediaCodec APIs. Video and audio look great, however while the video is shot in potrait mode, playback on the web or with VLC is always in landscape.

Having read through the h264 spec, I see that this sort of extra metadata can be specified in Supplemental Enhancement Information (SEI), and I've gone about adding it to the raw h264 bit stream. My SEI NAL unit for this follows this rudimentary format, I plan to optimize later:

```<code>val displayOrientationSEI = {
    val prefix = byteArrayOf(0, 0, 0, 1)
    val nalHeader = byteArrayOf(6) // forbidden_zero_bit:0; nal_ref_idc:0; nal_unit_type:6

    val display = byteArrayOf(47 /* Display orientation type*/, 3 /*payload size*/)

    val displayOrientationCancelFlag = "0" // u(1); Rotation information follows
    val horFlip = "1" // hor_flip; u(1); Flip horizontally
    val verFlip = "1" // ver_flip; u(1); Flip vertically
    val anticlockwiseRotation = "0100000000000000" // u(16); value / 2^16 -> 90 degrees
    val displayOrientationRepetitionPeriod = "010" // ue(v); Persistent till next video sequence
    val displayOrientationExtensionFlag = "0" // u(1); No other value is permitted by the spec atm
    val byteAlignment = "1"

    val bitString = displayOrientationCancelFlag +
            horFlip +
            verFlip +
            anticlockwiseRotation +
            displayOrientationRepetitionPeriod +
            displayOrientationExtensionFlag +
            byteAlignment

    prefix + nalHeader + display + BigInteger(bitString, 2).toByteArray()
}()
</code>```

Using Jcodec's SEI class, I can see that my SEI message is parsed properly. I write out these packets to the RTMP stream using an Android JNI wrapper for LibRtmp.

Despite this, ffprobe does not show the orientation metadata, and the video when played remains in landscape.

At this point I think I'm missing a very small detail about how FLV headers work when the raw h264 units are written out by LibRtmp. I have tried appending this displayOrientationSEI NAL unit:

To the initial SPS and PPS configuration only.

To each raw h264 NAL units straight from the encoder.

To both.

What am I doing wrong? Going through the source of some RTMP libraries, like rtmp-rtsp-stream-client-java, it seems the SEI message is dropped when creating FLV tags.

Help is much, much appreciated.

答:
Does RTMP support the Display Orientation SEI Message in h264 streams?

RTMP is unaware of the very concept. from RTMPs perspective, the SEI is just a series of bytes it copys. It never looks at them, it never parses them.

The thing that needs to support it, is the h.264 decoder (which RTMP is also unaware of) and the player software. If it is not working for you, you must check the player, or the validity of the encoded SEI, not the transport.

ContentLicense: CC BY-SA 4.0

Body:
I'm streaming video h264 video and AAC audio over RTMP on Android using the native MediaCodec APIs. Video and audio look great, however while the video is shot in potrait mode, playback on the web or with VLC is always in landscape.

Having read through the h264 spec, I see that this sort of extra metadata can be specified in Supplemental Enhancement Information (SEI), and I've gone about adding it to the raw h264 bit stream. My SEI NAL unit for this follows this rudimentary format, I plan to optimize later:

val displayOrientationSEI = {
    val prefix = byteArrayOf(0, 0, 0, 1)
    val nalHeader = byteArrayOf(6) // forbidden_zero_bit:0; nal_ref_idc:0; nal_unit_type:6

    val display = byteArrayOf(47 /* Display orientation type*/, 3 /*payload size*/)

    val displayOrientationCancelFlag = "0" // u(1); Rotation information follows
    val horFlip = "1" // hor_flip; u(1); Flip horizontally
    val verFlip = "1" // ver_flip; u(1); Flip vertically
    val anticlockwiseRotation = "0100000000000000" // u(16); value / 2^16 -> 90 degrees
    val displayOrientationRepetitionPeriod = "010" // ue(v); Persistent till next video sequence
    val displayOrientationExtensionFlag = "0" // u(1); No other value is permitted by the spec atm
    val byteAlignment = "1"

    val bitString = displayOrientationCancelFlag +
            horFlip +
            verFlip +
            anticlockwiseRotation +
            displayOrientationRepetitionPeriod +
            displayOrientationExtensionFlag +
            byteAlignment

    prefix + nalHeader + display + BigInteger(bitString, 2).toByteArray()
}()

Using Jcodec's SEI class, I can see that my SEI message is parsed properly. I write out these packets to the RTMP stream using an Android JNI wrapper for LibRtmp.

Despite this, ffprobe does not show the orientation metadata, and the video when played remains in landscape.

At this point I think I'm missing a very small detail about how FLV headers work when the raw h264 units are written out by LibRtmp. I have tried appending this displayOrientationSEI NAL unit:

To the initial SPS and PPS configuration only.

To each raw h264 NAL units straight from the encoder.

To both.

What am I doing wrong? Going through the source of some RTMP libraries, like rtmp-rtsp-stream-client-java, it seems the SEI message is dropped when creating FLV tags.

Help is much, much appreciated.


问:
Organising folders in terraform
I have a terraform setup in which i am creating resources in aws, i am using s3, ec2 and also kubernetes. For kubernetes i have more than 5 .tf files. I have created a folder called kube-aws and placed the .tf files there. Right now i have a setup like below

```<code>scripts/
 |
  s3.tf
  ec2.tf
  kube-aws/
   |
   web-deploy.tf
   web-service.tf
   app-deploy.tf
   app-service.tf
</code>```

Is this a right approach, will terraform pick the .tf files from kubw-aws folder as well? or should i do anything else to make this work.

答:
The resources in kube-aws directory will not be included when scripts is your working directory. The scripts directory is considered the root module in this instance (see Modules documentation):

The .tf files in your working directory when you run terraform plan or terraform apply together form the root module.

You have two options to include kube-aws resources:

Move them up to the scripts directory.

Create a module block in one of the scripts/*.tf files and pass in required variables.

For example, in, say, s3.tf:

module "kube_aws" {
  source = "./kube-aws"

  // pass in your variables here
}
```

The choice you make is entirely up to you but the guidance in when to write a module is pretty persuasive:

We do not recommend writing modules that are just thin wrappers around single other resource types. If you have trouble finding a name for your module that isn't the same as the main resource type inside it, that may be a sign that your module is not creating any new abstraction and so the module is adding unnecessary complexity. Just use the resource type directly in the calling module instead.

I would recommend option 1 above, i.e. move your .tf files into a single directory, at least until you clear about when to use a module and how to best structure them. I would also highly recommend getting acquainted with the official (and excellent) documentation on Modules and Module Composition, as well as looking at example modules in Terraform Registry and their associated source code (links to source can be found on module pages).

Title: Organising folders in terraform

Body:
I have a terraform setup in which i am creating resources in aws, i am using s3, ec2 and also kubernetes. For kubernetes i have more than 5 .tf files. I have created a folder called kube-aws and placed the .tf files there. Right now i have a setup like below

scripts/
 |
  s3.tf
  ec2.tf
  kube-aws/
   |
   web-deploy.tf
   web-service.tf
   app-deploy.tf
   app-service.tf

Is this a right approach, will terraform pick the .tf files from kubw-aws folder as well? or should i do anything else to make this work.

Body:
The resources in kube-aws directory will not be included when scripts is your working directory. The scripts directory is considered the root module in this instance (see Modules documentation):

The .tf files in your working directory when you run terraform plan or terraform apply together form the root module.

You have two options to include kube-aws resources:

Move them up to the scripts directory.

Create a module block in one of the scripts/*.tf files and pass in required variables.

For example, in, say, s3.tf:

module "kube_aws" {
  source = "./kube-aws"

  // pass in your variables here
}

The choice you make is entirely up to you but the guidance in when to write a module is pretty persuasive:

We do not recommend writing modules that are just thin wrappers around single other resource types. If you have trouble finding a name for your module that isn't the same as the main resource type inside it, that may be a sign that your module is not creating any new abstraction and so the module is adding unnecessary complexity. Just use the resource type directly in the calling module instead.

I would recommend option 1 above, i.e. move your .tf files into a single directory, at least until you clear about when to use a module and how to best structure them. I would also highly recommend getting acquainted with the official (and excellent) documentation on Modules and Module Composition, as well as looking at example modules in Terraform Registry and their associated source code (links to source can be found on module pages).


问:
Can not delete Test Plan / Suite in Azure Dev Ops
Can anyone help me to delete items below?

I already set the permissions, may I missing something?

Error message

Failed to delete work item: 8423. Error Details: You don't have sufficient permissions to delete this work item. You must have work item and test artifacts delete permissions.

答:
As mentioned by Daniel Mann, Test Plans subscription is required to manage Test Plans.

Documentation


问:
What does the term 'binding' mean in JS?
Please clarify for me what the term binding means in JavaScript. I've started to read the book 'Eloquent JS' and there are lots of occurrences of this word. Does it just mean variable? Here are few examples from the book:

So if you know that the property you are interested in is called color, you say value.color. If you want to extract the property named by the value held in the binding i, you say value[i].Property names are strings. They can be any string, but the dot notation works only with names that look like valid binding names.

Bindings can also be changeable or constant, but this is separate from the way their values behave. Even though number values don’t change, you can use a let binding to keep track of a changing number by changing the value the binding points at. Similarly, though a const binding to an object can itself not be changed and will continue to point at the same object, the contents of that object might change.

答:
Okay, let me clarify. The first question what is a binding:

A binding is a symbol, variable, constant, etc. that points to some literal value, or object in memory.

In reference to your book, it says:

```<code>const myObj = { color: blue }; // the property color is defined on this object
myObj["color"]; // => "blue" The color property can be accessed by passing in a string
myObj = anotherObj; // not allowed, you declared it with const
</code>```

The reference or binding is to the object in memory and that cannot change because you declared this reference with const. But you can modify the properties of the object in memory. The object itself is mutable.

Any further discussion of bindings is a discussion on Lexical Scope.

Body:
Okay, let me clarify. The first question what is a binding:

A binding is a symbol, variable, constant, etc. that points to some literal value, or object in memory.

In reference to your book, it says:

const myObj = { color: blue }; // the property color is defined on this object
myObj["color"]; // => "blue" The color property can be accessed by passing in a string
myObj = anotherObj; // not allowed, you declared it with const

The reference or binding is to the object in memory and that cannot change because you declared this reference with const. But you can modify the properties of the object in memory. The object itself is mutable.

Any further discussion of bindings is a discussion on Lexical Scope.


问:
How to set grid (vector or arrows) lines in gnuplot
The location of the grid lines (parallel to Y-axis) at X-axis are defined at third row of a files, for example.

The third lines has the points

```<code>#   0.00000000 0.08329780 0.11683890 0.20013670 0.23367770
</code>```

I can get the Ymax from another file defined as FILE with

```<code>set table $Dummy
plot FILE u ($0==1?(Ymax=$2): NaN) w table # i have updated this line. This will be used only for height of the grid line. Here FILE is a data file with two columns only which will be plotted in X-Y format.

unset table
</code>```

How I can set grid lines at above locations that should end to Ymax ?

I need something like:

```<code>for i in 0.00000000 0.08329780 0.11683890 0.20013670 0.23367770
do
set arrow $i, Ymax lc rgb "black" dt 2 nohead
done
</code>```

答:
Grid lines are placed at axis tick locations.  The major ticks (tick level 0) and minor ticks (tick level 1) are tracked separately.  The linetype of the grid lines can also be chosen. To generate thin blue vertical grid lines at the x coordinates you show using minor ticks to control the grid lines:

```<code>  set xtics add ( 0.00000000 1, 0.08329780 1, 0.11683890 1, 0.20013670 1, 0.23367770 1 )
  set grid mx lt 0, lt 1 lw 0.5 lc "blue"
</code>```

As always see the documentation (help set xtics, help set grid) for more details.

Body:
The location of the grid lines (parallel to Y-axis) at X-axis are defined at third row of a files, for example.

The third lines has the points

#   0.00000000 0.08329780 0.11683890 0.20013670 0.23367770

I can get the Ymax from another file defined as FILE with

set table $Dummy
plot FILE u ($0==1?(Ymax=$2): NaN) w table # i have updated this line. This will be used only for height of the grid line. Here FILE is a data file with two columns only which will be plotted in X-Y format.

unset table

How I can set grid lines at above locations that should end to Ymax ?

I need something like:

for i in 0.00000000 0.08329780 0.11683890 0.20013670 0.23367770
do
set arrow $i, Ymax lc rgb "black" dt 2 nohead
done

Body:
Grid lines are placed at axis tick locations.  The major ticks (tick level 0) and minor ticks (tick level 1) are tracked separately.  The linetype of the grid lines can also be chosen. To generate thin blue vertical grid lines at the x coordinates you show using minor ticks to control the grid lines:

  set xtics add ( 0.00000000 1, 0.08329780 1, 0.11683890 1, 0.20013670 1, 0.23367770 1 )
  set grid mx lt 0, lt 1 lw 0.5 lc "blue"

As always see the documentation (help set xtics, help set grid) for more details.


问:
How to change the colors of a segment in a UISegmentedControl in iOS 13?
A UISegmentedControl has a new appearance in iOS 13 and existing code to alter the colors of the segmented control no longer work as they did.

Prior to iOS 13 you could set the tintColor and that would be used for the border around the segmented control, the lines between the segments, and the background color of the selected segment. Then you could change the color of the titles of each segment using the foreground color attribute with titleTextAttributes.

Under iOS 13, the tintColor does nothing. You can set the segmented control's backgroundColor to change the overall color of the segmented control. But I can't find any way to alter the color used as the background of the selected segment. Setting the text attributes still works. I even tried setting the background color of the title but that only affects the background of the title, not the rest of the selected segment's background color.

In short, how do you modify the background color of the currently selected segment of a UISegmentedControl in iOS 13? Is there a proper solution, using public APIs, that doesn't require digging into the private subview structure?

There are no new properties in iOS 13 for UISegmentedControl or UIControl and none of the changes in UIView are relevant.

答:
While answers above are great, most of them get the color of text inside selected segment wrong. I've created UISegmentedControl subclass which you can use on iOS 13 and pre-iOS 13 devices and use the tintColor property as you would on pre iOS 13 devices.

```<code>    class LegacySegmentedControl: UISegmentedControl {
        private func stylize() {
            if #available(iOS 13.0, *) {
                selectedSegmentTintColor = tintColor
                let tintColorImage = UIImage(color: tintColor)
                setBackgroundImage(UIImage(color: backgroundColor ?? .clear), for: .normal, barMetrics: .default)
                setBackgroundImage(tintColorImage, for: .selected, barMetrics: .default)
                setBackgroundImage(UIImage(color: tintColor.withAlphaComponent(0.2)), for: .highlighted, barMetrics: .default)
                setBackgroundImage(tintColorImage, for: [.highlighted, .selected], barMetrics: .default)
                setTitleTextAttributes([.foregroundColor: tintColor!, NSAttributedString.Key.font: UIFont.systemFont(ofSize: 13, weight: .regular)], for: .normal)

                setDividerImage(tintColorImage, forLeftSegmentState: .normal, rightSegmentState: .normal, barMetrics: .default)
                layer.borderWidth = 1
                layer.borderColor = tintColor.cgColor

// Detect underlying backgroundColor so the text color will be properly matched

                if let background = backgroundColor {
                    self.setTitleTextAttributes([.foregroundColor: background, NSAttributedString.Key.font: UIFont.systemFont(ofSize: 13, weight: .regular)], for: .selected)
                } else {
                    func detectBackgroundColor(of view: UIView?) -> UIColor? {
                        guard let view = view else {
                            return nil
                        }
                        if let color = view.backgroundColor, color != .clear {
                            return color
                        }
                        return detectBackgroundColor(of: view.superview)
                    }
                    let textColor = detectBackgroundColor(of: self) ?? .black

                    self.setTitleTextAttributes([.foregroundColor: textColor, NSAttributedString.Key.font: UIFont.systemFont(ofSize: 13, weight: .regular)], for: .selected)
                }
            }
        }

        override func tintColorDidChange() {
            super.tintColorDidChange()
            stylize()
        }
    }

    fileprivate extension UIImage {
        public convenience init?(color: UIColor, size: CGSize = CGSize(width: 1, height: 1)) {
          let rect = CGRect(origin: .zero, size: size)
          UIGraphicsBeginImageContextWithOptions(rect.size, false, 0.0)
          color.setFill()
          UIRectFill(rect)
          let image = UIGraphicsGetImageFromCurrentImageContext()
          UIGraphicsEndImageContext()

          guard let cgImage = image?.cgImage else { return nil }
          self.init(cgImage: cgImage)
        }
    }
</code>```

Using tintColorDidChange method we ensure that the stylize method will be called every time the tintColor property changes on the segment view, or any of the underlying views, which is preferred behaviour on iOS.

Result:

Body:
While answers above are great, most of them get the color of text inside selected segment wrong. I've created UISegmentedControl subclass which you can use on iOS 13 and pre-iOS 13 devices and use the tintColor property as you would on pre iOS 13 devices.

    class LegacySegmentedControl: UISegmentedControl {
        private func stylize() {
            if #available(iOS 13.0, *) {
                selectedSegmentTintColor = tintColor
                let tintColorImage = UIImage(color: tintColor)
                setBackgroundImage(UIImage(color: backgroundColor ?? .clear), for: .normal, barMetrics: .default)
                setBackgroundImage(tintColorImage, for: .selected, barMetrics: .default)
                setBackgroundImage(UIImage(color: tintColor.withAlphaComponent(0.2)), for: .highlighted, barMetrics: .default)
                setBackgroundImage(tintColorImage, for: [.highlighted, .selected], barMetrics: .default)
                setTitleTextAttributes([.foregroundColor: tintColor!, NSAttributedString.Key.font: UIFont.systemFont(ofSize: 13, weight: .regular)], for: .normal)

                setDividerImage(tintColorImage, forLeftSegmentState: .normal, rightSegmentState: .normal, barMetrics: .default)
                layer.borderWidth = 1
                layer.borderColor = tintColor.cgColor

// Detect underlying backgroundColor so the text color will be properly matched

                if let background = backgroundColor {
                    self.setTitleTextAttributes([.foregroundColor: background, NSAttributedString.Key.font: UIFont.systemFont(ofSize: 13, weight: .regular)], for: .selected)
                } else {
                    func detectBackgroundColor(of view: UIView?) -> UIColor? {
                        guard let view = view else {
                            return nil
                        }
                        if let color = view.backgroundColor, color != .clear {
                            return color
                        }
                        return detectBackgroundColor(of: view.superview)
                    }
                    let textColor = detectBackgroundColor(of: self) ?? .black

                    self.setTitleTextAttributes([.foregroundColor: textColor, NSAttributedString.Key.font: UIFont.systemFont(ofSize: 13, weight: .regular)], for: .selected)
                }
            }
        }

        override func tintColorDidChange() {
            super.tintColorDidChange()
            stylize()
        }
    }

    fileprivate extension UIImage {
        public convenience init?(color: UIColor, size: CGSize = CGSize(width: 1, height: 1)) {
          let rect = CGRect(origin: .zero, size: size)
          UIGraphicsBeginImageContextWithOptions(rect.size, false, 0.0)
          color.setFill()
          UIRectFill(rect)
          let image = UIGraphicsGetImageFromCurrentImageContext()
          UIGraphicsEndImageContext()

          guard let cgImage = image?.cgImage else { return nil }
          self.init(cgImage: cgImage)
        }
    }

Using tintColorDidChange method we ensure that the stylize method will be called every time the tintColor property changes on the segment view, or any of the underlying views, which is preferred behaviour on iOS.

Result:


问:
Find next / previous number in mysql table
Given this table:

```<code>contractnumber | itemnumber
1234           | 100151
1234           | 100152
1235           | 100127
1235           | 100128
1236           | 100001
1236           | 100002
</code>```

How can I get the next (or previous) itemnumber from the table after a given itemnumber with the table order is contractnumber ASC, itemnumber ASC?

For example I'd like to get the next itemnumber after 100128 (100128) or the previous itemnumber to 100001 (100128).

答:
Since for each contractnumber may exist different itemnumbers it's not as simple as ORDER BY and LIMIT 1.

You must also check the case that the next/previous itemnumber has the same contractnumber.

For the previous item of 100128:

```<code>select
  coalesce(
    (
      select min(itemnumber) from tablename
      where contractnumber = (
        select contractnumber from tablename
        where itemnumber = 100128
      ) and itemnumber > 100128
    ),
    (
      select itemnumber from tablename
      where contractnumber > (
        select contractnumber from tablename
        where itemnumber = 100128
      )
      order by contractnumber, itemnumber limit 1
    )
  ) itemnumber
</code>```

For the next item of 100001:

```<code>select
  coalesce(
    (
      select max(itemnumber) from tablename
      where contractnumber = (
        select contractnumber from tablename
        where itemnumber = 100001
      ) and itemnumber < 100001
    ),
    (
      select itemnumber from tablename
      where contractnumber < (
        select contractnumber from tablename
        where itemnumber = 100001
      )
      order by contractnumber desc, itemnumber desc limit 1
    )
  ) itemnumber
</code>```

See the demo.

Body:
Given this table:

contractnumber | itemnumber
1234           | 100151
1234           | 100152
1235           | 100127
1235           | 100128
1236           | 100001
1236           | 100002

How can I get the next (or previous) itemnumber from the table after a given itemnumber with the table order is contractnumber ASC, itemnumber ASC?

For example I'd like to get the next itemnumber after 100128 (100128) or the previous itemnumber to 100001 (100128).

Body:
Since for each contractnumber may exist different itemnumbers it's not as simple as ORDER BY and LIMIT 1.

You must also check the case that the next/previous itemnumber has the same contractnumber.

For the previous item of 100128:

select
  coalesce(
    (
      select min(itemnumber) from tablename
      where contractnumber = (
        select contractnumber from tablename
        where itemnumber = 100128
      ) and itemnumber > 100128
    ),
    (
      select itemnumber from tablename
      where contractnumber > (
        select contractnumber from tablename
        where itemnumber = 100128
      )
      order by contractnumber, itemnumber limit 1
    )
  ) itemnumber

For the next item of 100001:

select
  coalesce(
    (
      select max(itemnumber) from tablename
      where contractnumber = (
        select contractnumber from tablename
        where itemnumber = 100001
      ) and itemnumber < 100001
    ),
    (
      select itemnumber from tablename
      where contractnumber < (
        select contractnumber from tablename
        where itemnumber = 100001
      )
      order by contractnumber desc, itemnumber desc limit 1
    )
  ) itemnumber

See the demo.


答:
I've found out what it is (in this book in an earlier chapter). Here is the snippet:

How does a program keep an internal state? How does it remember things? We have seen how to produce new values from old values, but this does not change the old values, and the new value has to be immediately used or it will dissipate again. To catch and hold values, JavaScript provides a thing called a binding, or variable:

```<code>let caught = 5 * 5;
</code>```

That’s a second kind of statement. The special word (keyword) let indicates that this sentence is going to define a binding. It is followed by the name of the binding and, if we want to immediately give it a value, by an = operator and an expression.

The previous statement creates a binding called caught and uses it to grab hold of the number that is produced by multiplying 5 by 5.

Title: What does the term 'binding' mean in JS?

Body:
Please clarify for me what the term binding means in JavaScript. I've started to read the book 'Eloquent JS' and there are lots of occurrences of this word. Does it just mean variable? Here are few examples from the book:

So if you know that the property you are interested in is called color, you say value.color. If you want to extract the property named by the value held in the binding i, you say value[i].Property names are strings. They can be any string, but the dot notation works only with names that look like valid binding names.

Bindings can also be changeable or constant, but this is separate from the way their values behave. Even though number values don’t change, you can use a let binding to keep track of a changing number by changing the value the binding points at. Similarly, though a const binding to an object can itself not be changed and will continue to point at the same object, the contents of that object might change.

Body:
I've found out what it is (in this book in an earlier chapter). Here is the snippet:

How does a program keep an internal state? How does it remember things? We have seen how to produce new values from old values, but this does not change the old values, and the new value has to be immediately used or it will dissipate again. To catch and hold values, JavaScript provides a thing called a binding, or variable:

let caught = 5 * 5;

That’s a second kind of statement. The special word (keyword) let indicates that this sentence is going to define a binding. It is followed by the name of the binding and, if we want to immediately give it a value, by an = operator and an expression.

The previous statement creates a binding called caught and uses it to grab hold of the number that is produced by multiplying 5 by 5.


问:
ts-node-dev doesn't apply changes in auto reload
I have built an application using FeathersJS in Typescript but althought the nodemon for typescript (ts-node-dev) says that the server has restarted when a typescript file is changed, the change is not applyed.
I always need to kill the application and start again to see the changes.

Here is the log:

```<code>[INFO] 15:43:51 Restarting: C:\api\src\models\favorites.model.ts has been modified
Using ts-node version 7.0.1, typescript version 3.9.3
info: Feathers application started on http://localhost:3030
</code>```

Here is the dev script on package.json:

ts-node-dev --no-notify src/

Here is the tsconfig.json:

```<code>{
  "compilerOptions": {
    "target": "es2018",
    "module": "commonjs",
    "outDir": "./lib",
    "rootDir": "./src",
    "strict": true,
    "esModuleInterop": true
  },
  "exclude": [
    "test"
  ]
}
</code>```

And here is the package.json:

```<code>{
  "homepage": "",
  "private": true,
  "main": "src",
  "keywords": [
    "feathers"
  ],
  "contributors": [],
  "bugs": {},
  "directories": {
    "lib": "src",
    "test": "test/",
    "config": "config/"
  },
  "engines": {
    "node": "^12.0.0",
    "npm": ">= 3.0.0"
  },
  "scripts": {
    "test": "npm run compile && npm run mocha",
    "dev": "ts-node-dev --no-notify src/",
    "start": "npm run compile && node lib/",
    "mocha": "ts-mocha \"test/**/*.ts\" --recursive --exit",
    "compile": "shx rm -rf lib/ && tsc"
  },
  "prettier":{
    "singleQuote": true
  },
  "standard": {
    "env": [
      "mocha"
    ],
    "ignore": []
  },
  "types": "lib/",
  "dependencies": {
    "@feathersjs/authentication": "^4.5.3",
    "@feathersjs/authentication-local": "^4.5.4",
    "@feathersjs/authentication-oauth": "^4.5.4",
    "@feathersjs/configuration": "^4.5.3",
    "@feathersjs/errors": "^4.5.3",
    "@feathersjs/express": "^4.5.4",
    "@feathersjs/feathers": "^4.5.3",
    "@feathersjs/transport-commons": "^4.5.3",
    "compression": "^1.7.4",
    "cors": "^2.8.5",
    "feathers-mongoose": "^8.3.0",
    "helmet": "^3.22.0",
    "mongodb-core": "^3.2.7",
    "mongoose": "^5.9.16",
    "serve-favicon": "^2.5.0",
    "winston": "^3.2.1"
  },
  "devDependencies": {
    "@types/compression": "^1.7.0",
    "@types/cors": "^2.8.6",
    "@types/helmet": "0.0.47",
    "@types/jsonwebtoken": "^8.5.0",
    "@types/mocha": "^7.0.2",
    "@types/mongoose": "^5.7.21",
    "@types/serve-favicon": "^2.5.0",
    "axios": "^0.19.2",
    "mocha": "^7.2.0",
    "nodemon": "^2.0.4",
    "shx": "^0.3.2",
    "ts-mocha": "^7.0.0",
    "ts-node-dev": "^1.0.0-pre.44",
    "tslint": "^6.1.2",
    "typescript": "^3.9.3"
  }
}
</code>```

答:
You need to tell the compiler to watch for changes. Add the following script or adjust your compile script with the watch flag:

```<code>"watch-ts": "tsc -w"
</code>```

or

```<code>"compile": "shx rm -rf lib/ && tsc -w"
</code>```

I took a closer look to your scripts and it seems to me that you should start your server from the compiled files (which I guess they are in the lib folder). If it's true your script for running the server should be for example:

```<code>"dev": "ts-node-dev --no-notify lib/server.js"
</code>```

And you need to run in two separate terminal tabs:

npm run compile
```

<p>and</p>

<pre class="lang-sh prettyprint-override"><code>npm run dev
</code>```

Body:
I have built an application using FeathersJS in Typescript but althought the nodemon for typescript (ts-node-dev) says that the server has restarted when a typescript file is changed, the change is not applyed.
I always need to kill the application and start again to see the changes.

Here is the log:

[INFO] 15:43:51 Restarting: C:\api\src\models\favorites.model.ts has been modified
Using ts-node version 7.0.1, typescript version 3.9.3
info: Feathers application started on http://localhost:3030

Here is the dev script on package.json:

ts-node-dev --no-notify src/

Here is the tsconfig.json:

{
  "compilerOptions": {
    "target": "es2018",
    "module": "commonjs",
    "outDir": "./lib",
    "rootDir": "./src",
    "strict": true,
    "esModuleInterop": true
  },
  "exclude": [
    "test"
  ]
}

And here is the package.json:

{
  "homepage": "",
  "private": true,
  "main": "src",
  "keywords": [
    "feathers"
  ],
  "contributors": [],
  "bugs": {},
  "directories": {
    "lib": "src",
    "test": "test/",
    "config": "config/"
  },
  "engines": {
    "node": "^12.0.0",
    "npm": ">= 3.0.0"
  },
  "scripts": {
    "test": "npm run compile && npm run mocha",
    "dev": "ts-node-dev --no-notify src/",
    "start": "npm run compile && node lib/",
    "mocha": "ts-mocha \"test/**/*.ts\" --recursive --exit",
    "compile": "shx rm -rf lib/ && tsc"
  },
  "prettier":{
    "singleQuote": true
  },
  "standard": {
    "env": [
      "mocha"
    ],
    "ignore": []
  },
  "types": "lib/",
  "dependencies": {
    "@feathersjs/authentication": "^4.5.3",
    "@feathersjs/authentication-local": "^4.5.4",
    "@feathersjs/authentication-oauth": "^4.5.4",
    "@feathersjs/configuration": "^4.5.3",
    "@feathersjs/errors": "^4.5.3",
    "@feathersjs/express": "^4.5.4",
    "@feathersjs/feathers": "^4.5.3",
    "@feathersjs/transport-commons": "^4.5.3",
    "compression": "^1.7.4",
    "cors": "^2.8.5",
    "feathers-mongoose": "^8.3.0",
    "helmet": "^3.22.0",
    "mongodb-core": "^3.2.7",
    "mongoose": "^5.9.16",
    "serve-favicon": "^2.5.0",
    "winston": "^3.2.1"
  },
  "devDependencies": {
    "@types/compression": "^1.7.0",
    "@types/cors": "^2.8.6",
    "@types/helmet": "0.0.47",
    "@types/jsonwebtoken": "^8.5.0",
    "@types/mocha": "^7.0.2",
    "@types/mongoose": "^5.7.21",
    "@types/serve-favicon": "^2.5.0",
    "axios": "^0.19.2",
    "mocha": "^7.2.0",
    "nodemon": "^2.0.4",
    "shx": "^0.3.2",
    "ts-mocha": "^7.0.0",
    "ts-node-dev": "^1.0.0-pre.44",
    "tslint": "^6.1.2",
    "typescript": "^3.9.3"
  }
}

Body:
You need to tell the compiler to watch for changes. Add the following script or adjust your compile script with the watch flag:

"watch-ts": "tsc -w"

or

"compile": "shx rm -rf lib/ && tsc -w"

I took a closer look to your scripts and it seems to me that you should start your server from the compiled files (which I guess they are in the lib folder). If it's true your script for running the server should be for example:

"dev": "ts-node-dev --no-notify lib/server.js"

And you need to run in two separate terminal tabs:

npm run compile

and

npm run dev


问:
Is it possible to track memory usage in a C# application without using a profiler?
I'd like to write a simple application which keeps track of its current memory usage, number of created objects etc. In C++ I'd normally override the new operator, but for obvious reasons I can't do this in C#. Is there any way to do this without using a profiler?</p>

答:
Using WMI try :

To get process usage (W2K3/2K8) :

```<code>"SELECT IDProcess, PercentPrivilegedTime, PercentProcessorTime, PercentUserTime FROM Win32_PerfFormattedData_PerfProc_Process where Name='process_name.exe'"
</code>```

To identify your site use this :

```<code>"SELECT ProcessId, CommandLine, WorkingSetSize, ThreadCount, PrivatePageCount, PageFileUsage, PageFaults, HandleCount, CreationDate, Caption FROM Win32_Process where Caption='process_name.exe'"
</code>```

Use this tool for WQL teste

Or use PerfMon tool.

For more information about counters see Windows System Resource Manager Accounting, at the end of doc.

Good luck.

OwnerDisplayName: Trap

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Rich B

Body:
Using WMI try :

To get process usage (W2K3/2K8) :

"SELECT IDProcess, PercentPrivilegedTime, PercentProcessorTime, PercentUserTime FROM Win32_PerfFormattedData_PerfProc_Process where Name='process_name.exe'"

To identify your site use this :

"SELECT ProcessId, CommandLine, WorkingSetSize, ThreadCount, PrivatePageCount, PageFileUsage, PageFaults, HandleCount, CreationDate, Caption FROM Win32_Process where Caption='process_name.exe'"

Use this tool for WQL teste

Or use PerfMon tool.

For more information about counters see Windows System Resource Manager Accounting, at the end of doc.

Good luck.

OwnerDisplayName: lsalamon

LastEditorDisplayName: lsalamon


问:
Trouble with Eclipse Listener and getting the Source
In My Eclipse Project, I have a

```<code>Text custom_text = new Text(....);
</code>```

Now I add a listener -

custom_text.addKeyListener(new
  KeyListener(){

@Override  public void keyPressed(KeyEvent event) {

}

@Override   public void
  keyReleased(KeyEvent event) {
        System.err.println("event
  "+event.getSource()));

} });

Anyhow, I am not getting the source name,despite I am getting the output as Text {}.
Well I want to get the source name ie custom_text .

How to get the output in a listener as
  custom_text

答:
You can use event.widget to identify wich widget notify event.

But general approach is relaying with anonymous listener.
because it can use more readable method name which is more fit to subject of controller.

```<code>Text nameField, emailField = ...

nameField.addListener(SWT.KeyUp, new Listener(){
    public void handleEvent(Event e){
        handleNameEdited();
    }
});

emailField.addListener(SWT.KeyUp, new Listener(){
   public void handleEvent(Event e){
       handleEmailEdited();
   }
});
</code>```

ContentLicense: CC BY-SA 3.0

Body:
In My Eclipse Project, I have a

Text custom_text = new Text(....);

Now I add a listener -

custom_text.addKeyListener(new
  KeyListener(){

@Override  public void keyPressed(KeyEvent event) {

}

@Override   public void
  keyReleased(KeyEvent event) {
        System.err.println("event
  "+event.getSource()));

} });

Anyhow, I am not getting the source name,despite I am getting the output as Text {}.
Well I want to get the source name ie custom_text .

How to get the output in a listener as
  custom_text

Body:
You can use event.widget to identify wich widget notify event.

But general approach is relaying with anonymous listener.
because it can use more readable method name which is more fit to subject of controller.

Text nameField, emailField = ...

nameField.addListener(SWT.KeyUp, new Listener(){
    public void handleEvent(Event e){
        handleNameEdited();
    }
});

emailField.addListener(SWT.KeyUp, new Listener(){
   public void handleEvent(Event e){
       handleEmailEdited();
   }
});


问:
Unexpected non-equality after assignment
Given the following code:

using System;

class MyClass
{
    public MyClass x;
}

public static class Program
{
    public static void Main()
    {
        var a = new MyClass();
        var b = new MyClass();
        a.x = (a = b);
        Console.WriteLine(a.x == a);
    }
}
```

The first two lines are very obvious, just two different objects.

I assume the third line to do the following:

The part (a = b) assigns b to a and returns b, so now a equals b.

Then, a.x is assigned to b.

That means, a.x equals to b, and also b equals to a. Which implies that a.x equals to a.

However, the code prints False.

What's going on?

答:
Just to add some IL fun into the discussion:

The Main method header looks next way:

```<code>method private hidebysig static void
    Main() cil managed
  {
    .maxstack 3
    .locals init (
      [0] class MyClass a,
      [1] class MyClass b
    )
</code>```

The a.x = (a=b); statement is translated to the next IL:

```<code>IL_000d: ldloc.0      // a
IL_000e: ldloc.1      // b
IL_000f: dup
IL_0010: stloc.0      // a
IL_0011: stfld        class MyClass::x
</code>```

First two instructions load (ldloc.0, ldloc.1) onto evaluation stack references stored in a and b variables, lets call them aRef and bRef, so we have next evaluation stack state:

```<code>bRef
aRef
</code>```

The dup instruction copies the current topmost value on the evaluation stack, and then pushes the copy onto the evaluation stack:

```<code>bRef
bRef
aRef
</code>```

The stloc.0 pops the current value from the top of the evaluation stack and stores it in a the local variable list at index 0 (a variable is set to bRef), leaving stack in next state:

```<code>bRef
aRef
</code>```

And finally stfld poppes from the stack the value (bRef) and the object reference/pointer (aRef). The value of field in the object (aRef.x) is replaced with the supplied value (bRef).

Which all result in the behavior described in the post, with both variables (a and b) pointing to the bRef with bRef.x being null and aRef.x pointing to bRef, which can be checked with extra variable containing aRef as @Magnetron suggested.

Body:
Given the following code:

using System;

class MyClass
{
    public MyClass x;
}

public static class Program
{
    public static void Main()
    {
        var a = new MyClass();
        var b = new MyClass();
        a.x = (a = b);
        Console.WriteLine(a.x == a);
    }
}

The first two lines are very obvious, just two different objects.

I assume the third line to do the following:

The part (a = b) assigns b to a and returns b, so now a equals b.

Then, a.x is assigned to b.

That means, a.x equals to b, and also b equals to a. Which implies that a.x equals to a.

However, the code prints False.

What's going on?

Body:
Just to add some IL fun into the discussion:

The Main method header looks next way:

method private hidebysig static void
    Main() cil managed
  {
    .maxstack 3
    .locals init (
      [0] class MyClass a,
      [1] class MyClass b
    )

The a.x = (a=b); statement is translated to the next IL:

IL_000d: ldloc.0      // a
IL_000e: ldloc.1      // b
IL_000f: dup
IL_0010: stloc.0      // a
IL_0011: stfld        class MyClass::x

First two instructions load (ldloc.0, ldloc.1) onto evaluation stack references stored in a and b variables, lets call them aRef and bRef, so we have next evaluation stack state:

bRef
aRef

The dup instruction copies the current topmost value on the evaluation stack, and then pushes the copy onto the evaluation stack:

bRef
bRef
aRef

The stloc.0 pops the current value from the top of the evaluation stack and stores it in a the local variable list at index 0 (a variable is set to bRef), leaving stack in next state:

bRef
aRef

And finally stfld poppes from the stack the value (bRef) and the object reference/pointer (aRef). The value of field in the object (aRef.x) is replaced with the supplied value (bRef).

Which all result in the behavior described in the post, with both variables (a and b) pointing to the bRef with bRef.x being null and aRef.x pointing to bRef, which can be checked with extra variable containing aRef as @Magnetron suggested.


问:
Optimizing pixi grid viewport
I am using pixi.js to create an interactive grid. This grid is composed of PIXI Graphics rectangles. I am now creating a layout of 25000 rectangles and the browser is having a hard time to process it (code sandbox below)

This is my setup :

```<code>setup() {
                // making a 30 x 13 grid of tiles
                for (let i = 0; i < 25000; i++) {
                    let square = new PIXI.Graphics();
                    square.beginFill(0xF2F2F2);
                    square.drawRect(0, 0, 25, 25);
                    square.endFill();
                    // Opt-in to interactivity
                    square.interactive = true;
                    square.buttonMode = true;

                    square.on('pointerdown', this.onButtonDown);
                    // square.on('pointerover', this.onButtonOver);
                    // square.on('mouseout', this.onButtonOut);

                    square.x = (i % 30) * 32;
                    square.y = Math.floor(i / 30) * 32;
                    // add squares to stage
                    this.viewport.addChild(square);
                }
            }

</code>```

Is there a way to optimize this or have I maxed out Canvas capacities ?

https://codesandbox.io/s/zen-flower-5q09u?file=/src/App.vue

答:
I noticed 2 things that impact performance in the codesandbox you provided:

Vue - keeping PIXI and stage (with all those thousands of rectangles) as Vue data probably causes Vue to analyze all those objects on each frame.

The interactivity of each rectangle:

```<code>      // Opt-in to interactivity
      square.interactive = true;
      square.buttonMode = true;
</code>```

^ If you comment this out then you will notice that all works smoother. This is affecting performance because maybe plugin is creating some events listeners or something for each rectangle - so when its 25k of them then it is noticable.

Note: to see difference you need to save file in sandbox and reload page - reloading only the preview there doesnt seem to destroy the previous preview (so you will still see slowness).

Anyway, here is your code but without Vue and with commented out interactivity: https://codesandbox.io/s/pixi-demo-z97nz?file=/src/index.js:2002-2105 - but with 25000 rectangles instead of 1000 :)

About the interactivity: i think you should try to do it in different way: on click you should take the x and y of click and then calculate which rectangle was on that position. I mean something like that: https://www.html5gamedevs.com/topic/40609-detect-click-in-children-container/

For further possible optimization try reading about "batch rendering" (for example: https://medium.com/swlh/inside-pixijs-batch-rendering-system-fad1b466c420 )

Title: Optimizing pixi grid viewport

Body:
I am using pixi.js to create an interactive grid. This grid is composed of PIXI Graphics rectangles. I am now creating a layout of 25000 rectangles and the browser is having a hard time to process it (code sandbox below)

This is my setup :

setup() {
                // making a 30 x 13 grid of tiles
                for (let i = 0; i < 25000; i++) {
                    let square = new PIXI.Graphics();
                    square.beginFill(0xF2F2F2);
                    square.drawRect(0, 0, 25, 25);
                    square.endFill();
                    // Opt-in to interactivity
                    square.interactive = true;
                    square.buttonMode = true;

                    square.on('pointerdown', this.onButtonDown);
                    // square.on('pointerover', this.onButtonOver);
                    // square.on('mouseout', this.onButtonOut);

                    square.x = (i % 30) * 32;
                    square.y = Math.floor(i / 30) * 32;
                    // add squares to stage
                    this.viewport.addChild(square);
                }
            }

Is there a way to optimize this or have I maxed out Canvas capacities ?

https://codesandbox.io/s/zen-flower-5q09u?file=/src/App.vue

Body:
I noticed 2 things that impact performance in the codesandbox you provided:

Vue - keeping PIXI and stage (with all those thousands of rectangles) as Vue data probably causes Vue to analyze all those objects on each frame.

The interactivity of each rectangle:

      // Opt-in to interactivity
      square.interactive = true;
      square.buttonMode = true;

^ If you comment this out then you will notice that all works smoother. This is affecting performance because maybe plugin is creating some events listeners or something for each rectangle - so when its 25k of them then it is noticable.

Note: to see difference you need to save file in sandbox and reload page - reloading only the preview there doesnt seem to destroy the previous preview (so you will still see slowness).

Anyway, here is your code but without Vue and with commented out interactivity: https://codesandbox.io/s/pixi-demo-z97nz?file=/src/index.js:2002-2105 - but with 25000 rectangles instead of 1000 :)

About the interactivity: i think you should try to do it in different way: on click you should take the x and y of click and then calculate which rectangle was on that position. I mean something like that: https://www.html5gamedevs.com/topic/40609-detect-click-in-children-container/

For further possible optimization try reading about "batch rendering" (for example: https://medium.com/swlh/inside-pixijs-batch-rendering-system-fad1b466c420 )


问:
NestJS - Cannot inject a service into a subscriber
I have a subscriber for NestJS to listen to any create, update or delete events (TypeORM). When one of these events is fired, I'd like to use an injected service in order to create a new revision entry.

However, it seems I cannot get the dependency loaded inside of the subscriber and the service comes back as being undefined

Key files:

EntityModificationSubscriber (Subscriber)

RevisionEntity (Entity)

app.module.ts

```<code>@Module({
  imports: [
      HttpModule,
      TypeOrmModule.forRoot({
          type: (process.env.DB_TYPE as any) || 'postgres',
          host: process.env.DB_HOST || '127.0.0.1',
          port: (process.env.DB_PORT as any) || 5432,
          username: process.env.DB_USER || 'root',
          password: process.env.DB_PASS || '',
          database: process.env.DB_NAME || 'test',
          entities: [join(__dirname, '**/**.entity{.ts,.js}')],
          synchronize: true,
          logging: 'all',
          logger: 'advanced-console',
          subscribers: [EntityModificationSubscriber],
      }),
      TypeOrmModule.forFeature([
          RevisionEntity,
      ]),
      TerminusModule.forRootAsync({
          // Inject the TypeOrmHealthIndicator provided by nestjs/terminus
          inject: [TypeOrmHealthIndicator, MicroserviceHealthIndicator],
          useFactory: (db, msg) => getTerminusOptions(db, msg),
      }),
      GraphQLModule.forRoot({
          debug: true,
          playground: true,
          typePaths: ['./**/*.graphql'],
      }),
  ],
  controllers: [AppController],
  providers: [
      RevisionService,
      EntityModificationSubscriber,
  ],
})
</code>```

entity_modification_subscriber.ts

```<code>import {EntitySubscriberInterface, EventSubscriber, InsertEvent, RemoveEvent, UpdateEvent} from 'typeorm';
import {RevisionEntity, RevisonEntityStatus} from '../entities/revison.entity';
import {RevisionService} from '../services/revisions.service';
import {Injectable} from '@nestjs/common';

@Injectable()
@EventSubscriber()
export class EntityModificationSubscriber implements EntitySubscriberInterface {

    constructor(private revisionService: RevisionService) {
    }

    // tslint:disable-next-line:no-empty
    afterInsert(event: InsertEvent<any>): Promise<any> | void {
        const revision = new RevisionEntity();

        revision.action = RevisonEntityStatus.Created;
    }

    afterUpdate(event: UpdateEvent<any>): Promise<any> | void {
    }

    // tslint:disable-next-line:no-empty
    afterRemove(event: RemoveEvent<any>) {
        // this.revisionService.createRevisionEntry(revision);
    }
}
</code>```

答:
The only way I found to inject a dependency into a subscriber using NestJS, was not to register that subscriber in the TypeORM configuration. I subscribe it manually into the TypeORM connection on subscriber's constructor.

import { EntitySubscriberInterface, EventSubscriber, InsertEvent, RemoveEvent, UpdateEvent, Connection } from 'typeorm';
    import { RevisionEntity, RevisonEntityStatus } from '../entities/revison.entity';
    import { RevisionService } from '../services/revisions.service';
    import { Injectable } from '@nestjs/common';

    @Injectable()
    @EventSubscriber()
    export class EntityModificationSubscriber implements EntitySubscriberInterface {

        constructor(private readonly connection: Connection, private readonly revisionService: RevisionService) {
            connection.subscribers.push(this); // <---- THIS
        }

        // tslint:disable-next-line:no-empty
        afterInsert(event: InsertEvent<any>): Promise<any> | void {
            const revision = new RevisionEntity();

            revision.action = RevisonEntityStatus.Created;

            //this.revisionService <- should be working!
        }

        afterUpdate(event: UpdateEvent<any>): Promise<any> | void {
        }

        // tslint:disable-next-line:no-empty
        afterRemove(event: RemoveEvent<any>) {
            // this.revisionService.createRevisionEntry(revision);
        }
    }
```

<p>Then in your app.module on the TypeORM module configuration (TypeOrmModule.forRoot).
<strong>Remove the line</strong>:</p>

```subscribers: [EntityModificationSubscriber],
```

It solved to me, hope it help others.
You can find discussions about that in some NestJS issues/pull requests.

https://github.com/nestjs/typeorm/issues/85

https://github.com/nestjs/typeorm/pull/27

Body:
I have a subscriber for NestJS to listen to any create, update or delete events (TypeORM). When one of these events is fired, I'd like to use an injected service in order to create a new revision entry.

However, it seems I cannot get the dependency loaded inside of the subscriber and the service comes back as being undefined

Key files:

EntityModificationSubscriber (Subscriber)

RevisionEntity (Entity)

app.module.ts

@Module({
  imports: [
      HttpModule,
      TypeOrmModule.forRoot({
          type: (process.env.DB_TYPE as any) || 'postgres',
          host: process.env.DB_HOST || '127.0.0.1',
          port: (process.env.DB_PORT as any) || 5432,
          username: process.env.DB_USER || 'root',
          password: process.env.DB_PASS || '',
          database: process.env.DB_NAME || 'test',
          entities: [join(__dirname, '**/**.entity{.ts,.js}')],
          synchronize: true,
          logging: 'all',
          logger: 'advanced-console',
          subscribers: [EntityModificationSubscriber],
      }),
      TypeOrmModule.forFeature([
          RevisionEntity,
      ]),
      TerminusModule.forRootAsync({
          // Inject the TypeOrmHealthIndicator provided by nestjs/terminus
          inject: [TypeOrmHealthIndicator, MicroserviceHealthIndicator],
          useFactory: (db, msg) => getTerminusOptions(db, msg),
      }),
      GraphQLModule.forRoot({
          debug: true,
          playground: true,
          typePaths: ['./**/*.graphql'],
      }),
  ],
  controllers: [AppController],
  providers: [
      RevisionService,
      EntityModificationSubscriber,
  ],
})

entity_modification_subscriber.ts

import {EntitySubscriberInterface, EventSubscriber, InsertEvent, RemoveEvent, UpdateEvent} from 'typeorm';
import {RevisionEntity, RevisonEntityStatus} from '../entities/revison.entity';
import {RevisionService} from '../services/revisions.service';
import {Injectable} from '@nestjs/common';

@Injectable()
@EventSubscriber()
export class EntityModificationSubscriber implements EntitySubscriberInterface {

    constructor(private revisionService: RevisionService) {
    }

    // tslint:disable-next-line:no-empty
    afterInsert(event: InsertEvent<any>): Promise<any> | void {
        const revision = new RevisionEntity();

        revision.action = RevisonEntityStatus.Created;
    }

    afterUpdate(event: UpdateEvent<any>): Promise<any> | void {
    }

    // tslint:disable-next-line:no-empty
    afterRemove(event: RemoveEvent<any>) {
        // this.revisionService.createRevisionEntry(revision);
    }
}

Body:
The only way I found to inject a dependency into a subscriber using NestJS, was not to register that subscriber in the TypeORM configuration. I subscribe it manually into the TypeORM connection on subscriber's constructor.

import { EntitySubscriberInterface, EventSubscriber, InsertEvent, RemoveEvent, UpdateEvent, Connection } from 'typeorm';
    import { RevisionEntity, RevisonEntityStatus } from '../entities/revison.entity';
    import { RevisionService } from '../services/revisions.service';
    import { Injectable } from '@nestjs/common';

    @Injectable()
    @EventSubscriber()
    export class EntityModificationSubscriber implements EntitySubscriberInterface {

        constructor(private readonly connection: Connection, private readonly revisionService: RevisionService) {
            connection.subscribers.push(this); // <---- THIS
        }

        // tslint:disable-next-line:no-empty
        afterInsert(event: InsertEvent<any>): Promise<any> | void {
            const revision = new RevisionEntity();

            revision.action = RevisonEntityStatus.Created;

            //this.revisionService <- should be working!
        }

        afterUpdate(event: UpdateEvent<any>): Promise<any> | void {
        }

        // tslint:disable-next-line:no-empty
        afterRemove(event: RemoveEvent<any>) {
            // this.revisionService.createRevisionEntry(revision);
        }
    }

Then in your app.module on the TypeORM module configuration (TypeOrmModule.forRoot).
Remove the line:

subscribers: [EntityModificationSubscriber],

It solved to me, hope it help others.
You can find discussions about that in some NestJS issues/pull requests.

https://github.com/nestjs/typeorm/issues/85

https://github.com/nestjs/typeorm/pull/27


问:
Problems making map collision using the hex of a mask image in Java
I was making a game and I came up with the idea of using hex color codes to make collisions with objects on the map using a png image as a mask. For this to work, the code would scan every pixel of this mask and, if a pixel had a specific color, an invisible block would spawn at its location. However, since the image I'm using as a mask is pretty large (1582 x 1146), the code uses way too much cpu power (I think it's the cpu, not so sure) to scan every single pixel and the game runs literally at 1 FPS.

public class World {
    private Tile[] tiles;
    private static int WIDTH = 1582, HEIGHT = 1146;

    public World(String path) {
        try {
            BufferedImage map = ImageIO.read(getClass().getResource(path));
            int[] pixels = new int[map.getWidth() * map.getHeight()];
            tiles = new Tile[map.getWidth() * map.getHeight()];
            map.getRGB(0, 0, map.getWidth(), map.getHeight(), pixels, 0, map.getWidth());
            for (int xx = 0; xx < map.getWidth(); xx++) {
                for (int yy = 0; yy < map.getHeight(); yy++) {
                    int pixelAtual = pixels[xx + (yy * map.getWidth())];
                    if (pixelAtual == 0xfffcff00) //Pixel's hex verification
                    {
                        tiles[xx + (yy * WIDTH)] = new TileWall(xx, yy, Tile.TILE_WALL); //Invisible tile wall
                    }
                    /*else if (pixelAtual == )  Adding another tile
                        tiles[xx + (yy * WIDTH)] = new  TileWall(xx, yy, Tile.TILE_WALL);
                    } */
                    else {
                        tiles[xx + (yy * WIDTH)] = new TileFloor(xx, yy, Tile.TILE_FLOOR); //Invisible tile floor, just to complete the array
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void render(Graphics g) {
        for (int xx = 0; xx < WIDTH; xx++) {
            for (int yy = 0; yy < HEIGHT; yy++) {
                Tile tile = tiles[xx + (yy * WIDTH)];
                tile.render(g);
            }
        }
    }
}
```

I thought this method of hex scanning would be easy to write and practical to use. Is there any other way to add collisions to the game?

答:
Minor note: There's https://gamedev.stackexchange.com/ , which you may find a useful resource for these types of questions.

Collision detection can be a challenging and indeed also computationally challenging topic, consuming lots of runtime and memory. However, it can also be fairly straight-forward. It depends on your requirements and game design. It can often be useful to change the game design to make collision detection easier to implement, though this is of course a trade-off relative to what kind of interesting, fun or profitable games you seek to make.

The way you describe sound a bit like raster-based collision detection, where an area defined by pixels (if in 3D, it would be a volume defined by voxels) is used for collision detection. A more common approach is to instead do collision detection by using geometric approaches - a rectangle as defined by 4 points, a circle by a center and a radius, a polygon, etc. These can often give good results and be sufficient for one's needs, and they typically permit decently fast collision detection, though they can be a bit more difficult to implement. That said, there are articles and learning resources available in different places reg. such algorithms, so using collision detection based on geometric shapes should still be fairly accessible.

A rectangle-based collision detection is very easy to implement. A circle-based one is still fairly easy. A convex-polygon-based one is more complex, but there are resources for it, such as the links in this answer: 2D Polygon Collision Detection .

There might also be libraries for collision detection, which may well be a good approach as well. Game engines and game libraries often provide these. Search online for one, and if you are using a game engine, there may be components or plugins for such things available.

As a side-note, there are some game engines and libraries that support raster-based collision detection, such as GameMaker. But since it (as in your example) can be very or extremely slow, one has to be careful with it.

Reg. the loop, it does make sense that it can be slow: In the worst case, it might have to iterate through all pixels. 1582 x 1146 gives for the worst-case 1812972. Assuming you do not create objects and instead just let it be represented by an array with a boolean or similar, this might then be run multiple times (for each time you would check collisions) in a frame, and a frame may then be executed multiple times a second. This all multiplies up to a large burden every second. There are various ways to optimize such things, and for a real-time game, keeping the time spent each frame down can be important and a challenge. Though again, changing the game design and requirements to something less intensive can be useful (which again is a trade-off).

As a final note, you use objects to represent a single pixel if I understand your code correctly. In case you are new to object-oriented programming, you may have been led to believe that objects are generally good for modelling your domain directly. That is a very common beginner belief (also common in various teaching materials), but it does not hold in general. For real-time games, performance often matters, and using objects in different ways rather than using them to directly model the domain can be a good idea, since certain usages of objects can have considerable runtime overhead. For other cases, other concerns may come into play. For instance, you may have been taught that a class can be used to describe an Animal type, and sub-types could then be Dog and Cat. This is a very direct modelling (and easy for teaching). However, in practice, describing all kinds of animals with a single data class might be more suitable, for instance if you want to describe lots and lots and lots of animals and they don't have varying functionality, only attributes. If you tried to describe all these animals using sub-types like some teaching material might suggest, you might end up with a very large number of sub-types, with minor variance between them, with the very many classes costing more than they benefit you reg. development relative to just having a single data class. I hope this last part is clear, though I am uncertain how clear I made it.

Body:
I was making a game and I came up with the idea of using hex color codes to make collisions with objects on the map using a png image as a mask. For this to work, the code would scan every pixel of this mask and, if a pixel had a specific color, an invisible block would spawn at its location. However, since the image I'm using as a mask is pretty large (1582 x 1146), the code uses way too much cpu power (I think it's the cpu, not so sure) to scan every single pixel and the game runs literally at 1 FPS.

public class World {
    private Tile[] tiles;
    private static int WIDTH = 1582, HEIGHT = 1146;

    public World(String path) {
        try {
            BufferedImage map = ImageIO.read(getClass().getResource(path));
            int[] pixels = new int[map.getWidth() * map.getHeight()];
            tiles = new Tile[map.getWidth() * map.getHeight()];
            map.getRGB(0, 0, map.getWidth(), map.getHeight(), pixels, 0, map.getWidth());
            for (int xx = 0; xx < map.getWidth(); xx++) {
                for (int yy = 0; yy < map.getHeight(); yy++) {
                    int pixelAtual = pixels[xx + (yy * map.getWidth())];
                    if (pixelAtual == 0xfffcff00) //Pixel's hex verification
                    {
                        tiles[xx + (yy * WIDTH)] = new TileWall(xx, yy, Tile.TILE_WALL); //Invisible tile wall
                    }
                    /*else if (pixelAtual == )  Adding another tile
                        tiles[xx + (yy * WIDTH)] = new  TileWall(xx, yy, Tile.TILE_WALL);
                    } */
                    else {
                        tiles[xx + (yy * WIDTH)] = new TileFloor(xx, yy, Tile.TILE_FLOOR); //Invisible tile floor, just to complete the array
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void render(Graphics g) {
        for (int xx = 0; xx < WIDTH; xx++) {
            for (int yy = 0; yy < HEIGHT; yy++) {
                Tile tile = tiles[xx + (yy * WIDTH)];
                tile.render(g);
            }
        }
    }
}

I thought this method of hex scanning would be easy to write and practical to use. Is there any other way to add collisions to the game?


问:
Can I have 100s of thousands of topics in a Kafka Cluster?
I have a data flow use case where I want to have topics defined based on each of the customer repositories (which might be in the order of 100,000s) Each data flow would be a topic with partitions (in the order of a few 10s) defining the different stages of the flow.

Is Kafka good for a scenario like this? If not how would I remodel my use case to handle such scenarios. Also it is the case that each customer repository data cannot be mingled with others even during processing.

答: Consider that Kafka is a compelling choice within the network but it was not designed to effectively and efficiently (but yes quickly) distribute data to hundreds of thousands of consumers over the last mile - via sometimes congested and unreliable web mobile and satellite networks.  Inserting a or alternatively  using  a real time API management platform allows the same data aggregation but is also purpose-built to maximize efficient, selective, and highly  scalable data distribution outside the corporate network. A real-time api management solution handles the challenges of these networks and manages hundreds of thousand of discrete topics required with ease and without massive amounts of added infrastructure.</p>


问:
React Native What Design Pattern should I be using for this calling API then updating other components?
Let's say I do an api fetching in the componentDidMount() in the App.js to get data for other components, for instance the data could be a List. If I navigate to another component, and there is new data present for the list - how would I update this list so that it affects the other components, and if I'm at one of the other components how would I Re-render() the UI for that component?

How would the App.js do the API calls since I'm no longer in that activity (currently in the other component)?

I am not too sure what relevant libraries or patterns I should be using? Should I be using a singleton if I want all components to have access to this List?

答:
You can use a State Management Tool (eg. Redux, MobX).

Using this tool, the state of your application is kept in a store, and each component can access any state that it needs from this store.

The way Redux works is simple. There is a central store that holds the entire state of the application. Each component can access the stored state without having to send down props from one component to another.


问:
JQuery Attr is not function
I try to add attribute of option by using JQuery. I run this code.

```<code> $("option[value='430']").attr("selected","selected");
</code>```

It return TypeError: $(...).attr is not a function(…)

I cannot saw my error. Where is the problem?

Thanks.

答:
in jQuery 1.4.1 you can use the .setAttribute method, for example:</p>

```<code>$("option[value='430']").setAttribute('selected','selected');
</code>```

Title: JQuery Attr is not function

Body:
I try to add attribute of option by using JQuery. I run this code.

 $("option[value='430']").attr("selected","selected");

It return TypeError: $(...).attr is not a function(…)

I cannot saw my error. Where is the problem?

Thanks.

Body:
in jQuery 1.4.1 you can use the .setAttribute method, for example:

$("option[value='430']").setAttribute('selected','selected');


问:
Iterate over three lists simultaneously in R
I would like to ask how to iterate over three lists simultaneously in R.  Actually the same function as purr::walk2 does for two lists, but for three or more lists. I suppose that function I should use is purr::pwalk but not sure.

So I have 3 lists (same length):

```<code>buffers_points_with_data <-
  list.files(
    path = "data/buffers_points_with_data",
    pattern = "*.csv$",
    full.names = TRUE,
    recursive = FALSE
  )

species_data_CZ_moved <-
  list.files(
    path = "data/species_data_CZ_moved",
    pattern = "*.txt$",
    full.names = TRUE,
    recursive = FALSE
  )

species_data_GBIF_moved <-
  list.files(
    path = "data/species_data_GBIF_moved",
    pattern = "*.txt$",
    full.names = TRUE,
    recursive = FALSE
  )
</code>```

And want to run:
Read first chr from list buffers_points_with_data, then first chr from second list, first chr from third list, continue to the end of script and start with second chr for each and so on.

```<code>{
    clim <- read.csv("data/buffers_points_with_data/Acer negundo.csv", header = TRUE, sep = ",") #replace by 1st list
    occ.sp1 <- na.exclude(read.table("data/species_data_CZ_moved/Acer negundo.txt", h = TRUE)) #replace by 2nd list
    occ.sp2 <- na.exclude(read.table("data/species_data_GBIF_moved/Acer negundo.txt", h = TRUE)) #replace by 3rd list
#code continues
}
</code>```

I am pretty new to R and programming so I do apologies if this question has been asked elsewhere or  the text is somewhat confusing.

Any help or suggestions would be great.
Thank You.

答:
We can use map from purrr

```<code>library(dplyr)
library(purrr)
list(buffers_points_with_data , species_data_CZ_moved , species_data_GBIF_moved) %>%
        map(~ map(.x, read.csv, header = TRUE))
</code>```

Body:
I would like to ask how to iterate over three lists simultaneously in R.  Actually the same function as purr::walk2 does for two lists, but for three or more lists. I suppose that function I should use is purr::pwalk but not sure.

So I have 3 lists (same length):

buffers_points_with_data <-
  list.files(
    path = "data/buffers_points_with_data",
    pattern = "*.csv$",
    full.names = TRUE,
    recursive = FALSE
  )

species_data_CZ_moved <-
  list.files(
    path = "data/species_data_CZ_moved",
    pattern = "*.txt$",
    full.names = TRUE,
    recursive = FALSE
  )

species_data_GBIF_moved <-
  list.files(
    path = "data/species_data_GBIF_moved",
    pattern = "*.txt$",
    full.names = TRUE,
    recursive = FALSE
  )

And want to run:
Read first chr from list buffers_points_with_data, then first chr from second list, first chr from third list, continue to the end of script and start with second chr for each and so on.

{
    clim <- read.csv("data/buffers_points_with_data/Acer negundo.csv", header = TRUE, sep = ",") #replace by 1st list
    occ.sp1 <- na.exclude(read.table("data/species_data_CZ_moved/Acer negundo.txt", h = TRUE)) #replace by 2nd list
    occ.sp2 <- na.exclude(read.table("data/species_data_GBIF_moved/Acer negundo.txt", h = TRUE)) #replace by 3rd list
#code continues
}

I am pretty new to R and programming so I do apologies if this question has been asked elsewhere or  the text is somewhat confusing.

Any help or suggestions would be great.
Thank You.

Body:
We can use map from purrr

library(dplyr)
library(purrr)
list(buffers_points_with_data , species_data_CZ_moved , species_data_GBIF_moved) %>%
        map(~ map(.x, read.csv, header = TRUE))


问:
Replace & symbol and combine surrounding strings
I'm doing some string cleaning on business names, and I would like to do two things:

Replace the ampersand symbol (&) with 'and'.

Combine the strings surrounding the &, but only those elements, not the entire string

Here is what I've tried to far but the output is not vectorised for some reason.

library(stringr)
library(dplyr)
test <- tibble(name = c("brady & frank mortgage bank", "joe and sons deli"))
new <- test %>%
  mutate(clean = paste(str_split(name, "\\s+")[[1]][grep("&|and", str_split(name, "\\s+")[[1]]) - 1],
                       str_split(name, "\\s+")[[1]][grep("&|and", str_split(name, "\\s+")[[1]]) + 1], sep = "and"))
```

<p>Here is the output of that:  </p>

```  |name                        |clean         |
  |:---------------------------|:-------------|
  |brady & frank mortgage bank |bradyandfrank |
  |joe and sons deli           |bradyandfrank |
```

<p>I know somehow that the <code>clean</code> var is referencing the first element but I'm not sure why it's not vectorised. </p>

<p>Here is my desired output:</p>

```  |name                        |clean         |
  |:---------------------------|:-------------|
  |brady & frank mortgage bank |bradyandfrank |
  |joe and sons deli           |joeandsons    |
```

Thanks!

答:
The problem here is that str_split returns a list with an entry for every string, and with str_split(name, "\\s+")[[1]] you always reference the entry for the first string. Therefore you have to map your function to every entry of the list. You could do this with lapply or the a map function from the purrr package:

```<code>new <- test %>%
  mutate(clean = purrr::map_chr(name, function(x) {
    paste(str_split(x, "\\s+")[[1]][grep("&|and", str_split(x, "\\s+")[[1]]) - 1],
          str_split(x, "\\s+")[[1]][grep("&|and", str_split(x, "\\s+")[[1]]) + 1], sep = "and")
  }))

> new
# A tibble: 2 x 2
  name                        clean
  <chr>                       <chr>
1 brady & frank mortgage bank bradyandfrank
2 joe and sons deli           joeandsons
</code>```

Body:
I'm doing some string cleaning on business names, and I would like to do two things:

Replace the ampersand symbol (&) with 'and'.

Combine the strings surrounding the &, but only those elements, not the entire string

Here is what I've tried to far but the output is not vectorised for some reason.

library(stringr)
library(dplyr)
test <- tibble(name = c("brady & frank mortgage bank", "joe and sons deli"))
new <- test %>%
  mutate(clean = paste(str_split(name, "\\s+")[[1]][grep("&|and", str_split(name, "\\s+")[[1]]) - 1],
                       str_split(name, "\\s+")[[1]][grep("&|and", str_split(name, "\\s+")[[1]]) + 1], sep = "and"))

Here is the output of that:

  |name                        |clean         |
  |:---------------------------|:-------------|
  |brady & frank mortgage bank |bradyandfrank |
  |joe and sons deli           |bradyandfrank |

I know somehow that the clean var is referencing the first element but I'm not sure why it's not vectorised.

Here is my desired output:

  |name                        |clean         |
  |:---------------------------|:-------------|
  |brady & frank mortgage bank |bradyandfrank |
  |joe and sons deli           |joeandsons    |

Thanks!

Body:
The problem here is that str_split returns a list with an entry for every string, and with str_split(name, "\\s+")[[1]] you always reference the entry for the first string. Therefore you have to map your function to every entry of the list. You could do this with lapply or the a map function from the purrr package:

new <- test %>%
  mutate(clean = purrr::map_chr(name, function(x) {
    paste(str_split(x, "\\s+")[[1]][grep("&|and", str_split(x, "\\s+")[[1]]) - 1],
          str_split(x, "\\s+")[[1]][grep("&|and", str_split(x, "\\s+")[[1]]) + 1], sep = "and")
  }))

> new
# A tibble: 2 x 2
  name                        clean
  <chr>                       <chr>
1 brady & frank mortgage bank bradyandfrank
2 joe and sons deli           joeandsons


问:
Java WeakReference GC finalized , not finalized?
I thought WeakReference refer object will be finalized after System.gc() called, but I'm wrong.

Here are two test cases, the only difference is WeakReference constructor, the first one new an object while the second one use a referer, and they have different performance, I don't konw why...

Weak reference objects, which do not prevent their referents from being
made finalizable, finalized, and then reclaimed.  Weak references are most
often used to implement canonicalizing mappings.

 Suppose that the garbage collector determines at a certain point in time
that an object is weakly
reachable.  At that time it will atomically clear all weak references to
that object and all weak references to any other weakly-reachable objects
from which that object is reachable through a chain of strong and soft
references.  At the same time it will declare all of the formerly
weakly-reachable objects to be finalizable.  At the same time or at some
later time it will enqueue those newly-cleared weak references that are
registered with reference queues.

```<code>package com.zeng.javaReference;

import org.junit.Test;

import java.lang.ref.WeakReference;

/**
 * @author zeng
 * @version 1.0.0
 * @date 2020-05-11
 */
public class WeakReferenceTest {

    @Test
    public void weakRefRemoved() {
        WeakReference<Apple> weakReference = new WeakReference<>(new Apple("green-apple"));

        System.gc();

        if (weakReference.get() == null) {
            System.out.println("GC remove weakReference!");
        } else {
            System.out.println("weakReference still alive");
        }
    }

    @Test
    public void weakRefNotRemoved() {
        Apple apple = new Apple("green-apple");
        WeakReference<Apple> weakReference = new WeakReference<>(apple);

        System.gc();

        if (weakReference.get() == null) {
            System.out.println("GC remove weakReference!");
        } else {
            System.out.println("weakReference still alive");
        }
    }

    public static class Apple {

        private String name;

        public Apple(String name) {
            this.name = name;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        @Override
        protected void finalize() throws Throwable {
            super.finalize();
            System.out.println("Apple： " + name + " finalized。");
        }

        @Override
        public String toString() {
            return "Apple{" +
                    "name='" + name + '\'' +
                    '}' + ", hashCode:" + this.hashCode();
        }
    }

}

</code>```

答:
This is rather interesting indeed.

Assuming you use a GC collector that actually does something when calling System.gc(), like G1 let's say and you did not disable explicit invocation to GC via -XX:+DisableExplicitGC, there is an explanation to this, somehow.

The weakRefNotRemoved in theory should work the same as weakRefRemoved. This has to do with scope and reachability, more details about this here.

The point is that in weakRefNotRemoved, apple reference after the invocation System.gc() is not used by anyone, so at that point in time it is un-reacheable. So, in theory, a GC can reclaim that, but for whatever reason it will not. I can only assume that this special path is only triggered when there is real memory pressure.

To prove a point, we can change that code slightly, to:

```<code> public static void weakRefNotRemoved() {
    Apple apple = new Apple("green-apple");
    WeakReference<Apple> weakReference = new WeakReference<>(apple);

    // explicitly set to null
    apple = null;
    System.gc();

    if (weakReference.get() == null) {
        System.out.println("GC remove weakReference!");
    } else {
        System.out.println("weakReference still alive");
    }
}
</code>```

And now, GC will indeed clean it. In general, if you try to prove a point, it would be better to call that under a while loop because there are no guarantees about the cycle that will "catch" that reference. Also because the clearing happens in an  asynchronous fashion.  Something like:

```<code> public static void weakRefNotRemoved() {
    Apple apple = new Apple("green-apple");
    WeakReference<Apple> weakReference = new WeakReference<>(apple);

    apple = null;
    while (weakReference.get() != null) {
        System.out.println("weakReference still alive");
        System.gc();
        LockSupport.parkNanos(TimeUnit.SECONDS.toNanos(1));
    }

    System.out.println("GC remove weakReference!");

}
</code>```

And it's perfectly legal to get such an output, for example:

```<code>weakReference still alive  // zero or more of these messages
GC remove weakReference!
</code>```

Body:
I thought WeakReference refer object will be finalized after System.gc() called, but I'm wrong.

Here are two test cases, the only difference is WeakReference constructor, the first one new an object while the second one use a referer, and they have different performance, I don't konw why...

Weak reference objects, which do not prevent their referents from being
made finalizable, finalized, and then reclaimed.  Weak references are most
often used to implement canonicalizing mappings.

 Suppose that the garbage collector determines at a certain point in time
that an object is weakly
reachable.  At that time it will atomically clear all weak references to
that object and all weak references to any other weakly-reachable objects
from which that object is reachable through a chain of strong and soft
references.  At the same time it will declare all of the formerly
weakly-reachable objects to be finalizable.  At the same time or at some
later time it will enqueue those newly-cleared weak references that are
registered with reference queues.

package com.zeng.javaReference;

import org.junit.Test;

import java.lang.ref.WeakReference;

/**
 * @author zeng
 * @version 1.0.0
 * @date 2020-05-11
 */
public class WeakReferenceTest {

    @Test
    public void weakRefRemoved() {
        WeakReference<Apple> weakReference = new WeakReference<>(new Apple("green-apple"));

        System.gc();

        if (weakReference.get() == null) {
            System.out.println("GC remove weakReference!");
        } else {
            System.out.println("weakReference still alive");
        }
    }

    @Test
    public void weakRefNotRemoved() {
        Apple apple = new Apple("green-apple");
        WeakReference<Apple> weakReference = new WeakReference<>(apple);

        System.gc();

        if (weakReference.get() == null) {
            System.out.println("GC remove weakReference!");
        } else {
            System.out.println("weakReference still alive");
        }
    }

    public static class Apple {

        private String name;

        public Apple(String name) {
            this.name = name;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        @Override
        protected void finalize() throws Throwable {
            super.finalize();
            System.out.println("Apple： " + name + " finalized。");
        }

        @Override
        public String toString() {
            return "Apple{" +
                    "name='" + name + '\'' +
                    '}' + ", hashCode:" + this.hashCode();
        }
    }

}

Body:
This is rather interesting indeed.

Assuming you use a GC collector that actually does something when calling System.gc(), like G1 let's say and you did not disable explicit invocation to GC via -XX:+DisableExplicitGC, there is an explanation to this, somehow.

The weakRefNotRemoved in theory should work the same as weakRefRemoved. This has to do with scope and reachability, more details about this here.

The point is that in weakRefNotRemoved, apple reference after the invocation System.gc() is not used by anyone, so at that point in time it is un-reacheable. So, in theory, a GC can reclaim that, but for whatever reason it will not. I can only assume that this special path is only triggered when there is real memory pressure.

To prove a point, we can change that code slightly, to:

 public static void weakRefNotRemoved() {
    Apple apple = new Apple("green-apple");
    WeakReference<Apple> weakReference = new WeakReference<>(apple);

    // explicitly set to null
    apple = null;
    System.gc();

    if (weakReference.get() == null) {
        System.out.println("GC remove weakReference!");
    } else {
        System.out.println("weakReference still alive");
    }
}

And now, GC will indeed clean it. In general, if you try to prove a point, it would be better to call that under a while loop because there are no guarantees about the cycle that will "catch" that reference. Also because the clearing happens in an  asynchronous fashion.  Something like:

 public static void weakRefNotRemoved() {
    Apple apple = new Apple("green-apple");
    WeakReference<Apple> weakReference = new WeakReference<>(apple);

    apple = null;
    while (weakReference.get() != null) {
        System.out.println("weakReference still alive");
        System.gc();
        LockSupport.parkNanos(TimeUnit.SECONDS.toNanos(1));
    }

    System.out.println("GC remove weakReference!");

}

And it's perfectly legal to get such an output, for example:

weakReference still alive  // zero or more of these messages
GC remove weakReference!


问:
looking for Windows RAM-based shared memory solution in C++
I'm facing a situation where I need to pass up to several hundreds of megabytes of memory from one process to another. Right now I'm doing it via files and it's too slow.
I guess that to make it quicker, those files should be written directly to RAM and be accessible from another process. No fancy synchronization required. One process would create  shared memory objects and would fill them with data. The other process would read and remove them. However I've done a quick research and it seems like you can't share memory in RAM in Windows - the shared memory is backed by either a file or paging file. The docs of boost::interprocess confirm this. Where is the speed up then if the shared memory implementation still uses disk? Is there any C++ library that uses RAM-based shared memory?

EDIT: I made some further reading:
1. from boost::interprocess docs:
"as the operating system has to synchronize the file contents with the memory contents, memory-mapped files are not as fast as shared memory. "
2. from http://msdn.microsoft.com/en-us/library/ms810613.aspx:
"A memory-mapped file can also be mapped by more than one application simultaneously. This represents the only mechanism for two or more processes to directly share data in Windows NT."

答:
As far as I know you have essentially 2 Options here.

1)You create a DLL and use the data_seg pragma and load the DLL in both of your processes. This has HUGE drawbacks which are explained in detail here:
http://msdn.microsoft.com/en-us/library/h90dkhs0(v=vs.80).aspx

The most important drawbacks are: The space has to be initialized statically and are stored in the data segment of the compiled DLL, meaning that if you want to share hundreds of MBs using this method then your DLL is going to be hundreds of MBs big.

2)There's nothing wrong with using regular Memory-mapped files though as they are cached anyways. You can even use the Systems pagefile to store the data as described in this article:
http://msdn.microsoft.com/en-us/library/ms810613.aspx

I actually tested this example [1] of Inter-process communication
With a 1 GiB memory-mapped file and can confirm that nothing was written to disk even after filling the whole GiB with data.

[1] http://msdn.microsoft.com/en-us/library/aa366551(v=vs.85).aspx


问:
how to add image in one fragment and display it in another fragment/pass image through bundle in android
i want to select image in one fragment and display it in another fragment.

how can i do this.

my code is this but not working

```<code>button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent gallery = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI);
            startActivityForResult(gallery, 100);
        }
    });

@Override
public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    Uri imageUri;
    if (resultCode == RESULT_OK && requestCode == 100){
        imageUri = data.getData();
        file1path = imageUri.getPath();
        TVfrontimg.setText(file1path);
    }
}
</code>```

and i send this using bundle

```<code>Bundle bundle = new Bundle();
bundle.putString("image1", file1path);

registerPartThreeFragment.setArguments(bundle);
transaction.replace(R.id.FLcontainer, registerPartThreeFragment);
transaction.addToBackStack(null);
transaction.commit();
</code>```

in another fragment

```<code>String imgPath = getArguments().getString("image1");
Bitmap bitmap = BitmapFactory.decodeFile(String.valueOf(new File(imgPath)));
imageview.setImageBitmap(bitmap);
</code>```

but its not working.please help.

its giving me this error

2020-05-30 00:16:20.808 8995-8995/com.example.deliveryapp E/BitmapFactory: Unable to decode stream: java.io.FileNotFoundException: /raw/storage/emulated/0/DCIM/Camera/IMG_20200319_173033.jpg (No such file or directory)

答:
```<code>Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
</code>```

This code you are want showing for image

You should look find real path

Look at answers : Get filepath and filename of selected gallery image in Android

android get real path by Uri.getPath()

Body:
i want to select image in one fragment and display it in another fragment.

how can i do this.

my code is this but not working

button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent gallery = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI);
            startActivityForResult(gallery, 100);
        }
    });

@Override
public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    Uri imageUri;
    if (resultCode == RESULT_OK && requestCode == 100){
        imageUri = data.getData();
        file1path = imageUri.getPath();
        TVfrontimg.setText(file1path);
    }
}

and i send this using bundle

Bundle bundle = new Bundle();
bundle.putString("image1", file1path);

registerPartThreeFragment.setArguments(bundle);
transaction.replace(R.id.FLcontainer, registerPartThreeFragment);
transaction.addToBackStack(null);
transaction.commit();

in another fragment

String imgPath = getArguments().getString("image1");
Bitmap bitmap = BitmapFactory.decodeFile(String.valueOf(new File(imgPath)));
imageview.setImageBitmap(bitmap);

but its not working.please help.

its giving me this error

2020-05-30 00:16:20.808 8995-8995/com.example.deliveryapp E/BitmapFactory: Unable to decode stream: java.io.FileNotFoundException: /raw/storage/emulated/0/DCIM/Camera/IMG_20200319_173033.jpg (No such file or directory)

Body:
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);

This code you are want showing for image

You should look find real path

Look at answers : Get filepath and filename of selected gallery image in Android

android get real path by Uri.getPath()


问:
Design: send duplicate states into Kafka topic
I'm working on a side project where I ingest transportation data into a kafka cluster. The data comes from my city's public API. For example : each road works in the city.

I'm fetching the road works every few hours. But there is no timestamp returned by the public API, so I have no way to easily tell which road works are new or have been modified recently. Most of the time the content returned by the API has not moved since last time.
I use the roadwork id as the topic key and I activated log compaction, so having a lot of duplicates does not scare me as I'm sure the last state of each work will be kept.

But given the high number of duplicate and the fact that I'm only interested in the last version, is this ok ? Should I try to detect the new/modified roadwork and only push thoses ? Is there a way to do this directly in Kafka ?

答:
Kafka's log compaction is a very good fit to your use case. Alternatives would mean to write code on your own while adding additional complexity.

As you have already noted, when enabling log compaction, it is important to remember that at least the last state of each key (roadwork) is kept in the topic. You will still find duplicates.

In order to minimise duplicates and therefore keep the overall volume low, you can tweak the available topic configurations. Most notably I suggest to

decrease the min.cleanable.dirty.ratio (which defaults to 0.5) to have more frequent cleanings. However, keep in mind that this will lead to inefficient cleanings while using more resources.

reduce max.compaction.lag.ms (which defaults to MAX_LONG) to reduce the maximum time a message will remain ineligible for compaction in the log.

set cleanup.policy=delete,compact if your application can afford to loose older messages. In that mode, both cleanup policies will be activated and you can keep at least the latest state for each key for a given retention time (or even byte size).

Also, if you are concerned with volume size, apply a compression.type in your producer. Since Kafka version 2.2.0 you have zstd available which usually helps to reduce the byte size significantly.