问:
How to use array reduce with condition in JavaScript?
So I have an array

```<code>const records = [
    {
        value: 24,
        gender: "BOYS"
    },
    {
        value: 42,
        gender: "BOYS"
    },
    {
        value: 85,
        gender: "GIRLS"
    },
    {
        value: 12,
        gender: "GIRLS"
    },
    {
        value: 10,
        gender: "BOYS"
    }
]
</code>```

And I want to get the sum so I used the JavaScript array reduce function and got it right. Here is my code:

```<code>someFunction() {
  return records.reduce(function(sum, record){
    return sum + record.value;
  }, 0);
}
</code>```

With that code I get the value 173 which is correct. Now what I wanted to do is to get all the sum only to those objects who got a "BOYS" gender.

I tried something like

```<code>someFunction() {
  return records.reduce(function(sum, record){
    if(record.gender == 'BOYS') return sum + record.value;
  }, 0);
}
</code>```

But I get nothing. Am I missing something here? Any help would be much appreciated.

答:
Well, in case you just want to stick with reduce and don't want to use filter, you can do it this way:

const records = [
    {
        value: 24,
        gender: "BOYS"
    },
    {
        value: 42,
        gender: "BOYS"
    },
    {
        value: 85,
        gender: "GIRLS"
    },
    {
        value: 12,
        gender: "GIRLS"
    },
    {
        value: 10,
        gender: "BOYS"
    }
];

  var res = records.reduce(function(sum, record){
    if(record.gender === 'BOYS') {
       return sum + record.value;
     } else{
        return sum
    };
  }, 0);
  console.log(res);```
</div>
</div>
</p>

```  var res = records.reduce(function(sum, record){
    if(record.gender == 'BOYS') {
       return sum + record.value;
     } else{
        return sum
    };
  }, 0);
```

Body:
So I have an array

const records = [
    {
        value: 24,
        gender: "BOYS"
    },
    {
        value: 42,
        gender: "BOYS"
    },
    {
        value: 85,
        gender: "GIRLS"
    },
    {
        value: 12,
        gender: "GIRLS"
    },
    {
        value: 10,
        gender: "BOYS"
    }
]

And I want to get the sum so I used the JavaScript array reduce function and got it right. Here is my code:

someFunction() {
  return records.reduce(function(sum, record){
    return sum + record.value;
  }, 0);
}

With that code I get the value 173 which is correct. Now what I wanted to do is to get all the sum only to those objects who got a "BOYS" gender.

I tried something like

someFunction() {
  return records.reduce(function(sum, record){
    if(record.gender == 'BOYS') return sum + record.value;
  }, 0);
}

But I get nothing. Am I missing something here? Any help would be much appreciated.

Body:
Well, in case you just want to stick with reduce and don't want to use filter, you can do it this way:

const records = [
    {
        value: 24,
        gender: "BOYS"
    },
    {
        value: 42,
        gender: "BOYS"
    },
    {
        value: 85,
        gender: "GIRLS"
    },
    {
        value: 12,
        gender: "GIRLS"
    },
    {
        value: 10,
        gender: "BOYS"
    }
];

  var res = records.reduce(function(sum, record){
    if(record.gender === 'BOYS') {
       return sum + record.value;
     } else{
        return sum
    };
  }, 0);
  console.log(res);

  var res = records.reduce(function(sum, record){
    if(record.gender == 'BOYS') {
       return sum + record.value;
     } else{
        return sum
    };
  }, 0);


来源: stackexchange

问:
Why does the same gstreamer command does work on WIndows but not on linux?
I try to capture a video from a webcam and save it after appr. 10 seconds (splitmuxsink)
I have tried the same gstreamer cmd at Windows(10) and on Linux (yocto), but it does only work on windows. Windows machine is a regular laptop, Linux machine is a Raspy 3
At Linux the file get created after start, but doesn't grow in size and does not split after certain time..

```<code>c:\gstreamer\1.0\x86\bin>gst-launch-1.0.exe  -v souphttpsrc location=http://192.168.1.245:8080/video ! multipartdemux ! image/jpeg, framerate=25/1 ! jpegparse  ! splitmuxsink location=file%02d.mkv max-size-time=10000000000 muxer=matroskamux
</code>```

```<code>gst-launch-1.0  -v souphttpsrc location=http://192.168.1.245:8080/video ! multipartdemux ! image/jpeg, framerate=25/1 ! jpegparse  ! splitmuxsink location=file%02d.mkv max-size-time=10000000000 muxer=matroskamux
</code>```

I also tried to captue a singe jpg file, that worked at both systems similar.

```<code>gst-launch-1.0.exe  -v souphttpsrc location=http://192.168.1.245:8080/shot.jpg  ! filesink location=capture1.jpg
</code>```

Versions of gstreamer:
c:\gstreamer\1.0\x86\bin>gst-launch-1.0 --gst-version
GStreamer Core Library version 1.15.90

root@raspberrypi3:~# gst-launch-1.0 --gst-version
GStreamer Core Library version 1.14.4

The output is also quite similar, but at linux I have a output like
/GstPipeline:pipeline0/GstSplitMuxSink:splitmuxsink0/GstQueue:queue0: max-size-buffers = 13
/GstPipeline:pipeline0/GstSplitMuxSink:splitmuxsink0/GstQueue:queue0: max-size-buffers = 14
all the time....
Is this output slowing everything so much down that it does not work?

Windows:

```<code>c:\gstreamer\1.0\x86\bin>gst-launch-1.0.exe  -v souphttpsrc location=http://192.168.1.245:8080/video ! multipartdemux ! image/jpeg, framerate=25/1 ! jpegparse  ! splitmuxsink location=file%02d.mkv max-size-time=10000000000 muxer=matroskamux
Setting pipeline to PAUSED ...
Pipeline is PREROLLING ...
/GstPipeline:pipeline0/GstSplitMuxSink:splitmuxsink0/GstFileSink:sink: async = false
Got context from element 'souphttpsrc0': gst.soup.session=context, session=(SoupSession)NULL, force=(boolean)false;
/GstPipeline:pipeline0/GstCapsFilter:capsfilter1: caps = image/jpeg, framerate=(fraction)25/1
/GstPipeline:pipeline0/GstCapsFilter:capsfilter1.GstPad:src: caps = image/jpeg, framerate=(fraction)25/1
/GstPipeline:pipeline0/GstJpegParse:jpegparse0.GstPad:sink: caps = image/jpeg, framerate=(fraction)25/1
/GstPipeline:pipeline0/GstCapsFilter:capsfilter1.GstPad:sink: caps = image/jpeg
/GstPipeline:pipeline0/GstJpegParse:jpegparse0.GstPad:src: caps = image/jpeg, parsed=(boolean)true, format=(string)I420, width=(int)1280, height=(int)720, framerate=(fraction)25/1
/GstPipeline:pipeline0/GstSplitMuxSink:splitmuxsink0.GstGhostPad:video.GstProxyPad:proxypad0: caps = image/jpeg, parsed=(boolean)true, format=(string)I420, width=(int)1280, height=(int)720, framerate=(fraction)25/1
/GstPipeline:pipeline0/GstSplitMuxSink:splitmuxsink0/GstQueue:queue0.GstPad:sink: caps = image/jpeg, parsed=(boolean)true, format=(string)I420, width=(int)1280, height=(int)720, framerate=(fraction)25/1
/GstPipeline:pipeline0/GstSplitMuxSink:splitmuxsink0.GstGhostPad:video: caps = image/jpeg, parsed=(boolean)true, format=(string)I420, width=(int)1280, height=(int)720, framerate=(fraction)25/1
/GstPipeline:pipeline0/GstSplitMuxSink:splitmuxsink0/GstQueue:queue0.GstPad:src: caps = image/jpeg, parsed=(boolean)true, format=(string)I420, width=(int)1280, height=(int)720, framerate=(fraction)25/1
/GstPipeline:pipeline0/GstSplitMuxSink:splitmuxsink0/GstMatroskaMux:matroskamux0.GstMatroskamuxPad:video_0: caps = image/jpeg, parsed=(boolean)true, format=(string)I420, width=(int)1280, height=(int)720, framerate=(fraction)25/1
/GstPipeline:pipeline0/GstSplitMuxSink:splitmuxsink0/GstMatroskaMux:matroskamux0.GstMatroskamuxPad:video_0: caps = NULL
/GstPipeline:pipeline0/GstSplitMuxSink:splitmuxsink0/GstFileSink:sink: location = file00.mkv
Pipeline is PREROLLED ...
/GstPipeline:pipeline0/GstSplitMuxSink:splitmuxsink0/GstMatroskaMux:matroskamux0.GstMatroskamuxPad:video_0: caps = image/jpeg, parsed=(boolean)true, format=(string)I420, width=(int)1280, height=(int)720, framerate=(fraction)25/1
/GstPipeline:pipeline0/GstSplitMuxSink:splitmuxsink0/GstMatroskaMux:matroskamux0.GstPad:src: caps = video/x-matroska
/GstPipeline:pipeline0/GstSplitMuxSink:splitmuxsink0/GstFileSink:sink.GstPad:sink: caps = video/x-matroska
Setting pipeline to PLAYING ...
New clock: GstSystemClock
</code>```

Linux:

```<code>root@raspberrypi3:~# gst-launch-1.0  -v souphttpsrc location=http://192.168.1.245:8080/video ! multipartdemux ! image/jpeg, framerate=25/1 ! jpegparse  ! splitmuxsink location=file%02d.mkv max-size-time=10000000000 muxer=matroskamux
Setting pipeline to PAUSED ...
Pipeline is PREROLLING ...
/GstPipeline:pipeline0/GstSplitMuxSink:splitmuxsink0/GstFileSink:sink: async = false
Got context from element 'souphttpsrc0': gst.soup.session=context, session=(SoupSession)NULL, force=(boolean)false;
/GstPipeline:pipeline0/GstCapsFilter:capsfilter1: caps = image/jpeg, framerate=(fraction)25/1
/GstPipeline:pipeline0/GstCapsFilter:capsfilter1.GstPad:src: caps = image/jpeg, framerate=(fraction)25/1
/GstPipeline:pipeline0/GstJpegParse:jpegparse0.GstPad:sink: caps = image/jpeg, framerate=(fraction)25/1
/GstPipeline:pipeline0/GstCapsFilter:capsfilter1.GstPad:sink: caps = image/jpeg
/GstPipeline:pipeline0/GstJpegParse:jpegparse0.GstPad:src: caps = image/jpeg, parsed=(boolean)true, format=(string)I420, width=(int)1280, height=(int)720, framerate=(fraction)25/1
/GstPipeline:pipeline0/GstSplitMuxSink:splitmuxsink0.GstGhostPad:video.GstProxyPad:proxypad0: caps = image/jpeg, parsed=(boolean)true, format=(string)I420, width=(int)1280, height=(int)720, framerate=(fraction)25/1
/GstPipeline:pipeline0/GstSplitMuxSink:splitmuxsink0/GstQueue:queue0.GstPad:sink: caps = image/jpeg, parsed=(boolean)true, format=(string)I420, width=(int)1280, height=(int)720, framerate=(fraction)25/1
/GstPipeline:pipeline0/GstSplitMuxSink:splitmuxsink0/GstQueue:queue0.GstPad:src: caps = image/jpeg, parsed=(boolean)true, format=(string)I420, width=(int)1280, height=(int)720, framerate=(fraction)25/1
/GstPipeline:pipeline0/GstSplitMuxSink:splitmuxsink0/GstQueue:queue0.GstPad:src: caps = image/jpeg, parsed=(boolean)true, format=(string)I420, width=(int)1280, height=(int)720, framerate=(fraction)25/1
/GstPipeline:pipeline0/GstSplitMuxSink:splitmuxsink0/GstMatroskaMux:matroskamux0.GstMatroskamuxPad:video_0: caps = image/jpeg, parsed=(boolean)true, format=(string)I420, width=(int)1280, height=(int)720, framerate=(fraction)25/1
/GstPipeline:pipeline0/GstSplitMuxSink:splitmuxsink0/GstMatroskaMux:matroskamux0.GstMatroskamuxPad:video_0: caps = NULL
/GstPipeline:pipeline0/GstSplitMuxSink:splitmuxsink0/GstFileSink:sink: location = file00.mkv
Pipeline is PREROLLED ...
/GstPipeline:pipeline0/GstSplitMuxSink:splitmuxsink0/GstMatroskaMux:matroskamux0.GstMatroskamuxPad:video_0: caps = image/jpeg, parsed=(boolean)true, format=(string)I420, width=(int)1280, height=(int)720, framerate=(fraction)25/1
Setting pipeline to PLAYING ...
New clock: GstSystemClock
/GstPipeline:pipeline0/GstSplitMuxSink:splitmuxsink0/GstQueue:queue0: max-size-buffers = 6
/GstPipeline:pipeline0/GstSplitMuxSink:splitmuxsink0/GstQueue:queue0: max-size-buffers = 7
/GstPipeline:pipeline0/GstSplitMuxSink:splitmuxsink0/GstQueue:queue0: max-size-buffers = 8
/GstPipeline:pipeline0/GstSplitMuxSink:splitmuxsink0/GstQueue:queue0: max-size-buffers = 9
/GstPipeline:pipeline0/GstSplitMuxSink:splitmuxsink0/GstQueue:queue0: max-size-buffers = 10
/GstPipeline:pipeline0/GstSplitMuxSink:splitmuxsink0/GstQueue:queue0: max-size-buffers = 11
/GstPipeline:pipeline0/GstSplitMuxSink:splitmuxsink0/GstQueue:queue0: max-size-buffers = 12
/GstPipeline:pipeline0/GstSplitMuxSink:splitmuxsink0/GstQueue:queue0: max-size-buffers = 13
[...]
</code>```

答:
I found out after trying several things:

GSteamer debug info is not realy usable because for me its too much info....

I got my example working with the following:

If I remove "jpegparse" and "framerate=25/1"

And add "do-timestamp=true" and reduce the size of the image "image/jpeg,width=640,height=480"

it does work.

Fiddling around with Gstreamer is IMO after 3 weeks of testing it not very user-friendly, but indeed its a very powerful tool.

```<code>gst-launch-1.0 -v souphttpsrc location=http://192.168.1.133:8080/video  do-timestamp=true ! multipartdemux ! image/jpeg,width=640,height=480 ! splitmuxsink location=FILE%02d.mkv max-size-time=10000000000 muxer=matroskamux
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I try to capture a video from a webcam and save it after appr. 10 seconds (splitmuxsink)
I have tried the same gstreamer cmd at Windows(10) and on Linux (yocto), but it does only work on windows. Windows machine is a regular laptop, Linux machine is a Raspy 3
At Linux the file get created after start, but doesn't grow in size and does not split after certain time..

c:\gstreamer\1.0\x86\bin>gst-launch-1.0.exe  -v souphttpsrc location=http://192.168.1.245:8080/video ! multipartdemux ! image/jpeg, framerate=25/1 ! jpegparse  ! splitmuxsink location=file%02d.mkv max-size-time=10000000000 muxer=matroskamux

gst-launch-1.0  -v souphttpsrc location=http://192.168.1.245:8080/video ! multipartdemux ! image/jpeg, framerate=25/1 ! jpegparse  ! splitmuxsink location=file%02d.mkv max-size-time=10000000000 muxer=matroskamux

I also tried to captue a singe jpg file, that worked at both systems similar.

gst-launch-1.0.exe  -v souphttpsrc location=http://192.168.1.245:8080/shot.jpg  ! filesink location=capture1.jpg

Versions of gstreamer:
c:\gstreamer\1.0\x86\bin>gst-launch-1.0 --gst-version
GStreamer Core Library version 1.15.90

root@raspberrypi3:~# gst-launch-1.0 --gst-version
GStreamer Core Library version 1.14.4

The output is also quite similar, but at linux I have a output like
/GstPipeline:pipeline0/GstSplitMuxSink:splitmuxsink0/GstQueue:queue0: max-size-buffers = 13
/GstPipeline:pipeline0/GstSplitMuxSink:splitmuxsink0/GstQueue:queue0: max-size-buffers = 14
all the time....
Is this output slowing everything so much down that it does not work?

Windows:

c:\gstreamer\1.0\x86\bin>gst-launch-1.0.exe  -v souphttpsrc location=http://192.168.1.245:8080/video ! multipartdemux ! image/jpeg, framerate=25/1 ! jpegparse  ! splitmuxsink location=file%02d.mkv max-size-time=10000000000 muxer=matroskamux
Setting pipeline to PAUSED ...
Pipeline is PREROLLING ...
/GstPipeline:pipeline0/GstSplitMuxSink:splitmuxsink0/GstFileSink:sink: async = false
Got context from element 'souphttpsrc0': gst.soup.session=context, session=(SoupSession)NULL, force=(boolean)false;
/GstPipeline:pipeline0/GstCapsFilter:capsfilter1: caps = image/jpeg, framerate=(fraction)25/1
/GstPipeline:pipeline0/GstCapsFilter:capsfilter1.GstPad:src: caps = image/jpeg, framerate=(fraction)25/1
/GstPipeline:pipeline0/GstJpegParse:jpegparse0.GstPad:sink: caps = image/jpeg, framerate=(fraction)25/1
/GstPipeline:pipeline0/GstCapsFilter:capsfilter1.GstPad:sink: caps = image/jpeg
/GstPipeline:pipeline0/GstJpegParse:jpegparse0.GstPad:src: caps = image/jpeg, parsed=(boolean)true, format=(string)I420, width=(int)1280, height=(int)720, framerate=(fraction)25/1
/GstPipeline:pipeline0/GstSplitMuxSink:splitmuxsink0.GstGhostPad:video.GstProxyPad:proxypad0: caps = image/jpeg, parsed=(boolean)true, format=(string)I420, width=(int)1280, height=(int)720, framerate=(fraction)25/1
/GstPipeline:pipeline0/GstSplitMuxSink:splitmuxsink0/GstQueue:queue0.GstPad:sink: caps = image/jpeg, parsed=(boolean)true, format=(string)I420, width=(int)1280, height=(int)720, framerate=(fraction)25/1
/GstPipeline:pipeline0/GstSplitMuxSink:splitmuxsink0.GstGhostPad:video: caps = image/jpeg, parsed=(boolean)true, format=(string)I420, width=(int)1280, height=(int)720, framerate=(fraction)25/1
/GstPipeline:pipeline0/GstSplitMuxSink:splitmuxsink0/GstQueue:queue0.GstPad:src: caps = image/jpeg, parsed=(boolean)true, format=(string)I420, width=(int)1280, height=(int)720, framerate=(fraction)25/1
/GstPipeline:pipeline0/GstSplitMuxSink:splitmuxsink0/GstMatroskaMux:matroskamux0.GstMatroskamuxPad:video_0: caps = image/jpeg, parsed=(boolean)true, format=(string)I420, width=(int)1280, height=(int)720, framerate=(fraction)25/1
/GstPipeline:pipeline0/GstSplitMuxSink:splitmuxsink0/GstMatroskaMux:matroskamux0.GstMatroskamuxPad:video_0: caps = NULL
/GstPipeline:pipeline0/GstSplitMuxSink:splitmuxsink0/GstFileSink:sink: location = file00.mkv
Pipeline is PREROLLED ...
/GstPipeline:pipeline0/GstSplitMuxSink:splitmuxsink0/GstMatroskaMux:matroskamux0.GstMatroskamuxPad:video_0: caps = image/jpeg, parsed=(boolean)true, format=(string)I420, width=(int)1280, height=(int)720, framerate=(fraction)25/1
/GstPipeline:pipeline0/GstSplitMuxSink:splitmuxsink0/GstMatroskaMux:matroskamux0.GstPad:src: caps = video/x-matroska
/GstPipeline:pipeline0/GstSplitMuxSink:splitmuxsink0/GstFileSink:sink.GstPad:sink: caps = video/x-matroska
Setting pipeline to PLAYING ...
New clock: GstSystemClock

Linux:

root@raspberrypi3:~# gst-launch-1.0  -v souphttpsrc location=http://192.168.1.245:8080/video ! multipartdemux ! image/jpeg, framerate=25/1 ! jpegparse  ! splitmuxsink location=file%02d.mkv max-size-time=10000000000 muxer=matroskamux
Setting pipeline to PAUSED ...
Pipeline is PREROLLING ...
/GstPipeline:pipeline0/GstSplitMuxSink:splitmuxsink0/GstFileSink:sink: async = false
Got context from element 'souphttpsrc0': gst.soup.session=context, session=(SoupSession)NULL, force=(boolean)false;
/GstPipeline:pipeline0/GstCapsFilter:capsfilter1: caps = image/jpeg, framerate=(fraction)25/1
/GstPipeline:pipeline0/GstCapsFilter:capsfilter1.GstPad:src: caps = image/jpeg, framerate=(fraction)25/1
/GstPipeline:pipeline0/GstJpegParse:jpegparse0.GstPad:sink: caps = image/jpeg, framerate=(fraction)25/1
/GstPipeline:pipeline0/GstCapsFilter:capsfilter1.GstPad:sink: caps = image/jpeg
/GstPipeline:pipeline0/GstJpegParse:jpegparse0.GstPad:src: caps = image/jpeg, parsed=(boolean)true, format=(string)I420, width=(int)1280, height=(int)720, framerate=(fraction)25/1
/GstPipeline:pipeline0/GstSplitMuxSink:splitmuxsink0.GstGhostPad:video.GstProxyPad:proxypad0: caps = image/jpeg, parsed=(boolean)true, format=(string)I420, width=(int)1280, height=(int)720, framerate=(fraction)25/1
/GstPipeline:pipeline0/GstSplitMuxSink:splitmuxsink0/GstQueue:queue0.GstPad:sink: caps = image/jpeg, parsed=(boolean)true, format=(string)I420, width=(int)1280, height=(int)720, framerate=(fraction)25/1
/GstPipeline:pipeline0/GstSplitMuxSink:splitmuxsink0/GstQueue:queue0.GstPad:src: caps = image/jpeg, parsed=(boolean)true, format=(string)I420, width=(int)1280, height=(int)720, framerate=(fraction)25/1
/GstPipeline:pipeline0/GstSplitMuxSink:splitmuxsink0/GstQueue:queue0.GstPad:src: caps = image/jpeg, parsed=(boolean)true, format=(string)I420, width=(int)1280, height=(int)720, framerate=(fraction)25/1
/GstPipeline:pipeline0/GstSplitMuxSink:splitmuxsink0/GstMatroskaMux:matroskamux0.GstMatroskamuxPad:video_0: caps = image/jpeg, parsed=(boolean)true, format=(string)I420, width=(int)1280, height=(int)720, framerate=(fraction)25/1
/GstPipeline:pipeline0/GstSplitMuxSink:splitmuxsink0/GstMatroskaMux:matroskamux0.GstMatroskamuxPad:video_0: caps = NULL
/GstPipeline:pipeline0/GstSplitMuxSink:splitmuxsink0/GstFileSink:sink: location = file00.mkv
Pipeline is PREROLLED ...
/GstPipeline:pipeline0/GstSplitMuxSink:splitmuxsink0/GstMatroskaMux:matroskamux0.GstMatroskamuxPad:video_0: caps = image/jpeg, parsed=(boolean)true, format=(string)I420, width=(int)1280, height=(int)720, framerate=(fraction)25/1
Setting pipeline to PLAYING ...
New clock: GstSystemClock
/GstPipeline:pipeline0/GstSplitMuxSink:splitmuxsink0/GstQueue:queue0: max-size-buffers = 6
/GstPipeline:pipeline0/GstSplitMuxSink:splitmuxsink0/GstQueue:queue0: max-size-buffers = 7
/GstPipeline:pipeline0/GstSplitMuxSink:splitmuxsink0/GstQueue:queue0: max-size-buffers = 8
/GstPipeline:pipeline0/GstSplitMuxSink:splitmuxsink0/GstQueue:queue0: max-size-buffers = 9
/GstPipeline:pipeline0/GstSplitMuxSink:splitmuxsink0/GstQueue:queue0: max-size-buffers = 10
/GstPipeline:pipeline0/GstSplitMuxSink:splitmuxsink0/GstQueue:queue0: max-size-buffers = 11
/GstPipeline:pipeline0/GstSplitMuxSink:splitmuxsink0/GstQueue:queue0: max-size-buffers = 12
/GstPipeline:pipeline0/GstSplitMuxSink:splitmuxsink0/GstQueue:queue0: max-size-buffers = 13
[...]

Body:
I found out after trying several things:

GSteamer debug info is not realy usable because for me its too much info....

I got my example working with the following:

If I remove "jpegparse" and "framerate=25/1"

And add "do-timestamp=true" and reduce the size of the image "image/jpeg,width=640,height=480"

it does work.

Fiddling around with Gstreamer is IMO after 3 weeks of testing it not very user-friendly, but indeed its a very powerful tool.

gst-launch-1.0 -v souphttpsrc location=http://192.168.1.133:8080/video  do-timestamp=true ! multipartdemux ! image/jpeg,width=640,height=480 ! splitmuxsink location=FILE%02d.mkv max-size-time=10000000000 muxer=matroskamux


问:
Close Modal - Ionic 4 using Angular
I had created a page reservation.page.ts in which i want to make a modal form using ionic 4.
i'm using ionic modal controller for that.
the example code which i did is

```<code>async closeModal() {
    await this.viewCtrl.dismiss();
}

</code>```

still my modal is didn't work.

it gives an error like

```<code>core.js:9110 ERROR Error: Uncaught (in promise): overlay does not exist
    at resolvePromise (VM11170 polyfills.js:3803)
    at VM11170 polyfills.js:3713
    at rejected (VM11177 vendor.js:129666)
    at ZoneDelegate.invoke (VM11170 polyfills.js:3365)
    at Object.onInvoke (VM11177 vendor.js:71868)
    at ZoneDelegate.invoke (VM11170 polyfills.js:3364)
    at Zone.run (VM11170 polyfills.js:3130)
    at VM11170 polyfills.js:3861
    at ZoneDelegate.invokeTask (VM11170 polyfills.js:3397)
    at Object.onInvokeTask (VM11177 vendor.js:71849)
</code>```

so please help me out.

答:
I was able to fix this issue by declaring the variable modal and then using it to close the modal:

export class BlaBlaPage implements OnInit {

modal:any;

close() {
  this.modal.dismiss();
}
```

Title: Close Modal - Ionic 4 using Angular

Body:
I had created a page reservation.page.ts in which i want to make a modal form using ionic 4.
i'm using ionic modal controller for that.
the example code which i did is

async closeModal() {
    await this.viewCtrl.dismiss();
}

still my modal is didn't work.

it gives an error like

core.js:9110 ERROR Error: Uncaught (in promise): overlay does not exist
    at resolvePromise (VM11170 polyfills.js:3803)
    at VM11170 polyfills.js:3713
    at rejected (VM11177 vendor.js:129666)
    at ZoneDelegate.invoke (VM11170 polyfills.js:3365)
    at Object.onInvoke (VM11177 vendor.js:71868)
    at ZoneDelegate.invoke (VM11170 polyfills.js:3364)
    at Zone.run (VM11170 polyfills.js:3130)
    at VM11170 polyfills.js:3861
    at ZoneDelegate.invokeTask (VM11170 polyfills.js:3397)
    at Object.onInvokeTask (VM11177 vendor.js:71849)

so please help me out.


问:
micronaut-spring and spring-boot-actuator, can't access /actuator endpoints
Just trying out micronaut with Spring capability, and can't get access to my /actuator endpoints Spring Boot v2.3.0 release and micronaut 2.0.0.M3

I created a basic micronaut project using the mn create-app xxx --lang groovy.

I have then added the spring dependencies and micronaut-spring and associated annotation processors.

My build.gradle now looks as follows

```<code>plugins {
    id "groovy"
    id "com.github.johnrengelman.shadow" version "5.2.0"
    id "application"
    id "net.ltgt.apt" version "0.21"  //enables annotation preproccessing support
    id "net.ltgt.apt-idea" version "0.21"
    id "org.springframework.boot" version "2.3.0.RELEASE"
    id "io.spring.dependency-management" version "1.0.9.RELEASE"
}

ext['groovy.version'] = '3.0.4'

version "0.1"
group "com.softwood"

repositories {
    mavenCentral()
    maven { url "https://jcenter.bintray.com" }
}

configurations {
    // for dependencies that are needed for development only
    developmentOnly
}

dependencies {

    //annotation processors
    annotationProcessor platform("io.micronaut:micronaut-bom:$micronautVersion")
    annotationProcessor "io.micronaut.spring:micronaut-spring-boot-annotation"
    annotationProcessor "io.micronaut.spring:micronaut-spring-web-annotation"
    testAnnotationProcessor "io.micronaut.spring:micronaut-spring-web-annotation:2.0.1"

    //latest groovy v3
    implementation group: 'org.codehaus.groovy', name: 'groovy-all', version: '3.0.4' //, ext: 'pom'

    //spring
    compileOnly "io.micronaut.spring:micronaut-spring-annotation:2.0.1"
    implementation("org.springframework.boot:spring-boot-starter-web")
    implementation("org.springframework.boot:spring-boot-starter-actuator")
    implementation group: 'io.micronaut.spring', name: 'micronaut-spring-web', version: '2.0.1'
    runtime ("io.micronaut.spring:micronaut-spring-boot:2.0.1")

    compileOnly platform("io.micronaut:micronaut-bom:$micronautVersion")
    compileOnly "io.micronaut:micronaut-inject-groovy"
    implementation platform("io.micronaut:micronaut-bom:$micronautVersion")
    implementation "io.micronaut:micronaut-runtime-groovy"
    implementation "io.micronaut:micronaut-validation"
    implementation "javax.annotation:javax.annotation-api"
    implementation "io.micronaut:micronaut-http-server-netty"
    implementation "io.micronaut:micronaut-http-client"
    runtimeOnly "ch.qos.logback:logback-classic:1.2.3"
    testCompileOnly platform("io.micronaut:micronaut-bom:$micronautVersion")
    testImplementation platform("io.micronaut:micronaut-bom:$micronautVersion")
    testImplementation("org.spockframework:spock-core:2.0-M2-groovy-3.0") {
        exclude group: "org.codehaus.groovy", module: "groovy-all"
    }
    testImplementation "io.micronaut:micronaut-inject-groovy"
    testImplementation "io.micronaut.test:micronaut-test-spock"
    testImplementation "io.micronaut.test:micronaut-test-junit5"
}

test.classpath += configurations.developmentOnly

mainClassName = "com.softwood.Application"

//added - enable incremetal compile feature - can't enable with annotation processors !
/*tasks.withType(GroovyCompile).configureEach {
    options.incremental = true
}*/

tasks.withType(GroovyCompile) {
    groovyOptions.forkOptions.jvmArgs.add('-Dgroovy.parameters=true')
}

shadowJar {
    mergeServiceFiles()
}

tasks.withType(JavaExec) {
    classpath += configurations.developmentOnly
    jvmArgs('-noverify', '-XX:TieredStopAtLevel=1', '-Dcom.sun.management.jmxremote')
}
</code>```

I have adjusted a HelloController as follows

```<code>import io.micronaut.http.annotation.Controller
import io.micronaut.http.annotation.Get
import io.micronaut.http.HttpStatus
import org.springframework.boot.actuate.endpoint.annotation.Endpoint

@Controller("/hello")
@Endpoint
class HelloController {

    @Get("/")
    String index() {
        return 'hello william'
    }
}
</code>```

and marked the Application class as being a SpringbootApplication - but call the Micronaut.run() to build the MN context etc

```<code>import io.micronaut.runtime.Micronaut
import groovy.transform.CompileStatic
import org.springframework.boot.autoconfigure.SpringBootApplication

@CompileStatic
@SpringBootApplication
class Application {
    static void main(String[] args) {
        Micronaut.run(Application)
    }
}
</code>```

I tried to adjust application.yml to expose all the endpoints as follows

```<code>micronaut:
  application:
    name: micronaut-std-app

management:
  endpoints:
    web:
      exposure:
        include=*:
</code>```

This all compiles ok, and runs ok.  if you invoke the localhost:8080/hello you get the expected string

if you try and access the actuator endpoints - nothing is being generated, and the browser displays

```<code>{"message":"Page Not Found","_links":{"self":{"href":"/actuator/health","templated":false}}}
</code>```

if your trying to do a mixed micronaut and spring project, then how do you get any actuator endpoints enabled for your MN pre processed controllers etc ?

答:
If you just want a health check endpoint, Micronaut have build in health check endpoint available.

Add in the build.gradle the fallowing dependence to add the endpoints like health:

```<code>implementation("io.micronaut:micronaut-management")
</code>```

You can add in the application.yml

```<code>endpoints:
    health:
        enabled: true
</code>```

Then change the health check url to "/health"

Body:
Just trying out micronaut with Spring capability, and can't get access to my /actuator endpoints Spring Boot v2.3.0 release and micronaut 2.0.0.M3

I created a basic micronaut project using the mn create-app xxx --lang groovy.

I have then added the spring dependencies and micronaut-spring and associated annotation processors.

My build.gradle now looks as follows

plugins {
    id "groovy"
    id "com.github.johnrengelman.shadow" version "5.2.0"
    id "application"
    id "net.ltgt.apt" version "0.21"  //enables annotation preproccessing support
    id "net.ltgt.apt-idea" version "0.21"
    id "org.springframework.boot" version "2.3.0.RELEASE"
    id "io.spring.dependency-management" version "1.0.9.RELEASE"
}

ext['groovy.version'] = '3.0.4'

version "0.1"
group "com.softwood"

repositories {
    mavenCentral()
    maven { url "https://jcenter.bintray.com" }
}

configurations {
    // for dependencies that are needed for development only
    developmentOnly
}

dependencies {

    //annotation processors
    annotationProcessor platform("io.micronaut:micronaut-bom:$micronautVersion")
    annotationProcessor "io.micronaut.spring:micronaut-spring-boot-annotation"
    annotationProcessor "io.micronaut.spring:micronaut-spring-web-annotation"
    testAnnotationProcessor "io.micronaut.spring:micronaut-spring-web-annotation:2.0.1"

    //latest groovy v3
    implementation group: 'org.codehaus.groovy', name: 'groovy-all', version: '3.0.4' //, ext: 'pom'

    //spring
    compileOnly "io.micronaut.spring:micronaut-spring-annotation:2.0.1"
    implementation("org.springframework.boot:spring-boot-starter-web")
    implementation("org.springframework.boot:spring-boot-starter-actuator")
    implementation group: 'io.micronaut.spring', name: 'micronaut-spring-web', version: '2.0.1'
    runtime ("io.micronaut.spring:micronaut-spring-boot:2.0.1")

    compileOnly platform("io.micronaut:micronaut-bom:$micronautVersion")
    compileOnly "io.micronaut:micronaut-inject-groovy"
    implementation platform("io.micronaut:micronaut-bom:$micronautVersion")
    implementation "io.micronaut:micronaut-runtime-groovy"
    implementation "io.micronaut:micronaut-validation"
    implementation "javax.annotation:javax.annotation-api"
    implementation "io.micronaut:micronaut-http-server-netty"
    implementation "io.micronaut:micronaut-http-client"
    runtimeOnly "ch.qos.logback:logback-classic:1.2.3"
    testCompileOnly platform("io.micronaut:micronaut-bom:$micronautVersion")
    testImplementation platform("io.micronaut:micronaut-bom:$micronautVersion")
    testImplementation("org.spockframework:spock-core:2.0-M2-groovy-3.0") {
        exclude group: "org.codehaus.groovy", module: "groovy-all"
    }
    testImplementation "io.micronaut:micronaut-inject-groovy"
    testImplementation "io.micronaut.test:micronaut-test-spock"
    testImplementation "io.micronaut.test:micronaut-test-junit5"
}

test.classpath += configurations.developmentOnly

mainClassName = "com.softwood.Application"

//added - enable incremetal compile feature - can't enable with annotation processors !
/*tasks.withType(GroovyCompile).configureEach {
    options.incremental = true
}*/

tasks.withType(GroovyCompile) {
    groovyOptions.forkOptions.jvmArgs.add('-Dgroovy.parameters=true')
}

shadowJar {
    mergeServiceFiles()
}

tasks.withType(JavaExec) {
    classpath += configurations.developmentOnly
    jvmArgs('-noverify', '-XX:TieredStopAtLevel=1', '-Dcom.sun.management.jmxremote')
}

I have adjusted a HelloController as follows

import io.micronaut.http.annotation.Controller
import io.micronaut.http.annotation.Get
import io.micronaut.http.HttpStatus
import org.springframework.boot.actuate.endpoint.annotation.Endpoint

@Controller("/hello")
@Endpoint
class HelloController {

    @Get("/")
    String index() {
        return 'hello william'
    }
}

and marked the Application class as being a SpringbootApplication - but call the Micronaut.run() to build the MN context etc

import io.micronaut.runtime.Micronaut
import groovy.transform.CompileStatic
import org.springframework.boot.autoconfigure.SpringBootApplication

@CompileStatic
@SpringBootApplication
class Application {
    static void main(String[] args) {
        Micronaut.run(Application)
    }
}

I tried to adjust application.yml to expose all the endpoints as follows

micronaut:
  application:
    name: micronaut-std-app

management:
  endpoints:
    web:
      exposure:
        include=*:

This all compiles ok, and runs ok.  if you invoke the localhost:8080/hello you get the expected string

if you try and access the actuator endpoints - nothing is being generated, and the browser displays

{"message":"Page Not Found","_links":{"self":{"href":"/actuator/health","templated":false}}}

if your trying to do a mixed micronaut and spring project, then how do you get any actuator endpoints enabled for your MN pre processed controllers etc ?

Body:
If you just want a health check endpoint, Micronaut have build in health check endpoint available.

Add in the build.gradle the fallowing dependence to add the endpoints like health:

implementation("io.micronaut:micronaut-management")

You can add in the application.yml

endpoints:
    health:
        enabled: true

Then change the health check url to "/health"


问:
What the ImageNet Vid policy over evaluation of frames with zero object inside
Ι am trying to evaluate my video object detection module and I am using InageNet VID dataset for this purpose. At some point I am facing the case to evaluate a frame containing zero objects. Meaning there are no ground truth bboxes in this frame (this is fine since we are talking about video object detection).

Since, the module I am using expected at least 1 bbox to be present I was wondering what's the official treatment for these case by ImageNet. I found this description which obviously not exhaustive one may provide some point in ImageNet site which states:

The evaluation metric is the same as for the objct detection task,
  meaning objects which are not annotated will be penalized, as will
  duplicate detections (two annotations for the same object instance).

(sic; typo is from the original text)

Which does not mention the above case scenario. Since this is a simple description I am not sure it covers every edge case. Normally in single image object detection this is not an issues since evaluation samples always contain some object. But in this case does this mean I should ignore those frames for example altogether?

Also, checking this repository about object detection metric (which is super analytic by the way) the no gt case seems to fall into the general scenario about False Positive (FP). In this case Intersection would be 0 (since no gt bbox exists) and Union would be just a non zero number equal to the FP bbox and so, IoU = 0.

So, how does the official ImageNet deal with these cases? I am not interested in what is reasonable choice here, just the official version.

答:
What about the case where there is a missing annotation for an object which should have had a GT annotation ?

For example ILSVRC2015_val_00000001/000266.JPEG clearly has a turtle (in fact up until 000265.JPEG all the frames has the corresponding annotation of turtle) but the corresponding annotation file ILSVRC2015_val_00000001/000266.xml doesn't have any annotation.

In my analysis, there are 4046 frames out of 176126 in validation dataset which have missing GT annotation. Most of these frames have no GT annotation despite containing an object which belongs to one of the 30 categories of ImageNetVID.


问:
poor IronPython performance of external modules when debugging enabled
I am running into some performance problems with IronPython inside of VS2010 while trying to import and use SymPy.

I have an IronPython test project containing the following code:

```<code>import time

print 'StandaloneIronPython'

startTime = time.time()
from sympy import *
importTime = time.time() - startTime
print 'Import time = %f' % importTime

startTime = time.time()
for x in (x/10.0 for x in xrange(-100,100)):
    (x**2-2*x)
numericsTime = time.time() - startTime
print 'Basic numerics time= %f' % numericsTime

startTime = time.time()
for x in (x/10.0 for x in xrange(-100,100)):
    N(x**2-2*x)
sympyTime = time.time() - startTime
print 'SymPy time = %f' % sympyTime

raw_input('Press enter to continue...')
</code>```

SymPy was downloaded and installed as an egg; my "IronPython 2.7\Lib\site-packages" folder is in the project Search Path.

If I run the program via "Debug > Start Debugging" I get approximately this:

```<code>StandaloneIronPython
Import time = 12.090019
Basic numerics time= 0.015594
SymPy time = 2.230804
Press enter to continue...
</code>```

If, however, I run the program via "Debug > Start Without Debugging" I get approximately:

```<code>StandaloneIronPython
Import time = 2.199600
Basic numerics time= 0.015602
SymPy time = 0.140404
Press enter to continue...
</code>```

I get ~5 times the speed importing and >10 times the speed running sympy.

So how can I get good performance out of IronPython if it's spending all its time debugging library code?

Is there a way that I can bundle up SymPy as a library, assembly, or something else such that it will perform quickly?

Is there a way to tell VS2010 not to debug the code for SymPy?

Is there some other sort of solution?

答:
Whenever you see a big performance discrepancy between running with and without a debugger attached, it's usually because your app is generating a ton of events that the debugger has to handle.

The most common example of this is exceptions. If SymPy is throwing and catching lots and lots of exceptions during initialization, each exception causes a round trip to the debugger (even if it's handled), causing a massive slowdown.

You can verify this by going to "Debug > Exceptions...", checking the "Thrown" box next to "Common Language Runtime Exceptions" and re-running the app. If you stop at hundreds of exceptions, there's your problem.

If that is indeed your problem, unfortunately there's not a good workaround for it. Pre-compiling your Python code into a .dll won't prevent those exceptions from being thrown.

ContentLicense: CC BY-SA 3.0

Body:
I am running into some performance problems with IronPython inside of VS2010 while trying to import and use SymPy.

I have an IronPython test project containing the following code:

import time

print 'StandaloneIronPython'

startTime = time.time()
from sympy import *
importTime = time.time() - startTime
print 'Import time = %f' % importTime

startTime = time.time()
for x in (x/10.0 for x in xrange(-100,100)):
    (x**2-2*x)
numericsTime = time.time() - startTime
print 'Basic numerics time= %f' % numericsTime

startTime = time.time()
for x in (x/10.0 for x in xrange(-100,100)):
    N(x**2-2*x)
sympyTime = time.time() - startTime
print 'SymPy time = %f' % sympyTime

raw_input('Press enter to continue...')

SymPy was downloaded and installed as an egg; my "IronPython 2.7\Lib\site-packages" folder is in the project Search Path.

If I run the program via "Debug > Start Debugging" I get approximately this:

StandaloneIronPython
Import time = 12.090019
Basic numerics time= 0.015594
SymPy time = 2.230804
Press enter to continue...

If, however, I run the program via "Debug > Start Without Debugging" I get approximately:

StandaloneIronPython
Import time = 2.199600
Basic numerics time= 0.015602
SymPy time = 0.140404
Press enter to continue...

I get ~5 times the speed importing and >10 times the speed running sympy.

So how can I get good performance out of IronPython if it's spending all its time debugging library code?

Is there a way that I can bundle up SymPy as a library, assembly, or something else such that it will perform quickly?

Is there a way to tell VS2010 not to debug the code for SymPy?

Is there some other sort of solution?


问:
How to show a snackbar or toast after a user logs in
How can i show a snackbar or a toast when i user logs in <code>['you have successfully logged in!']</code>or it can be how can i show a snackbar or toast after a navigation. </p>

答:
You can display it like this:

```<code>final snackBar = SnackBar(content: Text('you have successfully logged in!'));
Scaffold.of(context).showSnackBar(snackBar);
</code>```

Here's the official documentation.

Body: How can i show a snackbar or a toast when i user logs in ['you have successfully logged in!']or it can be how can i show a snackbar or toast after a navigation.

Body:
You can display it like this:

final snackBar = SnackBar(content: Text('you have successfully logged in!'));
Scaffold.of(context).showSnackBar(snackBar);

Here's the official documentation.


问:
Only allow properties that are declared in JSON schema
I am using json-schema and wanting to only allow properties that are declared in this file to pass validation. For instance if a user passes a "name" property in their json object it will fail this schema because "name" is not listed here as a property.

Is there some function similar to "required" that will only allow the listed properties to pass?

```<code>{
"$schema": "http://json-schema.org/draft-04/schema#",
"title": "Accounting Resource - Add Item",
"type": "object",
"properties": {
    "itemNumber": {
        "type":"string",
        "minimum": 3
    },
    "title": {
        "type":"string",
        "minimum": 5
    },
    "description": {
        "type":"string",
        "minimum": 5
    }
},
"required": [
    "itemNumber",
    "title",
    "description"
]
}
</code>```

答:
Inside your definition provide:

all required fields inside "required": []

and set "additionalProperties": false

DEMO:

without "additionalProperties": false:

with "additionalProperties": false:

Body:
I am using json-schema and wanting to only allow properties that are declared in this file to pass validation. For instance if a user passes a "name" property in their json object it will fail this schema because "name" is not listed here as a property.

Is there some function similar to "required" that will only allow the listed properties to pass?

{
"$schema": "http://json-schema.org/draft-04/schema#",
"title": "Accounting Resource - Add Item",
"type": "object",
"properties": {
    "itemNumber": {
        "type":"string",
        "minimum": 3
    },
    "title": {
        "type":"string",
        "minimum": 5
    },
    "description": {
        "type":"string",
        "minimum": 5
    }
},
"required": [
    "itemNumber",
    "title",
    "description"
]
}


问:
Android studio new update version 4.0 says Kotlin is incompatible with this new build
I got the new update (4.0) of android studio and the update wizard says that kotlin and firebase services are incompatible with this update.

Can i use the kotlin and firebase services after the update? or is it safe to download this update considering some of my active projects use kotlin.

答:
I had the same message as you and just updated it. Kotlin and Firebase plugins are bundled. That should mean that the studio is preinstalled with them and they must be compatible. Looks fine so far.

My new version:

Android Studio 4.0
Build #AI-193.6911.18.40.6514223, built on May 20, 2020


问:
QT socket wait for user input
i'm trying to develop a simple server with basic authentication,
i have the following code:

```<code>socket = new QTcpSocket();
connect(socket,SIGNAL(readyRead()),this,SLOT(readyRead()),Qt::DirectConnection);
connect(socket,SIGNAL(disconnected()),this,SLOT(disconnected()),Qt::DirectConnection);
check_user();
</code>```

.......
and check_user() is

```<code>socket->write("Please enter username:");
socket->flush();
QStringList list;
while (socket->canReadLine())
{
    QString data = QString(socket->readLine());
    if ( data == "\r\n" )
        break;
    list.append(data);
}
qDebug()<<list;
</code>```

but this don't wait for user input and go further.
I would like that this function wait for user input for a string of variable lenght till carriage return.
but how?

答:
You can connect a slot to the readyRead() signal of the socket and handle the input there.

(https://doc.qt.io/qt-5/qiodevice.html#readyRead)

But for that to work you will need an event loop running in the thread the socket lives in.

(https://doc.qt.io/archives/qt-4.8/qeventloop.html)

Another solution would be to use waitForReadyRead(-1) of the socket. This would block the thread and emit the readyRead() signal. The function will return true if the signal gets emitted. But you would also need a running event loop.

(https://doc.qt.io/qt-5/qabstractsocket.html#waitForReadyRead)

Title: QT socket wait for user input

Body:
i'm trying to develop a simple server with basic authentication,
i have the following code:

socket = new QTcpSocket();
connect(socket,SIGNAL(readyRead()),this,SLOT(readyRead()),Qt::DirectConnection);
connect(socket,SIGNAL(disconnected()),this,SLOT(disconnected()),Qt::DirectConnection);
check_user();

.......
and check_user() is

socket->write("Please enter username:");
socket->flush();
QStringList list;
while (socket->canReadLine())
{
    QString data = QString(socket->readLine());
    if ( data == "\r\n" )
        break;
    list.append(data);
}
qDebug()<<list;

but this don't wait for user input and go further.
I would like that this function wait for user input for a string of variable lenght till carriage return.
but how?


问:
Ignore specific nodes/attributes while comparing two JSONs
I want to compare two JSON strings which is a huge hierarchy and want to know where they differ in values. But some values are generated at runtime and are dynamic. I want to ignore those particular nodes from my comparison.

I am currently using JSONAssert from org.SkyScreamer to do the comparison. It gives me nice console output but does not ignore any attributes.

for ex.

```<code>java.lang.AssertionError messageHeader.sentTime
expected:null
got:09082016 18:49:41.123
</code>```

Now this comes dynamic and should be ignored. Something like

```<code>JSONAssert.assertEquals(expectedJSONString, actualJSONString,JSONCompareMode, *list of attributes to be ignored*)
</code>```

It would be great if someone suggests a solution in JSONAssert. However other ways are also welcome.

答:
Thank you @dknaus for the detailed answer. Although this solution will not work in STRICT mode and checkJsonObjectKeysExpectedInActual method code needs to be replaced by following code [As suggested by @tk-gospodinov]:

```<code> for (String attribute : attributesToIgnore) {
     expected.remove(attribute);
     super.checkJsonObjectKeysExpectedInActual(prefix, expected, actual, result);
  }
</code>```

Body:
I want to compare two JSON strings which is a huge hierarchy and want to know where they differ in values. But some values are generated at runtime and are dynamic. I want to ignore those particular nodes from my comparison.

I am currently using JSONAssert from org.SkyScreamer to do the comparison. It gives me nice console output but does not ignore any attributes.

for ex.

java.lang.AssertionError messageHeader.sentTime
expected:null
got:09082016 18:49:41.123

Now this comes dynamic and should be ignored. Something like

JSONAssert.assertEquals(expectedJSONString, actualJSONString,JSONCompareMode, *list of attributes to be ignored*)

It would be great if someone suggests a solution in JSONAssert. However other ways are also welcome.

Body:
Thank you @dknaus for the detailed answer. Although this solution will not work in STRICT mode and checkJsonObjectKeysExpectedInActual method code needs to be replaced by following code [As suggested by @tk-gospodinov]:

 for (String attribute : attributesToIgnore) {
     expected.remove(attribute);
     super.checkJsonObjectKeysExpectedInActual(prefix, expected, actual, result);
  }


问:
How do I make Dartfmt "friendly" for Matrices?
For a Matrix that supposed to look like this:

```<code>const ColorFilter sepia = ColorFilter.matrix(<double>[
          0.393, 0.769, 0.189, 0, 0,
          0.349, 0.686, 0.168, 0, 0,
          0.272, 0.534, 0.131, 0, 0,
          0,     0,     0,     1, 0,
        ]);
</code>```

But dartfmt changed it to become like this:

```<code>const ColorFilter sepia = ColorFilter.matrix(<double>[
          0.393,
          0.769,
          0.189,
          0,
          0,
          0.349,
          0.686,
          0.168,
          0,
          0,
          0.272,
          0.534,
          0.131,
          0,
          0,
          0,
          0,
          0,
          1,
          0,
        ]);
</code>```

This is hard to read. Thus, how can I keep the original format so that the Matrix can be seen more "friendly". Or at least how can I make Dartfmt not to reformat any List?

答:
Whereas @julemand101's answer should be the accepted one, as it directly changes dartfmt's behavior, this spread operator workaround could be worth to mention :

final matrix = [
   ...[1, 2, 3],
   ...[4, 5, 6],
   ...[7, 8, 9],
];
```

Body:
For a Matrix that supposed to look like this:

const ColorFilter sepia = ColorFilter.matrix(<double>[
          0.393, 0.769, 0.189, 0, 0,
          0.349, 0.686, 0.168, 0, 0,
          0.272, 0.534, 0.131, 0, 0,
          0,     0,     0,     1, 0,
        ]);

But dartfmt changed it to become like this:

const ColorFilter sepia = ColorFilter.matrix(<double>[
          0.393,
          0.769,
          0.189,
          0,
          0,
          0.349,
          0.686,
          0.168,
          0,
          0,
          0.272,
          0.534,
          0.131,
          0,
          0,
          0,
          0,
          0,
          1,
          0,
        ]);

This is hard to read. Thus, how can I keep the original format so that the Matrix can be seen more "friendly". Or at least how can I make Dartfmt not to reformat any List?


问:
Unable to detect faces of cartoon images
I am trying to implement a simple face detection of cartoons code using opencv and python. Though the code I have used works for faces of humans I am not able to detect cartoon faces using this. Is there any way I can make it detect cartoon faces too.

import cv2
import matplotlib.pyplot as plt

imagePath = 'frame179.jpg'
cascPath = '/Users/tonystark/opencv/data/haarcascades/haarcascade_frontalface_default.xml'

faceCascade = cv2.CascadeClassifier(cascPath)
image = cv2.imread(imagePath)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

faces = faceCascade.detectMultiScale(
    gray,
    scaleFactor=1.1,
    minNeighbors=40,
    minSize=(24, 24),
    flags=cv2.CASCADE_SCALE_IMAGE
)
```

The images are human for which I am able to get the location of the face, whereas for cartoon, I am not able to get the location of faces.

Thanks a lot in advance !

答:
So as cartoon images are very different to that of humans, we need to train a model from scratch for them separately.
I implemented a YOLO model, and trained it, and the results were really good !

labelImg can be used to prepare the dataset.

I referred this blog : Darknet YOLO using OpenCV to create my own YOLO detector in which the github repository Darknet YOLO is cloned and modified.

EDIT :
My project on github

Body:
I am trying to implement a simple face detection of cartoons code using opencv and python. Though the code I have used works for faces of humans I am not able to detect cartoon faces using this. Is there any way I can make it detect cartoon faces too.

import cv2
import matplotlib.pyplot as plt

imagePath = 'frame179.jpg'
cascPath = '/Users/tonystark/opencv/data/haarcascades/haarcascade_frontalface_default.xml'

faceCascade = cv2.CascadeClassifier(cascPath)
image = cv2.imread(imagePath)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

faces = faceCascade.detectMultiScale(
    gray,
    scaleFactor=1.1,
    minNeighbors=40,
    minSize=(24, 24),
    flags=cv2.CASCADE_SCALE_IMAGE
)

The images are human for which I am able to get the location of the face, whereas for cartoon, I am not able to get the location of faces.

Thanks a lot in advance !


问:
Since upgrade, on-prem AzureDevops Server 2019 is retaining 10x build data in dbo.tbl_content
My on-prem, Azure DevOps 2019's backups are showing an unsubstainable increase in size of the .mdf file

query1 shows that it's the "dbo.tbl_content" table

query2 shows that    it's "FileContainer" at 112GB.

query3 shows that it's pipelines://b    at 93GB.

query4 shows that the size used has gone up from 1GB a    month, to the unsubstainable 10GB per
month. This occurred in Jan 2020, when possibly coincidentally, we upgraded from TFS18 to AzureDevOps19.

So,I believe I'm looking for a build pipe (not release pipe) that needs cleaning up? Historically, we've tried to keep 366 days worth of old build logs but at the rate we're going we won't make it.

We've got about 40 build pipes (some historic, that no longer run), inc 4 triggered on commit (CI).

re: retention policy...

typical CI build retention policy. Days to keep: 10 Min to Keep: 1

typical RC build retention policy. Days to keep: 180 Min to Keep: 50

from: DefaultCollection/Base/_settings/buildqueue...
Maximum retention policy / Days to keep: 183 Min to Keep: 55
Default retention policy / Days to keep: 15 Min to Keep: 1
Permanently destroy builds / Days to keep build record after deletion: 366   <- I reduced this yesterday down from 7000

Any help appreciated here, but specifically:

How can I track down the specific build that's causing the problem? and how can I fix it?

Is there any tooling that will show me where problems lie. e.g. TFS used to have a health audit tool, but I can't see it?

query1
SELECT TOP 10 o.name,
SUM(reserved_page_count) * 8.0 / 1024 SizeInMB,
SUM(CASE
WHEN p.index_id <= 1 THEN p.row_count
ELSE 0
END) Row_Count
FROM sys.dm_db_partition_stats p
JOIN sys.objects o
ON p.object_id = o.object_id
GROUP BY o.name
ORDER BY SUM(reserved_page_count) DESC

query2
SELECT Owner =
CASE
WHEN OwnerId = 0 THEN 'Generic'
WHEN OwnerId = 1 THEN 'VersionControl'
WHEN OwnerId = 2 THEN 'WorkItemTracking'
WHEN OwnerId = 3 THEN 'TeamBuild'
WHEN OwnerId = 4 THEN 'TeamTest'
WHEN OwnerId = 5 THEN 'Servicing'
WHEN OwnerId = 6 THEN 'UnitTest'
WHEN OwnerId = 7 THEN 'WebAccess'
WHEN OwnerId = 8 THEN 'ProcessTemplate'
WHEN OwnerId = 9 THEN 'StrongBox'
WHEN OwnerId = 10 THEN 'FileContainer'
WHEN OwnerId = 11 THEN 'CodeSense'
WHEN OwnerId = 12 THEN 'Profile'
WHEN OwnerId = 13 THEN 'Aad'
WHEN OwnerId = 14 THEN 'Gallery'
WHEN OwnerId = 15 THEN 'BlobStore'
WHEN OwnerId = 255 THEN 'PendingDeletion'
END,
SUM(CompressedLength) / 1024.0 / 1024.0 AS BlobSizeInMB
FROM tbl_FileReference AS r
JOIN tbl_FileMetadata AS m
ON r.ResourceId = m.ResourceId
AND r.PartitionId = m.PartitionId
WHERE r.PartitionId = 1
GROUP BY OwnerId
ORDER BY 2 DESC

query3
SELECT CASE
WHEN Container = 'vstfs:///Buil' THEN 'Build'
WHEN Container = 'vstfs:///Git/' THEN 'Git'
WHEN Container = 'vstfs:///Dist' THEN 'DistributedTask'
WHEN Container = 'vstfs:///Rele' THEN 'Release'
ELSE Container
END AS FileContainerOwner,
SUM(fm.CompressedLength) / 1024 / 1024 AS TotalSizeInMB
FROM (SELECT DISTINCT LEFT(c.ArtifactUri, 13) AS Container,
fr.ResourceId,
ci.PartitionId
FROM tbl_Container c with (nolock)
INNER JOIN tbl_ContainerItem ci
ON c.ContainerId = ci.ContainerId
AND c.PartitionId = ci.PartitionId
INNER JOIN tbl_FileReference fr
ON ci.fileId = fr.fileId
AND ci.DataspaceId = fr.DataspaceId
AND ci.PartitionId = fr.PartitionId) c
INNER JOIN tbl_FileMetadata fm
ON fm.ResourceId = c.ResourceId
AND fm.PartitionId = c.PartitionId
GROUP BY c.Container
ORDER BY TotalSizeInMB DESC

query4
Select DATEPART(yyyy, CreationDate) as [year],
DATEPART(mm, CreationDate) as [month],
SUM(DATALENGTH(Content)) / 1048576 as [Size in Mb]
From tbl_Content With (nolock)
Group by DATEPART(yyyy, CreationDate),
DATEPART(mm, CreationDate)
Order by DATEPART(yyyy, CreationDate),
DATEPART(mm, CreationDate)

Related question: TFS2015 tbl_Content increase

答:
You could try to run below query to narrow down the date:

```<code>SELECT ci.ContainerId,
c.ArtifactUri,
c.Name,
c.DateCreated,
SUM(fm.FileLength)
FROM tbl_ContainerItem ci
JOIN tbl_FileReference f
ON f.FileId = ci.FileId
JOIN tbl_FileMetadata fm
ON fm.PartitionId = 1
AND fm.ResourceId = f.ResourceId
LEFT JOIN tbl_Container c
ON c.ContainerId = ci.ContainerId
AND c.PartitionId = 1
WHERE f.PartitionId = 1
AND ci.PartitionId = 1
GROUP BY ci.ContainerId, c.ArtifactUri, c.Name, c.DateCreated
</code>```

And since it's related to build, kindly check if test report caused this. You could refer detail actions in this thread: TFS database growing too large

Besides, you could also try shrinking the transaction log in TFS/Azure DevOps Database.

Shrinking log file for TFS databases

How to shrink TFS database size

Body:
You could try to run below query to narrow down the date:

SELECT ci.ContainerId,
c.ArtifactUri,
c.Name,
c.DateCreated,
SUM(fm.FileLength)
FROM tbl_ContainerItem ci
JOIN tbl_FileReference f
ON f.FileId = ci.FileId
JOIN tbl_FileMetadata fm
ON fm.PartitionId = 1
AND fm.ResourceId = f.ResourceId
LEFT JOIN tbl_Container c
ON c.ContainerId = ci.ContainerId
AND c.PartitionId = 1
WHERE f.PartitionId = 1
AND ci.PartitionId = 1
GROUP BY ci.ContainerId, c.ArtifactUri, c.Name, c.DateCreated

And since it's related to build, kindly check if test report caused this. You could refer detail actions in this thread: TFS database growing too large

Besides, you could also try shrinking the transaction log in TFS/Azure DevOps Database.

Shrinking log file for TFS databases

How to shrink TFS database size


问:
Is there a way to get data from multiple Activity in a single Fragment?
I have a fragment in a User Activity that opens up a Map Activity to receive some string variables.The fragment Has Already Recieved 2 String Variables from the User Activity using Bundles.

This is my Method for doing such but i keep getting that error :

And this is the error i get that kick me out

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.project_seraphim_disease_tracker, PID: 17049
    java.lang.RuntimeException: Failure delivering result ResultInfo{who=null,
request=66738, result=-1, data=Intent { (has extras) }} to activity
{com.example.project_seraphim_disease_tracker/com.example.project_seraphim_diseas
e_tracker.User}: java.lang.NullPointerException: Attempt to invoke virtual method
'void android.widget.EditText.setText(java.lang.CharSequence)' on a null object reference
```

<p><strong>These are in both Map Activity and the Fragment that's in User Activity</strong></p>

<pre class="lang-java prettyprint-override"><code>private static final String SEARCHED_ADDRESS = "searched_address";
private static final String SEARCHED_NAME = "searched_address_name";
private LatLng SearchedLocationlatLng;
private String SearchedlocationAddress;
private String SearchedlocationName;
</code>```

This is the button that called to a Map activity from a fragment which is in User Activity

btnAddress.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Intent intent = new Intent(getActivity(),Map.class);
        startActivityForResult(intent,IDENTIFIER);
    }
});
```

<p><strong>This is what i used to Receive the Strings</strong></p>

<pre class="lang-java prettyprint-override"><code>@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    switch(requestCode) {
        case (IDENTIFIER) : {
            if (resultCode == Map.RESULT_OK) {
                SearchedlocationAddress=data.getStringExtra(SEARCHED_ADDRESS);
                SearchedlocationName=data.getStringExtra(SEARCHED_NAME);
                editTextSearchLocationBar.setText(SearchedlocationName);
            }
            break;
        }
    }
}
</code>```

This is in the Map Activity for passing the strings

btnConfirmAddress.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Intent resultIntent = new Intent();
        resultIntent.putExtra(SEARCHED_NAME,SearchedlocationName);
        resultIntent.putExtra(SEARCHED_ADDRESS,SearchedlocationAddress);
        setResult(Map.RESULT_OK, resultIntent);
        finish();

    }
```

答:
The Solution was found on this old post but it still works.

https://stackoverflow.com/a/16449850/13594169

basically When i call startActivityForResult in a fragment the parent activity (Inmy case the User Activity get to handle the data first) Then from there i have to pass the data to the fragment.

Imagein Activities as the parent A and B and Fragment in A as the child A.1.
Child A.1 request data from parent B. Parent B give the data to parent A, after parent A receive the data, then it will pass it to child A.1.

So after Calling from fragment A.1

```<code>startActivityForResult(intent,IDENTIFIER);
</code>```

put this in Activity B for passing the required data

```<code>Intent resultIntent = new Intent();
resultIntent.putExtra(key_word,String);
setResult(Map.RESULT_OK, resultIntent);
</code>```

put this in activity A To handel the data received from activity B

```<code>@Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
    super.onActivityResult(requestCode, resultCode, intent);
    Fragment fragment = (Fragment) getChildFragmentManager().findFragmentByTag(childTag);
    if (fragment != null) {
        fragment.onActivityResult(requestCode, resultCode, intent);
    }
}
//If you have your child Fragment as a private member,
//then use Fragment fragment = myChildFragment;
//to replace the above findFragmentByTag line of code. The rest can be kept unchanged
</code>```

Then put this in fragment A.1 to receive the data orgin from Activity B

```<code>@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    switch(requestCode) {
        case (IDENTIFIER) : {
            if (resultCode == Map.RESULT_OK) {
                //Assign data
                //Update Ui
            }
            break;
        }
    }
}
</code>```

Body:
I have a fragment in a User Activity that opens up a Map Activity to receive some string variables.The fragment Has Already Recieved 2 String Variables from the User Activity using Bundles.

This is my Method for doing such but i keep getting that error :

And this is the error i get that kick me out

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.project_seraphim_disease_tracker, PID: 17049
    java.lang.RuntimeException: Failure delivering result ResultInfo{who=null,
request=66738, result=-1, data=Intent { (has extras) }} to activity
{com.example.project_seraphim_disease_tracker/com.example.project_seraphim_diseas
e_tracker.User}: java.lang.NullPointerException: Attempt to invoke virtual method
'void android.widget.EditText.setText(java.lang.CharSequence)' on a null object reference

These are in both Map Activity and the Fragment that's in User Activity

private static final String SEARCHED_ADDRESS = "searched_address";
private static final String SEARCHED_NAME = "searched_address_name";
private LatLng SearchedLocationlatLng;
private String SearchedlocationAddress;
private String SearchedlocationName;

This is the button that called to a Map activity from a fragment which is in User Activity

btnAddress.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Intent intent = new Intent(getActivity(),Map.class);
        startActivityForResult(intent,IDENTIFIER);
    }
});

This is what i used to Receive the Strings

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    switch(requestCode) {
        case (IDENTIFIER) : {
            if (resultCode == Map.RESULT_OK) {
                SearchedlocationAddress=data.getStringExtra(SEARCHED_ADDRESS);
                SearchedlocationName=data.getStringExtra(SEARCHED_NAME);
                editTextSearchLocationBar.setText(SearchedlocationName);
            }
            break;
        }
    }
}

This is in the Map Activity for passing the strings

btnConfirmAddress.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Intent resultIntent = new Intent();
        resultIntent.putExtra(SEARCHED_NAME,SearchedlocationName);
        resultIntent.putExtra(SEARCHED_ADDRESS,SearchedlocationAddress);
        setResult(Map.RESULT_OK, resultIntent);
        finish();

    }

Body:
The Solution was found on this old post but it still works.

https://stackoverflow.com/a/16449850/13594169

basically When i call startActivityForResult in a fragment the parent activity (Inmy case the User Activity get to handle the data first) Then from there i have to pass the data to the fragment.

Imagein Activities as the parent A and B and Fragment in A as the child A.1.
Child A.1 request data from parent B. Parent B give the data to parent A, after parent A receive the data, then it will pass it to child A.1.

So after Calling from fragment A.1

startActivityForResult(intent,IDENTIFIER);

put this in Activity B for passing the required data

Intent resultIntent = new Intent();
resultIntent.putExtra(key_word,String);
setResult(Map.RESULT_OK, resultIntent);

put this in activity A To handel the data received from activity B

@Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
    super.onActivityResult(requestCode, resultCode, intent);
    Fragment fragment = (Fragment) getChildFragmentManager().findFragmentByTag(childTag);
    if (fragment != null) {
        fragment.onActivityResult(requestCode, resultCode, intent);
    }
}
//If you have your child Fragment as a private member,
//then use Fragment fragment = myChildFragment;
//to replace the above findFragmentByTag line of code. The rest can be kept unchanged

Then put this in fragment A.1 to receive the data orgin from Activity B

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    switch(requestCode) {
        case (IDENTIFIER) : {
            if (resultCode == Map.RESULT_OK) {
                //Assign data
                //Update Ui
            }
            break;
        }
    }
}


问:
Joining tables in SQL Server to get all the data
I have 3 tables as

```<code>Customer
Customer    |Name
1002        |ABB
2006        |Aberdeen C
.
.
</code>```

And Sales Revenue table

```<code>Customer|Inv.   |Product    |Sales Amount   |Gross Margin
1002    |600    |5      |8000       |125
1002    |601    |20     |0      |-10
1002    |602    |0      |320        |160
2006    |603    |7      |120        |0
.
.
</code>```

Account Receivable table

```<code>Customer|Inv.   |Product    |Balance    |Line Amount    |Amount
1002    |500    |0      |150        |NULL       |150
1002    |600    |5      |8000       |8000       |8000
1002    |601    |20     |0      |0      |0
1002    |602    |0      |0      |160        |160
2006    |603    |7      |120        |120        |0
.
.
</code>```

I want to create a view of customer by joining Sales Revenue and Account Receivable table as:

```<code>Customer|Name|Inv.|Product|Sales Amount |Gross Margin   |Balance    |Line Amount
1002    |ABB |500 |0      |NULL     |NULL       |150        |150
1002    |ABB |600 |5      |8000     |125        |8000       |8000
1002    |ABB |601 |20     |0        |-10        |0      |0
1002    |ABB |602 |0      |320      |160        |160        |160
2006    |ABB |603 |7      |120      |0      |120        |0
.
.
</code>```

I tried

```<code>CREATE  or alter   VIEW [dbo].[custmermasterview] as
SELECT [Customer]
      ,[Name]
      ,[Inv]
      ,[Sales Amount]
      ,[Gross Margin]
      ,[Balance]
      ,isnull([Line Amount],[Amount]) as LineAmount
      ,[dbo].[SalesRevenue].[product_key]

  FROM [PDI].[dbo].[Customer]
  LEFT JOIN [dbo].[SalesRevenue] ON
   ([PDI].[dbo].[Customer].[customer_key] = [dbo].[SalesRevenue].[customer_key] and
  LEFT JOIN [dbo].[AccountReceivables] ON
  ([dbo].[SalesRevenue].[Inv] = [dbo].[AccountReceivables].Inv)
</code>```

Obviously it's left joining with SalesRevenue, so records from AccountReceivables are not getting pulled.
How can I get the required output?

答:
Its a bit hard to test but i think this will work

```<code>SELECT [Customer]
  ,[Name]
  ,[Inv]
  ,[Sales Amount]
  ,[Gross Margin]
  ,[Balance]
  ,isnull([Line Amount],[Amount]) as LineAmount
  ,[dbo].[SalesRevenue].[product_key]

  FROM [PDI].[dbo].[Customer]
  LEFT JOIN [dbo].[SalesRevenue] ON
   ([PDI].[dbo].[Customer].[customer_key] = [dbo].[SalesRevenue].[customer_key]
  LEFT JOIN [dbo].[AccountReceivables] ar ON
  ([dbo].[SalesRevenue].[Inv] = [dbo].[AccountReceivables].Inv)
  OR
  ([PDI].[dbo].[Customer].[customer_key] = [dbo].[AccountReceivables].[customer]
    AND NOT EXISTS(SELECT NULL FROM [dbo].[SalesRevenue] sr WHERE sr.[Inv] = ar.[Inv] and
    sr.[customer] = ar.[customer] ) )
</code>```

I added some alias to the tables to make it a bit easier to join. also, your query uses customer_key to join, but your tables say customer?

Body:
I have 3 tables as

Customer
Customer    |Name
1002        |ABB
2006        |Aberdeen C
.
.

And Sales Revenue table

Customer|Inv.   |Product    |Sales Amount   |Gross Margin
1002    |600    |5      |8000       |125
1002    |601    |20     |0      |-10
1002    |602    |0      |320        |160
2006    |603    |7      |120        |0
.
.

Account Receivable table

Customer|Inv.   |Product    |Balance    |Line Amount    |Amount
1002    |500    |0      |150        |NULL       |150
1002    |600    |5      |8000       |8000       |8000
1002    |601    |20     |0      |0      |0
1002    |602    |0      |0      |160        |160
2006    |603    |7      |120        |120        |0
.
.

I want to create a view of customer by joining Sales Revenue and Account Receivable table as:

Customer|Name|Inv.|Product|Sales Amount |Gross Margin   |Balance    |Line Amount
1002    |ABB |500 |0      |NULL     |NULL       |150        |150
1002    |ABB |600 |5      |8000     |125        |8000       |8000
1002    |ABB |601 |20     |0        |-10        |0      |0
1002    |ABB |602 |0      |320      |160        |160        |160
2006    |ABB |603 |7      |120      |0      |120        |0
.
.

I tried

CREATE  or alter   VIEW [dbo].[custmermasterview] as
SELECT [Customer]
      ,[Name]
      ,[Inv]
      ,[Sales Amount]
      ,[Gross Margin]
      ,[Balance]
      ,isnull([Line Amount],[Amount]) as LineAmount
      ,[dbo].[SalesRevenue].[product_key]

  FROM [PDI].[dbo].[Customer]
  LEFT JOIN [dbo].[SalesRevenue] ON
   ([PDI].[dbo].[Customer].[customer_key] = [dbo].[SalesRevenue].[customer_key] and
  LEFT JOIN [dbo].[AccountReceivables] ON
  ([dbo].[SalesRevenue].[Inv] = [dbo].[AccountReceivables].Inv)

Obviously it's left joining with SalesRevenue, so records from AccountReceivables are not getting pulled.
How can I get the required output?

Body:
Its a bit hard to test but i think this will work

SELECT [Customer]
  ,[Name]
  ,[Inv]
  ,[Sales Amount]
  ,[Gross Margin]
  ,[Balance]
  ,isnull([Line Amount],[Amount]) as LineAmount
  ,[dbo].[SalesRevenue].[product_key]

  FROM [PDI].[dbo].[Customer]
  LEFT JOIN [dbo].[SalesRevenue] ON
   ([PDI].[dbo].[Customer].[customer_key] = [dbo].[SalesRevenue].[customer_key]
  LEFT JOIN [dbo].[AccountReceivables] ar ON
  ([dbo].[SalesRevenue].[Inv] = [dbo].[AccountReceivables].Inv)
  OR
  ([PDI].[dbo].[Customer].[customer_key] = [dbo].[AccountReceivables].[customer]
    AND NOT EXISTS(SELECT NULL FROM [dbo].[SalesRevenue] sr WHERE sr.[Inv] = ar.[Inv] and
    sr.[customer] = ar.[customer] ) )

I added some alias to the tables to make it a bit easier to join. also, your query uses customer_key to join, but your tables say customer?


问:
Using submithandler (Jquery Validate ) to submit a form upon validation
Ive been having a hard time using the "submit handler" part of the jquery validate function.

My code for that is as follows ($ms for a noconflict call):

```<code>    submitHandler: function(a2) {
        $ms("#HID_Join2").val("J2");
        $ms("#submit_button").hide();
        $ms("#submit_loading").show();
        a2.submit();
    }
</code>```

but I keep seeing in firebug that
"a2.submit is not a function"

Here is how I call the form, if it matters.

```<code><form id="billingForm" name="billingForm" method="post" action="joinSEM2.asp">
stuff stuff stuff
</form>
</code>```

the first three steps are executed, but the form does not submit. Ive tried using the .submit and .post functions instead, but I cant get them to work in conjunction with validate.
Any suggestions? something Obvious I am doing wrong? I have used this before with no problem, so i dont know why this is happening... Thank you so much.

答:
In this case try:
$("#billingForm").submit();</p>

Body:
Ive been having a hard time using the "submit handler" part of the jquery validate function.

My code for that is as follows ($ms for a noconflict call):

    submitHandler: function(a2) {
        $ms("#HID_Join2").val("J2");
        $ms("#submit_button").hide();
        $ms("#submit_loading").show();
        a2.submit();
    }

but I keep seeing in firebug that
"a2.submit is not a function"

Here is how I call the form, if it matters.

<form id="billingForm" name="billingForm" method="post" action="joinSEM2.asp">
stuff stuff stuff
</form>

the first three steps are executed, but the form does not submit. Ive tried using the .submit and .post functions instead, but I cant get them to work in conjunction with validate.
Any suggestions? something Obvious I am doing wrong? I have used this before with no problem, so i dont know why this is happening... Thank you so much.


问:
Cannot get list of entries: The resource could not be found (Contentful)
I am trying to retrieve a list of entries based on category_type but I'm getting the exception below:

```<code>I/flutter ( 8486): Cannot get list of entries. Finished with error: {
I/flutter ( 8486):   "sys": {
I/flutter ( 8486):     "type": "Error",
I/flutter ( 8486):     "id": "NotFound"
I/flutter ( 8486):   },
I/flutter ( 8486):   "message": "The resource could not be found.",
I/flutter ( 8486):   "requestId": "883045ce-dcc2-4187-ab1d-28c57ad18756"
I/flutter ( 8486): }
I/flutter ( 8486): null
</code>```

This is the calling code:

```<code>Future<List<Category>> getCategories() async {
  try {
     final entries = await _contentfulClient.getEntries<Category>(
      params: {
        'content_type': 'category',
        'skip': '0',
        'limit': '100',
        'order': 'sys.createdAt',
    },
  );

    return entries.items.asList();
  } catch(exception){
    print(exception.message);
  }
}
</code>```

The content_type name is correct and there is no mistake in the spelling.

I tried a different code to get information about the space I'm trying to access and that works just fine:

```<code>Future<Space> getCurrentSpaceDetails() async {
  try {
    return await _contentfulClient.getSpaceDetails(
      spaceid: Secrets.CONTENTFUL_SPACE_ID);
  } on ContentfulError catch (error) {
  throw ContentfulError(message: error.message);
  }
 }
</code>```

with the output:

```<code>I/flutter ( 8486): Space {
I/flutter ( 8486):   sys=SystemFields {
I/flutter ( 8486):     id=5k4zwxslsof9,
I/flutter ( 8486):     type=Space,
I/flutter ( 8486):   },
I/flutter ( 8486):   locales=[Locale {
I/flutter ( 8486):     code=en-US,
I/flutter ( 8486):     name=English (United States),
I/flutter ( 8486):     isDefault=true,
I/flutter ( 8486):   }],
I/flutter ( 8486):   name=afro-quiz,
I/flutter ( 8486): }
</code>```

So I don't think this has anything to do with the installation.

I am using the contentful_dart 0.0.5 dependency

答:
So what I finally did was go to the content delivery API references for java:

https://www.contentful.com/developers/docs/references/content-delivery-api/#/reference/search-parameters/content-type/query-entries/console/java

where i followed the example to query entries by content type

I modified the url below to fit my use case:

```<code>/spaces/{space_id}/environments/{environment_id}/entries?access_token={access_token}&content_type={content_type}
</code>```

Final result:

```<code> Future getAllCategories(String spaceId,
   String accessToken, String contentTypeId) async {

   try {
     final response = await _contentfulClient.client.get(
         'https://$_baseUrl/spaces/$spaceId/environments/$_baseEnvironment

          /entries?access_token=$accessToken&content_type=$contentTypeId');
        return response.body;
   } catch (exception) {

     print(exception.message);
   }
 }
</code>```

This finally  worked for me.

Body:
I am trying to retrieve a list of entries based on category_type but I'm getting the exception below:

I/flutter ( 8486): Cannot get list of entries. Finished with error: {
I/flutter ( 8486):   "sys": {
I/flutter ( 8486):     "type": "Error",
I/flutter ( 8486):     "id": "NotFound"
I/flutter ( 8486):   },
I/flutter ( 8486):   "message": "The resource could not be found.",
I/flutter ( 8486):   "requestId": "883045ce-dcc2-4187-ab1d-28c57ad18756"
I/flutter ( 8486): }
I/flutter ( 8486): null

This is the calling code:

Future<List<Category>> getCategories() async {
  try {
     final entries = await _contentfulClient.getEntries<Category>(
      params: {
        'content_type': 'category',
        'skip': '0',
        'limit': '100',
        'order': 'sys.createdAt',
    },
  );

    return entries.items.asList();
  } catch(exception){
    print(exception.message);
  }
}

The content_type name is correct and there is no mistake in the spelling.

I tried a different code to get information about the space I'm trying to access and that works just fine:

Future<Space> getCurrentSpaceDetails() async {
  try {
    return await _contentfulClient.getSpaceDetails(
      spaceid: Secrets.CONTENTFUL_SPACE_ID);
  } on ContentfulError catch (error) {
  throw ContentfulError(message: error.message);
  }
 }

with the output:

I/flutter ( 8486): Space {
I/flutter ( 8486):   sys=SystemFields {
I/flutter ( 8486):     id=5k4zwxslsof9,
I/flutter ( 8486):     type=Space,
I/flutter ( 8486):   },
I/flutter ( 8486):   locales=[Locale {
I/flutter ( 8486):     code=en-US,
I/flutter ( 8486):     name=English (United States),
I/flutter ( 8486):     isDefault=true,
I/flutter ( 8486):   }],
I/flutter ( 8486):   name=afro-quiz,
I/flutter ( 8486): }

So I don't think this has anything to do with the installation.

I am using the contentful_dart 0.0.5 dependency

Body:
So what I finally did was go to the content delivery API references for java:

https://www.contentful.com/developers/docs/references/content-delivery-api/#/reference/search-parameters/content-type/query-entries/console/java

where i followed the example to query entries by content type

I modified the url below to fit my use case:

/spaces/{space_id}/environments/{environment_id}/entries?access_token={access_token}&content_type={content_type}

Final result:

 Future getAllCategories(String spaceId,
   String accessToken, String contentTypeId) async {

   try {
     final response = await _contentfulClient.client.get(
         'https://$_baseUrl/spaces/$spaceId/environments/$_baseEnvironment

          /entries?access_token=$accessToken&content_type=$contentTypeId');
        return response.body;
   } catch (exception) {

     print(exception.message);
   }
 }

This finally  worked for me.


问:
C# Attributes mandatory property
I've created attribute like

```<code>    [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
    [Serializable]
    public class TestPropertyAttribute : System.Attribute
    {
        public string Name
        {
            get { return _name; }
            set { _name = value; }
        }string _name;
    }
</code>```

and I should mark "Name" as mandatory property of this attribute. How to do it?

答:
The accepted answer by Jon Skeet is a good solution. However, you can write this with shorter code nowadays. It works the same:</p>

```<code>public class TestPropertyAttribute : Attribute
{
    public TestPropertyAttribute(string name)
    {
        Name = name;
    }

    public string Name { get; }
}
</code>```

Title: C# Attributes mandatory property

Body:
I've created attribute like

    [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
    [Serializable]
    public class TestPropertyAttribute : System.Attribute
    {
        public string Name
        {
            get { return _name; }
            set { _name = value; }
        }string _name;
    }

and I should mark "Name" as mandatory property of this attribute. How to do it?

Body:
The accepted answer by Jon Skeet is a good solution. However, you can write this with shorter code nowadays. It works the same:

public class TestPropertyAttribute : Attribute
{
    public TestPropertyAttribute(string name)
    {
        Name = name;
    }

    public string Name { get; }
}


问:
How to avoid adding user to all groups with a resource
New to using Keycloak and I am trying to understand assigning of roles to users. This is the format I use. I create roles and users and create groups with certain roles. I then assign users to groups to have the permissions based on roles in the group. Now I have difficulty in the following case.

Lets say I have 4 resources A, B, C, D, 2 roles R1, R2, 2 groups G1, G2 and a user U.

R1 have permissions (i use these authorization scopes: read, write, create, delete) to access A, B.

R2 have permissions to access only to  A, B, C, D resources.

G1 has role R1 and G2 has role R2 assigned to them.

Now I create a user U and want to give him access to G1 hoping this user will have access to 2 mentioned resources. But that is not the case and I notice U is not given access to any of the 4 resources. I will need to add this user to G2 as well to get access to all 4 resources which is not what I wanted.

Also in another case, if I want to add user to G2, I expect him to have access to all 4 resources. But I notice that this user can only access C, D. And I should add him to G1 as well to get access to all the resources.

I believe keycloak checks with an and condition fashion in assigning permissions. Is there a way to define roles with resources exclusive to each other?

答:
From my experience of using Keycloak and in absence of your complete configuration in question, I would recommend to bring permissions into picture.

https://www.keycloak.org/docs/latest/authorization_services/#_permission_overview

NOTE: Please note that this is just a PERSONAL recommendation, not a
  hard-fast approach.

When you use permission, you can set the decision strategy to be affirmative. (It seems in your case default permission is set to Unanimous which means all policies must evaluate to true)

(https://www.keycloak.org/docs/latest/authorization_services/#_permission_decision_strategies)

The way I would approach this is:

Assign roles to groups (same as what you did)
G1 -> R1
G2 -> R2

Add users to groups (same as what you did)

Create a role based policy for R1(Policy1) and R2(Policy2).

Create permission for each resource (PermA, PermB, PermC, PermD)

Associate permission with required role policy

(taking your example)

Since R2 has access to all resources. Associate Policy2 with all 4 permsions.

Since R1 has access to A,B resources. Associate Policy1 with only PermA, PermB.

Keeping the decision strategy as Affirmative.


问:
Curl PHP Api V4 Google Sheets
with the following code I call the API v4 to print the values of a spreadsheet. It is going very well.

```<code>$curl = curl_init();
curl_setopt($curl, CURLOPT_URL,"https://sheets.googleapis.com/v4/spreadsheets/
spreadsheetID/values/PHP?valueRenderOption=UNFORMATTED_VALUE&key=yourKeyId");
$result = curl_exec ($curl);
curl_close ($curl);
</code>```

What I can't achieve is to do an insert or update on it, I can't manage to put the PHP curl together for this. Some help? Please try as below but it doesn't work.

```<code>$curl = curl_init();
curl_setopt($curl, CURLOPT_URL,"https://sheets.googleapis.com/v4/spreadsheets/
spreadsheetID/append/PHP?InsertDataOption=INSERT_ROWS&key=yourKeyId");
$jvalues=array(array("5869","35685987","Ema","2020-05-29","no brinda","3563430423"));

$jsonData = array(
'values' => $jvalues
 );

$jsonDataEncoded = json_encode($jsonData);

curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
$result = curl_exec ($curl);
curl_close ($curl);
</code>```

image for error

Some help, I found no examples anywhere.
Thanks.

答:
Unfortunately, the API key cannot be used for the POST methods while it can be used for the GET method. So it is required for putting values to Google Spreadsheet to use the access token retrieved by OAuth2 and/or the service account. By the way, when the Google Spreadsheet is not yours or you have no permission for writing, even when the access token is used, the values cannot be used.

References:

Sheets Authorizing requests

OAuth2

Title: Curl PHP Api V4 Google Sheets

Body:
with the following code I call the API v4 to print the values of a spreadsheet. It is going very well.

$curl = curl_init();
curl_setopt($curl, CURLOPT_URL,"https://sheets.googleapis.com/v4/spreadsheets/
spreadsheetID/values/PHP?valueRenderOption=UNFORMATTED_VALUE&key=yourKeyId");
$result = curl_exec ($curl);
curl_close ($curl);

What I can't achieve is to do an insert or update on it, I can't manage to put the PHP curl together for this. Some help? Please try as below but it doesn't work.

$curl = curl_init();
curl_setopt($curl, CURLOPT_URL,"https://sheets.googleapis.com/v4/spreadsheets/
spreadsheetID/append/PHP?InsertDataOption=INSERT_ROWS&key=yourKeyId");
$jvalues=array(array("5869","35685987","Ema","2020-05-29","no brinda","3563430423"));

$jsonData = array(
'values' => $jvalues
 );

$jsonDataEncoded = json_encode($jsonData);

curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
$result = curl_exec ($curl);
curl_close ($curl);

image for error

Some help, I found no examples anywhere.
Thanks.


问:
Ruby/Rails - Is there an easy way to make hard-coded HTML symbols html_safe?
In my view I want to display some right double angle quotes in my link.

Before Rails 3, this worked:

<%= link_to "» #{@category.name}", some_path %>

Now what should I do if I want to specify the » as html_safe but not the rest of the link's text?

In other words I do not want to do this:

<%= link_to "» #{@category.name}".html_safe, some_path %>
I do not want the @category.name treated as html_safe.

This produces the desired result:

<%= link_to "»".html_safe + " #{@category.name}", some_path %>

However, if I do this:

<%= link_to "#{@category.name}" + "»".html_safe, some_path %>

The output of the angle quotes is not treated as safe.  I see » on my page and not ».

Why?

I tried extracting "»".html_safe to a helper method with the same results.

Is there a way to easily designate hard coded text/symbols as HMTL safe in Rails 3?

Thanks.

答:
In this situation I often explicitly escape the unsafe part: </p>

```<code>"» #{h @category.name}".html_safe
</code>```

Body:
In this situation I often explicitly escape the unsafe part:

"&raquo; #{h @category.name}".html_safe


问:
Convert column with string json string to column with dictionary in pyspark
I have a column with following structure in my dataframe. </p>

```<code>+--------------------+
|                data|
+--------------------+
|{"sbar":{"_id":"5...|
|{"sbar":{"_id":"5...|
|{"sbar":{"_id":"5...|
|{"sbar":{"_id":"5...|
|{"sbar":{"_id":"5...|
+--------------------+
only showing top 5 rows
</code>```

<p>The data inside column is a json string. I want to convert the column to some other type (map, struct..). How do I do this with a udf function? I have created a function like this but cant figure out what the return type should be. I tried StructType and MapType which threw error. This is my code. </p>

```<code>import json
from pyspark.sql.types import MapType, StructType

udf_getDict = F.udf(lambda x: json.loads(x), StructType)

subset.select(udf_getDict(F.col('data'))).printSchema()
</code>```

答:
You can use an approach with spark.read.json and df.rdd.map such as this:

```<code>json_string = """
{
    "glossary": {
        "title": "example glossary",
        "GlossDiv": {
            "title": "S",
            "GlossList": {
                "GlossEntry": {
                    "ID": "SGML",
                    "SortAs": "SGML",
                    "GlossTerm": "Standard Generalized Markup Language",
                    "Acronym": "SGML",
                    "Abbrev": "ISO 8879:1986",
                    "GlossDef": {
                        "para": "A meta-markup language, used to create markup languages such as DocBook.",
                        "GlossSeeAlso": ["GML", "XML"]
                    },
                    "GlossSee": "markup"
                }
            }
        }
    }
}
"""
df2 = spark.createDataFrame(
    [
        (1, json_string),
    ],
    ['id', 'txt']
)
df2.dtypes
[('id', 'bigint'), ('txt', 'string')]

new_df = spark.read.json(df2.rdd.map(lambda r: r.txt))
new_df.printSchema()
root
 |-- glossary: struct (nullable = true)
 |    |-- GlossDiv: struct (nullable = true)
 |    |    |-- GlossList: struct (nullable = true)
 |    |    |    |-- GlossEntry: struct (nullable = true)
 |    |    |    |    |-- Abbrev: string (nullable = true)
 |    |    |    |    |-- Acronym: string (nullable = true)
 |    |    |    |    |-- GlossDef: struct (nullable = true)
 |    |    |    |    |    |-- GlossSeeAlso: array (nullable = true)
 |    |    |    |    |    |    |-- element: string (containsNull = true)
 |    |    |    |    |    |-- para: string (nullable = true)
 |    |    |    |    |-- GlossSee: string (nullable = true)
 |    |    |    |    |-- GlossTerm: string (nullable = true)
 |    |    |    |    |-- ID: string (nullable = true)
 |    |    |    |    |-- SortAs: string (nullable = true)
 |    |    |-- title: string (nullable = true)
 |    |-- title: string (nullable = true)
</code>```

Body:
I have a column with following structure in my dataframe.

+--------------------+
|                data|
+--------------------+
|{"sbar":{"_id":"5...|
|{"sbar":{"_id":"5...|
|{"sbar":{"_id":"5...|
|{"sbar":{"_id":"5...|
|{"sbar":{"_id":"5...|
+--------------------+
only showing top 5 rows

The data inside column is a json string. I want to convert the column to some other type (map, struct..). How do I do this with a udf function? I have created a function like this but cant figure out what the return type should be. I tried StructType and MapType which threw error. This is my code.

import json
from pyspark.sql.types import MapType, StructType

udf_getDict = F.udf(lambda x: json.loads(x), StructType)

subset.select(udf_getDict(F.col('data'))).printSchema()

Body:
You can use an approach with spark.read.json and df.rdd.map such as this:

json_string = """
{
    "glossary": {
        "title": "example glossary",
        "GlossDiv": {
            "title": "S",
            "GlossList": {
                "GlossEntry": {
                    "ID": "SGML",
                    "SortAs": "SGML",
                    "GlossTerm": "Standard Generalized Markup Language",
                    "Acronym": "SGML",
                    "Abbrev": "ISO 8879:1986",
                    "GlossDef": {
                        "para": "A meta-markup language, used to create markup languages such as DocBook.",
                        "GlossSeeAlso": ["GML", "XML"]
                    },
                    "GlossSee": "markup"
                }
            }
        }
    }
}
"""
df2 = spark.createDataFrame(
    [
        (1, json_string),
    ],
    ['id', 'txt']
)
df2.dtypes
[('id', 'bigint'), ('txt', 'string')]

new_df = spark.read.json(df2.rdd.map(lambda r: r.txt))
new_df.printSchema()
root
 |-- glossary: struct (nullable = true)
 |    |-- GlossDiv: struct (nullable = true)
 |    |    |-- GlossList: struct (nullable = true)
 |    |    |    |-- GlossEntry: struct (nullable = true)
 |    |    |    |    |-- Abbrev: string (nullable = true)
 |    |    |    |    |-- Acronym: string (nullable = true)
 |    |    |    |    |-- GlossDef: struct (nullable = true)
 |    |    |    |    |    |-- GlossSeeAlso: array (nullable = true)
 |    |    |    |    |    |    |-- element: string (containsNull = true)
 |    |    |    |    |    |-- para: string (nullable = true)
 |    |    |    |    |-- GlossSee: string (nullable = true)
 |    |    |    |    |-- GlossTerm: string (nullable = true)
 |    |    |    |    |-- ID: string (nullable = true)
 |    |    |    |    |-- SortAs: string (nullable = true)
 |    |    |-- title: string (nullable = true)
 |    |-- title: string (nullable = true)