问:
What do you recommend for accepting in-browser user drawings?
I need to write an application that accepts very simple doodles by users, kind of like in tenthousandcents and thesheepmarket.

For example, I might want users to write their name using their mouse.

Any suggestions?

I don't even need to host it myself. If there are services offered somewhere that I can just use that is fine.

答:
I would recommend using the <canvas> tag; it's available natively in Safari, Chrome, Firefox, and Opera, and available by using ExplorerCanvas in IE, which is a simple wrapper that makes IE's VML language accessible from a canvas compatible interface. See this article for a tutorial on how to make a drawing app using the <canvas> element. You can find a lot of docs and tutorials by searching Google.

There is an open-source <canvas> base drawing app that you can play with and download here.

OwnerDisplayName: carrier

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: mmyers

OwnerDisplayName: Brian Campbell

LastEditorDisplayName: Brian Campbell


来源: stackexchange

问:
View Designer Code in Visual Studio 2010
What is a standard way to open the Designer (automatically generated) code for a VB file?

As a workaround, I can get to it by searching the entire solution for some keyword that is usually only found in those files: Global, Partial, etc.

答: Open the code file, and in the top-right corner of the code window is a drop-down containing all methods.  Open this and select "InitializeComponent".</p>

ContentLicense: CC BY-SA 3.0


问:
Plot polygon with centroid located exterior/outside of polygon
How do I plot a polygon with the centroid located outside of the polygon in Python?</p>

答:
No idea how to in python, but I guess the assumption is, that polygon has to be convex. Not necessary. Below an illustration in R with standard st_centroid (as in Postgis or sf).

library(sf)
#> Linking to GEOS 3.9.0, GDAL 3.2.2, PROJ 7.2.1; sf_use_s2() is TRUE
pl1 = list(rbind(c(0,0), c(1,0), c(0.12,0.12), c(0,1), c(0,0)))
polygon <- st_polygon(x = pl1)
plot(polygon)
pt <- st_centroid(polygon)
plot(pt, pch = 18, col = "red", add = TRUE)
```

Created on 2022-02-06 by the reprex package (v2.0.1)

ContentLicense: CC BY-SA 4.0

Body:
No idea how to in python, but I guess the assumption is, that polygon has to be convex. Not necessary. Below an illustration in R with standard st_centroid (as in Postgis or sf).

library(sf)
#> Linking to GEOS 3.9.0, GDAL 3.2.2, PROJ 7.2.1; sf_use_s2() is TRUE
pl1 = list(rbind(c(0,0), c(1,0), c(0.12,0.12), c(0,1), c(0,0)))
polygon <- st_polygon(x = pl1)
plot(polygon)
pt <- st_centroid(polygon)
plot(pt, pch = 18, col = "red", add = TRUE)

Created on 2022-02-06 by the reprex package (v2.0.1)


问:
Three.js cube is not rendering after bundling – Webpack, Wordpress
I’m trying to integrate three.js with wordpress via webpack. The problem is that, 3d cube is not appearing inside canvas.

```<code><div class="div" id="canvas"></div>
</code>```

is empty.

If I would put app.js code into

答:
According to your comment, you are including the script in the head tag, just move it to the end of the body (footer).

You are not able to see anything because your script tries to get the canvas element, which does not yet exist at that time. By moving your script to the end, you are ensuring that your page has rendered before your script is ran.

Using WordPress you can do:

```<code>wp_enqueue_script( 'jakubtrz-portfolio-scripts', get_template_directory_uri() . '/dist/app.js', array(), false, true );
</code>```

The last argument is the one that indicate WordPress to add the script in the footer. By default, it is false hence, added in the head tag.

Body:
I’m trying to integrate three.js with wordpress via webpack. The problem is that, 3d cube is not appearing inside canvas.

is empty.

If I would put app.js code into

Body:
According to your comment, you are including the script in the head tag, just move it to the end of the body (footer).

You are not able to see anything because your script tries to get the canvas element, which does not yet exist at that time. By moving your script to the end, you are ensuring that your page has rendered before your script is ran.

Using WordPress you can do:

wp_enqueue_script( 'jakubtrz-portfolio-scripts', get_template_directory_uri() . '/dist/app.js', array(), false, true );

The last argument is the one that indicate WordPress to add the script in the footer. By default, it is false hence, added in the head tag.


问:
CSS Simple Dropdown click event
I am trying to build a very simple functionality to create a drop down under a certain text field when its clicked.

$(".val").children("div").on("click", function() {
  alert("CLICK");
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.container {
  display: inline-block;
}

.val {
  display: none;
  position: absolute;
  z-index: 1;
}

.container:focus-within .val {
  display: block;
}</code>```

LABEL

VAL1

VAL2

```

Main problem comes with the click function which it never gets triggered... (I guess it runs first the lost focus in CSS and then no click is done in that element as its hidden?)

Even though there is an "alert" there, I want to use the click event to set the value back in the .lab field like a dropdown.

答:
In the solution below, clicking the
 element with the .lab class style applied will fire the first event listener and the dropdown list will be visible. Clicking on any of the
 elements in the dropdown list that implements the .clickable class style fires the second event listener. In this case, the dropdown list is closed and the id value of the clicked
 element is printed to the console.

/* Fires when clicking the
 element with the ".lab" class style applied. */
$(document).on('click', '.lab', function(event) {
  event.stopPropagation();
  console.clear();
  console.log("The dropdown list opens.");

  /* Open Dropdown List */
  $('.val').attr('style', 'display: inline-block');

  /* Fires when clicking the
 element with the ".clickable" class style applied. */
  $(document).on('click', '.clickable', function(event) {
    event.stopPropagation();
    console.clear();
    console.log(`Clicked Container ID: ${$(this).attr('id')}`);

    /* Close Dropdown List */
    $('.val').attr('style', 'display: none');
  });

  $(document).on('click',function(event){
    event.stopPropagation();
    $('.val').attr('style', 'display: none');
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>div {
  padding: 5px;
}
.container {
  display: inline-block;
}
.lab {
  border: 1px solid blue;
  margin-bottom: 5px;
  cursor: pointer;
}
.val {
  display: none;
  position: absolute;
  z-index: 1;
}
.container:focus-within .val {
  display: block;
}
.clickable {
  cursor: pointer;
  border: 1px solid red;
  margin-bottom: 5px;
}</code>```

Open Dropdown

First

Second

```

Title: CSS Simple Dropdown click event

Body:
I am trying to build a very simple functionality to create a drop down under a certain text field when its clicked.

$(".val").children("div").on("click", function() {
  alert("CLICK");
});

.container {
  display: inline-block;
}

.val {
  display: none;
  position: absolute;
  z-index: 1;
}

.container:focus-within .val {
  display: block;
}

LABEL

VAL1

VAL2

Main problem comes with the click function which it never gets triggered... (I guess it runs first the lost focus in CSS and then no click is done in that element as its hidden?)

Even though there is an "alert" there, I want to use the click event to set the value back in the .lab field like a dropdown.

Body:
In the solution below, clicking the <div> element with the .lab class style applied will fire the first event listener and the dropdown list will be visible. Clicking on any of the <div> elements in the dropdown list that implements the .clickable class style fires the second event listener. In this case, the dropdown list is closed and the id value of the clicked <div> element is printed to the console.

/* Fires when clicking the <div> element with the ".lab" class style applied. */
$(document).on('click', '.lab', function(event) {
  event.stopPropagation();
  console.clear();
  console.log("The dropdown list opens.");

  /* Open Dropdown List */
  $('.val').attr('style', 'display: inline-block');

  /* Fires when clicking the <div> element with the ".clickable" class style applied. */
  $(document).on('click', '.clickable', function(event) {
    event.stopPropagation();
    console.clear();
    console.log(`Clicked Container ID: ${$(this).attr('id')}`);

    /* Close Dropdown List */
    $('.val').attr('style', 'display: none');
  });

  $(document).on('click',function(event){
    event.stopPropagation();
    $('.val').attr('style', 'display: none');
  });
});

div {
  padding: 5px;
}
.container {
  display: inline-block;
}
.lab {
  border: 1px solid blue;
  margin-bottom: 5px;
  cursor: pointer;
}
.val {
  display: none;
  position: absolute;
  z-index: 1;
}
.container:focus-within .val {
  display: block;
}
.clickable {
  cursor: pointer;
  border: 1px solid red;
  margin-bottom: 5px;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<body>
  <div class="container">
    <div class="lab" contenteditable>Open Dropdown</div>

    <div class="val">
      <div id="first" class="clickable">First</div>
      <div id="second" class="clickable">Second</div>
    </div>
  </div>
</body>


问:
Algorithm that reduces an array of integers to a single value
Given an array of integers.

Inside the for loop, firstly, I'm making a copy of the initial array to a new array. Then the last element is being removed and the rest elements are being rotated by one to the right.

That means the element at index 0 will go to index 1, and so on, and the element will go to index 0.

At this point, I am facing the issue. The previous result has to be a source for the subsequent iteration.

The process continues until there's only one element left in the array.

Here is the code I have:

```<code>        int[] arr= {1,2,3,4,5}; // orignal array

        int[] newArr = new int[arr.length];
        int[] result = new int[newArr.length];
        for(int i = 1;i<n;i++)
        {

            newArr = Arrays.copyOf(arr, arr.length - i);
            System.out.println(Arrays.toString(newArr));// here i am deleting one array at last,
// code works fine upto here. but i want the next step as below commented code to perform in loop. which i am really unable to do.

            //System.arraycopy(newArr, 0, result, 1, newArr.length - 1);
            //result[0] = newArr[newArr.length - 1];
            //result = Arrays.copyOf(result,result.length-1);
            //System.out.println(Arrays.toString(result));
        }
</code>```

output should come like this

```<code>[1, 2, 3, 4, 5] // original array

[1, 2, 3, 4] // array after deletion

[4, 1, 2, 3] // array after rotaion

[4, 1, 2]// again after deletion from previous array

[2, 4, 1]// array after rotaion

[2, 4]// again after deletion from previous array

[4, 2]// array after rotation

[4]

final answer is 4
</code>```

答:
Here is one approach.

```<code>int[] arr = {1,2,3,4,5};
while (arr.length > 1) {
    System.out.println(Arrays.toString(arr));
    arr = deleteAndRotate(arr);
}
System.out.println(Arrays.toString(arr));
</code>```

prints

```<code>[1, 2, 3, 4, 5]
[4, 1, 2, 3]
[2, 4, 1]
[4, 2]
[4]
</code>```

return array if length == 1.

create a new array of one less size

store next to last item in first position

fill remainder of new array starting with old.

return new array.

```<code>public static int[] deleteAndRotate(int[] v) {
    if (v.length == 1) {
        return v;
    }
    int[] r = new int[v.length-1];
    r[0] = v[v.length-2];

    System.arraycopy(v, 0, r, 1, v.length-2);
    return r;
}
</code>```

Body:
Given an array of integers.

Inside the for loop, firstly, I'm making a copy of the initial array to a new array. Then the last element is being removed and the rest elements are being rotated by one to the right.

That means the element at index 0 will go to index 1, and so on, and the element will go to index 0.

At this point, I am facing the issue. The previous result has to be a source for the subsequent iteration.

The process continues until there's only one element left in the array.

Here is the code I have:

        int[] arr= {1,2,3,4,5}; // orignal array

        int[] newArr = new int[arr.length];
        int[] result = new int[newArr.length];
        for(int i = 1;i<n;i++)
        {

            newArr = Arrays.copyOf(arr, arr.length - i);
            System.out.println(Arrays.toString(newArr));// here i am deleting one array at last,
// code works fine upto here. but i want the next step as below commented code to perform in loop. which i am really unable to do.

            //System.arraycopy(newArr, 0, result, 1, newArr.length - 1);
            //result[0] = newArr[newArr.length - 1];
            //result = Arrays.copyOf(result,result.length-1);
            //System.out.println(Arrays.toString(result));
        }

output should come like this

[1, 2, 3, 4, 5] // original array

[1, 2, 3, 4] // array after deletion

[4, 1, 2, 3] // array after rotaion

[4, 1, 2]// again after deletion from previous array

[2, 4, 1]// array after rotaion

[2, 4]// again after deletion from previous array

[4, 2]// array after rotation

[4]

final answer is 4

Body:
Here is one approach.

int[] arr = {1,2,3,4,5};
while (arr.length > 1) {
    System.out.println(Arrays.toString(arr));
    arr = deleteAndRotate(arr);
}
System.out.println(Arrays.toString(arr));

prints

[1, 2, 3, 4, 5]
[4, 1, 2, 3]
[2, 4, 1]
[4, 2]
[4]

return array if length == 1.

create a new array of one less size

store next to last item in first position

fill remainder of new array starting with old.

return new array.

public static int[] deleteAndRotate(int[] v) {
    if (v.length == 1) {
        return v;
    }
    int[] r = new int[v.length-1];
    r[0] = v[v.length-2];

    System.arraycopy(v, 0, r, 1, v.length-2);
    return r;
}


问:
How to disable error squiggles in visual studio code
I am using Visual Studio Code to program in C++ but it keeps giving me error squiggles. I tried disabling them in the settings by changing C_Cpp error squiggles to disabled but they still appear. Is there anything else I need to do to disable them as I find them very annoying?

答: just go to command palette (ctrl + shift + P) and then search C/C++ enable error squiggles and select that. Done


问:
How to select the rows with same absolute value in a column
I want to select rows 0, 1, 3, and 4 and other rows with values that have the same absolution values. Note that assume we don't know the values (there could be -25, 25, -2356, 2356, etc.)

```<code>test = pd.DataFrame({'id':[1, 2, 3, 4, 5],
                     'quantity':[20, 30, 40, -30, -20]})

    id  quantity
0   1   20
1   2   30
2   3   40
3   4   -30
4   5   -20
.....
</code>```

What is the best way of doing this?

答:
IIUC, you want to filter the rows that have at least 2 times a value in absolute form. You could use groupby on the abs value:

```<code>test[test.groupby(test['quantity'].abs())['quantity'].transform('size').ge(2)]
</code>```

If you want to ensure that you have both the negative and positive value, make it a set and check that there are 2 elements (the positive and negative):

```<code>test[test.groupby(test['quantity'].abs())['quantity'].transform(lambda g: len(set(g))==2)]
</code>```

output:

```<code>   id  quantity
0   1        20
1   2        30
3   4       -30
4   5       -20
</code>```

Body:
I want to select rows 0, 1, 3, and 4 and other rows with values that have the same absolution values. Note that assume we don't know the values (there could be -25, 25, -2356, 2356, etc.)

test = pd.DataFrame({'id':[1, 2, 3, 4, 5],
                     'quantity':[20, 30, 40, -30, -20]})

    id  quantity
0   1   20
1   2   30
2   3   40
3   4   -30
4   5   -20
.....

What is the best way of doing this?

Body:
IIUC, you want to filter the rows that have at least 2 times a value in absolute form. You could use groupby on the abs value:

test[test.groupby(test['quantity'].abs())['quantity'].transform('size').ge(2)]

If you want to ensure that you have both the negative and positive value, make it a set and check that there are 2 elements (the positive and negative):

test[test.groupby(test['quantity'].abs())['quantity'].transform(lambda g: len(set(g))==2)]

output:

   id  quantity
0   1        20
1   2        30
3   4       -30
4   5       -20


问:
How to do a basic left outer join with data.table in R?
I have a data.table of a and b that I've partitioned into below with b < .5 and above with b > .5:

```<code>DT = data.table(a=as.integer(c(1,1,2,2,3,3)), b=c(0,0,0,1,1,1))
above = DT[DT$b > .5]
below = DT[DT$b < .5, list(a=a)]
</code>```

I'd like to do a left outer join between above and below: for each a in above, count the number of rows in below. This is equivalent to the following in SQL:

```<code>with dt as (select 1 as a, 0 as b union select 1, 0 union select 2, 0 union select 2, 1 union select 3, 1 union select 3, 1),
  above as (select a, b from dt where b > .5),
  below as (select a, b from dt where b < .5)
select above.a, count(below.a) from above left outer join below on (above.a = below.a) group by above.a;
 a | count
---+-------
 3 |     0
 2 |     1
(2 rows)
</code>```

How do I accomplish the same thing with data.tables?  This is what I tried so far:

```<code>> key(below) = 'a'
> below[above, list(count=length(b))]
     a count
[1,] 2     1
[2,] 3     1
[3,] 3     1
> below[above, list(count=length(b)), by=a]
Error in eval(expr, envir, enclos) : object 'b' not found
> below[, list(count=length(a)), by=a][above]
     a count b
[1,] 2     1 1
[2,] 3    NA 1
[3,] 3    NA 1
</code>```

I should also be more specific in that I already tried merge but that blows through the memory on my system (and the dataset takes only about 20% of my memory).

答:
I eventually found a way to do this with data.table, which I felt is more natural for me to understand than DWin's table, though YMMV:

```<code>result = below[, list(count=length(b)), by=a]
key(result) = 'a'
result = result[J(unique(above$a))]
result$count[is.na(result$count)] = 0
</code>```

I don't know if this could be more compact, though. I especially wanted to be able to do something like result = below[J(unique(above$a)), list(count=length(b))], but that doesn't work.

Body:
I have a data.table of a and b that I've partitioned into below with b < .5 and above with b > .5:

DT = data.table(a=as.integer(c(1,1,2,2,3,3)), b=c(0,0,0,1,1,1))
above = DT[DT$b > .5]
below = DT[DT$b < .5, list(a=a)]

I'd like to do a left outer join between above and below: for each a in above, count the number of rows in below. This is equivalent to the following in SQL:

with dt as (select 1 as a, 0 as b union select 1, 0 union select 2, 0 union select 2, 1 union select 3, 1 union select 3, 1),
  above as (select a, b from dt where b > .5),
  below as (select a, b from dt where b < .5)
select above.a, count(below.a) from above left outer join below on (above.a = below.a) group by above.a;
 a | count
---+-------
 3 |     0
 2 |     1
(2 rows)

How do I accomplish the same thing with data.tables?  This is what I tried so far:

> key(below) = 'a'
> below[above, list(count=length(b))]
     a count
[1,] 2     1
[2,] 3     1
[3,] 3     1
> below[above, list(count=length(b)), by=a]
Error in eval(expr, envir, enclos) : object 'b' not found
> below[, list(count=length(a)), by=a][above]
     a count b
[1,] 2     1 1
[2,] 3    NA 1
[3,] 3    NA 1

I should also be more specific in that I already tried merge but that blows through the memory on my system (and the dataset takes only about 20% of my memory).

Body:
I eventually found a way to do this with data.table, which I felt is more natural for me to understand than DWin's table, though YMMV:

result = below[, list(count=length(b)), by=a]
key(result) = 'a'
result = result[J(unique(above$a))]
result$count[is.na(result$count)] = 0

I don't know if this could be more compact, though. I especially wanted to be able to do something like result = below[J(unique(above$a)), list(count=length(b))], but that doesn't work.


问:
Pages overlaps on navigation in Ionic4
I have developed an application using ionic4. I am facing an issue during navigation the pages overlaps like below give picture. I am using NavController for navigation.

```<code>    public editUserProfile() {
       this.menuCtrl.close('side-menu');
       this.navCtrl.navigateForward('/home/edit-profile');
  }
</code>```

Any solution for this?

答:
Overlapping content while routing to other pages could be due to default routing animation.

Try disabling "animated" property to false in ion-router-outlet.

<ion-router-outlet [animated]="false" id="main"></ion-router-outlet>```

Title: Pages overlaps on navigation in Ionic4

Body:
I have developed an application using ionic4. I am facing an issue during navigation the pages overlaps like below give picture. I am using NavController for navigation.

    public editUserProfile() {
       this.menuCtrl.close('side-menu');
       this.navCtrl.navigateForward('/home/edit-profile');
  }

Any solution for this?


问:
What Date Class is used in grails?
I want to get the 4-digit year from today.

I have a variable def todayDate = new Date() in my controller.

I googled to see how to do it.  It pointed me to this page.

https://docs.groovy-lang.org/latest/html/groovy-jdk/java/util/Date.html

There is a method called toYear()

Actually, none of the methods in this document works. The Date class in this document is not the same Date class in  the controller for sure.

Did Google show me the wrong document?  What is the correct way to get the 4-digit year from a Date()?

答:
I was reading and trying to understand all the comments and checking the links.  I think I get what is going on here.

When I declare a Date variable in Grails, it is a java.util.Date.  If I google how to work with the Date, this gets confusing.  The methods that process the Date are not from the java.util.Date class.  Majority of the java.util.Date methods are deprecated.  The methods you can find from google are actually coming from the org.codehaus.groovy:groovy-dateutil:3.0.9 Groovy date enhancement package.

So, the Date is a java.util.Date but the methods are from the enhancement package.

Title: What Date Class is used in grails?


问:
How to delete the extra spacing in code after it is printed?
I have been working on a project. I am limited to using a few libraries so any additional library would not be helpful. I am noticing an extra space after the last number when the calendar is finished. How do I fix this extra spacing issue? please help! Here's an example picture of the output.
**UPDATE: Thanks Drew for helping me with the alignment!</p>
```<code>//extracted code..
#include <iostream>

int main() {
         int day = 0;
         if (day > 9)
         {
            std::cout << day << '\n';
         }
         else
         {
            std::cout << day << '\n' << " ";
         }
}

</code>```

答:
Change every (day > 9) to (day >= 9 ).

You are using that condition to decide how much whitespace should appear after the number.

Demo

Body:
I have been working on a project. I am limited to using a few libraries so any additional library would not be helpful. I am noticing an extra space after the last number when the calendar is finished. How do I fix this extra spacing issue? please help! Here's an example picture of the output.
**UPDATE: Thanks Drew for helping me with the alignment!

//extracted code..
#include <iostream>

int main() {
         int day = 0;
         if (day > 9)
         {
            std::cout << day << '\n';
         }
         else
         {
            std::cout << day << '\n' << " ";
         }
}


问:
Is it possible to force Serilog.Sink.File to start a new log file when application starts up?
I'm using Serilog.Sinks.File and would like to get a fresh log file when my application starts up.

Is there any way to do that?

The logger always appends to the existing log file.

答:
You can use a method like this:

```<code>public static void CreateNextLogInSequence(string path, string prefix, DateTime timestamp, string suffix, string format, int? index = null)
{
    var target = new FileInfo(string.Format("{0}/{1}{2}{3}{4}",
        path,
        prefix,
        timestamp.ToString(format, CultureInfo.InvariantCulture),
        index == null ? string.Empty : ("_" + index.Value.ToString("000", CultureInfo.InvariantCulture)),
        suffix));
    if (target.Exists || index == null)
        CreateNextLogInSequence(path, prefix, timestamp, suffix, format, (index ?? 0) + 1);
    else
        target.Create().Close();
}
</code>```

.. and use it like this:

```<code>.UseSerilog((context, services, config) =>
{
    ...

    CreateNextLogInSequence("Logs", "log-", DateTime.Now, ".txt", "yyyyMMdd");

    config.WriteTo.Logger(lc => lc
        .WriteTo.File(path: $"Logs/log-.txt", rollOnFileSizeLimit: true, rollingInterval: RollingInterval.Day,
            formatter: new ExpressionTemplate("{@t:yyyy-MM-dd HH:mm:ss} [{@l:u3}] [{SourceContext}] {if @m = '[null]' then '' else @m}\n{@x}")));
}
</code>```

This will create a brand new file in the sequence and simulate a rollover that Serilog will recognize. It will start using the freshly created file.

Body:
You can use a method like this:

public static void CreateNextLogInSequence(string path, string prefix, DateTime timestamp, string suffix, string format, int? index = null)
{
    var target = new FileInfo(string.Format("{0}/{1}{2}{3}{4}",
        path,
        prefix,
        timestamp.ToString(format, CultureInfo.InvariantCulture),
        index == null ? string.Empty : ("_" + index.Value.ToString("000", CultureInfo.InvariantCulture)),
        suffix));
    if (target.Exists || index == null)
        CreateNextLogInSequence(path, prefix, timestamp, suffix, format, (index ?? 0) + 1);
    else
        target.Create().Close();
}

.. and use it like this:

.UseSerilog((context, services, config) =>
{
    ...

    CreateNextLogInSequence("Logs", "log-", DateTime.Now, ".txt", "yyyyMMdd");

    config.WriteTo.Logger(lc => lc
        .WriteTo.File(path: $"Logs/log-.txt", rollOnFileSizeLimit: true, rollingInterval: RollingInterval.Day,
            formatter: new ExpressionTemplate("{@t:yyyy-MM-dd HH:mm:ss} [{@l:u3}] [{SourceContext}] {if @m = '[null]' then '' else @m}\n{@x}")));
}

This will create a brand new file in the sequence and simulate a rollover that Serilog will recognize. It will start using the freshly created file.


问:
How do you stop processing when there's an error on the GRPC input stream?
Say I have a method

rpc saveFormData(stream SavedFormChunk) returns (stream SavedFormChunk) {}
```
<p>in the server implementation</p>
<pre class="lang-java prettyprint-override"><code>public StreamObserver<SavedFormChunk> saveFormData(StreamObserver<SavedFormChunk> responseObserver) {
  return new StreamObserver<>() {
    public void onNext(SavedFormChunk chunk) {
      // say chunk was in error what do I do to stop the processing?
    }
    ...
  }
}
</code>```

答: About "what do I do to stop the processing" : if you want to stop the whole call (i.e. saveFormData rpc) then you call responseObserver.onError() with appropriate status. But if you just want to "stop processing" of the current current chunk received, you can just skip it and not do anything unless your client expects a SavedFormChunk in response for every SavedFormChunk it sent in the request. In that case your response message needs to be enhanced to indicate error cases so may be the response type can be SavedFormChunkOrError .

Body:
Say I have a method

rpc saveFormData(stream SavedFormChunk) returns (stream SavedFormChunk) {}

in the server implementation

public StreamObserver<SavedFormChunk> saveFormData(StreamObserver<SavedFormChunk> responseObserver) {
  return new StreamObserver<>() {
    public void onNext(SavedFormChunk chunk) {
      // say chunk was in error what do I do to stop the processing?
    }
    ...
  }
}


问:
Post request secure, only my site can post to server
i want to make a Post Request to Node.js from React, but in the Developer Tool in Payload it shows me the Secret Key, and if it shows me there I haven't solved anything, is there a way for me to do this securely? and without SECRET KEY being visible in Developer Tool?

my react post request code

```<code>     .post("http://.../api/test", {
          secret: process.env.REACT_APP_SECRET_KEY,
          battleData: battleData,
          accountCurent: accountCurent,
        })
        .then(function (response) {}
....
</code>```

and my Node.js code

```<code>app.post("/api/test", (req, res) => {
if(req.body.secret === process.env.REACT_APP_SECRET_KEY){}
...// I only want when Secret Key is identical by Node to the frontEnd and run my code in Node.js
</code>```

答: No, if the secret is part of the frontend a user will always be able to find it. Instead of solving that problem, you should try to make sure that you don't need secrets.

Body:
i want to make a Post Request to Node.js from React, but in the Developer Tool in Payload it shows me the Secret Key, and if it shows me there I haven't solved anything, is there a way for me to do this securely? and without SECRET KEY being visible in Developer Tool?

my react post request code

     .post("http://.../api/test", {
          secret: process.env.REACT_APP_SECRET_KEY,
          battleData: battleData,
          accountCurent: accountCurent,
        })
        .then(function (response) {}
....

and my Node.js code

app.post("/api/test", (req, res) => {
if(req.body.secret === process.env.REACT_APP_SECRET_KEY){}
...// I only want when Secret Key is identical by Node to the frontEnd and run my code in Node.js


问:
How do I edit the javafx ui in another class?

AppRunner class

```<code>import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.fxml.FXMLLoader;

public class AppRunner {

    public static void main(String[] args) {
        startUi.launchPanel(args);
    }

    public static void waitFiveSecToClear() {
        new Thread(
                new Runnable() {
            public void run() {
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException ex) {
                    Logger.getLogger(AppRunner.class.getName()).log(Level.SEVERE, null, ex);
                }
                FXMLLoader loader = new FXMLLoader(getClass().getResource("listView.fxml"));
                try {
                    loader.load();
                } catch (IOException ex) {
                    Logger.getLogger(AppRunner.class.getName()).log(Level.SEVERE, null, ex);
                }
                System.out.println("clearing listView");
                ((ListViewController) loader.getController()).clearAll();
            }
        }).start();
    }
}
</code>```

ListViewController class

```<code>package apprunner;

import java.net.URL;
import java.util.ResourceBundle;
import javafx.application.Platform;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.ListView;

/**
 * FXML Controller class
 *
 */
public class ListViewController implements Initializable {

    public ListViewController() {

    }

    @FXML
    private ListView<String> listView;

    /**
     * Initializes the controller class.
     */
    @Override
    public void initialize(URL url, ResourceBundle rb) {
        // TODO
        listView.getItems().add("clear all!");
        listView.getItems().add("clear all!");
        listView.getItems().add("clear all!");
        listView.getItems().add("clear all!");
        AppRunner.waitFiveSecToClear();
    }

    public void clearAll() {
        Platform.runLater(new Runnable() {
            @Override
            public void run() {
                listView.getItems().clear();
            }
        });

    }
}
</code>```

startUi class

```<code>package apprunner;

/**
 *
 */
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class startUi extends Application {

    public static void launchPanel(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage stage) throws Exception {
        Parent root = FXMLLoader.load(getClass().getResource("listView.fxml"));
        Scene scene = new Scene(root);
        stage.setScene(scene);
        stage.show();
    }
}
</code>```

listView.fxml

```<code><?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.ListView?>
<?import javafx.scene.layout.AnchorPane?>

<AnchorPane id="AnchorPane" prefHeight="400.0" prefWidth="600.0" xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/17" fx:controller="apprunner.ListViewController">
   <children>
      <ListView fx:id="listView" layoutX="68.0" layoutY="39.0" prefHeight="200.0" prefWidth="200.0" />
   </children>
</AnchorPane>
</code>```

Currently there is no error. However my code isn't doing what I want. I want the waitFiveSecToClear() method inside the AppRunner class to clear the listView in the javafx ui. However this isn't happening. I used ((ListViewController) loader.getController()).clearAll(); to attempt to clear the listView which doesen't seem to do anything. If someone could help me figure out my problem that would be great thanks!

Context for my problem

I have a highschool capstone project. I chose to make a music internet downloader. When my program is downloading music, it would freeze the whole javafx application without the thread, so I used a thread and Thread.sleep(5000) in my waitFiveSecToClear() method to simulate that. My program has a listView which shows a queue of all the music urls currently being downloaded. I want it so that when one url is finished downloading, the listView is updated which must be done on the Javafx thread which requires Platform.runlater. So, I used Platform.runLater in the clearAll() method to simluate that. I don't want to do that in the controller because based on what I've learned that would break model, view, controller architecture. I have an AppRunner class because my teachers program example had that so I just copied it.

答: I solved my problem by using a Task and ObservableList as suggested by @James_D and @jewelsea. I have a Task in my model which would download music and remove the url of the music from the ObservableList once it finished downloading. I then have a Listener in my controller which would update the ListView when the ObservableList changed.</p>

Body:
AppRunner class

import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.fxml.FXMLLoader;

public class AppRunner {

    public static void main(String[] args) {
        startUi.launchPanel(args);
    }

    public static void waitFiveSecToClear() {
        new Thread(
                new Runnable() {
            public void run() {
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException ex) {
                    Logger.getLogger(AppRunner.class.getName()).log(Level.SEVERE, null, ex);
                }
                FXMLLoader loader = new FXMLLoader(getClass().getResource("listView.fxml"));
                try {
                    loader.load();
                } catch (IOException ex) {
                    Logger.getLogger(AppRunner.class.getName()).log(Level.SEVERE, null, ex);
                }
                System.out.println("clearing listView");
                ((ListViewController) loader.getController()).clearAll();
            }
        }).start();
    }
}

ListViewController class

package apprunner;

import java.net.URL;
import java.util.ResourceBundle;
import javafx.application.Platform;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.ListView;

/**
 * FXML Controller class
 *
 */
public class ListViewController implements Initializable {

    public ListViewController() {

    }

    @FXML
    private ListView<String> listView;

    /**
     * Initializes the controller class.
     */
    @Override
    public void initialize(URL url, ResourceBundle rb) {
        // TODO
        listView.getItems().add("clear all!");
        listView.getItems().add("clear all!");
        listView.getItems().add("clear all!");
        listView.getItems().add("clear all!");
        AppRunner.waitFiveSecToClear();
    }

    public void clearAll() {
        Platform.runLater(new Runnable() {
            @Override
            public void run() {
                listView.getItems().clear();
            }
        });

    }
}

startUi class

package apprunner;

/**
 *
 */
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class startUi extends Application {

    public static void launchPanel(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage stage) throws Exception {
        Parent root = FXMLLoader.load(getClass().getResource("listView.fxml"));
        Scene scene = new Scene(root);
        stage.setScene(scene);
        stage.show();
    }
}

listView.fxml

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.ListView?>
<?import javafx.scene.layout.AnchorPane?>

<AnchorPane id="AnchorPane" prefHeight="400.0" prefWidth="600.0" xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/17" fx:controller="apprunner.ListViewController">
   <children>
      <ListView fx:id="listView" layoutX="68.0" layoutY="39.0" prefHeight="200.0" prefWidth="200.0" />
   </children>
</AnchorPane>

Currently there is no error. However my code isn't doing what I want. I want the waitFiveSecToClear() method inside the AppRunner class to clear the listView in the javafx ui. However this isn't happening. I used ((ListViewController) loader.getController()).clearAll(); to attempt to clear the listView which doesen't seem to do anything. If someone could help me figure out my problem that would be great thanks!

Context for my problem

I have a highschool capstone project. I chose to make a music internet downloader. When my program is downloading music, it would freeze the whole javafx application without the thread, so I used a thread and Thread.sleep(5000) in my waitFiveSecToClear() method to simulate that. My program has a listView which shows a queue of all the music urls currently being downloaded. I want it so that when one url is finished downloading, the listView is updated which must be done on the Javafx thread which requires Platform.runlater. So, I used Platform.runLater in the clearAll() method to simluate that. I don't want to do that in the controller because based on what I've learned that would break model, view, controller architecture. I have an AppRunner class because my teachers program example had that so I just copied it.


问:
How to exclude 0 from count()? in sql?
I have a code as below where I want to count number of first purchases for a given period of time. I have a column in my sales table where if the buyer is not a first time buyer, then is_first_purchase = 0

For example:
buyer_id = 456391 is already an existing buyer who made purchases on 2 different dates.
Hence is_first_purchase column will show as 0 as per below.

If i do a count() on is_first_purchase for this buyer_id = 456391 then it should return 0 instead of 2.

My query is as follows:

```<code>with first_purchases as
    (select *,
    case when is_first_purchase = 1 then 'Yes'  else 'No' end as first_purchase
    from sales)

select
    count(case when first_purchase = 'Yes' then 1 else 0 end) as no_of_first_purchases
from first_purchases
where buyer_id = 456391
    and date_id between '2021-02-01' and '2021-03-01'
    order by 1 desc;
</code>```

It returned the below which is not an intended output

Appreciate if someone can help explain how to exclude is_first_purchase = 0 from the count, thanks.

答:
The simplest approach for Trino (f.k.a. Presto SQL) is to use an aggregate with a filter:</p>
```<code>count(name) FILTER (WHERE first_purchase = 'Yes') AS no_of_first_purchases
</code>```

Title: How to exclude 0 from count()? in sql?

Body:
I have a code as below where I want to count number of first purchases for a given period of time. I have a column in my sales table where if the buyer is not a first time buyer, then is_first_purchase = 0

For example:
buyer_id = 456391 is already an existing buyer who made purchases on 2 different dates.
Hence is_first_purchase column will show as 0 as per below.

If i do a count() on is_first_purchase for this buyer_id = 456391 then it should return 0 instead of 2.

My query is as follows:

with first_purchases as
    (select *,
    case when is_first_purchase = 1 then 'Yes'  else 'No' end as first_purchase
    from sales)

select
    count(case when first_purchase = 'Yes' then 1 else 0 end) as no_of_first_purchases
from first_purchases
where buyer_id = 456391
    and date_id between '2021-02-01' and '2021-03-01'
    order by 1 desc;

It returned the below which is not an intended output

Appreciate if someone can help explain how to exclude is_first_purchase = 0 from the count, thanks.

Body:
The simplest approach for Trino (f.k.a. Presto SQL) is to use an aggregate with a filter:

count(name) FILTER (WHERE first_purchase = 'Yes') AS no_of_first_purchases


问:
Short (and useful) python snippets
In spirit of the existing "what's your most useful C/C++ snippet" - thread:

Do you guys have short, monofunctional Python snippets that you use (often) and would like to share with the StackOverlow Community? Please keep the entries small (under 25
lines maybe?) and give only one example per post.

I'll start of with a short snippet i use from time to time to count sloc (source lines of code) in python projects:

```<code># prints recursive count of lines of python source code from current directory
# includes an ignore_list. also prints total sloc

import os
cur_path = os.getcwd()
ignore_set = set(["__init__.py", "count_sourcelines.py"])

loclist = []

for pydir, _, pyfiles in os.walk(cur_path):
    for pyfile in pyfiles:
        if pyfile.endswith(".py") and pyfile not in ignore_set:
            totalpath = os.path.join(pydir, pyfile)
            loclist.append( ( len(open(totalpath, "r").read().splitlines()),
                               totalpath.split(cur_path)[1]) )

for linenumbercount, filename in loclist:
    print "%05d lines in %s" % (linenumbercount, filename)

print "\nTotal: %s lines (%s)" %(sum([x[0] for x in loclist]), cur_path)
</code>```

答:
```<code>import tempfile
import cPickle

class DiskFifo:
    """A disk based FIFO which can be iterated, appended and extended in an interleaved way"""
    def __init__(self):
        self.fd = tempfile.TemporaryFile()
        self.wpos = 0
        self.rpos = 0
        self.pickler = cPickle.Pickler(self.fd)
        self.unpickler = cPickle.Unpickler(self.fd)
        self.size = 0

    def __len__(self):
        return self.size

    def extend(self, sequence):
        map(self.append, sequence)

    def append(self, x):
        self.fd.seek(self.wpos)
        self.pickler.clear_memo()
        self.pickler.dump(x)
        self.wpos = self.fd.tell()
        self.size = self.size + 1

    def next(self):
        try:
            self.fd.seek(self.rpos)
            x = self.unpickler.load()
            self.rpos = self.fd.tell()
            return x

        except EOFError:
            raise StopIteration

    def __iter__(self):
        self.rpos = 0
        return self
</code>```

OwnerDisplayName: ChristopheD

Title: Short (and useful) python snippets

Body:
In spirit of the existing "what's your most useful C/C++ snippet" - thread:

Do you guys have short, monofunctional Python snippets that you use (often) and would like to share with the StackOverlow Community? Please keep the entries small (under 25
lines maybe?) and give only one example per post.

I'll start of with a short snippet i use from time to time to count sloc (source lines of code) in python projects:

# prints recursive count of lines of python source code from current directory
# includes an ignore_list. also prints total sloc

import os
cur_path = os.getcwd()
ignore_set = set(["__init__.py", "count_sourcelines.py"])

loclist = []

for pydir, _, pyfiles in os.walk(cur_path):
    for pyfile in pyfiles:
        if pyfile.endswith(".py") and pyfile not in ignore_set:
            totalpath = os.path.join(pydir, pyfile)
            loclist.append( ( len(open(totalpath, "r").read().splitlines()),
                               totalpath.split(cur_path)[1]) )

for linenumbercount, filename in loclist:
    print "%05d lines in %s" % (linenumbercount, filename)

print "\nTotal: %s lines (%s)" %(sum([x[0] for x in loclist]), cur_path)

LastEditorDisplayName: ChristopheD


问:
static navbar shakes horizontaly on leaving modal
currently I have troubles with bootstrap5 and modal respectively glightbox.

when switching back from these applications, the static navbar shakes horizontaly.

the same with glightbox, additional to that the sticky footer also slides up when the screen is grayed out.

deliberate specific features: sticky footer, vertical scrollbar always on

```<code>fullscreen sample: https://codepen.io/manu_g/full/dyZOdbV
</code>```

答:
Inspecting your codepen, I observed that the margin-left and margin-right of the child element of the #header increases, when the modal opens.

When you leave modal, margin-left and margin-right are returning back to their initial values, causing the shake.

The fixed position seems to be the root of cause. Thus, I would go with position: sticky instead and add some margin top in the .inner-pages.

For example,

```<code>.fixed-top {
    position: sticky;
    top: 0;
    right: 0;
    left: 0;
    z-index: 1030;
}

.inner-page {
    margin-top: 50px;
}

</code>```

Body:
currently I have troubles with bootstrap5 and modal respectively glightbox.

when switching back from these applications, the static navbar shakes horizontaly.

the same with glightbox, additional to that the sticky footer also slides up when the screen is grayed out.

deliberate specific features: sticky footer, vertical scrollbar always on

fullscreen sample: https://codepen.io/manu_g/full/dyZOdbV

Body:
Inspecting your codepen, I observed that the margin-left and margin-right of the child element of the #header increases, when the modal opens.

When you leave modal, margin-left and margin-right are returning back to their initial values, causing the shake.

The fixed position seems to be the root of cause. Thus, I would go with position: sticky instead and add some margin top in the .inner-pages.

For example,

.fixed-top {
    position: sticky;
    top: 0;
    right: 0;
    left: 0;
    z-index: 1030;
}

.inner-page {
    margin-top: 50px;
}


问:
How can i connect to robomongo in my windows to mongodb installed on amazon ec2 instance?
I have installed mongodb v4.4.2 in my amazon linux 2 (on aws ec2 instance) and installed robomongo in my local windows machine. Now i want to connect to my db on ec2 but i always get this error window from robomongo:

Cannot connect to the MongoDB at <ec2_ipv4>:27017.

Error: Network is unreachable. Reason: couldn't connect to server
<ec2_ipv4>:27017, connection attempt failed: NetworkTimeout: Error
connecting to <ec2_ipv4>:27017 :: caused by :: Socket operation timed
out

These are the things that i have done:

Changed bindIp field in /etc/mongod.conf(in ec2 linux) file to 0.0.0.0 and port already set to 27017

stopped and started the mongod server again.

Exposed the port 27017 in security groups in my aws account with tcp protocol with source set to 0.0.0.0/0

in robomongo created a new connection with address: "ipv4 address of ec2 instance" and port = 27017

Is there anything that i have missed. Why is my connection not being established?

答:
I fixed this by add EC2's private IPv4 as a bind IP in /etc/mongod.conf

so it would look like this

```<code># network interfaces
net:
  port: 27017
  bindIp: 127.0.0.1,<your-ec2-private-ipv4>
</code>```

Body:
I fixed this by add EC2's private IPv4 as a bind IP in /etc/mongod.conf

so it would look like this

# network interfaces
net:
  port: 27017
  bindIp: 127.0.0.1,<your-ec2-private-ipv4>


问:
Windows Forms designer compilation symbol: does it exist?
Does Windows Forms for full Windows OS has some compilation symbol so when designer is going to compile code I can conditionally compile with preprocessor directives?

Compact Framework projects have so, but I don't find such symbol in a full Windows Forms project.

Sample code:

```<code>#if DESIGNTIME

#endif
</code>```

答:
From .Net source:</p>
```<code>public static bool DesignTime( Control myControlOrForm )
{
    return myControlOrForm.Site != null && myControlOrForm.Site.DesignMode;
}
</code>```

Body:
Does Windows Forms for full Windows OS has some compilation symbol so when designer is going to compile code I can conditionally compile with preprocessor directives?

Compact Framework projects have so, but I don't find such symbol in a full Windows Forms project.

Sample code:

#if DESIGNTIME

#endif

Body:
From .Net source:

public static bool DesignTime( Control myControlOrForm )
{
    return myControlOrForm.Site != null && myControlOrForm.Site.DesignMode;
}


问:
Getting information from mysql using jquery
i have mysql database for i fetch information using json
for example:

```<code>$sql ="SELECT * FROM parent WHERE id = '$name'";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
 {
$abc=$row[id];
}
echo json_encode($abc)
</code>```

Now how can i display this json encoded element in my main html file using jquery?
what i want to do is based on this fetched element i want to do some if else operation.

for example:

```<code>if(value of row[id](should be achieved using jquery) ==null)
{}
else
{}
</code>```

I am looking for something like $(xxxx).somefunction()
Thanks in advance.

答:
You could use jQuery to convert the JSON into a JavaScript object and then add the properties  of the object into your html.

```<code>jQuery.parseJSON( json )
</code>```

Add the JSON from the database to your webpage through:

```<code>echo "var myJson = ".json_encode($abc);
</code>```

Then use jQuery to parse the JSON through:

```<code>myObject = jQuery.parseJSON(myJson);
alert(myObject.id);
</code>```

Body:
i have mysql database for i fetch information using json
for example:

$sql ="SELECT * FROM parent WHERE id = '$name'";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
 {
$abc=$row[id];
}
echo json_encode($abc)

Now how can i display this json encoded element in my main html file using jquery?
what i want to do is based on this fetched element i want to do some if else operation.

for example:

if(value of row[id](should be achieved using jquery) ==null)
{}
else
{}

I am looking for something like $(xxxx).somefunction()
Thanks in advance.

Body:
You could use jQuery to convert the JSON into a JavaScript object and then add the properties  of the object into your html.

jQuery.parseJSON( json )

Add the JSON from the database to your webpage through:

echo "var myJson = ".json_encode($abc);

Then use jQuery to parse the JSON through:

myObject = jQuery.parseJSON(myJson);
alert(myObject.id);


问:
How to get value from form field in django framework?
How do I get values from form fields in the django framework? I want to do this in views, not in templates...</p>

答:
Incase of django viewsets or APIView you can simply get the request.data
and if you're sure the data being passed to the view is always form data then

copy the data e.g
data = request.data.copy()

form data is returned with key values in lists so data['key'][0]
to get the first element of the list which is the value first value and most likely only value if they key only returns a single value of the key.

for example

```<code>class EquipmentView(APIView):

    def post(self, request: Request):
        data = request.data.copy()
        author = data.get('author')[0]

</code>```

Body:
Incase of django viewsets or APIView you can simply get the request.data
and if you're sure the data being passed to the view is always form data then

copy the data e.g
data = request.data.copy()

form data is returned with key values in lists so data['key'][0]
to get the first element of the list which is the value first value and most likely only value if they key only returns a single value of the key.

for example

class EquipmentView(APIView):

    def post(self, request: Request):
        data = request.data.copy()
        author = data.get('author')[0]


问:
Bad Request ("error reading build args: json: cannot unmarshal number into Go value of type string")
Using docker python library,

```<code>
    UID = USER_ID = os.getuid()
    GROUP_ID = os.getgid()
    USER = getpass.getuser()
    HOME = "~"
    DIR = os.getcwd()
    DOCKER_GID = execute_shell_command('"$(stat -c "%g" /var/run/docker.sock)"', log_path)
    VERSION = "latest"
    BASE_DOCKER = "ubuntu:20.04"

    assert os.path.isfile(dockerfile_path)

    build_args = {
        "UID": UID,
        "DOCKER_GID": DOCKER_GID,
        "UNAME": USER,
        "VER": VERSION,
        "BASE_IMAGE": BASE_DOCKER,
    }

client = client = docker.from_env()
client.images.build(fileobj=dockerfile, buildargs=build_args)
</code>```

Getting

```<code>Bad Request ("error reading build args: json: cannot unmarshal number into Go value of type string")
</code>```

答:
This is not Googleable, so posting for future readers

Answer was found here

Convert numbers in build_args to strings to avoid this undocumented error:

```<code> build_args = {k: str(v) for k, v in {
        "UID": UID,
        "DOCKER_GID": DOCKER_GID,
        "UNAME": USER,
        "VER": VERSION,
        "BASE_IMAGE": BASE_DOCKER,
    }.items()}
</code>```

Body:
Using docker python library,

    UID = USER_ID = os.getuid()
    GROUP_ID = os.getgid()
    USER = getpass.getuser()
    HOME = "~"
    DIR = os.getcwd()
    DOCKER_GID = execute_shell_command('"$(stat -c "%g" /var/run/docker.sock)"', log_path)
    VERSION = "latest"
    BASE_DOCKER = "ubuntu:20.04"

    assert os.path.isfile(dockerfile_path)

    build_args = {
        "UID": UID,
        "DOCKER_GID": DOCKER_GID,
        "UNAME": USER,
        "VER": VERSION,
        "BASE_IMAGE": BASE_DOCKER,
    }

client = client = docker.from_env()
client.images.build(fileobj=dockerfile, buildargs=build_args)

Getting

Bad Request ("error reading build args: json: cannot unmarshal number into Go value of type string")

Body:
This is not Googleable, so posting for future readers

Answer was found here

Convert numbers in build_args to strings to avoid this undocumented error:

 build_args = {k: str(v) for k, v in {
        "UID": UID,
        "DOCKER_GID": DOCKER_GID,
        "UNAME": USER,
        "VER": VERSION,
        "BASE_IMAGE": BASE_DOCKER,
    }.items()}


问:
How to prevent named grid area blowout when using grid-template-areas?
I have a simple page layout with a side section and a main section. I want my main section to be 3x the side section so I specified a template for areas like so:

```<code>grid-template-areas: "side main main main";
</code>```

However the side section is growing way larger than expected, making the main section very small.

Expected behavior:

Actual behavior:

Here's the code:

.page-layout {
  display: grid;
  grid-template-areas: "side main main main";
}

.main-section {
  background-color: lightgreen;
  grid-area: main;
}

.side-section {
  background-color: orange;
  grid-area: side;
}

.side-layout {
  display: grid;
  grid-auto-rows: minmax(min-content, max-content);
  grid-template-areas: "name" "summary" "summary";
}

.name-section {
  grid-area: name;
}

.summary-section {
  grid-area: summary;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="page-layout">
  <div class="side-section side-layout">
    <h2 class="name">
      Side section
    </h2>
    <p>
      Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus blanditiis enim eveniet fugiat impedit laboriosam laudantium magni, maxime, molestiae nemo provident repudiandae.
    </p>
  </div>

  <div class="main-section">
    <h2>Main section</h2>
  </div>
</div></code>```

I did read this Preventing a Grid Blowout article, but in that article they are using constant pixel value for one of the columns, which will not work for me. I want the main section to be 3x the side section, without specifying a constant pixel size for either of the sections.

答:
Don't define areas, define sizes using the fr unit

.page-layout {
  display: grid;
  /*grid-template-areas: "side main main main";*/
  grid-template-columns: 1fr 3fr
}

.main-section {
  background-color: lightgreen;
}

.side-section {
  background-color: orange;
}

.side-layout {
  display: grid;
  /*
   not need since you want the content to define the height
  grid-auto-rows: minmax(min-content, max-content);
  grid-template-areas: "name" "summary" "summary";*/
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="page-layout">
  <div class="side-section side-layout">
    <h2 class="name">
      Side section
    </h2>
    <p>
      Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus blanditiis enim eveniet fugiat impedit laboriosam laudantium magni, maxime, molestiae nemo provident repudiandae.
    </p>
  </div>

  <div class="main-section">
    <h2>Main section</h2>
  </div>
</div></code>```

Body:
I have a simple page layout with a side section and a main section. I want my main section to be 3x the side section so I specified a template for areas like so:

grid-template-areas: "side main main main";

However the side section is growing way larger than expected, making the main section very small.

Expected behavior:

Actual behavior:

Here's the code:

.page-layout {
  display: grid;
  grid-template-areas: "side main main main";
}

.main-section {
  background-color: lightgreen;
  grid-area: main;
}

.side-section {
  background-color: orange;
  grid-area: side;
}

.side-layout {
  display: grid;
  grid-auto-rows: minmax(min-content, max-content);
  grid-template-areas: "name" "summary" "summary";
}

.name-section {
  grid-area: name;
}

.summary-section {
  grid-area: summary;
}

      Side section

      Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus blanditiis enim eveniet fugiat impedit laboriosam laudantium magni, maxime, molestiae nemo provident repudiandae.

Main section

I did read this Preventing a Grid Blowout article, but in that article they are using constant pixel value for one of the columns, which will not work for me. I want the main section to be 3x the side section, without specifying a constant pixel size for either of the sections.

Body:
Don't define areas, define sizes using the fr unit

.page-layout {
  display: grid;
  /*grid-template-areas: "side main main main";*/
  grid-template-columns: 1fr 3fr
}

.main-section {
  background-color: lightgreen;
}

.side-section {
  background-color: orange;
}

.side-layout {
  display: grid;
  /*
   not need since you want the content to define the height
  grid-auto-rows: minmax(min-content, max-content);
  grid-template-areas: "name" "summary" "summary";*/
}

<div class="page-layout">
  <div class="side-section side-layout">
    <h2 class="name">
      Side section
    </h2>
    <p>
      Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus blanditiis enim eveniet fugiat impedit laboriosam laudantium magni, maxime, molestiae nemo provident repudiandae.
    </p>
  </div>

  <div class="main-section">
    <h2>Main section</h2>
  </div>
</div>


问:
IE9 Input Form type=file, manually edit text field
I'm looking to improve one of my company's web applications to support IE9.

One of the issues I'm having is with the input field. In IE8, a user could use the input form field to select a file, then manually edit the textual contents of the text box to, for instance, select a host folder of a file, or what have you.

In IE9, it seems that the text box is not editable. You click browse to select a file in the dialog window, and then the textbox from that point is locked.

Is there any attribute I can set to alter this behaviour?

答:
Actually, IE8 introduced the read-only text box for File Upload, and it was not changed in IE9. There's no mechanism to turn off that behavior.

To change the contents of the box, simply click the Browse button and select or paste in the new filename.


问:
How to check index of string even when the guess word is shorter than the secret word
I am having a really tough time with an error. Every time I input a guess word that is less characters than the secret word, I get "IndexError: string out of range". I am trying to get my code to find the matching letters of the guess word in the secret word. How do I get it to check each index of the word without this error? It doesn't have to print the emoji colors if the character length is less than or greater than 6 letters. I want to keep asking for a new guess until the guess is 6 characters long. I also can only use these basic functions for a class assignment and nothing more than this.

Any help would be appreciated!

WHITE_BOX: str = "\U00002B1C"
GREEN_BOX: str = "\U0001F7E9"
YELLOW_BOX: str = "\U0001F7E8"

secret_word: str = "python"
length_of_secret = len(secret_word)

guess_word: str = input(f"What is your {length_of_secret} letter guess? ")
length_of_guess = len(guess_word)

i: int = 0
check_index: int = 0
emoji_color: str = ""

while check_index < length_of_secret:
    if guess_word[check_index] in secret_word[check_index]:
        emoji_color += GREEN_BOX
    else:
        emoji_color += WHITE_BOX
    check_index += 1

while i < length_of_secret:
    if length_of_guess < length_of_secret:
        guess_word = input(f"That was not {length_of_secret} letters! Try again: ")
        length_of_guess = len(guess_word)
        if guess_word == secret_word:
            print(emoji_color)
            print("Woo! You got it!")
            break
        if length_of_guess == length_of_secret:
            print(emoji_color)
            print("Not quite. Play again soon!")
            break
    if length_of_guess > length_of_secret:
        guess_word = input(f"That was not {length_of_secret} letters! Try again: ")
        length_of_guess = len(guess_word)
        if guess_word == secret_word:
            print(emoji_color)
            print("Woo! You got it!")
            break
        if length_of_guess == length_of_secret:
            print(emoji_color)
            print("Not quite. Play again soon!")
            break
    i += 1
    if guess_word == secret_word:
        print("Woo! You got it!")
        print(emoji_color)
        break
    if length_of_guess == length_of_secret:
        print(emoji_color)
        print("Not quite. Play again soon!")
        break

```

答:
You should perform a length check before analyzing the input string. You should verify your assumption on the length before doing anything else that relies on that assumption.

secret_word: str = "python"
length_of_secret = len(secret_word)

guess_word = ""
while len(guess_word) != length_of_secret:
    guess_word: str = input(f"What is your {length_of_secret} letter guess? ")
    if len(guess_word) != length_of_secret:
        print(f"That was not {length_of_secret} letters! Try again.")
```


问:
React Hook useState behavior
I don't quietly undestand when the useState sets initial value. In this code example only on first click props and state values in Table component will be the same. Why they will not be equal on a second/third/fourth click?</p>

```<code>import React, { useState } from "react";
import "./App.module.css";
import styles from "./App.module.css";

function App() {
  const [mode, setMode] = useState({ bo: false, value: "1" });
  const onClickHanlder = (value: string) => {
    setMode({ bo: true, value });
  };
  return (
    <div className="App">
      <div onClick={() => onClickHanlder("2")}>one</div>
      <div onClick={() => onClickHanlder("3")}>one</div>
      <div onClick={() => onClickHanlder("4")}>one</div>
      <div onClick={() => onClickHanlder("25")}>one</div>
      <div onClick={() => onClickHanlder("6")}>one</div>
      {mode && <Table value={mode.value} />}
    </div>
  );
}

export default App;

type TablePropsType = {
  value: string
};
export const Table: React.FC<TablePropsType> = (props) => {
  const [a, setA] = useState(props.value);
  return (
    <div>
      {a}
      {props.value}
    </div>
  );
};
</code>```

答:
You never set the state in Table, only on initial render you give it the default state. If you want them to be the same you have to also have to set the state in Table:</p>
```<code>import React, {useState, useEffect} from 'react';

function App() {
    const [mode, setMode] = useState({bo: false, value: '1'})
    const onClickHanlder = (value: string) => {
        setMode({bo: true, value})
    }
    return (
        <div className="App">
            <div onClick={() => onClickHanlder('2')}>one</div>
            <div onClick={() => onClickHanlder('3')}>one</div>
            <div onClick={() => onClickHanlder('4')}>one</div>
            <div onClick={() => onClickHanlder('25')}>one</div>
            <div onClick={() => onClickHanlder('6')}>one</div>
            {
                mode && <Table value={mode.value}/>
            }
        </div>
    );
}

export default App;

type TablePropsType = {
    value: string,
}
export const Table:React.FC<TablePropsType> = (props) => {
    const [a, setA] = useState(props.value)
    useEffect(()=>{
      setA(props.value)
    },[props.value])
    return (
        <div>
            {a}
            {props.value}
        </div>
    )
}
</code>```

Title: React Hook useState behavior

Body:
I don't quietly undestand when the useState sets initial value. In this code example only on first click props and state values in Table component will be the same. Why they will not be equal on a second/third/fourth click?

import React, { useState } from "react";
import "./App.module.css";
import styles from "./App.module.css";

function App() {
  const [mode, setMode] = useState({ bo: false, value: "1" });
  const onClickHanlder = (value: string) => {
    setMode({ bo: true, value });
  };
  return (

 onClickHanlder("2")}>one

 onClickHanlder("3")}>one

 onClickHanlder("4")}>one

 onClickHanlder("25")}>one

 onClickHanlder("6")}>one

      {mode &&
}

  );
}

export default App;

type TablePropsType = {
  value: string
};
export const Table: React.FC<TablePropsType> = (props) => {
  const [a, setA] = useState(props.value);
  return (

      {a}
      {props.value}

  );
};

Body:
You never set the state in Table, only on initial render you give it the default state. If you want them to be the same you have to also have to set the state in Table:

import React, {useState, useEffect} from 'react';

function App() {
    const [mode, setMode] = useState({bo: false, value: '1'})
    const onClickHanlder = (value: string) => {
        setMode({bo: true, value})
    }
    return (
        <div className="App">
            <div onClick={() => onClickHanlder('2')}>one</div>
            <div onClick={() => onClickHanlder('3')}>one</div>
            <div onClick={() => onClickHanlder('4')}>one</div>
            <div onClick={() => onClickHanlder('25')}>one</div>
            <div onClick={() => onClickHanlder('6')}>one</div>
            {
                mode && <Table value={mode.value}/>
            }
        </div>
    );
}

export default App;

type TablePropsType = {
    value: string,
}
export const Table:React.FC<TablePropsType> = (props) => {
    const [a, setA] = useState(props.value)
    useEffect(()=>{
      setA(props.value)
    },[props.value])
    return (
        <div>
            {a}
            {props.value}
        </div>
    )
}


问:
Create a ggplot barplot with differently coloured horizontal rectangles as background
I would like to create a bar plot with four bars – where a transparent background of 4 differently colored, horizontal areas represent whether the strength of the bars are considered "low", "medium", "high", or "very high".

```<code># Load ggplot2
library(ggplot2)

# Example data
data <- data.frame(
  name=c("A","B","C", "D") ,
  value=c(3, 12, 16, 22)
)

# Background data
backgound_area_color <- c(5, 10, 14, 20)
background_area_name <- c("low", "medium", "high", "very high")
background_data <- as.data.frame(backgound_area_color, background_area_name)

# My attempt:
ggplot(data, aes(x=name, y=value)) +
  geom_bar(stat = "identity") +
  geom_rect(data = background_data,
            aes(y = backgound_area_color))
</code>```

Thanks in advance

答:
I like Allan Camerons approach best. Here is what I have tried to provide as an alternative using annotations:

```<code>library(ggplot2)

ggplot(data, aes(x=name, y=value))+
  annotate("rect", xmin = 0.5, xmax = 4.5, ymin = 0, ymax = 5, fill = "red", alpha = 0.2)+
  annotate("rect", xmin = 0.5, xmax = 4.5, ymin = 5, ymax = 10, fill = "green", alpha = 0.2)+
  annotate("rect", xmin = 0.5, xmax = 4.5, ymin = 10, ymax = 14, fill = "yellow", alpha = 0.2)+
  annotate("rect", xmin = 0.5, xmax = 4.5, ymin = 14, ymax = 20, fill = "blue", alpha = 0.2) +
  geom_col()+
  scale_x_discrete()+
  geom_text(aes(label=background_area_name), hjust=2.5, vjust=0, angle=90, size=5, color="white") +
  theme_classic()
</code>```

Body:
I would like to create a bar plot with four bars – where a transparent background of 4 differently colored, horizontal areas represent whether the strength of the bars are considered "low", "medium", "high", or "very high".

# Load ggplot2
library(ggplot2)

# Example data
data <- data.frame(
  name=c("A","B","C", "D") ,
  value=c(3, 12, 16, 22)
)

# Background data
backgound_area_color <- c(5, 10, 14, 20)
background_area_name <- c("low", "medium", "high", "very high")
background_data <- as.data.frame(backgound_area_color, background_area_name)

# My attempt:
ggplot(data, aes(x=name, y=value)) +
  geom_bar(stat = "identity") +
  geom_rect(data = background_data,
            aes(y = backgound_area_color))

Thanks in advance

Body:
I like Allan Camerons approach best. Here is what I have tried to provide as an alternative using annotations:

library(ggplot2)

ggplot(data, aes(x=name, y=value))+
  annotate("rect", xmin = 0.5, xmax = 4.5, ymin = 0, ymax = 5, fill = "red", alpha = 0.2)+
  annotate("rect", xmin = 0.5, xmax = 4.5, ymin = 5, ymax = 10, fill = "green", alpha = 0.2)+
  annotate("rect", xmin = 0.5, xmax = 4.5, ymin = 10, ymax = 14, fill = "yellow", alpha = 0.2)+
  annotate("rect", xmin = 0.5, xmax = 4.5, ymin = 14, ymax = 20, fill = "blue", alpha = 0.2) +
  geom_col()+
  scale_x_discrete()+
  geom_text(aes(label=background_area_name), hjust=2.5, vjust=0, angle=90, size=5, color="white") +
  theme_classic()


问:
git-upload-pack '.': git-upload-pack: command not found fatal: Could not read from remote repository
I am trying to deploy an Angular PWA to gh pages and receive this error on deploy:
git-upload-pack '.': git-upload-pack: command not found
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

My scripts are:

```<code>"scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "watch": "ng build --watch --configuration development",
    "test": "ng test",
    "start-pwa": "ng build --prod && http-server -p 8080 -c-1 dist/billFold-client",
    "predeploy": "ng build --prod --base-href=/billFold-client/",
    "deploy": "npx gh-pages -d dist/billFold-client"
  },
  "private": true,
  "homepage": "https://gcy2312.github.io/billFold",
</code>```

Has anyone been able to fix this issue? I've tried changing my scripts, using angular-cli-ghpages instead.... always the same error....

答:
It seems angular deployments are tricky - sometimes they won't simply create the gh-pages and it doesn't exist: run these scripts instead:
install angular-cli-ghpages: npm install -g angular-cli-ghpages
create gh-pages branch: git branch gh-pages
set to new gh-pages branch: git checkout -b gh-pages
build app: ng build --prod --base-href https://githubUsername.github.io/repositoryName
deploy: ngh --dir=dist/projectName

Body:
I am trying to deploy an Angular PWA to gh pages and receive this error on deploy:
git-upload-pack '.': git-upload-pack: command not found
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

My scripts are:

"scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "watch": "ng build --watch --configuration development",
    "test": "ng test",
    "start-pwa": "ng build --prod && http-server -p 8080 -c-1 dist/billFold-client",
    "predeploy": "ng build --prod --base-href=/billFold-client/",
    "deploy": "npx gh-pages -d dist/billFold-client"
  },
  "private": true,
  "homepage": "https://gcy2312.github.io/billFold",

Has anyone been able to fix this issue? I've tried changing my scripts, using angular-cli-ghpages instead.... always the same error....


答:
i can suggest you to create a different SECERET_KEY dynamically for each user so if any user can find its own secret key it can access only within its own data and cant access unwanted data
you should learn more about Authentication and Authorisation
check passport.js</p>

Title: Post request secure, only my site can post to server

Body:
i want to make a Post Request to Node.js from React, but in the Developer Tool in Payload it shows me the Secret Key, and if it shows me there I haven't solved anything, is there a way for me to do this securely? and without SECRET KEY being visible in Developer Tool?

my react post request code

     .post("http://.../api/test", {
          secret: process.env.REACT_APP_SECRET_KEY,
          battleData: battleData,
          accountCurent: accountCurent,
        })
        .then(function (response) {}
....

and my Node.js code

app.post("/api/test", (req, res) => {
if(req.body.secret === process.env.REACT_APP_SECRET_KEY){}
...// I only want when Secret Key is identical by Node to the frontEnd and run my code in Node.js


问:
CSS wrap text exactly to width
I'm using white-space:nowrap; to keep my text in one line. But the text is long and goes beyond the element. How to wrap the text exactly to the width of an element?

To understand more clearly what I mean, see this JSfiddle.

Update: another JSfiddle to show more clearly what I need.

答:
Take off white-space: nowrap; and put on word-spacing: -1px;

I'm not sure how each browser is going to react, so you may need to adjust the word-spacing property.

Title: CSS wrap text exactly to width


问:
Spring boot unable to autowire class in tests after disable JPA
hope you all are doing well

I'm facing some problems on testing my Spring Boot application. I created a simple API (currently has only one method, and it's working) and I created the domain tests disabling JPA configurations. When I test with JPA disabled, the tests provide the following error:

```<code>org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.mhrehbein.curriculum.register.infrastructure.mysql.ISpringDataAboutMeRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
</code>```

When I enable JPA configuration it works fine, but I would like to disable once it is unit tests. You can check the code in the following PR: https://github.com/retatu/curriculum/pull/6/files (sorry for it)

In the code you can see that all tests are broke, the tests are basically the same and the example is here: https://github.com/retatu/curriculum/blob/dev/src/test/java/com/mhrehbein/curriculum/register/domain/entity/AboutMeTest.java

Appreciate any help

答:
In your code you declared an interface that extends PagingAndSortingRepository:

```<code>public interface ISpringDataAboutMeRepository extends PagingAndSortingRepository<AboutMe, UUID> {
}
</code>```

It means that spring boot must autoconfigure this repository bean for you, namely, it will be configured a proxy bean of SimpleJpaRepository.

But since you disabled DataSourceAutoConfiguration in application-test.properties, no DataSource bean is configured, therefore the automatic JpaRepositoriesAutoConfiguration is not activated and user-defined JPA-repositories, in your case ISpringDataAboutMeRepository, are not registered, which leads to the NoSuchBeanDefinitionException. More info  about it here.

Also, if you disable HibernateJpaAutoConfiguration, EntityManagerFactory bean isn't configured, which is necessary to create your ISpringDataAboutMeRepository bean.

As a result, if you want to run @SpringBootTest, you need to remove your spring.autoconfigure.exclude property from application-test.properties and configure a database for tests, e.g. in-memory H2-database:

Add to your build.gradle:

```<code>testImplementation group: 'com.h2database', name: 'h2', version: '1.4.200'
</code>```

Your application-test.properties:

```<code>spring.datasource.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1
spring.datasource.username=sa
spring.datasource.password=sa
</code>```

Otherwise, you can use @MockBean annotation on your test classes to mock your ISpringDataAboutMeRepository so:

```<code>@SpringBootTest
@ExtendWith(SpringExtension.class) // remove it since  @SpringBootTest already contains it
@TestPropertySource(locations = "classpath:application-test.properties")
@MockBean(ISpringDataAboutMeRepository.class)
public class AboutMeTest {
      ...
}
</code>```

Body:
hope you all are doing well

I'm facing some problems on testing my Spring Boot application. I created a simple API (currently has only one method, and it's working) and I created the domain tests disabling JPA configurations. When I test with JPA disabled, the tests provide the following error:

org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.mhrehbein.curriculum.register.infrastructure.mysql.ISpringDataAboutMeRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}

When I enable JPA configuration it works fine, but I would like to disable once it is unit tests. You can check the code in the following PR: https://github.com/retatu/curriculum/pull/6/files (sorry for it)

In the code you can see that all tests are broke, the tests are basically the same and the example is here: https://github.com/retatu/curriculum/blob/dev/src/test/java/com/mhrehbein/curriculum/register/domain/entity/AboutMeTest.java

Appreciate any help

Body:
In your code you declared an interface that extends PagingAndSortingRepository:

public interface ISpringDataAboutMeRepository extends PagingAndSortingRepository<AboutMe, UUID> {
}

It means that spring boot must autoconfigure this repository bean for you, namely, it will be configured a proxy bean of SimpleJpaRepository.

But since you disabled DataSourceAutoConfiguration in application-test.properties, no DataSource bean is configured, therefore the automatic JpaRepositoriesAutoConfiguration is not activated and user-defined JPA-repositories, in your case ISpringDataAboutMeRepository, are not registered, which leads to the NoSuchBeanDefinitionException. More info  about it here.

Also, if you disable HibernateJpaAutoConfiguration, EntityManagerFactory bean isn't configured, which is necessary to create your ISpringDataAboutMeRepository bean.

As a result, if you want to run @SpringBootTest, you need to remove your spring.autoconfigure.exclude property from application-test.properties and configure a database for tests, e.g. in-memory H2-database:

Add to your build.gradle:

testImplementation group: 'com.h2database', name: 'h2', version: '1.4.200'

Your application-test.properties:

spring.datasource.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1
spring.datasource.username=sa
spring.datasource.password=sa

Otherwise, you can use @MockBean annotation on your test classes to mock your ISpringDataAboutMeRepository so:

@SpringBootTest
@ExtendWith(SpringExtension.class) // remove it since  @SpringBootTest already contains it
@TestPropertySource(locations = "classpath:application-test.properties")
@MockBean(ISpringDataAboutMeRepository.class)
public class AboutMeTest {
      ...
}


问:
Highlight item in RecyclerView while Pressed
I can't seem to find a simpler way to only highlight a RecyclerView item when pressed but while this code I have come up with seems to work ok it will remove the highlight (ACTION_CANCEL occurs) if I move up/down (while pressed) but it stays highlighted if I move right or left while pressed (No ACTION_CANCEL event is called). Can anyone tell me why or if there is better way of doing this please?</p>
```<code>           itemView.setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View view, MotionEvent pEvent) {
                selected_position = getAdapterPosition();
                if(pEvent.getAction() == MotionEvent.ACTION_DOWN) {
                    parent.setBackgroundColor(Color.RED);
                    txtName.setTextColor(Color.GREEN);
                }
                else if(pEvent.getAction() == MotionEvent.ACTION_UP) {
                    parent.setBackgroundColor(Color.WHITE);
                    txtName.setTextColor(Color.BLACK);
                }
                else if(pEvent.getAction() == MotionEvent.ACTION_CANCEL) {
                    parent.setBackgroundColor(Color.WHITE);
                    txtName.setTextColor(Color.BLACK);
                }
                else if(pEvent.getAction() == MotionEvent.ACTION_MOVE) {
                    int x = (int)pEvent.getRawX();
                    int y = (int)pEvent.getRawY();
                    int[] coordinates = new int[2];
                    parent.getLocationInWindow(coordinates);
                    if(x < (coordinates[0]) || (x > (coordinates[0]) + parent.getWidth())) {
                        parent.setBackgroundColor(Color.WHITE);
                        txtName.setTextColor(Color.BLACK);
                    }
                    else if(y < (coordinates[1]) || (y > (coordinates[1]) + parent.getHeight())) {
                        parent.setBackgroundColor(Color.WHITE);
                        txtName.setTextColor(Color.BLACK);
                    }
                    else {
                        parent.setBackgroundColor(Color.RED);
                        txtName.setTextColor(Color.GREEN);
                    }
                }
                return false;
            }
        });
</code>```

答:
In the root layout of your recycler view item.xml, you can write android:foreground="?attr/selectableItemBackground". This will highlight recycler view item, when a click occurs.

For example, let`s say it is your recycler view item layout:

```<code> <androidx.constraintlayout.widget.ConstraintLayout

    android:id="@+id/item"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:foreground="?attr/selectableItemBackground">

     ...

</androidx.constraintlayout.widget.ConstraintLayout>`
</code>```

Body:
I can't seem to find a simpler way to only highlight a RecyclerView item when pressed but while this code I have come up with seems to work ok it will remove the highlight (ACTION_CANCEL occurs) if I move up/down (while pressed) but it stays highlighted if I move right or left while pressed (No ACTION_CANCEL event is called). Can anyone tell me why or if there is better way of doing this please?

           itemView.setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View view, MotionEvent pEvent) {
                selected_position = getAdapterPosition();
                if(pEvent.getAction() == MotionEvent.ACTION_DOWN) {
                    parent.setBackgroundColor(Color.RED);
                    txtName.setTextColor(Color.GREEN);
                }
                else if(pEvent.getAction() == MotionEvent.ACTION_UP) {
                    parent.setBackgroundColor(Color.WHITE);
                    txtName.setTextColor(Color.BLACK);
                }
                else if(pEvent.getAction() == MotionEvent.ACTION_CANCEL) {
                    parent.setBackgroundColor(Color.WHITE);
                    txtName.setTextColor(Color.BLACK);
                }
                else if(pEvent.getAction() == MotionEvent.ACTION_MOVE) {
                    int x = (int)pEvent.getRawX();
                    int y = (int)pEvent.getRawY();
                    int[] coordinates = new int[2];
                    parent.getLocationInWindow(coordinates);
                    if(x < (coordinates[0]) || (x > (coordinates[0]) + parent.getWidth())) {
                        parent.setBackgroundColor(Color.WHITE);
                        txtName.setTextColor(Color.BLACK);
                    }
                    else if(y < (coordinates[1]) || (y > (coordinates[1]) + parent.getHeight())) {
                        parent.setBackgroundColor(Color.WHITE);
                        txtName.setTextColor(Color.BLACK);
                    }
                    else {
                        parent.setBackgroundColor(Color.RED);
                        txtName.setTextColor(Color.GREEN);
                    }
                }
                return false;
            }
        });

Body:
In the root layout of your recycler view item.xml, you can write android:foreground="?attr/selectableItemBackground". This will highlight recycler view item, when a click occurs.

For example, let`s say it is your recycler view item layout:

 <androidx.constraintlayout.widget.ConstraintLayout

    android:id="@+id/item"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:foreground="?attr/selectableItemBackground">

     ...

</androidx.constraintlayout.widget.ConstraintLayout>`


问:
a href target blank sometimes stucks on about:blank
I am trying to open a google docs link in a new tab on browser like:

Google Sheet

But sometimes link does not open and stucks on about:blank page. But if I press refresh button, the link opens. What can be the problem and how can I fix it?

I tried on Chrome, Opera and Yandex browsers. All of them acts the same.

答:
Dont use the url=
Or download the file and put it in your folder. Then set the href to open or download your pdf. Would this be a sol?</p>


问:
localStorage not working properly/localStorage overwriting itself
I'm attempting to create a simple to-do list and I've encountered two problems:

After refreshing the page, all the created elements are no longer visible on the page despite being in local storage.

After refreshing the page and submitting new values to the input, localStorage overwrites itself.
Despite that, the items displayed from the input fields are from the previous localStorage, which no longer exists (I really hope this makes sense).

const inputEl = document.getElementById("inputEl")
const submitBtn = document.getElementById("submit")
const clearBtn = document.getElementById("clearBtn")
const todoListContainer = document.getElementById("todoList")
const taskContainer = document.querySelector(".task")
const cancelBtn = document.querySelector(".cancelBtn")
const doneBtn = document.querySelector(".doneBtn")
const errorMsg = document.querySelector(".error")

let localStorageContent = localStorage.getItem("tasks")
let tasksItem = JSON.parse(localStorageContent)
let tasks = []

function createTask() {
    if (inputEl.value.length != 0) {

        const newDiv = document.createElement("div")
        newDiv.classList.add("task")
        const newParagraph = document.createElement("p")
        const newCancelBtn = document.createElement("button")
        newCancelBtn.classList.add("cancelBtn")
        newCancelBtn.textContent = "X"
        const newDoneBtn = document.createElement("button")
        newDoneBtn.classList.add("doneBtn")
        newDoneBtn.textContent = "Done"

        todoListContainer.appendChild(newDiv)
        newDiv.appendChild(newParagraph)
        newDiv.appendChild(newCancelBtn)
        newDiv.appendChild(newDoneBtn)
        //^^ Creating a container for a new task, with all its elements and assigning the classes^^

        tasks.push(inputEl.value)
        inputEl.value = ""

        for (let i = 0; i < tasks.length; i++) {
            localStorage.setItem("tasks", JSON.stringify(tasks))
            newParagraph.textContent = JSON.parse(localStorageContent)[i]
        }

        errorMsg.textContent = ""

    } else {
        errorMsg.textContent = "You have to type something in!"
        errorMsg.classList.toggle("visibility")

    }

}

submitBtn.addEventListener("click", () => {
    createTask()
})

clearBtn.addEventListener("click", () => {
    localStorage.clear()
})
```
<p>HTML code below:</p>
<pre class="lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
   <head>
      <meta charset="UTF-8">
      <meta http-equiv="X-UA-Compatible" content="IE=edge">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <link rel="stylesheet" href="/style.css">
      <script src="/script.js" defer></script>
      <title>To-do list</title>
   </head>
   <body>
      <h2 class="error visibility"></h2>
      <div id="todoList">
         <h1>To-Do List</h1>
         <input type="text" name="" id="inputEl" placeholder="Add an item!">
         <button type="submitBtn" id="submit">Submit</button>
         <button id="clearBtn">Clear list</button>
         <div class="task">
         </div>
      </div>
   </body>
</html>
</code>```

答:
After refreshing the page, all the created elements are no longer visible on the page despite being in local storage

That is because you are rendering the HTML only after the click event and not on page load. To render the HTML for existing tasks stored in the localStorage you have to write a code that loops over your existing tasks in  the tasksItem and applies the rendering logic to it.

I would suggest splitting the rendering code from your createTask() function and create a new function for it (for example renderTask()), then you can use it inside a loop on page load and also call the function once a new task is created in the  createTask() function.

window.addEventListener('load', (event) => {
  // Your read, loop and render logic goes here
})
```
<blockquote>
<p>After refreshing the page and submitting new values to the input, localStorage overwrites itself.</p>
</blockquote>
<p>That's because you are actually overriding the tasks in the <code>localStorage</code>. To keep existing tasks, you have to use your <code>tasksItem</code> variable instead of the blank <code>tasks</code> array to create your tasks in and save them to the <code>localStorage</code>.</p>
<p>So, instead of:</p>
<pre class="lang-js prettyprint-override"><code>tasks.push(inputEl.value)
</code>```

You would use:

tasksItem.push(inputEl.value)
```
<p>The same goes for:</p>
<pre class="lang-js prettyprint-override"><code>for (let i = 0; i < tasksItem.length; i++) {
    localStorage.setItem("tasks", JSON.stringify(tasksItem))
    // …
}

</code>```

Body:
I'm attempting to create a simple to-do list and I've encountered two problems:

After refreshing the page, all the created elements are no longer visible on the page despite being in local storage.

After refreshing the page and submitting new values to the input, localStorage overwrites itself.
Despite that, the items displayed from the input fields are from the previous localStorage, which no longer exists (I really hope this makes sense).

const inputEl = document.getElementById("inputEl")
const submitBtn = document.getElementById("submit")
const clearBtn = document.getElementById("clearBtn")
const todoListContainer = document.getElementById("todoList")
const taskContainer = document.querySelector(".task")
const cancelBtn = document.querySelector(".cancelBtn")
const doneBtn = document.querySelector(".doneBtn")
const errorMsg = document.querySelector(".error")

let localStorageContent = localStorage.getItem("tasks")
let tasksItem = JSON.parse(localStorageContent)
let tasks = []

function createTask() {
    if (inputEl.value.length != 0) {

        const newDiv = document.createElement("div")
        newDiv.classList.add("task")
        const newParagraph = document.createElement("p")
        const newCancelBtn = document.createElement("button")
        newCancelBtn.classList.add("cancelBtn")
        newCancelBtn.textContent = "X"
        const newDoneBtn = document.createElement("button")
        newDoneBtn.classList.add("doneBtn")
        newDoneBtn.textContent = "Done"

        todoListContainer.appendChild(newDiv)
        newDiv.appendChild(newParagraph)
        newDiv.appendChild(newCancelBtn)
        newDiv.appendChild(newDoneBtn)
        //^^ Creating a container for a new task, with all its elements and assigning the classes^^

        tasks.push(inputEl.value)
        inputEl.value = ""

        for (let i = 0; i < tasks.length; i++) {
            localStorage.setItem("tasks", JSON.stringify(tasks))
            newParagraph.textContent = JSON.parse(localStorageContent)[i]
        }

        errorMsg.textContent = ""

    } else {
        errorMsg.textContent = "You have to type something in!"
        errorMsg.classList.toggle("visibility")

    }

}

submitBtn.addEventListener("click", () => {
    createTask()
})

clearBtn.addEventListener("click", () => {
    localStorage.clear()
})

HTML code below:

<!DOCTYPE html>

      <meta charset="UTF-8">
      <meta http-equiv="X-UA-Compatible" content="IE=edge">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <link rel="stylesheet" href="/style.css">

      <title>To-do list</title>

To-Do List

         <input type="text" name="" id="inputEl" placeholder="Add an item!">
         <button type="submitBtn" id="submit">Submit</button>
         <button id="clearBtn">Clear list</button>

Body:
After refreshing the page, all the created elements are no longer visible on the page despite being in local storage

That is because you are rendering the HTML only after the click event and not on page load. To render the HTML for existing tasks stored in the localStorage you have to write a code that loops over your existing tasks in  the tasksItem and applies the rendering logic to it.

I would suggest splitting the rendering code from your createTask() function and create a new function for it (for example renderTask()), then you can use it inside a loop on page load and also call the function once a new task is created in the  createTask() function.

window.addEventListener('load', (event) => {
  // Your read, loop and render logic goes here
})

After refreshing the page and submitting new values to the input, localStorage overwrites itself.

That's because you are actually overriding the tasks in the localStorage. To keep existing tasks, you have to use your tasksItem variable instead of the blank tasks array to create your tasks in and save them to the localStorage.

So, instead of:

tasks.push(inputEl.value)

You would use:

tasksItem.push(inputEl.value)

The same goes for:

for (let i = 0; i < tasksItem.length; i++) {
    localStorage.setItem("tasks", JSON.stringify(tasksItem))
    // …
}


问:
Python 3: How to get a random 4 digit number?
I need help to get a random 4 digit long number with no repeated digits inside the number so I have

```<code>import random
numbers = random.sample(range(10), 4)
</code>```

Would this be the best way to go at it?
I also need help with making sure the first digit is not 0, how could I do that? Cheers for the input

答:
you can use this code:

# make 4 random number

```<code>mylist = ['1','2','3','4','5','6','7','8','9']
x1 = int(random.choice(mylist))
x2 = int(random.choice(mylist))
x3 = int(random.choice(mylist))
x4 = int(random.choice(mylist))
x = x1 * 1000 + x2 * 100 + x3 * 10 + x4
print(x)
</code>```

you'll give a number like 1728 in format(xxxx)

just wait a moment and think.

Body:
I need help to get a random 4 digit long number with no repeated digits inside the number so I have

import random
numbers = random.sample(range(10), 4)

Would this be the best way to go at it?
I also need help with making sure the first digit is not 0, how could I do that? Cheers for the input

Body:
you can use this code:

# make 4 random number

mylist = ['1','2','3','4','5','6','7','8','9']
x1 = int(random.choice(mylist))
x2 = int(random.choice(mylist))
x3 = int(random.choice(mylist))
x4 = int(random.choice(mylist))
x = x1 * 1000 + x2 * 100 + x3 * 10 + x4
print(x)

you'll give a number like 1728 in format(xxxx)

just wait a moment and think.