问:
Code doesnt work after pulling rst pin low
I am trying to make an automatic house using ESP 8266 NodeMCU
Since this project will have to be charged from batteries, I need to act sparingly with energy.

My Products: https://www.amazon.de/gp/product/B07Z63MFYC/ref=ppx_yo_dt_b_asin_title_o06_s00?ie=UTF8&psc=1

I connected the RST and GND pin to my sensor and everything seems to be working well. But if I connect the sensors at the moment of connecting to the Wi-Fi, the code stops working.

My Code:

#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>

HTTPClient sender;
WiFiClient wifiClient;

const char* ssid = "xxx";
const char* password = "xxx";

void setup() {
  Serial.begin(9600);
  WiFi.persistent( false );
  WiFi.mode( WIFI_STA );
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(100);
    Serial.print(".");
  }
  Serial.println("Verbunden!");
  if (sender.begin(wifiClient, "http://192.168.178.64:1880/update-sensor")) {
    int httpCode = sender.GET();
    if (httpCode > 0) {
      if (httpCode == HTTP_CODE_OK) {
        String payload = sender.getString();
        Serial.println(payload);
      }
    } else {
      Serial.printf("HTTP-Error: ", sender.errorToString(httpCode).c_str());
    }
    sender.end();
  } else {
    Serial.printf("HTTP-Verbindung konnte nicht hergestellt werden!");
  }
  ESP.deepSleep(0);
}

void loop() {

}
```

I tried this code: delay(5000); on the start of setup() but it doesn't help me

Steps:
perfect-case:

I connect the magnetic switches (=door closed)

I connect ESP8266 to my PC

I disconnect the magnetic switches (=door opened)

I wait till WiFi is connected and ESP sends http request (takes about 10-30 sec.)
P.S. HTTP-Error is ok, because I didn't start my server.
enter image description here

realistic-case:

I connect the magnetic switches (=door closed)

I connect ESP8266 to my PC

I disconnect the magnetic switches (=door opened)

After 4-6 seconds I close the "door" and my code stops.
enter image description here

So... I don't want to wait about 30 seconds to close my door in real life.

Body:
I am trying to make an automatic house using ESP 8266 NodeMCU
Since this project will have to be charged from batteries, I need to act sparingly with energy.

My Products: https://www.amazon.de/gp/product/B07Z63MFYC/ref=ppx_yo_dt_b_asin_title_o06_s00?ie=UTF8&psc=1

I connected the RST and GND pin to my sensor and everything seems to be working well. But if I connect the sensors at the moment of connecting to the Wi-Fi, the code stops working.

My Code:

#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>

HTTPClient sender;
WiFiClient wifiClient;

const char* ssid = "xxx";
const char* password = "xxx";

void setup() {
  Serial.begin(9600);
  WiFi.persistent( false );
  WiFi.mode( WIFI_STA );
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(100);
    Serial.print(".");
  }
  Serial.println("Verbunden!");
  if (sender.begin(wifiClient, "http://192.168.178.64:1880/update-sensor")) {
    int httpCode = sender.GET();
    if (httpCode > 0) {
      if (httpCode == HTTP_CODE_OK) {
        String payload = sender.getString();
        Serial.println(payload);
      }
    } else {
      Serial.printf("HTTP-Error: ", sender.errorToString(httpCode).c_str());
    }
    sender.end();
  } else {
    Serial.printf("HTTP-Verbindung konnte nicht hergestellt werden!");
  }
  ESP.deepSleep(0);
}

void loop() {

}

I tried this code: delay(5000); on the start of setup() but it doesn't help me

Steps:
perfect-case:

I connect the magnetic switches (=door closed)

I connect ESP8266 to my PC

I disconnect the magnetic switches (=door opened)

I wait till WiFi is connected and ESP sends http request (takes about 10-30 sec.)
P.S. HTTP-Error is ok, because I didn't start my server.
enter image description here

realistic-case:

I connect the magnetic switches (=door closed)

I connect ESP8266 to my PC

I disconnect the magnetic switches (=door opened)

After 4-6 seconds I close the "door" and my code stops.
enter image description here

So... I don't want to wait about 30 seconds to close my door in real life.


来源: stackexchange

问:
MRTK Scene Understanding FindCentermostPlacement: ObjectDisposedException
I want to use MRTKs (2.8.2) experimental Scene Understanding to place an object at the centermost position on a quad. I'm trying to do this using the windows scene understanding observer's TryFindCentermostPlacement(int quadId, Vector2 objExtents, out Vector3 placementPosOnQuad), which finds the corresponding quad using cachedSceneQuads.TryGetValue(quadId, out result) - with result being Tuple<SceneQuad, SceneObject> - and calls FindCentermostPlacement on the quad (indicated by the quadId) as it is used e.g. here.

However, it seems like in about 90% of the runs, all properties of SceneQuad and SceneObject found by cachedSceneQuads.TryGetValue (e.g. Extents, Alignment, even the ID?) cannot be found due to a System.ObjectDisposedException:

ObjectDisposedException: Cannot access a disposed object.
Object name: 'Exception thrown and an unexpected error in exception handling.'.
Microsoft.MixedReality.SceneUnderstanding.NativeLibraryHelpers.CheckStatus (System.IntPtr handle, Microsoft.MixedReality.SceneUnderstanding.status value) (at Library/PackageCache/com.microsoft.mixedreality.sceneunderstanding@7bfd3a8ea18c/Editor/Microsoft.MixedReality.SceneUnderstanding.cs:136)
Microsoft.MixedReality.SceneUnderstanding.SceneQuad.get_Extents () (at Library/PackageCache/com.microsoft.mixedreality.sceneunderstanding@7bfd3a8ea18c/Editor/Microsoft.MixedReality.SceneUnderstanding.cs:1277)

I don't (at least not to my knowledge) clear the scenequads anywhere.
The cachedSceneQuads contain all IDs as keys and the scene objects and -quads as values, only the objects' and quads' properties are disposed apparently.

I'm using Unity 2021.3.11.

Does anyone have a clue?

Edit: When I set AutoUpdate to false, the exceptions are gone, even though UsePersistentObjects has always been turned on. Don't know if this can be a "solution" as I still want to use AutoUpdate...

ContentLicense: CC BY-SA 4.0


问:
cron - Running multiple cron jobs located in etc/cron.d
In my docker container, I have multiple cron jobs that need to be ran, with each doing a different thing:

Some cron jobs will import a module

Some cron jobs will activate the imported module

Finally, some cron jobs will do a cleanup

This is the order in which they should run.

Currently, cron is not a running process in my container however, including the following in my entrypoint script has it running in the foreground:

```<code>#!/bin/bash
cron -n -s -m off
</code>```

With this included, it does run the cron jobs. However, a key point is that each set of cron jobs (import, activate, cleanup) uses one of three bash scripts to perform their tasks. So, for example, the cron jobs that activate a module will have the following format:

```<code>MAILTO=""
* * * * * root /tmp/moduleActivation.sh  <module> <version>
</code>```

Each activation cron job will use a bash script that takes in two parameters and the bash script will activate it as so. The way these scripts are set up, only one instance can be running at any one time.

With my current setup, it will attempt to run each cron job at the same time, which is not my desired result as multiple instances of the activation script will attempt to run at the same time, which can't happen.

I am quite new to cron - how can I prevent this from happening and have the cron jobs run in the desired order? Will a crontab file take precedence in some way if I was to include one?

Body:
In my docker container, I have multiple cron jobs that need to be ran, with each doing a different thing:

Some cron jobs will import a module

Some cron jobs will activate the imported module

Finally, some cron jobs will do a cleanup

This is the order in which they should run.

Currently, cron is not a running process in my container however, including the following in my entrypoint script has it running in the foreground:

#!/bin/bash
cron -n -s -m off

With this included, it does run the cron jobs. However, a key point is that each set of cron jobs (import, activate, cleanup) uses one of three bash scripts to perform their tasks. So, for example, the cron jobs that activate a module will have the following format:

MAILTO=""
* * * * * root /tmp/moduleActivation.sh  <module> <version>

Each activation cron job will use a bash script that takes in two parameters and the bash script will activate it as so. The way these scripts are set up, only one instance can be running at any one time.

With my current setup, it will attempt to run each cron job at the same time, which is not my desired result as multiple instances of the activation script will attempt to run at the same time, which can't happen.

I am quite new to cron - how can I prevent this from happening and have the cron jobs run in the desired order? Will a crontab file take precedence in some way if I was to include one?


问:
open failed: EPERM during saving PDF file
Context and problem:

Im trying to save pdf file in external storage, but i'm getting the following error:
Caused by: android.system.ErrnoException: open failed: EPERM (Operation not permitted)

1)When user opens the app, permissions are checked:

```<code>private fun initAndCheckPermissions() {
        bmp = BitmapFactory.decodeResource(resources, R.drawable.logo_nuin_nomb_subt)
        scaledbmp = Bitmap.createScaledBitmap(bmp, 140, 140, false)
        if (checkPermissions()) {
            // if permission is granted we are displaying a toast message.
            Toast.makeText(requireContext(), "Permissions Granted..", Toast.LENGTH_SHORT).show()
        } else {
            requestPermission()
        }
    }
</code>```
```<code>fun requestPermission() {
        ActivityCompat.requestPermissions(
            requireActivity(),
            arrayOf(
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
            ), PERMISSION_CODE
        )
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == PERMISSION_CODE) {
            if (grantResults.size > 0) {
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1]
                    == PackageManager.PERMISSION_GRANTED) {
                    Toast.makeText(requireContext(), "Permission Granted..", Toast.LENGTH_SHORT).show()
                } else {
                    requireActivity().finish()
                }
            }
        }
    }

</code>```

So, when user clicks a specific button in activity.. PDF file with text and image is generated:

```<code>@RequiresApi(Build.VERSION_CODES.KITKAT)
    fun generatePDF() {
        var pdfDocument: PdfDocument = PdfDocument()
        var paint: Paint = Paint()
        var title: Paint = Paint()
        var myPageInfo: PdfDocument.PageInfo? =
            PdfDocument.PageInfo.Builder(pageWidth, pageHeight, 1).create()

        var myPage: PdfDocument.Page = pdfDocument.startPage(myPageInfo)

        var canvas: Canvas = myPage.canvas

        canvas.drawBitmap(scaledbmp, 56F, 40F, paint)

        title.typeface = Typeface.create(Typeface.DEFAULT, Typeface.NORMAL)

        title.textSize = 15F

        title.color = ContextCompat.getColor(requireContext(), R.color.purple_200)

        canvas.drawText("A portal for IT professionals.", 209F, 100F, title)
        canvas.drawText("Geeks for Geeks", 209F, 80F, title)
        title.typeface = Typeface.defaultFromStyle(Typeface.NORMAL)
        title.color = ContextCompat.getColor(requireContext(), R.color.purple_200)
        title.textSize = 15F

        title.textAlign = Paint.Align.CENTER
        canvas.drawText("This is sample document which we have created", 396F, 560F, title)

        pdfDocument.finishPage(myPage)

        val file: File = File(Environment.getExternalStorageState(), "GFG.pdf")
        pdfDocument.writeTo(FileOutputStream(file))
        Toast.makeText(requireContext(), "PDF file generated..", Toast.LENGTH_SHORT).show()
        pdfDocument.close()
    }
</code>```

Problem:

The problem is that the line
val file: File = File(Environment.getExternalStorageState(), "GFG.pdf") is causing the following error:
Caused by: android.system.ErrnoException: open failed: EPERM (Operation not permitted)

Body:
Context and problem:

Im trying to save pdf file in external storage, but i'm getting the following error:
Caused by: android.system.ErrnoException: open failed: EPERM (Operation not permitted)

1)When user opens the app, permissions are checked:

private fun initAndCheckPermissions() {
        bmp = BitmapFactory.decodeResource(resources, R.drawable.logo_nuin_nomb_subt)
        scaledbmp = Bitmap.createScaledBitmap(bmp, 140, 140, false)
        if (checkPermissions()) {
            // if permission is granted we are displaying a toast message.
            Toast.makeText(requireContext(), "Permissions Granted..", Toast.LENGTH_SHORT).show()
        } else {
            requestPermission()
        }
    }

fun requestPermission() {
        ActivityCompat.requestPermissions(
            requireActivity(),
            arrayOf(
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
            ), PERMISSION_CODE
        )
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == PERMISSION_CODE) {
            if (grantResults.size > 0) {
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1]
                    == PackageManager.PERMISSION_GRANTED) {
                    Toast.makeText(requireContext(), "Permission Granted..", Toast.LENGTH_SHORT).show()
                } else {
                    requireActivity().finish()
                }
            }
        }
    }

So, when user clicks a specific button in activity.. PDF file with text and image is generated:

@RequiresApi(Build.VERSION_CODES.KITKAT)
    fun generatePDF() {
        var pdfDocument: PdfDocument = PdfDocument()
        var paint: Paint = Paint()
        var title: Paint = Paint()
        var myPageInfo: PdfDocument.PageInfo? =
            PdfDocument.PageInfo.Builder(pageWidth, pageHeight, 1).create()

        var myPage: PdfDocument.Page = pdfDocument.startPage(myPageInfo)

        var canvas: Canvas = myPage.canvas

        canvas.drawBitmap(scaledbmp, 56F, 40F, paint)

        title.typeface = Typeface.create(Typeface.DEFAULT, Typeface.NORMAL)

        title.textSize = 15F

        title.color = ContextCompat.getColor(requireContext(), R.color.purple_200)

        canvas.drawText("A portal for IT professionals.", 209F, 100F, title)
        canvas.drawText("Geeks for Geeks", 209F, 80F, title)
        title.typeface = Typeface.defaultFromStyle(Typeface.NORMAL)
        title.color = ContextCompat.getColor(requireContext(), R.color.purple_200)
        title.textSize = 15F

        title.textAlign = Paint.Align.CENTER
        canvas.drawText("This is sample document which we have created", 396F, 560F, title)

        pdfDocument.finishPage(myPage)

        val file: File = File(Environment.getExternalStorageState(), "GFG.pdf")
        pdfDocument.writeTo(FileOutputStream(file))
        Toast.makeText(requireContext(), "PDF file generated..", Toast.LENGTH_SHORT).show()
        pdfDocument.close()
    }

Problem:

The problem is that the line
val file: File = File(Environment.getExternalStorageState(), "GFG.pdf") is causing the following error:
Caused by: android.system.ErrnoException: open failed: EPERM (Operation not permitted)


问:
How do you code a 3-dimensional object with HTML/CSS/JS? (e.g. dice)
I want to create a 3 dimensional object so that when I apply an animation with rotate3d(), the object shows its different sides.

I can do this with javascript but it gets more complicated with more sides and I wonder if there's a smarter way to do this, or if it is possible to just apply the rotate3d() and the div shows different sides automatically.

$("#div").click(function() {
  if (!($(this).attr("data-flipped"))) {
    $(this).removeClass("flip-to-front");
    $(this).addClass("flip-to-back");
    $(this).attr("data-flipped", true);
  } else {
    $(this).removeClass("flip-to-back");
    $(this).addClass("flip-to-front");
    $(this).attr("data-flipped", null);
  }
  $(this).children().toggle();
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>div {
  width: 300px;
  height: 300px;
}

#front {
  background-color: red;
}

#back {
  background-color: green;
  display: none;
}

.flip-to-back {
  animation: flip-to-back 1s;
}

@keyframes flip-to-back {
  0% {transform: rotate3d(0);}
  100% {transform: rotate3d(0, 1, 0, 180deg);}
}

.flip-to-front {
  animation: flip-to-front 1s;
}

@keyframes flip-to-front {
  0% {transform: rotate3d(0, 1, 0, 180deg);}
  100% {transform: rotate3d(0);}
}</code>```

```

Body:
I want to create a 3 dimensional object so that when I apply an animation with rotate3d(), the object shows its different sides.

I can do this with javascript but it gets more complicated with more sides and I wonder if there's a smarter way to do this, or if it is possible to just apply the rotate3d() and the div shows different sides automatically.

$("#div").click(function() {
  if (!($(this).attr("data-flipped"))) {
    $(this).removeClass("flip-to-front");
    $(this).addClass("flip-to-back");
    $(this).attr("data-flipped", true);
  } else {
    $(this).removeClass("flip-to-back");
    $(this).addClass("flip-to-front");
    $(this).attr("data-flipped", null);
  }
  $(this).children().toggle();
});

div {
  width: 300px;
  height: 300px;
}

#front {
  background-color: red;
}

#back {
  background-color: green;
  display: none;
}

.flip-to-back {
  animation: flip-to-back 1s;
}

@keyframes flip-to-back {
  0% {transform: rotate3d(0);}
  100% {transform: rotate3d(0, 1, 0, 180deg);}
}

.flip-to-front {
  animation: flip-to-front 1s;
}

@keyframes flip-to-front {
  0% {transform: rotate3d(0, 1, 0, 180deg);}
  100% {transform: rotate3d(0);}
}


问:
NoSQL injection - java server
I am trying to create a java servlet with a NoSQL injection vulnerability. I've connected the servlet with MongoDB and check if the login info submitted by the user exists, I'm doing the next query:

```<code>String andQuery = "{$and: [{user: \""+u+"\"}, {password: \""+p+"\"}]}";
</code>```

Where u is the user and p is the password given by the user.
For what I've seen this is correct, and the NoSQL injection should exist, bu I really dont kno how to prove it.

I've tried submitting with burp this:

```<code>username[$ne]=1&password[$ne]=1
</code>```

But its not working, and when I check the content of u and p after I submitted that the content of both variables is null.
I dont have the servlet configured to receive json objects so I need a solition that doesn't imply send a json object with burp.

PD: I tryed also to insert something like this:

```<code>{\"$gt\":\"\" }
</code>```

in the user and password fields but the result query is

```<code>{"$and": [{"user": "{\"$gt\":\"\" }"}, {"password": "{\"$gt\":\"\" }"}]}
</code>```

I guess this doesn't work because the {"$gt":"" } is in quotes, ¿how can I do the servlet to be vulnarable and with which input it would be vulnerabel?

Title: NoSQL injection - java server

Body:
I am trying to create a java servlet with a NoSQL injection vulnerability. I've connected the servlet with MongoDB and check if the login info submitted by the user exists, I'm doing the next query:

String andQuery = "{$and: [{user: \""+u+"\"}, {password: \""+p+"\"}]}";

Where u is the user and p is the password given by the user.
For what I've seen this is correct, and the NoSQL injection should exist, bu I really dont kno how to prove it.

I've tried submitting with burp this:

username[$ne]=1&password[$ne]=1

But its not working, and when I check the content of u and p after I submitted that the content of both variables is null.
I dont have the servlet configured to receive json objects so I need a solition that doesn't imply send a json object with burp.

PD: I tryed also to insert something like this:

{\"$gt\":\"\" }

in the user and password fields but the result query is

{"$and": [{"user": "{\"$gt\":\"\" }"}, {"password": "{\"$gt\":\"\" }"}]}

I guess this doesn't work because the {"$gt":"" } is in quotes, ¿how can I do the servlet to be vulnarable and with which input it would be vulnerabel?


问:
Can't divide by function for use in ordinary differential equations
I'm a first year maths and physics student and have next to no experience in python and this is my first time working with SciPy.
This is why I ran into some trouble when trying to handle ODEs;
My Problem is that I'm not able to divide by a previously defined function for use in another ODE.

I tried replacing dvdt with the code from the return statement in the previously defined function dvdt but that doesn't work since v is not defined inside dxdt.
Casting dvdt to float also doesn't work, since I can't cast to a function.

I'm absolutely clueless about what to do, so I turned to StackOverflow in hopes of getting some suggestions :O).

This is my code:

```<code>from scipy import integrate
import numpy as np
import matplotlib.pyplot as plt
import math

def dvdt(t, v):

    k = 0.3
    Fs = 200000
    m0 = 10000
    lam = 200

    return (Fs + k*v**2) / (m0 - lam*t)

v0 = 0

def dxdt(t, x):

    k = 0.3
    Fs = 200000
    m0 = 10000
    lam = 200

    # This is where the Problem arises.

    return math.sqrt(Fs / (dvdt*k))

# Inserting ((Fs + k*v**2) / (m0 - lam*t)) for dvdt didn't help either, since v is not defined inside dxdt :/

x0 = 0

t = np.linspace(0, 30, 100)

sol_v = integrate.solve_ivp(dvdt, t_span = (0, max(t)), y0=[v0], t_eval=t)
v_sol = sol_v.y[0]

sol_x = integrate.solve_ivp(dxdt, t_span = (0, max(t)), y0=[x0], t_eval=t)
x_sol = sol_x.y[0]

plt.plot(t, v_sol)
plt.ylabel('$v(t)$', fontsize=22)
plt.xlabel('$t$', fontsize=22)

plt.plot(t, x_sol)
plt.ylabel('$x(t)$', fontsize=22)
plt.xlabel('$t$', fontsize=22)

plt.show()

</code>```

Corrected code:

```<code>from scipy import integrate
import numpy as np
import matplotlib.pyplot as plt
import math

def dvdt(t, v):

    k = 0.3
    Fs = 200000
    m0 = 10000
    lam = 200

    return (Fs + k*v**2) / (m0 - lam*t)

v0 = 0

def dxdt(t, x):

    k = 0.3
    Fs = 200000
    m0 = 10000
    lam = 200

    return math.sqrt(Fs / (dvdt(t, 0)*k))

x0 = 0

t = np.linspace(0, 30, 100)

sol_v = integrate.solve_ivp(dvdt, t_span = (0, max(t)), y0=[v0], t_eval=t)
v_sol = sol_v.y[0]

sol_x = integrate.solve_ivp(dxdt, t_span = (0, max(t)), y0=[x0], t_eval=t)
x_sol = sol_x.y[0]

plt.plot(t, v_sol, label="v(t)")
plt.plot(t, x_sol, label="x(t)")

plt.ylabel('Geschwindigkeit', fontsize=15)
plt.xlabel('Zeit', fontsize=15)

plt.legend(["v(t) - Geschwindigkeit", "x(t) - Höhe"])
plt.title("Verhalten der Rakete")
plt.show()
</code>```

Body:
I'm a first year maths and physics student and have next to no experience in python and this is my first time working with SciPy.
This is why I ran into some trouble when trying to handle ODEs;
My Problem is that I'm not able to divide by a previously defined function for use in another ODE.

I tried replacing dvdt with the code from the return statement in the previously defined function dvdt but that doesn't work since v is not defined inside dxdt.
Casting dvdt to float also doesn't work, since I can't cast to a function.

I'm absolutely clueless about what to do, so I turned to StackOverflow in hopes of getting some suggestions :O).

This is my code:

from scipy import integrate
import numpy as np
import matplotlib.pyplot as plt
import math

def dvdt(t, v):

    k = 0.3
    Fs = 200000
    m0 = 10000
    lam = 200

    return (Fs + k*v**2) / (m0 - lam*t)

v0 = 0

def dxdt(t, x):

    k = 0.3
    Fs = 200000
    m0 = 10000
    lam = 200

    # This is where the Problem arises.

    return math.sqrt(Fs / (dvdt*k))

# Inserting ((Fs + k*v**2) / (m0 - lam*t)) for dvdt didn't help either, since v is not defined inside dxdt :/

x0 = 0

t = np.linspace(0, 30, 100)

sol_v = integrate.solve_ivp(dvdt, t_span = (0, max(t)), y0=[v0], t_eval=t)
v_sol = sol_v.y[0]

sol_x = integrate.solve_ivp(dxdt, t_span = (0, max(t)), y0=[x0], t_eval=t)
x_sol = sol_x.y[0]

plt.plot(t, v_sol)
plt.ylabel('$v(t)$', fontsize=22)
plt.xlabel('$t$', fontsize=22)

plt.plot(t, x_sol)
plt.ylabel('$x(t)$', fontsize=22)
plt.xlabel('$t$', fontsize=22)

plt.show()

Corrected code:

from scipy import integrate
import numpy as np
import matplotlib.pyplot as plt
import math

def dvdt(t, v):

    k = 0.3
    Fs = 200000
    m0 = 10000
    lam = 200

    return (Fs + k*v**2) / (m0 - lam*t)

v0 = 0

def dxdt(t, x):

    k = 0.3
    Fs = 200000
    m0 = 10000
    lam = 200

    return math.sqrt(Fs / (dvdt(t, 0)*k))

x0 = 0

t = np.linspace(0, 30, 100)

sol_v = integrate.solve_ivp(dvdt, t_span = (0, max(t)), y0=[v0], t_eval=t)
v_sol = sol_v.y[0]

sol_x = integrate.solve_ivp(dxdt, t_span = (0, max(t)), y0=[x0], t_eval=t)
x_sol = sol_x.y[0]

plt.plot(t, v_sol, label="v(t)")
plt.plot(t, x_sol, label="x(t)")

plt.ylabel('Geschwindigkeit', fontsize=15)
plt.xlabel('Zeit', fontsize=15)

plt.legend(["v(t) - Geschwindigkeit", "x(t) - Höhe"])
plt.title("Verhalten der Rakete")
plt.show()


问:
Python Requests POST timeout prematurely closed connection
I'm doing some file uploads that sends to an nginx reverse proxy.  If I set the python requests timeout to 10 seconds and upload a large file, nginx will report client prematurely closed connection and forward an empty body to the server.  If I remove the requests timeout, the file uploads without any issues.  As I understand it, the timeout should only apply if the client fails to receive or send any bytes, which I don't believe is the case as it's in the middle of uploading the file.  It seems to behave more like a time limit, cutting the connection after 10 seconds with no exception being raised by requests.  Is sending bytes different than reading bytes for timeout?  I haven't set anything for stream or tried any type of multi-part.  I would like to set a timeout but confused as to why the connection is getting aborted early - thanks for any help.


问:
how to allow amount filed with leading zero with open API swagger definition
how to Allow leading zero's,
I am getting the below exception,

```<code>Caused by: org.springframework.core.codec.DecodingException: JSON decoding error: Invalid numeric value: Leading zeroes not allowed; nested exception is com.fasterxml.jackson.core.JsonParseException: Invalid numeric value: Leading zeroes not allowed
 at [Source: (org.springframework.core.io.buffer.DefaultDataBuffer$DefaultDataBufferInputStream); line: 4, column: 21]
</code>```

the swagger definition for the amount with Regex,

```<code> "amount": {
      "type": "number",
      "description": "The amount of tnx",
      "pattern" : "^-?[0-9]*(\\.([0-9]{1,2}))?$",
      "example" : "9999.99"
    },
</code>```

Working test:
"amount": 6.81

not Working test with exception:
"amount": 06.81

Body:
how to Allow leading zero's,
I am getting the below exception,

Caused by: org.springframework.core.codec.DecodingException: JSON decoding error: Invalid numeric value: Leading zeroes not allowed; nested exception is com.fasterxml.jackson.core.JsonParseException: Invalid numeric value: Leading zeroes not allowed
 at [Source: (org.springframework.core.io.buffer.DefaultDataBuffer$DefaultDataBufferInputStream); line: 4, column: 21]

the swagger definition for the amount with Regex,

 "amount": {
      "type": "number",
      "description": "The amount of tnx",
      "pattern" : "^-?[0-9]*(\\.([0-9]{1,2}))?$",
      "example" : "9999.99"
    },

Working test:
"amount": 6.81

not Working test with exception:
"amount": 06.81


问:
Clustering geospatial data on equal distance coordinates but with a non spatial feature which can be used as weight for distance
I have a dataset that looks like this. It has an equal distance of 180x360 (latxlon) coordinates at one-degree resolution with an additional column for value at each lat-lon pair which is unique (varies from 0 to 1).

```<code>    Lat Lon Val
0   1   1   0.510007
1   1   2   0.720702
2   1   3   0.910986
3   1   4   0.910000
4   1   5   0.992826
5   2   1   0.132230
6   2   2   0.086200
7   2   3   0.910000
8   2   4   0.920000
9   2   5   0.990000
10  3   1   0.447686
11  3   2   0.157000
12  3   3   0.543912
13  3   4   0.993600
14  3   5   0.379585
15  4   1   0.110000
16  4   2   0.125600
17  4   3   0.175600
18  4   4   0.735500
19  4   5   0.590000
20  5   1   0.990117
21  5   2   0.162610
22  5   3   0.749480
23  5   4   0.726996
24  5   5   0.599000
</code>```

Since the distance between points is the same, Using this additional column (Val), I want to apply DBSCAN clustering.

```<code>from sklearn.cluster import DBSCAN
import pandas as pd
import matplotlib.pyplot as plt
df=pd.read_excel('corr.xlsx')

import numpy as np
from sklearn.metrics.pairwise import haversine_distances
from sklearn.metrics.pairwise import euclidean_distances

points_in_radians = df[['Lat','Lon']].apply(np.radians).values
distances_in_km = haversine_distances(points_in_radians) * 6371

distances2 = euclidean_distances(df[['Val']].values)
distances=distances_in_km + distances2
distances

clustering = DBSCAN(metric='precomputed', eps=111.2, min_samples=3)
df['Cluster'] = clustering.fit_predict(distances)
print(f"Found {df['Cluster'].nunique()} clusters \n")
df

import seaborn as sns
import matplotlib.pyplot as plt
p = sns.scatterplot(data=df[['Lat','Lon','Cluster']], x="Lat", y="Lon", hue=df['Cluster'], legend="full", palette="deep")
sns.move_legend(p, "upper right", bbox_to_anchor=(1.17, 1.2), title='Clusters')
plt.show()
</code>```

I am getting the correct clusters. I am not able to find where I'm doing wrong.

Body:
I have a dataset that looks like this. It has an equal distance of 180x360 (latxlon) coordinates at one-degree resolution with an additional column for value at each lat-lon pair which is unique (varies from 0 to 1).

    Lat Lon Val
0   1   1   0.510007
1   1   2   0.720702
2   1   3   0.910986
3   1   4   0.910000
4   1   5   0.992826
5   2   1   0.132230
6   2   2   0.086200
7   2   3   0.910000
8   2   4   0.920000
9   2   5   0.990000
10  3   1   0.447686
11  3   2   0.157000
12  3   3   0.543912
13  3   4   0.993600
14  3   5   0.379585
15  4   1   0.110000
16  4   2   0.125600
17  4   3   0.175600
18  4   4   0.735500
19  4   5   0.590000
20  5   1   0.990117
21  5   2   0.162610
22  5   3   0.749480
23  5   4   0.726996
24  5   5   0.599000

Since the distance between points is the same, Using this additional column (Val), I want to apply DBSCAN clustering.

from sklearn.cluster import DBSCAN
import pandas as pd
import matplotlib.pyplot as plt
df=pd.read_excel('corr.xlsx')

import numpy as np
from sklearn.metrics.pairwise import haversine_distances
from sklearn.metrics.pairwise import euclidean_distances

points_in_radians = df[['Lat','Lon']].apply(np.radians).values
distances_in_km = haversine_distances(points_in_radians) * 6371

distances2 = euclidean_distances(df[['Val']].values)
distances=distances_in_km + distances2
distances

clustering = DBSCAN(metric='precomputed', eps=111.2, min_samples=3)
df['Cluster'] = clustering.fit_predict(distances)
print(f"Found {df['Cluster'].nunique()} clusters \n")
df

import seaborn as sns
import matplotlib.pyplot as plt
p = sns.scatterplot(data=df[['Lat','Lon','Cluster']], x="Lat", y="Lon", hue=df['Cluster'], legend="full", palette="deep")
sns.move_legend(p, "upper right", bbox_to_anchor=(1.17, 1.2), title='Clusters')
plt.show()

I am getting the correct clusters. I am not able to find where I'm doing wrong.


问:
MongoDB POJO in Java producing empty document and not using fields
I'm using MongoDB's POJO encoder, but it's not working. it's returning an empty document only containing an _id. i have enabled the Convention for annotation based POJOs, i also enabled the private field convention so that it uses reflection for private fields. I also know that it was using the getters instead of fields, since it did work before i put @BsonIgnore on my getters, but i modify data in a getter so this is not desirable for me. Here's my code for the class i want to serialize:

```<code>public class PermissionPlayer {
    public static final String MONGO_COLLECTION = "permission_players";

    @BsonProperty( "uuid")
    private UUID uuid;

    @BsonProperty( "groupNames")
    private List<String> groupNames = new ArrayList<>();

    @BsonProperty( "permissions")
    private List<String> perms = new ArrayList<>();

    @BsonIgnore
    private List<PermissionGroup> groups = new ArrayList<>();

    @BsonCreator
    public PermissionPlayer(@BsonProperty( "uuid") UUID uuid, @BsonProperty( "groupNames") List<String> groupNames, @BsonProperty( "permissions") List<String> perms) {
        this.uuid = uuid;
        this.groupNames = groupNames == null ? new ArrayList<>() : groupNames;
        this.perms = perms;
        loadGroups();
    }

    @BsonIgnore
    public void loadGroups() {
        groups = new ArrayList<>();
        for (String s : groupNames)
            groups.add(PermissionManager.get().getGroup(s));
        groups.removeIf(Objects::isNull);
        Collections.sort(groups);
    }

    public PermissionPlayer(UUID uuid) {
        this.uuid = uuid;
    }

    @BsonIgnore
    public void removePermission(String permission) {
        perms.remove(permission);
    }

    @BsonIgnore
    public void addPermission(String permission) {
        perms.add(permission);
    }

    @BsonIgnore
    public List<String> getPermissions() {
        List<String> permissions = new ArrayList<>(); // individually set perms
        permissions.addAll(perms);
        for (PermissionGroup g : groups) {
            permissions.addAll(g.getPermissions());
</code>```

and here is the Mongo class for database access & how i construct the client:

```<code>public class Mongo {

    private static MongoClient client = null;
    private static MongoDatabase database = null;

    public static final CodecRegistry codecRegistry = CodecRegistries.fromRegistries(
            MongoClientSettings.builder().uuidRepresentation(UuidRepresentation.STANDARD).build().getCodecRegistry(),
            CodecRegistries.fromProviders(PojoCodecProvider.builder()
                    .conventions(Arrays.asList(Conventions.ANNOTATION_CONVENTION, Conventions.SET_PRIVATE_FIELDS_CONVENTION)).automatic(true).build())
    );

    public static void connectDatabase() {
        String db = Main.env.get("DATABASE_NAME");
        String uri = Main.env.get("DATABASE_URL");
        client = MongoClients.create(MongoClientSettings.builder().applyConnectionString(new ConnectionString(uri)).
                uuidRepresentation(UuidRepresentation.STANDARD).codecRegistry(codecRegistry).build());

        database = client.getDatabase(db);
    }

    public static MongoCollection<Document> getCollection(String name) {
        return database.getCollection(name.toLowerCase());
    }

    public static MongoDatabase getDatabase() {
        return database;
    }
}
</code>```

I have tried changing the Conventions to no avail. also i have followed an article on this by MongoDB itself which you can find here.

Body:
I'm using MongoDB's POJO encoder, but it's not working. it's returning an empty document only containing an _id. i have enabled the Convention for annotation based POJOs, i also enabled the private field convention so that it uses reflection for private fields. I also know that it was using the getters instead of fields, since it did work before i put @BsonIgnore on my getters, but i modify data in a getter so this is not desirable for me. Here's my code for the class i want to serialize:

public class PermissionPlayer {
    public static final String MONGO_COLLECTION = "permission_players";

    @BsonProperty( "uuid")
    private UUID uuid;

    @BsonProperty( "groupNames")
    private List<String> groupNames = new ArrayList<>();

    @BsonProperty( "permissions")
    private List<String> perms = new ArrayList<>();

    @BsonIgnore
    private List<PermissionGroup> groups = new ArrayList<>();

    @BsonCreator
    public PermissionPlayer(@BsonProperty( "uuid") UUID uuid, @BsonProperty( "groupNames") List<String> groupNames, @BsonProperty( "permissions") List<String> perms) {
        this.uuid = uuid;
        this.groupNames = groupNames == null ? new ArrayList<>() : groupNames;
        this.perms = perms;
        loadGroups();
    }

    @BsonIgnore
    public void loadGroups() {
        groups = new ArrayList<>();
        for (String s : groupNames)
            groups.add(PermissionManager.get().getGroup(s));
        groups.removeIf(Objects::isNull);
        Collections.sort(groups);
    }

    public PermissionPlayer(UUID uuid) {
        this.uuid = uuid;
    }

    @BsonIgnore
    public void removePermission(String permission) {
        perms.remove(permission);
    }

    @BsonIgnore
    public void addPermission(String permission) {
        perms.add(permission);
    }

    @BsonIgnore
    public List<String> getPermissions() {
        List<String> permissions = new ArrayList<>(); // individually set perms
        permissions.addAll(perms);
        for (PermissionGroup g : groups) {
            permissions.addAll(g.getPermissions());

and here is the Mongo class for database access & how i construct the client:

public class Mongo {

    private static MongoClient client = null;
    private static MongoDatabase database = null;

    public static final CodecRegistry codecRegistry = CodecRegistries.fromRegistries(
            MongoClientSettings.builder().uuidRepresentation(UuidRepresentation.STANDARD).build().getCodecRegistry(),
            CodecRegistries.fromProviders(PojoCodecProvider.builder()
                    .conventions(Arrays.asList(Conventions.ANNOTATION_CONVENTION, Conventions.SET_PRIVATE_FIELDS_CONVENTION)).automatic(true).build())
    );

    public static void connectDatabase() {
        String db = Main.env.get("DATABASE_NAME");
        String uri = Main.env.get("DATABASE_URL");
        client = MongoClients.create(MongoClientSettings.builder().applyConnectionString(new ConnectionString(uri)).
                uuidRepresentation(UuidRepresentation.STANDARD).codecRegistry(codecRegistry).build());

        database = client.getDatabase(db);
    }

    public static MongoCollection<Document> getCollection(String name) {
        return database.getCollection(name.toLowerCase());
    }

    public static MongoDatabase getDatabase() {
        return database;
    }
}

I have tried changing the Conventions to no avail. also i have followed an article on this by MongoDB itself which you can find here.


问:
How to deal with discrepancy in csv and pandas Df?
when i load the dataset on pandas it shows 1,00,000 rows but when i open it on excel it shows 3,00,000 rows ? is there any python code that could help me in dealing with this kind of discrepancy</p>
```<code>import pandas as pd
df=pd.read_csv('C_data_2.csv')

</code>```
```<code># Get the counts of each value in the gender column
counts = df['Gender'].value_counts()

# Find the most common value in the gender column
most_common = counts.index[0]

# Impute missing values in the gender column with the most common value
df['Gender'] = df['Gender'].fillna(most_common)

# Replace all instances of "nan" with most_common in the "gender" column
df["Gender"].replace("nan", most_common, inplace=True)
</code>```

Body:
when i load the dataset on pandas it shows 1,00,000 rows but when i open it on excel it shows 3,00,000 rows ? is there any python code that could help me in dealing with this kind of discrepancy

import pandas as pd
df=pd.read_csv('C_data_2.csv')

# Get the counts of each value in the gender column
counts = df['Gender'].value_counts()

# Find the most common value in the gender column
most_common = counts.index[0]

# Impute missing values in the gender column with the most common value
df['Gender'] = df['Gender'].fillna(most_common)

# Replace all instances of "nan" with most_common in the "gender" column
df["Gender"].replace("nan", most_common, inplace=True)


问:
Laravel DOMPDF RTL text space
Hi I am using DOMPDF and trying to creating a invoice with it. everything working even with RTL Arabic font except text-align:left; does not working properly there is a space which i can see Not sure why this space is visible.

Using DejaVuSans fonts.

Below is the code which generate below columns:

```<code>        <tr>
            <td width="50%">
                <p class="line-height mt-1 mb-0 f-14 text-black" style="text-align: left;direction: ltr;">
                    @if (!is_null($invoice->project) && !is_null($invoice->project->client))
                    @php
                        $client = $invoice->project;
                    @endphp
                    @elseif(!is_null($invoice->client_id) && !is_null($invoice->clientdetails))
                        @php
                            $client = $invoice->client;
                        @endphp
                    @endif

                    <br><?php echo Lang::get('app.from',[],'en'); ?>: {{ ucwords($company_name_en) }}
                    @if (!is_null($settings))
                    <br><?php echo Lang::get('app.address',[],'en'); ?>: {!! nl2br($company_address_en) !!}
                    <br><?php echo Lang::get('app.phone',[],'en'); ?>: {{ $global->company_phone }}
                    @endif
                    @if ($invoiceSetting->show_gst == 'yes' && !is_null($invoiceSetting->gst_number))
                       <br><?php echo Lang::get('app.gstIn',[],'en'); ?>: {{ $invoiceSetting->gst_number }}
                    @endif
                    <br><?php echo Lang::get('modules.invoices.invoiceNumber',[],'en'); ?>: <?php echo str_replace("فاتورة","Invoice",$invoice->invoice_number); ?>
                    @if ($creditNote)
                        <br><?php echo Lang::get('app.credit-note',[],'en'); ?>: {{ $creditNote->cn_number }}
                    @endif
                    <br><?php echo Lang::get('modules.invoices.invoiceDate',[],'en'); ?>: {{ $invoice->issue_date->format($company->date_format) }}
                    <br><?php echo Lang::get('app.dueDate',[],'en'); ?>: {{ $invoice->due_date->format($company->date_format) }}
                    <br><strong><?php echo Lang::get('app.client',[],'en'); ?>:</strong>
                    @if(isset($client))
                        <br><?php echo Lang::get('app.company_name',[],'en'); ?>: {{ ucwords($client->client_details->company_name) }}
                        <br><?php echo Lang::get('app.address',[],'en'); ?>: {!! nl2br($client->client_details->address) !!}
                        @else
                    @endif
                    @if ($invoiceSetting->show_gst == 'yes' && !is_null($client->client_details->gst_number))
                        <br><?php echo Lang::get('app.gstIn',[],'en'); ?>: {{ $client->client_details->gst_number }}
                    @endif
                    @if ($invoiceSetting->show_gst == 'yes' && !is_null($client->client_details->cr_number))
                        <br><?php echo Lang::get('app.crNumber',[],'en'); ?>: {{ $client->client_details->cr_number }}
                    @endif
                    @if ($invoice->show_shipping_address === 'yes')
                        <br><?php echo Lang::get('app.shippingAddress',[],'en'); ?>: {!! nl2br($client->client_details->address) !!}
                    @endif
                    <br><?php echo Lang::get('app.invoice',[],'en'); ?> <?php echo Lang::get('app.status',[],'en'); ?>: <?php echo Lang::get('app.'.$invoice->status,[],'en'); ?>
                </p>
            </td>
            <td width="50%">
                    <p class="line-height mt-1 mb-0 f-13 text-black text-right fixfonts" style="direction:ltr;text-align: right;float:right;left:auto;right:0;">
                        @if (!is_null($invoice->project) && !is_null($invoice->project->client))
                        @php
                            $client = $invoice->project;
                        @endphp
                        @elseif(!is_null($invoice->client_id) && !is_null($invoice->clientdetails))
                            @php
                                $client = $invoice->client;
                            @endphp
                        @endif

                        <br><?php echo Lang::get('app.from',[],'ar'); ?>: {{ nl2br($company_name_ar) }}
                        @if (!is_null($settings))
                        <br><?php echo Lang::get('app.address',[],'ar'); ?>: {!! nl2br($company_address_ar) !!}
                        <br><?php echo Lang::get('app.phone',[],'ar'); ?>: {{ $global->company_phone }}
                        @endif
                        @if ($invoiceSetting->show_gst == 'yes' && !is_null($invoiceSetting->gst_number))
                        <br><?php echo Lang::get('app.gstIn',[],'ar'); ?>: {{ $invoiceSetting->gst_number }}
                        @endif
                        <br><?php echo Lang::get('modules.invoices.invoiceNumber',[],'ar'); ?>: {{ $invoice->invoice_number }}
                        @if ($creditNote)
                            <br><?php echo Lang::get('app.credit-note',[],'ar'); ?>: {{ $creditNote->cn_number }}
                        @endif
                        <br><?php echo Lang::get('modules.invoices.invoiceDate',[],'ar'); ?>: {{ $invoice->issue_date->format($company->date_format) }}
                        <br><?php echo Lang::get('app.dueDate',[],'ar'); ?>: {{ $invoice->due_date->format($company->date_format) }}
                        <br><strong><?php echo Lang::get('app.client',[],'ar'); ?>:</strong>
                        @if(isset($client))
                            <br><?php echo Lang::get('app.company_name',[],'ar'); ?>: {{ ucwords($client->client_details->company_name) }}
                            <br><?php echo Lang::get('app.address',[],'ar'); ?>: {!! nl2br($client->client_details->address) !!}
                            @else
                        @endif
                        @if ($invoiceSetting->show_gst == 'yes' && !is_null($client->client_details->gst_number))
                            <br><?php echo Lang::get('app.gstIn',[],'ar'); ?>: {{ $client->client_details->gst_number }}
                        @endif
                        @if ($invoiceSetting->show_gst == 'yes' && !is_null($client->client_details->cr_number))
                            <br><?php echo Lang::get('app.crNumber',[],'ar'); ?>: {{ $client->client_details->cr_number }}
                        @endif
                        @if ($invoice->show_shipping_address === 'yes')
                            <br><?php echo Lang::get('app.shippingAddress',[],'ar'); ?>: {!! nl2br($client->client_details->address) !!}
                        @endif
                        <br><?php echo Lang::get('app.invoice',[],'ar'); ?> <?php echo Lang::get('app.status',[],'ar'); ?>: <?php echo Lang::get('app.'.$invoice->status,[],'ar'); ?>
                    </p>
            </td>
        </tr>
</code>```

How to remove this space in arabic text on right side.

Title: Laravel DOMPDF RTL text space

Body:
Hi I am using DOMPDF and trying to creating a invoice with it. everything working even with RTL Arabic font except text-align:left; does not working properly there is a space which i can see Not sure why this space is visible.

Using DejaVuSans fonts.

Below is the code which generate below columns:

                    @if (!is_null($invoice->project) && !is_null($invoice->project->client))
                    @php
                        $client = $invoice->project;
                    @endphp
                    @elseif(!is_null($invoice->client_id) && !is_null($invoice->clientdetails))
                        @php
                            $client = $invoice->client;
                        @endphp
                    @endif

<?php echo Lang::get('app.from',[],'en'); ?>: {{ ucwords($company_name_en) }}
                    @if (!is_null($settings))

<?php echo Lang::get('app.address',[],'en'); ?>: {!! nl2br($company_address_en) !!}

<?php echo Lang::get('app.phone',[],'en'); ?>: {{ $global->company_phone }}
                    @endif
                    @if ($invoiceSetting->show_gst == 'yes' && !is_null($invoiceSetting->gst_number))

<?php echo Lang::get('app.gstIn',[],'en'); ?>: {{ $invoiceSetting->gst_number }}
                    @endif

<?php echo Lang::get('modules.invoices.invoiceNumber',[],'en'); ?>: <?php echo str_replace("فاتورة","Invoice",$invoice->invoice_number); ?>
                    @if ($creditNote)

<?php echo Lang::get('app.credit-note',[],'en'); ?>: {{ $creditNote->cn_number }}
                    @endif

<?php echo Lang::get('modules.invoices.invoiceDate',[],'en'); ?>: {{ $invoice->issue_date->format($company->date_format) }}

<?php echo Lang::get('app.dueDate',[],'en'); ?>: {{ $invoice->due_date->format($company->date_format) }}

<?php echo Lang::get('app.client',[],'en'); ?>:
                    @if(isset($client))

<?php echo Lang::get('app.company_name',[],'en'); ?>: {{ ucwords($client->client_details->company_name) }}

<?php echo Lang::get('app.address',[],'en'); ?>: {!! nl2br($client->client_details->address) !!}
                        @else
                    @endif
                    @if ($invoiceSetting->show_gst == 'yes' && !is_null($client->client_details->gst_number))

<?php echo Lang::get('app.gstIn',[],'en'); ?>: {{ $client->client_details->gst_number }}
                    @endif
                    @if ($invoiceSetting->show_gst == 'yes' && !is_null($client->client_details->cr_number))

<?php echo Lang::get('app.crNumber',[],'en'); ?>: {{ $client->client_details->cr_number }}
                    @endif
                    @if ($invoice->show_shipping_address === 'yes')

<?php echo Lang::get('app.shippingAddress',[],'en'); ?>: {!! nl2br($client->client_details->address) !!}
                    @endif

<?php echo Lang::get('app.invoice',[],'en'); ?> <?php echo Lang::get('app.status',[],'en'); ?>: <?php echo Lang::get('app.'.$invoice->status,[],'en'); ?>

                        @if (!is_null($invoice->project) && !is_null($invoice->project->client))
                        @php
                            $client = $invoice->project;
                        @endphp
                        @elseif(!is_null($invoice->client_id) && !is_null($invoice->clientdetails))
                            @php
                                $client = $invoice->client;
                            @endphp
                        @endif

<?php echo Lang::get('app.from',[],'ar'); ?>: {{ nl2br($company_name_ar) }}
                        @if (!is_null($settings))

<?php echo Lang::get('app.address',[],'ar'); ?>: {!! nl2br($company_address_ar) !!}

<?php echo Lang::get('app.phone',[],'ar'); ?>: {{ $global->company_phone }}
                        @endif
                        @if ($invoiceSetting->show_gst == 'yes' && !is_null($invoiceSetting->gst_number))

<?php echo Lang::get('app.gstIn',[],'ar'); ?>: {{ $invoiceSetting->gst_number }}
                        @endif

<?php echo Lang::get('modules.invoices.invoiceNumber',[],'ar'); ?>: {{ $invoice->invoice_number }}
                        @if ($creditNote)

<?php echo Lang::get('app.credit-note',[],'ar'); ?>: {{ $creditNote->cn_number }}
                        @endif

<?php echo Lang::get('modules.invoices.invoiceDate',[],'ar'); ?>: {{ $invoice->issue_date->format($company->date_format) }}

<?php echo Lang::get('app.dueDate',[],'ar'); ?>: {{ $invoice->due_date->format($company->date_format) }}

<?php echo Lang::get('app.client',[],'ar'); ?>:
                        @if(isset($client))

<?php echo Lang::get('app.company_name',[],'ar'); ?>: {{ ucwords($client->client_details->company_name) }}

<?php echo Lang::get('app.address',[],'ar'); ?>: {!! nl2br($client->client_details->address) !!}
                            @else
                        @endif
                        @if ($invoiceSetting->show_gst == 'yes' && !is_null($client->client_details->gst_number))

<?php echo Lang::get('app.gstIn',[],'ar'); ?>: {{ $client->client_details->gst_number }}
                        @endif
                        @if ($invoiceSetting->show_gst == 'yes' && !is_null($client->client_details->cr_number))

<?php echo Lang::get('app.crNumber',[],'ar'); ?>: {{ $client->client_details->cr_number }}
                        @endif
                        @if ($invoice->show_shipping_address === 'yes')

<?php echo Lang::get('app.shippingAddress',[],'ar'); ?>: {!! nl2br($client->client_details->address) !!}
                        @endif

<?php echo Lang::get('app.invoice',[],'ar'); ?> <?php echo Lang::get('app.status',[],'ar'); ?>: <?php echo Lang::get('app.'.$invoice->status,[],'ar'); ?>

How to remove this space in arabic text on right side.


问:
Unable to augment next-auth module: property 'id' does not exist on User
I'm trying to augment the User interface from the next-auth module via the next-auth.d.ts file. There I'm adding the username field, but when I do I get the following error:

This is my next-auth.d.ts file:

import "next-auth";
import { ISODateString } from "next-auth";

declare module "next-auth" {
  interface User {
    username: string;
  }

  interface Session {
    user: User;
    expires: ISODateString;
  }
}```
</div>
</div>
</p>
<p>This is my user.ts resolver file where the error happens on line 26:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import { User } from "next-auth";
import {
  CreateUsernameResponseInterface,
  GraphQLContextInterface,
} from "../../interfaces/graphqlInterfaces";

const userResolvers = {
  Query: {
    searchUsers: () => {},
  },
  Mutation: {
    createUsername: async (
      parent: any,
      args: { username: string },
      contextValue: GraphQLContextInterface,
      info: any
    ): Promise<CreateUsernameResponseInterface> => {
      const { username } = args;
      const { prisma, session } = contextValue;

      if (!session?.user) {
        return {
          error: "Not authorized",
        };
      }
      const { id: userId } = session.user;

      try {
        // check that username is available
        const existingUser = await prisma.user.findUnique({
          where: { username },
        });
        if (existingUser) {
          return {
            error: "Username already taken. Try another",
          };
        }

        const user = await prisma.user.update({
          where: { id: userId },
          data: { username },
        });
        if (user) {
          return { success: true };
        }

        // update user
      } catch (error: any) {
        return {
          error: error?.message,
        };
      }
    },
  },
};

export default userResolvers;</code>```

If on line 26 I explicitly cast session.user as User, the error disappears. But I don't understand why it is appearing in the first place.

Body:
I'm trying to augment the User interface from the next-auth module via the next-auth.d.ts file. There I'm adding the username field, but when I do I get the following error:

This is my next-auth.d.ts file:

import "next-auth";
import { ISODateString } from "next-auth";

declare module "next-auth" {
  interface User {
    username: string;
  }

  interface Session {
    user: User;
    expires: ISODateString;
  }
}

This is my user.ts resolver file where the error happens on line 26:

import { User } from "next-auth";
import {
  CreateUsernameResponseInterface,
  GraphQLContextInterface,
} from "../../interfaces/graphqlInterfaces";

const userResolvers = {
  Query: {
    searchUsers: () => {},
  },
  Mutation: {
    createUsername: async (
      parent: any,
      args: { username: string },
      contextValue: GraphQLContextInterface,
      info: any
    ): Promise<CreateUsernameResponseInterface> => {
      const { username } = args;
      const { prisma, session } = contextValue;

      if (!session?.user) {
        return {
          error: "Not authorized",
        };
      }
      const { id: userId } = session.user;

      try {
        // check that username is available
        const existingUser = await prisma.user.findUnique({
          where: { username },
        });
        if (existingUser) {
          return {
            error: "Username already taken. Try another",
          };
        }

        const user = await prisma.user.update({
          where: { id: userId },
          data: { username },
        });
        if (user) {
          return { success: true };
        }

        // update user
      } catch (error: any) {
        return {
          error: error?.message,
        };
      }
    },
  },
};

export default userResolvers;

If on line 26 I explicitly cast session.user as User, the error disappears. But I don't understand why it is appearing in the first place.


问:
Error adding information to the database using an API
I'm trying to enter an appointment into a calendar. I'm using a laravel api but I'm sure the problem is in the DateTime because with other formats like String, ind and bool it works normally. I'm still new to programming and would be very grateful if you could help me.

This is the error

```<code>[ERROR:flutter/lib/ui/ui_dart_state.cc(198)] Unhandled Exception: NoSuchMethodError: Class '_CompactLinkedHashSet<String>' has no instance method '[]'.
Receiver: _LinkedHashSet len:1
Tried calling: []("data")
#0      Object.noSuchMethod (dart:core-patch/object_patch.dart:38:5)
#1      CallsRepository.addCallCommitments (package:project_002_italian_citizenship/src/pages/calls/repository/calls_repository.dart:129:16)
<asynchronous suspension>
#2      CallsController.addCallCommitments (package:project_002_italian_citizenship/src/pages/calls/controller/calls_controller.dart:173:35)
<asynchronous suspension>
</code>```

Repository

```<code>Future<OverallResults<Map<String, dynamic>>> addCallCommitments({
    required String token,
    required int idUser,
    required String name,
    required DateTime start,
    required DateTime finish,
    required int color,
    required bool isAllDay,
  }) async {
    final result = await _httpManager.restRequest(
      url: EndPoints.callsCommitments,
      method: HttpMethods.post,
      headers: {'Authorization': 'Bearer $token'},
      body: {
        "id_user": idUser,
        "name": name,
        "start": start,
        "finish": finish,
        "color": color,
        "is_all_day": isAllDay,
      },
    );

    if (result ['data'] != null) {
      return OverallResults<Map<String, dynamic>>.success(result ['data']);
    } else {
      return OverallResults.error(
        'Não foi possível adicionar este compromisso. ${result ['message']}',
      );
    }
  }
</code>```

Controller

```<code>Future<void> addCallCommitments({
    required String name,
    required DateTime start,
    required DateTime finish,
    required int color,
    required bool isAllDay,
  }) async {
    final OverallResults result = await callsRepository.addCallCommitments(
      token: authController.user.token!,
      idUser: authController.user.id!,
      name: name,
      start: start,
      finish: finish,
      color: color,
      isAllDay: isAllDay,
    );

    result.when(
      success: (data) {
        authController.allCallsCommitments.add(
          CallsCommitmentsModel(
            idUser: authController.user.id!,
            name: name,
            start: start,
            finish: finish,
            color: color,
            isAllDay: isAllDay,
          ),
        );
      },
      error: (message) {
        utilsServices.showToast(
          message: message,
          isError: true,
        );
      },
    );

    update();
  }
</code>```

Call

```<code>import 'package:flutter/material.dart';
import 'package:flutter_form_builder/flutter_form_builder.dart';
import 'package:get/get.dart';

import '../../commun_widgets/custom_text_field.dart';
import '../controller/calls_controller.dart';

class CardAddCallsCommitments extends StatelessWidget {
  CardAddCallsCommitments({Key? key}) : super(key: key);

  TextEditingController titleController = TextEditingController();
  TextEditingController colorController = TextEditingController();
  TextEditingController isAllDayController = TextEditingController();
  final controller = Get.find<CallsController>();

  TimeOfDay time = TimeOfDay.now();

  @override
  Widget build(BuildContext context) {
    DateTime? start;
    DateTime? finish;

    return SizedBox(
      height: 300,
      width: 300,
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Card(
            elevation: 3,
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(15),
            ),
            margin: const EdgeInsets.symmetric(horizontal: 200, vertical: 80),
            child: Padding(
              padding: const EdgeInsets.all(8),
              child: Column(
                children: [
                  const Text(
                    'Novo Agendamento',
                    style: TextStyle(fontSize: 35),
                  ),
                  const SizedBox(height: 25),

                  // Campo de Titulo
                  CustomTextField(
                    icon: Icons.title,
                    label: 'Titulo',
                    controller: titleController,
                  ),
                  const SizedBox(height: 15),

                  SizedBox(
                    child: FormBuilderDateTimePicker(
                      name: 'Teste',
                      onChanged: (data) {
                        start = data;
                      },
                    ),
                  ),
                  SizedBox(
                    child: FormBuilderDateTimePicker(
                      name: 'Teste',
                      onChanged: (data) {
                        finish = data;
                      },
                    ),
                  ),

                  // Botoes
                  Row(
                    children: [
                      Expanded(
                        child: SizedBox(
                          height: 50,
                          child: TextButton(
                            onPressed: () {
                              controller.addCallCommitments(
                                name: titleController.text,
                                start: start!,
                                finish: finish!,
                                color: 1,
                                isAllDay: false,
                              );
                              Get.back();
                            },
                            child: const Text(
                              'Agendar',
                              style: TextStyle(fontSize: 20),
                            ),
                          ),
                        ),
                      ),
                      Expanded(
                        child: SizedBox(
                          height: 50,
                          child: TextButton(
                            onPressed: () {
                              Get.back();
                            },
                            child: const Text(
                              'Cancelar',
                              style: TextStyle(fontSize: 20),
                            ),
                          ),
                        ),
                      ),
                    ],
                  )
                ],
              ),
            ),
          )
        ],
      ),
    );
  }
}
</code>```

Body:
I'm trying to enter an appointment into a calendar. I'm using a laravel api but I'm sure the problem is in the DateTime because with other formats like String, ind and bool it works normally. I'm still new to programming and would be very grateful if you could help me.

This is the error

[ERROR:flutter/lib/ui/ui_dart_state.cc(198)] Unhandled Exception: NoSuchMethodError: Class '_CompactLinkedHashSet<String>' has no instance method '[]'.
Receiver: _LinkedHashSet len:1
Tried calling: []("data")
#0      Object.noSuchMethod (dart:core-patch/object_patch.dart:38:5)
#1      CallsRepository.addCallCommitments (package:project_002_italian_citizenship/src/pages/calls/repository/calls_repository.dart:129:16)
<asynchronous suspension>
#2      CallsController.addCallCommitments (package:project_002_italian_citizenship/src/pages/calls/controller/calls_controller.dart:173:35)
<asynchronous suspension>

Repository

Future<OverallResults<Map<String, dynamic>>> addCallCommitments({
    required String token,
    required int idUser,
    required String name,
    required DateTime start,
    required DateTime finish,
    required int color,
    required bool isAllDay,
  }) async {
    final result = await _httpManager.restRequest(
      url: EndPoints.callsCommitments,
      method: HttpMethods.post,
      headers: {'Authorization': 'Bearer $token'},
      body: {
        "id_user": idUser,
        "name": name,
        "start": start,
        "finish": finish,
        "color": color,
        "is_all_day": isAllDay,
      },
    );

    if (result ['data'] != null) {
      return OverallResults<Map<String, dynamic>>.success(result ['data']);
    } else {
      return OverallResults.error(
        'Não foi possível adicionar este compromisso. ${result ['message']}',
      );
    }
  }

Controller

Future<void> addCallCommitments({
    required String name,
    required DateTime start,
    required DateTime finish,
    required int color,
    required bool isAllDay,
  }) async {
    final OverallResults result = await callsRepository.addCallCommitments(
      token: authController.user.token!,
      idUser: authController.user.id!,
      name: name,
      start: start,
      finish: finish,
      color: color,
      isAllDay: isAllDay,
    );

    result.when(
      success: (data) {
        authController.allCallsCommitments.add(
          CallsCommitmentsModel(
            idUser: authController.user.id!,
            name: name,
            start: start,
            finish: finish,
            color: color,
            isAllDay: isAllDay,
          ),
        );
      },
      error: (message) {
        utilsServices.showToast(
          message: message,
          isError: true,
        );
      },
    );

    update();
  }

Call

import 'package:flutter/material.dart';
import 'package:flutter_form_builder/flutter_form_builder.dart';
import 'package:get/get.dart';

import '../../commun_widgets/custom_text_field.dart';
import '../controller/calls_controller.dart';

class CardAddCallsCommitments extends StatelessWidget {
  CardAddCallsCommitments({Key? key}) : super(key: key);

  TextEditingController titleController = TextEditingController();
  TextEditingController colorController = TextEditingController();
  TextEditingController isAllDayController = TextEditingController();
  final controller = Get.find<CallsController>();

  TimeOfDay time = TimeOfDay.now();

  @override
  Widget build(BuildContext context) {
    DateTime? start;
    DateTime? finish;

    return SizedBox(
      height: 300,
      width: 300,
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Card(
            elevation: 3,
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(15),
            ),
            margin: const EdgeInsets.symmetric(horizontal: 200, vertical: 80),
            child: Padding(
              padding: const EdgeInsets.all(8),
              child: Column(
                children: [
                  const Text(
                    'Novo Agendamento',
                    style: TextStyle(fontSize: 35),
                  ),
                  const SizedBox(height: 25),

                  // Campo de Titulo
                  CustomTextField(
                    icon: Icons.title,
                    label: 'Titulo',
                    controller: titleController,
                  ),
                  const SizedBox(height: 15),

                  SizedBox(
                    child: FormBuilderDateTimePicker(
                      name: 'Teste',
                      onChanged: (data) {
                        start = data;
                      },
                    ),
                  ),
                  SizedBox(
                    child: FormBuilderDateTimePicker(
                      name: 'Teste',
                      onChanged: (data) {
                        finish = data;
                      },
                    ),
                  ),

                  // Botoes
                  Row(
                    children: [
                      Expanded(
                        child: SizedBox(
                          height: 50,
                          child: TextButton(
                            onPressed: () {
                              controller.addCallCommitments(
                                name: titleController.text,
                                start: start!,
                                finish: finish!,
                                color: 1,
                                isAllDay: false,
                              );
                              Get.back();
                            },
                            child: const Text(
                              'Agendar',
                              style: TextStyle(fontSize: 20),
                            ),
                          ),
                        ),
                      ),
                      Expanded(
                        child: SizedBox(
                          height: 50,
                          child: TextButton(
                            onPressed: () {
                              Get.back();
                            },
                            child: const Text(
                              'Cancelar',
                              style: TextStyle(fontSize: 20),
                            ),
                          ),
                        ),
                      ),
                    ],
                  )
                ],
              ),
            ),
          )
        ],
      ),
    );
  }
}


问:
In a Ts.ED controller: How to make Swagger-UI use my @Example instead of "interpreting" it?
I'm writing a REST controller method in a TypeScript/Ts.ED project.

The request body is a complex object (containing arrays of child objects etc.), so I'd like to provide an example (via the @Example decorator) that can actually be used in tests. Because of the complexity, I'm adding a "scaled down" example with only one element in an array.

But... the generated Swagger-UI repeats every array element of my example 4 times (probably to show that arrays can have multiple elements) which (1) blows up the example way too much and (2) creates non-unique data which won't even work in my controller.

I tried finding a solution, but the docs are hardly even existing.

Can anyone tell me how I can tell the Swagger generator in a Ts.ED project to just use my provided example as-is and not "blow it up"?

Shortened, simplified example:

My Code:

```<code>  @Post("/import")
  async postTreeElements(
    @Example({ containers: [{ name: "ABC" }] })
    @BodyParams()
    body: IxResponseModel,
    ...
</code>```

What SwaggerUi shows:

```<code>{
  "containers": [
    {
      "name": "ABC"
    },
    {
      "name": "ABC"
    },
    {
      "name": "ABC"
    },
    {
      "name": "ABC"
    }
  ]
}
</code>```

Thanks in advance!

Body:
I'm writing a REST controller method in a TypeScript/Ts.ED project.

The request body is a complex object (containing arrays of child objects etc.), so I'd like to provide an example (via the @Example decorator) that can actually be used in tests. Because of the complexity, I'm adding a "scaled down" example with only one element in an array.

But... the generated Swagger-UI repeats every array element of my example 4 times (probably to show that arrays can have multiple elements) which (1) blows up the example way too much and (2) creates non-unique data which won't even work in my controller.

I tried finding a solution, but the docs are hardly even existing.

Can anyone tell me how I can tell the Swagger generator in a Ts.ED project to just use my provided example as-is and not "blow it up"?

Shortened, simplified example:

My Code:

  @Post("/import")
  async postTreeElements(
    @Example({ containers: [{ name: "ABC" }] })
    @BodyParams()
    body: IxResponseModel,
    ...

What SwaggerUi shows:

{
  "containers": [
    {
      "name": "ABC"
    },
    {
      "name": "ABC"
    },
    {
      "name": "ABC"
    },
    {
      "name": "ABC"
    }
  ]
}

Thanks in advance!


问:
SSLSessionContextImpl Error (null pointer) in JAX-WS generated code?
Can anyone tell me if this is related to the SSL session, or if this is indicative of a certificate issue?

I'm using some code created from JAX wsimport and have run into an occassional issue.  The error thrown seems to be related to SSL session invalidation.  However, this code was working fine previously and I am at a loss as to where to look.

Exception:

```<code> [ java.lang.NullPointerException ] java.lang.NullPointerException
    at com.sun.net.ssl.internal.ssl.SSLSessionContextImpl.remove(SSLSessionContextImpl.java:199)
    at com.sun.net.ssl.internal.ssl.SSLSessionImpl.invalidate(SSLSessionImpl.java:558)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1559)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1547)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.handleException(SSLSocketImpl.java:1511)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.handleException(SSLSocketImpl.java:1456)
    at com.sun.net.ssl.internal.ssl.AppOutputStream.write(AppOutputStream.java:64)
    at java.io.BufferedOutputStream.flushBuffer(BufferedOutputStream.java:65)
    at java.io.BufferedOutputStream.flush(BufferedOutputStream.java:123)
    at java.io.PrintStream.flush(PrintStream.java:286)
    at sun.net.www.MessageHeader.print(MessageHeader.java:228)
    at sun.net.www.http.HttpClient.writeRequests(HttpClient.java:602)
    at sun.net.www.protocol.http.HttpURLConnection.writeRequests(HttpURLConnection.java:430)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:970)
    at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:234)
    at java.net.URL.openStream(URL.java:1007)
    at com.sun.xml.ws.wsdl.parser.RuntimeWSDLParser.createReader(RuntimeWSDLParser.java:837)
    at com.sun.xml.ws.wsdl.parser.RuntimeWSDLParser.resolveWSDL(RuntimeWSDLParser.java:294)
    at com.sun.xml.ws.wsdl.parser.RuntimeWSDLParser.parse(RuntimeWSDLParser.java:151)
    at com.sun.xml.ws.wsdl.parser.RuntimeWSDLParser.parse(RuntimeWSDLParser.java:131)
    at com.sun.xml.ws.client.WSServiceDelegate.parseWSDL(WSServiceDelegate.java:267)
    at com.sun.xml.ws.client.WSServiceDelegate.<init>(WSServiceDelegate.java:230)
    at com.sun.xml.ws.client.WSServiceDelegate.<init>(WSServiceDelegate.java:178)
    at com.sun.xml.ws.spi.ProviderImpl.createServiceDelegate(ProviderImpl.java:106)
    at javax.xml.ws.Service.<init>(Service.java:57)
... (truncated)
</code>```

EDIT:

I traced the exception up through the stacktrace and found myself at the line com.sun.net.ssl.internal.ssl.AppOutputStream.write(AppOutputStream.java:64).  This appears to be writing bytes to the output stream, and catches any exceptions thrown during this process.  Within the catch block, it sends the exception into the SSLSocketImpl class which eventually tries to invalidate the session.  During the session invalidation is where the null pointer occurs (a secondary exception).

AppOutputStream.write():

```<code>public synchronized void write(byte[] paramArrayOfByte, int paramInt1, int paramInt2)
throws IOException
{
    this.c.checkWrite();
    try
    {
      do
      {
        int i = Math.min(paramInt2, this.r.availableDataBytes());

        if (i > 0) {
          this.r.write(paramArrayOfByte, paramInt1, i);
          paramInt1 += i;
          paramInt2 -= i;
        }
        this.c.writeRecord(this.r);
        this.c.checkWrite();
      }while (paramInt2 > 0);
    }
    catch (Exception localException) {
      this.c.handleException(localException);
    }
}
</code>```

The details of the initial exception are not printed by default.  You must use the jvm switch -Djavax.net.debug=SSL,session to get this information to print to your localhost/console log.  I have enabled this in my test environment, but have never seen the error there so it may not prove useful.  Because of the volume of logging information this produces, I am wary of enabling this option in production.

It seems that the literal question I asked may be answered with these findings.  However, the source of the exception (the output stream writes occasionally failing) is still unanswered.

Request suggestions about closing/answering this question and opening another, or continuing to solicit responses here.

ContentLicense: CC BY-SA 3.0

Body:
Can anyone tell me if this is related to the SSL session, or if this is indicative of a certificate issue?

I'm using some code created from JAX wsimport and have run into an occassional issue.  The error thrown seems to be related to SSL session invalidation.  However, this code was working fine previously and I am at a loss as to where to look.

Exception:

 [ java.lang.NullPointerException ] java.lang.NullPointerException
    at com.sun.net.ssl.internal.ssl.SSLSessionContextImpl.remove(SSLSessionContextImpl.java:199)
    at com.sun.net.ssl.internal.ssl.SSLSessionImpl.invalidate(SSLSessionImpl.java:558)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1559)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1547)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.handleException(SSLSocketImpl.java:1511)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.handleException(SSLSocketImpl.java:1456)
    at com.sun.net.ssl.internal.ssl.AppOutputStream.write(AppOutputStream.java:64)
    at java.io.BufferedOutputStream.flushBuffer(BufferedOutputStream.java:65)
    at java.io.BufferedOutputStream.flush(BufferedOutputStream.java:123)
    at java.io.PrintStream.flush(PrintStream.java:286)
    at sun.net.www.MessageHeader.print(MessageHeader.java:228)
    at sun.net.www.http.HttpClient.writeRequests(HttpClient.java:602)
    at sun.net.www.protocol.http.HttpURLConnection.writeRequests(HttpURLConnection.java:430)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:970)
    at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:234)
    at java.net.URL.openStream(URL.java:1007)
    at com.sun.xml.ws.wsdl.parser.RuntimeWSDLParser.createReader(RuntimeWSDLParser.java:837)
    at com.sun.xml.ws.wsdl.parser.RuntimeWSDLParser.resolveWSDL(RuntimeWSDLParser.java:294)
    at com.sun.xml.ws.wsdl.parser.RuntimeWSDLParser.parse(RuntimeWSDLParser.java:151)
    at com.sun.xml.ws.wsdl.parser.RuntimeWSDLParser.parse(RuntimeWSDLParser.java:131)
    at com.sun.xml.ws.client.WSServiceDelegate.parseWSDL(WSServiceDelegate.java:267)
    at com.sun.xml.ws.client.WSServiceDelegate.<init>(WSServiceDelegate.java:230)
    at com.sun.xml.ws.client.WSServiceDelegate.<init>(WSServiceDelegate.java:178)
    at com.sun.xml.ws.spi.ProviderImpl.createServiceDelegate(ProviderImpl.java:106)
    at javax.xml.ws.Service.<init>(Service.java:57)
... (truncated)

EDIT:

I traced the exception up through the stacktrace and found myself at the line com.sun.net.ssl.internal.ssl.AppOutputStream.write(AppOutputStream.java:64).  This appears to be writing bytes to the output stream, and catches any exceptions thrown during this process.  Within the catch block, it sends the exception into the SSLSocketImpl class which eventually tries to invalidate the session.  During the session invalidation is where the null pointer occurs (a secondary exception).

AppOutputStream.write():

public synchronized void write(byte[] paramArrayOfByte, int paramInt1, int paramInt2)
throws IOException
{
    this.c.checkWrite();
    try
    {
      do
      {
        int i = Math.min(paramInt2, this.r.availableDataBytes());

        if (i > 0) {
          this.r.write(paramArrayOfByte, paramInt1, i);
          paramInt1 += i;
          paramInt2 -= i;
        }
        this.c.writeRecord(this.r);
        this.c.checkWrite();
      }while (paramInt2 > 0);
    }
    catch (Exception localException) {
      this.c.handleException(localException);
    }
}

The details of the initial exception are not printed by default.  You must use the jvm switch -Djavax.net.debug=SSL,session to get this information to print to your localhost/console log.  I have enabled this in my test environment, but have never seen the error there so it may not prove useful.  Because of the volume of logging information this produces, I am wary of enabling this option in production.

It seems that the literal question I asked may be answered with these findings.  However, the source of the exception (the output stream writes occasionally failing) is still unanswered.

Request suggestions about closing/answering this question and opening another, or continuing to solicit responses here.


问:
Openpyxl to read radio button
I am reading an excel file with cells having image and radio button , with the input source file i able to add desired values to cell and save as a new excel but

But my problem is Openpyxl not reading image and radio button, somehow image i managed to add the required image to specific cell with

```<code> sheet.add_image(img,"C10")
</code>```

Not sure how to add radio button , as i need users to have this radio button option out of the new file saved from the script

Title: Openpyxl to read radio button

Body:
I am reading an excel file with cells having image and radio button , with the input source file i able to add desired values to cell and save as a new excel but

But my problem is Openpyxl not reading image and radio button, somehow image i managed to add the required image to specific cell with

 sheet.add_image(img,"C10")

Not sure how to add radio button , as i need users to have this radio button option out of the new file saved from the script


问:
Elasticsearch ids from one index which are not present in one of the field in another index
I have 1 index 'images' and its ids are present in 2nd index's field 'images'.
I want to know which of the image ids from index 1 aren't there in  2nd index's field 'images' (this field is an array).

Its SQL equivalent would be something like:

Select t2.image_id from images t2 where t2.image_id not in (select t1.images from index2 t1)

Any suggestions on how I can go about this?


问:
How to forward all MouseEvents from QGraphicsView to its QFrame to its QMainWindow? (C++, Qt5)
I have a widget with this structure:
main->QMainWindow->QFrame->QGraphicsView->QScene->QGraphicsPixMapItem->QPixmap

I had to do it this way because im not using Qt creator or QML, just widgets. Anyway I added an event filter to my QMainindow to be movable when clicking and dragging whenever side of the window And it worked. But due to the QGraphicsView implementation if I try to drag it doesnt work but still receives input (a menu opens when i click). What makes QGraphicsview so stubborn and how do i make the window to be draggable when i click and drag on the QGraphics view, Even installing the eventFilter on the view and frame but with no results. Thanks in advance and this is my code.
This is the problem, the red square is the QGrapicsView, the white one is the MainWindow/Qframe. See how i still can make right clic on the red one and the menu still appears. I made a debug and see i get 2 objs when i click, the mainwindow and the Qgraphicview so i dont know why the move functionality just doesn work.

enter image description here

Main.cpp

```<code>int main(int argc, char *argv[]) {
    QApplication a(argc, argv);
    MainWindow w;
    w.show();
    return QApplication::exec();
}
</code>```

MainWindow.h

```<code>protected:

    bool eventFilter(QObject *obj, QEvent *event) override{
        if (event->type() == QEvent::MouseButtonPress ) {
            qDebug() << event;
            auto *ev = (QMouseEvent *) event;
            if (ev->button() == Qt::RightButton) {
                //Opens menu, it works well when i click on the QGraphics as well
                auto *menu = new QMenu(this);
                auto *idle = new QAction("Idle", this);
                auto *close = new QAction("Quit", this);
                menu->addAction(idle);

                menu->popup(ev->globalPos());
                connect(close, &QAction::triggered, [](){QCoreApplication::quit();});
                connect(idle, &QAction::triggered, [this](){changeDance(0);});
            }
            else{
                // "grab" the mainWindow
                this->oldPos = ev->globalPos();
            }
        }
        if (event->type() == QEvent::MouseMove) {
            //drag the window
            auto *ev = (QMouseEvent *) event;
            const QPoint delta = ev->globalPos() - oldPos;
            move(x() + delta.x(), y() + delta.y());
            oldPos = ev->globalPos();
        }
    }
</code>```

MainWindow.cpp

```<code>MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent) {
    setWindowTitle("waifu"); //waifu
    setWindowFlags(Qt::Dialog | Qt::MSWindowsFixedSizeDialogHint);
    setFixedSize(screenWidth, screenHeight);
    //setAttribute(Qt::WA_TranslucentBackground, true);
    setWindowFlags(Qt::Widget | Qt::FramelessWindowHint);
    setWindowFlags(Qt::BypassGraphicsProxyWidget);

    //mainWindow->frame->view->scene->pixmap
    installEventFilter(this);
    frame =  new Frame(this);
    setCentralWidget(frame);

    view = new View(frame);
    view->setFixedSize(50, 50);
    scene = new Scene(view);
    view->setScene(this->scene); // That connects the view with the scene
    frame->layout()->addWidget(view);
    myItem = new QGraphicsPixmapItem(*new QPixmap());
    //scene->setBackgroundBrush(QBrush(Qt::yellow));
    scene->addItem(myItem);
    view->show();
</code>```

Frame.h

```<code>
class Frame : public QFrame {
Q_OBJECT

public:
    explicit Frame(QMainWindow *parent = 0) : QFrame(parent) {
        setMouseTracking(true);
        setStyleSheet("background-color: red;"); //delete
        setLayout(new QVBoxLayout);
        layout()->setContentsMargins(0, 0, 0, 0);
        setWindowFlags(Qt::FramelessWindowHint);   //No windowing
        setAttribute(Qt::WA_TranslucentBackground); // No background
        setStyleSheet("background-color: transparent;");
    };
};

</code>```

QGraphicsView.h

```<code>class View : public QGraphicsView {
Q_OBJECT

public:
    explicit View(QFrame *parent) : QGraphicsView(parent) {
        setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
        setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
        setMouseTracking(true);
    };
protected:

private:

};
</code>```

Tried to install the event filter located in the main window, in the Qframe and QGraphicsView class. with the parameter event filter being *parent.

Body:
I have a widget with this structure:
main->QMainWindow->QFrame->QGraphicsView->QScene->QGraphicsPixMapItem->QPixmap

I had to do it this way because im not using Qt creator or QML, just widgets. Anyway I added an event filter to my QMainindow to be movable when clicking and dragging whenever side of the window And it worked. But due to the QGraphicsView implementation if I try to drag it doesnt work but still receives input (a menu opens when i click). What makes QGraphicsview so stubborn and how do i make the window to be draggable when i click and drag on the QGraphics view, Even installing the eventFilter on the view and frame but with no results. Thanks in advance and this is my code.
This is the problem, the red square is the QGrapicsView, the white one is the MainWindow/Qframe. See how i still can make right clic on the red one and the menu still appears. I made a debug and see i get 2 objs when i click, the mainwindow and the Qgraphicview so i dont know why the move functionality just doesn work.

enter image description here

Main.cpp

int main(int argc, char *argv[]) {
    QApplication a(argc, argv);
    MainWindow w;
    w.show();
    return QApplication::exec();
}

MainWindow.h

protected:

    bool eventFilter(QObject *obj, QEvent *event) override{
        if (event->type() == QEvent::MouseButtonPress ) {
            qDebug() << event;
            auto *ev = (QMouseEvent *) event;
            if (ev->button() == Qt::RightButton) {
                //Opens menu, it works well when i click on the QGraphics as well
                auto *menu = new QMenu(this);
                auto *idle = new QAction("Idle", this);
                auto *close = new QAction("Quit", this);
                menu->addAction(idle);

                menu->popup(ev->globalPos());
                connect(close, &QAction::triggered, [](){QCoreApplication::quit();});
                connect(idle, &QAction::triggered, [this](){changeDance(0);});
            }
            else{
                // "grab" the mainWindow
                this->oldPos = ev->globalPos();
            }
        }
        if (event->type() == QEvent::MouseMove) {
            //drag the window
            auto *ev = (QMouseEvent *) event;
            const QPoint delta = ev->globalPos() - oldPos;
            move(x() + delta.x(), y() + delta.y());
            oldPos = ev->globalPos();
        }
    }

MainWindow.cpp

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent) {
    setWindowTitle("waifu"); //waifu
    setWindowFlags(Qt::Dialog | Qt::MSWindowsFixedSizeDialogHint);
    setFixedSize(screenWidth, screenHeight);
    //setAttribute(Qt::WA_TranslucentBackground, true);
    setWindowFlags(Qt::Widget | Qt::FramelessWindowHint);
    setWindowFlags(Qt::BypassGraphicsProxyWidget);

    //mainWindow->frame->view->scene->pixmap
    installEventFilter(this);
    frame =  new Frame(this);
    setCentralWidget(frame);

    view = new View(frame);
    view->setFixedSize(50, 50);
    scene = new Scene(view);
    view->setScene(this->scene); // That connects the view with the scene
    frame->layout()->addWidget(view);
    myItem = new QGraphicsPixmapItem(*new QPixmap());
    //scene->setBackgroundBrush(QBrush(Qt::yellow));
    scene->addItem(myItem);
    view->show();

Frame.h

class Frame : public QFrame {
Q_OBJECT

public:
    explicit Frame(QMainWindow *parent = 0) : QFrame(parent) {
        setMouseTracking(true);
        setStyleSheet("background-color: red;"); //delete
        setLayout(new QVBoxLayout);
        layout()->setContentsMargins(0, 0, 0, 0);
        setWindowFlags(Qt::FramelessWindowHint);   //No windowing
        setAttribute(Qt::WA_TranslucentBackground); // No background
        setStyleSheet("background-color: transparent;");
    };
};

QGraphicsView.h

class View : public QGraphicsView {
Q_OBJECT

public:
    explicit View(QFrame *parent) : QGraphicsView(parent) {
        setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
        setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
        setMouseTracking(true);
    };
protected:

private:

};

Tried to install the event filter located in the main window, in the Qframe and QGraphicsView class. with the parameter event filter being *parent.


问:
ImportError: The 'packaging.specifiers' package is required; normally this is bundled
I'm using py2app to package some Python scripts into an executable on Mac.

I get this error when running it:

    ...
      File "/xxx.app/Contents/Resources/lib/python3.10/paddle/utils/cpp_extension/cpp_extension.py", line 20, in <module>
        import setuptools
      File "setuptools/__init__.pyc", line 18, in <module>
      File "setuptools/dist.pyc", line 39, in <module>
      File "setuptools/config.pyc", line 17, in <module>
      File "setuptools/extern/__init__.pyc", line 52, in create_module
      File "setuptools/extern/__init__.pyc", line 44, in load_module
    ImportError: The 'packaging.specifiers' package is required; normally this is bundled with this package so if you get this warning, consult the packager of your distribution.
    2022-12-12 23:35:59.913 xxx[92028:45291215] Launch error
    2022-12-12 23:35:59.914 xxx[92028:45291215] Launch error
    See the py2app website for debugging launch issues
```

Currently I have:

paddlepaddle==2.4.0

setuptools==59.8.0

packaging==21.3

How can I fix this?

Body:
I'm using py2app to package some Python scripts into an executable on Mac.

I get this error when running it:

    ...
      File "/xxx.app/Contents/Resources/lib/python3.10/paddle/utils/cpp_extension/cpp_extension.py", line 20, in <module>
        import setuptools
      File "setuptools/__init__.pyc", line 18, in <module>
      File "setuptools/dist.pyc", line 39, in <module>
      File "setuptools/config.pyc", line 17, in <module>
      File "setuptools/extern/__init__.pyc", line 52, in create_module
      File "setuptools/extern/__init__.pyc", line 44, in load_module
    ImportError: The 'packaging.specifiers' package is required; normally this is bundled with this package so if you get this warning, consult the packager of your distribution.
    2022-12-12 23:35:59.913 xxx[92028:45291215] Launch error
    2022-12-12 23:35:59.914 xxx[92028:45291215] Launch error
    See the py2app website for debugging launch issues

Currently I have:

paddlepaddle==2.4.0

setuptools==59.8.0

packaging==21.3

How can I fix this?