问:
Is there a way to detect polygons with narrow angles for corners in python?
There is a database with the geometry column named, "Shape". The column contains all the geometry for some building footprints in an area with "polygon" being the polygon type. However, some of the building polygons were not digitized correctly, leaving some of the footprints with narrow angles( less than 40 degrees) for corners. The objective is to detect those building footprints through python code and fix them accordingly.

I have tried the following but with SQL:

```<code>SELECT *
From sde."building" AS g1
WHERE ST_Area(g1.shape) / ST_Area(ST_OrientedEnvelope(g1.shape)) < 0.42
</code>```

However, the above query only results in building footprints that are not rectangles without detecting the footprints with the narrow angles.

Body:
There is a database with the geometry column named, "Shape". The column contains all the geometry for some building footprints in an area with "polygon" being the polygon type. However, some of the building polygons were not digitized correctly, leaving some of the footprints with narrow angles( less than 40 degrees) for corners. The objective is to detect those building footprints through python code and fix them accordingly.

I have tried the following but with SQL:

SELECT *
From sde."building" AS g1
WHERE ST_Area(g1.shape) / ST_Area(ST_OrientedEnvelope(g1.shape)) < 0.42

However, the above query only results in building footprints that are not rectangles without detecting the footprints with the narrow angles.


来源: stackexchange

问:
Find used packages inside a folder in a React app
I am aware of the npm ls --depth=0 to find all installed packages but is there a way to find all used packages/imports for 3rd party libs inside a specific folder?

ContentLicense: CC BY-SA 4.0


问:
Why does regex require triple backslash to match a single backslash?
I was trying to match a backslash using regex and thought that this could be done by using two double backslashes, using the former to escape the latter. However, when I run the code

```<code>
path_str = r"\Animal_1-"
Match_backslash = re.search("[\\]", path_str)
print(Match_backslash)
</code>```

I get the error message:

```<code>error: unterminated character set at position 0
</code>```

But, when I use triple backslash:

```<code>
path_str = r"\Animal_1-"
Match_backslash = re.search("[\\\]", path_str)
print(Match_backslash)
</code>```

it for some reason works, can anyone explain why triple backslash is needed and why double backslash isn´t sufficient?

Body:
I was trying to match a backslash using regex and thought that this could be done by using two double backslashes, using the former to escape the latter. However, when I run the code

path_str = r"\Animal_1-"
Match_backslash = re.search("[\\]", path_str)
print(Match_backslash)

I get the error message:

error: unterminated character set at position 0

But, when I use triple backslash:

path_str = r"\Animal_1-"
Match_backslash = re.search("[\\\]", path_str)
print(Match_backslash)

it for some reason works, can anyone explain why triple backslash is needed and why double backslash isn´t sufficient?


问:
Can not infer schema for type when converting pandas dataframe to pyspark dataframe
I am trying to use pyspark.pandas to read excel and I need to convert the pandas dataframe to pyspark dataframe.

```<code>df = panndas .read_excel(filepath,sheet_name="A",  skiprows=12 ,usecols="B:AM",parse_dates=True)

pyspark_df= spark.createDataFrame(df)
</code>```

when I do this, I got error

```<code>TypeError: Can not infer schema for type:
</code>```

Even though I tried to specify the dtype for the read_excel and define the schema. I still have the error.

```<code>df = panndas .read_excel(filepath,sheet_name="A",  skiprows=12 ,usecols="B:AM",parse_dates=True,dtype= dtypetest)

pyspark_df= spark.createDataFrame(df,schema)
</code>```

Would you tell me how to solve it?

Body:
I am trying to use pyspark.pandas to read excel and I need to convert the pandas dataframe to pyspark dataframe.

df = panndas .read_excel(filepath,sheet_name="A",  skiprows=12 ,usecols="B:AM",parse_dates=True)

pyspark_df= spark.createDataFrame(df)

when I do this, I got error

TypeError: Can not infer schema for type:

Even though I tried to specify the dtype for the read_excel and define the schema. I still have the error.

df = panndas .read_excel(filepath,sheet_name="A",  skiprows=12 ,usecols="B:AM",parse_dates=True,dtype= dtypetest)

pyspark_df= spark.createDataFrame(df,schema)

Would you tell me how to solve it?


问:
Pyserial: Force open/close a serial port already opened by different program
Question:
Using pycharm, can I somehow close or open a serial port that is currently opened and used by some other software? It is acceptable if this other software crashes in the process.

Why I want to do this:
I am writing the control scripts for some mechanical hardware that is capable of breaking things (or people) if used wrongly. During the setup-phase this hardware will be adjusted via a terminal command software (for example "hterm"). If somebody messes up during this time I want an "emergency stop" script (probably bound to some key), which instantly takes over the serial port connected to the hardware and sends multiple "stop" commands.
I already have a hardware switch which kills the whole system, but I would like to have an emergency stop option on the controlling PC, also.

I already tried the naive approach, but expectedly ran into permission errors:

```<code>def winchEmergencyStop():
    ser = serial.Serial(baudrate=9600, timeout=1)
    ser.port = "COM66"

    try:
        ser.open()
        print("port opened, trying to send Stop signal")
    except serial.SerialException:
        ser.close()
        time.sleep(0.1)
        ser.open()
        print("port already opened, trying to send Stop signal")
    finally:
        time.sleep(0.1)
        ser.flushInput()
        ser.flushOutput()
        ser.write(b'ST\r')
        time.sleep(0.1)
        ser.write(b'ST\r')
        time.sleep(0.1)
        ser.write(b'ST\r')

</code>```

This gets me:

serial.serialutil.SerialException: could not open port 'COM66': PermissionError(13, 'Zugriff verweigert', None, 5)

(Zugriff verweigert -> Permission denied)

Thanks for the help

Body:
Question:
Using pycharm, can I somehow close or open a serial port that is currently opened and used by some other software? It is acceptable if this other software crashes in the process.

Why I want to do this:
I am writing the control scripts for some mechanical hardware that is capable of breaking things (or people) if used wrongly. During the setup-phase this hardware will be adjusted via a terminal command software (for example "hterm"). If somebody messes up during this time I want an "emergency stop" script (probably bound to some key), which instantly takes over the serial port connected to the hardware and sends multiple "stop" commands.
I already have a hardware switch which kills the whole system, but I would like to have an emergency stop option on the controlling PC, also.

I already tried the naive approach, but expectedly ran into permission errors:

def winchEmergencyStop():
    ser = serial.Serial(baudrate=9600, timeout=1)
    ser.port = "COM66"

    try:
        ser.open()
        print("port opened, trying to send Stop signal")
    except serial.SerialException:
        ser.close()
        time.sleep(0.1)
        ser.open()
        print("port already opened, trying to send Stop signal")
    finally:
        time.sleep(0.1)
        ser.flushInput()
        ser.flushOutput()
        ser.write(b'ST\r')
        time.sleep(0.1)
        ser.write(b'ST\r')
        time.sleep(0.1)
        ser.write(b'ST\r')

This gets me:

serial.serialutil.SerialException: could not open port 'COM66': PermissionError(13, 'Zugriff verweigert', None, 5)

(Zugriff verweigert -> Permission denied)

Thanks for the help


问:
Why parsing Invalid json returns Empty Object
I am trying to parse wrong json string to the data class. Ideally it should throw JsonSyntaxException but its

```<code> class MyStudent{
  int age;
  int marks;
  Student(int a, int m){
   age = a;
   marks = m;
  }
 }
</code>```

I am parsing "{name:test}" and this returns me Object of MyStudent with no data inside it.

```<code>Gson gson = new Gson();
    try {
        return gson.fromJson(json, MyStudent.class);
    } catch (JsonSyntaxException e) {
        return null;
    }
</code>```

Can someone please let me know isn't this expected?

Body:
I am trying to parse wrong json string to the data class. Ideally it should throw JsonSyntaxException but its

 class MyStudent{
  int age;
  int marks;
  Student(int a, int m){
   age = a;
   marks = m;
  }
 }

I am parsing "{name:test}" and this returns me Object of MyStudent with no data inside it.

Gson gson = new Gson();
    try {
        return gson.fromJson(json, MyStudent.class);
    } catch (JsonSyntaxException e) {
        return null;
    }

Can someone please let me know isn't this expected?


问:
Sharepoint List - Generate Unique # identifier in Column A based on Column B. Same # if duplicate
I am working on creating a tracker, my client has requested the data be on sharepoint list for ease of viewing.

In order to organize the tracker on the Sharepoint List, I would like to generate an autonumber (calculated column) in one column, I've given it the naming convention of Task ID.

For my logic - Task ID (Column A) will be based on another column, known as Title (Column B),

IF column B is not the same then Column A should generate a new number. IF Column B is duplicative then Column A should generate the same number.

I would like the Task ID (Column A) to generate something like this: "TSK-0001"

Is this possible to create for sharepoint list? Thanks again for any help. Let me know if there is still more questions to be answered before figuring out the calculated value.

Note: Column B is a single line of text

I have not tried anything to this point. I have seen that you can generate random numbers via the Left(Right(),X,X) function.

I would like the outcome to show this in Sharepoint List:
[1]: https://i.stack.imgur.com/quzGg.png


问:
How to gzip XML file?
I am working on integrating my application with the API of another application. Previously I have done such integrations using JSON and had no problem, unfortunately, the application I want to connect to uses XML which I have not interacted with before.
The task is to load an .xml file into a PHP script, then perform gzip on that XML, and then encode the byte array to base64.
I have the XML file ready, I can use base64_encode() too, but I sit on this gzip for several hours and nothing works. (I load the XML file into the script using simplexml_load_file)

I tried using gzencode, gzcompress but it doesn't work.
Authentication involves combining HTTP parameters and encoding them with urlencode(). The req_sig (signature) parameter contains the encoded parameters (mentioned above) + API code. If everything matches then a response is returned, if not then an error is displayed: ERROR4000Signature does not match, even though the signature matches, because it is generated the same way in other queries using GET.

My code:

```<code>$xml=simplexml_load_file("request.xml") or die("Failed to load");

$gzip = gzencode($xml);

$base64 = base64_encode($gzip);

$username = 'test-app-user';
$req_id = rand(10000000000, 99999999999);
$api_token = "za5rth23ku776fdvbn2";

$string_bazowy = "command=$base64"."req_id=$req_id"."username=$username";

$encoded = urlencode($string_bazowy);

$string_zmieniony = "$encoded"."$api_token";

$md5 = md5($string_zmieniony);

$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => "https://saldeo-test.brainshare.pl/api/xml/1.0/company/synchronize?command=$base64&req_id=$req_id&username=$username&req_sig=$md5",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => '',
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 0,
  CURLOPT_FOLLOWLOCATION => true,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => 'POST',
));

$response = curl_exec($curl);

curl_close($curl);
echo $response;
</code>```

Title: How to gzip XML file?

Body:
I am working on integrating my application with the API of another application. Previously I have done such integrations using JSON and had no problem, unfortunately, the application I want to connect to uses XML which I have not interacted with before.
The task is to load an .xml file into a PHP script, then perform gzip on that XML, and then encode the byte array to base64.
I have the XML file ready, I can use base64_encode() too, but I sit on this gzip for several hours and nothing works. (I load the XML file into the script using simplexml_load_file)

I tried using gzencode, gzcompress but it doesn't work.
Authentication involves combining HTTP parameters and encoding them with urlencode(). The req_sig (signature) parameter contains the encoded parameters (mentioned above) + API code. If everything matches then a response is returned, if not then an error is displayed: ERROR4000Signature does not match, even though the signature matches, because it is generated the same way in other queries using GET.

My code:

$xml=simplexml_load_file("request.xml") or die("Failed to load");

$gzip = gzencode($xml);

$base64 = base64_encode($gzip);

$username = 'test-app-user';
$req_id = rand(10000000000, 99999999999);
$api_token = "za5rth23ku776fdvbn2";

$string_bazowy = "command=$base64"."req_id=$req_id"."username=$username";

$encoded = urlencode($string_bazowy);

$string_zmieniony = "$encoded"."$api_token";

$md5 = md5($string_zmieniony);

$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => "https://saldeo-test.brainshare.pl/api/xml/1.0/company/synchronize?command=$base64&req_id=$req_id&username=$username&req_sig=$md5",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => '',
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 0,
  CURLOPT_FOLLOWLOCATION => true,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => 'POST',
));

$response = curl_exec($curl);

curl_close($curl);
echo $response;


问:
How to use double Selectors with priorities in provider package?
I have this widget that listens to a provider. It won't change until the p1.boolanalyt1 increment. It now works fine. My problem is that the data changes also but I want to do p1.boolanalyt1 as the first priority, then we can change data like if the data changed but the p1.boolanalyt1 didn't increment we don't have to rebuild my question is how to do that (i did try to make two selectors one inside one but it didn't work).

```<code>Selector<DataProvider, int>(
        selector: (p0, p1) => p1.boolanalyt1,
        builder: (context, value, child) => ItemFilter(
            key: UniqueKey(),
            data: data
                .where((student) => seen.add(student.analytNiv1))
                .toList()
                .map((e) => Checkbox_Item(item: e.analytNiv1 ?? "VIDE"))
                .toList(),
            title: "analyt_niv1",
        ),
),
</code>```

I tried to use Selector under a Selector but it didn't work

Body:
I have this widget that listens to a provider. It won't change until the p1.boolanalyt1 increment. It now works fine. My problem is that the data changes also but I want to do p1.boolanalyt1 as the first priority, then we can change data like if the data changed but the p1.boolanalyt1 didn't increment we don't have to rebuild my question is how to do that (i did try to make two selectors one inside one but it didn't work).

Selector<DataProvider, int>(
        selector: (p0, p1) => p1.boolanalyt1,
        builder: (context, value, child) => ItemFilter(
            key: UniqueKey(),
            data: data
                .where((student) => seen.add(student.analytNiv1))
                .toList()
                .map((e) => Checkbox_Item(item: e.analytNiv1 ?? "VIDE"))
                .toList(),
            title: "analyt_niv1",
        ),
),

I tried to use Selector under a Selector but it didn't work


问:
How to add .xml file (present in package) to the jar using maven shade plugin
I'm trying to add a .XML file to the jar, My .XML file is present in src/main/java/ I'm using the maven shade plugin for generating a jar but it's not including .XML file present in the package.

OR you can suggest any other way.


问:
div tag and nav tag uses in htlm
How come we use nav tag to create a region in our html body that is specific for links/hypertext only, why don't we use div tag for the same?

Just curious to know, didn't find any difference yet.
Might be because I'm a beginner in the field.

Title: div tag and nav tag uses in htlm


问:
Is there any way to shorten if statement with bitwise or?
Is there a way to shorten the if statement with the bitwise or and strcmp?

```<code>if
(strcmp(level, array[1])==0||
strcmp(level, array [2])==0||
strcmp(level, array [3])==0)
{
/*Code*/
}
</code>```

The goal is to shorten the code of if statement

Body:
Is there a way to shorten the if statement with the bitwise or and strcmp?

if
(strcmp(level, array[1])==0||
strcmp(level, array [2])==0||
strcmp(level, array [3])==0)
{
/*Code*/
}

The goal is to shorten the code of if statement


问:
Need help in GMS2 pls, trigger works again and save menu opens again, even though it should just close
I've run into this problem.

I have a save menu with two options: "Save" and "Return", which is selected by the option heart. When selecting the "Return" option, the option arrow going back to "Save" even though it should close the save menu(It seems that when menu is closing, the trigger works again and menu opens again, even though it should just close).

The second problem is that when you select the "Save" option, the "File saved" window appears, after which it does not disappear when im pressing "Z" key, and I do not understand what is the reason for these two errors, no matter how I tried to fix them.

It seems that I write the code correctly, but nevertheless it does not work.

Key Press "Z" Event:

```<code>if image_index = 0

{

instance_change(obj_saveconfirm, true);

audio_play_sound(snd_save, 10, false);

 }

else {

if image_index = 1

 {

instance_destroy();

 }

 }
</code>```

Code that opens the save menu:

```<code>if place_meeting(x, y, obj_player) && keyboard_check_pressed(ord("Z")) && !instance_exists(obj_savemenu) && !instance_exists(obj_saveconfirm)

{

instance_create_depth(x, y, -9999, obj\_savemenu);
}
</code>```

It seems that I write the code correctly, but nevertheless it does not work.
I also used "keyboard_check_released" in code that opens the save menu, and menu is closing, but after half a second it opens again.

Body:
I've run into this problem.

I have a save menu with two options: "Save" and "Return", which is selected by the option heart. When selecting the "Return" option, the option arrow going back to "Save" even though it should close the save menu(It seems that when menu is closing, the trigger works again and menu opens again, even though it should just close).

The second problem is that when you select the "Save" option, the "File saved" window appears, after which it does not disappear when im pressing "Z" key, and I do not understand what is the reason for these two errors, no matter how I tried to fix them.

It seems that I write the code correctly, but nevertheless it does not work.

Key Press "Z" Event:

if image_index = 0

{

instance_change(obj_saveconfirm, true);

audio_play_sound(snd_save, 10, false);

 }

else {

if image_index = 1

 {

instance_destroy();

 }

 }

Code that opens the save menu:

if place_meeting(x, y, obj_player) && keyboard_check_pressed(ord("Z")) && !instance_exists(obj_savemenu) && !instance_exists(obj_saveconfirm)

{

instance_create_depth(x, y, -9999, obj\_savemenu);
}

It seems that I write the code correctly, but nevertheless it does not work.
I also used "keyboard_check_released" in code that opens the save menu, and menu is closing, but after half a second it opens again.


问:
blogdown site formatting issue with blogdown::build_site()
I already have a site created with blogdown and want to make it live. To try it out, I built the site using blogdown::build_site() . After managing to upload all the content from the public folder on Github. I see that the formatting of my site does not match what I have on the localhost when I run blogdown::serve_site(). The site I created is slightly complex since there are many subfolders created under each topic. I used the Hugo Book theme from this github page. The format of the site is the same as shown on the theme's github page.

I also checked the index.html file from the public folder and it looks like the image above. I am not sure how can I make my site to look like the second picture. I would appreciate any help and thank you in advance.


问:
Jenkins call script after build success
I want to Jenkins call a shell script from another docker container.

I don't know Jenkins can do this, and what is the best way to make it.

In one machine, I have this containers:

Service
IP (Docker network)
Note

ERP system
172.74.42.2
Odoo 14 ERP system what work with many plugin.
 If a plugin got new functions or fixes some bugs,
 need to restart the system after the pull, then update the plugin.
(I write a shell script what run in ssh after push commits.

Jenkins
172.74.42.3
In here I want to call the shell script after the build is success

The Jenkins is work. So the connect between the github and jenkins is good.

I try to write shell commands in Jenkins file. But I think this is a dumb way...

Title: Jenkins call script after build success


问:
Spark SQL subpath get data from hierarchical tree-like structure
I'm trying to get data stored in a hierarchical tree-like structure from my DB. I use postgres to do it and I know they have inbuilt function to do that(subpath). But now I'm trying to use spark where I have loaded my table and want to run a query to get data from this hierarchical structure. I don't want to use the DataFrame methods but just a spark sql query.
In postgres I did something like

```<code>SELECT subpath(path,0,2) FROM test WHERE path <@ 'Top.Science.Astronomy';
</code>```

When I use same query in spark in spark like:

```<code>spark.sql("""
 SELECT subpath(path,0,2) FROM test WHERE path <@ 'Top.Science.Astronomy'
""")
</code>```

I get this error:

```<code>Undefined function: subpath. This function is neither a built-in/temporary
function, nor a persistent function that is qualified as spark_catalog.default.subpath.;
</code>```

How do I convert query so that I can use it on spark/pyspark ?

Body:
I'm trying to get data stored in a hierarchical tree-like structure from my DB. I use postgres to do it and I know they have inbuilt function to do that(subpath). But now I'm trying to use spark where I have loaded my table and want to run a query to get data from this hierarchical structure. I don't want to use the DataFrame methods but just a spark sql query.
In postgres I did something like

SELECT subpath(path,0,2) FROM test WHERE path <@ 'Top.Science.Astronomy';

When I use same query in spark in spark like:

spark.sql("""
 SELECT subpath(path,0,2) FROM test WHERE path <@ 'Top.Science.Astronomy'
""")

I get this error:

Undefined function: subpath. This function is neither a built-in/temporary
function, nor a persistent function that is qualified as spark_catalog.default.subpath.;

How do I convert query so that I can use it on spark/pyspark ?


问:
Automatically login into a site without using selenium
I have searched in different forums, blogs, documents but I cannot find a way out.
My goal is to open up a browser window to access obv a site, this site tho needs a login in order to be accessed. Is it possible to login with email and pass before the actual new browser window is opened, so that the new new browser window opens the site where I just logged in? (i hope I was clear).

I have experienced Selenium and Python in the past and I am not that keen on using it again.

Does someone have any suggestion or can reveal a different technique? (I was thinking about cookies but I don't think it's possibile)


问:
Require a users email ends in .edu
After much trial and error, I was finally able to complete a job portal using Maven project on Eclipse and have integrated MySQL. I am stuck on one more issue that I would appreciate any guidance on (this is my first time working on a project like this).

There are two views, a student view and a recruiter view. Once the user signs up and logs in, they will see their respected view. The part where I am now stuck on is I am not sure how to add a constraint so that when a user signs up, they must enter an email ending in .edu. I know this will probably utilize the String.endsWith() method, but I am unsure of where to place it.

Here is my RegisterServlet.java file:

package com.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.DB.DBConnect;
import com.dao.UserDAO;
import com.entity.User;

@WebServlet("/add_user")
public class RegisterServlet extends HttpServlet{

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            String name = req.getParameter("name");
            String qua = req.getParameter("qua");
            String email = req.getParameter("email");
            String ps = req.getParameter("ps");

            UserDAO dao = new UserDAO(DBConnect.getConn());

            User u = new User(name, email, ps, qua, "User");
            boolean f = dao.addUser(u);
            HttpSession session = req.getSession();

            if(f) {
                session.setAttribute("succMsg", "Registeration Complete!");
                resp.sendRedirect("signup.jsp");
            } else {
                session.setAttribute("succMsg", "Registeration Not Complete");
                resp.sendRedirect("signup.jsp");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
```
<p>and here is my signup.jsp file:</p>
<pre class="lang-html prettyprint-override"><code><%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
        <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page isELIgnored="false" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<%@include file="all_component/all_css.jsp"%>
</head>
<body style="background-color: #f7f7f7;">
<%@include file="all_component/navbar.jsp"%>
<div class="container-fluid">
<div class="row p-4">
<div class="col-md-4 offset-md-4">
<div class="card">
<div class="card-body">
<div class="text-center">
<i class="fa fa-user-plus fa-2x" aria-hidden="true"></i>
<h5>Register Now</h5>
</div>

<c:if test="${not empty succMsg }">
<h4 class="text-center text-success">${succMsg }</h4>
<c:remove var="succMsg" />
</c:if>

<form action="add_user" method="post">
<div class="form-group">
<label>Enter Full Name</label> <input type="text" required="required" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" name="name">
</div>

<div class="form-group">
<label>Student or Recruiter?</label> <input type="text" required="required" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" name="qua">
</div>

<div class="form-group">
<label>Enter Email</label> <input type="text" required="required" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" name="email">
</div>

<div class="form-group">
<label for="exampleInputPassword1">Enter Password</label> <input type="password" required="required" class="form-control" id="exampleInputPassword1" name="ps">
</div>

<button type="submit" class="btn btn-primary badge-pill btn-block">Register</button>
</form>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
</code>```

And this is my UserDAO.java code:

package com.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import com.entity.User;

public class UserDAO {

    private Connection conn;

    public UserDAO(Connection conn) {
        super();
        this.conn = conn;
    }

    public boolean addUser(User u) {
        boolean f = false;

        try {
            String sql = "insert into user(name, qualification, email, password, role) values(?,?,?,?,?)";
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setString(1, u.getName());
            ps.setString(2, u.getQualification());
            ps.setString(3, u.getEmail());
            ps.setString(4, u.getPassword());
            ps.setString(5, "user");

            int i = ps.executeUpdate();
            if(i == 1) {
                f = true;
            }

        } catch (Exception  e) {
            e.printStackTrace();
        }
        return f;
    }

    public User login(String em, String psw) {
        User u = null;
        try {
            String sql = "select * from user where email=? and password=?";
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setString(1, em);
            ps.setString(2, psw);

            ResultSet rs = ps.executeQuery();
            while(rs.next()) {
                u = new User();
                u.setId(rs.getInt(1));
                u.setName(rs.getString(2));
                u.setQualification(rs.getString(3));
                u.setEmail(rs.getString(4));
                u.setPassword(rs.getString(5));
                u.setRole(rs.getString(6));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return u;
    }
}
```
<p>I believe in RegisterServlet, I can do something like:</p>
<pre class="lang-java prettyprint-override"><code>if(f && email.endsWith(".edu") {
    session.setAttribute("succMsg", "Registeration Complete!");
    resp.sendRedirect("signup.jsp");
} else {
    session.setAttribute("succMsg", "Registeration Not Complete");
    resp.sendRedirect("signup.jsp");
}
</code>```

But although I get a "registration not complete" alert, the user still goes into the database.

Title: Require a users email ends in .edu

Body:
After much trial and error, I was finally able to complete a job portal using Maven project on Eclipse and have integrated MySQL. I am stuck on one more issue that I would appreciate any guidance on (this is my first time working on a project like this).

There are two views, a student view and a recruiter view. Once the user signs up and logs in, they will see their respected view. The part where I am now stuck on is I am not sure how to add a constraint so that when a user signs up, they must enter an email ending in .edu. I know this will probably utilize the String.endsWith() method, but I am unsure of where to place it.

Here is my RegisterServlet.java file:

package com.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.DB.DBConnect;
import com.dao.UserDAO;
import com.entity.User;

@WebServlet("/add_user")
public class RegisterServlet extends HttpServlet{

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            String name = req.getParameter("name");
            String qua = req.getParameter("qua");
            String email = req.getParameter("email");
            String ps = req.getParameter("ps");

            UserDAO dao = new UserDAO(DBConnect.getConn());

            User u = new User(name, email, ps, qua, "User");
            boolean f = dao.addUser(u);
            HttpSession session = req.getSession();

            if(f) {
                session.setAttribute("succMsg", "Registeration Complete!");
                resp.sendRedirect("signup.jsp");
            } else {
                session.setAttribute("succMsg", "Registeration Not Complete");
                resp.sendRedirect("signup.jsp");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

and here is my signup.jsp file:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
        <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page isELIgnored="false" %>
<!DOCTYPE html>

<meta charset="UTF-8">
<title>Insert title here</title>
<%@include file="all_component/all_css.jsp"%>

<%@include file="all_component/navbar.jsp"%>

Register Now

<c:if test="${not empty succMsg }">

${succMsg }

<c:remove var="succMsg" />
</c:if>

<form action="add_user" method="post">

Enter Full Name <input type="text" required="required" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" name="name">

Student or Recruiter? <input type="text" required="required" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" name="qua">

Enter Email <input type="text" required="required" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" name="email">

Enter Password <input type="password" required="required" class="form-control" id="exampleInputPassword1" name="ps">

<button type="submit" class="btn btn-primary badge-pill btn-block">Register</button>
</form>

And this is my UserDAO.java code:

package com.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import com.entity.User;

public class UserDAO {

    private Connection conn;

    public UserDAO(Connection conn) {
        super();
        this.conn = conn;
    }

    public boolean addUser(User u) {
        boolean f = false;

        try {
            String sql = "insert into user(name, qualification, email, password, role) values(?,?,?,?,?)";
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setString(1, u.getName());
            ps.setString(2, u.getQualification());
            ps.setString(3, u.getEmail());
            ps.setString(4, u.getPassword());
            ps.setString(5, "user");

            int i = ps.executeUpdate();
            if(i == 1) {
                f = true;
            }

        } catch (Exception  e) {
            e.printStackTrace();
        }
        return f;
    }

    public User login(String em, String psw) {
        User u = null;
        try {
            String sql = "select * from user where email=? and password=?";
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setString(1, em);
            ps.setString(2, psw);

            ResultSet rs = ps.executeQuery();
            while(rs.next()) {
                u = new User();
                u.setId(rs.getInt(1));
                u.setName(rs.getString(2));
                u.setQualification(rs.getString(3));
                u.setEmail(rs.getString(4));
                u.setPassword(rs.getString(5));
                u.setRole(rs.getString(6));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return u;
    }
}

I believe in RegisterServlet, I can do something like:

if(f && email.endsWith(".edu") {
    session.setAttribute("succMsg", "Registeration Complete!");
    resp.sendRedirect("signup.jsp");
} else {
    session.setAttribute("succMsg", "Registeration Not Complete");
    resp.sendRedirect("signup.jsp");
}

But although I get a "registration not complete" alert, the user still goes into the database.


问:
Unable to connect a node with Selenium Hub on ubuntu
I am using Ubuntu Remote machines to start Hub and nodes for Selenium Grid. The hub is running on an IP with default 4444. Now i am trying to register a node on it using following command in ubuntu terminal:

java -jar selenium-server-standalone-3.141.59.jar -role node -hub http://IP of HUB:4444/grid/register -browser browserName=”chrome”,version=ANY,platform=LINUX,maxInstances=200 -Dwebdriver.chrome.driver="path/to/the/chromedriver/chromedriver.exe"

When executing this command in Ubuntu terminal, getting error:
Exception in thread "main" com.beust.jcommander.ParameterException: was passed main parameter '-Dwebdriver.chrome.driver=path/to/the/chromedriver/chromedriver.exe' but no main parameter was defined in your arg class.

Can someone please point out what is wrong with this command in ubuntu?


问:
Level 1 authentication
Good day, Please help me find the error in my code for level one authentication I could create a database, register users and store in their inputs using body parser, but I couldn't login already registered users. the login page keeps loading till it tells me a connection error, please help me out</p>
```<code>const express = require("express");
const bodyParser = require("body-parser");
const ejs = require("ejs");
const mongoose = require("mongoose");

const app = express();

app.use(express.static("public"));
app.set('view-engine', 'ejs');
app.use(bodyParser.urlencoded({
  extended: true
}));

mongoose.connect("mongodb://localhost:27017/User", {useNewUrlParser: true});

const userSchema = ({
    email: String,
    password: String
  });

const User = new mongoose.model("User", userSchema);
const users = []
app.get("/", function(req, res){
  res.render("first.ejs");
});

app.get("/login", function(req, res){
  res.render("login.ejs");
});

app.get("/register", function(req, res){
  res.render("register.ejs");
});

app.post("/register", function(req, res){
  const newUser =  new User({
    email: req.body.username,
    password: req.body.password
  });
  newUser.save(function(err){
    if (err) {
      console.log(err);
    } else {
      res.render("home.ejs");
    }
  });
});

app.post("/login", function(req, res){
    const username = req.body.username;
    const password = req.body.password;

    User.findOne({email: username}, function(err, foundUser){
      if (err) {
        console.log(err);
      } else {
        if (foundUser) {
          if (foundUser.password === password) {
            res.send("hi");
        }
      }
    }
  });
});

app.listen(3000, function() {
  console.log("Server started on port 3000.");
});
</code>```

Title: Level 1 authentication

Body:
Good day, Please help me find the error in my code for level one authentication I could create a database, register users and store in their inputs using body parser, but I couldn't login already registered users. the login page keeps loading till it tells me a connection error, please help me out

const express = require("express");
const bodyParser = require("body-parser");
const ejs = require("ejs");
const mongoose = require("mongoose");

const app = express();

app.use(express.static("public"));
app.set('view-engine', 'ejs');
app.use(bodyParser.urlencoded({
  extended: true
}));

mongoose.connect("mongodb://localhost:27017/User", {useNewUrlParser: true});

const userSchema = ({
    email: String,
    password: String
  });

const User = new mongoose.model("User", userSchema);
const users = []
app.get("/", function(req, res){
  res.render("first.ejs");
});

app.get("/login", function(req, res){
  res.render("login.ejs");
});

app.get("/register", function(req, res){
  res.render("register.ejs");
});

app.post("/register", function(req, res){
  const newUser =  new User({
    email: req.body.username,
    password: req.body.password
  });
  newUser.save(function(err){
    if (err) {
      console.log(err);
    } else {
      res.render("home.ejs");
    }
  });
});

app.post("/login", function(req, res){
    const username = req.body.username;
    const password = req.body.password;

    User.findOne({email: username}, function(err, foundUser){
      if (err) {
        console.log(err);
      } else {
        if (foundUser) {
          if (foundUser.password === password) {
            res.send("hi");
        }
      }
    }
  });
});

app.listen(3000, function() {
  console.log("Server started on port 3000.");
});


问:
Wrong access path (favicon.ico/index.tsx) in a next.js app
I use the next-auth-example to study using next.js. Node.js v16.18.1 on debian 11. The app produces an error of accessing a strange path.
Error: ENOTDIR: not a directory, access '~/next-auth-example/pages/favicon.ico/index.tsx'.

I have searched all possible sources (files) of generating such a path but couldn't find it.
What can be the source of such wrong path?


问:
GRPC asynchronous requests and parallel server handling
I have followed the C++ GRPC asynchronous documentation and from stackoverflow I found out that actually the client that is doing 'true' async requests is client2 here.

I have that now all working nicely, however the server code is not handling the incoming requests in parallel.

What's happening is all the requests from the client are going out, but then the responses are coming back one after the other. I know this because I have modified the server code to sleep for 5 seconds during each processing of a request like so:

                new CallData(service_, cq_);
                //now process the request
                std::cout << " processing " << request_.name() << std::endl;
                sleep(5);
                std::string prefix("Hello ");
                reply_.set_message(prefix + request_.name() + "!");
                //inform that we are finished
                this->status_ = this->FINISH;
                responder_.Finish(reply_, Status::OK, this);
```

My expectation is that I (as the user) start the client, it fires off all 100 requests and then I wait ~5 seconds in total and all the responses come back. What's actually happening is I have to wait 5 seconds per request and they are processed one after the other.

The documentation I am finding quite thin on the ground with regards to handling async requests and I hoped someone might help me understand how to update the server side to process the requests in parallel.

Thank you

Body:
I have followed the C++ GRPC asynchronous documentation and from stackoverflow I found out that actually the client that is doing 'true' async requests is client2 here.

I have that now all working nicely, however the server code is not handling the incoming requests in parallel.

What's happening is all the requests from the client are going out, but then the responses are coming back one after the other. I know this because I have modified the server code to sleep for 5 seconds during each processing of a request like so:

                new CallData(service_, cq_);
                //now process the request
                std::cout << " processing " << request_.name() << std::endl;
                sleep(5);
                std::string prefix("Hello ");
                reply_.set_message(prefix + request_.name() + "!");
                //inform that we are finished
                this->status_ = this->FINISH;
                responder_.Finish(reply_, Status::OK, this);

My expectation is that I (as the user) start the client, it fires off all 100 requests and then I wait ~5 seconds in total and all the responses come back. What's actually happening is I have to wait 5 seconds per request and they are processed one after the other.

The documentation I am finding quite thin on the ground with regards to handling async requests and I hoped someone might help me understand how to update the server side to process the requests in parallel.

Thank you


问:
Can't install or update any nuget packages in my project in vs2017
When I used vs2015, packages were added to a packages folder in my solution and a package.config file was added and also reference includes in the csproj file. But since I use vs2017 I'm not able to install or update any nuget packages, although the packages are downloaded and unzipped in this location:

C:\Users\user.nuget\packages:

packages

I tried both Manage Nuget Packages and Package Manager Console, but I get the errors "Install failed. Rolling back." and "Could not add reference, dll not registered." I tried installing webview2, newtonsoft json and restsharp but get the same errors.
Here's the output:

output packetmanager

So how can I download and unzip a package into a package folder in my solution and install it in my project ?


问:
Python PyQt6 (6.4.0) QML Difficulty in Applying Style to Qt.QWidgets
I am in the research/education phase now, and am not seeing a lot of info on the web about applying a Qml-based style to QWidgets.  This implies it's difficult or not possible.  I doubt it's impossible, but I am curious what the options are for doing that?

Ideally, what I want to do is use the system (user-chosen) theme in my application.  I'm on Linux, and it uses GTK and GNOME for themes.  I want to support Linux in general (maybe one day, other platforms), so would like to make the app theme cross-distro.

I don't know if this is a tall order.  But, is it extremely involved to make PyQt6 QWidgets styled from a QML style?  Can widgets use the system theme?


问:
How do I remove myself as MR participant in Gitlab? (NOT notifications toggle)
My project frequently demotes MRs back to Draft when the dev needs to do substantial work before further review. I get removed as a reviewer but not as a participant and so I still get notifications/emails for every little thing that happens to the MR. But if I shut off notifications then I won't get notified when the MR is ready for me to review it again. How do I remove myself as a participant?
I don't want to shut off notifications forever for the MR, I just want to NOT be on the participant list until I'm manually added back to it.</p>


问:
How to use oneof in gRPC when chunking data
I am able to chunk data from client to server however before sending chunks of the data I'd like to send the hash of the complete dataset so when the server reconstructs the chunks it can verify whether the reconstructed data is correct or not.

I've seen users use oneof in messages however I've no idea how to use it. The idea is to use:

```<code>message Data {
   oneof data_fields {
         int32 hash = 1;
         bytes chunk = 2;
   }
}
</code>```

The idea is to send the hash first and the proceeding bytes. Any examples or resources would be great.

Body:
I am able to chunk data from client to server however before sending chunks of the data I'd like to send the hash of the complete dataset so when the server reconstructs the chunks it can verify whether the reconstructed data is correct or not.

I've seen users use oneof in messages however I've no idea how to use it. The idea is to use:

message Data {
   oneof data_fields {
         int32 hash = 1;
         bytes chunk = 2;
   }
}

The idea is to send the hash first and the proceeding bytes. Any examples or resources would be great.


问:
Unable to move annotation with PDFKit
By following this reference - https://developer.apple.com/documentation/pdfkit/pdfannotation/2869800-isreadonly

I am able to edit text of the annotation but i am unable to move the annotation over the pdf page.

Is there any other property by using which I will be able to move the annotations?

I added text annotation with following code:

```<code>func addText(x: Int, y: Int, width: Int, height: Int, text: String, fontSize: CGFloat, centerText: Bool){
        guard let document = pdfView.document else { return }
        let lastPage = document.page(at: document.pageCount - 1)
        let annotation = PDFAnnotation(bounds: CGRect(x: x , y: y, width: width, height: height), forType: .widget, withProperties: nil)
        annotation.widgetFieldType = .text
        annotation.widgetStringValue = text
        if (centerText){ annotation.alignment = .center }
        annotation.font = UIFont(name: "calibri", size: fontSize)
        annotation.fontColor = .black
        annotation.color = .clear
        annotation.backgroundColor = .clear
        annotation.isReadOnly = false
        lastPage?.addAnnotation(annotation)
    }
</code>```

Title: Unable to move annotation with PDFKit

Body:
By following this reference - https://developer.apple.com/documentation/pdfkit/pdfannotation/2869800-isreadonly

I am able to edit text of the annotation but i am unable to move the annotation over the pdf page.

Is there any other property by using which I will be able to move the annotations?

I added text annotation with following code:

func addText(x: Int, y: Int, width: Int, height: Int, text: String, fontSize: CGFloat, centerText: Bool){
        guard let document = pdfView.document else { return }
        let lastPage = document.page(at: document.pageCount - 1)
        let annotation = PDFAnnotation(bounds: CGRect(x: x , y: y, width: width, height: height), forType: .widget, withProperties: nil)
        annotation.widgetFieldType = .text
        annotation.widgetStringValue = text
        if (centerText){ annotation.alignment = .center }
        annotation.font = UIFont(name: "calibri", size: fontSize)
        annotation.fontColor = .black
        annotation.color = .clear
        annotation.backgroundColor = .clear
        annotation.isReadOnly = false
        lastPage?.addAnnotation(annotation)
    }


问:
Generating a vornoied mesh using cgal
Using CGAL, I would like to do the steps down, but don't know what functionalities CGAL have to support generating the following mesh.
I would like to know the steps required also.

Title: Generating a vornoied mesh using cgal


问:
What causes my conda environment to prefer .local packages *before* the conda packages, causing errors?
I'm trying to run automatic machine learning model benchmarking code from the pycaret python package, which in its turn uses scikit-learn, among others.

However, my conda environment seems to run the scikit-learn dependency installed in the .local folder in my own home directory, rather than from my conda environment's packages.

That is not what I expected and it leads to the called pycaret code crashing because the interface of the loaded scikit-learn' is not the interface it expected.

I've found a way to change that behavior by editing sys.path (see below), but I don't understand why my conda environment apparently prefers .local folder's packages first, instead of the installed conda environment packages.

I have checked the sys.path of a conda environment created at a different organization and there the order is not like the above, so it clearly prefers the conda environment packages first.

This weird behavior clearly causes runtime errors and I don't want to edit sys.path in every Jupyter notebook that I start here at this organization. Can someone tell me which configuration sets this behavior, so I understand and can avoid having to indeed edit sys.path everytime?

A minimal code example of what I'm running is:

```<code>import pandas as pd
from pycaret.regression import *

df_basetable = pd.read_csv('df_basetable.csv')
random_seed = 14
regr_exp1 = setup(
    data=df_basetable[df_basetable["split_level1"]=="full train"],
    target="my_prediction_target",
    ignore_features=["customer_id"],
    numeric_features=[col for col in df_basetable.columns if col not in ["my_prediction_target", "customer_id"],
    test_data=df_basetable[df_basetable["split_level1"]=="validation"],
    fold_strategy = 'kfold',
    fold=5,
    fold_shuffle=True,
    n_jobs=5,
    session_id=random_seed, # for reproducibility
)
</code>```

That results in the following error:

```<code>File ~/.local/lib/python3.9/site-packages/sklearn/base.py:211, in BaseEstimator.get_params(self, deep)
    209 out = dict()
    210 for key in self._get_param_names():
--> 211     value = getattr(self, key)
    212     if deep and hasattr(value, "get_params") and not isinstance(value, type):
    213         deep_items = value.get_params().items()

AttributeError: 'Simple_Imputer' object has no attribute 'fill_value_categorical'
</code>```

What strikes me is that the interpreter is crashing on File ~/.local/lib/python3.9/site-packages/sklearn/base.py:211: I expected to see the path listed here of the sklearn package installed on the conda environment that I'm using.

I am running the above python code within a Jupyter Lab notebook with the conda environment activated that I want to use (it's called model_dashboard).
Proof of that is:

```<code>import sys
print(sys.executable)
</code>```

That prints '/applis/xyz/.envs/model_dashboard/bin/python'.

The python paths involved however, are the following:

```<code>import sys
sys.path
</code>```

===>

```<code>['/applis/abc/notebooks',
 '/applis/xyz/.envs/model_dashboard/lib/python39.zip',
 '/applis/xyz/.envs/model_dashboard/lib/python3.9',
 '/applis/xyz/.envs/model_dashboard/lib/python3.9/lib-dynload',
 '',
 '/home/users/a12345/.local/lib/python3.9/site-packages',
 '/applis/xyz/.envs/model_dashboard/lib/python3.9/site-packages']
</code>```

That seems weird to me. I would expect at least to see the packages from my conda environment ( '/applis/xyz/.envs/model_dashboard/lib/python3.9/site-packages') appearing before my .local python install's packages ('/home/users/a12345/.local/lib/python3.9/site-packages'), not after. I'm even wondering why the .local packages are in the python path at all, I think I don't really need this.

So I tried restarting the kernel, then putting the .local last instead:

```<code>['/applis/abc/notebooks',
 '/applis/xyz/.envs/model_dashboard/lib/python39.zip',
 '/applis/xyz/.envs/model_dashboard/lib/python3.9',
 '/applis/xyz/.envs/model_dashboard/lib/python3.9/lib-dynload',
 '',
 '/applis/xyz/.envs/model_dashboard/lib/python3.9/site-packages',
 '/home/users/a12345/.local/lib/python3.9/site-packages'
]
</code>```

When printing sys.path, I see that the modification has worked, .local will now provide packages as last option.

With the kernel restarted and the above sys.path changes, when I run the pycaret code again, I no longer have the sklearn error.

So, good news, but a question remains: what is the .local folder meant for - I suppose just as the default python installation - and what configuration causes a system to prefer .local packages before a conda environment's packages in every Jupyter notebook that I start? It must be some configuration that I don't know about, since I could see in a different organization that the .local path was not even in ´sys.path´ when I'm printing it in a Jupyter notebook there.

I'd like to modify this configuration so I don't need to modify sys.path in every notebook.

Body:
I'm trying to run automatic machine learning model benchmarking code from the pycaret python package, which in its turn uses scikit-learn, among others.

However, my conda environment seems to run the scikit-learn dependency installed in the .local folder in my own home directory, rather than from my conda environment's packages.

That is not what I expected and it leads to the called pycaret code crashing because the interface of the loaded scikit-learn' is not the interface it expected.

I've found a way to change that behavior by editing sys.path (see below), but I don't understand why my conda environment apparently prefers .local folder's packages first, instead of the installed conda environment packages.

I have checked the sys.path of a conda environment created at a different organization and there the order is not like the above, so it clearly prefers the conda environment packages first.

This weird behavior clearly causes runtime errors and I don't want to edit sys.path in every Jupyter notebook that I start here at this organization. Can someone tell me which configuration sets this behavior, so I understand and can avoid having to indeed edit sys.path everytime?

A minimal code example of what I'm running is:

import pandas as pd
from pycaret.regression import *

df_basetable = pd.read_csv('df_basetable.csv')
random_seed = 14
regr_exp1 = setup(
    data=df_basetable[df_basetable["split_level1"]=="full train"],
    target="my_prediction_target",
    ignore_features=["customer_id"],
    numeric_features=[col for col in df_basetable.columns if col not in ["my_prediction_target", "customer_id"],
    test_data=df_basetable[df_basetable["split_level1"]=="validation"],
    fold_strategy = 'kfold',
    fold=5,
    fold_shuffle=True,
    n_jobs=5,
    session_id=random_seed, # for reproducibility
)

That results in the following error:

File ~/.local/lib/python3.9/site-packages/sklearn/base.py:211, in BaseEstimator.get_params(self, deep)
    209 out = dict()
    210 for key in self._get_param_names():
--> 211     value = getattr(self, key)
    212     if deep and hasattr(value, "get_params") and not isinstance(value, type):
    213         deep_items = value.get_params().items()

AttributeError: 'Simple_Imputer' object has no attribute 'fill_value_categorical'

What strikes me is that the interpreter is crashing on File ~/.local/lib/python3.9/site-packages/sklearn/base.py:211: I expected to see the path listed here of the sklearn package installed on the conda environment that I'm using.

I am running the above python code within a Jupyter Lab notebook with the conda environment activated that I want to use (it's called model_dashboard).
Proof of that is:

import sys
print(sys.executable)

That prints '/applis/xyz/.envs/model_dashboard/bin/python'.

The python paths involved however, are the following:

import sys
sys.path

===>

['/applis/abc/notebooks',
 '/applis/xyz/.envs/model_dashboard/lib/python39.zip',
 '/applis/xyz/.envs/model_dashboard/lib/python3.9',
 '/applis/xyz/.envs/model_dashboard/lib/python3.9/lib-dynload',
 '',
 '/home/users/a12345/.local/lib/python3.9/site-packages',
 '/applis/xyz/.envs/model_dashboard/lib/python3.9/site-packages']

That seems weird to me. I would expect at least to see the packages from my conda environment ( '/applis/xyz/.envs/model_dashboard/lib/python3.9/site-packages') appearing before my .local python install's packages ('/home/users/a12345/.local/lib/python3.9/site-packages'), not after. I'm even wondering why the .local packages are in the python path at all, I think I don't really need this.

So I tried restarting the kernel, then putting the .local last instead:

['/applis/abc/notebooks',
 '/applis/xyz/.envs/model_dashboard/lib/python39.zip',
 '/applis/xyz/.envs/model_dashboard/lib/python3.9',
 '/applis/xyz/.envs/model_dashboard/lib/python3.9/lib-dynload',
 '',
 '/applis/xyz/.envs/model_dashboard/lib/python3.9/site-packages',
 '/home/users/a12345/.local/lib/python3.9/site-packages'
]

When printing sys.path, I see that the modification has worked, .local will now provide packages as last option.

With the kernel restarted and the above sys.path changes, when I run the pycaret code again, I no longer have the sklearn error.

So, good news, but a question remains: what is the .local folder meant for - I suppose just as the default python installation - and what configuration causes a system to prefer .local packages before a conda environment's packages in every Jupyter notebook that I start? It must be some configuration that I don't know about, since I could see in a different organization that the .local path was not even in ´sys.path´ when I'm printing it in a Jupyter notebook there.

I'd like to modify this configuration so I don't need to modify sys.path in every notebook.


问:
Removing disabled="disabled" attribute for a checkbox in C#

How would I go about removing the disabled="disabled" attribute for a CheckBox inside a GridView...

.ascx file

```<code><asp:Label ID="lblHidden" runat="server" Text=""></asp:Label>
    <ajaxToolkit:ModalPopupExtender ID="mpePopUp" runat="server" TargetControlID="lblHidden" PopupControlID="divPopUp" BackgroundCssClass="modalBackground"></ajaxToolkit:ModalPopupExtender>

<div id="divPopUp" style="background: #eee;">
    <div id="Header" class="header" style="padding:8px;"><h2>Please select the items that are being excluded from the order</h2></div>
    <asp:Panel ID="pnlMain" runat="server" style="padding:8px;font-size: 15px !important;"></asp:Panel>

    <%-- I want my DataTable/GridView right here --%>
    <asp:GridView ID="GridView1" CellPadding="2" BorderColor="#CCCCCC" runat="server">
        <HeaderStyle CssClass="gridHeader" BorderColor="#cccccc" />
        <RowStyle CssClass="gridRowStyle" BorderColor="#cccccc" BackColor="#eeeeee" />
            <Columns>
            </Columns>
        <EmptyDataTemplate>
            <div style="height: 24px; margin-left: 5px; margin-top: 7px;"><b>No Line Items Found For This Order!</b></div>
        </EmptyDataTemplate>
    </asp:GridView>

    <div id="buttons" style="display:inline-block; padding:8px;">
    <asp:Button ID="ButtonPartial" runat="server" Text="Submit" BorderStyle="Solid" ToolTip="Submit" OnClick="ButtonPartial_Click" style="padding:2px;"/>
        <asp:Button ID="ButtonCancelPartial" runat="server" Text="Cancel" BorderStyle="Solid" ToolTip="Cancel" OnClick="ButtonCancelPartial_Click" style="padding:2px;"/>
    </div>
</div>
</code>```

c# code to generate the CheckBox in the GridView

```<code>    protected void LineItemsModalTable(string orderNumber)
    {
        DataTable dt = new DataTable();
        var selectColumn = new DataColumn("Excluding Selected", typeof(bool))
        {
            DefaultValue = true
        };
        dt.Columns.Add(selectColumn); //this will show checkboxes
        string sql = String.Format(@"sql stuff", orderNumber);

        using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionStringStuff"].ConnectionString))
            {
                using (SqlDataAdapter adapter = new SqlDataAdapter(sql, conn))
                {
                    try
                    {
                        //fill the datatable with the contents from the database
                        adapter.Fill(dt);
                    }
                    catch
                    {
                    }
                }
            }
            //bind the datasource to the gridview
            GridView1.DataSource = dt;
            GridView1.DataBind();
            //trying to remove the attribuyte of disabled.
            foreach (GridViewRow row in GridView1.Rows)
            {
                //var i = 0;
                //var uniqueID = row.Cells[0].ID;
                //CheckBox chkRow = GridView1.Rows[i].FindControl(uniqueID) as CheckBox;
                //chkRow.Attributes.Remove("disabled");
                //i++;
                row.Cells[0].Attributes.Remove("disabled");
            }
        }
</code>```

Output:

Output Table

Inspect Output

Basically when you save, it does some stuff and then brings you to the LineItemsModalTable function. I think this is the code that is breaking it but I have not been able to find anything that has helped me so far...

```<code>var selectColumn = new DataColumn("Excluding Selected", typeof(bool))
{
     DefaultValue = true
};
dt.Columns.Add(selectColumn); //this will show checkboxes
</code>```

I also tried to loop through the GridView rows and remove the attribute but it doesn't allow me because it's saying it's a DisabledCssClass. I want to be able to do this in the server side code, and I want to be able to click the check boxes, but right now they are disabled. Thank you for the help!

Body:
How would I go about removing the disabled="disabled" attribute for a CheckBox inside a GridView...

.ascx file

<asp:Label ID="lblHidden" runat="server" Text=""></asp:Label>
    <ajaxToolkit:ModalPopupExtender ID="mpePopUp" runat="server" TargetControlID="lblHidden" PopupControlID="divPopUp" BackgroundCssClass="modalBackground"></ajaxToolkit:ModalPopupExtender>

Please select the items that are being excluded from the order

    <asp:Panel ID="pnlMain" runat="server" style="padding:8px;font-size: 15px !important;"></asp:Panel>

    <%-- I want my DataTable/GridView right here --%>
    <asp:GridView ID="GridView1" CellPadding="2" BorderColor="#CCCCCC" runat="server">
        <HeaderStyle CssClass="gridHeader" BorderColor="#cccccc" />
        <RowStyle CssClass="gridRowStyle" BorderColor="#cccccc" BackColor="#eeeeee" />
            <Columns>
            </Columns>
        <EmptyDataTemplate>

No Line Items Found For This Order!

        </EmptyDataTemplate>
    </asp:GridView>

    <asp:Button ID="ButtonPartial" runat="server" Text="Submit" BorderStyle="Solid" ToolTip="Submit" OnClick="ButtonPartial_Click" style="padding:2px;"/>
        <asp:Button ID="ButtonCancelPartial" runat="server" Text="Cancel" BorderStyle="Solid" ToolTip="Cancel" OnClick="ButtonCancelPartial_Click" style="padding:2px;"/>

c# code to generate the CheckBox in the GridView

    protected void LineItemsModalTable(string orderNumber)
    {
        DataTable dt = new DataTable();
        var selectColumn = new DataColumn("Excluding Selected", typeof(bool))
        {
            DefaultValue = true
        };
        dt.Columns.Add(selectColumn); //this will show checkboxes
        string sql = String.Format(@"sql stuff", orderNumber);

        using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionStringStuff"].ConnectionString))
            {
                using (SqlDataAdapter adapter = new SqlDataAdapter(sql, conn))
                {
                    try
                    {
                        //fill the datatable with the contents from the database
                        adapter.Fill(dt);
                    }
                    catch
                    {
                    }
                }
            }
            //bind the datasource to the gridview
            GridView1.DataSource = dt;
            GridView1.DataBind();
            //trying to remove the attribuyte of disabled.
            foreach (GridViewRow row in GridView1.Rows)
            {
                //var i = 0;
                //var uniqueID = row.Cells[0].ID;
                //CheckBox chkRow = GridView1.Rows[i].FindControl(uniqueID) as CheckBox;
                //chkRow.Attributes.Remove("disabled");
                //i++;
                row.Cells[0].Attributes.Remove("disabled");
            }
        }

Output:

Output Table

Inspect Output

Basically when you save, it does some stuff and then brings you to the LineItemsModalTable function. I think this is the code that is breaking it but I have not been able to find anything that has helped me so far...

var selectColumn = new DataColumn("Excluding Selected", typeof(bool))
{
     DefaultValue = true
};
dt.Columns.Add(selectColumn); //this will show checkboxes

I also tried to loop through the GridView rows and remove the attribute but it doesn't allow me because it's saying it's a DisabledCssClass. I want to be able to do this in the server side code, and I want to be able to click the check boxes, but right now they are disabled. Thank you for the help!


问:
Multiple automatic staging areas in git
I find myself in a workflow where we are doing changes in some subdirectories to be released later next year, but still patching small bugs in other areas, to be release immediately after testing. So it seems natural to use two branches, say "fixes" for the global branch and "future2023" for the updates in the subdirectories

I wonder, is it possible to configure git in a way that it knows automatically that any change in a subdirectory is to be considered against a branch, while any other changes should to be considered against the other, "fixes", branch? It seems similar to having multiple worktrees except that in this case the path of the files for one worktree is inside the other.

Title: Multiple automatic staging areas in git


问:
Angular 14 failed proxying request
In angular 14 with dotnet 6 , in one machine i have problem to call any api from angular that will proxy to dotnet. i some other computers everything is fine.
i get this error while https://localhost:7156/api/Resource/Login successfully response.

 [webpack-dev-server] [HPM] Error occurred while proxying request localhost:44495/api/Resource/Login to https://localhost:7156/ [ECONNREFUSED] (https://nodejs.org/api/errors.html#errors_common_system_errors)

In stackoverflow users said the target address is not listening while it is working fine

Title: Angular 14 failed proxying request


问:
Can we receive "gender" based dimension data from G4 Reporting API?
Here is a record from a GA file we fetched  (example)

```<code>{
    "dimensions": [
        "male",
        "www.example.com",
        "/test/12345/howGADataLooksSampleArticle"
    ],
    "metrics": [
        {
            "values": [
                "922"
            ]
        }
    ]
}
</code>```

and compared it to the JSON Representation of the getMetadata on the new API for GA4.

The structure looks the same. Does that mean that the above mentioned record can be retrieved with the gender dimension that we currently use?

We would need to clarify of there is any difference from the UA API version that we need to adjust?

Body:
Here is a record from a GA file we fetched  (example)

{
    "dimensions": [
        "male",
        "www.example.com",
        "/test/12345/howGADataLooksSampleArticle"
    ],
    "metrics": [
        {
            "values": [
                "922"
            ]
        }
    ]
}

and compared it to the JSON Representation of the getMetadata on the new API for GA4.

The structure looks the same. Does that mean that the above mentioned record can be retrieved with the gender dimension that we currently use?

We would need to clarify of there is any difference from the UA API version that we need to adjust?


问:
GCP PubSub - filter on attribute range, not only equality/inequality comparison?
Currently only exact equal or not equal PubSub filter comparison operations are available.

We've submitted a Feature Request to Google for a range check filter comparison operation when pulling PubSub messages.

For our application (callbacks on a massive scale that exponentially backoff on failure), it would be most convenient to pull only those messages that are not only equal or not equal, but fulfill a range function check as AWS SNS does here and only see relevant messages, e.g. the filter logic would be relegated to the PubSub mechanism.

Unfortunately, the alternatives are not pretty, and PubSub push notifications will not work for a couple of reasons (IAC dependencies & limit on delay time), and the alternative of re-reading every message every N seconds to perform the check, and then re-inserting the message again after ACK is pretty inefficient.

Anyone have any ideas that are simple and do not add a lot of clumsy GCP machinery?

TIA!


问:
Setting column widths using bscols in crosstalk package
I have the following simple example of using bscols method (bootstraps columns) as part of the crosstalk package in R.  While setting  widths = c(6, 6) works, it seems to set the default column sizes as col-xs-6

I'm wondering how to customize this, so that for example the columns would stack (i.e. collapse) when resized to small, i.e. col-xs-12.  Or really any further customization of the columns i.e. col-md, col-lg

I see the bscols documentation has the following parameter:

```<code>device = c("xs", "sm", "md", "lg"))
</code>```

Which makes me think this is possible, but I don't see any examples of how to use this to achieve what I'm after, i.e. setting column widths based on device size.

barchart.js:

```<code>// !preview r2d3 data=c(0.3, 0.6, 0.8, 0.95, 0.40, 0.20)

var barHeight = Math.floor(height / data.length);

svg
  .selectAll("rect")
  .data(data)
  .enter()
  .append("rect")
  .attr("width", function (d) {
    return d * width;
  })
  .attr("height", barHeight)
  .attr("y", function (d, i) {
    return i * barHeight;
  })
  .attr("fill", "steelblue");
</code>```

RMarkdown:

```<code>library(r2d3)
library(crosstalk)

crosstalk::bscols(
  widths = c(6, 6),
   r2d3(data=c(0.3, 0.6, 0.8, 0.95, 0.40, 0.20), script = "barchart.js",
        width = 300, height = 200),
   r2d3(data=c(0.3, 0.6, 0.8, 0.95, 0.40, 0.20), script = "barchart.js",
        width = 300, height = 200)
)
</code>```

Body:
I have the following simple example of using bscols method (bootstraps columns) as part of the crosstalk package in R.  While setting  widths = c(6, 6) works, it seems to set the default column sizes as col-xs-6

I'm wondering how to customize this, so that for example the columns would stack (i.e. collapse) when resized to small, i.e. col-xs-12.  Or really any further customization of the columns i.e. col-md, col-lg

I see the bscols documentation has the following parameter:

device = c("xs", "sm", "md", "lg"))

Which makes me think this is possible, but I don't see any examples of how to use this to achieve what I'm after, i.e. setting column widths based on device size.

barchart.js:

// !preview r2d3 data=c(0.3, 0.6, 0.8, 0.95, 0.40, 0.20)

var barHeight = Math.floor(height / data.length);

svg
  .selectAll("rect")
  .data(data)
  .enter()
  .append("rect")
  .attr("width", function (d) {
    return d * width;
  })
  .attr("height", barHeight)
  .attr("y", function (d, i) {
    return i * barHeight;
  })
  .attr("fill", "steelblue");

RMarkdown:

library(r2d3)
library(crosstalk)

crosstalk::bscols(
  widths = c(6, 6),
   r2d3(data=c(0.3, 0.6, 0.8, 0.95, 0.40, 0.20), script = "barchart.js",
        width = 300, height = 200),
   r2d3(data=c(0.3, 0.6, 0.8, 0.95, 0.40, 0.20), script = "barchart.js",
        width = 300, height = 200)
)


问:
Putting a Shadow on a List makes the View Render Incorrectly on iOS 15
I have recently been making an app using SwiftUI. In this app, I have a background image that is mostly white, and so decided to add some shadows to the list to better distinguish the elements from the background. However, when adding a shadow to the list, the view seems to get pushed up and off the screen. These elements can then no longer be clicked.

Below shows an example of this:

Shadows breaking View

On the left is what happens when I do not add a shadow, and on the right is what happens when I do. For this question, I have removed the background. The example on the right does not show it's shadow in the screenshot, but when the background is added it does.

Below is the code I have used for his example:

```<code>List {
    Section(header: Text("Header")) {
        Button("Test") {}
    }
}
.shadow(color: Color(red: 201 / 255, green: 201 / 255, blue: 201 / 255), radius: 1)
</code>```

The devices this problem occurs on also doesn't seem to be very consistent.

Everything works as expected on:

iPhone 14 physical (iOS 16) and simulator (iOS 16).

iPhone 11 Pro Max physical (iOS 15).

The problem occurs when using:

iPod touch 7th generation (iOS 15) simulator.

iPhone 7 (iOS 15) physical.

iPhone 11 Pro Max simulator (iOS 15).

At first I thought it would be because iOS 15 needs shadows to be done differently, but on a physical iPhone 11 Pro Max device, everything renders correctly whereas in the simulator it does not.

In case it is important, the list is inside a navigation view which is inside a tab view.

Does anyone have any idea why this is happening or if there are any alternative ways of showing a shadow?

Body:
I have recently been making an app using SwiftUI. In this app, I have a background image that is mostly white, and so decided to add some shadows to the list to better distinguish the elements from the background. However, when adding a shadow to the list, the view seems to get pushed up and off the screen. These elements can then no longer be clicked.

Below shows an example of this:

Shadows breaking View

On the left is what happens when I do not add a shadow, and on the right is what happens when I do. For this question, I have removed the background. The example on the right does not show it's shadow in the screenshot, but when the background is added it does.

Below is the code I have used for his example:

List {
    Section(header: Text("Header")) {
        Button("Test") {}
    }
}
.shadow(color: Color(red: 201 / 255, green: 201 / 255, blue: 201 / 255), radius: 1)

The devices this problem occurs on also doesn't seem to be very consistent.

Everything works as expected on:

iPhone 14 physical (iOS 16) and simulator (iOS 16).

iPhone 11 Pro Max physical (iOS 15).

The problem occurs when using:

iPod touch 7th generation (iOS 15) simulator.

iPhone 7 (iOS 15) physical.

iPhone 11 Pro Max simulator (iOS 15).

At first I thought it would be because iOS 15 needs shadows to be done differently, but on a physical iPhone 11 Pro Max device, everything renders correctly whereas in the simulator it does not.

In case it is important, the list is inside a navigation view which is inside a tab view.

Does anyone have any idea why this is happening or if there are any alternative ways of showing a shadow?


问:
Maven shade plugin how to add package level resources
I am using shade plugin to build a fat or uber jar . Please see my shade plugin pom snippet as below

```<code><plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-shade-plugin</artifactId>
        <version>3.4.1</version>
        <executions>
          <execution>
            <phase>package</phase>
            <goals>
              <goal>shade</goal>
            </goals>
            <configuration>
            <artifactSet>
                <includes>
                  <include>*:*</include>
                </includes>
              </artifactSet>

            </configuration>
          </execution>
        </executions>
      </plugin>

</code>```

I have some resource file for XML and properties which are not in src/main/resources but lies along with java packages.

When I build the code with maven  with mvn clean package it compiles and add all dependent jar file but all resources files that are at the package level say src/main/java/x/y/z/hibernate.hbm.xml doesnt get added into respective place of fat jar.
Could someone please let me know what extra I have to do in above maven snippet to add those resources

I tried adding  . in the artifacts set it didn't work . Also using maven assembly plugin its not working. I also searched direct eclipse plugin which can help but no clue. please help

Body:
I am using shade plugin to build a fat or uber jar . Please see my shade plugin pom snippet as below

<plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-shade-plugin</artifactId>
        <version>3.4.1</version>
        <executions>
          <execution>
            <phase>package</phase>
            <goals>
              <goal>shade</goal>
            </goals>
            <configuration>
            <artifactSet>
                <includes>
                  <include>*:*</include>
                </includes>
              </artifactSet>

            </configuration>
          </execution>
        </executions>
      </plugin>

I have some resource file for XML and properties which are not in src/main/resources but lies along with java packages.

When I build the code with maven  with mvn clean package it compiles and add all dependent jar file but all resources files that are at the package level say src/main/java/x/y/z/hibernate.hbm.xml doesnt get added into respective place of fat jar.
Could someone please let me know what extra I have to do in above maven snippet to add those resources

I tried adding  . in the artifacts set it didn't work . Also using maven assembly plugin its not working. I also searched direct eclipse plugin which can help but no clue. please help


问:
javascript table size didnt match the card size nor the chart size
i have this html code to make table from chart dataset automatic, but the table size is not the same as the chart, i wanted to make the table size same as the chart size or same as the box. // i tried to change the css but it doesnt work, hope u can helpyour text

```<code><!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Getting Started with Chart JS with www.chartjs3.com</title>
    <style>
      * {
        margin: 0;
        padding: 0;
        font-family: sans-serif;
      }
      .chartMenu {
        width: 100%;
        height: 40px;
        background: #1A1A1A;
        color: rgba(255, 26, 104, 1);
      }
      .chartMenu p {
        padding: 10px;
        font-size: 20px;

      }
      .chartCard {
        width: 100%;
        height: calc(100vh - 40px);
        background: rgba(255, 26, 104, 0.2);
        display: flex;
        align-items: center;
        justify-content: center;
      }
      .chartBox {
        width: 700px;
        padding: 20px;
        border-radius: 20px;
        border: solid 3px rgba(255, 26, 104, 1);
        background: white;
      }
      .table, th, td{
        border-collapse: collapse;
        border: 1px solid black;
        padding:10px;
        height: auto;
      }
      .chartjs-thead {
        font-weight: bold;
      }
      .chartjs-body {
        text-align: center;
      }
      /* .table1 {
        width: 50%;
      } */
    </style>

  </head>
  <body>
    <div class="chartMenu">
      <p>WWW.CHARTJS3.COM (Chart JS 3.9.1)</p>
    </div>
    <div class="chartCard">
      <div class="chartBox">
        <canvas id="myChart"></canvas>
        <body onload="createTable()"></body>
        <!-- <canvas id="mytable"></canvas> -->
      </div>
    </div>
    <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <script>
      const cars = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun', 'Thu', 'Fri', 'Sat', 'Sun', 'Thu', 'Fri', 'Sat', 'Sun'];
    </script>
    <script>

    // setup
    const data = {
      labels: cars,
      datasets: [{
        label: 'Weekly Sales',
        data: [18, 12, 6, 9, 12, 3, 9],
        backgroundColor: [
          'rgba(255, 26, 104, 0.2)',
          'rgba(54, 162, 235, 0.2)',
          'rgba(255, 206, 86, 0.2)',
          'rgba(75, 192, 192, 0.2)',
          'rgba(153, 102, 255, 0.2)',
          'rgba(255, 159, 64, 0.2)',
          'rgba(0, 0, 0, 0.2)'
        ],
        borderColor: [
          'rgba(255, 26, 104, 1)',
          'rgba(54, 162, 235, 1)',
          'rgba(255, 206, 86, 1)',
          'rgba(75, 192, 192, 1)',
          'rgba(153, 102, 255, 1)',
          'rgba(255, 159, 64, 1)',
          'rgba(0, 0, 0, 1)'
        ],
        borderWidth: 1
      },
      {
        label: 'Weekly daw',
        data: [1, 1, null, 11, 1, 13, 15],
        backgroundColor: [
          'rgba(255, 26, 104, 0.2)',
          'rgba(54, 162, 235, 0.2)',
          'rgba(255, 206, 86, 0.2)',
          'rgba(75, 192, 192, 0.2)',
          'rgba(153, 102, 255, 0.2)',
          'rgba(255, 159, 64, 0.2)',
          'rgba(0, 0, 0, 0.2)'
        ],
        borderColor: [
          'rgba(255, 26, 104, 1)',
          'rgba(54, 162, 235, 1)',
          'rgba(255, 206, 86, 1)',
          'rgba(75, 192, 192, 1)',
          'rgba(153, 102, 255, 1)',
          'rgba(255, 159, 64, 1)',
          'rgba(0, 0, 0, 1)'
        ],
        borderWidth: 1
      }
    ]
    };

    // config
    const config = {
      type: 'bar',
      data,
      options: {
        scales: {
          y: {
            beginAtZero: true
          }
        }
      }
    };

    // render init block
    const myChart = new Chart(
      document.getElementById('myChart'),
      config
    );
</code>```

the table function

```<code>
    function createTable(){
      console.log('triggered');
      const chartBox = document.querySelector('.chartBox');
      const tableDiv = document.createElement('div');
      tableDiv.setAttribute('id', 'tableDiv');

      const table = document.createElement('table');

      // add thead
      const thead = table.createTHead();
      thead.classList.add('chartjs-thead');

      thead.insertRow(0);
      console.log(data.labels)
      for(let i = 0; i< data.labels.length; i++) {
         thead.rows[0].insertCell(i).innerText = data.labels[i];

      };
      thead.rows[0].insertCell(0).innerText = 'Days';

      table.style.width = "50%";

      // add tbody
      const tbody = table.createTBody();
      tbody.classList.add('chartjs-tbody');

      console.log(data.datasets)
      data.datasets.map((dataset, index) => {
        tbody.insertRow(index);
        for(let i = 0; i < data.datasets[0].data.length; i++){
          tbody.rows[index].insertCell(i).innerText = dataset.data[i];
        };
        tbody.rows[index].insertCell(0).innerText = dataset.label;
      })

      //<table>
      //<thead>
      //  <tr>
      //  <td></td>
      //  </tr>
      //</thead>
      //</table>

      chartBox.appendChild(tableDiv);
      tableDiv.appendChild(table);
    };
</code>```
```<code></script>
</code>```

// i tried to change the css but it doesnt work, hope u can help

Body:
i have this html code to make table from chart dataset automatic, but the table size is not the same as the chart, i wanted to make the table size same as the chart size or same as the box. // i tried to change the css but it doesnt work, hope u can helpyour text

<!doctype html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Getting Started with Chart JS with www.chartjs3.com</title>

WWW.CHARTJS3.COM (Chart JS 3.9.1)

        <canvas id="myChart"></canvas>

// i tried to change the css but it doesnt work, hope u can help


问:
How to get the objects of an object using foreach in Laravel blade
I am trying to get all the order details that are linked to and order which is linked to a booking.

Let's say I pass the booking id and wanna retrieve all the order details linked to it. but the orderOrderDetials in the view returns an empty array even if there is record in the database.

Booking Model

```<code>protected $fillable = [
    'room_id',
    'invoice_id',
    'order_id',
    'status',
    'start_time',
    'end_time',
];
public function invoice()
{
    return $this->belongsTo(Invoice::class, 'invoice_id');
}

public function order()
{
    return $this->belongsTo(Order::class, 'order_id');
}
</code>```

Order Model

```<code>protected $fillable = [
    'booking_id',
    'serial_number',
    'subtotal',
];
public function orderOrderDetails()
{
    return $this->hasMany(OrderDetail::class, 'order_id', 'id');
}
public function booking()
{
    return $this->belongsTo(Booking::class, 'booking_id');
}
</code>```

Order Details Model

```<code>protected $fillable = [
    'order_id',
    'order_item_id',
    'quantity',
    'amount',
];

public function order()
{
    return $this->belongsTo(Order::class, 'order_id');
}

public function order_item()
{
    return $this->belongsTo(Product::class, 'order_item_id');
}
</code>```

Home Controller

```<code> class HomeController
 {
   public function index()
   {
     $bookings = Booking::where('status', "in_progress")->orWhere('status', "unpaid")->get();   \\ shows 5 objects when dd($bookings)
    return view('home', compact('bookings'));
   }
 }
</code>```

Home View

```<code> @if ($bookings !== NULL)
   @foreach ($bookings as  $booking)
     @foreach ($booking->order->orderOrderDetails as  $orderDetail)   \\$booking->order->orderOrderDetails returns an empty array even tho there are records in the database
       <p>{{ $orderDetail->item->name ?? ''}}</p>
       <p>{{ $orderDetail->item->price ?? ''}}</p>
       <p>{{ $orderDetail->item->quantity ?? ''}}</p>
     @endforeach
   @endforeach
 @endif
</code>```

Order Details Table

Orders Table

Bookings Table

Body:
I am trying to get all the order details that are linked to and order which is linked to a booking.

Let's say I pass the booking id and wanna retrieve all the order details linked to it. but the orderOrderDetials in the view returns an empty array even if there is record in the database.

Booking Model

protected $fillable = [
    'room_id',
    'invoice_id',
    'order_id',
    'status',
    'start_time',
    'end_time',
];
public function invoice()
{
    return $this->belongsTo(Invoice::class, 'invoice_id');
}

public function order()
{
    return $this->belongsTo(Order::class, 'order_id');
}

Order Model

protected $fillable = [
    'booking_id',
    'serial_number',
    'subtotal',
];
public function orderOrderDetails()
{
    return $this->hasMany(OrderDetail::class, 'order_id', 'id');
}
public function booking()
{
    return $this->belongsTo(Booking::class, 'booking_id');
}

Order Details Model

protected $fillable = [
    'order_id',
    'order_item_id',
    'quantity',
    'amount',
];

public function order()
{
    return $this->belongsTo(Order::class, 'order_id');
}

public function order_item()
{
    return $this->belongsTo(Product::class, 'order_item_id');
}

Home Controller

 class HomeController
 {
   public function index()
   {
     $bookings = Booking::where('status', "in_progress")->orWhere('status', "unpaid")->get();   \\ shows 5 objects when dd($bookings)
    return view('home', compact('bookings'));
   }
 }

Home View

 @if ($bookings !== NULL)
   @foreach ($bookings as  $booking)
     @foreach ($booking->order->orderOrderDetails as  $orderDetail)   \\$booking->order->orderOrderDetails returns an empty array even tho there are records in the database

{{ $orderDetail->item->name ?? ''}}

{{ $orderDetail->item->price ?? ''}}

{{ $orderDetail->item->quantity ?? ''}}

     @endforeach
   @endforeach
 @endif

Order Details Table

Orders Table

Bookings Table


问:
Get disk activity like in the windows task manager
I need to get the performance from the disk C:/ from my computer with python.
I'm using psutil but there's no method to get this information.
I want it exactly like in the task manager from windows but I can't get it :

I tried different code found on stackoverflow but i don't get the right information.
For example this one :

```<code>p = psutil.Process()
io_counters = p.io_counters()
disk_usage_process = io_counters[2] + io_counters[3] # read_bytes + write_bytes
disk_io_counter = psutil.disk_io_counters()
disk_total = disk_io_counter[2] + disk_io_counter[3] # read_bytes + write_bytes
print(disk_usage_process/disk_total * 100)
#Result 0.0004283707980337007
</code>```

but i don't get the usage only the writing and the reading from the disk.
i tried to put the code in a loop and wait 1 second but i doesn't change.
If anyone have a solution maybe with another library.

Thanks !

Body:
I need to get the performance from the disk C:/ from my computer with python.
I'm using psutil but there's no method to get this information.
I want it exactly like in the task manager from windows but I can't get it :

I tried different code found on stackoverflow but i don't get the right information.
For example this one :

p = psutil.Process()
io_counters = p.io_counters()
disk_usage_process = io_counters[2] + io_counters[3] # read_bytes + write_bytes
disk_io_counter = psutil.disk_io_counters()
disk_total = disk_io_counter[2] + disk_io_counter[3] # read_bytes + write_bytes
print(disk_usage_process/disk_total * 100)
#Result 0.0004283707980337007

but i don't get the usage only the writing and the reading from the disk.
i tried to put the code in a loop and wait 1 second but i doesn't change.
If anyone have a solution maybe with another library.

Thanks !


问:
Stuck in displaying google maps with locations and polylines
I am trying to create an app that shows a map after the user has logged in and has given permission for location. Here is my current code

```<code>class MapScreen extends StatefulWidget {
  const MapScreen({Key? key}) : super(key: key);

  @override
  State<MapScreen> createState() => MapScreenState();
}

List<LatLng> polylineCoordinates = [];
LocationData? currentLocation;

void getCurrentLocation() {
  Location location = Location();

  location.getLocation().then(
    (location) {
      currentLocation = location;
    },
  );
}

class MapScreenState extends State<MapScreen> {
  final Completer<GoogleMapController> _controller = Completer();

  late BitmapDescriptor sourceIcon;
  late BitmapDescriptor destinationIcon;

  void getPolyPoints() async {
    PolylinePoints polylinePoints = PolylinePoints();

    PolylineResult result = await polylinePoints.getRouteBetweenCoordinates(
      mapsApiKey,
      PointLatLng(currentLocation!.latitude!, currentLocation!.longitude!),
      PointLatLng(destination.latitude, destination.longitude),
    );

    if (result.points.isNotEmpty) {
      polylineCoordinates = [];
      result.points.forEach((PointLatLng point) {
        polylineCoordinates.add(LatLng(point.latitude, point.longitude));
      });
      setState(() {});
    }
  }

  Future setSourceAndDestinationIcons() async {
    sourceIcon = await BitmapDescriptor.fromAssetImage(
        const ImageConfiguration(devicePixelRatio: 1.5, size: Size(10, 10)),
        'assets/images/icon1.png');

    destinationIcon = await BitmapDescriptor.fromAssetImage(
        const ImageConfiguration(devicePixelRatio: 1.5),
        'assets/images/icon2.png');
  }

  @override
  void initState() {
    getCurrentLocation();
    getPolyPoints();
    setSourceAndDestinationIcons();

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          backgroundColor: Colors.white,
          title: const Text(
            "Tracker",
            style: TextStyle(
              color: Colors.black,
              fontSize: 16,
            ),
          ),
        ),
        body: currentLocation == null? Center(child: Text("Loading")):
        GoogleMap(

            initialCameraPosition: CameraPosition(
                target: LatLng(currentLocation!.latitude!, currentLocation!.longitude!), zoom: 14.5, tilt: 80),
            polylines: {
              Polyline(
                polylineId: PolylineId("Route"),
                points: polylineCoordinates,
                color: colorCustom,
                width: 6,
              )
            },
            markers: {
              Marker(
                markerId: MarkerId("CurrentLocation"),
                position: LatLng(currentLocation!.latitude!, currentLocation!.longitude!),
                icon: sourceIcon,
                ),
              Marker(
                markerId: MarkerId("Destination"),
                position: destination,
                icon: destinationIcon,
              )
            }));
  }
}
</code>```

When I click the button that will send me to the maps page, I get stuck at the loading sign. However, if I return to the previous page and then navigate back to the maps page, the maps will load, although the loading sign will be gone and there is a red screen error for a slight moment.

loading sign
Red screen after going back to the last page and then navigating again to the maps page

Any ideas on how to solve this?

Body:
I am trying to create an app that shows a map after the user has logged in and has given permission for location. Here is my current code

class MapScreen extends StatefulWidget {
  const MapScreen({Key? key}) : super(key: key);

  @override
  State<MapScreen> createState() => MapScreenState();
}

List<LatLng> polylineCoordinates = [];
LocationData? currentLocation;

void getCurrentLocation() {
  Location location = Location();

  location.getLocation().then(
    (location) {
      currentLocation = location;
    },
  );
}

class MapScreenState extends State<MapScreen> {
  final Completer<GoogleMapController> _controller = Completer();

  late BitmapDescriptor sourceIcon;
  late BitmapDescriptor destinationIcon;

  void getPolyPoints() async {
    PolylinePoints polylinePoints = PolylinePoints();

    PolylineResult result = await polylinePoints.getRouteBetweenCoordinates(
      mapsApiKey,
      PointLatLng(currentLocation!.latitude!, currentLocation!.longitude!),
      PointLatLng(destination.latitude, destination.longitude),
    );

    if (result.points.isNotEmpty) {
      polylineCoordinates = [];
      result.points.forEach((PointLatLng point) {
        polylineCoordinates.add(LatLng(point.latitude, point.longitude));
      });
      setState(() {});
    }
  }

  Future setSourceAndDestinationIcons() async {
    sourceIcon = await BitmapDescriptor.fromAssetImage(
        const ImageConfiguration(devicePixelRatio: 1.5, size: Size(10, 10)),
        'assets/images/icon1.png');

    destinationIcon = await BitmapDescriptor.fromAssetImage(
        const ImageConfiguration(devicePixelRatio: 1.5),
        'assets/images/icon2.png');
  }

  @override
  void initState() {
    getCurrentLocation();
    getPolyPoints();
    setSourceAndDestinationIcons();

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          backgroundColor: Colors.white,
          title: const Text(
            "Tracker",
            style: TextStyle(
              color: Colors.black,
              fontSize: 16,
            ),
          ),
        ),
        body: currentLocation == null? Center(child: Text("Loading")):
        GoogleMap(

            initialCameraPosition: CameraPosition(
                target: LatLng(currentLocation!.latitude!, currentLocation!.longitude!), zoom: 14.5, tilt: 80),
            polylines: {
              Polyline(
                polylineId: PolylineId("Route"),
                points: polylineCoordinates,
                color: colorCustom,
                width: 6,
              )
            },
            markers: {
              Marker(
                markerId: MarkerId("CurrentLocation"),
                position: LatLng(currentLocation!.latitude!, currentLocation!.longitude!),
                icon: sourceIcon,
                ),
              Marker(
                markerId: MarkerId("Destination"),
                position: destination,
                icon: destinationIcon,
              )
            }));
  }
}

When I click the button that will send me to the maps page, I get stuck at the loading sign. However, if I return to the previous page and then navigate back to the maps page, the maps will load, although the loading sign will be gone and there is a red screen error for a slight moment.

loading sign
Red screen after going back to the last page and then navigating again to the maps page

Any ideas on how to solve this?