问:
translateZ element still looks flat when rotating parent
I have a "rotate on hover" effect on a div and I want to make it so when it's being rotated the elements inside of it seem to be closer to the viewer and have more depth with regards to the background. However, applying translateZ(); makes them look bigger, but they still look "stuck" to the background.

So far, I tried to apply both perspective and transform: perspective(); properties to the parent element and transform-style: preserve-3d; to the child element, but it still looks glued to the background.

So to be clear, this is what I want to recreate.

But this is what I get.

let gridElements = document.getElementsByClassName('grid-member');

    let magify = (container, inner, adjust) => {
      // Mouse
      var mouse = {
        _x: 0,
        _y: 0,
        x: 0,
        y: 0,
        updatePosition: function (event) {
          var e = event || window.event;
          this.x = e.clientX - this._x;
          this.y = (e.clientY - this._y) * -1;
        },
        setOrigin: function (e) {
          this._x = e.offsetLeft + Math.floor(e.offsetWidth / 2);
          this._y = e.offsetTop + Math.floor(e.offsetHeight / 2);
        },
        show: function () {
          return '(' + this.x + ', ' + this.y + ')';
        },
      };

      // Track the mouse position relative to the center of the container.
      mouse.setOrigin(container);

      //----------------------------------------------------

      var counter = 0;
      var refreshRate = 3;
      var isTimeToUpdate = function () {
        return counter++ % refreshRate === 0;
      };

      //----------------------------------------------------

      var onMouseEnterHandler = function (event) {
        container.style.zIndex = '3';
        update(event);
      };

      var onMouseLeaveHandler = function () {
        container.style.transform = '';
        // inner.children[1].style.transform = '';
        container.style.zIndex = '';
      };

      var onMouseMoveHandler = function (event) {
        if (isTimeToUpdate()) {
          update(event);
        }
      };

      //----------------------------------------------------

      var update = function (e) {
        // Set up multipliers
        var yMult = 0.03;
        var xMult = 0.063;

        var d = document,
          bd = d.getElementsByTagName('body')[0],
          win = window;

        var bdst = $(window).scrollTop();
        var bdsl = bd.scrollLeft;
        var pageX = e.pageX;
        var pageY = e.pageY;
        var offsets = inner.getBoundingClientRect();
        var w = inner.clientWidth || inner.offsetWidth || inner.scrollWidth;
        var h = inner.clientHeight || inner.offsetHeight || inner.scrollHeight;
        var wMultiple = 320 / w;
        var offsetX = 0.52 - (pageX - offsets.left - bdsl) / w;
        var offsetY = 0.52 - (pageY - offsets.top - bdst) / h;
        var dy = pageY - offsets.top - bdst - h / 2;
        var dx = pageX - offsets.left - bdsl - w / 2;
        var yRotate = (offsetX - dx) * (yMult * wMultiple);
        var xRotate = (dy - offsetY) * (xMult * wMultiple);

        var imgCSS;

        imgCSS =
          'perspective(' +
          w * 3 +
          'px) rotateX(' +
          xRotate * 1 +
          'deg) rotateY(' +
          yRotate * 1 +
          'deg)';

        // var innerCSS = 'rotateX(' + xRotate * 0.2 + 'deg) rotateY(' + yRotate * 0.35 + 'deg) translateZ(30px)';

        // inner.children[1].style.transform = innerCSS;
        container.style.transform = imgCSS;
      };

      var updateTransformStyle = function (x, y) {
        var style = 'rotateX(' + x + 'deg) rotateY(' + y + 'deg)';
        container.style.transform = style;
        container.style.webkitTransform = style;
        container.style.mozTranform = style;
        container.style.msTransform = style;
        container.style.oTransform = style;
      };

      //--------------------------------------------------------

      container.onmousemove = onMouseMoveHandler;
      container.onmouseleave = onMouseLeaveHandler;
      container.onmouseenter = onMouseEnterHandler;
    };

    magify(gridElements[0], gridElements[0].children[0], 0.5);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
      background: black;
      display: flex;
      justify-content: center;
    }
    #container {
      display: flex;
      flex-wrap: wrap;
      width: 1500px;
      margin: auto;
    }
    #container > div {
      height: 300px;
      width: 300px;
      background: red;
      perspective: 30px;
      perspective-origin: center;
      display: flex;
      justify-content: center;
      align-items: center;
      align-content: center;
      background: url('https://i.picsum.photos/id/1018/3914/2935.jpg');
      background-size: cover;
      background-repeat: no-repeat;
    }
    #container > div > div {
      transform: translateZ(20px);
      transform-style: preserve-3d;
    }
    #container > div p {
      color: white;
      font-family: 'Montserrat', sans-serif;
      font-weight: 800;
      display: block;
    }</code>```

Lorem Ipsum

```

答:
I have done it with translate()

let gridElements = document.getElementsByClassName('grid-member');
var textContainer = document.querySelector("#text");
    let magify = (container, inner, adjust) => {
      // Mouse
      var mouse = {
        _x: 0,
        _y: 0,
        x: 0,
        y: 0,
        updatePosition: function (event) {
          var e = event || window.event;
          this.x = e.clientX - this._x;
          this.y = (e.clientY - this._y) * -1;
        },
        setOrigin: function (e) {
          this._x = e.offsetLeft + Math.floor(e.offsetWidth / 2);
          this._y = e.offsetTop + Math.floor(e.offsetHeight / 2);
        },
        show: function () {
          return '(' + this.x + ', ' + this.y + ')';
        },
      };

      // Track the mouse position relative to the center of the container.
      mouse.setOrigin(container);

      //----------------------------------------------------

      var counter = 0;
      var refreshRate = 3;
      var isTimeToUpdate = function () {
        return counter++ % refreshRate === 0;
      };

      //----------------------------------------------------

      var onMouseEnterHandler = function (event) {
        container.style.zIndex = '3';
        update(event);
      };

      var onMouseLeaveHandler = function () {
        container.style.transform = '';
        // inner.children[1].style.transform = '';
             textContainer.style.transform = "";
        container.style.zIndex = '';
      };

      var onMouseMoveHandler = function (event) {
        if (isTimeToUpdate()) {
          update(event);
        }
      };

      //----------------------------------------------------

      var update = function (e) {
        // Set up multipliers
        var yMult = 0.03;
        var xMult = 0.063;

        var d = document,
          bd = d.getElementsByTagName('body')[0],
          win = window;

        var bdst = $(window).scrollTop();
        var bdsl = bd.scrollLeft;
        var pageX = e.pageX;
        var pageY = e.pageY;
        var offsets = inner.getBoundingClientRect();
        var w = inner.clientWidth || inner.offsetWidth || inner.scrollWidth;
        var h = inner.clientHeight || inner.offsetHeight || inner.scrollHeight;
        var wMultiple = 320 / w;
        var offsetX = 0.52 - (pageX - offsets.left - bdsl) / w;
        var offsetY = 0.52 - (pageY - offsets.top - bdst) / h;
        var dy = pageY - offsets.top - bdst - h / 2;
        var dx = pageX - offsets.left - bdsl - w / 2;
        var yRotate = (offsetX - dx) * (yMult * wMultiple);
        var xRotate = (dy - offsetY) * (xMult * wMultiple);

        var imgCSS;
        let dirX = yRotate;
        let dirY = xRotate - ( 2 * xRotate);

        var textStyle = `translate(${dirX}px, ${dirY}px)`;
        textContainer.style.transform = textStyle;
        imgCSS =
          'perspective(' +
          w * 3 +
          'px) rotateX(' +
          xRotate * 1 +
          'deg) rotateY(' +
          yRotate * 1 +
          'deg)';

        // var innerCSS = 'rotateX(' + xRotate * 0.2 + 'deg) rotateY(' + yRotate * 0.35 + 'deg) translateZ(30px)';

        // inner.children[1].style.transform = innerCSS;
        container.style.transform = imgCSS;
      };

      var updateTransformStyle = function (x, y) {
        var style = 'rotateX(' + x + 'deg) rotateY(' + y + 'deg)';
        container.style.transform = style;
        container.style.webkitTransform = style;
        container.style.mozTranform = style;
        container.style.msTransform = style;
        container.style.oTransform = style;
      };

      //--------------------------------------------------------

      container.onmousemove = onMouseMoveHandler;
      container.onmouseleave = onMouseLeaveHandler;
      container.onmouseenter = onMouseEnterHandler;
    };

    magify(gridElements[0], gridElements[0].children[0], 0.5);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
      background: black;
      display: flex;
      justify-content: center;
    }
    #container {
      display: flex;
      flex-wrap: wrap;
      width: 1500px;
      margin: auto;
    }
    #container > div {
      height: 300px;
      width: 300px;
      background: red;
      perspective: 30px;
      perspective-origin: center;
      display: flex;
      justify-content: center;
      align-items: center;
      align-content: center;
      background: url('https://i.picsum.photos/id/1018/3914/2935.jpg');
      background-size: cover;
      background-repeat: no-repeat;
    }
    #container > div > div {
       font-size: 26px;
    }
    #container > div p {
      color: white;
      font-family: 'Montserrat', sans-serif;
      font-weight: 800;
      display: block;
    }</code>```

Lorem Ipsum

```

Body:
I have a "rotate on hover" effect on a div and I want to make it so when it's being rotated the elements inside of it seem to be closer to the viewer and have more depth with regards to the background. However, applying translateZ(); makes them look bigger, but they still look "stuck" to the background.

So far, I tried to apply both perspective and transform: perspective(); properties to the parent element and transform-style: preserve-3d; to the child element, but it still looks glued to the background.

So to be clear, this is what I want to recreate.

But this is what I get.

let gridElements = document.getElementsByClassName('grid-member');

    let magify = (container, inner, adjust) => {
      // Mouse
      var mouse = {
        _x: 0,
        _y: 0,
        x: 0,
        y: 0,
        updatePosition: function (event) {
          var e = event || window.event;
          this.x = e.clientX - this._x;
          this.y = (e.clientY - this._y) * -1;
        },
        setOrigin: function (e) {
          this._x = e.offsetLeft + Math.floor(e.offsetWidth / 2);
          this._y = e.offsetTop + Math.floor(e.offsetHeight / 2);
        },
        show: function () {
          return '(' + this.x + ', ' + this.y + ')';
        },
      };

      // Track the mouse position relative to the center of the container.
      mouse.setOrigin(container);

      //----------------------------------------------------

      var counter = 0;
      var refreshRate = 3;
      var isTimeToUpdate = function () {
        return counter++ % refreshRate === 0;
      };

      //----------------------------------------------------

      var onMouseEnterHandler = function (event) {
        container.style.zIndex = '3';
        update(event);
      };

      var onMouseLeaveHandler = function () {
        container.style.transform = '';
        // inner.children[1].style.transform = '';
        container.style.zIndex = '';
      };

      var onMouseMoveHandler = function (event) {
        if (isTimeToUpdate()) {
          update(event);
        }
      };

      //----------------------------------------------------

      var update = function (e) {
        // Set up multipliers
        var yMult = 0.03;
        var xMult = 0.063;

        var d = document,
          bd = d.getElementsByTagName('body')[0],
          win = window;

        var bdst = $(window).scrollTop();
        var bdsl = bd.scrollLeft;
        var pageX = e.pageX;
        var pageY = e.pageY;
        var offsets = inner.getBoundingClientRect();
        var w = inner.clientWidth || inner.offsetWidth || inner.scrollWidth;
        var h = inner.clientHeight || inner.offsetHeight || inner.scrollHeight;
        var wMultiple = 320 / w;
        var offsetX = 0.52 - (pageX - offsets.left - bdsl) / w;
        var offsetY = 0.52 - (pageY - offsets.top - bdst) / h;
        var dy = pageY - offsets.top - bdst - h / 2;
        var dx = pageX - offsets.left - bdsl - w / 2;
        var yRotate = (offsetX - dx) * (yMult * wMultiple);
        var xRotate = (dy - offsetY) * (xMult * wMultiple);

        var imgCSS;

        imgCSS =
          'perspective(' +
          w * 3 +
          'px) rotateX(' +
          xRotate * 1 +
          'deg) rotateY(' +
          yRotate * 1 +
          'deg)';

        // var innerCSS = 'rotateX(' + xRotate * 0.2 + 'deg) rotateY(' + yRotate * 0.35 + 'deg) translateZ(30px)';

        // inner.children[1].style.transform = innerCSS;
        container.style.transform = imgCSS;
      };

      var updateTransformStyle = function (x, y) {
        var style = 'rotateX(' + x + 'deg) rotateY(' + y + 'deg)';
        container.style.transform = style;
        container.style.webkitTransform = style;
        container.style.mozTranform = style;
        container.style.msTransform = style;
        container.style.oTransform = style;
      };

      //--------------------------------------------------------

      container.onmousemove = onMouseMoveHandler;
      container.onmouseleave = onMouseLeaveHandler;
      container.onmouseenter = onMouseEnterHandler;
    };

    magify(gridElements[0], gridElements[0].children[0], 0.5);

body {
      background: black;
      display: flex;
      justify-content: center;
    }
    #container {
      display: flex;
      flex-wrap: wrap;
      width: 1500px;
      margin: auto;
    }
    #container > div {
      height: 300px;
      width: 300px;
      background: red;
      perspective: 30px;
      perspective-origin: center;
      display: flex;
      justify-content: center;
      align-items: center;
      align-content: center;
      background: url('https://i.picsum.photos/id/1018/3914/2935.jpg');
      background-size: cover;
      background-repeat: no-repeat;
    }
    #container > div > div {
      transform: translateZ(20px);
      transform-style: preserve-3d;
    }
    #container > div p {
      color: white;
      font-family: 'Montserrat', sans-serif;
      font-weight: 800;
      display: block;
    }

Lorem Ipsum

Body:
I have done it with translate()

let gridElements = document.getElementsByClassName('grid-member');
var textContainer = document.querySelector("#text");
    let magify = (container, inner, adjust) => {
      // Mouse
      var mouse = {
        _x: 0,
        _y: 0,
        x: 0,
        y: 0,
        updatePosition: function (event) {
          var e = event || window.event;
          this.x = e.clientX - this._x;
          this.y = (e.clientY - this._y) * -1;
        },
        setOrigin: function (e) {
          this._x = e.offsetLeft + Math.floor(e.offsetWidth / 2);
          this._y = e.offsetTop + Math.floor(e.offsetHeight / 2);
        },
        show: function () {
          return '(' + this.x + ', ' + this.y + ')';
        },
      };

      // Track the mouse position relative to the center of the container.
      mouse.setOrigin(container);

      //----------------------------------------------------

      var counter = 0;
      var refreshRate = 3;
      var isTimeToUpdate = function () {
        return counter++ % refreshRate === 0;
      };

      //----------------------------------------------------

      var onMouseEnterHandler = function (event) {
        container.style.zIndex = '3';
        update(event);
      };

      var onMouseLeaveHandler = function () {
        container.style.transform = '';
        // inner.children[1].style.transform = '';
             textContainer.style.transform = "";
        container.style.zIndex = '';
      };

      var onMouseMoveHandler = function (event) {
        if (isTimeToUpdate()) {
          update(event);
        }
      };

      //----------------------------------------------------

      var update = function (e) {
        // Set up multipliers
        var yMult = 0.03;
        var xMult = 0.063;

        var d = document,
          bd = d.getElementsByTagName('body')[0],
          win = window;

        var bdst = $(window).scrollTop();
        var bdsl = bd.scrollLeft;
        var pageX = e.pageX;
        var pageY = e.pageY;
        var offsets = inner.getBoundingClientRect();
        var w = inner.clientWidth || inner.offsetWidth || inner.scrollWidth;
        var h = inner.clientHeight || inner.offsetHeight || inner.scrollHeight;
        var wMultiple = 320 / w;
        var offsetX = 0.52 - (pageX - offsets.left - bdsl) / w;
        var offsetY = 0.52 - (pageY - offsets.top - bdst) / h;
        var dy = pageY - offsets.top - bdst - h / 2;
        var dx = pageX - offsets.left - bdsl - w / 2;
        var yRotate = (offsetX - dx) * (yMult * wMultiple);
        var xRotate = (dy - offsetY) * (xMult * wMultiple);

        var imgCSS;
        let dirX = yRotate;
        let dirY = xRotate - ( 2 * xRotate);

        var textStyle = `translate(${dirX}px, ${dirY}px)`;
        textContainer.style.transform = textStyle;
        imgCSS =
          'perspective(' +
          w * 3 +
          'px) rotateX(' +
          xRotate * 1 +
          'deg) rotateY(' +
          yRotate * 1 +
          'deg)';

        // var innerCSS = 'rotateX(' + xRotate * 0.2 + 'deg) rotateY(' + yRotate * 0.35 + 'deg) translateZ(30px)';

        // inner.children[1].style.transform = innerCSS;
        container.style.transform = imgCSS;
      };

      var updateTransformStyle = function (x, y) {
        var style = 'rotateX(' + x + 'deg) rotateY(' + y + 'deg)';
        container.style.transform = style;
        container.style.webkitTransform = style;
        container.style.mozTranform = style;
        container.style.msTransform = style;
        container.style.oTransform = style;
      };

      //--------------------------------------------------------

      container.onmousemove = onMouseMoveHandler;
      container.onmouseleave = onMouseLeaveHandler;
      container.onmouseenter = onMouseEnterHandler;
    };

    magify(gridElements[0], gridElements[0].children[0], 0.5);

body {
      background: black;
      display: flex;
      justify-content: center;
    }
    #container {
      display: flex;
      flex-wrap: wrap;
      width: 1500px;
      margin: auto;
    }
    #container > div {
      height: 300px;
      width: 300px;
      background: red;
      perspective: 30px;
      perspective-origin: center;
      display: flex;
      justify-content: center;
      align-items: center;
      align-content: center;
      background: url('https://i.picsum.photos/id/1018/3914/2935.jpg');
      background-size: cover;
      background-repeat: no-repeat;
    }
    #container > div > div {
       font-size: 26px;
    }
    #container > div p {
      color: white;
      font-family: 'Montserrat', sans-serif;
      font-weight: 800;
      display: block;
    }

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container">
  <div class="grid-member large">
    <div id="text"><p>Lorem Ipsum</p></div>
  </div>
</div>


来源: stackexchange

答:
You can use a subquery:</p>

```<code>SELECT a.Student_id , a.Admit_date,
    (   SELECT MIN( b.Admit_date)
        FROM tempB b
        WHERE b.Admit_date >= a.Admit_date
        AND a.Student_id = b.Student_id
    ) as Admit_date2

FROM tempA a
</code>```

ContentLicense: CC BY-SA 4.0

Title: Return specific row using offset or lead or lag

Body:
I have two tables; #tempA  and #tempB
I want to join both tables matching on Student_id and Admit_date.
I want to return the #tempB table row immediately after the row that matches on student_id and admit date.
In this case, I want to return #tempB rows 2, row 5 and row 18.
I can't get it to work.

tempA

Student_id  Admit_date
709652      2020-01-31
709652      2019-10-09
368671      2015-04-19

tempB

Unique_id   Student_id  Admit date
1           709652      2020-01-31
2           709652      2019-12-16
3           709652      2019-12-04
4           709652      2019-10-09
5           709652      2019-10-07
6           709652      2019-09-22
7           709652      2019-09-21
8           709652      2019-08-29
9           709652      2019-08-01
10          709652      2019-07-01
11          709652      2019-06-24
12          709652      2019-03-25
13          709652      2019-03-14
14          709652      2014-03-31
15          709652      2016-06-23
16          709652      2014-05-14
17          368671      2015-04-19
18          368671      2014-04-10
19          368671      2014-04-01
20          368671      2014-03-21

Body:
You can use a subquery:

SELECT a.Student_id , a.Admit_date,
    (   SELECT MIN( b.Admit_date)
        FROM tempB b
        WHERE b.Admit_date >= a.Admit_date
        AND a.Student_id = b.Student_id
    ) as Admit_date2

FROM tempA a


问:
How to create a unique array in mongodb aggregation pipeline by preserving the order
I am trying to solve one use case. In aggregation pipeline need to create a unique array of one field by preserving the order by sorting the documents.

$addtoset creates a unique array but order is not preserved where as push preserves order but duplicates are allowed. How to deal this scenario?

Example:
Input documents in collection

{
studentid: 1,
createddate: 2020-05-24
exam:english
}

{
studentid: 1,
createddate: 2020-05-25
exam: maths
}

{
studentid: 1,
createddate: 2020-05-26
exam:physics
}

{
studentid: 1,
createddate: 2020-05-27
exam:maths
}

{
studentid: 1,
createddate: 2020-05-28
exam:chemistry
}
```

<p>Expected output:</p>

<pre class="lang-sh prettyprint-override"><code>{
studentid:1,
exam:[chemistry,maths,physiscs,english]

}
</code>```

答:
To get what you want first $push all of the values into an array, then use $addFields and $reduce the array to build an array of unique values.</p>

```<code>{$addFields:{
     outputarray:{
        $reduce:{
            input:"$inputArray",
            initialValue:[],
            in:{
              $cond:{
                  if: {$in: [ "$$this", "$$value"]},
                  then: "$$value",
                  else: {$concatArrays:["$$value",["$$this"]]}
              }
           }
        }
    }
}}
</code>```

Body:
I am trying to solve one use case. In aggregation pipeline need to create a unique array of one field by preserving the order by sorting the documents.

$addtoset creates a unique array but order is not preserved where as push preserves order but duplicates are allowed. How to deal this scenario?

Example:
Input documents in collection

{
studentid: 1,
createddate: 2020-05-24
exam:english
}

{
studentid: 1,
createddate: 2020-05-25
exam: maths
}

{
studentid: 1,
createddate: 2020-05-26
exam:physics
}

{
studentid: 1,
createddate: 2020-05-27
exam:maths
}

{
studentid: 1,
createddate: 2020-05-28
exam:chemistry
}

Expected output:

{
studentid:1,
exam:[chemistry,maths,physiscs,english]

}

Body:
To get what you want first $push all of the values into an array, then use $addFields and $reduce the array to build an array of unique values.

{$addFields:{
     outputarray:{
        $reduce:{
            input:"$inputArray",
            initialValue:[],
            in:{
              $cond:{
                  if: {$in: [ "$$this", "$$value"]},
                  then: "$$value",
                  else: {$concatArrays:["$$value",["$$this"]]}
              }
           }
        }
    }
}}


问:
Java "Type mismatch: cannot convert from int[][] to int" when returning copied array
I wanted to make function that returns a copied array, but I'm getting this error:

```<code>"Type mismatch: cannot convert from int[][] to int" on line 10,
</code>```

and I don't know what is wrong.

public class Usun {

    public int newTable(int[] table[]) {
        int[] newTable[];
        for (int i = 0; i <= table.length; i++)  {
            newTable[i] = table[i];
        }
        return newTable;
    }
}
```

答:
you want to return an array of int (int[]) not an int, also for declaring an array of int you use int[] table and not int[] table[]

also, as @small_ticket mentioned in his comment, you have to initialize your array, or you will get NullPointerException because you'll be trying to add elements to an uninitialized array, which results in compile time errors.

```<code>public class usun {
    public int[] newTable(int[] table) {

       int[] newTable = new int[table.length];
       for (int i = 0; i < table.length; i++)  {
          newTable[i] = table[i];
       }
       return newTable;
   }
}
</code>```

Body:
I wanted to make function that returns a copied array, but I'm getting this error:

"Type mismatch: cannot convert from int[][] to int" on line 10,

and I don't know what is wrong.

public class Usun {

    public int newTable(int[] table[]) {
        int[] newTable[];
        for (int i = 0; i <= table.length; i++)  {
            newTable[i] = table[i];
        }
        return newTable;
    }
}

Body:
you want to return an array of int (int[]) not an int, also for declaring an array of int you use int[] table and not int[] table[]

also, as @small_ticket mentioned in his comment, you have to initialize your array, or you will get NullPointerException because you'll be trying to add elements to an uninitialized array, which results in compile time errors.

public class usun {
    public int[] newTable(int[] table) {

       int[] newTable = new int[table.length];
       for (int i = 0; i < table.length; i++)  {
          newTable[i] = table[i];
       }
       return newTable;
   }
}


问:
How to make Font awesome 5 work with webpack
I'm trying to use Fontawesome in my Flask/webpack project.

The craziest thing is some point it worked then stopped, I changed something stupid, it worked again and finally it stopped working completely.

What I have:

package config:

```<code>  "devDependencies": {
        ...
        "css-loader": "^1.0.0",
        "node-sass": "^4.9.3",
        "sass-loader": "^7.1.0",
        "style-loader": "^0.23.0",
        "webpack": "^4.19.0",
        "webpack-cli": "^3.1.0",
        "webpack-merge": "^4.1.4"
    },
    "dependencies": {
        "@fortawesome/fontawesome-free": "^5.3.1",
        "bootstrap": "^4.1.3",
         ...
    }
</code>```

webpack config (rules section):

```<code>   test: /.(ttf|otf|eot|svg|woff(2)?)(\?[a-z0-9]+)?$/,
        use: [{
            loader: 'file-loader',
            options: {
            name: '[name].[ext]',
            outputPath: '../fonts/',
            publicPath: '../static/fonts'
            }
        }]
    },
    {
        test: /\.css$/,
        use: [
            'style-loader',
            'css-loader',
            'sass-loader'
        ]
    },
    {
        test: /\.scss$/,
        use: [
            "style-loader",
            "css-loader",
            "sass-loader"
        ]
    },
</code>```

webpack, entry section:

```<code>entry: {
        myStyles: './stles/myStyles.js'
    },
</code>```

myStyles.js:

```<code>import fontawesome from "@fortawesome/fontawesome-free/scss/fontawesome.scss";
import regular from "@fortawesome/fontawesome-free/scss/regular.scss";
import solid from "@fortawesome/fontawesome-free/scss/solid.scss";
import brands from "@fortawesome/fontawesome-free/scss/brands.scss";

fontawesome.library.add(solid, regular, brands)
</code>```

The last line though caused the error in Chrome:

```<code>Uncaught TypeError: Cannot read property 'add' of undefined
</code>```

I also tried to add imports into my entry scss and it worked at some point, then stopped:

```<code>$fa-font-path: '~@fortawesome/fontawesome-free/webfonts';
@import "~@fortawesome/fontawesome-free/scss/fontawesome";
@import "~@fortawesome/fontawesome-free/scss/regular";
@import "~@fortawesome/fontawesome-free/scss/solid";
@import "~@fortawesome/fontawesome-free/scss/brands";
</code>```

So, finally in my template I have:

```<code><i class="fas fa-user-circle fa-fw"></i>
</code>```

and what I see is only squares.

I checked Chrome, fonts are loaded (ttf, woff, woff2).

Please help. I already spent more than 6(!!!!) hours wasted on this problem and it's more than I spent on anything else related with webpack.

UPD I think I figured it out. I found that my public path was wrong, I mean this part of webpack config: publicPath: '../static/fonts' - it currently points to the static/fonts folder one level up from my html. First of all, relative path is wrong per se, secondly, a relative path will not work for other folders, third, I've changed it to the relative to the root: '/static/fonts' and it worked.

答:
this worked for me

```<code>import "@fortawesome/fontawesome-free/js/all.js";
import "@fortawesome/fontawesome-free/css/all.css";
</code>```

in: app/javascript/packs/application.js

my case: Rails 6 webpacker gem, webpack, yarn

installed via yarn add @fortawesome/fontawesome-free

from https://github.com/rails/webpacker/issues/619#issuecomment-590454028

Body:
I'm trying to use Fontawesome in my Flask/webpack project.

The craziest thing is some point it worked then stopped, I changed something stupid, it worked again and finally it stopped working completely.

What I have:

package config:

  "devDependencies": {
        ...
        "css-loader": "^1.0.0",
        "node-sass": "^4.9.3",
        "sass-loader": "^7.1.0",
        "style-loader": "^0.23.0",
        "webpack": "^4.19.0",
        "webpack-cli": "^3.1.0",
        "webpack-merge": "^4.1.4"
    },
    "dependencies": {
        "@fortawesome/fontawesome-free": "^5.3.1",
        "bootstrap": "^4.1.3",
         ...
    }

webpack config (rules section):

   test: /.(ttf|otf|eot|svg|woff(2)?)(\?[a-z0-9]+)?$/,
        use: [{
            loader: 'file-loader',
            options: {
            name: '[name].[ext]',
            outputPath: '../fonts/',
            publicPath: '../static/fonts'
            }
        }]
    },
    {
        test: /\.css$/,
        use: [
            'style-loader',
            'css-loader',
            'sass-loader'
        ]
    },
    {
        test: /\.scss$/,
        use: [
            "style-loader",
            "css-loader",
            "sass-loader"
        ]
    },

webpack, entry section:

entry: {
        myStyles: './stles/myStyles.js'
    },

myStyles.js:

import fontawesome from "@fortawesome/fontawesome-free/scss/fontawesome.scss";
import regular from "@fortawesome/fontawesome-free/scss/regular.scss";
import solid from "@fortawesome/fontawesome-free/scss/solid.scss";
import brands from "@fortawesome/fontawesome-free/scss/brands.scss";

fontawesome.library.add(solid, regular, brands)

The last line though caused the error in Chrome:

Uncaught TypeError: Cannot read property 'add' of undefined

I also tried to add imports into my entry scss and it worked at some point, then stopped:

$fa-font-path: '~@fortawesome/fontawesome-free/webfonts';
@import "~@fortawesome/fontawesome-free/scss/fontawesome";
@import "~@fortawesome/fontawesome-free/scss/regular";
@import "~@fortawesome/fontawesome-free/scss/solid";
@import "~@fortawesome/fontawesome-free/scss/brands";

So, finally in my template I have:

and what I see is only squares.

I checked Chrome, fonts are loaded (ttf, woff, woff2).

Please help. I already spent more than 6(!!!!) hours wasted on this problem and it's more than I spent on anything else related with webpack.

UPD I think I figured it out. I found that my public path was wrong, I mean this part of webpack config: publicPath: '../static/fonts' - it currently points to the static/fonts folder one level up from my html. First of all, relative path is wrong per se, secondly, a relative path will not work for other folders, third, I've changed it to the relative to the root: '/static/fonts' and it worked.

Body:
this worked for me

import "@fortawesome/fontawesome-free/js/all.js";
import "@fortawesome/fontawesome-free/css/all.css";

in: app/javascript/packs/application.js

my case: Rails 6 webpacker gem, webpack, yarn

installed via yarn add @fortawesome/fontawesome-free

from https://github.com/rails/webpacker/issues/619#issuecomment-590454028


问:
Can someone explain the parameter void(*pfn)(void*)?
I've come across this piece of code

```<code>inline pthread_t CreateThread(void(*pfn)(void*), void* parg, bool fWantHandle=false)
</code>```

I don't understand this part

```<code>void(*pfn)(void*)
</code>```

Can someone tell me what it means/is?

This is btw not listed in books for beginners so if you want to mention to read books, it's not there.

Afaik, void is datatype of a function meaning it will not return anything, however that part there...void is used on a pointer?

答:
This is called a function pointer.

It points to a function rather than a variable.

If it isn't in your book, you should get a better book.

ContentLicense: CC BY-SA 3.0

Body:
I've come across this piece of code

inline pthread_t CreateThread(void(*pfn)(void*), void* parg, bool fWantHandle=false)

I don't understand this part

void(*pfn)(void*)

Can someone tell me what it means/is?

This is btw not listed in books for beginners so if you want to mention to read books, it's not there.

Afaik, void is datatype of a function meaning it will not return anything, however that part there...void is used on a pointer?


问:
How to place program code in several memory regions?
There are several memory regions

```<code>MEMORY
{
  rom1 (rx)   : ORIGIN = 0x00000000,    LENGTH = 256k
  rom2 (rwx)  : ORIGIN = 0x10000000,    LENGTH = 16M
  ram1 (rw!x) : ORIGIN = 0x20000000,    LENGTH = 64k
  ram2 (rwx)  : ORIGIN = 0x21000000,    LENGTH = 16M
}
</code>```

How to place .text sections of all input files in the memory area of rom1, and if there is not enough space, then the remaining characters to place in rom2? Only one memory region can be specified in the description of the output section.

```<code>  .text :
  {
    *(.text)
  } > rom1
</code>```

答:
As far as I know, there is no way to distribute a section over several non-contiguous memory regions.

As suggested here, the section should be divided into several sections and then assigned to the memory regions.

In general this is a very handy documentation about the different possibilities.

Body:
There are several memory regions

MEMORY
{
  rom1 (rx)   : ORIGIN = 0x00000000,    LENGTH = 256k
  rom2 (rwx)  : ORIGIN = 0x10000000,    LENGTH = 16M
  ram1 (rw!x) : ORIGIN = 0x20000000,    LENGTH = 64k
  ram2 (rwx)  : ORIGIN = 0x21000000,    LENGTH = 16M
}

How to place .text sections of all input files in the memory area of rom1, and if there is not enough space, then the remaining characters to place in rom2? Only one memory region can be specified in the description of the output section.

  .text :
  {
    *(.text)
  } > rom1


问:
Disable bell in MacVim
I know this topic has been asked multiple times. But I don't seem to be able to disable the acoustic bell in MacVim. What I have in my .vimrc:

```<code>set noerrorbells
set novisualbell
set t_vb=
</code>```

Am I missing anything?

答:
Even
set belloff=all in your .vimrc

Title: Disable bell in MacVim

Body:
I know this topic has been asked multiple times. But I don't seem to be able to disable the acoustic bell in MacVim. What I have in my .vimrc:

set noerrorbells
set novisualbell
set t_vb=

Am I missing anything?

Body:
Even
set belloff=all in your .vimrc


问:
using wxpython calling frame function python interpreter returns error
```<code>class MyFrame(wx.Frame):
    def __init__(self, parent, title):
        super(MyFrame, self).__init__(parent, title=title, size=(620, 665))

        splitter = wx.SplitterWindow(self, wx.ID_ANY)
        self.MainPanel = NewPanel(splitter)
        self.MyNotebook = Nbook(splitter)
        splitter.SplitHorizontally(self.MainPanel, self.MyNotebook, sashPosition=210)
        self.sb = self.CreateStatusBar(3)
        self.MainPanel.Show()
        self.Centre()

    def setNotebookDisabled(self):
        self.MyNotebook.Enabled = False

    def PrintSomething(self):
        print("Something")

class NewPanel(wx.Panel):
    def __init__(self, parent):
        super(NewPanel, self).__init__(parent=parent)

    def Disable_Controls(self):
        self.GrandParent.MyNotebook.Enabled = False

class Nbook(wx.Notebook):
    def __init__(self, parent):
        super(Nbook, self).__init__(parent)

        # self.MyNotebook = wx.Notebook(splitter,wx.ID_ANY)
        page_one = NbPanel1(self)
        page_two = NbPanel2(self)
        page_three = NbPanel3(self)
        self.AddPage(page_one, "Cable")
        self.AddPage(page_two, "Busduct")
        self.AddPage(page_three, "Transformer")
</code>```

I can call PrintSomething() with success however...

The error:

File "c:/Users/Mark/Documents/FaultWireCalc/FCCalc.py", line 331, in Disable_Controls
    self.GrandParent.MyNotebook.Enabled = False

AttributeError: 'MyFrame' object has no attribute 'MyNotebook'

答:
This is not so much an answer as a work in progress, given that a comment simply wouldn't hack it.

Given that you haven't stated when or how the error occurs and it's occurring somewhere in 1000 lines of code, which we can't see, right about now might be a good time for

a minimal, complete and verifiable example (mcve)

https://stackoverflow.com/help/minimal-reproducible-example

As you seem reluctant to provide one, let's try this:

```<code>import wx

class MyFrame(wx.Frame):
    def __init__(self, parent, title):
        super(MyFrame, self).__init__(parent, title=title, size=(620, 665))

        splitter = wx.SplitterWindow(self, wx.ID_ANY)
        self.MainPanel = NewPanel(splitter)
        self.MyNotebook = Nbook(splitter)
        splitter.SplitHorizontally(self.MainPanel, self.MyNotebook, sashPosition=210)
        self.sb = self.CreateStatusBar(3)
        self.MainPanel.Show()
        self.Centre()
        self.Show()

    def setNotebookDisabled(self):
        self.MyNotebook.Enabled = False

    def PrintSomething(self):
        print("Something")

class NewPanel(wx.Panel):
    def __init__(self, parent):
        super(NewPanel, self).__init__(parent=parent)
        testbut = wx.Button(self, -1, "Panel Hit Me")
        self.Bind(wx.EVT_BUTTON, self.Disable_Controls)

    def Disable_Controls(self, event):
        self.GrandParent.MyNotebook.Enabled = not self.GrandParent.MyNotebook.IsEnabled()

class Nbook(wx.Notebook):
    def __init__(self, parent):
        super(Nbook, self).__init__(parent)

        # self.MyNotebook = wx.Notebook(splitter,wx.ID_ANY)
        page_one = wx.Panel(self)
        page_two = wx.Panel(self)
        page_three = wx.Panel(self)
        self.AddPage(page_one, "Cable")
        self.AddPage(page_two, "Busduct")
        self.AddPage(page_three, "Transformer")

if __name__ == "__main__":
    app = wx.App()
    frame = MyFrame(None, "Test")
    app.MainLoop()
</code>```

As you can see, it does function (below) the notebook can be enabled/disabled.

So, can you make this produce the error or deduce from it, how your code differs in the way or when the code is called, that produces the error?

You may find that GrandParent is not what you think it is! (I suspect splitter is involved)

You might try:

```<code>print("I am",self)
print("My parent is",self.Parent)
print("Granddad is",self.GrandParent)
print("His parent is",self.GrandParent.GetParent())
</code>```

The other thing you might try when calling the routine, is to call it directly:

```<code>MyFrame.setNotebookDisabled(parent.GetParent())
</code>```

or a variation to get the right parent, depending on where you are calling it from.

Over to you.

Body:
class MyFrame(wx.Frame):
    def __init__(self, parent, title):
        super(MyFrame, self).__init__(parent, title=title, size=(620, 665))

        splitter = wx.SplitterWindow(self, wx.ID_ANY)
        self.MainPanel = NewPanel(splitter)
        self.MyNotebook = Nbook(splitter)
        splitter.SplitHorizontally(self.MainPanel, self.MyNotebook, sashPosition=210)
        self.sb = self.CreateStatusBar(3)
        self.MainPanel.Show()
        self.Centre()

    def setNotebookDisabled(self):
        self.MyNotebook.Enabled = False

    def PrintSomething(self):
        print("Something")

class NewPanel(wx.Panel):
    def __init__(self, parent):
        super(NewPanel, self).__init__(parent=parent)

    def Disable_Controls(self):
        self.GrandParent.MyNotebook.Enabled = False

class Nbook(wx.Notebook):
    def __init__(self, parent):
        super(Nbook, self).__init__(parent)

        # self.MyNotebook = wx.Notebook(splitter,wx.ID_ANY)
        page_one = NbPanel1(self)
        page_two = NbPanel2(self)
        page_three = NbPanel3(self)
        self.AddPage(page_one, "Cable")
        self.AddPage(page_two, "Busduct")
        self.AddPage(page_three, "Transformer")

I can call PrintSomething() with success however...

The error:

File "c:/Users/Mark/Documents/FaultWireCalc/FCCalc.py", line 331, in Disable_Controls
    self.GrandParent.MyNotebook.Enabled = False

AttributeError: 'MyFrame' object has no attribute 'MyNotebook'

Body:
This is not so much an answer as a work in progress, given that a comment simply wouldn't hack it.

Given that you haven't stated when or how the error occurs and it's occurring somewhere in 1000 lines of code, which we can't see, right about now might be a good time for

a minimal, complete and verifiable example (mcve)

https://stackoverflow.com/help/minimal-reproducible-example

As you seem reluctant to provide one, let's try this:

import wx

class MyFrame(wx.Frame):
    def __init__(self, parent, title):
        super(MyFrame, self).__init__(parent, title=title, size=(620, 665))

        splitter = wx.SplitterWindow(self, wx.ID_ANY)
        self.MainPanel = NewPanel(splitter)
        self.MyNotebook = Nbook(splitter)
        splitter.SplitHorizontally(self.MainPanel, self.MyNotebook, sashPosition=210)
        self.sb = self.CreateStatusBar(3)
        self.MainPanel.Show()
        self.Centre()
        self.Show()

    def setNotebookDisabled(self):
        self.MyNotebook.Enabled = False

    def PrintSomething(self):
        print("Something")

class NewPanel(wx.Panel):
    def __init__(self, parent):
        super(NewPanel, self).__init__(parent=parent)
        testbut = wx.Button(self, -1, "Panel Hit Me")
        self.Bind(wx.EVT_BUTTON, self.Disable_Controls)

    def Disable_Controls(self, event):
        self.GrandParent.MyNotebook.Enabled = not self.GrandParent.MyNotebook.IsEnabled()

class Nbook(wx.Notebook):
    def __init__(self, parent):
        super(Nbook, self).__init__(parent)

        # self.MyNotebook = wx.Notebook(splitter,wx.ID_ANY)
        page_one = wx.Panel(self)
        page_two = wx.Panel(self)
        page_three = wx.Panel(self)
        self.AddPage(page_one, "Cable")
        self.AddPage(page_two, "Busduct")
        self.AddPage(page_three, "Transformer")

if __name__ == "__main__":
    app = wx.App()
    frame = MyFrame(None, "Test")
    app.MainLoop()

As you can see, it does function (below) the notebook can be enabled/disabled.

So, can you make this produce the error or deduce from it, how your code differs in the way or when the code is called, that produces the error?

You may find that GrandParent is not what you think it is! (I suspect splitter is involved)

You might try:

print("I am",self)
print("My parent is",self.Parent)
print("Granddad is",self.GrandParent)
print("His parent is",self.GrandParent.GetParent())

The other thing you might try when calling the routine, is to call it directly:

MyFrame.setNotebookDisabled(parent.GetParent())

or a variation to get the right parent, depending on where you are calling it from.

Over to you.


问:
Angular Mat-table with expandable rows - stop expansion on row button click
I want the row expansion disabled when a user clicks on buttons located on the row. Especially if we have a popup menu per row, it's really distracting when row expansion happens simultaneously. Is there a way to stop this from happening.

see the example below, when the user tries to click on three verticle dots at the right end of the row, row expands. In fact, this occurs for any button click on the row.
https://stackblitz.com/edit/angular-uy3mc4-cfmqoh

答:
A simple approach would be to call the $event.stopPropagation() event handler to prevent the panel receiving the click event. For example:

instead of

```<code><button mat-icon-button (click)="editAsset(row)" title="Edit">
   <mat-icon color="primary">mode_edit</mat-icon>
</button>
</code>```

use

```<code><button mat-icon-button (click)="$event.stopPropagation(); editAsset(row)" title="Edit">
   <mat-icon color="primary">mode_edit</mat-icon>
</button>
</code>```

Body:
A simple approach would be to call the $event.stopPropagation() event handler to prevent the panel receiving the click event. For example:

instead of

<button mat-icon-button (click)="editAsset(row)" title="Edit">
   <mat-icon color="primary">mode_edit</mat-icon>
</button>

use

<button mat-icon-button (click)="$event.stopPropagation(); editAsset(row)" title="Edit">
   <mat-icon color="primary">mode_edit</mat-icon>
</button>


问:
Ruby: Is there a way to get the enclosing Module const of a Class?
I'm doing some metaprogramming in Ruby, and I need to dynamically generate a sibling class inside of a module. In doing so, I want to call const_set on the module, but I don't know which Module constant to call that on until runtime. An example:

Given classes

```<code>Foo::Bar::Baz
Foo::Quox::Quack
</code>```

I want to be able to call a function like this (oversimplified here):

```<code>def generate_from klass
  mod = klass.enclosing_module # <- THIS LINE is the one I need to figure out
  mod.const_set("GeneratedClassName", Class.new)
end
</code>```

and what I want to end up with, when calling with Baz, is a new class defined as

```<code>Foo::Bar::GeneratedClassName
</code>```

and with a Quack, I want

```<code>Foo::Quox::GeneratedClassName
</code>```

The only way I know of is to split up klass.name, then repeatedly call const_get on those strings, constantized. Does anyone know of a more elegant way?

答:
Got it.
ActiveSupport has this Ruby extension, Module#parent. It's good enough for my use.</p>

Body:
I'm doing some metaprogramming in Ruby, and I need to dynamically generate a sibling class inside of a module. In doing so, I want to call const_set on the module, but I don't know which Module constant to call that on until runtime. An example:

Given classes

Foo::Bar::Baz
Foo::Quox::Quack

I want to be able to call a function like this (oversimplified here):

def generate_from klass
  mod = klass.enclosing_module # <- THIS LINE is the one I need to figure out
  mod.const_set("GeneratedClassName", Class.new)
end

and what I want to end up with, when calling with Baz, is a new class defined as

Foo::Bar::GeneratedClassName

and with a Quack, I want

Foo::Quox::GeneratedClassName

The only way I know of is to split up klass.name, then repeatedly call const_get on those strings, constantized. Does anyone know of a more elegant way?


问:
INSTALL_FAILED_NO_MATCHING_ABIS
When i use
implementation files ('libs/signalr-client-sdk.jar')
Then my application not install in my Device
Here is image where error show
I try so many solution like

```<code>1:`ndk.abiFilters 'armeabi-v7a','arm64-v8a','x86','x86_64'`

2:splits {
            abi {
                enable true
                reset()
                include 'x86', 'armeabi-v7a'
                universalApk true
            }
        }
3:-r -t in Flag
</code>```

But not working any other Solution

答:
Did you try as follows:

disable "Use libusb backend"

Title: INSTALL_FAILED_NO_MATCHING_ABIS

Body:
When i use
implementation files ('libs/signalr-client-sdk.jar')
Then my application not install in my Device
Here is image where error show
I try so many solution like

1:`ndk.abiFilters 'armeabi-v7a','arm64-v8a','x86','x86_64'`

2:splits {
            abi {
                enable true
                reset()
                include 'x86', 'armeabi-v7a'
                universalApk true
            }
        }
3:-r -t in Flag

But not working any other Solution


问:
How to use matrix-shaped inputs for dense layer in keras?
To build a regression/forecast model I'd like to take a matrix of sensor-readings (rows~sensors, columns~timepoints) and predict a future trend for these sensors.

Example implementation

```<code># install.packages(c("keras", "tensorflow"))
library(keras)
library(tensorflow)

#' Prepare some training data mapping matrices to other smaller matrices where the response entries correspond to basic math
n = 1000000
nb = 10
mx = matrix(rnorm(6 * n, 0, 1), nrow = n, byrow = TRUE)
my = matrix(0, nrow = n, ncol = 3)
eps = 0.01

for (i in 1 : n) {
    x1 = mx[i, 1]; x2 = mx[i, 2]; x3 = mx[i, 3]; x4 = mx[i, 4]; x5 = mx[i, 5]; x6 = mx[i, 6];
    s1 = x1 * x1;   s2 = x2 * x2;   s3 = x3 * x3;   s4 = x4 * x4;   s5 = x5 * x5;   s6 = x6 * x6;
    zz = rnorm(1, 0, 1)

    my[i, 1] = (x1 + x2 + x3 + x4 + x5 + x6 + eps * zz)
    my[i, 2] = (s1 + s2 + eps * zz * zz)
    my[i, 3] = (x1 * s1 + s2 + x5 * s5 + x6 * s6 + eps * zz)
}

#' Recast into tf types
x_train = tf$constant(mx, shape = as.integer(c(n / nb, nb, 6)))
# FLATTENING the input would work WOULD WORK:
# x_train = tf$constant(mx, shape = as.integer(c(n / nb, nb, 6)))
y_train = tf$constant(my, shape = as.integer(c(n / nb, nb, 3)))

#' Build the model
inputShape = dim(x_train)[- 1]
outputShape = dim(y_train)[- 1]

model1 = keras_model_sequential() %>%
    layer_dense(units = 64, activation = "relu", input_shape = inputShape) %>%
    layer_dense(units = 256, activation = "relu") %>%
    layer_dense(units = prod(outputShape)) %>%
    layer_reshape(outputShape) %>%
    compile(loss = "mse", optimizer = "adam", metrics = list("mean_absolute_error", "mean_squared_error"))

model1 %>% summary
fit(model1, x_train, y_train, epochs = 3, validation_split = 0.2, verbose = 1)

model2 = keras_model_sequential() %>%
## tbd layer_input  --> layer_rehsape --> layer_dense (which seems to work best with non-matrix valued inputs
    layer_dense(units = 64, activation = "relu", input_shape = inputShape) %>%
    layer_dense(units = 256, activation = "relu") %>%
    layer_dense(units = outputShape[2]) %>%
# layer_dense(units = prod(outputShape)) %>%
# layer_reshape(outputShape) %>%
    compile(loss = "mse", optimizer = "adam", metrics = list("mean_absolute_error", "mean_squared_error"))

model2 %>% summary

fit(model2, x_train, y_train, epochs = 3, validation_split = 0.2, verbose = 1)
</code>```

Summary of model1 is

```<code>> model1 %>% summary
Model: "sequential_42"
________________________________________________________________________________
Layer (type)                        Output Shape                    Param #
================================================================================
dense_126 (Dense)                   (None, 10, 64)                  448
________________________________________________________________________________
dense_127 (Dense)                   (None, 10, 256)                 16640
________________________________________________________________________________
dense_128 (Dense)                   (None, 10, 30)                  7710
________________________________________________________________________________
reshape_29 (Reshape)                (None, 10, 3)                   0
================================================================================
Total params: 24,798
Trainable params: 24,798
Non-trainable params: 0
________________________________________________________________________________
</code>```

Shape of mode2 is

```<code>> model2 %>% summary
Model: "sequential_43"
________________________________________________________________________________
Layer (type)                        Output Shape                    Param #
================================================================================
dense_129 (Dense)                   (None, 10, 64)                  448
________________________________________________________________________________
dense_130 (Dense)                   (None, 10, 256)                 16640
________________________________________________________________________________
dense_131 (Dense)                   (None, 10, 3)                   771
================================================================================
Total params: 17,859
Trainable params: 17,859
Non-trainable params: 0
________________________________________________________________________________
</code>```

Although both models have the same input and output shape, model1 fails to train with with

```<code>Error in py_call_impl(callable, dots$args, dots$keywords) :
  ValueError: in user code:

    C:\Users\brandl\AppData\Local\r-miniconda\envs\r-reticulate\lib\site-packages\tensorflow\python\keras\engine\training.py:571 train_function  *
        outputs = self.distribute_strategy.run(
    C:\Users\brandl\AppData\Local\r-miniconda\envs\r-reticulate\lib\site-packages\tensorflow\python\distribute\distribute_lib.py:951 run  **
        return self._extended.call_for_each_replica(fn, args=args, kwargs=kwargs)
    C:\Users\brandl\AppData\Local\r-miniconda\envs\r-reticulate\lib\site-packages\tensorflow\python\distribute\distribute_lib.py:2290 call_for_each_replica
        return self._call_for_each_replica(fn, args, kwargs)
    C:\Users\brandl\AppData\Local\r-miniconda\envs\r-reticulate\lib\site-packages\tensorflow\python\distribute\distribute_lib.py:2649 _call_for_each_replica
        return fn(*args, **kwargs)
    C:\Users\brandl\AppData\Local\r-miniconda\envs\r-reticulate\lib\site-packages\tensorflow\python\keras\engine\training.py:531 train_s
</code>```

By flattening the input it works (see the commented line where x_train is defined). However,  I wonder why we can't use matrix-shaped input value here for the dense layer (or how to do so correctly)?

Note: The example is written using https://keras.rstudio.com/ but since it's a rather 1:1 wrapper API, I'd happy with a python answer as well.

答: Well, since you are have time-depend dataset, why not try the keras.layer.TimeDistributed API and see if your data sequence is aligned sort by time points?

Body:
To build a regression/forecast model I'd like to take a matrix of sensor-readings (rows~sensors, columns~timepoints) and predict a future trend for these sensors.

Example implementation

# install.packages(c("keras", "tensorflow"))
library(keras)
library(tensorflow)

#' Prepare some training data mapping matrices to other smaller matrices where the response entries correspond to basic math
n = 1000000
nb = 10
mx = matrix(rnorm(6 * n, 0, 1), nrow = n, byrow = TRUE)
my = matrix(0, nrow = n, ncol = 3)
eps = 0.01

for (i in 1 : n) {
    x1 = mx[i, 1]; x2 = mx[i, 2]; x3 = mx[i, 3]; x4 = mx[i, 4]; x5 = mx[i, 5]; x6 = mx[i, 6];
    s1 = x1 * x1;   s2 = x2 * x2;   s3 = x3 * x3;   s4 = x4 * x4;   s5 = x5 * x5;   s6 = x6 * x6;
    zz = rnorm(1, 0, 1)

    my[i, 1] = (x1 + x2 + x3 + x4 + x5 + x6 + eps * zz)
    my[i, 2] = (s1 + s2 + eps * zz * zz)
    my[i, 3] = (x1 * s1 + s2 + x5 * s5 + x6 * s6 + eps * zz)
}

#' Recast into tf types
x_train = tf$constant(mx, shape = as.integer(c(n / nb, nb, 6)))
# FLATTENING the input would work WOULD WORK:
# x_train = tf$constant(mx, shape = as.integer(c(n / nb, nb, 6)))
y_train = tf$constant(my, shape = as.integer(c(n / nb, nb, 3)))

#' Build the model
inputShape = dim(x_train)[- 1]
outputShape = dim(y_train)[- 1]

model1 = keras_model_sequential() %>%
    layer_dense(units = 64, activation = "relu", input_shape = inputShape) %>%
    layer_dense(units = 256, activation = "relu") %>%
    layer_dense(units = prod(outputShape)) %>%
    layer_reshape(outputShape) %>%
    compile(loss = "mse", optimizer = "adam", metrics = list("mean_absolute_error", "mean_squared_error"))

model1 %>% summary
fit(model1, x_train, y_train, epochs = 3, validation_split = 0.2, verbose = 1)

model2 = keras_model_sequential() %>%
## tbd layer_input  --> layer_rehsape --> layer_dense (which seems to work best with non-matrix valued inputs
    layer_dense(units = 64, activation = "relu", input_shape = inputShape) %>%
    layer_dense(units = 256, activation = "relu") %>%
    layer_dense(units = outputShape[2]) %>%
# layer_dense(units = prod(outputShape)) %>%
# layer_reshape(outputShape) %>%
    compile(loss = "mse", optimizer = "adam", metrics = list("mean_absolute_error", "mean_squared_error"))

model2 %>% summary

fit(model2, x_train, y_train, epochs = 3, validation_split = 0.2, verbose = 1)

Summary of model1 is

> model1 %>% summary
Model: "sequential_42"
________________________________________________________________________________
Layer (type)                        Output Shape                    Param #
================================================================================
dense_126 (Dense)                   (None, 10, 64)                  448
________________________________________________________________________________
dense_127 (Dense)                   (None, 10, 256)                 16640
________________________________________________________________________________
dense_128 (Dense)                   (None, 10, 30)                  7710
________________________________________________________________________________
reshape_29 (Reshape)                (None, 10, 3)                   0
================================================================================
Total params: 24,798
Trainable params: 24,798
Non-trainable params: 0
________________________________________________________________________________

Shape of mode2 is

> model2 %>% summary
Model: "sequential_43"
________________________________________________________________________________
Layer (type)                        Output Shape                    Param #
================================================================================
dense_129 (Dense)                   (None, 10, 64)                  448
________________________________________________________________________________
dense_130 (Dense)                   (None, 10, 256)                 16640
________________________________________________________________________________
dense_131 (Dense)                   (None, 10, 3)                   771
================================================================================
Total params: 17,859
Trainable params: 17,859
Non-trainable params: 0
________________________________________________________________________________

Although both models have the same input and output shape, model1 fails to train with with

Error in py_call_impl(callable, dots$args, dots$keywords) :
  ValueError: in user code:

    C:\Users\brandl\AppData\Local\r-miniconda\envs\r-reticulate\lib\site-packages\tensorflow\python\keras\engine\training.py:571 train_function  *
        outputs = self.distribute_strategy.run(
    C:\Users\brandl\AppData\Local\r-miniconda\envs\r-reticulate\lib\site-packages\tensorflow\python\distribute\distribute_lib.py:951 run  **
        return self._extended.call_for_each_replica(fn, args=args, kwargs=kwargs)
    C:\Users\brandl\AppData\Local\r-miniconda\envs\r-reticulate\lib\site-packages\tensorflow\python\distribute\distribute_lib.py:2290 call_for_each_replica
        return self._call_for_each_replica(fn, args, kwargs)
    C:\Users\brandl\AppData\Local\r-miniconda\envs\r-reticulate\lib\site-packages\tensorflow\python\distribute\distribute_lib.py:2649 _call_for_each_replica
        return fn(*args, **kwargs)
    C:\Users\brandl\AppData\Local\r-miniconda\envs\r-reticulate\lib\site-packages\tensorflow\python\keras\engine\training.py:531 train_s

By flattening the input it works (see the commented line where x_train is defined). However,  I wonder why we can't use matrix-shaped input value here for the dense layer (or how to do so correctly)?

Note: The example is written using https://keras.rstudio.com/ but since it's a rather 1:1 wrapper API, I'd happy with a python answer as well.


问:
jQuery get img width after src change and before fadeIn
I've got quite the problem with jQuery and a custom photo gallery I am building.  I've searched high and low and tried endlessly different solutions but nothing is working perfectly.  So let me present the information:

This photo gallery has thumbnails on the left side and a big image in the center.  Every thumbnail can be clicked which calls a function passing in its' ID.  What I want it to do is, AJAX POST to server to get image comment and image name.  Fadeout the current big picture div, switch the src in the img tag, get the new image's width, set the width of an overlaying comment div, fadeIn the big picture div.

The problem is that I can't get the width of the new image after it has loaded (even using the a form of .load() to wait for the image to finish loading).  Now I can get it to work when I fadeIn the new image and then get the width but that isn't what I need.  I need to get the width and set the div's width before I fadeIn.

Any ideas or corrections would be great, hopefully I have provided enough information.

Here is the code I am wrestling with:

```<code>function thumbClick(val) {
    $.post('ajax.php', {
        photo_in: val
    }, function (data) {
        $('div#picture').fadeOut('slow', function () {

            //$('img#big-picture').load(function(){
            $('img#big-picture').one('load', function () {

                //alert($('img#big-picture').width());
                //will alert 0
                $('div#picture').fadeIn('slow', function () {
                    $('div#comment-box').width($('img#big-picture').width());
                    //set comment to what I want
                    $('p#comment').html("");
                    //alert($('img#big-picture').width());
                    //will alert new image width after FadeIN
                    $('p#comment').html(data.comment);
                });

            }); //end of one(load)
            $('img#big-picture').attr("src", data.newImage);

        }); //end of fadeout
    }, "json"); //end of post
}
</code>```

答:
The width is zero because hidden elements (elements with display: none have, by definition, zero height and width). After fadeOut(), jQuery hides the element(s). A few different solutions:

Use .fadeTo(), not .fadeOut():

```<code>$('#picture').fadeTo('slow', 0, function () {
    var $pic = $(this);

    $('#big-picture').one('load', function () {

        var $bigPic = $(this);

        $pic.fadeIn('slow', function () {
            $('#comment-box').width($bigPic.width());
            $('#comment').html(data.comment);
        });

    }).attr('src', data.newImage);
});
</code>```

Use a separage  element:

```<code>$('#picture').fadeOut('slow', function () {
    var $pic = $(this);

    $('#big-picture').one('load', function () {

        var img = new Image(),
            width;

        img.src = this.src;
        width = img.width;

        $pic.fadeIn('slow', function () {
            $('#comment-box').width(width);
            $('#comment').html(data.comment);
        });

    }).attr('src', data.newImage);
});
</code>```

Use the "off-left" technique:

CSS

```<code>.off-left {
    position: absolute;
    left: -99999px;
}
</code>```

JavaScript

```<code>$('#picture').fadeOut('slow', function () {
    var $pic = $(this);

    $('#big-picture').one('load', function () {

        var $this = $(this),
            width = $this.addClass('off-left').show().width();

        $this.removeClass('off-left').hide();

        $('#picture').fadeIn('slow', function () {
            $('#comment-box').width(width);
            $('#comment').html(data.comment);
        });

    }).attr('src', data.newImage);
});
</code>```

Notes

When using an ID selector, there's no point in qualifying the selector further, since element IDs must be unique.

Pick a quote style and use it consistently. Avoid mixing single- and double-quotes as string delimiters.

Body:
I've got quite the problem with jQuery and a custom photo gallery I am building.  I've searched high and low and tried endlessly different solutions but nothing is working perfectly.  So let me present the information:

This photo gallery has thumbnails on the left side and a big image in the center.  Every thumbnail can be clicked which calls a function passing in its' ID.  What I want it to do is, AJAX POST to server to get image comment and image name.  Fadeout the current big picture div, switch the src in the img tag, get the new image's width, set the width of an overlaying comment div, fadeIn the big picture div.

The problem is that I can't get the width of the new image after it has loaded (even using the a form of .load() to wait for the image to finish loading).  Now I can get it to work when I fadeIn the new image and then get the width but that isn't what I need.  I need to get the width and set the div's width before I fadeIn.

Any ideas or corrections would be great, hopefully I have provided enough information.

Here is the code I am wrestling with:

function thumbClick(val) {
    $.post('ajax.php', {
        photo_in: val
    }, function (data) {
        $('div#picture').fadeOut('slow', function () {

            //$('img#big-picture').load(function(){
            $('img#big-picture').one('load', function () {

                //alert($('img#big-picture').width());
                //will alert 0
                $('div#picture').fadeIn('slow', function () {
                    $('div#comment-box').width($('img#big-picture').width());
                    //set comment to what I want
                    $('p#comment').html("");
                    //alert($('img#big-picture').width());
                    //will alert new image width after FadeIN
                    $('p#comment').html(data.comment);
                });

            }); //end of one(load)
            $('img#big-picture').attr("src", data.newImage);

        }); //end of fadeout
    }, "json"); //end of post
}

Body:
The width is zero because hidden elements (elements with display: none have, by definition, zero height and width). After fadeOut(), jQuery hides the element(s). A few different solutions:

Use .fadeTo(), not .fadeOut():

$('#picture').fadeTo('slow', 0, function () {
    var $pic = $(this);

    $('#big-picture').one('load', function () {

        var $bigPic = $(this);

        $pic.fadeIn('slow', function () {
            $('#comment-box').width($bigPic.width());
            $('#comment').html(data.comment);
        });

    }).attr('src', data.newImage);
});

Use a separage <img> element:

$('#picture').fadeOut('slow', function () {
    var $pic = $(this);

    $('#big-picture').one('load', function () {

        var img = new Image(),
            width;

        img.src = this.src;
        width = img.width;

        $pic.fadeIn('slow', function () {
            $('#comment-box').width(width);
            $('#comment').html(data.comment);
        });

    }).attr('src', data.newImage);
});

Use the "off-left" technique:

CSS

.off-left {
    position: absolute;
    left: -99999px;
}

JavaScript

$('#picture').fadeOut('slow', function () {
    var $pic = $(this);

    $('#big-picture').one('load', function () {

        var $this = $(this),
            width = $this.addClass('off-left').show().width();

        $this.removeClass('off-left').hide();

        $('#picture').fadeIn('slow', function () {
            $('#comment-box').width(width);
            $('#comment').html(data.comment);
        });

    }).attr('src', data.newImage);
});

Notes

When using an ID selector, there's no point in qualifying the selector further, since element IDs must be unique.

Pick a quote style and use it consistently. Avoid mixing single- and double-quotes as string delimiters.


问:
Understanding Coefficient of Determination
I was going through the documentation to understand the Coefficient of Determination and from the document i got an understanding that Coefficient of Determination is nothing but R x R (correlation coefficient)

so i took the housing price dataset from kaggle.com and started to try on it for better understanding, this is my code

took the correlation coefficient

```<code>test_data=pd.read_csv(r'\house_price\test.csv')
_d=test_data.loc[:,['MSSubClass','LotFrontage']]
_d.fillna(0,inplace=True)
_d.corr()
</code>```

now, taking the Coefficient of Determination like this

```<code>from sklearn.metrics import r2_score
r2_score(_d['MSSubClass'],_d['LotFrontage'])
</code>```

for which, i got the value -0.9413195412943647

ideally shouldnt it be 0.060531252961 ? as -0.246031 x -0.246031 = 0.060531252961

答:
following the docs: https://scikit-learn.org/stable/modules/model_evaluation.html#r2-score

the r2_score is defined as:

Whereer the df.corrmethod is (with pearson correlation):

so let's built an example:

```<code>x   y
1   1
1   0
0   0
1   1
</code>```

correlation: 4*(1+0+0+1) - 3*2 / sqrt(4*(3-9)*4*(2-4)) = 8-6/ sqr(-24*4*-8) = 2/sqr(-24*4*-8)
wherever R2 is: 1-((0)^2+(1)^2+(0)^2+(0)^2) / (1-0.75)^2+(1-0.75)^2+(0 - 0.75)^2 +(1-0.75)^2

Hope that helps

Body:
I was going through the documentation to understand the Coefficient of Determination and from the document i got an understanding that Coefficient of Determination is nothing but R x R (correlation coefficient)

so i took the housing price dataset from kaggle.com and started to try on it for better understanding, this is my code

took the correlation coefficient

test_data=pd.read_csv(r'\house_price\test.csv')
_d=test_data.loc[:,['MSSubClass','LotFrontage']]
_d.fillna(0,inplace=True)
_d.corr()

now, taking the Coefficient of Determination like this

from sklearn.metrics import r2_score
r2_score(_d['MSSubClass'],_d['LotFrontage'])

for which, i got the value -0.9413195412943647

ideally shouldnt it be 0.060531252961 ? as -0.246031 x -0.246031 = 0.060531252961

Body:
following the docs: https://scikit-learn.org/stable/modules/model_evaluation.html#r2-score

the r2_score is defined as:

Whereer the df.corrmethod is (with pearson correlation):

so let's built an example:

x   y
1   1
1   0
0   0
1   1

correlation: 4*(1+0+0+1) - 3*2 / sqrt(4*(3-9)*4*(2-4)) = 8-6/ sqr(-24*4*-8) = 2/sqr(-24*4*-8)
wherever R2 is: 1-((0)^2+(1)^2+(0)^2+(0)^2) / (1-0.75)^2+(1-0.75)^2+(0 - 0.75)^2 +(1-0.75)^2

Hope that helps


答:
newTable is an 2 dimensional array. You try to return this array in your method with a return type of int.

Change the return type of your function to int[][]. Also, newTable is not properly initialized in your code.

In addition, you can use built-in methods like Arrays#copyOf and so on for array deep copying as you don't have to write them yourself.

Title: Java "Type mismatch: cannot convert from int[][] to int" when returning copied array

Body:
I wanted to make function that returns a copied array, but I'm getting this error:

"Type mismatch: cannot convert from int[][] to int" on line 10,

and I don't know what is wrong.

public class Usun {

    public int newTable(int[] table[]) {
        int[] newTable[];
        for (int i = 0; i <= table.length; i++)  {
            newTable[i] = table[i];
        }
        return newTable;
    }
}


问:
Does dart support operator overloading? (not to be confused with overriding)
This sounds like an exact duplicate of: Does dart support operator overloading

But the name is misleading, the question is about how to override existing operators (the == operator).

As far as I understand, overloading a function means having multiple implementations that vary only in their parameters, but not in the name of the function:

```<code>int max(int a, int b);
double max(double a, double b);
</code>```

By contrast, overriding means rewriting an existing implementation. Since the original function is replaced, there are no name clashes. This is common in OOP where you extend a base class and override its methods.

The docs say that there are overridable operators. So I see that you can implement custom operators. At the same time, dart does not support overloading methods. So, does dart support overloading operators?

Would it be possible to write the following code:

```<code>class Matrix{
  Matrix operator+(int b){//...};
  Matrix operator+(Matrix b({//...};
}
</code>```

答:
After loading up dartpad, dart does NOT seem to support overloading operators:

```<code>class A{
  operator*(int b){
    print("mul int");
  }
  operator*(double b){
    print("mul double");
  }
}
</code>```

Leads to an error message:

```<code>Error compiling to JavaScript:
main.dart:5:11:
Error: '*' is already declared in this scope.
  operator*(double b){
</code>```

Body:
This sounds like an exact duplicate of: Does dart support operator overloading

But the name is misleading, the question is about how to override existing operators (the == operator).

As far as I understand, overloading a function means having multiple implementations that vary only in their parameters, but not in the name of the function:

int max(int a, int b);
double max(double a, double b);

By contrast, overriding means rewriting an existing implementation. Since the original function is replaced, there are no name clashes. This is common in OOP where you extend a base class and override its methods.

The docs say that there are overridable operators. So I see that you can implement custom operators. At the same time, dart does not support overloading methods. So, does dart support overloading operators?

Would it be possible to write the following code:

class Matrix{
  Matrix operator+(int b){//...};
  Matrix operator+(Matrix b({//...};
}

Body:
After loading up dartpad, dart does NOT seem to support overloading operators:

class A{
  operator*(int b){
    print("mul int");
  }
  operator*(double b){
    print("mul double");
  }
}

Leads to an error message:

Error compiling to JavaScript:
main.dart:5:11:
Error: '*' is already declared in this scope.
  operator*(double b){


问:
MD5 value for file in a remote FTP server using Python ftplib
Once transferring a file to a server using ftplib, how do I determine the MD5 of that file to the one in my local server?</p>
```<code>from ftplib import FTP
import hashlib

ftp = FTP('server')
ftp.login('username','password')
ftp.cwd('path_to_upload')

file_to_upload = open(file,'rb')
filename = os.path.basename(file)
ftp.storbinary('STOR ' + filename, file_to_upload)

local_file_hash = hashlib.md5(open(file, 'rb').read()).hexdigest()
# not sure how to achieve this
server_file_hash = hashlib.md5(open(filename, 'rb').read()).hexdigest()

if local_file_hash == server_file_hash:
     print("Successful transfer")
else:
     print("Failure transfer")
</code>```

答:
First, make sure your remote server supports the checksum calculation at all. Many do not. I believe there's even no standard FTP command to calculate a checksum of a remote file. There were many proposals and there are many proprietary solutions.

The latest proposal is:

https://datatracker.ietf.org/doc/html/draft-bryan-ftpext-hash-02

Some of the commands that can be used to calculate checksum are: XSHA1, XSHA256, XSHA512, XMD5, MD5, XCRC and HASH.

You can test that with WinSCP FTP client. The WinSCP supports all the previously mentioned commands. Test its checksum calculation function or the checksum scripting command. If they work, enable logging and check, what command and what syntax WinSCP uses against your server. (I'm the author of WinSCP)

Once you find out, what command does your server support (if any), you can use FTP.voidcmd method:

```<code>ftp.voidcmd("XSHA1 " + filename)
</code>```

Body:
Once transferring a file to a server using ftplib, how do I determine the MD5 of that file to the one in my local server?

from ftplib import FTP
import hashlib

ftp = FTP('server')
ftp.login('username','password')
ftp.cwd('path_to_upload')

file_to_upload = open(file,'rb')
filename = os.path.basename(file)
ftp.storbinary('STOR ' + filename, file_to_upload)

local_file_hash = hashlib.md5(open(file, 'rb').read()).hexdigest()
# not sure how to achieve this
server_file_hash = hashlib.md5(open(filename, 'rb').read()).hexdigest()

if local_file_hash == server_file_hash:
     print("Successful transfer")
else:
     print("Failure transfer")

Body:
First, make sure your remote server supports the checksum calculation at all. Many do not. I believe there's even no standard FTP command to calculate a checksum of a remote file. There were many proposals and there are many proprietary solutions.

The latest proposal is:

https://datatracker.ietf.org/doc/html/draft-bryan-ftpext-hash-02

Some of the commands that can be used to calculate checksum are: XSHA1, XSHA256, XSHA512, XMD5, MD5, XCRC and HASH.

You can test that with WinSCP FTP client. The WinSCP supports all the previously mentioned commands. Test its checksum calculation function or the checksum scripting command. If they work, enable logging and check, what command and what syntax WinSCP uses against your server. (I'm the author of WinSCP)

Once you find out, what command does your server support (if any), you can use FTP.voidcmd method:

ftp.voidcmd("XSHA1 " + filename)


问:
How to check number of digits from BigDecimal?
The requirement is to check if the number of digits is less than 7 digits in that case insert in DB else don't. I have tried the following solutions:

First solution:

```<code>public static void checkNoOfDigitVal(BigDecimal bigDecVal) {
    BigInteger digits = bigDecVal.toBigInteger();
    BigInteger ten = BigInteger.valueOf(10);
    int count = 0;
    do {
        digits = digits.divide(ten);
        count++;
    } while (!digits.equals(BigInteger.ZERO));
    System.out.println("Number of digits : " + count);
}
</code>```

First solution works fine sometimes but sometimes the condition in while loop is not satisfied and it keeps on increasing the count number leading to endless count.

Second solution:

```<code>public static void checkNoOfDigitsVal(BigDecimal bigDecVal) {
    String string = bigDecVal.toString();
    String[] splitedString = string.split("\\.");
    String[] newVal = splitedString[0].split("");
    int a = newVal.length - 1;
    if (a <= 6) {
        System.out.println("correct size insert into DB: " + a);
    } else {
        System.out.println("Incorrect size insert cancel: " + a);
    }
}
</code>```

For example, if the value is 999999.9999, the second solution will return newVal.length = 6.

Please suggest a better solution to check the number of digits for big decimal where looping overhead can be minimized.

答:
If you want to ignore the Dot (".") and count. then try this :

```<code>        int count = 0;
        BigDecimal bigDecimal = new BigDecimal("123.1000");

        String[] split = bigDecimal.toString()
                .split("\\.");

        for (String element : split) {
            count = count + element.length();
        }

        System.out.println("Total digits are " + count);

</code>```

Body:
The requirement is to check if the number of digits is less than 7 digits in that case insert in DB else don't. I have tried the following solutions:

First solution:

public static void checkNoOfDigitVal(BigDecimal bigDecVal) {
    BigInteger digits = bigDecVal.toBigInteger();
    BigInteger ten = BigInteger.valueOf(10);
    int count = 0;
    do {
        digits = digits.divide(ten);
        count++;
    } while (!digits.equals(BigInteger.ZERO));
    System.out.println("Number of digits : " + count);
}

First solution works fine sometimes but sometimes the condition in while loop is not satisfied and it keeps on increasing the count number leading to endless count.

Second solution:

public static void checkNoOfDigitsVal(BigDecimal bigDecVal) {
    String string = bigDecVal.toString();
    String[] splitedString = string.split("\\.");
    String[] newVal = splitedString[0].split("");
    int a = newVal.length - 1;
    if (a <= 6) {
        System.out.println("correct size insert into DB: " + a);
    } else {
        System.out.println("Incorrect size insert cancel: " + a);
    }
}

For example, if the value is 999999.9999, the second solution will return newVal.length = 6.

Please suggest a better solution to check the number of digits for big decimal where looping overhead can be minimized.

Body:
If you want to ignore the Dot (".") and count. then try this :

        int count = 0;
        BigDecimal bigDecimal = new BigDecimal("123.1000");

        String[] split = bigDecimal.toString()
                .split("\\.");

        for (String element : split) {
            count = count + element.length();
        }

        System.out.println("Total digits are " + count);


答:
It's a function pointer to a function returning void and accepting void *.

```<code>void example(void *arg);
</code>```

You can find more information about function pointers in C++ (and in C) at The Function Pointer Tutorials.

Title: Can someone explain the parameter void(*pfn)(void*)?

Body:
I've come across this piece of code

inline pthread_t CreateThread(void(*pfn)(void*), void* parg, bool fWantHandle=false)

I don't understand this part

void(*pfn)(void*)

Can someone tell me what it means/is?

This is btw not listed in books for beginners so if you want to mention to read books, it's not there.

Afaik, void is datatype of a function meaning it will not return anything, however that part there...void is used on a pointer?

Body:
It's a function pointer to a function returning void and accepting void *.

void example(void *arg);

You can find more information about function pointers in C++ (and in C) at The Function Pointer Tutorials.


问:
ServiceStack Service class with constructor
I’m using Service Stack, and I can´t (or I don´t know how make a Service class with constructor).

Here is what I did:

```<code>public class AppHost : AppSelfHostBase
{
    public AppHost()
        : base("ClientService", typeof(ClientService).Assembly)
    {
    }

    public override void Configure(Container container)
    {
    }
}

public class Context : ApplicationContext
{
    //This class is invoked from program.cs (winform application)
    //Here i have the logic of what form should i start.
    var listeningOn = string.Format("http://*:{0}/", port);
    var appHost = new AppHost();
    appHost.Init();
    appHost.Start(listeningOn);
    ClientService cl = new ClientService((ILayout)f, i);
}

public class ClientService : Service
{
    private readonly ILayout _activeForm;
    private static Init _initConf;

    public ClientService(ILayout f, Init i)
    {
        _activeForm = f;
        _activeForm.GetClientData(i);
        _initConf = i;
    }

    public HttpResult Post(Person request)
    {
       //Here i use _activeForm and _initConf
    }
}
</code>```

So, as I said, in the class ClientService, I wanna make a constructor, but when I make a request to the post message, it shows me the following error:

Error trying to resolve Service
  'DexBrokerClient.Services.ClientService' or one of its auto wired
  dependencies

答:
@Mati, @TheMiddleMan The @mythz's answer expects you to have some general knowledge about dependency injection and containers that is IOC (inversion of control). In your question you ask about constructor injection. ServiceStack's IOC can handle it using auto-wiring if you have pre-configured (registered) the parameter object, for example:

container.Register(c => new Layout());
  For more samples see https://docs.servicestack.net/ioc.

More about IOC and DI (dependency injection) can be read from https://dzone.com/articles/ioc-vs-di.

Body:
I’m using Service Stack, and I can´t (or I don´t know how make a Service class with constructor).

Here is what I did:

public class AppHost : AppSelfHostBase
{
    public AppHost()
        : base("ClientService", typeof(ClientService).Assembly)
    {
    }

    public override void Configure(Container container)
    {
    }
}

public class Context : ApplicationContext
{
    //This class is invoked from program.cs (winform application)
    //Here i have the logic of what form should i start.
    var listeningOn = string.Format("http://*:{0}/", port);
    var appHost = new AppHost();
    appHost.Init();
    appHost.Start(listeningOn);
    ClientService cl = new ClientService((ILayout)f, i);
}

public class ClientService : Service
{
    private readonly ILayout _activeForm;
    private static Init _initConf;

    public ClientService(ILayout f, Init i)
    {
        _activeForm = f;
        _activeForm.GetClientData(i);
        _initConf = i;
    }

    public HttpResult Post(Person request)
    {
       //Here i use _activeForm and _initConf
    }
}

So, as I said, in the class ClientService, I wanna make a constructor, but when I make a request to the post message, it shows me the following error:

Error trying to resolve Service
  'DexBrokerClient.Services.ClientService' or one of its auto wired
  dependencies


问:
Invariant Violation: Objects are not valid as a React child (found: object with keys {_40, _65, _55, _72})
I have one Flatlist and in flat list each item has geolocation.

I am calling {this.getitemlocation(item.location)} from inside of Flatlist. Here getitemlocation() is function and item.location is longitude and latitude.

My getitemlocation():

```<code> async getitemlocation(item) {
   let locationstring = item.split(",");
    if(locationstring[0]!="None"&&locationstring[1]!="None"){
    let location = {
      latitude: Number(locationstring[0]),
      longitude: Number(locationstring[1]),
    };
    itemloacation = await Location.reverseGeocodeAsync(location);
    return (
      <Text style={styles.itemLocation} key={item}>
        {itemloacation.name} {"\u2022"} 2.3 km
      </Text>
    );
    }
    else{
      return (
        <Text style={styles.itemLocation}>
          No Location
        </Text>
      );
    }
  }
</code>```

Error I am getting:

Invariant Violation: Objects are not valid as a React child (found: object with keys {_40, _65, _55, _72}). If you meant to render a collection of children, use an array instead.

答:
You can't return on async function like that. You can use Promise like this:

getitemlocation(item){
  return new Promise(async (resolve) => {
    let locationstring = item.split(",");
    if(locationstring[0]!="None"&&locationstring[1]!="None"){
      let location = {
        latitude: Number(locationstring[0]),
        longitude: Number(locationstring[1]),
      };
      itemloacation = await Location.reverseGeocodeAsync(location);
      resolve(
        <Text style={styles.itemLocation} key={item}>
          {itemloacation.name} {"\u2022"} 2.3 km
        </Text>
      )
    }else{
      resolve (
        <Text style={styles.itemLocation}>
          No Location
        </Text>
      );
    }
}```

Body:
I have one Flatlist and in flat list each item has geolocation.

I am calling {this.getitemlocation(item.location)} from inside of Flatlist. Here getitemlocation() is function and item.location is longitude and latitude.

My getitemlocation():

 async getitemlocation(item) {
   let locationstring = item.split(",");
    if(locationstring[0]!="None"&&locationstring[1]!="None"){
    let location = {
      latitude: Number(locationstring[0]),
      longitude: Number(locationstring[1]),
    };
    itemloacation = await Location.reverseGeocodeAsync(location);
    return (
      <Text style={styles.itemLocation} key={item}>
        {itemloacation.name} {"\u2022"} 2.3 km
      </Text>
    );
    }
    else{
      return (
        <Text style={styles.itemLocation}>
          No Location
        </Text>
      );
    }
  }

Error I am getting:

Invariant Violation: Objects are not valid as a React child (found: object with keys {_40, _65, _55, _72}). If you meant to render a collection of children, use an array instead.


问:
eBay inventory API: Get InventoryItems Always return 0 Results
I have a problem about ebay API.

When I call the inventory_item API  I get an empty result.
My request is

https://api.ebay.com/sell/inventory/v1/inventory_item?limit=2&offset=0

Response body is:

```<code>{
    "total": 0,
    "size": 0
}
</code>```

Then I call the inventory_item API By SKU, of course I failed again.

My request is:

https://api.ebay.com/sell/inventory/v1/inventory_item/80003953

（80003953 is my sku in ebay sell platform）

Response body is:

```<code>{
    "errors": [
        {
            "errorId": 25710,
            "domain": "API_INVENTORY",
            "subdomain": "Selling",
            "category": "REQUEST",
            "message": "We didn't find the entity you are requesting. Please verify the request"
        }
    ]
}
</code>```

I'm confirm my authorization and sku are correct!

答:
Perhaps you are trying to get items that are created by Ebay-GUI.

This case was already discribed here

So it turns out that eBay's Inventory API is fairly new. Only items created via the Inventory API's can be queried with the Inventory API.

In my case, using the old Trading-API solved the problem.

Body:
I have a problem about ebay API.

When I call the inventory_item API  I get an empty result.
My request is

https://api.ebay.com/sell/inventory/v1/inventory_item?limit=2&offset=0

Response body is:

{
    "total": 0,
    "size": 0
}

Then I call the inventory_item API By SKU, of course I failed again.

My request is:

https://api.ebay.com/sell/inventory/v1/inventory_item/80003953

（80003953 is my sku in ebay sell platform）

Response body is:

{
    "errors": [
        {
            "errorId": 25710,
            "domain": "API_INVENTORY",
            "subdomain": "Selling",
            "category": "REQUEST",
            "message": "We didn't find the entity you are requesting. Please verify the request"
        }
    ]
}

I'm confirm my authorization and sku are correct!


问:
Why is the order of execution of attribute assignments failing?
I am passing these parameters to a controller:

```<code>{
  "utf8" => "✓",
  "authenticity_token" => "ersjaJ4/ieZelVifP/YpBHTJtiQ53HgO5KYjEdW0BlQ=",
  "transaction" => {
    "use_balance" => "1",
    "traces_attributes" => {
      "trace_ids" => ["6"],
      "6" => {
        "amount" => "12.0",
        "charge_id" => "6"
      }
    },
    "positive_balance" => "12",
    "property_id" => "2",
    "community_id" => "1"
  },
  "commit" => "Save Payment",
  "community_id" => "1",
  "property_id" => "2"
}
</code>```

The controller#create then:

```<code>@payment = Transaction.new(params[:transaction])
</code>```

Then the Transaction model:

```<code>belongs_to :property
belongs_to :community
attr_accessible :positive_balance

def traces_attributes=(params)
  #INSIDE HERE THE VALUES OF
  #params[:trace_ids] => ['6'] OK
  #BUT
  #self.possitive_balance => "" **NOT OK**
  #self.property_id => nil **NOT OK**
end
</code>```

My hypothesis is that traces_attribute= is executed before positive_balance= and property_id

Can I change this?
Why is this failing?

答:
it looks based on the transaction hash that the property_id is outside of that hash so if you are building based on transactions it won't have a property_id

```<code>"transaction"=>{"use_balance"=>"1",
                "traces_attributes"=>{"trace_ids"=>["6"],
                                      "6"=>{"amount"=>"12.0",
                                            "charge_id"=>"6"
                                            }
                                      },
                "positive_balance"=>"12",
                "property_id"=>"2",
                "community_id"=>"1"
 },
"commit"=>"Save Payment",
"community_id"=>"1",
"property_id"=>"2"}
</code>```

do you see what i mean, the number of curly braces is messed up and prop. id isn't ending up in transactions ( i just copy and pasted your code pasted above )

Body:
I am passing these parameters to a controller:

{
  "utf8" => "✓",
  "authenticity_token" => "ersjaJ4/ieZelVifP/YpBHTJtiQ53HgO5KYjEdW0BlQ=",
  "transaction" => {
    "use_balance" => "1",
    "traces_attributes" => {
      "trace_ids" => ["6"],
      "6" => {
        "amount" => "12.0",
        "charge_id" => "6"
      }
    },
    "positive_balance" => "12",
    "property_id" => "2",
    "community_id" => "1"
  },
  "commit" => "Save Payment",
  "community_id" => "1",
  "property_id" => "2"
}

The controller#create then:

@payment = Transaction.new(params[:transaction])

Then the Transaction model:

belongs_to :property
belongs_to :community
attr_accessible :positive_balance

def traces_attributes=(params)
  #INSIDE HERE THE VALUES OF
  #params[:trace_ids] => ['6'] OK
  #BUT
  #self.possitive_balance => "" **NOT OK**
  #self.property_id => nil **NOT OK**
end

My hypothesis is that traces_attribute= is executed before positive_balance= and property_id

Can I change this?
Why is this failing?

Body:
it looks based on the transaction hash that the property_id is outside of that hash so if you are building based on transactions it won't have a property_id

"transaction"=>{"use_balance"=>"1",
                "traces_attributes"=>{"trace_ids"=>["6"],
                                      "6"=>{"amount"=>"12.0",
                                            "charge_id"=>"6"
                                            }
                                      },
                "positive_balance"=>"12",
                "property_id"=>"2",
                "community_id"=>"1"
 },
"commit"=>"Save Payment",
"community_id"=>"1",
"property_id"=>"2"}

do you see what i mean, the number of curly braces is messed up and prop. id isn't ending up in transactions ( i just copy and pasted your code pasted above )


问:
Get original view definition from POSTGRESQL DB
I have created a view with the below definition :

```<code>CREATE TABLE t1(id int,name varchar);
INSERT INTO t1 values(1,'n1'),(2,'n2');
CREATE VIEW v2 AS SELECT * FROM t1 WHERE name = 'n1';
</code>```

But when i checked the definition in postgresql DB(9.5) in pg_views table, it is getting modified in the below way :

```<code>postgres=# select * from pg_views where schemaname = 'sc1' and viewname = 'v2';
     schemaname | viewname | viewowner |               definition
    ------------+----------+-----------+-----------------------------------------
     sc1        | v2       | postgres  |  SELECT t1.id,                         +
                |          |           |     t1.name                            +
                |          |           |    FROM sc1.t1                         +
                |          |           |   WHERE ((t1.name)::text = 'n1'::text);
    (1 row)
</code>```

I am fine with adding tablename before columnname but i don't want the extra '::text' part.
Is there anyway to achieve this(like any other system table i can query from to get original definition)

答:
You can not get the "original" view definition from the Postgres system tables.

Postgres only stores the parsed version.

Body:
I have created a view with the below definition :

CREATE TABLE t1(id int,name varchar);
INSERT INTO t1 values(1,'n1'),(2,'n2');
CREATE VIEW v2 AS SELECT * FROM t1 WHERE name = 'n1';

But when i checked the definition in postgresql DB(9.5) in pg_views table, it is getting modified in the below way :

postgres=# select * from pg_views where schemaname = 'sc1' and viewname = 'v2';
     schemaname | viewname | viewowner |               definition
    ------------+----------+-----------+-----------------------------------------
     sc1        | v2       | postgres  |  SELECT t1.id,                         +
                |          |           |     t1.name                            +
                |          |           |    FROM sc1.t1                         +
                |          |           |   WHERE ((t1.name)::text = 'n1'::text);
    (1 row)

I am fine with adding tablename before columnname but i don't want the extra '::text' part.
Is there anyway to achieve this(like any other system table i can query from to get original definition)