问:
Ajax laravel doesn't return single record in console but all data and nothing in html
I'am trying to make search function that user input code of product in textbox and click button to see detail of the product using ajax and laravel.

this is my route

```<code>Route::get('tracking', 'ClientController@show')->name('tracking');
</code>```

and my controller (ClientController)

```<code>public function show(Request $request){
    $no_smu = $request->input('search');
    $tracking = Incoming::where('no_smu', 'like', '%' . $no_smu . '%')->get();
    return response()->json($tracking);
}
</code>```

my form blade

```<code><form class="lockscreen-credentials" id="form">
  <div class="input-group">
    <input type="text" name="no_smu" id="no_smu" class="form-control" placeholder="SMU Number">
    <div class="input-group-append">
      <button type="submit" id="submit" class="btn"><i class="fas fa-arrow-right text-muted"></i></a>
    </div>
  </div>
</form>

<div class="help-block text-center" id="content">
 <!-- data should load here -->
</div>
</code>```

ajax script

```<code>  $(document).ready(function(){
    $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });

    $('#submit').on('click', function(e){
      e.preventDefault();
      var no_smu = $('#no_smu').val();
      // alert(no_smu);
      $.ajax({
        type: "GET",
        url: "{{ route('tracking') }}",
        dataType: "json",
        data: {'no_smu' : no_smu},
        success: function(data){
          console.log(data);
          // $('#content').html(data);
        }
      });
    });
  });
</code>```

the problems, it return all data not a single data of input product and if i comment console.log(data) and uncommented $('#content').html(data) it's return nothing.

答:
After struggling for a half day, I finally solved this.

Like @DilipHirapara suggested it should use first() to get single data. In my controller i called request input with wrong name with textbox in blade.

Now my controller

```<code>public function show(Request $request)
    {
        $no_smu = $request->input('no_smu');
        $tracking = Incoming::where('no_smu', 'LIKE','%'. $no_smu .'%')->first();
        return response()->json($tracking);
    }
</code>```

and my form

```<code><form class="lockscreen-credentials" id="form">
  <div class="input-group">
    <input type="text" name="no_smu" id="no_smu" class="form-control" placeholder="SMU Number">
    <div class="input-group-append">
      <button type="submit" id="submit" class="btn"><i class="fas fa-arrow-right text-muted"></i></a>
    </div>
  </div>
</form>
</code>```

And for my ajax, i should add the item of my column with data.

```<code><script type="text/javascript">
      $(document).ready(function(){
        $.ajaxSetup({
          headers: { 'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content') },
        });

        $('#submit').on('click', function(e){
          e.preventDefault();
          var no_smu = $('#no_smu').val();
          // alert(no_smu);
          $.ajax({
            type: "get",
            url: "{{ url('tracking') }}",
            data: {'no_smu' : no_smu, "_token": "{{ csrf_token() }}"},
            dataType: "json",
            success: function(data){
              $('#smu').html(data.no_smu);
              $('#flight').html("Flight number " + ": " + data.flight_no);
              $('#koli').html("Koli " + ": " + data.koli);
              $('#kilo').html("Kilo" + ": " + data.kilo);
              $('#asal').html("Asal" + ": " + data.asal);
              $('#status').html("Status" + ": " + data.status);
              // console.log(data.no_smu);
            }
          });
        });
      });
    </script>
</code>```

in the process i faced Error internal server 500 something like that.

to resolve this. add meta tag in head of html

```<code><meta name="csrf-token" content="{{ csrf_token() }}">
</code>```

and add "_token": "{{ csrf_token() }}" with passing data in ajax like above.

Body:
I'am trying to make search function that user input code of product in textbox and click button to see detail of the product using ajax and laravel.

this is my route

Route::get('tracking', 'ClientController@show')->name('tracking');

and my controller (ClientController)

public function show(Request $request){
    $no_smu = $request->input('search');
    $tracking = Incoming::where('no_smu', 'like', '%' . $no_smu . '%')->get();
    return response()->json($tracking);
}

my form blade

<form class="lockscreen-credentials" id="form">

    <input type="text" name="no_smu" id="no_smu" class="form-control" placeholder="SMU Number">

      <button type="submit" id="submit" class="btn">

</form>

ajax script

  $(document).ready(function(){
    $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });

    $('#submit').on('click', function(e){
      e.preventDefault();
      var no_smu = $('#no_smu').val();
      // alert(no_smu);
      $.ajax({
        type: "GET",
        url: "{{ route('tracking') }}",
        dataType: "json",
        data: {'no_smu' : no_smu},
        success: function(data){
          console.log(data);
          // $('#content').html(data);
        }
      });
    });
  });

the problems, it return all data not a single data of input product and if i comment console.log(data) and uncommented $('#content').html(data) it's return nothing.

Body:
After struggling for a half day, I finally solved this.

Like @DilipHirapara suggested it should use first() to get single data. In my controller i called request input with wrong name with textbox in blade.

Now my controller

public function show(Request $request)
    {
        $no_smu = $request->input('no_smu');
        $tracking = Incoming::where('no_smu', 'LIKE','%'. $no_smu .'%')->first();
        return response()->json($tracking);
    }

and my form

<form class="lockscreen-credentials" id="form">
  <div class="input-group">
    <input type="text" name="no_smu" id="no_smu" class="form-control" placeholder="SMU Number">
    <div class="input-group-append">
      <button type="submit" id="submit" class="btn"><i class="fas fa-arrow-right text-muted"></i></a>
    </div>
  </div>
</form>

And for my ajax, i should add the item of my column with data.

<script type="text/javascript">
      $(document).ready(function(){
        $.ajaxSetup({
          headers: { 'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content') },
        });

        $('#submit').on('click', function(e){
          e.preventDefault();
          var no_smu = $('#no_smu').val();
          // alert(no_smu);
          $.ajax({
            type: "get",
            url: "{{ url('tracking') }}",
            data: {'no_smu' : no_smu, "_token": "{{ csrf_token() }}"},
            dataType: "json",
            success: function(data){
              $('#smu').html(data.no_smu);
              $('#flight').html("Flight number " + ": " + data.flight_no);
              $('#koli').html("Koli " + ": " + data.koli);
              $('#kilo').html("Kilo" + ": " + data.kilo);
              $('#asal').html("Asal" + ": " + data.asal);
              $('#status').html("Status" + ": " + data.status);
              // console.log(data.no_smu);
            }
          });
        });
      });
    </script>

in the process i faced Error internal server 500 something like that.

to resolve this. add meta tag in head of html

<meta name="csrf-token" content="{{ csrf_token() }}">

and add "_token": "{{ csrf_token() }}" with passing data in ajax like above.


来源: stackexchange

问:
Error when trying to give values to matrix, shows problem with dimensions
I made a numpy array of size 6*6*51 with the command

matrix = np.zeros((6,6,51))

But when I write a loop so that a 6 element array is placed in matrix[i][:][j] it says the

ValueError: could not broadcast input array from shape (6) into shape
  (51)

What am I doing wrong here ?

答:
```<code>import numpy as np
a = np.zeros((6,6,51))
</code>```

You are indexing incorrectly. Your subscription should include all the dimensions.

a[i][:] is essentially the same as a[i] then j in a[i][:][j] is indexing the second dimension.

```<code>In [14]: b = a[1][:]

In [15]: b.shape
Out[15]: (6, 51)
In [16]: c = a[1][:][1]

In [17]: c.shape
Out[17]: (51,)
</code>```

Use a[i,:,j] for the subscription.

```<code>In [20]: a[1,:,1] = np.arange(6)
In [21]: a[1,:,1]
Out[21]: array([ 0.,  1.,  2.,  3.,  4.,  5.])
</code>```

Numpy Indexing

ContentLicense: CC BY-SA 4.0

Body:
import numpy as np
a = np.zeros((6,6,51))

You are indexing incorrectly. Your subscription should include all the dimensions.

a[i][:] is essentially the same as a[i] then j in a[i][:][j] is indexing the second dimension.

In [14]: b = a[1][:]

In [15]: b.shape
Out[15]: (6, 51)
In [16]: c = a[1][:][1]

In [17]: c.shape
Out[17]: (51,)

Use a[i,:,j] for the subscription.

In [20]: a[1,:,1] = np.arange(6)
In [21]: a[1,:,1]
Out[21]: array([ 0.,  1.,  2.,  3.,  4.,  5.])

Numpy Indexing


问:
Apache + PHP: how to change the value of $_SERVER['SERVER_NAME'] in apache?
for example, i have mysite.com and beta.mysite.com. both point to the same index file using the virtualHost directive. what will i do in the apache conf so that when i access the $_SERVER['SERVER_NAME'], the value would still be mysite.com?

this should be flexible that only the beta would be removed.

答:
http://httpd.apache.org/docs/2.2/mod/core.html#usecanonicalname

Try this:

```<code><VirtualHost *:80>
  ServerName mysite.com
  ServerAlias beta.mysite.com

  UseCanonicalName On
</VirtualHost>
</code>```

I'm assuming you have 1 VH, and not: 1 for each site (since they are the same site).

Restart apache after.

ContentLicense: CC BY-SA 3.0

Body:
http://httpd.apache.org/docs/2.2/mod/core.html#usecanonicalname

Try this:

<VirtualHost *:80>
  ServerName mysite.com
  ServerAlias beta.mysite.com

  UseCanonicalName On
</VirtualHost>

I'm assuming you have 1 VH, and not: 1 for each site (since they are the same site).

Restart apache after.


问:
ReactJS Datepicker multiple dates selection
I am making a form in reactJS which has a datepicker from https://reactdatepicker.com/ and my question is:

Is there any option to have multiple dates selection in one datepicker ??

According to documentation there isn't or maybe I missed something ?

I would appreciate any help. Thanks in advance.

答:
I recently viewed your question.

you can use selectsStart option followed by startDate={-your start date here-}, endDate={-your end date here-}, and end your selects using Keyword selectsEnd. That's all.

```<code>    <DatePicker
      selectsStart
      startDate={startDate}
      endDate={endDate}
      selectsEnd
      inline
    />
</code>```

Body:
I recently viewed your question.

you can use selectsStart option followed by startDate={-your start date here-}, endDate={-your end date here-}, and end your selects using Keyword selectsEnd. That's all.

    <DatePicker
      selectsStart
      startDate={startDate}
      endDate={endDate}
      selectsEnd
      inline
    />


问:
I am trying to add a modal to my html page but the close button seems to have a problem
I made a modal in my web-page and it shows when I click the but when I click close nothing happens (it doesn't close) any idea?

function voice() {
  $("#myModal").modal('show');
  $('.try').css("opacity", "0.3");

}

function closeModal() {
  $("#myModal").modal('hide');
  $('.try').css("opacity", "1");
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
----- Try -----
<div id="myModal" class="modal fade" tabindex="-1" style="opacity:1;">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h3 class="modal-title">Try saying something...</h3>
        <button type="button" class="close" data-dismiss="modal" onclick="closeModal()">×</button>

      </div>
      <div class="modal-body">
        <i class="fas fa-microphone"></i>
        <button class="button button5"></button>
      </div>

    </div>
  </div>
</div></code>```

答:
Your HTML must have correct order to make it work in your PC!

<!doctype html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

  <title>Hello, world!</title>

  ----- Try -----

Try saying something...

          <button type="button" class="close" data-dismiss="modal" onclick="closeModal()">×</button>

          <button class="button button5"></button>

```

Body:
I made a modal in my web-page and it shows when I click the but when I click close nothing happens (it doesn't close) any idea?

function voice() {
  $("#myModal").modal('show');
  $('.try').css("opacity", "0.3");

}

function closeModal() {
  $("#myModal").modal('hide');
  $('.try').css("opacity", "1");
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">

----- Try -----

Try saying something...

        <button type="button" class="close" data-dismiss="modal" onclick="closeModal()">×</button>

        <button class="button button5"></button>

Body:
Your HTML must have correct order to make it work in your PC!

<!doctype html>
<html lang="en">

<head>
  <!-- Required meta tags -->
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

  <!-- Bootstrap CSS -->
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

  <title>Hello, world!</title>
</head>

<body>

  <a class="boxed-btn3 " onclick="voice()">----- Try -----</a>
  <div id="myModal" class="modal fade" tabindex="-1" style="opacity:1;">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <h3 class="modal-title">Try saying something...</h3>
          <button type="button" class="close" data-dismiss="modal" onclick="closeModal()">&times;</button>

        </div>
        <div class="modal-body">
          <i class="fas fa-microphone"></i>
          <button class="button button5"></button>
        </div>

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

  <script>
    function voice() {
      $("#myModal").modal('show');
      $('.try').css("opacity", "0.3");

    }

    function closeModal() {
      $("#myModal").modal('hide');
      $('.try').css("opacity", "1");
    }
  </script>

  <!-- Optional JavaScript -->
  <!-- jQuery first, then Popper.js, then Bootstrap JS -->
  <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous">
  </script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous">
  </script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous">
  </script>
</body>

</html>


问:
To count unique digits in a given number N in java
Given a number N, for example, take 1091, here the count of digits is 4 but the count of unique digits is 3 i.e. 1, 0 & 9 are unique (since 1 is repeated).

I have tried breaking the number into individual digits and adding it to ArrayList and later converting it to an array. Then, iterating through the array and increasing the count of unique digits by 1 every time I got a unique digit in the array, But I have not got the required output. Kindly someone help in finding the unique digits count in a given number in Java.

import java.util.ArrayList;

public class UniqueDigits {
    static int uniqueDigitCount(int n) {
        ArrayList<Integer> ar = new ArrayList<>();
        int temp = n;
        int count = 1;
        do {
            ar.add(temp % 10);
            temp /= 10;
        }
        while (temp > 0);
        Integer[] arr = new Integer[ar.size()];
        arr = ar.toArray(arr);
        if (arr.length > 0) {
            for (int i = 0; i < arr.length - 1; i++) {
                if (arr[i] != arr[i + 1]) {

                    count++;
                }
            }
            return count;
        } else {
            return 0;
        }
    }

    public static void main(String[] args) {
        System.out.println(uniqueDigitCount(1091));
    }
}
```

答:
```<code>import java.util.ArrayList;
import java.util.HashSet;

public class UniqueDigits {

    static int uniqueDigitCount(int n) {
        ArrayList<Integer> ar = new ArrayList<>();
        int temp = n;
        int count = 1;

        do {
            ar.add(temp % 10);
            temp /= 10;
        } while (temp > 0);
        Integer[] arr = new Integer[ar.size()];
        arr = ar.toArray(arr);
        HashSet<Integer> hs = new HashSet<Integer>();

        for (int i = 0; i < arr.length - 1; i++) {
            hs.add(arr[i]);
        }
        return hs.size();
    }

    public static void main(String[] args) {
        System.out.println(uniqueDigitCount(1091));
    }
}
</code>```


问:
varying in webgl is not working as expected
I am new to WebGL and now learning varying variables. In this, my expected output is the image below.

In the code below, I tried to pass colour from the vertex shader to fragment shader.The primitive type pass in drawArray is a triangle but it is not drawing triangles.I wrote this code to understand varying variables in WebGL and is derived from WebGLfundamental website. I don't know what went wrong since from my knowledge, this is what I am supposed to do.

The output I was expecting is :

Code is :

"use strict";

var vs = `#version 300 es

precision highp float;

in vec2 a_position;
in vec4 a_color;

out vec4 v_color;

void main(){
 gl_Position = vec4(a_position, 0, 1);
 v_color = a_color;
}
`;

var fs = `#version 300 es

precision highp float;

in  vec4 v_color;

out vec4 outColor;

void main(){
 outColor = v_color;
}
`;

function main() {
    var canvas = document.querySelector("#c");
    var gl = canvas.getContext("webgl2");
    if (!gl) {
        return;
    }

    var program = webglUtils.createProgramFromSources(gl, [vs, fs]);

    var vertexPosition = gl.getAttribLocation(program, 'a_position');
    var vertexColor = gl.getAttribLocation(program, 'a_color');

    var vao = gl.createVertexArray();
    gl.bindVertexArray(vao);

    var buffer = gl.createBuffer();
    gl.bindBuffer(gl.ARRAY_BUFFER, buffer);

    var position = [
        -150, -100,
        150, -100,
        -150, 100,
        -150, 100,
        150, -100,
        150, 100
    ];

    gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(position), gl.STATIC_DRAW);

    gl.enableVertexAttribArray(vertexPosition);

    var size = 2;
    var type = gl.FLOAT;
    var normalize = false;
    var stride = 0;
    var offset = 0;

    gl.vertexAttribPointer(vertexPosition, size, type, normalize, stride, offset);

    var buffer = gl.createBuffer();
    gl.bindBuffer(gl.ARRAY_BUFFER, buffer);

    var color = [
        0.7, 0.2, 0.9, 1,
      0.6, 0.7, 0.2, 1,
      0.5, 0.7, 0.9, 1,
      0.4, 0.7, 0.2, 1,
      0.7, 0.2, 0.9, 1,
      0.5, 0.7, 0.9, 1,
    ];

    gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(color), gl.STATIC_DRAW);

    gl.enableVertexAttribArray(vertexColor);

    var size =4;
    var type = gl.FLOAT;
    var normalize = false;
    var stride = 0;
    var offset = 0;

    gl.vertexAttribPointer(vertexColor, size, type, normalize, stride, offset);

    webglUtils.resizeCanvasToDisplaySize(gl.canvas);

    gl.viewport(0, 0, gl.canvas.width, gl.canvas.height);

    gl.clearColor(0, 0, 0, 0);

    gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);

    gl.useProgram(program);

    gl.bindVertexArray(vao);

    var offset = 0;
    var count = 6;
    gl.drawArrays(gl.TRIANGLES, offset, count);

}

main();```
<pre class="snippet-code-css lang-css prettyprint-override"><code> body{
     overflow: hidden;
    }

    canvas {
        width: 100vw;
        height: 100vh;
        display: block;
    }</code>```

<canvas id="c">
</canvas>```

答:
The issue is you're providing positions in pixels but WebGL requires positions in clip space. So you're drawing what you think you were drawing except only the center 2x2 units of your 300x200 rectangle are being shown.

For example if we just hack and divide the position by 300,200

```<code>gl_Position = vec4(a_position / vec2(300, 200);
</code>```

Then it works

"use strict";

var vs = `#version 300 es

precision highp float;

in vec2 a_position;
in vec4 a_color;

out vec4 v_color;

void main(){
 gl_Position = vec4(a_position / vec2(300, 200), 0, 1);
 v_color = a_color;
}
`;

var fs = `#version 300 es

precision highp float;

in  vec4 v_color;

out vec4 outColor;

void main(){
 outColor = v_color;
}
`;

function main() {
    var canvas = document.querySelector("#c");
    var gl = canvas.getContext("webgl2");
    if (!gl) {
        return;
    }

    var program = webglUtils.createProgramFromSources(gl, [vs, fs]);

    var vertexPosition = gl.getAttribLocation(program, 'a_position');
    var vertexColor = gl.getAttribLocation(program, 'a_color');

    var vao = gl.createVertexArray();
    gl.bindVertexArray(vao);

    var buffer = gl.createBuffer();
    gl.bindBuffer(gl.ARRAY_BUFFER, buffer);

    var position = [
        -150, -100,
        150, -100,
        -150, 100,
        -150, 100,
        150, -100,
        150, 100
    ];

    gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(position), gl.STATIC_DRAW);

    gl.enableVertexAttribArray(vertexPosition);

    var size = 2;
    var type = gl.FLOAT;
    var normalize = false;
    var stride = 0;
    var offset = 0;

    gl.vertexAttribPointer(vertexPosition, size, type, normalize, stride, offset);

    var buffer = gl.createBuffer();
    gl.bindBuffer(gl.ARRAY_BUFFER, buffer);

    var color = [
        0.7, 0.2, 0.9, 1,
      0.6, 0.7, 0.2, 1,
      0.5, 0.7, 0.9, 1,
      0.4, 0.7, 0.2, 1,
      0.7, 0.2, 0.9, 1,
      0.5, 0.7, 0.9, 1,
    ];

    gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(color), gl.STATIC_DRAW);

    gl.enableVertexAttribArray(vertexColor);

    var size =4;
    var type = gl.FLOAT;
    var normalize = false;
    var stride = 0;
    var offset = 0;

    gl.vertexAttribPointer(vertexColor, size, type, normalize, stride, offset);

    webglUtils.resizeCanvasToDisplaySize(gl.canvas);

    gl.viewport(0, 0, gl.canvas.width, gl.canvas.height);

    gl.clearColor(0, 0, 0, 0);

    gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);

    gl.useProgram(program);

    gl.bindVertexArray(vao);

    var offset = 0;
    var count = 6;
    gl.drawArrays(gl.TRIANGLES, offset, count);

}

main();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body{
     overflow: hidden;
    }

    canvas {
        width: 100vw;
        height: 100vh;
        display: block;
    }</code>```

<canvas id="c">
</canvas>```

The normal way to convert positions from pixel space to clip space is to use a matrix

Body:
I am new to WebGL and now learning varying variables. In this, my expected output is the image below.

In the code below, I tried to pass colour from the vertex shader to fragment shader.The primitive type pass in drawArray is a triangle but it is not drawing triangles.I wrote this code to understand varying variables in WebGL and is derived from WebGLfundamental website. I don't know what went wrong since from my knowledge, this is what I am supposed to do.

The output I was expecting is :

Code is :

"use strict";

var vs = `#version 300 es

precision highp float;

in vec2 a_position;
in vec4 a_color;

out vec4 v_color;

void main(){
 gl_Position = vec4(a_position, 0, 1);
 v_color = a_color;
}
`;

var fs = `#version 300 es

precision highp float;

in  vec4 v_color;

out vec4 outColor;

void main(){
 outColor = v_color;
}
`;

function main() {
    var canvas = document.querySelector("#c");
    var gl = canvas.getContext("webgl2");
    if (!gl) {
        return;
    }

    var program = webglUtils.createProgramFromSources(gl, [vs, fs]);

    var vertexPosition = gl.getAttribLocation(program, 'a_position');
    var vertexColor = gl.getAttribLocation(program, 'a_color');

    var vao = gl.createVertexArray();
    gl.bindVertexArray(vao);

    var buffer = gl.createBuffer();
    gl.bindBuffer(gl.ARRAY_BUFFER, buffer);

    var position = [
        -150, -100,
        150, -100,
        -150, 100,
        -150, 100,
        150, -100,
        150, 100
    ];

    gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(position), gl.STATIC_DRAW);

    gl.enableVertexAttribArray(vertexPosition);

    var size = 2;
    var type = gl.FLOAT;
    var normalize = false;
    var stride = 0;
    var offset = 0;

    gl.vertexAttribPointer(vertexPosition, size, type, normalize, stride, offset);

    var buffer = gl.createBuffer();
    gl.bindBuffer(gl.ARRAY_BUFFER, buffer);

    var color = [
        0.7, 0.2, 0.9, 1,
      0.6, 0.7, 0.2, 1,
      0.5, 0.7, 0.9, 1,
      0.4, 0.7, 0.2, 1,
      0.7, 0.2, 0.9, 1,
      0.5, 0.7, 0.9, 1,
    ];

    gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(color), gl.STATIC_DRAW);

    gl.enableVertexAttribArray(vertexColor);

    var size =4;
    var type = gl.FLOAT;
    var normalize = false;
    var stride = 0;
    var offset = 0;

    gl.vertexAttribPointer(vertexColor, size, type, normalize, stride, offset);

    webglUtils.resizeCanvasToDisplaySize(gl.canvas);

    gl.viewport(0, 0, gl.canvas.width, gl.canvas.height);

    gl.clearColor(0, 0, 0, 0);

    gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);

    gl.useProgram(program);

    gl.bindVertexArray(vao);

    var offset = 0;
    var count = 6;
    gl.drawArrays(gl.TRIANGLES, offset, count);

}

main();

 body{
     overflow: hidden;
    }

    canvas {
        width: 100vw;
        height: 100vh;
        display: block;
    }

<canvas id="c">
</canvas>

Body:
The issue is you're providing positions in pixels but WebGL requires positions in clip space. So you're drawing what you think you were drawing except only the center 2x2 units of your 300x200 rectangle are being shown.

For example if we just hack and divide the position by 300,200

gl_Position = vec4(a_position / vec2(300, 200);

Then it works

"use strict";

var vs = `#version 300 es

precision highp float;

in vec2 a_position;
in vec4 a_color;

out vec4 v_color;

void main(){
 gl_Position = vec4(a_position / vec2(300, 200), 0, 1);
 v_color = a_color;
}
`;

var fs = `#version 300 es

precision highp float;

in  vec4 v_color;

out vec4 outColor;

void main(){
 outColor = v_color;
}
`;

function main() {
    var canvas = document.querySelector("#c");
    var gl = canvas.getContext("webgl2");
    if (!gl) {
        return;
    }

    var program = webglUtils.createProgramFromSources(gl, [vs, fs]);

    var vertexPosition = gl.getAttribLocation(program, 'a_position');
    var vertexColor = gl.getAttribLocation(program, 'a_color');

    var vao = gl.createVertexArray();
    gl.bindVertexArray(vao);

    var buffer = gl.createBuffer();
    gl.bindBuffer(gl.ARRAY_BUFFER, buffer);

    var position = [
        -150, -100,
        150, -100,
        -150, 100,
        -150, 100,
        150, -100,
        150, 100
    ];

    gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(position), gl.STATIC_DRAW);

    gl.enableVertexAttribArray(vertexPosition);

    var size = 2;
    var type = gl.FLOAT;
    var normalize = false;
    var stride = 0;
    var offset = 0;

    gl.vertexAttribPointer(vertexPosition, size, type, normalize, stride, offset);

    var buffer = gl.createBuffer();
    gl.bindBuffer(gl.ARRAY_BUFFER, buffer);

    var color = [
        0.7, 0.2, 0.9, 1,
      0.6, 0.7, 0.2, 1,
      0.5, 0.7, 0.9, 1,
      0.4, 0.7, 0.2, 1,
      0.7, 0.2, 0.9, 1,
      0.5, 0.7, 0.9, 1,
    ];

    gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(color), gl.STATIC_DRAW);

    gl.enableVertexAttribArray(vertexColor);

    var size =4;
    var type = gl.FLOAT;
    var normalize = false;
    var stride = 0;
    var offset = 0;

    gl.vertexAttribPointer(vertexColor, size, type, normalize, stride, offset);

    webglUtils.resizeCanvasToDisplaySize(gl.canvas);

    gl.viewport(0, 0, gl.canvas.width, gl.canvas.height);

    gl.clearColor(0, 0, 0, 0);

    gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);

    gl.useProgram(program);

    gl.bindVertexArray(vao);

    var offset = 0;
    var count = 6;
    gl.drawArrays(gl.TRIANGLES, offset, count);

}

main();

body{
     overflow: hidden;
    }

    canvas {
        width: 100vw;
        height: 100vh;
        display: block;
    }

<script src="https://webgl2fundamentals.org/webgl/resources/webgl-utils.js"></script>
<canvas id="c">
</canvas>

The normal way to convert positions from pixel space to clip space is to use a matrix


问:
Why does exponential smoothing in statsmodels return identical values for a time series forecast?
I am using the following code to get simple exponential smoothing in statsmodels.

```<code>years = [1979,1980,1981,1982,1983,1984,1985,1986,1987,1988]
mylist = [3.508046180009842, 64.08556070923805, 15.407086104154587, 0, 3.8572598099708557, 11.009202659130096, 5.324577212333679, 4.33474725484848, 4.024865210056305, 5.065838277339935]

import pandas as pd
from statsmodels.tsa.api import ExponentialSmoothing, SimpleExpSmoothing
myinput = pd.Series(mylist, years)
fit_model = SimpleExpSmoothing(myinput).fit()
smoothed = fit_model.fittedvalues
print(smoothed.tolist())
</code>```

The result I got was quite surprising. i.e. I get the same value for every year.

```<code>[11.661719028226004, 11.661719028226004, 11.661719028226004, 11.661719028226004, 11.661719028226004, 11.661719028226004, 11.661719028226004, 11.661719028226004, 11.661719028226004, 11.661719028226004]
</code>```

I am wondering why I get the same value for every year. Please let me know how to fix this?

I am happy to provide more details if needed.

答:
From the documentation:

"Simple exponential smoothing has a “flat” forecast function.

That is, all forecasts take the same value, equal to the last level component. Remember that these forecasts will only be suitable if the time series has no trend or seasonal component."

https://otexts.com/fpp2/ses.html

Body:
I am using the following code to get simple exponential smoothing in statsmodels.

years = [1979,1980,1981,1982,1983,1984,1985,1986,1987,1988]
mylist = [3.508046180009842, 64.08556070923805, 15.407086104154587, 0, 3.8572598099708557, 11.009202659130096, 5.324577212333679, 4.33474725484848, 4.024865210056305, 5.065838277339935]

import pandas as pd
from statsmodels.tsa.api import ExponentialSmoothing, SimpleExpSmoothing
myinput = pd.Series(mylist, years)
fit_model = SimpleExpSmoothing(myinput).fit()
smoothed = fit_model.fittedvalues
print(smoothed.tolist())

The result I got was quite surprising. i.e. I get the same value for every year.

[11.661719028226004, 11.661719028226004, 11.661719028226004, 11.661719028226004, 11.661719028226004, 11.661719028226004, 11.661719028226004, 11.661719028226004, 11.661719028226004, 11.661719028226004]

I am wondering why I get the same value for every year. Please let me know how to fix this?

I am happy to provide more details if needed.


问:
Creating new entities while enabling injection
I have a method on a stateless session bean which creates a new instance of an entity and persists it. You might normally use new MyEntity() to create the object but I would like injection to populate some of the properties of the entity for me.

I got partial success using

```<code>@Inject
@New
private MyEntity myNewEntity;
</code>```

in the session bean and then using that instance in my method.

The problem I have now is that the second time the method is called, myNewEntity isn't a new object, its the same object as the one created the first time. As a result I'm getting

com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry '9' for key 'PRIMARY'

Or at least that's why I think I'm getting this exception. Certainly if I use new MyEntity() I don't get the exception but my injection doesn't happen.

Am I on the wrong track? How can I create a new local entity object while enabling injection?

Any help would be great!

答:
First of all - I have serious doubts that it's a good idea to use CDI to control the lifecycle of a Entity. See this quote from the documentation (here):

According to this definition, JPA
  entities are technically managed
  beans. However, entities have their
  own special lifecycle, state and
  identity model and are usually
  instantiated by JPA or using new.
  Therefore we don't recommend directly
  injecting an entity class. We
  especially recommend against assigning
  a scope other than @Dependent to an
  entity class, since JPA is not able to
  persist injected CDI proxies.

What you should do to create new instances of entities is adding a layer of indirection, either with @Produces or @Unwraps (Seam Solder, if you need it to be truly stateless), and thereby making sure that you code explicitly calls new.

Body:
I have a method on a stateless session bean which creates a new instance of an entity and persists it. You might normally use new MyEntity() to create the object but I would like injection to populate some of the properties of the entity for me.

I got partial success using

@Inject
@New
private MyEntity myNewEntity;

in the session bean and then using that instance in my method.

The problem I have now is that the second time the method is called, myNewEntity isn't a new object, its the same object as the one created the first time. As a result I'm getting

com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry '9' for key 'PRIMARY'

Or at least that's why I think I'm getting this exception. Certainly if I use new MyEntity() I don't get the exception but my injection doesn't happen.

Am I on the wrong track? How can I create a new local entity object while enabling injection?

Any help would be great!


问:
ERROR: No matching distribution found for tensorflow==1.7.1 (from unityagents)
Tried to install  unityagents  agents using pip install unityagents command but I'm getting this error:

```<code>ERROR: No matching distribution found for tensorflow==1.7.1 (from unityagents)
</code>```

Im using tensorflow version 2.2.1

答:
It looks like the pypi release you're installing is around 2 years old.

The way you're supposed to install the package from the mlagents package instead. See the full instructions.

Body:
Tried to install  unityagents  agents using pip install unityagents command but I'm getting this error:

ERROR: No matching distribution found for tensorflow==1.7.1 (from unityagents)

Im using tensorflow version 2.2.1


问:
Creating New Column in SQL with Regex
I have the result set which contains a list of years. But some of the entries have years menioned as VII2016 or II2014. How can write a query for creating a new column with original years i.e 2000,2002 and with modified 2014 and 2016.

Here is my code:

```<code>WITH female_year_count as
(SELECT m.year as f FROM Movie m
JOIN M_Cast c ON m.MID=c.MID
JOIN Person p ON trim(c.PID)=p.PID
WHERE trim(p.Gender) = 'Female'
)
SELECT * FROM female_year_count
</code>```

I am using SQLite3 library in Python. Please let me know how to write that query.

答:
If you are sure that the year is always the four last chars of the field value, you can use substr. Here's a proof of concept:

```<code>>>> import sqlite3
>>> c = sqlite3.connect(':memory:').cursor()
>>> c.execute("CREATE TEMP TABLE t(x)").execute(
... "INSERT INTO t VALUES ('VI2016'), ('III2014'), ('2018'), (NULL)")
<sqlite3.Cursor object at ...>
</code>```

Original data is:

```<code>>>> c.execute("SELECT x FROM t").fetchall()
[('VI2016',), ('III2014',), ('2018',), (None,)]
</code>```

Take the 4 rightmost chars:

```<code>>>> c.execute("SELECT substr(x, length(x)-3, 4) FROM t").fetchall()
[('2016',), ('2014',), ('2018',), (None,)]
</code>```

You may want to cast the year to an int:

```<code>>>> c.execute("SELECT CAST(substr(x, length(x)-3, 4) AS int) FROM t").fetchall()
[(2016,), (2014,), (2018,), (None,)]
</code>```

Title: Creating New Column in SQL with Regex

Body:
I have the result set which contains a list of years. But some of the entries have years menioned as VII2016 or II2014. How can write a query for creating a new column with original years i.e 2000,2002 and with modified 2014 and 2016.

Here is my code:

WITH female_year_count as
(SELECT m.year as f FROM Movie m
JOIN M_Cast c ON m.MID=c.MID
JOIN Person p ON trim(c.PID)=p.PID
WHERE trim(p.Gender) = 'Female'
)
SELECT * FROM female_year_count

I am using SQLite3 library in Python. Please let me know how to write that query.

Body:
If you are sure that the year is always the four last chars of the field value, you can use substr. Here's a proof of concept:

>>> import sqlite3
>>> c = sqlite3.connect(':memory:').cursor()
>>> c.execute("CREATE TEMP TABLE t(x)").execute(
... "INSERT INTO t VALUES ('VI2016'), ('III2014'), ('2018'), (NULL)")
<sqlite3.Cursor object at ...>

Original data is:

>>> c.execute("SELECT x FROM t").fetchall()
[('VI2016',), ('III2014',), ('2018',), (None,)]

Take the 4 rightmost chars:

>>> c.execute("SELECT substr(x, length(x)-3, 4) FROM t").fetchall()
[('2016',), ('2014',), ('2018',), (None,)]

You may want to cast the year to an int:

>>> c.execute("SELECT CAST(substr(x, length(x)-3, 4) AS int) FROM t").fetchall()
[(2016,), (2014,), (2018,), (None,)]


问:
Pandas/datetime issue
I have a pandas dataset where by I am trying to relate two columns... One (df['IssueDatetime']) is properly formatted as a date time, the other is only has the %dd/%HH (df['forecastTime']) :

```<code>            IssueDatetime                   Regions forecastTime WindDirSpeed
0     2019-01-01 06:00:00                EAST COAST        01/06         NW25
1     2019-01-01 06:00:00                EAST COAST        01/15         SW15
2     2019-01-01 06:00:00                EAST COAST        02/00         SE25
3     2019-01-01 06:00:00                EAST COAST        02/06      SE35-45
4     2019-01-01 06:00:00                EAST COAST        02/15         SW40
...                   ...                       ...          ...          ...
12292 2019-12-30 06:00:00  SOUTHEASTERN GRAND BANKS        01/00       N15-20
12293 2019-12-30 06:00:00  SOUTHWESTERN GRAND BANKS        30/06      NW15-20
12294 2019-12-30 06:00:00  SOUTHWESTERN GRAND BANKS        31/00          N25
12295 2019-12-30 06:00:00  SOUTHWESTERN GRAND BANKS        31/15       N15-20
12296 2019-12-30 06:00:00  SOUTHWESTERN GRAND BANKS        01/00     VRB10-15
</code>```

Is it possible to relate the df['IssueDatetime'] to the df['forecastTime'], for a result such that:

```<code>            IssueDatetime                   Regions     forecastTime             WindDirSpeed
0     2019-01-01 06:00:00                EAST COAST      2019-01-01 06:00:00             NW25
1     2019-01-01 06:00:00                EAST COAST      2019-01-01 15:00:00             SW15
2     2019-01-01 06:00:00                EAST COAST      2019-01-02 00:00:00             SE25
3     2019-01-01 06:00:00                EAST COAST      2019-01-02 06:00:00          SE35-45
</code>```

The issue arises when relating the columns at the end of the months. Any suggestions would be helpful.

Title: Pandas/datetime issue

Body:
I have a pandas dataset where by I am trying to relate two columns... One (df['IssueDatetime']) is properly formatted as a date time, the other is only has the %dd/%HH (df['forecastTime']) :

            IssueDatetime                   Regions forecastTime WindDirSpeed
0     2019-01-01 06:00:00                EAST COAST        01/06         NW25
1     2019-01-01 06:00:00                EAST COAST        01/15         SW15
2     2019-01-01 06:00:00                EAST COAST        02/00         SE25
3     2019-01-01 06:00:00                EAST COAST        02/06      SE35-45
4     2019-01-01 06:00:00                EAST COAST        02/15         SW40
...                   ...                       ...          ...          ...
12292 2019-12-30 06:00:00  SOUTHEASTERN GRAND BANKS        01/00       N15-20
12293 2019-12-30 06:00:00  SOUTHWESTERN GRAND BANKS        30/06      NW15-20
12294 2019-12-30 06:00:00  SOUTHWESTERN GRAND BANKS        31/00          N25
12295 2019-12-30 06:00:00  SOUTHWESTERN GRAND BANKS        31/15       N15-20
12296 2019-12-30 06:00:00  SOUTHWESTERN GRAND BANKS        01/00     VRB10-15

Is it possible to relate the df['IssueDatetime'] to the df['forecastTime'], for a result such that:

            IssueDatetime                   Regions     forecastTime             WindDirSpeed
0     2019-01-01 06:00:00                EAST COAST      2019-01-01 06:00:00             NW25
1     2019-01-01 06:00:00                EAST COAST      2019-01-01 15:00:00             SW15
2     2019-01-01 06:00:00                EAST COAST      2019-01-02 00:00:00             SE25
3     2019-01-01 06:00:00                EAST COAST      2019-01-02 06:00:00          SE35-45

The issue arises when relating the columns at the end of the months. Any suggestions would be helpful.

Body:
Try this:

df['IssueDatetime'] = pd.to_datetime(df['IssueDatetime'])
df['forecastTime'] = pd.to_datetime(df['forecastTime'], format='%d/%H')
df['forecastTime'] = df['forecastTime'].astype(str).str.replace('1900', '2019')
print(df)

        IssueDatetime                   Regions         forecastTime WindDirSpeed
0 2019-01-01 06:00:00                EAST COAST  2019-01-01 06:00:00         NW25
1 2019-01-01 06:00:00                EAST COAST  2019-01-01 15:00:00         SW15
2 2019-01-01 06:00:00                EAST COAST  2019-01-02 00:00:00         SE25
3 2019-01-01 06:00:00                EAST COAST  2019-01-02 06:00:00      SE35-45
4 2019-01-01 06:00:00                EAST COAST  2019-01-02 15:00:00         SW40
5 2019-12-30 06:00:00  SOUTHEASTERN GRAND BANKS  2019-01-01 00:00:00       N15-20
6 2019-12-30 06:00:00  SOUTHWESTERN GRAND BANKS  2019-01-30 06:00:00      NW15-20
7 2019-12-30 06:00:00  SOUTHWESTERN GRAND BANKS  2019-01-31 00:00:00          N25
8 2019-12-30 06:00:00  SOUTHWESTERN GRAND BANKS  2019-01-31 15:00:00       N15-20
9 2019-12-30 06:00:00  SOUTHWESTERN GRAND BANKS  2019-01-01 00:00:00     VRB10-15


问:
Why does my Python freeze when I do an overflow calculation?
I'm a MATLAB user trying to understand Python so sorry if this is obvious.

If I say

```<code>print(9**9)
</code>```

I get:
387420489

Great.

If I say print(9**9**9)
Python just sits there indefinitely and freezes (I use Spyder version 4). Ctrl-C doesn't stop it.
Why does it not just immediately return Inf? Is this expected behavior?

答:
Why does my Python freeze when I do an overflow calculation?

because no overflow occurred and python hasn't given up. Python will extend the precision until either the calculation succeeds or the machine runs out of memory.

Body:
I'm a MATLAB user trying to understand Python so sorry if this is obvious.

If I say

print(9**9)

I get:
387420489

Great.

If I say print(9**9**9)
Python just sits there indefinitely and freezes (I use Spyder version 4). Ctrl-C doesn't stop it.
Why does it not just immediately return Inf? Is this expected behavior?


问:
Can you run quser with a PSCredential object?

Question

I'm writing SolarWinds SAM script that can monitor logged in users on a remote machine.  I wanted to use quser  rather than a WMI/CIM based solution because quser provides exactly the data that i'm looking for.

The kicker is that the monitoring application provides a PSCredential object to use in order to authenticate with remote machines, something that quser can't use.

Code

When running with no credential object I get the following.

```<code>quser /server:'testserver1'
</code>```

Output

```<code>No User exists for *
</code>```

答:
Answer

The answer to this dilemma was painfully obvious once I realized it.  You can simply use the Invoke-Command cmdlet with the -Credential and -ScriptBlock parameter to run the quser command on the remote server with the appropriate user context.

One final note - if you need help parsing the output of quser into a more PowerShell friendly object, see Get-LoggedOnUser.  It's a fantastic script that handles all of the string parsing necessary to get the properties from the quser output.

Code

```<code>$Server = 'testserver1'
$Credential = Get-Credential
Invoke-Command -ComputerName $Server -ScriptBlock { quser } -Credential $Credential
</code>```

Output

```<code> USERNAME              SESSIONNAME        ID  STATE   IDLE TIME  LOGON TIME
 a-srz                 rdp-tcp#0           2  Active         19  6/2/2020 10:19 AM
</code>```

Body:
Question

I'm writing SolarWinds SAM script that can monitor logged in users on a remote machine.  I wanted to use quser  rather than a WMI/CIM based solution because quser provides exactly the data that i'm looking for.

The kicker is that the monitoring application provides a PSCredential object to use in order to authenticate with remote machines, something that quser can't use.

Code

When running with no credential object I get the following.

quser /server:'testserver1'

Output

No User exists for *

Body:
Answer

The answer to this dilemma was painfully obvious once I realized it.  You can simply use the Invoke-Command cmdlet with the -Credential and -ScriptBlock parameter to run the quser command on the remote server with the appropriate user context.

One final note - if you need help parsing the output of quser into a more PowerShell friendly object, see Get-LoggedOnUser.  It's a fantastic script that handles all of the string parsing necessary to get the properties from the quser output.

Code

$Server = 'testserver1'
$Credential = Get-Credential
Invoke-Command -ComputerName $Server -ScriptBlock { quser } -Credential $Credential

Output

 USERNAME              SESSIONNAME        ID  STATE   IDLE TIME  LOGON TIME
 a-srz                 rdp-tcp#0           2  Active         19  6/2/2020 10:19 AM


问:
Will Python open a file before it's finished writing?
I am writing a script that will be polling a directory looking for new files.

In this scenario, is it necessary to do some sort of error checking to make sure the files are completely written prior to accessing them?

I don't want to work with a file before it has been written completely to disk, but because the info I want from the file is near the beginning, it seems like it could be possible to pull the data I need without realizing the file isn't done being written.

Is that something I should worry about, or will the file be locked because the OS is writing to the hard drive?

This is on a Linux system.

答:
Typically on Linux, unless you're using locking of some kind, two processes can quite happily have the same file open at once, even for writing. There are three ways of avoiding problems with this:

Locking

By having the writer apply a lock to the file, it is possible to prevent the reader from reading the file partially. However, most locks are advisory so it is still entirely possible to see partial results anyway. (Mandatory locks exist, but a strongly not recommended on the grounds that they're far too fragile.) It's relatively difficult to write correct locking code, and it is normal to delegate such tasks to a specialist library (i.e., to a database engine!) In particular, you don't want to use locking on networked filesystems; it's a source of colossal trouble when it works and can often go thoroughly wrong.

Convention

A file can instead be created in the same directory with another name that you don't automatically look for on the reading side (e.g., .foobar.txt.tmp) and then renamed atomically to the right name (e.g., foobar.txt) once the writing is done. This can work quite well, so long as you take care to deal with the possibility of previous runs failing to correctly write the file. If there should only ever be one writer at a time, this is fairly simple to implement.

Not Worrying About It

The most common type of file that is frequently written is a log file. These can be easily written in such a way that information is strictly only ever appended to the file, so any reader can safely look at the beginning of the file without having to worry about anything changing under its feet. This works very well in practice.

There's nothing special about Python in any of this. All programs running on Linux have the same issues.


问:
Group array objects by two elements and sum values (Javascript)
I have the following case:

I have an array consisting of all the appointments of the currently logged in user, like this:

```<code> this.appointments = [
{
 CreatedBy: "bob",
 Description: "smthng",
 EndTime: "2020-06-01T17:00:00.000Z",
 EndTimezone: null,
 Id: 3,
 IsAllDay: false,
 Client: "Steven",
 Location: "smthng",
 RecurrenceRule: "FREQ=DAILY;INTERVAL=1;COUNT=5;",
 StartTime: "2020-06-01T09:00:00.000Z",
 StartTimezone: null,
 Subject: "smthng",
 km: 88,
 week: 23,
 _id: "5ecc6f4a08c79c6328974699"
},
{
 CreatedBy: "bob",
 Description: "smthng",
 EndTime: "2020-06-08T10:30:00.000Z",
 EndTimezone: null,
 Id: 4,
 IsAllDay: false,
 Client: "Steven",
 Location: "smthng",
 RecurrenceRule: null,
 StartTime: "2020-06-08T10:00:00.000Z",
 StartTimezone: null,
 Subject: "smthng"  ,
 km: 88,
 week: 24,
 _id: "5ed450d299d5303bd0338a7f"
}
  ]
</code>```

What I ultimately want to do is group the array by Client per Week. So accumulate all the time and km of the appointments (using dayjs library) of one week per client. This is the .reduce function I have now which groups the array only by Client but not yet per week:

```<code>this.appointments.reduce(function (res, value) {
  let diff = dayjs(value.EndTime).diff(dayjs(value.StartTime), "hour",true) % 60;
  let count;

  if(value.RecurrenceRule != null) {
    count =  parseInt(value.RecurrenceRule.split("COUNT=")[1]);
    if(value.RecurrenceException){
    if(value.RecurrenceException.match(/,/g) ) {
      if(value.RecurrenceException.match(/,/g).length == 0) {
        console.log(value.RecurrenceException.match(/,/g).length);
        count = count -1;
      }
    } else if(value.RecurrenceException && value.RecurrenceException.match(/,/g).length == 1) {
      console.log(value.RecurrenceException.match(/,/g).length);
      count = count -2;
    } else if(value.RecurrenceException && value.RecurrenceException.match(/,/g).length == 2) {
      console.log(value.RecurrenceException.match(/,/g).length);
      count = count -3;
    } else
    if(value.RecurrenceException && value.RecurrenceException.match(/,/g).length == 3) {
       count = count -4;
    };
  }
  }
  else if(value.RecurrenceRule == null) {
       count = 1;
  }
  if (!res[value.Client]) {
    res[value.Client] = {

      week: value.week,
      km: value.km * count,
      Client: value.Client,
      count: count,
      difference: diff * count
    };
    result.push(res[value.Client]);

  } else {
    res[value.Client].km += value.km * count;
    res[value.Client].difference += diff * count;
  }

  return res;
}, {});
</code>```

How do I go about this situation?
the output now is that instead of creating two rows (week 23 & 24), it sums all the appointments of Steven in week 23 which is incorrect because 0.5 hour took place in another week.

```<code>{Client: "Steven"
count: 5
difference: 40.5
km: 528
week: 23}
</code>```

So the ideal output is:

```<code>{
Client: "Steven"
count: 5
difference: 40
km: 440
week: 23
},

{
Client: "Steven"
count: 1
difference: 0.5
km: 88
week: 24
}
</code>```

You can have rows with the same week number as long as the Client differs.

I hope i made it clear and if you need more context, please mention

答:
Building on @ajai's answer (and using his input first for comparison), hopefully giving you what you need (and using reduce).

const data = [
  {
   CreatedBy: "bob",
   Description: "smthng",
   EndTime: "2020-06-01T17:00:00.000Z",
   EndTimezone: null,
   Id: 3,
   IsAllDay: false,
   Client: "Steven",
   Location: "smthng",
   RecurrenceRule: "FREQ=DAILY;INTERVAL=1;COUNT=5;",
   StartTime: "2020-06-01T09:00:00.000Z",
   StartTimezone: null,
   Subject: "smthng",
   km: 88,
   week: 23,
   _id: "5ecc6f4a08c79c6328974699"
  },
  {
   CreatedBy: "bob",
   Description: "smthng",
   EndTime: "2020-06-08T10:30:00.000Z",
   EndTimezone: null,
   Id: 4,
   IsAllDay: false,
   Client: "Steven",
   Location: "smthng",
   RecurrenceRule: null,
   StartTime: "2020-06-08T10:00:00.000Z",
   StartTimezone: null,
   Subject: "smthng"  ,
   km: 88,
   week: 24,
   _id: "5ed450d299d5303bd0338a7f"
  },
  {
   CreatedBy: "bob",
   Description: "smthng",
   EndTime: "2020-06-01T17:00:00.000Z",
   EndTimezone: null,
   Id: 3,
   IsAllDay: false,
   Client: "Steven",
   Location: "smthng",
   RecurrenceRule: "FREQ=DAILY;INTERVAL=1;COUNT=5;",
   StartTime: "2020-06-01T09:00:00.000Z",
   StartTimezone: null,
   Subject: "smthng",
   km: 40,
   week: 23,
   _id: "5ecc6f4a08c79c6328974699"
  },
  {
   CreatedBy: "bob",
   Description: "smtng",
   EndTime: "2020-06-01T17:00:00.000Z",
   EndTimezone: null,
   Id: 3,
   IsAllDay: false,
   Client: "ajai",
   Location: "smthng",
   RecurrenceRule: "FREQ=DAILY;INTERVAL=1;COUNT=5;",
   StartTime: "2020-06-01T09:00:00.000Z",
   StartTimezone: null,
   Subject: "smthng",
   km: 88,
   week: 23,
   _id: "5ecc6f4a08c79c6328974699"
  }
]

const result = Object.values(data.reduce((aggObj, item) => {
  const stringID = `${item.Client}_${item.week}`;
  const diff = (new Date(item.EndTime) - new Date(item.StartTime))/(1000*60*60);
  const RecurrenceObj = item.RecurrenceRule ?
    item.RecurrenceRule.split(";").map(a => {
      //console.log(a)
      return a.split("=") || ["_", null];
    }).reduce((aggObj, [key,val]) => {
      aggObj[key] = val;
      return aggObj;
    })
    : {COUNT: 1};

  if (aggObj[stringID]){
    aggObj[stringID].km += (item.km * RecurrenceObj.COUNT);
    aggObj[stringID].count += parseInt(RecurrenceObj.COUNT);
    aggObj[stringID].difference += (diff * RecurrenceObj.COUNT);
  }
  else {
    aggObj[stringID] = {
      Client: item.Client,
      km: item.km * RecurrenceObj.COUNT,
      count: parseInt(RecurrenceObj.COUNT),
      difference: diff * RecurrenceObj.COUNT,
      week: item.week
    };
  }
  return aggObj;
}, {}));

/*
for(var i=0;i<=data.length-1;i++){
   let pos = result.findIndex(el=> `${el.Client}-${el.week}`==`${data[i].Client}-${data[i].week}`)
   if(pos==-1){
     result.push({Client: data[i]['Client'],count: 1,difference: 0,km: data[i]['km'],week: data[i]['week']})
   }else{
     result[pos]['count'] = result[pos]['count'] + 1;
     result[pos]['km'] = result[pos]['km'] + data[i]['km'];
   }
}
*/
console.log(result)```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

OUTPUT:

[
  {
    "Client": "Steven",
    "km": 640,
    "count": 10,
    "difference": 80,
    "week": 23
  },
  {
    "Client": "Steven",
    "km": 88,
    "count": 1,
    "difference": 0.5,
    "week": 24
  },
  {
    "Client": "ajai",
    "km": 440,
    "count": 5,
    "difference": 40,
    "week": 23
  }
]
```

<p>Now with your exact input:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const data = [
  {
   CreatedBy: "bob",
   Description: "smthng",
   EndTime: "2020-06-01T17:00:00.000Z",
   EndTimezone: null,
   Id: 3,
   IsAllDay: false,
   Client: "Steven",
   Location: "smthng",
   RecurrenceRule: "FREQ=DAILY;INTERVAL=1;COUNT=5;",
   StartTime: "2020-06-01T09:00:00.000Z",
   StartTimezone: null,
   Subject: "smthng",
   km: 88,
   week: 23,
   _id: "5ecc6f4a08c79c6328974699"
  },
  {
   CreatedBy: "bob",
   Description: "smthng",
   EndTime: "2020-06-08T10:30:00.000Z",
   EndTimezone: null,
   Id: 4,
   IsAllDay: false,
   Client: "Steven",
   Location: "smthng",
   RecurrenceRule: null,
   StartTime: "2020-06-08T10:00:00.000Z",
   StartTimezone: null,
   Subject: "smthng"  ,
   km: 88,
   week: 24,
   _id: "5ed450d299d5303bd0338a7f"
  }
]

const result = Object.values(data.reduce((aggObj, item) => {
  const stringID = `${item.Client}_${item.week}`;
  const diff = (new Date(item.EndTime) - new Date(item.StartTime))/(1000*60*60);
  const RecurrenceObj = item.RecurrenceRule ?
    item.RecurrenceRule.split(";").map(a => {
      //console.log(a)
      return a.split("=") || ["_", null];
    }).reduce((aggObj, [key,val]) => {
      aggObj[key] = val;
      return aggObj;
    })
    : {COUNT: 1};

  if (aggObj[stringID]){
    aggObj[stringID].km += (item.km * RecurrenceObj.COUNT);
    aggObj[stringID].count += parseInt(RecurrenceObj.COUNT);
    aggObj[stringID].difference += (diff * RecurrenceObj.COUNT);
  }
  else {
    aggObj[stringID] = {
      Client: item.Client,
      km: item.km * RecurrenceObj.COUNT,
      count: parseInt(RecurrenceObj.COUNT),
      difference: diff * RecurrenceObj.COUNT,
      week: item.week
    };
  }
  return aggObj;
}, {}));

/*
for(var i=0;i<=data.length-1;i++){
   let pos = result.findIndex(el=> `${el.Client}-${el.week}`==`${data[i].Client}-${data[i].week}`)
   if(pos==-1){
     result.push({Client: data[i]['Client'],count: 1,difference: 0,km: data[i]['km'],week: data[i]['week']})
   }else{
     result[pos]['count'] = result[pos]['count'] + 1;
     result[pos]['km'] = result[pos]['km'] + data[i]['km'];
   }
}
*/
console.log(result)</code>```

.as-console-wrapper { max-height: 100% !important; top: 0; }```
</div>
</div>
</p>

<p>OUTPUT:</p>

<pre class="lang-js prettyprint-override"><code>[
  {
    "Client": "Steven",
    "km": 440,
    "count": 5,
    "difference": 40,
    "week": 23
  },
  {
    "Client": "Steven",
    "km": 88,
    "count": 1,
    "difference": 0.5,
    "week": 24
  }
]
</code>```

Body:
I have the following case:

I have an array consisting of all the appointments of the currently logged in user, like this:

 this.appointments = [
{
 CreatedBy: "bob",
 Description: "smthng",
 EndTime: "2020-06-01T17:00:00.000Z",
 EndTimezone: null,
 Id: 3,
 IsAllDay: false,
 Client: "Steven",
 Location: "smthng",
 RecurrenceRule: "FREQ=DAILY;INTERVAL=1;COUNT=5;",
 StartTime: "2020-06-01T09:00:00.000Z",
 StartTimezone: null,
 Subject: "smthng",
 km: 88,
 week: 23,
 _id: "5ecc6f4a08c79c6328974699"
},
{
 CreatedBy: "bob",
 Description: "smthng",
 EndTime: "2020-06-08T10:30:00.000Z",
 EndTimezone: null,
 Id: 4,
 IsAllDay: false,
 Client: "Steven",
 Location: "smthng",
 RecurrenceRule: null,
 StartTime: "2020-06-08T10:00:00.000Z",
 StartTimezone: null,
 Subject: "smthng"  ,
 km: 88,
 week: 24,
 _id: "5ed450d299d5303bd0338a7f"
}
  ]

What I ultimately want to do is group the array by Client per Week. So accumulate all the time and km of the appointments (using dayjs library) of one week per client. This is the .reduce function I have now which groups the array only by Client but not yet per week:

this.appointments.reduce(function (res, value) {
  let diff = dayjs(value.EndTime).diff(dayjs(value.StartTime), "hour",true) % 60;
  let count;

  if(value.RecurrenceRule != null) {
    count =  parseInt(value.RecurrenceRule.split("COUNT=")[1]);
    if(value.RecurrenceException){
    if(value.RecurrenceException.match(/,/g) ) {
      if(value.RecurrenceException.match(/,/g).length == 0) {
        console.log(value.RecurrenceException.match(/,/g).length);
        count = count -1;
      }
    } else if(value.RecurrenceException && value.RecurrenceException.match(/,/g).length == 1) {
      console.log(value.RecurrenceException.match(/,/g).length);
      count = count -2;
    } else if(value.RecurrenceException && value.RecurrenceException.match(/,/g).length == 2) {
      console.log(value.RecurrenceException.match(/,/g).length);
      count = count -3;
    } else
    if(value.RecurrenceException && value.RecurrenceException.match(/,/g).length == 3) {
       count = count -4;
    };
  }
  }
  else if(value.RecurrenceRule == null) {
       count = 1;
  }
  if (!res[value.Client]) {
    res[value.Client] = {

      week: value.week,
      km: value.km * count,
      Client: value.Client,
      count: count,
      difference: diff * count
    };
    result.push(res[value.Client]);

  } else {
    res[value.Client].km += value.km * count;
    res[value.Client].difference += diff * count;
  }

  return res;
}, {});

How do I go about this situation?
the output now is that instead of creating two rows (week 23 & 24), it sums all the appointments of Steven in week 23 which is incorrect because 0.5 hour took place in another week.

{Client: "Steven"
count: 5
difference: 40.5
km: 528
week: 23}

So the ideal output is:

{
Client: "Steven"
count: 5
difference: 40
km: 440
week: 23
},

{
Client: "Steven"
count: 1
difference: 0.5
km: 88
week: 24
}

You can have rows with the same week number as long as the Client differs.

I hope i made it clear and if you need more context, please mention

Body:
Building on @ajai's answer (and using his input first for comparison), hopefully giving you what you need (and using reduce).

const data = [
  {
   CreatedBy: "bob",
   Description: "smthng",
   EndTime: "2020-06-01T17:00:00.000Z",
   EndTimezone: null,
   Id: 3,
   IsAllDay: false,
   Client: "Steven",
   Location: "smthng",
   RecurrenceRule: "FREQ=DAILY;INTERVAL=1;COUNT=5;",
   StartTime: "2020-06-01T09:00:00.000Z",
   StartTimezone: null,
   Subject: "smthng",
   km: 88,
   week: 23,
   _id: "5ecc6f4a08c79c6328974699"
  },
  {
   CreatedBy: "bob",
   Description: "smthng",
   EndTime: "2020-06-08T10:30:00.000Z",
   EndTimezone: null,
   Id: 4,
   IsAllDay: false,
   Client: "Steven",
   Location: "smthng",
   RecurrenceRule: null,
   StartTime: "2020-06-08T10:00:00.000Z",
   StartTimezone: null,
   Subject: "smthng"  ,
   km: 88,
   week: 24,
   _id: "5ed450d299d5303bd0338a7f"
  },
  {
   CreatedBy: "bob",
   Description: "smthng",
   EndTime: "2020-06-01T17:00:00.000Z",
   EndTimezone: null,
   Id: 3,
   IsAllDay: false,
   Client: "Steven",
   Location: "smthng",
   RecurrenceRule: "FREQ=DAILY;INTERVAL=1;COUNT=5;",
   StartTime: "2020-06-01T09:00:00.000Z",
   StartTimezone: null,
   Subject: "smthng",
   km: 40,
   week: 23,
   _id: "5ecc6f4a08c79c6328974699"
  },
  {
   CreatedBy: "bob",
   Description: "smtng",
   EndTime: "2020-06-01T17:00:00.000Z",
   EndTimezone: null,
   Id: 3,
   IsAllDay: false,
   Client: "ajai",
   Location: "smthng",
   RecurrenceRule: "FREQ=DAILY;INTERVAL=1;COUNT=5;",
   StartTime: "2020-06-01T09:00:00.000Z",
   StartTimezone: null,
   Subject: "smthng",
   km: 88,
   week: 23,
   _id: "5ecc6f4a08c79c6328974699"
  }
]

const result = Object.values(data.reduce((aggObj, item) => {
  const stringID = `${item.Client}_${item.week}`;
  const diff = (new Date(item.EndTime) - new Date(item.StartTime))/(1000*60*60);
  const RecurrenceObj = item.RecurrenceRule ?
    item.RecurrenceRule.split(";").map(a => {
      //console.log(a)
      return a.split("=") || ["_", null];
    }).reduce((aggObj, [key,val]) => {
      aggObj[key] = val;
      return aggObj;
    })
    : {COUNT: 1};

  if (aggObj[stringID]){
    aggObj[stringID].km += (item.km * RecurrenceObj.COUNT);
    aggObj[stringID].count += parseInt(RecurrenceObj.COUNT);
    aggObj[stringID].difference += (diff * RecurrenceObj.COUNT);
  }
  else {
    aggObj[stringID] = {
      Client: item.Client,
      km: item.km * RecurrenceObj.COUNT,
      count: parseInt(RecurrenceObj.COUNT),
      difference: diff * RecurrenceObj.COUNT,
      week: item.week
    };
  }
  return aggObj;
}, {}));

/*
for(var i=0;i<=data.length-1;i++){
   let pos = result.findIndex(el=> `${el.Client}-${el.week}`==`${data[i].Client}-${data[i].week}`)
   if(pos==-1){
     result.push({Client: data[i]['Client'],count: 1,difference: 0,km: data[i]['km'],week: data[i]['week']})
   }else{
     result[pos]['count'] = result[pos]['count'] + 1;
     result[pos]['km'] = result[pos]['km'] + data[i]['km'];
   }
}
*/
console.log(result)

.as-console-wrapper { max-height: 100% !important; top: 0; }

OUTPUT:

[
  {
    "Client": "Steven",
    "km": 640,
    "count": 10,
    "difference": 80,
    "week": 23
  },
  {
    "Client": "Steven",
    "km": 88,
    "count": 1,
    "difference": 0.5,
    "week": 24
  },
  {
    "Client": "ajai",
    "km": 440,
    "count": 5,
    "difference": 40,
    "week": 23
  }
]

Now with your exact input:

const data = [
  {
   CreatedBy: "bob",
   Description: "smthng",
   EndTime: "2020-06-01T17:00:00.000Z",
   EndTimezone: null,
   Id: 3,
   IsAllDay: false,
   Client: "Steven",
   Location: "smthng",
   RecurrenceRule: "FREQ=DAILY;INTERVAL=1;COUNT=5;",
   StartTime: "2020-06-01T09:00:00.000Z",
   StartTimezone: null,
   Subject: "smthng",
   km: 88,
   week: 23,
   _id: "5ecc6f4a08c79c6328974699"
  },
  {
   CreatedBy: "bob",
   Description: "smthng",
   EndTime: "2020-06-08T10:30:00.000Z",
   EndTimezone: null,
   Id: 4,
   IsAllDay: false,
   Client: "Steven",
   Location: "smthng",
   RecurrenceRule: null,
   StartTime: "2020-06-08T10:00:00.000Z",
   StartTimezone: null,
   Subject: "smthng"  ,
   km: 88,
   week: 24,
   _id: "5ed450d299d5303bd0338a7f"
  }
]

const result = Object.values(data.reduce((aggObj, item) => {
  const stringID = `${item.Client}_${item.week}`;
  const diff = (new Date(item.EndTime) - new Date(item.StartTime))/(1000*60*60);
  const RecurrenceObj = item.RecurrenceRule ?
    item.RecurrenceRule.split(";").map(a => {
      //console.log(a)
      return a.split("=") || ["_", null];
    }).reduce((aggObj, [key,val]) => {
      aggObj[key] = val;
      return aggObj;
    })
    : {COUNT: 1};

  if (aggObj[stringID]){
    aggObj[stringID].km += (item.km * RecurrenceObj.COUNT);
    aggObj[stringID].count += parseInt(RecurrenceObj.COUNT);
    aggObj[stringID].difference += (diff * RecurrenceObj.COUNT);
  }
  else {
    aggObj[stringID] = {
      Client: item.Client,
      km: item.km * RecurrenceObj.COUNT,
      count: parseInt(RecurrenceObj.COUNT),
      difference: diff * RecurrenceObj.COUNT,
      week: item.week
    };
  }
  return aggObj;
}, {}));

/*
for(var i=0;i<=data.length-1;i++){
   let pos = result.findIndex(el=> `${el.Client}-${el.week}`==`${data[i].Client}-${data[i].week}`)
   if(pos==-1){
     result.push({Client: data[i]['Client'],count: 1,difference: 0,km: data[i]['km'],week: data[i]['week']})
   }else{
     result[pos]['count'] = result[pos]['count'] + 1;
     result[pos]['km'] = result[pos]['km'] + data[i]['km'];
   }
}
*/
console.log(result)

.as-console-wrapper { max-height: 100% !important; top: 0; }

OUTPUT:

[
  {
    "Client": "Steven",
    "km": 440,
    "count": 5,
    "difference": 40,
    "week": 23
  },
  {
    "Client": "Steven",
    "km": 88,
    "count": 1,
    "difference": 0.5,
    "week": 24
  }
]


问:
Mongoid and carrierwave
In order to remain DRY, I have a class ModelBase that includes Mongoid document as follows:

```<code>class ModelBase
  include Mongoid::Document

  alias_attribute :guid, :id

  def as_json(options = {})
    azove_hash = options.merge(:methods => :guid)
    super azove_hash
  end
end
</code>```

then all my models inherit from ModelBase and they seem to be working fine. However, there is one model where I use CarrierWave. when it inherits from ModelBase, the call to mount_uploader fails. And when I include the model inside with no subclassing it works fine. Isn't it possible to use carrierwave in a class that inherits from another class?

Here is the version of the class that is failing. would appreciate any suggestion/idea

```<code>require 'carrierwave/orm/mongoid'

class SomeOtherModel < ModelBase
  field :abstract
  validates :abstract, :presence => true

  field :category
  validates :category, :presence => true, :inclusion => {:in => %w{audio graphics text video}}

  field :content_uri
  validates :content_uri, :presence => true

  has_and_belongs_to_many :topics
  has_and_belongs_to_many :events
  has_and_belongs_to_many :authors, :class_name => "User"

  mount_uploader :content, ContentUploader

  attr_accessible :abstract, :category, :content, :content_uri, :authors, :topics, :events
end
</code>```

答:
I think you're making things too complicated. I see no need to inherit from modelbase with a mongoid document. Mongoid itself doesn't use inheritance, and simply includes modules as needed.

So if you have a set of fields re-used, such as contact information, just do something like:

```<code>class Customer
  include Mongoid::Document
  include DataModules::ContactDocument
  mounts_uploader :logo, LogoUploader
end

class User
  inclue Mongoid::Document
  include DataModules::ContactDocument
end
</code>```

Then include the code that you want to reuse in /lib/data_modules/contact_document.rb

```<code>module DataModules::ContactDocument

  def self.included(receiver)
    receiver.class_eval do
      field :email, :type=>String
      ...
      validates_existence_of :email
    end
  end
end
</code>```

Title: Mongoid and carrierwave

Body:
In order to remain DRY, I have a class ModelBase that includes Mongoid document as follows:

class ModelBase
  include Mongoid::Document

  alias_attribute :guid, :id

  def as_json(options = {})
    azove_hash = options.merge(:methods => :guid)
    super azove_hash
  end
end

then all my models inherit from ModelBase and they seem to be working fine. However, there is one model where I use CarrierWave. when it inherits from ModelBase, the call to mount_uploader fails. And when I include the model inside with no subclassing it works fine. Isn't it possible to use carrierwave in a class that inherits from another class?

Here is the version of the class that is failing. would appreciate any suggestion/idea

require 'carrierwave/orm/mongoid'

class SomeOtherModel < ModelBase
  field :abstract
  validates :abstract, :presence => true

  field :category
  validates :category, :presence => true, :inclusion => {:in => %w{audio graphics text video}}

  field :content_uri
  validates :content_uri, :presence => true

  has_and_belongs_to_many :topics
  has_and_belongs_to_many :events
  has_and_belongs_to_many :authors, :class_name => "User"

  mount_uploader :content, ContentUploader

  attr_accessible :abstract, :category, :content, :content_uri, :authors, :topics, :events
end

Body:
I think you're making things too complicated. I see no need to inherit from modelbase with a mongoid document. Mongoid itself doesn't use inheritance, and simply includes modules as needed.

So if you have a set of fields re-used, such as contact information, just do something like:

class Customer
  include Mongoid::Document
  include DataModules::ContactDocument
  mounts_uploader :logo, LogoUploader
end

class User
  inclue Mongoid::Document
  include DataModules::ContactDocument
end

Then include the code that you want to reuse in /lib/data_modules/contact_document.rb

module DataModules::ContactDocument

  def self.included(receiver)
    receiver.class_eval do
      field :email, :type=>String
      ...
      validates_existence_of :email
    end
  end
end


问:
I have to parse JSON response from API using Php, but somethings not working
I have this php script that makes this API call and returns JSON response.

```<code>    <?php
function display(){
    $searchKeywords = $_POST['searchKeywords'];
        list($firstname, $lastname) = preg_split("/[\s,]+/", $searchKeywords);
    $apikey = '**********************';
    $string = file_get_contents('https://completecriminalchecks.com/api/json/?firstname='.$firstname.'&lastname='.$lastname.'&apikey='.$apikey, true);
    $json =  json_decode($string);
    $companies = $json;
    $output = '
        <table class="table table-bordered table-striped" id="member_table" style="font-size:10px">
            <th>Name</th>
            <th>ID Numbers</th>
            <th>Aliases</th>
            <th>Birthdate</th>
            <th>Race</th>
            <th>Sex</th>
            <th>Height</th>
            <th>Weight</th>
            <th>Hair</th>
            <th>eyes</th>
            <th>address</th>
            <th>Crime</th>
        </tr>
    ';

    foreach($companies as $company){
        foreach($company as $data){

            $output .= "<tr>";
            $output .= "<td>".$data->full_name."</td>";
            $output .= "<td>".$data->id."</td>";
            $output .= "<td>".$data->aka."</td>";
            $output .= "<td>".$data->dob."</td>";
            $output .= "<td>".$data->race."</td>";
            $output .= "<td>".$data->sex."</td>";
            $output .= "<td>".$data->height."</td>";
            $output .= "<td>".$data->weight."</td>";
            $output .= "<td>".$data->hair."</td>";
            $output .= "<td>".$data->eyes."</td>";
            $output .= "<td>".$data->address."</td>";
            $output .= "<td>".$data->crime."</td>";
            $output .= "</tr>";
        }
    }

    $output .= "</table>";
    echo $output;
}
</code>```

The code seems to work, but there appears to be null or empty nodes which throws errors. I'm not sure why there are showing, if I simply place the url in the browser, the results do not have blank or empty nodes.

After executing the code here its what I see.
picture of html response with errors

Anyone have any ideas? what am I missing?

Here is the JSON

```<code>{
"response": {
    "status": "SUCCESS",
    "calls": "4929"
},
"person": [ {
    "id": "MI_SEX_65879",
    "full_name": "Lynn Francis Wilkinson",
    "dob": "05/14/1953",
    "race": "White",
    "sex": "M",
    "height": "507",
    "weight": "210lbs",
    "hair": "Brown",
    "eyes": "Blue",
    "address": "714 Howard St Bay City MI 48708",
    "crime": "750 520c1a Criminal Sexual Conduct Second Degree Person Under Thirteen ",
    "personal": "Lynn Wilkinson ",
    "image": "https://datadoesit.com/SOR-Images/MI/5011822-2018864.jpg",
    "state": "MI",
    "state_name": "Michigan",
    "db": "SEX"
} ],
"totals": {
    "count": "1",
    "sor_count": "1",
    "doc_count": "0",
    "court_count": "0"
}
}
</code>```

答:
You should use isset() to check object is set or not like below

```<code>(isset($data->full_name)) ? $data->full_name : '';
</code>```

Use the following code i have put isset()

```<code>function display(){
    $searchKeywords = $_POST['searchKeywords'];
        list($firstname, $lastname) = preg_split("/[\s,]+/", $searchKeywords);
    $apikey = '**********************';
    $string = file_get_contents('https://completecriminalchecks.com/api/json/?firstname='.$firstname.'&lastname='.$lastname.'&apikey='.$apikey, true);
    $json =  json_decode($string);
    $companies = $json;
    $output = '
        <table class="table table-bordered table-striped" id="member_table" style="font-size:10px">
            <th>Name</th>
            <th>ID Numbers</th>
            <th>Aliases</th>
            <th>Birthdate</th>
            <th>Race</th>
            <th>Sex</th>
            <th>Height</th>
            <th>Weight</th>
            <th>Hair</th>
            <th>eyes</th>
            <th>address</th>
            <th>Crime</th>
        </tr>
    ';

    foreach($companies as $company){
        foreach($company as $data){

            $output .= "<tr>";
            $output .= "<td>".((isset($data->full_name)) ? $data->full_name : '')."</td>";
            $output .= "<td>".((isset($data->id)) ? $data->id : '')."</td>";
            $output .= "<td>".((isset($data->aka)) ? $data->aka : '')."</td>";
            $output .= "<td>".((isset($data->dob)) ? $data->dob : '')."</td>";
            $output .= "<td>".((isset($data->race)) ? $data->race : '')."</td>";
            $output .= "<td>".((isset($data->sex)) ? $data->sex : '')."</td>";
            $output .= "<td>".((isset($data->height)) ? $data->height : '')."</td>";
            $output .= "<td>".((isset($data->weight)) ? $data->weight : '')."</td>";
            $output .= "<td>".((isset($data->hair)) ? $data->hair : '')."</td>";
            $output .= "<td>".((isset($data->eyes)) ? $data->eyes : '')."</td>";
            $output .= "<td>".((isset($data->address)) ? $data->address : '')."</td>";
            $output .= "<td>".((isset($data->crime)) ? $data->crime : '')."</td>";
            $output .= "</tr>";
        }
    }

    $output .= "</table>";
    echo $output;
}
</code>```

Body:
I have this php script that makes this API call and returns JSON response.

    <?php
function display(){
    $searchKeywords = $_POST['searchKeywords'];
        list($firstname, $lastname) = preg_split("/[\s,]+/", $searchKeywords);
    $apikey = '**********************';
    $string = file_get_contents('https://completecriminalchecks.com/api/json/?firstname='.$firstname.'&lastname='.$lastname.'&apikey='.$apikey, true);
    $json =  json_decode($string);
    $companies = $json;
    $output = '

            Name
            ID Numbers
            Aliases
            Birthdate
            Race
            Sex
            Height
            Weight
            Hair
            eyes
            address
            Crime

    ';

    foreach($companies as $company){
        foreach($company as $data){

            $output .= "
";
            $output .= "".$data->full_name."	";
            $output .= "".$data->id."	";
            $output .= "".$data->aka."	";
            $output .= "".$data->dob."	";
            $output .= "".$data->race."	";
            $output .= "".$data->sex."	";
            $output .= "".$data->height."	";
            $output .= "".$data->weight."	";
            $output .= "".$data->hair."	";
            $output .= "".$data->eyes."	";
            $output .= "".$data->address."	";
            $output .= "".$data->crime."	";
            $output .= "
";
        }
    }

    $output .= "
";
    echo $output;
}

The code seems to work, but there appears to be null or empty nodes which throws errors. I'm not sure why there are showing, if I simply place the url in the browser, the results do not have blank or empty nodes.

After executing the code here its what I see.
picture of html response with errors

Anyone have any ideas? what am I missing?

Here is the JSON

{
"response": {
    "status": "SUCCESS",
    "calls": "4929"
},
"person": [ {
    "id": "MI_SEX_65879",
    "full_name": "Lynn Francis Wilkinson",
    "dob": "05/14/1953",
    "race": "White",
    "sex": "M",
    "height": "507",
    "weight": "210lbs",
    "hair": "Brown",
    "eyes": "Blue",
    "address": "714 Howard St Bay City MI 48708",
    "crime": "750 520c1a Criminal Sexual Conduct Second Degree Person Under Thirteen ",
    "personal": "Lynn Wilkinson ",
    "image": "https://datadoesit.com/SOR-Images/MI/5011822-2018864.jpg",
    "state": "MI",
    "state_name": "Michigan",
    "db": "SEX"
} ],
"totals": {
    "count": "1",
    "sor_count": "1",
    "doc_count": "0",
    "court_count": "0"
}
}

Body:
You should use isset() to check object is set or not like below

(isset($data->full_name)) ? $data->full_name : '';

Use the following code i have put isset()

function display(){
    $searchKeywords = $_POST['searchKeywords'];
        list($firstname, $lastname) = preg_split("/[\s,]+/", $searchKeywords);
    $apikey = '**********************';
    $string = file_get_contents('https://completecriminalchecks.com/api/json/?firstname='.$firstname.'&lastname='.$lastname.'&apikey='.$apikey, true);
    $json =  json_decode($string);
    $companies = $json;
    $output = '
        <table class="table table-bordered table-striped" id="member_table" style="font-size:10px">
            <th>Name</th>
            <th>ID Numbers</th>
            <th>Aliases</th>
            <th>Birthdate</th>
            <th>Race</th>
            <th>Sex</th>
            <th>Height</th>
            <th>Weight</th>
            <th>Hair</th>
            <th>eyes</th>
            <th>address</th>
            <th>Crime</th>
        </tr>
    ';

    foreach($companies as $company){
        foreach($company as $data){

            $output .= "<tr>";
            $output .= "<td>".((isset($data->full_name)) ? $data->full_name : '')."</td>";
            $output .= "<td>".((isset($data->id)) ? $data->id : '')."</td>";
            $output .= "<td>".((isset($data->aka)) ? $data->aka : '')."</td>";
            $output .= "<td>".((isset($data->dob)) ? $data->dob : '')."</td>";
            $output .= "<td>".((isset($data->race)) ? $data->race : '')."</td>";
            $output .= "<td>".((isset($data->sex)) ? $data->sex : '')."</td>";
            $output .= "<td>".((isset($data->height)) ? $data->height : '')."</td>";
            $output .= "<td>".((isset($data->weight)) ? $data->weight : '')."</td>";
            $output .= "<td>".((isset($data->hair)) ? $data->hair : '')."</td>";
            $output .= "<td>".((isset($data->eyes)) ? $data->eyes : '')."</td>";
            $output .= "<td>".((isset($data->address)) ? $data->address : '')."</td>";
            $output .= "<td>".((isset($data->crime)) ? $data->crime : '')."</td>";
            $output .= "</tr>";
        }
    }

    $output .= "</table>";
    echo $output;
}


问:
AWS - Accessing private website hosted on an external AWS account
Background

My company has bought a SaaS product which is hosted on vendor's AWS environment. The product has a website dashboard which is currently only accessible within the vendor's AWS environment. The access to the vendor's AWS environment is tightly controlled by the vendor.

Right now my users are able to access that dashboard by using Amazon Workspaces provisioned by the vendor. However, the Workspaces have limited number of accounts for my company. My company would like to make this dashboard widely accessible within my company and not restricted by the number of Workspaces accounts.

Question

My company has our own AWS account as well but currently not linked to vendor's VPC/AWS environment at all. Can we build something in our own AWS (probably with a PrivateLink to vendor's VPC?) such that my users can securely access the vendor's dashboard via our own AWS environment? If there's a possible way to do this, what are the AWS services required on both sides?

My objective is to ensure this dashboard is not exposed to the Internet and yet all my company's users can view it without having Workspace credentials.

答:
As per your comment you would want to use AWS Private Link to accomplish this problem.

By doing this the only resource shared between is an endpoint to access the service.

This would be accessible over VPN too, which should grant you access on your on-premise.


问:
Why doesn't C++20 use `requires` to restrict the T for atomic<T>?
A generic std::atomic<T> is required to have a T that is Copy Constructible and Copy Assignable:

[atomics.types.generic]/1

The program is ill-formed if any of

(1.1) is_trivially_copyable_v<T>,

(1.2) is_copy_constructible_v<T>,

(1.3) is_move_constructible_v<T>,

(1.4) is_copy_assignable_v<T>,

or (1.5) is_move_assignable_v<T>

is false.

The above is not new to C++20. Compilers may use static_assert to issue an error for a non-conforming T.

However, C++20 could use formal constraints with the requires syntax to formally require the above as part of the type, e.g. something like:

```<code>template< class T > requires
    std::is_trivially_copyable_v<T> &&
    std::is_copy_constructible_v<T> &&
    std::is_move_constructible_v<T> &&
    std::is_copy_assignable_v<T> &&
    std::is_move_assignable_v<T>
struct atomic { ... };
</code>```

Is there a reason why C++20 refrained from using formal constraints for this purpose?

EDIT: @T.C. points out correctly, in an answer below:

For std::atomic in particular, constraining the primary template is
simply not an option, given the atomic<shared_ptr<T>> and
atomic<weak_ptr<T>> specializations that were added in C++20.

with an option suggesting that:

Perhaps you can do something fancier (like an undefined and
unconstrained primary template plus a constrained partial
specialization), but it adds very little value.

Well, there is another option, without the need for an undefined and
unconstrained primary template, which is still a bit complex and reduces the value and fun in going with concepts for this usage, but probably better than an undefined base template:

```<code>template< class T > requires
    std::is_trivially_copyable_v<T> &&
    std::is_copy_constructible_v<T> &&
    std::is_move_constructible_v<T> &&
    std::is_copy_assignable_v<T> &&
    std::is_move_assignable_v<T>
    || std::same_as<T, std::shared_ptr<typename T::element_type>>
    || std::same_as<T, std::weak_ptr<typename T::element_type>>
struct atomic { ... };

template< class T >
struct atomic<std::shared_ptr<T>> { ... };

template< class T >
struct atomic<std::weak_ptr<T>> { ... };

// types of all other specializations are Copy Constructible and Copy Assignable
</code>```

Code: https://godbolt.org/z/JaCu78

答:
The library specification deliberately avoids using any particular technology to achieve its goals P0788:

IV. Let’s avoid any specification that demands any particular technology by which implementations must comply with Library specifications.

a) Let’s permit an implementation to use a requires-clause, an enable_if, a constexpr if, or
  any other technology or combination of technologies to meet Constraints: specifications.

b) Let’s permit an implementation to use static_assert and/or any other technologies to
  meet Mandates: specifications.

c) Let’s permit an implementation to use Contracts attributes [P0542R1] and/or any other
  technologies to meet Expects: and Ensures: specifications.

d) Let’s consider user code that relies on any specific technology on the part of an implementation to be ill-formed, with no diagnostic required.

Which is expanded upon in P1369.

The goal is to avoid tying the specification of the library to any particular implementation of it. There are cases where you do need to do this - many of the Ranges things do require concepts to work, so they are specified in this way - but for the most part, you don't.

For the user, the important part is the mandated requirements on T. It's not important how those requirements are enforced. It could be a concept, it could be a static_assert, it could be some compiler intrisic, whatever.

Body:
A generic std::atomic<T> is required to have a T that is Copy Constructible and Copy Assignable:

[atomics.types.generic]/1

The program is ill-formed if any of

(1.1) is_trivially_copyable_v<T>,

(1.2) is_copy_constructible_v<T>,

(1.3) is_move_constructible_v<T>,

(1.4) is_copy_assignable_v<T>,

or (1.5) is_move_assignable_v<T>

is false.

The above is not new to C++20. Compilers may use static_assert to issue an error for a non-conforming T.

However, C++20 could use formal constraints with the requires syntax to formally require the above as part of the type, e.g. something like:

template< class T > requires
    std::is_trivially_copyable_v<T> &&
    std::is_copy_constructible_v<T> &&
    std::is_move_constructible_v<T> &&
    std::is_copy_assignable_v<T> &&
    std::is_move_assignable_v<T>
struct atomic { ... };

Is there a reason why C++20 refrained from using formal constraints for this purpose?

EDIT: @T.C. points out correctly, in an answer below:

For std::atomic in particular, constraining the primary template is
simply not an option, given the atomic<shared_ptr<T>> and
atomic<weak_ptr<T>> specializations that were added in C++20.

with an option suggesting that:

Perhaps you can do something fancier (like an undefined and
unconstrained primary template plus a constrained partial
specialization), but it adds very little value.

Well, there is another option, without the need for an undefined and
unconstrained primary template, which is still a bit complex and reduces the value and fun in going with concepts for this usage, but probably better than an undefined base template:

template< class T > requires
    std::is_trivially_copyable_v<T> &&
    std::is_copy_constructible_v<T> &&
    std::is_move_constructible_v<T> &&
    std::is_copy_assignable_v<T> &&
    std::is_move_assignable_v<T>
    || std::same_as<T, std::shared_ptr<typename T::element_type>>
    || std::same_as<T, std::weak_ptr<typename T::element_type>>
struct atomic { ... };

template< class T >
struct atomic<std::shared_ptr<T>> { ... };

template< class T >
struct atomic<std::weak_ptr<T>> { ... };

// types of all other specializations are Copy Constructible and Copy Assignable

Code: https://godbolt.org/z/JaCu78


问:
gwt multiple field suggest box
is it is possible to make multiple suggest values in suggestbox GWT

```<code>example..
if i search for a

Abraham   25   1984
Abi       23   1987
Aram      26   1999
</code>```

this should be in suggest box is it is possible ....

```<code>like this icefaces (check second textbox)
http://component-showcase.icefaces.org/component-showcase/showcase.iface
</code>```

答:
There's also a library that permits to do that natively:  http://code.google.com/p/advanced-suggest-select-box/

It also permits to have icons and handles other aspects (like a strict mode to work like a select box still proposing suggestions on typing, have other filtering algorithm, etc...

ContentLicense: CC BY-SA 2.5

Title: gwt multiple field suggest box

Body:
is it is possible to make multiple suggest values in suggestbox GWT

example..
if i search for a

Abraham   25   1984
Abi       23   1987
Aram      26   1999

this should be in suggest box is it is possible ....

like this icefaces (check second textbox)
http://component-showcase.icefaces.org/component-showcase/showcase.iface


问:
How can I access my downloads folder using Dockerfile?
I have to following Dockerfile to create a container image. This works fine for some scripts.

```<code>FROM python:3.8-slim-buster

COPY . /work

WORKDIR /work

RUN apt-get update

RUN apt-get upgrade -y

RUN pip install -r requirements.txt
</code>```

However, I have a script which requires access to my local downloads folder. My understanding is that the container creates an image with the copy of the directory that the Dockerfile sits within. However, I do not understand how to give the container access to my downloads folder outside of this. Any help would be great!

答:
For mounting or sharing purpose you can use docker volume a storing mechanism for docker. You should mount files from your host to the container.

```<code>docker run -v [host directory path]:[container directory path] -it [image name]
</code>```

This command will just mount your host directory whichever you give access to container

Body:
I have to following Dockerfile to create a container image. This works fine for some scripts.

FROM python:3.8-slim-buster

COPY . /work

WORKDIR /work

RUN apt-get update

RUN apt-get upgrade -y

RUN pip install -r requirements.txt

However, I have a script which requires access to my local downloads folder. My understanding is that the container creates an image with the copy of the directory that the Dockerfile sits within. However, I do not understand how to give the container access to my downloads folder outside of this. Any help would be great!

Body:
For mounting or sharing purpose you can use docker volume a storing mechanism for docker. You should mount files from your host to the container.

docker run -v [host directory path]:[container directory path] -it [image name]

This command will just mount your host directory whichever you give access to container


问:
In converting List<T> to DataTable add select properties from class
I am trying to convert a List to a DataTable. I have the basic outline done, but am stuck on one part. I am trying to only get a few of the properties form the class.

```<code>public static DataTable ToDataTable<T>(this IList<T> data)
{
    PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T));
    DataTable table = new DataTable();

    table.Columns.Add("type", typeof(string));
    table.Columns.Add("id", typeof(Int32));
    table.Columns.Add("name", typeof(string));
    table.Columns.Add("city", typeof(string));

    foreach (T item in data)
    {
        DataRow row = table.NewRow();
        foreach (PropertyDescriptor prop in properties)
        {
            row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
        }
        table.Rows.Add(row);
    }
    return table;
}
</code>```

The problem is when it gets to the second property it throws an error saying column 'unincludedCol' does not belong to table.

How do I get around this?

答:
May I suggest an additional fine point to an already-good accepted answer?

In your generic method, you seem to be relying on the existence of the properties 'type', 'id', 'name' and 'city'. Such things should not be left to chance.

To guarantee that the class <T> will have those four properties, consider constraining T in your ToDataTable method like this:

```<code>public static DataTable ToDataTable<T>(this IList<T> data) where T : IMyConstraint
{}
</code>```

... where IMyConstraint is declared as ...

```<code>interface IMyConstraint
{
    string type { get; }
    int id { get; }
    string name { get; }
    string city { get; }
}
</code>```

This makes your generic method safe for any class <T> that implements IMyConstraint:

```<code>class SomeClass : IMyConstraint
</code>```

If (as your code implies) the four properties you want in your DataTable are known, you can still iterate the names:

```<code>private static DataTable ToDataTable<T>(IEnumerable<T> data) where T : IMyConstraint
{
    DataTable table = new DataTable();
    Type type = typeof(T);
    // "If" you already know the names of the properties you want...
    string[] names = new string[] { "type", "id", "name", "city" };

    foreach (var name in names)     // Add columns
    {
        table.Columns.Add(name, type.GetProperty(name).PropertyType);
    }
    foreach (var item in data)      // Add rows
    {
        object[] values =
            names
            .Select(name => type.GetProperty(name).GetValue(item))
            .ToArray();
        table.Rows.Add(values);
    }
    return table;
}
</code>```

... or possibly cleaner-still, just iterate the IMyConstraints interface instead:

```<code>private static DataTable ToDataTableAlt<T>(IEnumerable<T> data) where T : IMyConstraint
{
    DataTable table = new DataTable();
    PropertyInfo[] propertyInfos = typeof(IMyConstraint).GetProperties();

    foreach (var propertyInfo in propertyInfos)     // Add columns
    {
        table.Columns.Add(propertyInfo.Name, propertyInfo.PropertyType);
    }
    foreach (var item in data)      // Add rows
    {
        object[] values =
            propertyInfos
            .Select(propertyInfo => propertyInfo.GetValue(item))
            .ToArray();
        table.Rows.Add(values);
    }
    return table;
}
</code>```

Clone or Download this working example from GitHub.

Body:
I am trying to convert a List to a DataTable. I have the basic outline done, but am stuck on one part. I am trying to only get a few of the properties form the class.

public static DataTable ToDataTable<T>(this IList<T> data)
{
    PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T));
    DataTable table = new DataTable();

    table.Columns.Add("type", typeof(string));
    table.Columns.Add("id", typeof(Int32));
    table.Columns.Add("name", typeof(string));
    table.Columns.Add("city", typeof(string));

    foreach (T item in data)
    {
        DataRow row = table.NewRow();
        foreach (PropertyDescriptor prop in properties)
        {
            row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
        }
        table.Rows.Add(row);
    }
    return table;
}

The problem is when it gets to the second property it throws an error saying column 'unincludedCol' does not belong to table.

How do I get around this?

Body:
May I suggest an additional fine point to an already-good accepted answer?

In your generic method, you seem to be relying on the existence of the properties 'type', 'id', 'name' and 'city'. Such things should not be left to chance.

To guarantee that the class <T> will have those four properties, consider constraining T in your ToDataTable method like this:

public static DataTable ToDataTable<T>(this IList<T> data) where T : IMyConstraint
{}

... where IMyConstraint is declared as ...

interface IMyConstraint
{
    string type { get; }
    int id { get; }
    string name { get; }
    string city { get; }
}

This makes your generic method safe for any class <T> that implements IMyConstraint:

class SomeClass : IMyConstraint

If (as your code implies) the four properties you want in your DataTable are known, you can still iterate the names:

private static DataTable ToDataTable<T>(IEnumerable<T> data) where T : IMyConstraint
{
    DataTable table = new DataTable();
    Type type = typeof(T);
    // "If" you already know the names of the properties you want...
    string[] names = new string[] { "type", "id", "name", "city" };

    foreach (var name in names)     // Add columns
    {
        table.Columns.Add(name, type.GetProperty(name).PropertyType);
    }
    foreach (var item in data)      // Add rows
    {
        object[] values =
            names
            .Select(name => type.GetProperty(name).GetValue(item))
            .ToArray();
        table.Rows.Add(values);
    }
    return table;
}

... or possibly cleaner-still, just iterate the IMyConstraints interface instead:

private static DataTable ToDataTableAlt<T>(IEnumerable<T> data) where T : IMyConstraint
{
    DataTable table = new DataTable();
    PropertyInfo[] propertyInfos = typeof(IMyConstraint).GetProperties();

    foreach (var propertyInfo in propertyInfos)     // Add columns
    {
        table.Columns.Add(propertyInfo.Name, propertyInfo.PropertyType);
    }
    foreach (var item in data)      // Add rows
    {
        object[] values =
            propertyInfos
            .Select(propertyInfo => propertyInfo.GetValue(item))
            .ToArray();
        table.Rows.Add(values);
    }
    return table;
}

Clone or Download this working example from GitHub.