问:
Can't understand this way of accessing 2-dimensional array in C
I run across this snippet of code, and found very strange that it manages to print 5. I can't understand why that casting to int* manages to make it basically a 1 dimensional array. Can someone explain?</p>

```<code>int main()
{
    int v[2][3] = {{1,2,3},{4,5,6}};
    int* c = (int*)v;
    printf("%d\n", c[4]);
}
</code>```

答:
Let's talk about how array subscripting works.

First, remember that the array subscript operation a[i] is defined as *(a + i) - that is, given an address a, offset i elements (not bytes!) from that address and dereference the result:

```<code>   +---+
a: |   |
   +---+
   |   |
   +---+
    ...
   +---+
   |   | <--- a + i
   +---+
</code>```

This works for two reasons:

Except when it is the operand of the sizeof, _Alignof, or unary & operators, or is a string literal used to initialize a character array in a declaration, an expression of type "N-element array of T" will be converted ("decay") to an expression of type "pointer to T" and the value of the expression will be the address of the first element of the array.  If T is itself an array type (such as with int [2][3], or "2-element array of 3-element array of int"), then you wind up with a pointer to an array type (int (*)[3], or "pointer to 3-element array of int).

Pointer arithmetic takes the size of the pointed-to type into account - if p is an int * and stores the address of an int object, then p + 1 yields the address of the next int object, not the next byte.  If p is a pointer to a 3-element array of int (int (*)[3]) and stores the address of an array, then p + 1 yields the address of the next 3-element array of int.

Graphically:

```<code> int         int *            int [3]    int (*)[3]
 +---+                        +---+
 | 1 |  <--- p                | 1 | <--- p
 +---+                        + - +
 | 2 |  <--- p + 1            | 2 |
 +---+                        + - +
 | 3 |                        | 3 |
 +---+                        +---+
 | 4 |                        | 4 | <--- p + 1
 +---+                        + - +
 | 5 |                        | 5 |
 +---+                        + - +
 | 6 |                        | 6 |
 +---+                        +---+
</code>```

The picture on the left is a sequence of int objects with int * pointers, and the picture on the right is a sequence of int [3] objects with int (*)[3] pointers.

So what's happening is that you're getting the address of the first element of v, but you're treating it as an int *, not as an int (*)[3]:

```<code>int* c = (int*)v;
</code>```

You're basically taking the picture on the right and pretending it's the picture on the left.  So c[4] corresponds to the 5th element in the sequence, which in this case is 5.

Now, this behavior is undefined - int (*)[3] and int * are not compatible types, and attempting to access elements of v this way is not guaranteed to work.  What would be safer would be to use

```<code>int *c = &v[0][0]; // int * = int *
</code>```

There's no casting to get around incompatible types, and you get the exact same effect.

Body:
I run across this snippet of code, and found very strange that it manages to print 5. I can't understand why that casting to int* manages to make it basically a 1 dimensional array. Can someone explain?

int main()
{
    int v[2][3] = {{1,2,3},{4,5,6}};
    int* c = (int*)v;
    printf("%d\n", c[4]);
}

Body:
Let's talk about how array subscripting works.

First, remember that the array subscript operation a[i] is defined as *(a + i) - that is, given an address a, offset i elements (not bytes!) from that address and dereference the result:

   +---+
a: |   |
   +---+
   |   |
   +---+
    ...
   +---+
   |   | <--- a + i
   +---+

This works for two reasons:

Except when it is the operand of the sizeof, _Alignof, or unary & operators, or is a string literal used to initialize a character array in a declaration, an expression of type "N-element array of T" will be converted ("decay") to an expression of type "pointer to T" and the value of the expression will be the address of the first element of the array.  If T is itself an array type (such as with int [2][3], or "2-element array of 3-element array of int"), then you wind up with a pointer to an array type (int (*)[3], or "pointer to 3-element array of int).

Pointer arithmetic takes the size of the pointed-to type into account - if p is an int * and stores the address of an int object, then p + 1 yields the address of the next int object, not the next byte.  If p is a pointer to a 3-element array of int (int (*)[3]) and stores the address of an array, then p + 1 yields the address of the next 3-element array of int.

Graphically:

 int         int *            int [3]    int (*)[3]
 +---+                        +---+
 | 1 |  <--- p                | 1 | <--- p
 +---+                        + - +
 | 2 |  <--- p + 1            | 2 |
 +---+                        + - +
 | 3 |                        | 3 |
 +---+                        +---+
 | 4 |                        | 4 | <--- p + 1
 +---+                        + - +
 | 5 |                        | 5 |
 +---+                        + - +
 | 6 |                        | 6 |
 +---+                        +---+

The picture on the left is a sequence of int objects with int * pointers, and the picture on the right is a sequence of int [3] objects with int (*)[3] pointers.

So what's happening is that you're getting the address of the first element of v, but you're treating it as an int *, not as an int (*)[3]:

int* c = (int*)v;

You're basically taking the picture on the right and pretending it's the picture on the left.  So c[4] corresponds to the 5th element in the sequence, which in this case is 5.

Now, this behavior is undefined - int (*)[3] and int * are not compatible types, and attempting to access elements of v this way is not guaranteed to work.  What would be safer would be to use

int *c = &v[0][0]; // int * = int *

There's no casting to get around incompatible types, and you get the exact same effect.


来源: stackexchange

问:
Scaling for coordinate transformation
I have a set of points in a rectangular space. The x-coordinates are scaled so that they are centered on 0:

```<code>#original points
x <- scale(runif(10000, min= 0, max= 1000), scale=FALSE)
y <- runif(10000, min= 0, max= 750)

plot(x, y, pch='.')
</code>```

I want to scale these points into a parabola, so that the x-values of points near y= 0 are closer than x-values near y= 750, essentially warping the image:

```<code>#SC = scale
SC <- 0
x_scale = x * (y + SC)
y_scale = y * (y + SC)

plot(x_scale,y_scale, pch='.')
</code>```

Sometimes, however, I don't want a complete parabola. I want there to be a bit of a buffer:

```<code>SC <- 200
x_scale_200 = x * (y + SC)
y_scale_200 = y * (y + SC)

plot(x_scale_200, y_scale_200, pch='.')
</code>```

As SC approaches infinity, the plotted space approaches the original rectangle:

```<code>SC <- 10000
x_scale_10k = x * (y + SC)
y_scale_10k = y * (y + SC)

plot(x_scale_10k, y_scale_10k, pch='.')
</code>```

I would like to create a variable T, that scales SC from 0 to 1. I essentially don't know how the degree of warping changes as SC gets larger.

In my mind, a function specifying T = 0 would result in a parabola, where T = 1 would result in a rectangle. I could just multiply T by 10,000 and use this (just making the assumption that the result is close enough to a rectangle), however the difference between T = 0 and T = 0.1 will be much larger than the difference between T = 0.9 and T = 1.0. I'd like T to scale the degree of 'warping' linearly. Just a bit lost as to what the mathematical relationship of (a linear scaling) T to the warping might be and how to code that in here.

I considered posting this in the math forum, but think it is still appropriate enough for stackoverflow.

答:
While I never solved this problem initially (turns out I didn't need to) I just happenned on this (4 years later) and the answer seemed apparent to me.

One solution would be to use the logit function to transform the input (in this case, 0.5 to 1 would need to used rather than 0 to 1, but this could be scaled as well. Since R doesn't like Inf (result of logit(1)), a small value has to be subtracted from 1. This is then scaled by 1000 (chosen based on some fiddling) to scale from parabola to rectangle.

```<code>sc_fun <- function(x)
{
  if (x == 1)
  {
    x1 <- x - 0.0000000000001
  } else {
    x1 <- x
  }
  SC <- boot::logit(x1) * 1000

  return(SC)
}

SC <- sc_fun(0.5)

x_scale_fun = x * (y + SC)
y_scale_fun = y * (y + SC)
plot(x_scale_fun, y_scale_fun, pch='.')

SC <- sc_fun(1)

x_scale_fun = x * (y + SC)
y_scale_fun = y * (y + SC)
plot(x_scale_fun, y_scale_fun, pch='.')
</code>```

ContentLicense: CC BY-SA 3.0

Title: Scaling for coordinate transformation

Body:
I have a set of points in a rectangular space. The x-coordinates are scaled so that they are centered on 0:

#original points
x <- scale(runif(10000, min= 0, max= 1000), scale=FALSE)
y <- runif(10000, min= 0, max= 750)

plot(x, y, pch='.')

I want to scale these points into a parabola, so that the x-values of points near y= 0 are closer than x-values near y= 750, essentially warping the image:

#SC = scale
SC <- 0
x_scale = x * (y + SC)
y_scale = y * (y + SC)

plot(x_scale,y_scale, pch='.')

Sometimes, however, I don't want a complete parabola. I want there to be a bit of a buffer:

SC <- 200
x_scale_200 = x * (y + SC)
y_scale_200 = y * (y + SC)

plot(x_scale_200, y_scale_200, pch='.')

As SC approaches infinity, the plotted space approaches the original rectangle:

SC <- 10000
x_scale_10k = x * (y + SC)
y_scale_10k = y * (y + SC)

plot(x_scale_10k, y_scale_10k, pch='.')

I would like to create a variable T, that scales SC from 0 to 1. I essentially don't know how the degree of warping changes as SC gets larger.

In my mind, a function specifying T = 0 would result in a parabola, where T = 1 would result in a rectangle. I could just multiply T by 10,000 and use this (just making the assumption that the result is close enough to a rectangle), however the difference between T = 0 and T = 0.1 will be much larger than the difference between T = 0.9 and T = 1.0. I'd like T to scale the degree of 'warping' linearly. Just a bit lost as to what the mathematical relationship of (a linear scaling) T to the warping might be and how to code that in here.

I considered posting this in the math forum, but think it is still appropriate enough for stackoverflow.

Body:
While I never solved this problem initially (turns out I didn't need to) I just happenned on this (4 years later) and the answer seemed apparent to me.

One solution would be to use the logit function to transform the input (in this case, 0.5 to 1 would need to used rather than 0 to 1, but this could be scaled as well. Since R doesn't like Inf (result of logit(1)), a small value has to be subtracted from 1. This is then scaled by 1000 (chosen based on some fiddling) to scale from parabola to rectangle.

sc_fun <- function(x)
{
  if (x == 1)
  {
    x1 <- x - 0.0000000000001
  } else {
    x1 <- x
  }
  SC <- boot::logit(x1) * 1000

  return(SC)
}

SC <- sc_fun(0.5)

x_scale_fun = x * (y + SC)
y_scale_fun = y * (y + SC)
plot(x_scale_fun, y_scale_fun, pch='.')

SC <- sc_fun(1)

x_scale_fun = x * (y + SC)
y_scale_fun = y * (y + SC)
plot(x_scale_fun, y_scale_fun, pch='.')

ContentLicense: CC BY-SA 4.0


问:
console.dir - how to show what object it applies to / label it?
Given a declaration like

myobj = {a:1, b:2};

I can write console.dir(myobj).  This results in

```<code>{ a: 1, b: 2 }
</code>```

But say I want to remind myself, in a complex debugging session, what the console.dir is about:

I can write

console.log("myobj"); console.dir(myobj);

This will print

```<code>myobj
{ a: 1, b: 2 }
</code>```

But it's a bit clunky.

Using console.log("myobj:" + myobj);

prints out

```<code>myobj:[object Object]
</code>```

which doesn't work at all.  Is there a better way to label a console.dir?

答:
You could just wrap your named variable in an object and the name will then be visible as the first layer of expansion.

myobj = {a:1, b:2};

console.dir({myobj});```
</div>
</div>
</p>

<hr>

<p>You can also use "groups" if you want the top-level wrapper to be your variable's name. Probably you'd want to do this with some sort of helper (and I don't really even suggest it, but it may meet your needs so just showing it as a demonstration):</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function labeledConsoleDirGroup(wrappedVar) {
  const varName = Object.keys({myobj})[0];
  console.group(varName);
  console.dir(wrappedVar[varName]);
  console.groupEnd(varName);
}

// Later ...
const myobj = {a: 1, b: 2};
labeledConsoleDirGroup({myobj});</code>```

Note that this doesn't work in the in-built code snippet runner since it doesn't support groups. But it looks like this in Chrome:

Body:
Given a declaration like

myobj = {a:1, b:2};

I can write console.dir(myobj).  This results in

{ a: 1, b: 2 }

But say I want to remind myself, in a complex debugging session, what the console.dir is about:

I can write

console.log("myobj"); console.dir(myobj);

This will print

myobj
{ a: 1, b: 2 }

But it's a bit clunky.

Using console.log("myobj:" + myobj);

prints out

myobj:[object Object]

which doesn't work at all.  Is there a better way to label a console.dir?

Body:
You could just wrap your named variable in an object and the name will then be visible as the first layer of expansion.

myobj = {a:1, b:2};

console.dir({myobj});

You can also use "groups" if you want the top-level wrapper to be your variable's name. Probably you'd want to do this with some sort of helper (and I don't really even suggest it, but it may meet your needs so just showing it as a demonstration):

function labeledConsoleDirGroup(wrappedVar) {
  const varName = Object.keys({myobj})[0];
  console.group(varName);
  console.dir(wrappedVar[varName]);
  console.groupEnd(varName);
}

// Later ...
const myobj = {a: 1, b: 2};
labeledConsoleDirGroup({myobj});

Note that this doesn't work in the in-built code snippet runner since it doesn't support groups. But it looks like this in Chrome:


问:
Only accept digits for textbox
I found this code for making my textbox only accept numbers.

```<code>Private Sub TextBox1_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
    Dim allowedChars As String = "0123456789"
    If allowedChars.IndexOf(e.KeyChar) = -1 Then
        ' Invalid Character
        e.Handled = True
    End If
End Sub
</code>```

But... the user can't delete the numbers using the backspace button. How do I do then?

答:
```<code> Private Sub txtValue_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles                 txtValue.KeyPress
        'Dim allowedChars As String = "0123456789"
        'If allowedChars.IndexOf(e.KeyChar) = -1 Then
        '    ' Invalid Character
        '    e.Handled = True
        'End If
        'If (e.KeyChar = Microsoft.VisualBasic.Chr(8)) Then
        '    e.Handled = True
        'End If
        If Char.IsDigit(e.KeyChar) = False And Char.IsControl(e.KeyChar) = False Then
            e.Handled = True
        End If
    End Sub
</code>```

ContentLicense: CC BY-SA 2.5

Title: Only accept digits for textbox

Body:
I found this code for making my textbox only accept numbers.

Private Sub TextBox1_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
    Dim allowedChars As String = "0123456789"
    If allowedChars.IndexOf(e.KeyChar) = -1 Then
        ' Invalid Character
        e.Handled = True
    End If
End Sub

But... the user can't delete the numbers using the backspace button. How do I do then?


问:
Cloud Functions with Firebase: signInWithEmailAndPassword is not a function
I'm beginning writing code with Cloud Functions with Firebase.
Of the functions below, testCreateUserAccount succeeds.
testLogin fails with a Type Error at runtime, stating "signInWithEmailAndPassword is not a function"

From what I have seen in the documentation, createUser is under the same class as  signInWithEmailAndPassword, so its not clear to me why attempting to call signInWithEmailAndPassword would fail.   Any ideas? Thanks!

```<code>"use strict";

var functions = require('firebase-functions');
const admin = require('firebase-admin');

admin.initializeApp(functions.config().firebase);

exports.testCreateUserAccount = functions.https.onRequest ((req, res) => {
    var email = "joe@example.com";
    var password = "joejoe";

    admin.auth().createUser({
      email: email,
      password: password,
      disabled: false
    });
} );

exports.testLogin = functions.https.onRequest ((req, res) => {
    var email = "joe@example.com";
    var password = "joejoe";

    admin.auth().signInWithEmailAndPassword(email, password);
} );
</code>```

答:
Now you could use the identitytoolkit's rest endpoint:

https://identitytoolkit.googleapis.com/v1/accounts:signUp?key=[API_KEY]

Here you have the documentation:

https://firebase.google.com/docs/reference/rest/auth/

Body:
I'm beginning writing code with Cloud Functions with Firebase.
Of the functions below, testCreateUserAccount succeeds.
testLogin fails with a Type Error at runtime, stating "signInWithEmailAndPassword is not a function"

From what I have seen in the documentation, createUser is under the same class as  signInWithEmailAndPassword, so its not clear to me why attempting to call signInWithEmailAndPassword would fail.   Any ideas? Thanks!

"use strict";

var functions = require('firebase-functions');
const admin = require('firebase-admin');

admin.initializeApp(functions.config().firebase);

exports.testCreateUserAccount = functions.https.onRequest ((req, res) => {
    var email = "joe@example.com";
    var password = "joejoe";

    admin.auth().createUser({
      email: email,
      password: password,
      disabled: false
    });
} );

exports.testLogin = functions.https.onRequest ((req, res) => {
    var email = "joe@example.com";
    var password = "joejoe";

    admin.auth().signInWithEmailAndPassword(email, password);
} );


问:
Google Font in GMAIL doesn't get recognized
I am sending mail using PHPMailer and Gmail doesn't seem to recognize the font "Kaushan Script" in heading while it successfully recognizes "Roboto Condensed" in rest of the body. Both are Google Fonts. Still, gmail is able to recognize one and ignores the other and places it's own random font. Inspecting element in gmail still shows the font name I used. Here is my code:</p>

```<code><!DOCTYPE html>
  <html>
   <head>
     <meta charset="utf-8">
     <meta name="viewport" content="width=device-width, initial-scale=1.0">
     <link href="https://fonts.googleapis.com/css2?family=Roboto+Condensed&display=swap" rel="stylesheet">
     <link href="https://fonts.googleapis.com/css2?family=Kaushan+Script&display=swap" rel="stylesheet">
     <style>
      .mail-head, .mail-foot {
        background: linear-gradient(315deg, #ee9617 0%, #fe5858 74%);
        padding: 10px;
        width: 100%;
        box-sizing: border-box;
        color: #fff;
        font-size: 2rem;
        font-family: "Kaushan Script", cursive;
      }
      .mail-foot {
        font-size: 14px;
        text-align: center;
        font-family: "Roboto Condensed", sans-serif;
      }
      .mail-body {
        font-size: 1rem;
        font-family: "Roboto Condensed", sans-serif;
        padding: 20px;
        line-height: 1.5;
        border-right: 1px solid #ee9617;
        border-left: 1px solid #fe5858;
      }
      .logo {
        width: auto;
        height: 2.5rem;
      }
      .logo-title {
        position: absolute;
        top: 1rem;
        left: 4.5rem;
      }
      .otp {
        color: #f69;
        margin-left: 10px;
      }
     </style>
   </head>
   <body>
     <div class="mail-head">
       <span class="logo-title">Site Name</span>
     </div>
</code>```

答:
CONTEXT

As far as I know Gmail doesn't support all Google Fonts or webfonts. In April 2018, Gmail released an updated interface for their webmail client. This new interface uses a limited list of popular webfonts including Google Sans and Roboto. (This explains why Roboto works is your case).

PROBLEM

I haven't found official documentation on this nor a list of the Google fonts or webfonts supported Gmail's interface.

ALTERNATIVE

These are the fonts supported by Gmail. Try to change "Kaushan Script" for any of them to confirm "Kaushan Script" is not supported by Gmail. Check if you can use any of these fonts to replace "Kaushan Script". Otherwise I suggest to use an image instead.

Arial

Arial Black

Arial Narrow

Bookman Old Style

Book Antiqua

Charcoal

Courier

Courier New

Comic Sans MS

Fixed width (monospace)

Garamond

Geneva

Georgia

Helvetica

Impact

Lucida Console

Lucida Grande

Lucida Sans Unicode

Monaco

Monospace

MS Sans Serif

Narrow (arial narrow)

New York

Palatino

Palatino Linotype

Roboto

Sans serif (arial)

Serif (times new roman)(serif)

Symbol

Tahoma

Times

Times New Roman (times new roman, serif)

Trebuchet MS (trebuchet ms, sans-serif)

Verdana

Webdings

Wide (arial black)

Wingdings

Zapf Dingbats

Good luck!

Body:
I am sending mail using PHPMailer and Gmail doesn't seem to recognize the font "Kaushan Script" in heading while it successfully recognizes "Roboto Condensed" in rest of the body. Both are Google Fonts. Still, gmail is able to recognize one and ignores the other and places it's own random font. Inspecting element in gmail still shows the font name I used. Here is my code:

<!DOCTYPE html>

     <meta charset="utf-8">
     <meta name="viewport" content="width=device-width, initial-scale=1.0">
     <link href="https://fonts.googleapis.com/css2?family=Roboto+Condensed&display=swap" rel="stylesheet">
     <link href="https://fonts.googleapis.com/css2?family=Kaushan+Script&display=swap" rel="stylesheet">

       Site Name


问:
OpenCV java implementaiton of Mat.dump() returns inaccurate data
I'm looking for extracting image pixel data into a list of integers (or any number representation). E.g., having a 2 x 2 white image, the result will be [255,255,255,255]. The Mat.dump() method prints the image pixel values accurately if the image was code generated and not read form the disk:

```<code>    Mat m = new Mat(5, 10, CvType.CV_8UC1, new Scalar(0));
    System.out.println("OpenCV Mat: " + m);
    Mat mr1 = m.row(1);
    mr1.setTo(new Scalar(1));
    Mat mc5 = m.col(5);
    mc5.setTo(new Scalar(5));
    System.out.println("OpenCV Mat data, "+m.total()+" elements:\n" +
    m.dump());
</code>```

prints accurately=>

```<code>    OpenCV Mat: Mat [ 5*10*CV_8UC1, isCont=true, isSubmat=false,
    nativeObj=0x1415d50, dataAddr=0x13a6880 ]
    OpenCV Mat data, 50 elements:
    [  0,   0,   0,   0,   0,   5,   0,   0,   0,   0;
       1,   1,   1,   1,   1,   5,   1,   1,   1,   1;
       0,   0,   0,   0,   0,   5,   0,   0,   0,   0;
       0,   0,   0,   0,   0,   5,   0,   0,   0,   0;
       0,   0,   0,   0,   0,   5,   0,   0,   0,   0]
</code>```

but if I write the Mat "m" contents on the disk and afterwards I read it again, the dump() method spits out strange output:

```<code>    Imgcodecs.imwrite(TRAIN_PATH_PROC+"m.jpg",m);

    m = null;
    m = Imgcodecs.imread(TRAIN_PATH_PROC+"m.jpg");
    System.out.println("Fresly read m, "+m.total()+" elements:\n"+m.dump());
</code>```

prints

```<code>Fresly read m, 50 elements:
[  0,   0,   0,   0,   0,   0,   0,   0,   0,   1,   1,   1,   0,   0,   0,
5,   5,   5,   1,   1,   1,   0,   0,   0,   0,   0,   0,   0,   0,   0;
1,   1,   1,   1,   1,   1,   1,   1,   1,   1,   1,   1,   1,   1,   1,
5,   5,   5,   1,   1,   1,   1,   1,   1,   1,   1,   1,   1,   1,   1;
0,   0,   0,   0,   0,   0,   0,   0,   0,   1,   1,   1,   0,   0,   0,   5,
5,   5,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0;
0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   4,
4,   4,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0;
0,   0,   0,   0,   0,   0,   0,   0,   0,   1,   1,   1,   0,   0,   0,
5,   5,   5,   1,   1,   1,   0,   0,   0,   0,   0,   0,   0,   0,   0]
</code>```

Due to the fact i need to extract the int values from read images, and relying on dump() for the string representation, this causes me trouble.

EDIT:

I have managed to extract the data simply using

```<code>    List<Integer> values = new ArrayList<>();

    for (int i = 0; i < m.rows(); i++) {
        for (int j = 0; j < m.cols(); j++) {
            values.add((int)m.get(i,j)[0]);
        }
    }
</code>```

答:
Mat.dump() is our friend as is printing the mat name to reveal its properties.  (The question title should be changed not to disparage dump().)  imread automatically assumes conversion to BGR thus the 3 channels of data instead of the expected 1 channel.  imwrite JPEG automatically compresses somewhat.  You can control the imread conversion and lessen the compression but it's still a little lossy.

MatOfInt imwrite_flags = new MatOfInt();
imwrite_flags.fromArray(Imgcodecs.IMWRITE_JPEG_QUALITY , 100);
Imgcodecs.imwrite(TRAIN_PATH_PROC+"m.jpg",m, imwrite_flags);

m = Imgcodecs.imread(TRAIN_PATH_PROC+"m.jpg", Imgcodecs.IMREAD_UNCHANGED);
```

<p>What you need is no or lossless compression so use TIFF format - example of both below with TIFF.  (See Is there a way to set specific compression scheme when saving tiff file in opencv?)</p>

<pre class="lang-java prettyprint-override"><code>String TRAIN_PATH_PROC = "";

Mat m = new Mat(5, 10, CvType.CV_8UC1, new Scalar(0));
System.out.println("OpenCV Mat: " + m);
Mat mr1 = m.row(1);
mr1.setTo(new Scalar(1));
Mat mc5 = m.col(5);
mc5.setTo(new Scalar(5));
System.out.println("OpenCV Mat data, "+m.total()+" elements:\n" +
m.dump());

MatOfInt imwrite_flags = new MatOfInt();
imwrite_flags.fromArray(Imgcodecs.IMWRITE_TIFF_COMPRESSION , 1); // no compression
Imgcodecs.imwrite(TRAIN_PATH_PROC+"m2.tif",m, imwrite_flags);// note name change so both examples can run
// OR
Imgcodecs.imwrite(TRAIN_PATH_PROC+"m.tif",m); // default compression LZW grayscale but lossless, I think

m = null;
m = Imgcodecs.imread(TRAIN_PATH_PROC+"m.tif", Imgcodecs.IMREAD_UNCHANGED);
System.out.println("OpenCV Mat: " + m);
System.out.println("Fresly read m, "+m.total()+" elements:\n"+m.dump());
</code>```

Body:
I'm looking for extracting image pixel data into a list of integers (or any number representation). E.g., having a 2 x 2 white image, the result will be [255,255,255,255]. The Mat.dump() method prints the image pixel values accurately if the image was code generated and not read form the disk:

    Mat m = new Mat(5, 10, CvType.CV_8UC1, new Scalar(0));
    System.out.println("OpenCV Mat: " + m);
    Mat mr1 = m.row(1);
    mr1.setTo(new Scalar(1));
    Mat mc5 = m.col(5);
    mc5.setTo(new Scalar(5));
    System.out.println("OpenCV Mat data, "+m.total()+" elements:\n" +
    m.dump());

prints accurately=>

    OpenCV Mat: Mat [ 5*10*CV_8UC1, isCont=true, isSubmat=false,
    nativeObj=0x1415d50, dataAddr=0x13a6880 ]
    OpenCV Mat data, 50 elements:
    [  0,   0,   0,   0,   0,   5,   0,   0,   0,   0;
       1,   1,   1,   1,   1,   5,   1,   1,   1,   1;
       0,   0,   0,   0,   0,   5,   0,   0,   0,   0;
       0,   0,   0,   0,   0,   5,   0,   0,   0,   0;
       0,   0,   0,   0,   0,   5,   0,   0,   0,   0]

but if I write the Mat "m" contents on the disk and afterwards I read it again, the dump() method spits out strange output:

    Imgcodecs.imwrite(TRAIN_PATH_PROC+"m.jpg",m);

    m = null;
    m = Imgcodecs.imread(TRAIN_PATH_PROC+"m.jpg");
    System.out.println("Fresly read m, "+m.total()+" elements:\n"+m.dump());

prints

Fresly read m, 50 elements:
[  0,   0,   0,   0,   0,   0,   0,   0,   0,   1,   1,   1,   0,   0,   0,
5,   5,   5,   1,   1,   1,   0,   0,   0,   0,   0,   0,   0,   0,   0;
1,   1,   1,   1,   1,   1,   1,   1,   1,   1,   1,   1,   1,   1,   1,
5,   5,   5,   1,   1,   1,   1,   1,   1,   1,   1,   1,   1,   1,   1;
0,   0,   0,   0,   0,   0,   0,   0,   0,   1,   1,   1,   0,   0,   0,   5,
5,   5,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0;
0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   4,
4,   4,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0;
0,   0,   0,   0,   0,   0,   0,   0,   0,   1,   1,   1,   0,   0,   0,
5,   5,   5,   1,   1,   1,   0,   0,   0,   0,   0,   0,   0,   0,   0]

Due to the fact i need to extract the int values from read images, and relying on dump() for the string representation, this causes me trouble.

EDIT:

I have managed to extract the data simply using

    List<Integer> values = new ArrayList<>();

    for (int i = 0; i < m.rows(); i++) {
        for (int j = 0; j < m.cols(); j++) {
            values.add((int)m.get(i,j)[0]);
        }
    }

Body:
Mat.dump() is our friend as is printing the mat name to reveal its properties.  (The question title should be changed not to disparage dump().)  imread automatically assumes conversion to BGR thus the 3 channels of data instead of the expected 1 channel.  imwrite JPEG automatically compresses somewhat.  You can control the imread conversion and lessen the compression but it's still a little lossy.

MatOfInt imwrite_flags = new MatOfInt();
imwrite_flags.fromArray(Imgcodecs.IMWRITE_JPEG_QUALITY , 100);
Imgcodecs.imwrite(TRAIN_PATH_PROC+"m.jpg",m, imwrite_flags);

m = Imgcodecs.imread(TRAIN_PATH_PROC+"m.jpg", Imgcodecs.IMREAD_UNCHANGED);

What you need is no or lossless compression so use TIFF format - example of both below with TIFF.  (See Is there a way to set specific compression scheme when saving tiff file in opencv?)

String TRAIN_PATH_PROC = "";

Mat m = new Mat(5, 10, CvType.CV_8UC1, new Scalar(0));
System.out.println("OpenCV Mat: " + m);
Mat mr1 = m.row(1);
mr1.setTo(new Scalar(1));
Mat mc5 = m.col(5);
mc5.setTo(new Scalar(5));
System.out.println("OpenCV Mat data, "+m.total()+" elements:\n" +
m.dump());

MatOfInt imwrite_flags = new MatOfInt();
imwrite_flags.fromArray(Imgcodecs.IMWRITE_TIFF_COMPRESSION , 1); // no compression
Imgcodecs.imwrite(TRAIN_PATH_PROC+"m2.tif",m, imwrite_flags);// note name change so both examples can run
// OR
Imgcodecs.imwrite(TRAIN_PATH_PROC+"m.tif",m); // default compression LZW grayscale but lossless, I think

m = null;
m = Imgcodecs.imread(TRAIN_PATH_PROC+"m.tif", Imgcodecs.IMREAD_UNCHANGED);
System.out.println("OpenCV Mat: " + m);
System.out.println("Fresly read m, "+m.total()+" elements:\n"+m.dump());


问:
Floor division using Gekko
In this optimization problem (a single variable simplified version of mine) I have one variable and I am trying to maximize the objective. The answer should be x = 4 with an objfcnval equal to 2 since as x increases these will be the calculations 0 - 0 = 0, 1 - 2 = -1, 2 - 2 = 0, 3 - 2 = 1, 4 - 2 = 2, 5 - 4 = 1.

Here is the code:

def my_ceiling(elem1, elem2):
    if (elem1 // elem2) == (elem1 / elem2):
        return elem1 / elem2
    else:
        return (elem1 // elem2) + 1

m = gekko.GEKKO(remote=False)
m.options.SOLVER = 1

x = m.Var(value=0, lb=0, ub=5, integer=True)

m.Obj((-1) * (x - 2 * my_ceiling(x, 4)))

m.solve(disp=False)

print('Objective: ' + str((-1) * m.options.objfcnval))
```

<pre class="lang-py prettyprint-override"><code>    if (elem1 // elem2) == (elem1 / elem2):
TypeError: unsupported operand type(s) for //: 'GKVariable' and 'int'
</code>```

The problem is that apparently this kind of operation is not supported. How would I go about using Gekko for problems like these?

答:
Taking inspiration from another discussion, one way to implement the floor function is to create a new integer variable y that is bounded by x/4 > y >= x/4 + 1e-8.

import gekko
m = gekko.GEKKO(remote=False)
m.options.SOLVER = 1

x = m.Var(value=0, lb=0,ub=5,integer=True)
y = m.Var(lb=0,ub=5,integer=True)

m.Equations([y<x/4,y>=x/4+1e-8])
m.Maximize((x - 2*y))

m.solve(disp=False)

print(x.value[0],y.value[0])
print('Objective: ' + str((-1)*m.options.objfcnval))
```

<p>This produces a solution for <code>x</code>, <code>y</code>, and the objective function:</p>

```4.0 1.0
Objective: 2.0
```

<p>This strategy also works if <code>x</code> is not an integer variable but Gekko gives a slightly different answer:</p>

```3.99999996 1.0
Objective: 1.99999996
```

If there is a reliable method, perhaps we should add a floor or ceil function in gekko that is similar to some of the other functions in the model building documentation. Could you keep us updated on your testing and what approach works best?

Title: Floor division using Gekko

Body:
In this optimization problem (a single variable simplified version of mine) I have one variable and I am trying to maximize the objective. The answer should be x = 4 with an objfcnval equal to 2 since as x increases these will be the calculations 0 - 0 = 0, 1 - 2 = -1, 2 - 2 = 0, 3 - 2 = 1, 4 - 2 = 2, 5 - 4 = 1.

Here is the code:

def my_ceiling(elem1, elem2):
    if (elem1 // elem2) == (elem1 / elem2):
        return elem1 / elem2
    else:
        return (elem1 // elem2) + 1

m = gekko.GEKKO(remote=False)
m.options.SOLVER = 1

x = m.Var(value=0, lb=0, ub=5, integer=True)

m.Obj((-1) * (x - 2 * my_ceiling(x, 4)))

m.solve(disp=False)

print('Objective: ' + str((-1) * m.options.objfcnval))

    if (elem1 // elem2) == (elem1 / elem2):
TypeError: unsupported operand type(s) for //: 'GKVariable' and 'int'

The problem is that apparently this kind of operation is not supported. How would I go about using Gekko for problems like these?

Body:
Taking inspiration from another discussion, one way to implement the floor function is to create a new integer variable y that is bounded by x/4 > y >= x/4 + 1e-8.

import gekko
m = gekko.GEKKO(remote=False)
m.options.SOLVER = 1

x = m.Var(value=0, lb=0,ub=5,integer=True)
y = m.Var(lb=0,ub=5,integer=True)

m.Equations([y<x/4,y>=x/4+1e-8])
m.Maximize((x - 2*y))

m.solve(disp=False)

print(x.value[0],y.value[0])
print('Objective: ' + str((-1)*m.options.objfcnval))

This produces a solution for x, y, and the objective function:

4.0 1.0
Objective: 2.0

This strategy also works if x is not an integer variable but Gekko gives a slightly different answer:

3.99999996 1.0
Objective: 1.99999996

If there is a reliable method, perhaps we should add a floor or ceil function in gekko that is similar to some of the other functions in the model building documentation. Could you keep us updated on your testing and what approach works best?


问:
ReferenceError: Phaser is not defined
I have this src/index.html file:.

```<code>    <!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <title>Making your first Phaser 3 Game - Part 1</title>
    <script src="//cdn.jsdelivr.net/npm/phaser@3.11.0/dist/phaser.js"></script>
    <style type="text/css">
        body {
            margin: 0;
        }
    </style>
</head>
<body>
<script type="text/javascript">

    var config = {
        type: Phaser.AUTO,
        width: 800,
        height: 600,
        scene: {
            preload: preload,
            create: create,
            update: update
        }
    };

    var game = new Phaser.Game(config);

    function preload ()
    {
        this.load.image('sky', 'assets/sky.png');
        this.load.image('ground', 'assets/platform.png');
        this.load.image('star', 'assets/star.png');
        this.load.image('bomb', 'assets/bomb.png');
        this.load.spritesheet('dude',
            'assets/dude.png',
            { frameWidth: 32, frameHeight: 48 }
    );
    }

    function create ()
    {
        this.add.image(400, 300, 'sky');
    }

    function update ()
    {
    }

</script>

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

I have this webpack.config.js file

```<code>    const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');

const config = {
  entry: './src/scripts/main.js',
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        loader: 'babel-loader',
      },
      {
        test: /\.scss$/,
        use: [
          'style-loader',
          'css-loader',
          'sass-loader',
        ],
      },
      {
        test: /\.(jpe?g|png|gif|svg)$/i,
        use: {
          loader: 'file-loader?name=/src/assets/[name].[ext]',
          options: {
            name: '[name].[hash].[ext]',
            outputPath: 'assets/',
          },
        },
      },
      {
        test: /\.html$/i,
        loader: 'html-loader',
      },
    ],
  },
  output: {
    path: path.resolve(
      __dirname,
      'dist',
    ),
  },
  plugins: [
    new HtmlWebpackPlugin({
      title: 'Output Management',
      template: './src/index.html',
    }),
  ],
};

module.exports = (env, argv) => {
  if (argv.mode === 'development') {
    config.devtool = 'source-map';
    config.output.filename = 'main.bundle.js';
  }

  if (argv.mode === 'production') {
    config.plugins.push(new CleanWebpackPlugin());
    config.output.filename = 'main.[hash].bundle.js';
  }

  return config;
};
</code>```

when I'm in the project root and type:

```<code>  npx webpack --mode development
</code>```

It creates a dist/index.html file in the root of the project

I open the file with my web browser (firefox) and I get this output

It doesn't recognize the 'Phaser' command in the index.html file

Check this line in the index.html file:

```<code>var game = new Phaser.Game(config);
</code>```

What's going on? How can I fix this? If you need more info just ask I'll expand so you can help.

This is the repository in the feature branch I'm working at the time of the question

答:
Extract the javascript from the index.html file and create a .js file that gets imported into the html by webpack

```<code>import Phaser from 'phaser';

function preload() {
  this.load.image('sky', 'assets/sky.png');
  this.load.image('ground', 'assets/platform.png');
  this.load.image('star', 'assets/star.png');
  this.load.image('bomb', 'assets/bomb.png');
  this.load.spritesheet('dude',
    'assets/dude.png',
    { frameWidth: 32, frameHeight: 48 });
}

function create() {
  this.add.image(400, 300, 'sky');
}

function update() {
}

const config = {
  type: Phaser.AUTO,
  width: 800,
  height: 600,
  scene: {
    preload,
    create,
    update,
  },
};

// eslint-disable-next-line no-unused-vars
const game = new Phaser.Game(config);
</code>```

Check the first line of the .js file

```<code>import Phaser from 'phaser';
</code>```

Title: ReferenceError: Phaser is not defined

Body:
I have this src/index.html file:.

    <!doctype html>

    <meta charset="UTF-8" />
    <title>Making your first Phaser 3 Game - Part 1</title>

I have this webpack.config.js file

    const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');

const config = {
  entry: './src/scripts/main.js',
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        loader: 'babel-loader',
      },
      {
        test: /\.scss$/,
        use: [
          'style-loader',
          'css-loader',
          'sass-loader',
        ],
      },
      {
        test: /\.(jpe?g|png|gif|svg)$/i,
        use: {
          loader: 'file-loader?name=/src/assets/[name].[ext]',
          options: {
            name: '[name].[hash].[ext]',
            outputPath: 'assets/',
          },
        },
      },
      {
        test: /\.html$/i,
        loader: 'html-loader',
      },
    ],
  },
  output: {
    path: path.resolve(
      __dirname,
      'dist',
    ),
  },
  plugins: [
    new HtmlWebpackPlugin({
      title: 'Output Management',
      template: './src/index.html',
    }),
  ],
};

module.exports = (env, argv) => {
  if (argv.mode === 'development') {
    config.devtool = 'source-map';
    config.output.filename = 'main.bundle.js';
  }

  if (argv.mode === 'production') {
    config.plugins.push(new CleanWebpackPlugin());
    config.output.filename = 'main.[hash].bundle.js';
  }

  return config;
};

when I'm in the project root and type:

  npx webpack --mode development

It creates a dist/index.html file in the root of the project

I open the file with my web browser (firefox) and I get this output

It doesn't recognize the 'Phaser' command in the index.html file

Check this line in the index.html file:

var game = new Phaser.Game(config);

What's going on? How can I fix this? If you need more info just ask I'll expand so you can help.

This is the repository in the feature branch I'm working at the time of the question

Body:
Extract the javascript from the index.html file and create a .js file that gets imported into the html by webpack

import Phaser from 'phaser';

function preload() {
  this.load.image('sky', 'assets/sky.png');
  this.load.image('ground', 'assets/platform.png');
  this.load.image('star', 'assets/star.png');
  this.load.image('bomb', 'assets/bomb.png');
  this.load.spritesheet('dude',
    'assets/dude.png',
    { frameWidth: 32, frameHeight: 48 });
}

function create() {
  this.add.image(400, 300, 'sky');
}

function update() {
}

const config = {
  type: Phaser.AUTO,
  width: 800,
  height: 600,
  scene: {
    preload,
    create,
    update,
  },
};

// eslint-disable-next-line no-unused-vars
const game = new Phaser.Game(config);

Check the first line of the .js file

import Phaser from 'phaser';


问:
Error: gobject-introspection: uninitialized constant Language::Python::Shebang
While executing the following command:

```<code>brew install opencv
</code>```

I am encountered with the following exception:

```<code>Error: gobject-introspection: uninitialized constant Language::Python::Shebang
</code>```

Could you please help me find the root cause for this and resolve it?

答:
Language::Python::Shebang is the replacement for Language::Python.rewrite_python_shebang, which was deprecated in Homebrew 2.3.0

So you are likely using a version of Homebrew prior to 2.3.0 You can check your Homebrew version with brew --version.

Just doing brew update should update Homebrew to the latest version.

If you at some point added or changed a formula and worked locally on it you could be on a feature branch or your Homebrew working directory is changed so it does not update the master branch.

In these cases try the following:

cd /usr/local/Homebrew

git status

Discard or git stash your changes or git checkout master if you are on a feature branch

Once the working directory is clean you can brew update to update Homebrew

Body:
While executing the following command:

brew install opencv

I am encountered with the following exception:

Error: gobject-introspection: uninitialized constant Language::Python::Shebang

Could you please help me find the root cause for this and resolve it?


问:
strapi + knex to execute complex Queries
How do  I get the knex object to execute custom or complex queries within my strapi service?

My Strapi version has the strapi-hook-knex and strapi-hook-bookshelf installed but when I run qb.raw it is an undefined object.

This is to run queries like this:

```<code>qb.select(knex.raw('.... ?? )', '...'))
</code>```

答:
Took me awhile to pin down exact syntax for this. Here it is in case helpful to others. Could not have gotten there without Jim LAURIE's answer.</p>

```<code>module.exports = {
  async findCustom(ctx) {
    const rawBuilder = strapi.connections.default.raw(
      "select field1 from mytable where field1 = 'x'"
    );
    const resp = await rawBuilder.then();
    return resp.rows;
  }
}
</code>```

Body:
How do  I get the knex object to execute custom or complex queries within my strapi service?

My Strapi version has the strapi-hook-knex and strapi-hook-bookshelf installed but when I run qb.raw it is an undefined object.

This is to run queries like this:

qb.select(knex.raw('.... ?? )', '...'))

Body:
Took me awhile to pin down exact syntax for this. Here it is in case helpful to others. Could not have gotten there without Jim LAURIE's answer.

module.exports = {
  async findCustom(ctx) {
    const rawBuilder = strapi.connections.default.raw(
      "select field1 from mytable where field1 = 'x'"
    );
    const resp = await rawBuilder.then();
    return resp.rows;
  }
}


问:
Binding datatemplate to ContentControl's Content
How to bind textbox text property, within datatemplate,  to ContentControl Content property?

(Without bindng via ElementName)

This is my code( that doesn't work):

```<code><Window.Resources>
    <DataTemplate x:Key="Temp">
       <TextBox TextWrapping="Wrap" Text="{TemplateBinding Content}" Height="20" Width="Auto"/>
    </DataTemplate>
</Window.Resources>
<Grid>
    <ContentControl  ContentTemplate="{DynamicResource Temp}" Content="1"/>
</Grid>
</code>```

答:
Use a relative source binding:

Text="{Binding RelativeSource={RelativeSource AncestorType=ContentControl}, Path=Content}"
```

Edit: I probably should note that, in terms of what the binding targets, this is equivalent to {Binding}, as the DataContext in the ContentTemplate is the Content.

However binding directly to the DataContext will not propagate back to the source DataContext, hence the Content of the ContentControl would not change when when using this binding (or the two-way compliant variation {Binding .}, which changes absolutely nothing as far as I can tell).

Body:
How to bind textbox text property, within datatemplate,  to ContentControl Content property?

(Without bindng via ElementName)

This is my code( that doesn't work):

<Window.Resources>
    <DataTemplate x:Key="Temp">
       <TextBox TextWrapping="Wrap" Text="{TemplateBinding Content}" Height="20" Width="Auto"/>
    </DataTemplate>
</Window.Resources>
<Grid>
    <ContentControl  ContentTemplate="{DynamicResource Temp}" Content="1"/>
</Grid>

Body:
Use a relative source binding:

Text="{Binding RelativeSource={RelativeSource AncestorType=ContentControl}, Path=Content}"

Edit: I probably should note that, in terms of what the binding targets, this is equivalent to {Binding}, as the DataContext in the ContentTemplate is the Content.

However binding directly to the DataContext will not propagate back to the source DataContext, hence the Content of the ContentControl would not change when when using this binding (or the two-way compliant variation {Binding .}, which changes absolutely nothing as far as I can tell).


问:
Cannot update state in reactJS
```<code> console.log(holder);
 console.log(index);

 console.log(holder);
 setWholeData(wholeData.filter((el, i) => i !== index));
 console.log(holder);
</code>```

For the above code, I want to remove one element with index = 'index' in wholeData which is a state setup using useState and initialize with []. In my test case, before this part of code, wholedata should have two elements and this part of code should remove one of its elements. I assign the updated/New array to holder and want to assign it to wholedata using 'setWholeData()".

But the problem is that if I do
setWholeData(holder). Then the holder will contain two elements, which means that the filter function did not work somehow. If I do
setWholeData(wholeData.filter((el, i) => i !== index));
The value of holder is what I expected, but 'wholedata' is not updated correctly still. The element is not removed. Seems like the filter in the
setWholeData(...) is not working.

If anyone could give a little hand, it would be so appreciated. Sorry for the confusing description, if any clarification is needed, please feel free to message.

答:
Filter returns an array where the result of the callback is 'true'. <br/>
If you want to remove an element by its index you can use a combination of findIndex and splice to find the index of the element you want to remove and splice to execute the removal of that element. </p>

Title: Cannot update state in reactJS

Body:
 console.log(holder);
 console.log(index);

 console.log(holder);
 setWholeData(wholeData.filter((el, i) => i !== index));
 console.log(holder);

For the above code, I want to remove one element with index = 'index' in wholeData which is a state setup using useState and initialize with []. In my test case, before this part of code, wholedata should have two elements and this part of code should remove one of its elements. I assign the updated/New array to holder and want to assign it to wholedata using 'setWholeData()".

But the problem is that if I do
setWholeData(holder). Then the holder will contain two elements, which means that the filter function did not work somehow. If I do
setWholeData(wholeData.filter((el, i) => i !== index));
The value of holder is what I expected, but 'wholedata' is not updated correctly still. The element is not removed. Seems like the filter in the
setWholeData(...) is not working.

If anyone could give a little hand, it would be so appreciated. Sorry for the confusing description, if any clarification is needed, please feel free to message.

Body:
Filter returns an array where the result of the callback is 'true'.

If you want to remove an element by its index you can use a combination of findIndex and splice to find the index of the element you want to remove and splice to execute the removal of that element.


问:
Font-weight not working on specif areas of a website
On this website, I'm unable to remove the bold property from the bold text (text starts with "Conforme o art. 43...").

What is most intriguing is that the font-weight command below applies normally to all parts of the referred site, except for the bold part.

I'm using the following code in Stylebot (Chrome Extension):

```<code>    div {
    font-family: Open Sans;
    font-size: 14.49px;
    text-align: justify;
    text-justify: auto;
    font-weight: 300;
}
</code>```

How can I get this done? Thanks in advance!

答:
Please let me know if this is what you are looking for.

```<code>div > * {
    font-family: Open Sans;
    font-size: 14.49px;
    text-align: justify;
    text-justify: auto;
    font-weight: 300;
}

or

* {
    font-family: Open Sans;
    font-size: 14.49px;
    text-align: justify;
    text-justify: auto;
    font-weight: 300;
}
</code>```

Edit: Maybe this is more what you are looking for->

```<code>.q-question-enunciation > span{
    font-family: Open Sans;
    font-size: 14.49px;
    text-align: justify;
    text-justify: auto;
    font-weight: 300;
}
</code>```

Body:
On this website, I'm unable to remove the bold property from the bold text (text starts with "Conforme o art. 43...").

What is most intriguing is that the font-weight command below applies normally to all parts of the referred site, except for the bold part.

I'm using the following code in Stylebot (Chrome Extension):

    div {
    font-family: Open Sans;
    font-size: 14.49px;
    text-align: justify;
    text-justify: auto;
    font-weight: 300;
}

How can I get this done? Thanks in advance!

Body:
Please let me know if this is what you are looking for.

div > * {
    font-family: Open Sans;
    font-size: 14.49px;
    text-align: justify;
    text-justify: auto;
    font-weight: 300;
}

or

* {
    font-family: Open Sans;
    font-size: 14.49px;
    text-align: justify;
    text-justify: auto;
    font-weight: 300;
}

Edit: Maybe this is more what you are looking for->

.q-question-enunciation > span{
    font-family: Open Sans;
    font-size: 14.49px;
    text-align: justify;
    text-justify: auto;
    font-weight: 300;
}


问:
Can't format datetime using Bokeh Hovertool with Custom HTML
Using Bokeh to display charts within Flask my hovertools works except for dates, which are my x axis in all charts.  I have tried a hundred permutations of the code and extensively reviewed the documentation and related questions but am missing some key element on how to use formatters within custom html.  This question seems to address my exact question, but I do not see how the answer relates to the actual custom html:
bokeh hover tool - format date variable in custom html

The data is passed to bokeh as a pandas data frame then use ColumnDataSource within Bokeh.  The index, and x values, are definitely datetime with Bokeh treating them as a datetime in other parts of the charting such as the x axis labels and ticks.

This is my current hovertools html within Python:

```<code>def create_hover_absolute():
"""Generates the HTML for the Bokeh's hover data tool on our graph."""
hover_html = """
    <div class="plot-tooltip">
        <div>
            <span style="font-weight: bold;">$name</span>
        </div>
        <div>
            $y{$,000}
        </div>
        <div>
            Date: @date{%Y-%m}
        </div>

    </div>
"""
return HoverTool(tooltips=hover_html, formatters={'date': 'datetime'})
</code>```

I have tried a variety of ways to enter the date including:

```<code>$x
$x with all sorts of formatting such as {%Y%b}
@date
@ date with all sorts of formatting
</code>```

I end up with the date as either a long integer (15 digits) or a mysterious three digit number with TIB.  Like this:

screenshot showing hover with Date: 118TB%

I can make all of this work on the local Bokeh server when I do show(plot) but not in the custom html when passing to web page.  How do I format the date within the html?  How do I include the formatters?

thank you

答:
All I needed to do, as pointed out in comment by Eugene Pakhomov was to change 'date' to '@date' in the formatters.  Like this:</p>

```<code>return HoverTool(tooltips=hover_html, formatters={'@date': 'datetime'})
</code>```

Body:
Using Bokeh to display charts within Flask my hovertools works except for dates, which are my x axis in all charts.  I have tried a hundred permutations of the code and extensively reviewed the documentation and related questions but am missing some key element on how to use formatters within custom html.  This question seems to address my exact question, but I do not see how the answer relates to the actual custom html:
bokeh hover tool - format date variable in custom html

The data is passed to bokeh as a pandas data frame then use ColumnDataSource within Bokeh.  The index, and x values, are definitely datetime with Bokeh treating them as a datetime in other parts of the charting such as the x axis labels and ticks.

This is my current hovertools html within Python:

def create_hover_absolute():
"""Generates the HTML for the Bokeh's hover data tool on our graph."""
hover_html = """

            $name

            $y{$,000}

            Date: @date{%Y-%m}

"""
return HoverTool(tooltips=hover_html, formatters={'date': 'datetime'})

I have tried a variety of ways to enter the date including:

$x
$x with all sorts of formatting such as {%Y%b}
@date
@ date with all sorts of formatting

I end up with the date as either a long integer (15 digits) or a mysterious three digit number with TIB.  Like this:

screenshot showing hover with Date: 118TB%

I can make all of this work on the local Bokeh server when I do show(plot) but not in the custom html when passing to web page.  How do I format the date within the html?  How do I include the formatters?

thank you

Body:
All I needed to do, as pointed out in comment by Eugene Pakhomov was to change 'date' to '@date' in the formatters.  Like this:

return HoverTool(tooltips=hover_html, formatters={'@date': 'datetime'})


问:
Postman returns ' Could not get any response '
Postman returns  ' Could not get any response '  when I send a Post request, but get a request to other URL works just fine. please how can I resolve this issue? index.js is the entry point to my application. the get URL below is working.

index.js

```<code>    const express = require('express')
const mongoose = require('mongoose')
const dotenv = require('dotenv')
const bodyParser = require('body-parser')
const app= express()

//body parser
app.use(bodyParser.json())

//config
dotenv.config()
//connect to db
mongoose.connect(
    process.env.DB_CONNECTION,
    { useNewUrlParser: true },
    ()=>{
        console.log('contented to db')
    }
)

//import route
const authRoute = require('./ROUTES/auth')

app.use('', authRoute)

app.use('/api/user', authRoute)

//start server
app.listen(5000);

# auth.js #
</code>```

all routings are done in auth.js

```<code>        const express =require('express')
    const router = express.Router();
    const User = require('./moduls/User')

    router.get('/',(req, res)=>{
        res.send('home')
    })

    //validation schema
    const joi =require('@hapi/joi');
    const regSchema ={
        name:joi.string().min(6).required(),
        email:joi.string().required().email(),
        password:joi.string().min(8).required()
    }

    router.post('/register', async(req, res)=>{
        //check and return error status
        const { error } = joi.ValidationError(regSchema);
        if(error) return res.status(400).json({message: err})
        const emailExist = await User.findOne(req.body.email)
        if (emailExist) return res.status(400).json({message:'there is a user with this email'})

        //get user object
        const user =new User({
            name:req.body.name,
            email:req.body.email,
            password:req.body.password,
            rePassword:req.body.rePassword
        })
        try{
            await user.save()
            .then(data=>{
                res.json(data)
            })
        }
        catch(err){
            res.status(400).json({message: err})
        }

    })

    module.exports=router;
</code>```

modules/User.js

user module in the modules folder

```<code>const mongoose = require('mongoose')

const userSchema =new  mongoose.Schema({
    name:{
        type: String,
        required:true,
        min:6,
        max:30
    },
    email:{
        type: String,
        required:true,
        max:100
    },
    password:{
        type:String,
        required:true,
        min:8
    },
    rePassword:{
        type:String,
        required:true,
        min:8
    },
    date:{
        type:Date,
        default:Date.now()
    }

})

module.exports = mongoose.model('User', userSchema)
</code>```

答:
The .save() function returns a promise that you can await. You don't need to use .then() when using async/await.

Instead of this.

```<code>await user.save()
.then(data=>{
    res.json(data)
})
</code>```

I'd do this.

```<code>const data = await user.save();
res.json(data);
</code>```

Body:
Postman returns  ' Could not get any response '  when I send a Post request, but get a request to other URL works just fine. please how can I resolve this issue? index.js is the entry point to my application. the get URL below is working.

index.js

    const express = require('express')
const mongoose = require('mongoose')
const dotenv = require('dotenv')
const bodyParser = require('body-parser')
const app= express()

//body parser
app.use(bodyParser.json())

//config
dotenv.config()
//connect to db
mongoose.connect(
    process.env.DB_CONNECTION,
    { useNewUrlParser: true },
    ()=>{
        console.log('contented to db')
    }
)

//import route
const authRoute = require('./ROUTES/auth')

app.use('', authRoute)

app.use('/api/user', authRoute)

//start server
app.listen(5000);

# auth.js #

all routings are done in auth.js

        const express =require('express')
    const router = express.Router();
    const User = require('./moduls/User')

    router.get('/',(req, res)=>{
        res.send('home')
    })

    //validation schema
    const joi =require('@hapi/joi');
    const regSchema ={
        name:joi.string().min(6).required(),
        email:joi.string().required().email(),
        password:joi.string().min(8).required()
    }

    router.post('/register', async(req, res)=>{
        //check and return error status
        const { error } = joi.ValidationError(regSchema);
        if(error) return res.status(400).json({message: err})
        const emailExist = await User.findOne(req.body.email)
        if (emailExist) return res.status(400).json({message:'there is a user with this email'})

        //get user object
        const user =new User({
            name:req.body.name,
            email:req.body.email,
            password:req.body.password,
            rePassword:req.body.rePassword
        })
        try{
            await user.save()
            .then(data=>{
                res.json(data)
            })
        }
        catch(err){
            res.status(400).json({message: err})
        }

    })

    module.exports=router;

modules/User.js

user module in the modules folder

const mongoose = require('mongoose')

const userSchema =new  mongoose.Schema({
    name:{
        type: String,
        required:true,
        min:6,
        max:30
    },
    email:{
        type: String,
        required:true,
        max:100
    },
    password:{
        type:String,
        required:true,
        min:8
    },
    rePassword:{
        type:String,
        required:true,
        min:8
    },
    date:{
        type:Date,
        default:Date.now()
    }

})

module.exports = mongoose.model('User', userSchema)

Body:
The .save() function returns a promise that you can await. You don't need to use .then() when using async/await.

Instead of this.

await user.save()
.then(data=>{
    res.json(data)
})

I'd do this.

const data = await user.save();
res.json(data);


问:
Rotate array while maintaining orientation of components in java
For a project I am working on I have to read a font sprite sheet (font.png as seen bellow) and convert each individual character into an array of indices.

When reading the file and converting it into an array I use the flowing code:

```<code>    BufferedImage img = ImageIO.read(new File("D:\\Downloads\\font.png"));
    int[][] font = new int[8][760];
    for(int i = 0; i < img.getWidth(); i++) {
        for(int j = 0; j < img.getHeight(); j++) {
            font[j][i] = (img.getRGB(i, j) != - 1) ? 1:0;
        }
    }
    System.out.println(Arrays.deepToString(font).replace("], ", "]\n").replace("[[", "[").replace("]]", "]"));
</code>```

Which give me an 8x760 int[][] where each black pixel is a 1 and each white pixel is a 0 (Characters in image are space, !, ", #)

In an attempt to rotate the array into a 760x8 array I tried the following code:

```<code>    int[][] rFont = new int[760][8];
    for(int a = 0; a < 95; a++) {
        for(int i = 0; i < 8; i++) {
            for(int j = 0; j < 8; j++) {
                rFont[i + 8*a][j] = font[j][i + 8*a];
            }
        }
    }
    System.out.println(Arrays.deepToString(rFont).replace("], ", "]\n").replace("[[", "[").replace("]]", "]"));
</code>```

This code works perfectly to rotate the array except each letter in the font is also rotated 90 degrees. As seen by the following image its clear that the '!' is rotated as well.

Where did I go wrong in my code to not maintain the orientation of the characters?

Body:
For a project I am working on I have to read a font sprite sheet (font.png as seen bellow) and convert each individual character into an array of indices.

When reading the file and converting it into an array I use the flowing code:

    BufferedImage img = ImageIO.read(new File("D:\\Downloads\\font.png"));
    int[][] font = new int[8][760];
    for(int i = 0; i < img.getWidth(); i++) {
        for(int j = 0; j < img.getHeight(); j++) {
            font[j][i] = (img.getRGB(i, j) != - 1) ? 1:0;
        }
    }
    System.out.println(Arrays.deepToString(font).replace("], ", "]\n").replace("[[", "[").replace("]]", "]"));

Which give me an 8x760 int[][] where each black pixel is a 1 and each white pixel is a 0 (Characters in image are space, !, ", #)

In an attempt to rotate the array into a 760x8 array I tried the following code:

    int[][] rFont = new int[760][8];
    for(int a = 0; a < 95; a++) {
        for(int i = 0; i < 8; i++) {
            for(int j = 0; j < 8; j++) {
                rFont[i + 8*a][j] = font[j][i + 8*a];
            }
        }
    }
    System.out.println(Arrays.deepToString(rFont).replace("], ", "]\n").replace("[[", "[").replace("]]", "]"));

This code works perfectly to rotate the array except each letter in the font is also rotated 90 degrees. As seen by the following image its clear that the '!' is rotated as well.

Where did I go wrong in my code to not maintain the orientation of the characters?

Body:
Replace

        for(int j = 0; j < 8; j++) {
            rFont[i + 8*a][j] = font[j][i + 8*a];
        }

with

                for (int j = 7; j >= 0; j--) {
                    rFont[i + 8 * a][7 - j] = font[j][i + 8 * a];
                }


问:
Merge two dataframes based on an exact match in one column and match within an error in another column in R
I have a dataframe

```<code>df1:

A  time B  C
a1 t1   b1 c1
a2 t2   b2 c2
a3 t3   b3 c3
</code>```

and another dataframe

```<code>df2:

A  time D E
a1 t4   d1 e1
a2 t5   d2 e2
a3 t6   d3 e3
</code>```

Assume time is in the format yyyy-mm-dd hh:mm:ss e.g. 2019-08-16 15:06:38

and lets assume:

```<code>t4 - t1 = 40 seconds
t5 - t2 = -5 seconds
t6 - t3 = 120 seconds
</code>```

I would like to merge these dataframes based on exact match on A and a match on column time with some acceptable difference between the dataframes , for example with in 1 min.

So my output would look like:

```<code>df3 :

A  B  C  D  E time(from df1)
a1 b1 c1 d1 e1 t1
a2 b2 c2 d2 e2 t2
</code>```

See that a3 is not there because even though it matches on column A the difference in time exceeded the acceptable limit.

How can I do this? If not for the "acceptable difference" part I would do like:

```<code>merge(df1, df2, by = c("A", "time"))
</code>```

答:
Or a non-equi inner join from data.table:

```<code>library(data.table)
setDT(df1)[, c("start", "end") := .(time-60*60, time+60*60)]
df2[df1, on=.(A, time>=start, time<=end), nomatch=0L, .(A, B, C, D, E, time=i.time)]
</code>```

Body:
I have a dataframe

df1:

A  time B  C
a1 t1   b1 c1
a2 t2   b2 c2
a3 t3   b3 c3

and another dataframe

df2:

A  time D E
a1 t4   d1 e1
a2 t5   d2 e2
a3 t6   d3 e3

Assume time is in the format yyyy-mm-dd hh:mm:ss e.g. 2019-08-16 15:06:38

and lets assume:

t4 - t1 = 40 seconds
t5 - t2 = -5 seconds
t6 - t3 = 120 seconds

I would like to merge these dataframes based on exact match on A and a match on column time with some acceptable difference between the dataframes , for example with in 1 min.

So my output would look like:

df3 :

A  B  C  D  E time(from df1)
a1 b1 c1 d1 e1 t1
a2 b2 c2 d2 e2 t2

See that a3 is not there because even though it matches on column A the difference in time exceeded the acceptable limit.

How can I do this? If not for the "acceptable difference" part I would do like:

merge(df1, df2, by = c("A", "time"))

Body:
Or a non-equi inner join from data.table:

library(data.table)
setDT(df1)[, c("start", "end") := .(time-60*60, time+60*60)]
df2[df1, on=.(A, time>=start, time<=end), nomatch=0L, .(A, B, C, D, E, time=i.time)]


问:
Using assignment as a condition expression?
Consider:

```<code>if (a=5) {
   /* do something */
}
</code>```

How does the assignment work as a condition?

Is it based on non-zero value of l-value?

答:
In more modern usage, you may sometimes see this pattern used to handle optionals:

std::optional x = ...;
if (auto v = x) {
  // Block only executes if x contained a value, accessible as *v
}
```

Body:
Consider:

if (a=5) {
   /* do something */
}

How does the assignment work as a condition?

Is it based on non-zero value of l-value?


问:
Google analytics measurement protocol authentication
I do not understand the reason for not having OAuth flow while using the measurement protocol. The user needs the track-id for sending the request, and there are possibilities of ghosting as well. So why is OAuth process not being used for authentication in Google Analytics. Could anybody help me in understanding this?</p>

答: The measurement protocol is an http request to a URL with querystring parameters. It does not require authentication. I agree that the data can get dirty, however its operation is that.</p>


问:
How can I retrieve the attribute of a clicked element with jQuery?
I'm using wordpress and woocommerce, and I want to add some scripts to run when a product variation is selected, with jQuery.

I have a set of "buttons" in html like this:

```<code><div class="adsw-attribute-option">
  <span class="meta-item-text sku-set" data-value="s">S</span>
  <span class="meta-item-text sku-set" data-value="m">M</span>
  <span class="meta-item-text sku-set" data-value="l">L</span>
  <span class="meta-item-text sku-set" data-value="xl">XL</span>
  <span class="meta-item-text sku-set" data-value="xxl">XXL</span>
  <span class="meta-item-text sku-set" data-value="xxxl">XXXL</span>
</div>
</code>```

I add click listeners with the following:

```<code>$(".adsw-attribute-option > .meta-item-text").on("click", () => {})
</code>```

And inside the handler I need to read the data-value attribute of the "button" that was clicked. First I tried: $(this).attr("data-value"). This returned undefined. I've tried with .data instead of the attr function, with the same result.

It seems like there's some issue with the usage of $(this), I couldn't read any of its properties like html, or class.

I thought $(this) should refer to the object, that the event was called on, but it seems, this is not the case.

What am I missing here? Is there any other way to retrieve the value of "data-value" in this case?

答:
if you're using an arrow function for the handler, try using the function keyword instead. the arrow function will have the same this value as its parent context, so it won't give you access to the attribute you're trying to read.

```<code>$(".adsw-attribute-option > .meta-item-text").on("click", function(e) {
    console.log($(this).attr('data-value'));
});
</code>```

Body:
I'm using wordpress and woocommerce, and I want to add some scripts to run when a product variation is selected, with jQuery.

I have a set of "buttons" in html like this:

  S
  M
  L
  XL
  XXL
  XXXL

I add click listeners with the following:

$(".adsw-attribute-option > .meta-item-text").on("click", () => {})

And inside the handler I need to read the data-value attribute of the "button" that was clicked. First I tried: $(this).attr("data-value"). This returned undefined. I've tried with .data instead of the attr function, with the same result.

It seems like there's some issue with the usage of $(this), I couldn't read any of its properties like html, or class.

I thought $(this) should refer to the object, that the event was called on, but it seems, this is not the case.

What am I missing here? Is there any other way to retrieve the value of "data-value" in this case?

Body:
if you're using an arrow function for the handler, try using the function keyword instead. the arrow function will have the same this value as its parent context, so it won't give you access to the attribute you're trying to read.

$(".adsw-attribute-option > .meta-item-text").on("click", function(e) {
    console.log($(this).attr('data-value'));
});


问:
Is Asynchronous file IO thread safe?
Is asynchronous file IO like FileStream.BeginWrite thread safe? If not, then it need to wrap with "SyncLock", that's mean it is still blocking thread.</p>

答: Also if the resource is accessed by multiple threads, it means it is a shared resource and there are plentiful of resources about using them in c#.</p>

Title: Is Asynchronous file IO thread safe?


答:
```<code>$(".adsw-attribute-option > .meta-item-text").on("click", e => {
  console.log($(e.target).data('value'));
  console.log(e.target.dataset.value);
});
</code>```

You can use an arrow function, if you use the event passed in.

Title: How can I retrieve the attribute of a clicked element with jQuery?

Body:
$(".adsw-attribute-option > .meta-item-text").on("click", e => {
  console.log($(e.target).data('value'));
  console.log(e.target.dataset.value);
});

You can use an arrow function, if you use the event passed in.


问:
Why array_unique does not detect duplicate objects?
I can't seem to figure out what magic is happening behind the PHP scene and why array_unique cannot detect my duplicates.

In my specific situation, I have 2 collections of users, which I am merging into one and then keeping only unique entries. For that I am converting both collections into arrays, array_merge() them and then based on parameter apply array_unique(..., SORT_REGULAR) so that they are compared as objects without any conversions. I realise that comparing objects is a slippery slope, but in this case it's weirder than I though.

After merge but before the uniqueness check I have this state:

As you can see, items 4 and 11 are the same User entity (both non-strict and strict comparison agree on that). Yet after array_unique() they both remain in the list for some reason:

As you can see, items 7-10 were detected and removed, but 11 wasn't.

How is that possible? What am I not seeing here?

Currently running PHP 7.4.5

Code is from project using Symfony 4.4.7 and Doctrine ORM 2.7.2 (although I think this should be irrelevant, if the objects are equal both by == and === comparisons).

Fun fact for bonus points - applying array_unique twice in a row gives actually unique results:

Mind = blown

UPDATE: I have added throw new \RuntimeException() in my User::__toString() method, to be extra sure noone is doing conversion to string.

Please do not suggest converting to string - that is neither a solution to my problem, nor what this question is about.

答:
For your issue at hand, I am really suspecting this is coming from the way
array_unique is removing elements out of the array, when using the SORT_REGULAR flag, by:

sorting it

removing adjacent items if they are equal

And because you do have a Proxy object in the middle of your User collection, this might cause you the issue you are currently facing.

This seems to be backed up by the warning of the sort page of PHP documentation, as pointed out be Marvin's comment.

Warning Be careful when sorting arrays with mixed types values because sort() can produce unexpected results, if sort_flags is SORT_REGULAR.

Source: https://www.php.net/manual/en/function.sort.php#refsect1-function.sort-notes

Now for a possible solution, this might get you something more Symfony flavoured.

It uses the ArrayCollection filter and contains methods in order to filter the second collection and only add the elements not present already in the first collection.

And to be fully complete, this solution is also making use of the use language construct in order to pass the second ArrayCollection to the closure function needed by filter.

This will result in a new ArrayCollection containing no duplicated user.

public static function merge(Collection $a, Collection $b, bool $unique = false): Collection {
  if($unique){
    return new ArrayCollection(
      array_merge(
        $a->toArray(),
        $b->filter(function($item) use ($a){
          return !$a->contains($item);
        })->toArray()
      )
    );
  }

  return new ArrayCollection(array_merge($a->toArray(), $b->toArray()));
}
```


问:
Ruby - convert string to date
I have a string like "2011-06-02T23:59:59+05:30".

I want to convert it to date format and need to parse only the date, "2011-06-02".

答:
For Ruby 1.9.2:</p>

```<code>require 'date'    # If not already required. If in Rails then you don't need this line).
puts DateTime.parse("2011-06-02T23:59:59+05:30").to_date.to_s
</code>```

Title: Ruby - convert string to date

Body:
For Ruby 1.9.2:

require 'date'    # If not already required. If in Rails then you don't need this line).
puts DateTime.parse("2011-06-02T23:59:59+05:30").to_date.to_s


问:
How to dynamically show Drawer items in React-Navigation V5?
I am having a bit of trouble trying to dynamically show different items at React-Navigation drawer.

I have a drawer that needs to show different items if the user is logged in or not. In this case, if the user is logged in, the buttons for "RegisterScreen" and "LoginScreen" should NOT be shown and the "Log Out" button should be shown. However, if the user is NOT logged in, then both Register and Login screens should be shown and the Log out button should not.

I have successfully shown the buttons using the code below (Except for the Logout button, I did not do it yet). However, once the user logs out, the app redirects them to the login screen. Since I did not declare them in the drawer, I get the following error:

console.error: The action 'NAVIGATE' with payload {"name":"LoginModal"} was not handled by any navigator.

I do understand that the screens were not added, but I have no idea how they can be hidden when the user is logged in.

Code:

```<code>//Added DrawerItemList for the Logout button.
  const CustomDrawerContent = (props) => {
    return (
      <DrawerContentScrollView {...props}>

        <DrawerItemList {...props} />
        <DrawerItem
          label="Logout"
          onPress={async () => {
            props.navigation.closeDrawer();
            await LogOut().then((result) => {
              props.navigation.navigate('LoginModal');
            });
          }}
        />

      </DrawerContentScrollView>
    );
  };

  const [drawerCategories, setDrawerCategories] = useState([]);

//Checks if the user is logged in and sets Login and Register screens in the state.
  useEffect(() => {
    let mounted = true;
    if (mounted) {
      AsyncStorage.getItem('userId').then((result) => {
        console.log(result);
        if (result == null) {
          setDrawerCategories([
            ...drawerCategories,
            {name: 'LoginModal', component: {LoginScreen}},
            {name: 'RegisterModal', component: {RegisterScreen}},
          ]);
        }
      });
    }
    return () => (mounted = false);
  }, []);

  return (
    <NavigationContainer>
      <RootDrawer.Navigator
        drawerType="front"
        initialRouteName="Home"
        mode="modal"
        drawerContent={(props) => <CustomDrawerContent {...props} />}>
        <RootDrawer.Screen name="Home" component={MainStackScreen} />

//Add the Register and Login buttons here
        {drawerCategories.map((drawer) => {
          <RootDrawer.Screen name={drawer.name} component={drawer.component} />;
        })}

      </RootDrawer.Navigator>
    </NavigationContainer>
  );
</code>```

Can you please help me figuring out how to fix this error? Thank you so much!

答:
Not sure what your LogOut function does, but unless it actually re-runs the effect so that your LoginModal screen is defined, there won't be a screen named LoginModal to navigate to.

Looking at your code, your effect won't re-run after you logout. Instead of setting the list of screens in the effect, you should arrange your code to something like this:

Global store like Redux, React Context or whatever you prefer to store the userId

The useEffect hook should restore try to restore the userId from AsyncStorage like you're doing now, but after restoring, it should update your global store to update the userId there instead of setting the screens

Your logOut function should delete the userId from AsyncStorage as well as update the global store so that it's null.

Inside your component, you should conditionally define the screens based on if userId is null, and they'll automatically change on login or logout

The docs for authentication flow show an example of how this works using a token and stack navigator: https://reactnavigation.org/docs/auth-flow/

You can use similar strategy with an user id and a drawer navigator.

Body:
I am having a bit of trouble trying to dynamically show different items at React-Navigation drawer.

I have a drawer that needs to show different items if the user is logged in or not. In this case, if the user is logged in, the buttons for "RegisterScreen" and "LoginScreen" should NOT be shown and the "Log Out" button should be shown. However, if the user is NOT logged in, then both Register and Login screens should be shown and the Log out button should not.

I have successfully shown the buttons using the code below (Except for the Logout button, I did not do it yet). However, once the user logs out, the app redirects them to the login screen. Since I did not declare them in the drawer, I get the following error:

console.error: The action 'NAVIGATE' with payload {"name":"LoginModal"} was not handled by any navigator.

I do understand that the screens were not added, but I have no idea how they can be hidden when the user is logged in.

Code:

//Added DrawerItemList for the Logout button.
  const CustomDrawerContent = (props) => {
    return (
      <DrawerContentScrollView {...props}>

        <DrawerItemList {...props} />
        <DrawerItem
          label="Logout"
          onPress={async () => {
            props.navigation.closeDrawer();
            await LogOut().then((result) => {
              props.navigation.navigate('LoginModal');
            });
          }}
        />

      </DrawerContentScrollView>
    );
  };

  const [drawerCategories, setDrawerCategories] = useState([]);

//Checks if the user is logged in and sets Login and Register screens in the state.
  useEffect(() => {
    let mounted = true;
    if (mounted) {
      AsyncStorage.getItem('userId').then((result) => {
        console.log(result);
        if (result == null) {
          setDrawerCategories([
            ...drawerCategories,
            {name: 'LoginModal', component: {LoginScreen}},
            {name: 'RegisterModal', component: {RegisterScreen}},
          ]);
        }
      });
    }
    return () => (mounted = false);
  }, []);

  return (
    <NavigationContainer>
      <RootDrawer.Navigator
        drawerType="front"
        initialRouteName="Home"
        mode="modal"
        drawerContent={(props) => <CustomDrawerContent {...props} />}>
        <RootDrawer.Screen name="Home" component={MainStackScreen} />

//Add the Register and Login buttons here
        {drawerCategories.map((drawer) => {
          <RootDrawer.Screen name={drawer.name} component={drawer.component} />;
        })}

      </RootDrawer.Navigator>
    </NavigationContainer>
  );

Can you please help me figuring out how to fix this error? Thank you so much!


问:
How to get a JsonProcessingException using Jackson
Might be a strange question but indeed I would like to achieve a a bit more coverage on my tests and although I coded against a JsonProcessingException I can't create a payload that generates this exception, maybe because Jackson is quite smart and converts everything to a string, and even for bad strings it goes around the JSON specs. My problem is that Jackson is quite good :)

I basically want a payload that when I run this, it break with JsonProcessingException:

```<code>String jsonPayload = objectMapper.writeValueAsString(payload);
</code>```

I've tried some like:

```<code>HashMap<String, String> invalidJSONPayload= new HashMap<>();

invalidJSONPayload.put("021",021);
invalidJSONPayload.put("---",021);
invalidJSONPayload.put("~",021);
</code>```

I'm not fussed with the type, so feel free to suggest another one. An empty object for example, throws JsonMappingException and I already catch that one as well.

答:
I found this in Jackson Github issue; but it solved my problem and I am able to throw the JsonProcessingException.

```<code> @Test
public void forceJsonParseException() {
try {
    Object mockItem = mock(Object.class);
    when(mockItem.toString()).thenReturn(mockItem.getClass().getName());
    new ObjectMapper().writeValueAsString(mockItem);
    fail("did not throw JsonProcessingException");
} catch (JsonProcessingException e) {
    //pass
}
}
</code>```

Now how I used this in my code

Need to test this method

```<code>public String geResponse(MyObject myObject) {

try {
  return objectMapper.writeValueAsString(myObject);
} catch (JsonProcessingException e) {
  log.error("Service response JsonParsing error {} ", e.getMessage());
  return "Validation Service response JsonParsing error {} "+ e.getMessage();
 }
}
</code>```

This how I test the JsonProcessingException

```<code>@SneakyThrows
@Test
public void testGetValidationResponseNegative() {
    MyObject mockItem = mock(MyObject.class);
    when(mockItem.toString()).thenReturn(mockItem.getClass().getName());
    String vr = geResponse(mockItem);
    assertTrue(!vr.isEmpty());
}
</code>```

I hope this helps!!!

Body:
Might be a strange question but indeed I would like to achieve a a bit more coverage on my tests and although I coded against a JsonProcessingException I can't create a payload that generates this exception, maybe because Jackson is quite smart and converts everything to a string, and even for bad strings it goes around the JSON specs. My problem is that Jackson is quite good :)

I basically want a payload that when I run this, it break with JsonProcessingException:

String jsonPayload = objectMapper.writeValueAsString(payload);

I've tried some like:

HashMap<String, String> invalidJSONPayload= new HashMap<>();

invalidJSONPayload.put("021",021);
invalidJSONPayload.put("---",021);
invalidJSONPayload.put("~",021);

I'm not fussed with the type, so feel free to suggest another one. An empty object for example, throws JsonMappingException and I already catch that one as well.

Body:
I found this in Jackson Github issue; but it solved my problem and I am able to throw the JsonProcessingException.

 @Test
public void forceJsonParseException() {
try {
    Object mockItem = mock(Object.class);
    when(mockItem.toString()).thenReturn(mockItem.getClass().getName());
    new ObjectMapper().writeValueAsString(mockItem);
    fail("did not throw JsonProcessingException");
} catch (JsonProcessingException e) {
    //pass
}
}

Now how I used this in my code

Need to test this method

public String geResponse(MyObject myObject) {

try {
  return objectMapper.writeValueAsString(myObject);
} catch (JsonProcessingException e) {
  log.error("Service response JsonParsing error {} ", e.getMessage());
  return "Validation Service response JsonParsing error {} "+ e.getMessage();
 }
}

This how I test the JsonProcessingException

@SneakyThrows
@Test
public void testGetValidationResponseNegative() {
    MyObject mockItem = mock(MyObject.class);
    when(mockItem.toString()).thenReturn(mockItem.getClass().getName());
    String vr = geResponse(mockItem);
    assertTrue(!vr.isEmpty());
}

I hope this helps!!!


问:
Create a feature in pandas based on another column
I have the following dataset:

```<code>data = {'ROC_9':  [0.006250, 0.087230, 0.045028, 0.165738, -0.006993, -0.432736, -0.11162, 0.057466, 0.203138, -0.008234]}

price_data = pd.DataFrame (data)
</code>```

It is an indicator about a stock price, namely rate of change.

I want to write a code that creates a new feature (column) on the pandas data frame when a current feature on the pandas data frame goes from positive to negative, or vice versa.

It is easier explained through an example: lets use the feature ROC9.

I create a new variable called ROC9_signal and set it equal to 0:

```<code>`price_data['ROC9_signal'] = 0`
</code>```

When ROC_9 goes from negative to positive, I want to change the ROC9_signal from 0 to 1.

When ROC_9 goes from positive to negative, I want to change the ROC9_signal from 0 to -1.

Looking at the data, I would like ROC9_signal to change from 0 to -1, since the value has gone from 0.16 (positive) to -0.006 (negative).

Looking at the data, I would like ROC_9 signal to change from 0 to 1, since the value has gone from -0.11 (negative) to 0.05 (positive).

Looking at the data, I would like ROC9_signal to change from 0 to -1, since the value has gone from 0.20 (positive) to -0.008 (negative).

It is only the row where the change happens that I want to change from 0 to 1 or 0 to -1, the other rows must remain at 0.

I will then apply this same logic to create a momentum10_signal column and a chalkin_money_flow_signal column. Therefore I want a solution that can be applied to different columns and not manually.

Thanks in advance for the help.

This is what the full data looks like:

Full Data

答:
Try using np.where:

First create a column of 'ROC9_prev' using shift:

price_data['ROC9_prev'] = price_data['ROC9'].shift(1)

You may need to groupby a column before shifting in order to ensure that you're taking each stock's previous ROC9 as opposed to a different stock's current ROC9.

Then creating the signal column will follow like this:

```<code>price_data['ROC9_Signal'] = np.where(price_data['ROC9'] > 0 & price_data['ROC9_prev'] < 0, 1, 0)
price_data['ROC9_Signal'] = np.where(price_data['ROC9'] < 0 & price_data['ROC9_prev'] > 0, -1, 0)
</code>```

Hope this helps.

Body:
I have the following dataset:

data = {'ROC_9':  [0.006250, 0.087230, 0.045028, 0.165738, -0.006993, -0.432736, -0.11162, 0.057466, 0.203138, -0.008234]}

price_data = pd.DataFrame (data)

It is an indicator about a stock price, namely rate of change.

I want to write a code that creates a new feature (column) on the pandas data frame when a current feature on the pandas data frame goes from positive to negative, or vice versa.

It is easier explained through an example: lets use the feature ROC9.

I create a new variable called ROC9_signal and set it equal to 0:

`price_data['ROC9_signal'] = 0`

When ROC_9 goes from negative to positive, I want to change the ROC9_signal from 0 to 1.

When ROC_9 goes from positive to negative, I want to change the ROC9_signal from 0 to -1.

Looking at the data, I would like ROC9_signal to change from 0 to -1, since the value has gone from 0.16 (positive) to -0.006 (negative).

Looking at the data, I would like ROC_9 signal to change from 0 to 1, since the value has gone from -0.11 (negative) to 0.05 (positive).

Looking at the data, I would like ROC9_signal to change from 0 to -1, since the value has gone from 0.20 (positive) to -0.008 (negative).

It is only the row where the change happens that I want to change from 0 to 1 or 0 to -1, the other rows must remain at 0.

I will then apply this same logic to create a momentum10_signal column and a chalkin_money_flow_signal column. Therefore I want a solution that can be applied to different columns and not manually.

Thanks in advance for the help.

This is what the full data looks like:

Full Data

Body:
Try using np.where:

First create a column of 'ROC9_prev' using shift:

price_data['ROC9_prev'] = price_data['ROC9'].shift(1)

You may need to groupby a column before shifting in order to ensure that you're taking each stock's previous ROC9 as opposed to a different stock's current ROC9.

Then creating the signal column will follow like this:

price_data['ROC9_Signal'] = np.where(price_data['ROC9'] > 0 & price_data['ROC9_prev'] < 0, 1, 0)
price_data['ROC9_Signal'] = np.where(price_data['ROC9'] < 0 & price_data['ROC9_prev'] > 0, -1, 0)

Hope this helps.


问:
Printing Right Triangles w/ Nested For-Loop
Here's my loop:

int height = Convert.ToInt32(Console.ReadLine());

Console.WriteLine("Printing a " + height + " by " + height + " right triangle...");

for (int i = 1; i <= height; i++)
{
    Console.WriteLine("*");
    for (int j = 1; j <= i; j++)
    {
        Console.Write("*");
    }
```

<p>And here is the resulting print (program takes a user input for the height, this example has a height of 5:</p>

<pre class="lang-none prettyprint-override"><code>*
**
***
****
****
</code>```

As you can see, I can't get the last star to print on the last row. This makes absolutely no sense to me, as I've compared it to many other similar constructs and there appears to be no discrepancies between the one I've constructed and the ones others have made. I just started coding about a month ago so I'm still a greenhorn.

答:
The problem is that you're doing a Console.WriteLine() first, followed by the Console.Write(), which means that for each iteration it's writing on two different lines.

To fix this, you can just add a WriteLine() to the end of the loop, so that you Write() each star for a row, then WriteLine() so the next iteration begins the next row on the next line:

```<code>// For each row
for (int row = 1; row <= height; row++)
{
    // For each column in the row
    for (int col = 1; col <= row; col++)
    {
        // Write a star
        Console.Write("*");
    }

    // End the row
    Console.WriteLine();
}
</code>```

Note that there's an overload to the string constructor that allows you to specify a character and the number of times it should be repeated to create the string. This can come in handy here, allowing us to remove the inner loop:

```<code>// For each row
for (int row = 1; row <= height; row++)
{
    // Write a string with 'row' number of stars
    Console.WriteLine(new string('*', row));
}
</code>```

Body:
Here's my loop:

int height = Convert.ToInt32(Console.ReadLine());

Console.WriteLine("Printing a " + height + " by " + height + " right triangle...");

for (int i = 1; i <= height; i++)
{
    Console.WriteLine("*");
    for (int j = 1; j <= i; j++)
    {
        Console.Write("*");
    }

And here is the resulting print (program takes a user input for the height, this example has a height of 5:

*
**
***
****
****

As you can see, I can't get the last star to print on the last row. This makes absolutely no sense to me, as I've compared it to many other similar constructs and there appears to be no discrepancies between the one I've constructed and the ones others have made. I just started coding about a month ago so I'm still a greenhorn.

Body:
The problem is that you're doing a Console.WriteLine() first, followed by the Console.Write(), which means that for each iteration it's writing on two different lines.

To fix this, you can just add a WriteLine() to the end of the loop, so that you Write() each star for a row, then WriteLine() so the next iteration begins the next row on the next line:

// For each row
for (int row = 1; row <= height; row++)
{
    // For each column in the row
    for (int col = 1; col <= row; col++)
    {
        // Write a star
        Console.Write("*");
    }

    // End the row
    Console.WriteLine();
}

Note that there's an overload to the string constructor that allows you to specify a character and the number of times it should be repeated to create the string. This can come in handy here, allowing us to remove the inner loop:

// For each row
for (int row = 1; row <= height; row++)
{
    // Write a string with 'row' number of stars
    Console.WriteLine(new string('*', row));
}