问:
JS function works in its own .html file but not when loaded into div
I have a function that changes the src of an image depending on slider position. It works perfectly fine in it's own .html file, however when I save it and import it to a div in a different .html file, the some functionality begins to fail. The buttons to move the slider and the play/pause button works to change the image, however if you were to physically move the slider it no longer works to update the image. The console log is saying that my updateImage() function is not defined when it clearly is.

var imgElement = document.getElementById("image");
var sliderValue_store = sessionStorage.getItem("sliderValue");
console.log(sessionStorage.getItem("sliderValue"))
if (sliderValue_store == null) {
    imgElement.src = "#";
}
else {
// Update the img src using the slider value
imgElement.src = "#" + sliderValue_store + ".png";
}
// Retrieve the stored value when the page is loaded
window.addEventListener("load", function() {

  var storedValue = sessionStorage.getItem("sliderValue");
  if (storedValue) {
    rangeSlider.value = storedValue;
  }
});

           console.log(updateImage)
                  // Get the buttons and range slider elements
          var prevButton = document.getElementById('prev-button');
          var nextButton = document.getElementById('next-button');
          var rangeSlider = document.getElementById('range-slider');
            var step = rangeSlider.step;
          // Add event listeners to the buttons
          prevButton.addEventListener('click', function() {
              event.preventDefault();
            // Decrement the value of the range slider by the step value
            rangeSlider.value -= rangeSlider.step;
          updateImage(rangeSlider.value)
          sessionStorage.setItem("sliderValue", parseInt(rangeSlider.value)-parseInt(6));
          });

          nextButton.addEventListener('click', function() {
              event.preventDefault();
            // Increment the value of the range slider by the step value
            val = parseInt(rangeSlider.value);
            step = parseInt(rangeSlider.step);
            val += step;
            rangeSlider.value = val;
            updateImage(rangeSlider.value);
              sessionStorage.setItem("sliderValue", parseInt(rangeSlider.value)+parseInt(6));
          });

            document.addEventListener('keydown', function(e) {
          if (e.keyCode == 39) { //right
            rangeSlider.value = +rangeSlider.value + +rangeSlider.step;
            sessionStorage.setItem("sliderValue", parseInt(rangeSlider.value)-parseInt(0));
          } else if (e.keyCode == 37) { //left
            rangeSlider.value = +rangeSlider.value - +rangeSlider.step;
              sessionStorage.setItem("sliderValue", parseInt(rangeSlider.value)+parseInt(0));
          }
          updateImage(rangeSlider.value)
        })
        function updateImage(sliderValue) {
          console.log(sliderValue)
          document.getElementById("image").src =
            "#" +
            sliderValue + ".png";
          // Get the image and arrow button elements
          const image = document.querySelector('.image');
          const backwardArrow = document.querySelector('.backward-arrow');
          const forwardArrow = document.querySelector('.forward-arrow');

    // to update the slider value depending on what the session storage of the slider is
// Update the value of the slider when it is changed
rangeSlider.addEventListener("change", function() {
  sessionStorage.setItem("sliderValue", this.value);
});

console.log(sessionStorage.getItem("sliderValue"))

                    // Index of the current image in the images array
            let currentImageIndex = images.length;

            // Function to change the image to the previous image in the images array
            function showPreviousImage() {
                event.preventDefault();
              // Only show the previous image if the current image is not the first image
              if (currentImageIndex > 0) {
                currentImageIndex--;
                image.src = images[currentImageIndex];
              }
            }

            // Function to change the image to the next image in the images array
            function showNextImage() {
                event.preventDefault();
              // Only show the next image if the current image is not the last image
              if (currentImageIndex < images.length - 1) {
                currentImageIndex++;
                image.src = images[currentImageIndex];
              }
            }

            // Add click event listeners to the arrow buttons to show the previous/next image when clicked
            backwardArrow.addEventListener('click', showPreviousImage);
            forwardArrow.addEventListener('click', showNextImage);
        }```
<pre class="snippet-code-html lang-html prettyprint-override"><code>        <input type="range" min="0" max="384" value="0" step="6"  oninput="updateImage(this.value)" id="range-slider" class="slider"/>
        <div>
    <button id="prev-button" class="prev"></button>
    <button class="play-pause-button">Play</button>
<button id="next-button" class="next"></button>
            </div>
</div>
        <div>
<img id="image" src="#" width="840" height="660" alt="image1" class="image">

</div></code>```

Here is the js code I use to import the .html file that both the html and js were stored in.

```<code>const body = document.querySelector('.body_test')
fetch('body_test.html')
.then(res=>res.text())
.then(data=>{
    body.innerHTML=data
    const parser = new DOMParser()
    const doc = parser.parseFromString(data, 'text/html')
    eval(doc.querySelector('script').textContent)
})
</code>```

Here is how I import the first html file into this one.

```<code>    <html lang="en">
    <script src="gifshot/dist/gifshot.js"></script>
<script src="FileSaver.js/dist/FileSaver.js"></script>
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://kit.fontawesome.com/57b929fbcb.js" crossorigin="anonymous">
   </script>
        <link rel="stylesheet" href="style.css">
        <title>Document</title>
</head>
<body>
    <div class="body_test">
    </div>
    <script src="test_script.js"></script>
</body>
</html>
</code>```

Body:
I have a function that changes the src of an image depending on slider position. It works perfectly fine in it's own .html file, however when I save it and import it to a div in a different .html file, the some functionality begins to fail. The buttons to move the slider and the play/pause button works to change the image, however if you were to physically move the slider it no longer works to update the image. The console log is saying that my updateImage() function is not defined when it clearly is.

var imgElement = document.getElementById("image");
var sliderValue_store = sessionStorage.getItem("sliderValue");
console.log(sessionStorage.getItem("sliderValue"))
if (sliderValue_store == null) {
    imgElement.src = "#";
}
else {
// Update the img src using the slider value
imgElement.src = "#" + sliderValue_store + ".png";
}
// Retrieve the stored value when the page is loaded
window.addEventListener("load", function() {

  var storedValue = sessionStorage.getItem("sliderValue");
  if (storedValue) {
    rangeSlider.value = storedValue;
  }
});

           console.log(updateImage)
                  // Get the buttons and range slider elements
          var prevButton = document.getElementById('prev-button');
          var nextButton = document.getElementById('next-button');
          var rangeSlider = document.getElementById('range-slider');
            var step = rangeSlider.step;
          // Add event listeners to the buttons
          prevButton.addEventListener('click', function() {
              event.preventDefault();
            // Decrement the value of the range slider by the step value
            rangeSlider.value -= rangeSlider.step;
          updateImage(rangeSlider.value)
          sessionStorage.setItem("sliderValue", parseInt(rangeSlider.value)-parseInt(6));
          });

          nextButton.addEventListener('click', function() {
              event.preventDefault();
            // Increment the value of the range slider by the step value
            val = parseInt(rangeSlider.value);
            step = parseInt(rangeSlider.step);
            val += step;
            rangeSlider.value = val;
            updateImage(rangeSlider.value);
              sessionStorage.setItem("sliderValue", parseInt(rangeSlider.value)+parseInt(6));
          });

            document.addEventListener('keydown', function(e) {
          if (e.keyCode == 39) { //right
            rangeSlider.value = +rangeSlider.value + +rangeSlider.step;
            sessionStorage.setItem("sliderValue", parseInt(rangeSlider.value)-parseInt(0));
          } else if (e.keyCode == 37) { //left
            rangeSlider.value = +rangeSlider.value - +rangeSlider.step;
              sessionStorage.setItem("sliderValue", parseInt(rangeSlider.value)+parseInt(0));
          }
          updateImage(rangeSlider.value)
        })
        function updateImage(sliderValue) {
          console.log(sliderValue)
          document.getElementById("image").src =
            "#" +
            sliderValue + ".png";
          // Get the image and arrow button elements
          const image = document.querySelector('.image');
          const backwardArrow = document.querySelector('.backward-arrow');
          const forwardArrow = document.querySelector('.forward-arrow');

    // to update the slider value depending on what the session storage of the slider is
// Update the value of the slider when it is changed
rangeSlider.addEventListener("change", function() {
  sessionStorage.setItem("sliderValue", this.value);
});

console.log(sessionStorage.getItem("sliderValue"))

                    // Index of the current image in the images array
            let currentImageIndex = images.length;

            // Function to change the image to the previous image in the images array
            function showPreviousImage() {
                event.preventDefault();
              // Only show the previous image if the current image is not the first image
              if (currentImageIndex > 0) {
                currentImageIndex--;
                image.src = images[currentImageIndex];
              }
            }

            // Function to change the image to the next image in the images array
            function showNextImage() {
                event.preventDefault();
              // Only show the next image if the current image is not the last image
              if (currentImageIndex < images.length - 1) {
                currentImageIndex++;
                image.src = images[currentImageIndex];
              }
            }

            // Add click event listeners to the arrow buttons to show the previous/next image when clicked
            backwardArrow.addEventListener('click', showPreviousImage);
            forwardArrow.addEventListener('click', showNextImage);
        }

        <input type="range" min="0" max="384" value="0" step="6"  oninput="updateImage(this.value)" id="range-slider" class="slider"/>

    <button id="prev-button" class="prev"></button>
    <button class="play-pause-button">Play</button>
<button id="next-button" class="next"></button>

Here is the js code I use to import the .html file that both the html and js were stored in.

const body = document.querySelector('.body_test')
fetch('body_test.html')
.then(res=>res.text())
.then(data=>{
    body.innerHTML=data
    const parser = new DOMParser()
    const doc = parser.parseFromString(data, 'text/html')
    eval(doc.querySelector('script').textContent)
})

Here is how I import the first html file into this one.

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

        <link rel="stylesheet" href="style.css">
        <title>Document</title>


来源: stackexchange

问:
How do I properly build a .NET 7 application using SkiaSharp on Linux? Getting a segmentation fault when creating GRGlInterface
I have a test application written in F# on .NET 7 that opens a window using GLFW and draws to it using SkiaSharp. This application works on Windows, and now I am testing support on Linux. Right now, I am testing on a fresh install of Linux Mint, but the same exit code described here also happens on Ubuntu through WSL2.

However, my application crashes, and the only response is an exit code of 139, which apparently means there's a segmentation fault. I whittled my test application down to just GLFW, and I am able to open up a window without error. As soon as I add back in any interaction with SkiaSharp, the crash happens. I have specifically determined this to happen at the line:

```<code>let grGlInterface = GRGlInterface.Create(getProcAddress)
</code>```

If I print out the string passed to getProcAddress, it prints out the following before the crash:

```<code>Name passed into `getProcAddress`: glGetString
Name passed into `getProcAddress`: glGetString
Name passed into `getProcAddress`: glGetStringi
Name passed into `getProcAddress`: glGetIntegerv
Name passed into `getProcAddress`: eglQueryString
Name passed into `getProcAddress`: eglGetCurrentDisplay
</code>```

However, this works on both Windows and macOS.

So something is either wrong with SkiaSharp on Linux or with my dependencies.

My project file (WindowTest.fsproj):

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net7.0</TargetFramework>
    <PlatformTarget>AnyCPU</PlatformTarget>
  </PropertyGroup>

  <ItemGroup>
    <Compile Include="Program.fs" />
  </ItemGroup>

  <ItemGroup>
    <PackageReference Include="SkiaSharp" Version="2.88.3" />
    <PackageReference Include="SkiaSharp.NativeAssets.Linux" Version="2.88.3" />
  </ItemGroup>

  <ItemGroup>
    <ProjectReference Include="..\GLFW\GLFW.fsproj" />
  </ItemGroup>

  <ItemGroup>
    <PackageReference Update="FSharp.Core" Version="6.0.6" />
  </ItemGroup>

</Project>
```
<p>I cannot find much information about how <code>SkiaSharp.NativeAssets.Linux</code> is supposed to work or be used. There's also <code>SkiaSharp.NativeAssets.Linux.NoDependencies</code>, which I'm not sure what it is. I guess it comes with a pre-built version of SkiaSharp or something?</p>
<p>My test application (<code>Program.fs</code>):</p>
<pre class="lang-ml prettyprint-override"><code>open SkiaSharp

open Windowing.GLFW.FSharp
open Windowing.GLFW.Native.Window
open Windowing.GLFW.Native.Initialization
open Windowing.GLFW.Native.Context
open Windowing.GLFW.Native.Helpers
open Windowing.GLFW.Native.OpenGL

let mutable width, height = 500, 500
let mutable framebufferWidth, framebufferHeight = width, height

let init = initialize() |> printfn "Initialized?: %A"

glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4)
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 6)
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GLFW_TRUE)
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE)

printfn "Starting to create window..."
let window = glfwCreateWindow(width, height, "Test Window", NULL_MONITOR, NULL_WINDOW)
printfn "Window: %A" window
printfn "Ending creating window..."

glfwMakeContextCurrent(window)

let grGlInterface = GRGlInterface.Create(getProcAddress)

if not (grGlInterface.Validate())
then raise (System.Exception("Invalid GRGlInterface"))

let grContext = GRContext.CreateGl(grGlInterface)
grContext.ResetContext()

let grGlFramebufferInfo = new GRGlFramebufferInfo(0u, uint32(GL_RGBA8))

let draw(window, width, height) =
   glfwPollEvents()

   use grBackendRenderTarget = new GRBackendRenderTarget(width, height, 1, 0, grGlFramebufferInfo)
   use surface = SKSurface.Create(grContext, grBackendRenderTarget, GRSurfaceOrigin.BottomLeft, SKColorType.Rgba8888)
   let canvas = surface.Canvas

   canvas.Clear(SKColors.Cyan)
   canvas.Flush()

   glfwSwapBuffers(window)

let resizeCallback (window, newWidth: int, newHeight: int) =
   width <- newWidth
   height <- newHeight
   draw(window, newWidth, newHeight)

glfwSetFramebufferSizeCallback(window, GLFWframebuffersizefun(fun window width height -> resizeCallback(window, width, height)))
|> ignore

while glfwWindowShouldClose window <> 1 do
   glfwGetFramebufferSize(window, &framebufferWidth, &framebufferHeight)
   draw(window, framebufferWidth, framebufferHeight)

glfwDestroyWindow(window)
terminate()
</code>```

I run this application with dotnet run --project WindowTest. Other than the exit code of 139 that gets returned, nothing gets printed to the console except for my debug print statements. I'm not sure how to debug this further. I'm hoping there is just something I'm supposed to do more with the SkiaSharp native dependencies on Linux. These are not required on Windows. The other option is that there is a bug in SkiaSharp on Linux.

Running the command glxinfo | grep "OpenGL" returns:

$ glxinfo | grep "OpenGL"
OpenGL vendor string: Intel
OpenGL renderer string: Mesa Intel(R) Xe Graphics (TGL GT2)
OpenGL core profile version string: 4.6 (Core Profile) Mesa 22.0.5
OpenGL core profile shading language version string: 4.60
OpenGL core profile context flags: (none)
OpenGL core profile profile mask: core profile
OpenGL core profile extensions:
OpenGL version string: 4.6 (Compatibility Profile) Mesa 22.0.5
OpenGL shading language version string: 4.60
OpenGL context flags: (none)
OpenGL profile mask: compatibility profile
OpenGL extensions:
OpenGL ES profile version string: OpenGL ES 3.2 Mesa 22.0.5
OpenGL ES profile shading language version string: OpenGL ES GLSL ES 3.20
OpenGL ES profile extensions:

```

Thank you for any help!

ContentLicense: CC BY-SA 4.0

Body:
I have a test application written in F# on .NET 7 that opens a window using GLFW and draws to it using SkiaSharp. This application works on Windows, and now I am testing support on Linux. Right now, I am testing on a fresh install of Linux Mint, but the same exit code described here also happens on Ubuntu through WSL2.

However, my application crashes, and the only response is an exit code of 139, which apparently means there's a segmentation fault. I whittled my test application down to just GLFW, and I am able to open up a window without error. As soon as I add back in any interaction with SkiaSharp, the crash happens. I have specifically determined this to happen at the line:

let grGlInterface = GRGlInterface.Create(getProcAddress)

If I print out the string passed to getProcAddress, it prints out the following before the crash:

Name passed into `getProcAddress`: glGetString
Name passed into `getProcAddress`: glGetString
Name passed into `getProcAddress`: glGetStringi
Name passed into `getProcAddress`: glGetIntegerv
Name passed into `getProcAddress`: eglQueryString
Name passed into `getProcAddress`: eglGetCurrentDisplay

However, this works on both Windows and macOS.

So something is either wrong with SkiaSharp on Linux or with my dependencies.

My project file (WindowTest.fsproj):

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net7.0</TargetFramework>
    <PlatformTarget>AnyCPU</PlatformTarget>
  </PropertyGroup>

  <ItemGroup>
    <Compile Include="Program.fs" />
  </ItemGroup>

  <ItemGroup>
    <PackageReference Include="SkiaSharp" Version="2.88.3" />
    <PackageReference Include="SkiaSharp.NativeAssets.Linux" Version="2.88.3" />
  </ItemGroup>

  <ItemGroup>
    <ProjectReference Include="..\GLFW\GLFW.fsproj" />
  </ItemGroup>

  <ItemGroup>
    <PackageReference Update="FSharp.Core" Version="6.0.6" />
  </ItemGroup>

</Project>

I cannot find much information about how SkiaSharp.NativeAssets.Linux is supposed to work or be used. There's also SkiaSharp.NativeAssets.Linux.NoDependencies, which I'm not sure what it is. I guess it comes with a pre-built version of SkiaSharp or something?

My test application (Program.fs):

open SkiaSharp

open Windowing.GLFW.FSharp
open Windowing.GLFW.Native.Window
open Windowing.GLFW.Native.Initialization
open Windowing.GLFW.Native.Context
open Windowing.GLFW.Native.Helpers
open Windowing.GLFW.Native.OpenGL

let mutable width, height = 500, 500
let mutable framebufferWidth, framebufferHeight = width, height

let init = initialize() |> printfn "Initialized?: %A"

glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4)
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 6)
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GLFW_TRUE)
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE)

printfn "Starting to create window..."
let window = glfwCreateWindow(width, height, "Test Window", NULL_MONITOR, NULL_WINDOW)
printfn "Window: %A" window
printfn "Ending creating window..."

glfwMakeContextCurrent(window)

let grGlInterface = GRGlInterface.Create(getProcAddress)

if not (grGlInterface.Validate())
then raise (System.Exception("Invalid GRGlInterface"))

let grContext = GRContext.CreateGl(grGlInterface)
grContext.ResetContext()

let grGlFramebufferInfo = new GRGlFramebufferInfo(0u, uint32(GL_RGBA8))

let draw(window, width, height) =
   glfwPollEvents()

   use grBackendRenderTarget = new GRBackendRenderTarget(width, height, 1, 0, grGlFramebufferInfo)
   use surface = SKSurface.Create(grContext, grBackendRenderTarget, GRSurfaceOrigin.BottomLeft, SKColorType.Rgba8888)
   let canvas = surface.Canvas

   canvas.Clear(SKColors.Cyan)
   canvas.Flush()

   glfwSwapBuffers(window)

let resizeCallback (window, newWidth: int, newHeight: int) =
   width <- newWidth
   height <- newHeight
   draw(window, newWidth, newHeight)

glfwSetFramebufferSizeCallback(window, GLFWframebuffersizefun(fun window width height -> resizeCallback(window, width, height)))
|> ignore

while glfwWindowShouldClose window <> 1 do
   glfwGetFramebufferSize(window, &framebufferWidth, &framebufferHeight)
   draw(window, framebufferWidth, framebufferHeight)

glfwDestroyWindow(window)
terminate()

I run this application with dotnet run --project WindowTest. Other than the exit code of 139 that gets returned, nothing gets printed to the console except for my debug print statements. I'm not sure how to debug this further. I'm hoping there is just something I'm supposed to do more with the SkiaSharp native dependencies on Linux. These are not required on Windows. The other option is that there is a bug in SkiaSharp on Linux.

Running the command glxinfo | grep "OpenGL" returns:

$ glxinfo | grep "OpenGL"
OpenGL vendor string: Intel
OpenGL renderer string: Mesa Intel(R) Xe Graphics (TGL GT2)
OpenGL core profile version string: 4.6 (Core Profile) Mesa 22.0.5
OpenGL core profile shading language version string: 4.60
OpenGL core profile context flags: (none)
OpenGL core profile profile mask: core profile
OpenGL core profile extensions:
OpenGL version string: 4.6 (Compatibility Profile) Mesa 22.0.5
OpenGL shading language version string: 4.60
OpenGL context flags: (none)
OpenGL profile mask: compatibility profile
OpenGL extensions:
OpenGL ES profile version string: OpenGL ES 3.2 Mesa 22.0.5
OpenGL ES profile shading language version string: OpenGL ES GLSL ES 3.20
OpenGL ES profile extensions:

Thank you for any help!


问:
WebStorm debugger breakpoints does not reflected into the browser until re-running the debugger
My breakpoints set in WebStorm do not work until I hit the 'Rerun' button to restart the debugger. It's a fresh install of the latest WebStorm and Chrome. I have the exact same setup running on my old machine and breakpoints change immediately takes effect without the need to rerun the debugger.

The issue may be related to the communications between WebStorm debugger and the browser. I tried few tricks but could not resolve the problem. Debugging directly in the browser works perfectly fine. I searched the web well and could not find any working solution.

What might cause the problem?

EDIT:
I found some setting that somewhat helps: open the dev-tools in the browser window of the debugger > Network tab > check 'Disable cache'. Now breakpoints can be removed immediately, and only a page refresh is needed in order to make new breakpoints take effect. However, still quite annoying. Any ideas?


问:
optimize an array for interpolation
I am using an array (51x51x181) to make a 3d interpolation in python (and I can calculate any point inbetween if needed).

I need to reduce the size of the array and would like to do this with the least amount of error possible.

Attached you find an example, with the error function I would like to improve on. The number of values in the array should stay the same, however the Angles and Shifts in the example do not have to be equally spaced.

```<code>import numpy as np
from scipy.interpolate import RegularGridInterpolator
import itertools
Data=np.zeros((5,180))
Angles=np.linspace(0,360,10)
Shifts=np.linspace(0,100,10)

Data=np.sin(np.deg2rad(Angles[:,None]+Shifts[None,:]))

interp = RegularGridInterpolator((Angles, Shifts),Data, bounds_error=False, fill_value=None)

def errorfunc():
    Angles=np.linspace(0,360,50)
    Shifts=np.linspace(0,100,50)

    Function_Results=np.sin(np.deg2rad(Angles[:,None]+Shifts[None,:]).flatten())
    Data_interp=interp(np.array(list(itertools.product(Angles,Shifts))))
    Error=np.sqrt(np.mean(np.square(Function_Results-Data_interp)))
    return(Error)
</code>```

I could not find a feasible optimizer in scipy (tried some with poor performance). Is there a standard way to do this?

Title: optimize an array for interpolation

Body:
I am using an array (51x51x181) to make a 3d interpolation in python (and I can calculate any point inbetween if needed).

I need to reduce the size of the array and would like to do this with the least amount of error possible.

Attached you find an example, with the error function I would like to improve on. The number of values in the array should stay the same, however the Angles and Shifts in the example do not have to be equally spaced.

import numpy as np
from scipy.interpolate import RegularGridInterpolator
import itertools
Data=np.zeros((5,180))
Angles=np.linspace(0,360,10)
Shifts=np.linspace(0,100,10)

Data=np.sin(np.deg2rad(Angles[:,None]+Shifts[None,:]))

interp = RegularGridInterpolator((Angles, Shifts),Data, bounds_error=False, fill_value=None)

def errorfunc():
    Angles=np.linspace(0,360,50)
    Shifts=np.linspace(0,100,50)

    Function_Results=np.sin(np.deg2rad(Angles[:,None]+Shifts[None,:]).flatten())
    Data_interp=interp(np.array(list(itertools.product(Angles,Shifts))))
    Error=np.sqrt(np.mean(np.square(Function_Results-Data_interp)))
    return(Error)

I could not find a feasible optimizer in scipy (tried some with poor performance). Is there a standard way to do this?


问:
Is there a way to execute a subquery on a prepared statement result?
I'm trying to find the statement results which have a specific userid column
Here's the code:</p>
```<code>$interazionequerystmt_string = "
    SELECT USERID
    FROM like_calendario_condivisioni
    WHERE TIPO LIKE ? AND COMUNE LIKE ? AND VIA LIKE ? AND CIVICO LIKE ?";
$interazionequerystmt = $con->prepare($interazionequerystmt_string);
$tipo = "LIKE";
$interazionequerystmt->bind_param("ssss", $tipo, $comune, $via, $civico);
$interazionequerystmt->execute();
$likesquery = $interazionequerystmt->get_result();
</code>```
```<code>$ennesimaquery = mysqli_query($con, "
    SELECT * FROM ($likesquery)
    WHERE USERID LIKE '$sessionuserid'");
</code>```

Body:
I'm trying to find the statement results which have a specific userid column
Here's the code:

$interazionequerystmt_string = "
    SELECT USERID
    FROM like_calendario_condivisioni
    WHERE TIPO LIKE ? AND COMUNE LIKE ? AND VIA LIKE ? AND CIVICO LIKE ?";
$interazionequerystmt = $con->prepare($interazionequerystmt_string);
$tipo = "LIKE";
$interazionequerystmt->bind_param("ssss", $tipo, $comune, $via, $civico);
$interazionequerystmt->execute();
$likesquery = $interazionequerystmt->get_result();

$ennesimaquery = mysqli_query($con, "
    SELECT * FROM ($likesquery)
    WHERE USERID LIKE '$sessionuserid'");


问:
Validation of a required number using Yup
I'm trying to implement a validation for a float number,  Validation schema is like following:

```<code>export const getSellingInvoiceDetailsScheme =(total:BigNumber)=>{
return yup.object().shape({
    firstInstallment: yup.number()
    .required("This field is required")
    .label("Prix initiale")
    .test(
        'is-decimal',
        'invalid decimal',
        (value:any) => (/^[0-9]+$|^[0-9]+[.][0-9]{1,2}$/).test(value)  ,
      )
.when([], {
     is: total.isGreaterThan(0) ,
     then: yup.number().max(total.toNumber())
 }),
});
</code>```

The number is required and it should match float shape. The problem is when my input field is empty is shows the following message:

Prix initiale must be a number type, but the final value was: NaN (cast from the value "").

But what i want is to print the message

This field is required

I tried to add to the yup shape :

.transform((value) => (isNaN(value) || value === null || value === undefined) ? 0 : value)

But it still shows the same message .

Body:
I'm trying to implement a validation for a float number,  Validation schema is like following:

export const getSellingInvoiceDetailsScheme =(total:BigNumber)=>{
return yup.object().shape({
    firstInstallment: yup.number()
    .required("This field is required")
    .label("Prix initiale")
    .test(
        'is-decimal',
        'invalid decimal',
        (value:any) => (/^[0-9]+$|^[0-9]+[.][0-9]{1,2}$/).test(value)  ,
      )
.when([], {
     is: total.isGreaterThan(0) ,
     then: yup.number().max(total.toNumber())
 }),
});

The number is required and it should match float shape. The problem is when my input field is empty is shows the following message:

Prix initiale must be a number type, but the final value was: NaN (cast from the value "").

But what i want is to print the message

This field is required

I tried to add to the yup shape :

.transform((value) => (isNaN(value) || value === null || value === undefined) ? 0 : value)

But it still shows the same message .


问:
Can I connect my Wordpress form datas to a Google Cloud Storage bucket?
I'm working on a little project at the moment and I have a Wordpress webpage that can be used to upload data. In every 2 hour the data is uploaded to a Dropbox folder. Every other detail is being scraped by a Python script. The data is downloaded to a cloud vm and it does it's job, and sends back the finished work to the person who uploaded the data. I want to make a shortcut where I connect the Wordpress form to the Google Cloud Storage but I'm not sure where to start.

I should use Flask with Postgres database so in the future I canupload in the future but if I'm being honest I never used it before so any help would be appreciated.


问:
How can I use a function from my hook in a component file?
I have two files, one is my hook for my react-table and the second file is a modal. My problem is I made a delete function in my hook and need to use that function in my modal file.

How can I choose a specific function to use in my component modal from my hook?

The hook file:

```<code>const useTableResource = () => {

const deleteButton = async (row) => {
    await axios.delete(`test/api/resources?_id=${row.original._id}`);
    console.log("deleted")
  };

  const DeleteHooks = (hook) => {
    hook.visibleColumns.push((colums) => [
      ...colums,
      {
        id: 'delete',
        accessor: () => 'delete',
        Cell: ({row}) => <div onClick={(event) => event.stopPropagation()}>
          <TrashButton/>
        </div>

      }
    ]);
  };

};

export default useTableResource;
</code>```

The ModalComponent where I need to call the delete Button function:

```<code>const TrashModal = ({show, handleClose, handleConfirm}) => {
  return (
    <>
      <Modal show={show} onHide={handleClose} className="Trashmodal">
        <Modal.Header closeButton>
          <Modal.Title>attention</Modal.Title>
        </Modal.Header>
        <Modal.Body>Confirm </Modal.Body>
        <Modal.Footer className="FooterTrash">
          <Button className="btn btn-sm" variant="secondary" onClick={handleClose} autoFocus={true}>Close</Button>

          <Button className="btn btn-sm btn-primary" onClick={//i need use here deleteButton function} autoFocus={true}>
            <i className="fa fa-check" aria-hidden="true"></i>Confirm</Button>
        </Modal.Footer>
      </Modal>
    </>
  );
};
</code>```

Body:
I have two files, one is my hook for my react-table and the second file is a modal. My problem is I made a delete function in my hook and need to use that function in my modal file.

How can I choose a specific function to use in my component modal from my hook?

The hook file:

const useTableResource = () => {

const deleteButton = async (row) => {
    await axios.delete(`test/api/resources?_id=${row.original._id}`);
    console.log("deleted")
  };

  const DeleteHooks = (hook) => {
    hook.visibleColumns.push((colums) => [
      ...colums,
      {
        id: 'delete',
        accessor: () => 'delete',
        Cell: ({row}) =>
 event.stopPropagation()}>
          <TrashButton/>

      }
    ]);
  };

};

export default useTableResource;

The ModalComponent where I need to call the delete Button function:

const TrashModal = ({show, handleClose, handleConfirm}) => {
  return (
    <>
      <Modal show={show} onHide={handleClose} className="Trashmodal">
        <Modal.Header closeButton>
          <Modal.Title>attention</Modal.Title>
        </Modal.Header>
        <Modal.Body>Confirm </Modal.Body>
        <Modal.Footer className="FooterTrash">
          <Button className="btn btn-sm" variant="secondary" onClick={handleClose} autoFocus={true}>Close</Button>

          <Button className="btn btn-sm btn-primary" onClick={//i need use here deleteButton function} autoFocus={true}>
            Confirm</Button>
        </Modal.Footer>
      </Modal>
    </>
  );
};


问:
Platformio: collect2.exe: error: ld returned 1 exit status
Im not really sure what causes the following problem and i wasn't able to find anything online that helped me so far.

stacktrace

Main.cpp

The only really important out of the Main.cpp for this is

```<code>void setup() {
  Serial.begin(115200);
  controller.connectToWiFi();
}
</code>```

Complete Main.cpp

```<code>#include <Arduino.h>
#include <MCUFRIEND_kbv.h>
#include <TouchScreen.h>
#include <EEPROM.h>
#include <iostream>
#include "Controller.cpp"

#define LCD_RD  2
#define LCD_WR  4
#define LCD_RS 15
#define LCD_CS 33
#define LCD_RST 32

#define LCD_D0 12
#define LCD_D1 13
#define LCD_D2 26
#define LCD_D3 25
#define LCD_D4 17
#define LCD_D5 16
#define LCD_D6 27
#define LCD_D7 14

#define BLACK   0x0000
#define BLUE    0x001F
#define RED     0xF800
#define GREEN   0x07E0
#define CYAN    0x07FF
#define MAGENTA 0xF81F
#define YELLOW  0xFFE0
#define WHITE   0xFFFF

int XP=LCD_D6, XM=LCD_RS, YP=LCD_WR, YM=LCD_D7;
const int LEFT=-2500,RIGHT=600,TOP=687,BOT=-2200; // still needs to be calibrated

int mappedX, mappedY;

bool enableDebugLogging = true;

TouchScreen touchScreen = TouchScreen(XP, YP, XM, YM, 300);
TSPoint touchScreenPoint;
MCUFRIEND_kbv tft;
Controller controller;
int cursorStart = 0;
String message = "Hallo wie gehts";

void initializeTFTScreen() {
  tft.reset();
  tft.begin(tft.readID());
  tft.setRotation(1);
}

void mapTouchScreenPoints() {
  touchScreenPoint = touchScreen.getPoint();
  mappedX = map(touchScreenPoint.x, LEFT, RIGHT, 0, tft.width());
  mappedY = map(touchScreenPoint.y, TOP, BOT, 0, tft.height());
}

void printStringOnDisplay(const String &string, int x, int y) {
  int16_t x1, y1;
  uint16_t w, h;

  tft.fillScreen(BLACK);

  tft.getTextBounds(string, x, y, &x1, &y1, &w, &h);

  cursorStart = x-w/2;
  tft.setCursor(cursorStart, y - h / 2);

  tft.print(string);
}

void calibrateTouchScreen() {
  mapTouchScreenPoints();
  Serial.println("-----------------------");
  Serial.println("X: " + String(touchScreenPoint.x));
  Serial.println("Y: " + String(touchScreenPoint.y));
  Serial.println("mapped X: " + String(mappedX));
  Serial.println("mapped Y: " + String(mappedY));
}

void debugLog(String logEntry) {
  if (enableDebugLogging) {
    Serial.println(logEntry);
  }
}

void debugLog(int logEntry) {
  debugLog(String(logEntry));
}

void setup() {
  Serial.begin(115200);
  controller.connectToWiFi();
}

void loop() {

}
</code>```

Controller.cpp

```<code>#include <WebServer.h>
#include "Credentials.cpp"

Credentials::WlanCredentials wlan;
WebServer server(80);

class Controller {
    public:

        void connectToWiFi() {
            WiFi.begin(wlan.SSID, wlan.PASSWORD);
            Serial.println("Connecting ");
            while(WiFi.status() != WL_CONNECTED) {}
            Serial.println("Connected!");
            Serial.println("Local IP: " + WiFi.localIP());
        }

        void startWebServer() {

        }

};
</code>```

Credentials.cpp

```<code>namespace Credentials {
    class WlanCredentials {
        public:
            const char* SSID = "*";
            const char* PASSWORD = "*";
    };
}
</code>```

What i already tried was moving the WiFi package into lib_deps but without deleting the .pio directory because i need it for other dependencies
link to the post where i got this as a possible solution

based on this post
i also tried to delete C:\Users\Name.platformio\packages\toolchain-xtensa-esp32
and the I also tried to delete C:\Users\Name.platformio\packages\toolchain-xtensa

Body:
Im not really sure what causes the following problem and i wasn't able to find anything online that helped me so far.

stacktrace

Main.cpp

The only really important out of the Main.cpp for this is

void setup() {
  Serial.begin(115200);
  controller.connectToWiFi();
}

Complete Main.cpp

#include <Arduino.h>
#include <MCUFRIEND_kbv.h>
#include <TouchScreen.h>
#include <EEPROM.h>
#include <iostream>
#include "Controller.cpp"

#define LCD_RD  2
#define LCD_WR  4
#define LCD_RS 15
#define LCD_CS 33
#define LCD_RST 32

#define LCD_D0 12
#define LCD_D1 13
#define LCD_D2 26
#define LCD_D3 25
#define LCD_D4 17
#define LCD_D5 16
#define LCD_D6 27
#define LCD_D7 14

#define BLACK   0x0000
#define BLUE    0x001F
#define RED     0xF800
#define GREEN   0x07E0
#define CYAN    0x07FF
#define MAGENTA 0xF81F
#define YELLOW  0xFFE0
#define WHITE   0xFFFF

int XP=LCD_D6, XM=LCD_RS, YP=LCD_WR, YM=LCD_D7;
const int LEFT=-2500,RIGHT=600,TOP=687,BOT=-2200; // still needs to be calibrated

int mappedX, mappedY;

bool enableDebugLogging = true;

TouchScreen touchScreen = TouchScreen(XP, YP, XM, YM, 300);
TSPoint touchScreenPoint;
MCUFRIEND_kbv tft;
Controller controller;
int cursorStart = 0;
String message = "Hallo wie gehts";

void initializeTFTScreen() {
  tft.reset();
  tft.begin(tft.readID());
  tft.setRotation(1);
}

void mapTouchScreenPoints() {
  touchScreenPoint = touchScreen.getPoint();
  mappedX = map(touchScreenPoint.x, LEFT, RIGHT, 0, tft.width());
  mappedY = map(touchScreenPoint.y, TOP, BOT, 0, tft.height());
}

void printStringOnDisplay(const String &string, int x, int y) {
  int16_t x1, y1;
  uint16_t w, h;

  tft.fillScreen(BLACK);

  tft.getTextBounds(string, x, y, &x1, &y1, &w, &h);

  cursorStart = x-w/2;
  tft.setCursor(cursorStart, y - h / 2);

  tft.print(string);
}

void calibrateTouchScreen() {
  mapTouchScreenPoints();
  Serial.println("-----------------------");
  Serial.println("X: " + String(touchScreenPoint.x));
  Serial.println("Y: " + String(touchScreenPoint.y));
  Serial.println("mapped X: " + String(mappedX));
  Serial.println("mapped Y: " + String(mappedY));
}

void debugLog(String logEntry) {
  if (enableDebugLogging) {
    Serial.println(logEntry);
  }
}

void debugLog(int logEntry) {
  debugLog(String(logEntry));
}

void setup() {
  Serial.begin(115200);
  controller.connectToWiFi();
}

void loop() {

}

Controller.cpp

#include <WebServer.h>
#include "Credentials.cpp"

Credentials::WlanCredentials wlan;
WebServer server(80);

class Controller {
    public:

        void connectToWiFi() {
            WiFi.begin(wlan.SSID, wlan.PASSWORD);
            Serial.println("Connecting ");
            while(WiFi.status() != WL_CONNECTED) {}
            Serial.println("Connected!");
            Serial.println("Local IP: " + WiFi.localIP());
        }

        void startWebServer() {

        }

};

Credentials.cpp

namespace Credentials {
    class WlanCredentials {
        public:
            const char* SSID = "*";
            const char* PASSWORD = "*";
    };
}

What i already tried was moving the WiFi package into lib_deps but without deleting the .pio directory because i need it for other dependencies
link to the post where i got this as a possible solution

based on this post
i also tried to delete C:\Users\Name.platformio\packages\toolchain-xtensa-esp32
and the I also tried to delete C:\Users\Name.platformio\packages\toolchain-xtensa


问:
keras: autoencoder with trainable preprocessing
I am building an autoencoder in keras. It has only Dense layers.
I am also including a preprocessing block, where I add convolutional layers to resize my images. Similar to what is explained here: https://keras.io/examples/vision/learnable_resizer/

After the conv layers, there is a flattening operation.

I add both the preprocessing block and the autoencoder in a single trainable model. So, lets suppose, I have a 200x200 input image. After pre-processing, I have a 400x1 flatten image, that is fed to the autoencoder. The output of the autoencoder is also 400x1.

When calling fit, I have to provide both X and Y, so that Y is compared with the output of the model Y_pred to compute the cost.

The thing here is, I want Y to be the output of the preprocessing block, and not the original image.
I have no clue how to access to the output of the preprocessing block during each training step.

So basically, I want to access the output of a specific layer during each training step.

Anyone has any insight?

Regards


问:
Checking if a JTextField is Empty or less than 1
When testing my program this if statement doesn't the issue.
If I enter a number less than 1 the if statement works and catches it however when I leave the field blank the if statement does not catch it.

String txt = txtQuantity.getText();
if (Integer.parseInt(txt) < 1 || txt.equals("")) {
    lblErrorMessage.setText("Error: Please enter a quantity =>1.");
}
```


问:
How to get detect a redirect with JS
I need to check if an external URL redirects and if it does, get the new URL.

I tried doing this:

```<code>var xhr = new XMLHttpRequest();
xhr.onload = function() {
  if (this.status < 400 && this.status >= 300) {
    alert('this redirects to ' + this.getResponseHeader("Location"));
  } else {
    alert('doesn\'t redirect ');
  }
};
xhr.open('HEAD', 'http://example.com/test', true);
xhr.send();
</code>```

from this post:
detecting a redirect with javascript - how?

but it gets blocked by CORS policy. Is there any way around that?

Title: How to get detect a redirect with JS

Body:
I need to check if an external URL redirects and if it does, get the new URL.

I tried doing this:

var xhr = new XMLHttpRequest();
xhr.onload = function() {
  if (this.status < 400 && this.status >= 300) {
    alert('this redirects to ' + this.getResponseHeader("Location"));
  } else {
    alert('doesn\'t redirect ');
  }
};
xhr.open('HEAD', 'http://example.com/test', true);
xhr.send();

from this post:
detecting a redirect with javascript - how?

but it gets blocked by CORS policy. Is there any way around that?


问:
My PyPi package can be installed with pip but I can't import it
I've created a Python project and I've uploaded to PyPi using Twine.

The project is now visible on PyPi and I can install my package via pip with pip install my_package
However, after installing it, if in a new project I try to import it using import my_package I get the ModuleNotFound error.

I go to my site-packages folder and, in fact, I notice that there is only my_package.dist without the actual package... What did I do wrong during the configuration?

I used setup.cfg instead a setup.py , could this be the cause? I also have a __ init __.py file which I leaved empty (as it was written in a tutorial that I followed)

These is my setup.cfg and pyproject.toml files:

setup.cfg:

```<code>[metadata]
name = example_package
version = 0.0.1
author = Me
author_email = me@example.com
description = example description
long_description = file: README.md
long_description_content_type = text/markdown
url = https://github.com/example/example
classifiers =
    Programming Language :: Python :: 3
    License :: OSI Approved :: MIT License
    Operating System :: OS Independent
[options]
packages = find:
python_requires = >=3.6
include_package_data = True
</code>```

pyproject.toml:

```<code>[build-system]
requires      = ["setuptools", "wheel"]
build-backend = "setuptools.build_meta"

[project]
name = "example_package"
version = "0.0.1"
description = "example description"
readme = "README.md"
authors = [{ name = "me", email = "me@example.com" }]
license = { file = "LICENSE" }
classifiers = [
    "License :: OSI Approved :: MIT License",
    "Programming Language :: Python",
    "Programming Language :: Python :: 3",
]
keywords = ["some", "tags", "opensource"]
dependencies = [

]
requires-python = ">=3.6"

[project.urls]
Homepage = "https://github.com/example/example"

</code>```

Body:
I've created a Python project and I've uploaded to PyPi using Twine.

The project is now visible on PyPi and I can install my package via pip with pip install my_package
However, after installing it, if in a new project I try to import it using import my_package I get the ModuleNotFound error.

I go to my site-packages folder and, in fact, I notice that there is only my_package.dist without the actual package... What did I do wrong during the configuration?

I used setup.cfg instead a setup.py , could this be the cause? I also have a __ init __.py file which I leaved empty (as it was written in a tutorial that I followed)

These is my setup.cfg and pyproject.toml files:

setup.cfg:

[metadata]
name = example_package
version = 0.0.1
author = Me
author_email = me@example.com
description = example description
long_description = file: README.md
long_description_content_type = text/markdown
url = https://github.com/example/example
classifiers =
    Programming Language :: Python :: 3
    License :: OSI Approved :: MIT License
    Operating System :: OS Independent
[options]
packages = find:
python_requires = >=3.6
include_package_data = True

pyproject.toml:

[build-system]
requires      = ["setuptools", "wheel"]
build-backend = "setuptools.build_meta"

[project]
name = "example_package"
version = "0.0.1"
description = "example description"
readme = "README.md"
authors = [{ name = "me", email = "me@example.com" }]
license = { file = "LICENSE" }
classifiers = [
    "License :: OSI Approved :: MIT License",
    "Programming Language :: Python",
    "Programming Language :: Python :: 3",
]
keywords = ["some", "tags", "opensource"]
dependencies = [

]
requires-python = ">=3.6"

[project.urls]
Homepage = "https://github.com/example/example"


问:
Problem trying to load a set of image using an array of UIImage to slide them
I'm trying to load a set of pictures to an imageView so that they slide alon with a time timer.

My problem is that I have the pictures store in Firebase with their URL as Strings. So I use a function to load a single image throug its URL into an imageView and it works. But now I need to find a way to use a function to put a set of images into the imageView so that the slide with a timer and I don´t now how to do it.

This is the code to load the images from URL

```<code>import UIKit

extension UIImageView {

func loadFrom(URLAddress: String) {

    guard let url = URL(string: URLAddress) else {
            return
        }
    DispatchQueue.main.async { [weak self] in
        if let imageData = try? Data(contentsOf: url) {
                if let loadedImage = UIImage(data: imageData) {
                        self?.image = loadedImage
                }
            }
        }
    }
}
</code>```

Here is the code to load the set of image as an UIImage array.

```<code>override func viewWillAppear(_ animated: Bool) {
        let even = eventos.eventoPulsado()
        var images = [UIImage]()
        print(even.imagenes!)
        //I load the picture this way
        imgFoto.loadFrom(URLAddress: (even.imagenes![0]))
        //But I cannot to append my images because I need UIImage data
        images.append(imgFoto.image!)

        for img in (even.imagenes!) {
            imgFoto.loadFrom(URLAddress: (img))
        }
        imgFoto.animationImages = images
        imgFoto.animationDuration = TimeInterval(0.4)
        imgFoto.animationRepeatCount = 4
        imgFoto.startAnimating()

    }
</code>```

Body:
I'm trying to load a set of pictures to an imageView so that they slide alon with a time timer.

My problem is that I have the pictures store in Firebase with their URL as Strings. So I use a function to load a single image throug its URL into an imageView and it works. But now I need to find a way to use a function to put a set of images into the imageView so that the slide with a timer and I don´t now how to do it.

This is the code to load the images from URL

import UIKit

extension UIImageView {

func loadFrom(URLAddress: String) {

    guard let url = URL(string: URLAddress) else {
            return
        }
    DispatchQueue.main.async { [weak self] in
        if let imageData = try? Data(contentsOf: url) {
                if let loadedImage = UIImage(data: imageData) {
                        self?.image = loadedImage
                }
            }
        }
    }
}

Here is the code to load the set of image as an UIImage array.

override func viewWillAppear(_ animated: Bool) {
        let even = eventos.eventoPulsado()
        var images = [UIImage]()
        print(even.imagenes!)
        //I load the picture this way
        imgFoto.loadFrom(URLAddress: (even.imagenes![0]))
        //But I cannot to append my images because I need UIImage data
        images.append(imgFoto.image!)

        for img in (even.imagenes!) {
            imgFoto.loadFrom(URLAddress: (img))
        }
        imgFoto.animationImages = images
        imgFoto.animationDuration = TimeInterval(0.4)
        imgFoto.animationRepeatCount = 4
        imgFoto.startAnimating()

    }


问:
How to create an ant project in intelliJ with existing source?
I would like to work on an ant project from github with intelliJ. The project works with netbeans where I created a new project with existing source, but it doesn´t really work with intelliJ.

The repository does not include the build file. I copied over the build.xml from the netbeans project and tried to right click on it and build the project. It doesn´t seem to work. Any advice?


问:
How to aggregate and limit the documents based on an array inside of an object from the req.body?
First of all, I'm Brazilian and my English (also my programming) are not that god but I will try to do my best here (desperate times call for... you know.).

Well, I'm just trying to create an order.

I'm passing through the body an object that consists of the seller, the customer, and an array with the typeProduct ids (which I'm going to use to bring all the itemProducts that matches it) and the quantity that I need to limit these products aggregated by these IDs

The limit that I want to pass in each one is on "qty"

i just cant go on from here...

Then I just separate the ids...
...
and the result returns all matched objects

I just need a way to aggregate this objects limiting the quantity of the itemObjects based on the value of the 'qty.'

I tried a lot of crazy stuff, even:

```<code>**
req.body.typeProducts.forEach(item){
 const dbItemProducts = await item.find(
      {
         $and: [
        {
            'typeProduct': item.typeProductId,
         },
         {
             isAvailable: { $eq: true },
          },
        ],
       },
    ).limit(item.qty);
}**

...of course, and find() inside a foreach didn't work.
</code>```

Body:
First of all, I'm Brazilian and my English (also my programming) are not that god but I will try to do my best here (desperate times call for... you know.).

Well, I'm just trying to create an order.

I'm passing through the body an object that consists of the seller, the customer, and an array with the typeProduct ids (which I'm going to use to bring all the itemProducts that matches it) and the quantity that I need to limit these products aggregated by these IDs

The limit that I want to pass in each one is on "qty"

i just cant go on from here...

Then I just separate the ids...
...
and the result returns all matched objects

I just need a way to aggregate this objects limiting the quantity of the itemObjects based on the value of the 'qty.'

I tried a lot of crazy stuff, even:

**
req.body.typeProducts.forEach(item){
 const dbItemProducts = await item.find(
      {
         $and: [
        {
            'typeProduct': item.typeProductId,
         },
         {
             isAvailable: { $eq: true },
          },
        ],
       },
    ).limit(item.qty);
}**

...of course, and find() inside a foreach didn't work.


问:
pdftk split pages by dynamic ranges php
I want to split one PDF into multiple pages - the page-ranges are alway different, defined by a user.
I know that pdftk has this feature, but i'm stuck on calculating the ranges.

My approach:
I read the PDF, convert the pages to a image - now i am able to display every single page in a grid. I also have a checkbox beside every page, so the user can select where to split the PDF.

```<code><input type="checkbox" name="ranges[]" value="{{ index }}" />
</code>```

Let's say the PDF has 7 pages, the user want to split into: page1, page2-3, page4-5 and page6-end. My ranges-array looks like this:

```<code>Array
(
    [0] => 1
    [1] => 3
    [2] => 5
)
</code>```

Now i know after which page i need the cut, but how to determine the ranges in between and then the last pages (6-7)? I don't have any clue how to approach this so i would be greatful for any hint.

Thanks so much

Title: pdftk split pages by dynamic ranges php

Body:
I want to split one PDF into multiple pages - the page-ranges are alway different, defined by a user.
I know that pdftk has this feature, but i'm stuck on calculating the ranges.

My approach:
I read the PDF, convert the pages to a image - now i am able to display every single page in a grid. I also have a checkbox beside every page, so the user can select where to split the PDF.

<input type="checkbox" name="ranges[]" value="{{ index }}" />

Let's say the PDF has 7 pages, the user want to split into: page1, page2-3, page4-5 and page6-end. My ranges-array looks like this:

Array
(
    [0] => 1
    [1] => 3
    [2] => 5
)

Now i know after which page i need the cut, but how to determine the ranges in between and then the last pages (6-7)? I don't have any clue how to approach this so i would be greatful for any hint.

Thanks so much


问:
Which sequence of bytes is the flag for determining file corruption?
I need to create a program that finds DOC, DOCX files in a folder and determines if the file is damaged or not. After that, distribute the files into two folders, respectively.
How do I know if a file is corrupted? Which sequence of bytes is the flag for determining file corruption?
If anyone has experienced something similar, please help me.

I read [MS-DOC]: Word (.doc) Binary File Format but I didn't find anything


问:
update qty value in DataGridView
If row with the same data already exists in DataGridView , just increment the value of Qty
don't want when add take new column.

image :
enter image description here

source ---
add_btn

```<code> DataTable tblProduct = new DataTable();
            tblProduct.Clear();
            tblProduct = db.readData("select * from Products where Pro_id="+cbxProduct.SelectedValue+"","");

            if (tblProduct.Rows.Count >= 1)
            {
                try
                {
                    string Pro_id = tblProduct.Rows[0][0].ToString();
                    string Pro_Name = tblProduct.Rows[0][1].ToString();
                    string Product_Qty = "1";
                    string Product_buyprice = tblProduct.Rows[0][3].ToString();
                    decimal Product_discount = 0;
                    decimal total = Convert.ToDecimal(Product_Qty) * Convert.ToDecimal(tblProduct.Rows[0][3]);

                    dgvbuy.Rows.Add(1);
                    int rowindex = dgvbuy.Rows.Count - 1;

                    dgvbuy.Rows[rowindex].Cells[0].Value = Pro_id;
                    dgvbuy.Rows[rowindex].Cells[1].Value = Pro_Name;
                    dgvbuy.Rows[rowindex].Cells[2].Value = Product_Qty;
                    dgvbuy.Rows[rowindex].Cells[3].Value = Product_buyprice;
                    dgvbuy.Rows[rowindex].Cells[4].Value = Product_discount;
                    dgvbuy.Rows[rowindex].Cells[5].Value = total;

                }
                catch (Exception)
                {

                }
                try
                {
                    decimal total=0;
                    for (int i =0; i <= dgvbuy.Rows.Count -1;i++)
                    {
                        total += Convert.ToDecimal(dgvbuy.Rows[i].Cells[5].Value);
                        dgvbuy.ClearSelection();
                        dgvbuy.FirstDisplayedScrollingRowIndex = dgvbuy.Rows.Count - 1;
                        dgvbuy.Rows[dgvbuy.Rows.Count - 1].Selected = true;
                    }
                    totalAmount.Text = Math.Round(total , 2).ToString();
                    lblItems.Text = (dgvbuy.Rows.Count).ToString();

                } catch (Exception) { }
            }
</code>```

I knew there is sql injection just learning so ...

Title: update qty value in DataGridView

Body:
If row with the same data already exists in DataGridView , just increment the value of Qty
don't want when add take new column.

image :
enter image description here

source ---
add_btn

 DataTable tblProduct = new DataTable();
            tblProduct.Clear();
            tblProduct = db.readData("select * from Products where Pro_id="+cbxProduct.SelectedValue+"","");

            if (tblProduct.Rows.Count >= 1)
            {
                try
                {
                    string Pro_id = tblProduct.Rows[0][0].ToString();
                    string Pro_Name = tblProduct.Rows[0][1].ToString();
                    string Product_Qty = "1";
                    string Product_buyprice = tblProduct.Rows[0][3].ToString();
                    decimal Product_discount = 0;
                    decimal total = Convert.ToDecimal(Product_Qty) * Convert.ToDecimal(tblProduct.Rows[0][3]);

                    dgvbuy.Rows.Add(1);
                    int rowindex = dgvbuy.Rows.Count - 1;

                    dgvbuy.Rows[rowindex].Cells[0].Value = Pro_id;
                    dgvbuy.Rows[rowindex].Cells[1].Value = Pro_Name;
                    dgvbuy.Rows[rowindex].Cells[2].Value = Product_Qty;
                    dgvbuy.Rows[rowindex].Cells[3].Value = Product_buyprice;
                    dgvbuy.Rows[rowindex].Cells[4].Value = Product_discount;
                    dgvbuy.Rows[rowindex].Cells[5].Value = total;

                }
                catch (Exception)
                {

                }
                try
                {
                    decimal total=0;
                    for (int i =0; i <= dgvbuy.Rows.Count -1;i++)
                    {
                        total += Convert.ToDecimal(dgvbuy.Rows[i].Cells[5].Value);
                        dgvbuy.ClearSelection();
                        dgvbuy.FirstDisplayedScrollingRowIndex = dgvbuy.Rows.Count - 1;
                        dgvbuy.Rows[dgvbuy.Rows.Count - 1].Selected = true;
                    }
                    totalAmount.Text = Math.Round(total , 2).ToString();
                    lblItems.Text = (dgvbuy.Rows.Count).ToString();

                } catch (Exception) { }
            }

I knew there is sql injection just learning so ...


问:
Create polygon shapefile from point shapefile in python
I am a beginner (very little experience) in Python. I am trying to use it with QGIS.

I have a points shapefile (pt.shp), and I would like to create a polygon shapefile (pol.shp) using Python.

Could anyone suggest code to build a polygon shapefile from the points shapefile?

I have only been able to order the points using geopandas with the following code:

```<code>import geopandas as gpd
shp = 'pt.shp'
gdf_pol = gpd.read_file(shp) # Read shapefile as geodataframe
ordered_gdf = gdf_pol.sort_values('point_id') # Sort by NAME column
print(ordered_gdf)
</code>```

Body:
I am a beginner (very little experience) in Python. I am trying to use it with QGIS.

I have a points shapefile (pt.shp), and I would like to create a polygon shapefile (pol.shp) using Python.

Could anyone suggest code to build a polygon shapefile from the points shapefile?

I have only been able to order the points using geopandas with the following code:

import geopandas as gpd
shp = 'pt.shp'
gdf_pol = gpd.read_file(shp) # Read shapefile as geodataframe
ordered_gdf = gdf_pol.sort_values('point_id') # Sort by NAME column
print(ordered_gdf)


问:
How do you make a Vuelidate typescript validator with optional parent fields?
How do you make a validator for data with an optional field that has nested fields?

useVuelidate accepts a "rules" object as it's first parameter and there doesn't seem to be a way to mark a property with nested children as optional. Because of this typescript reports an error, since in the data passed as the second parameter to useVuelidate, the field in question is optional.

This is the data structure I'm working with and as you see secondAddress is optional.

const rules = {
  name: {
    required
  },
  address: {
    city: { required },
    street: { required },
  },
  secondAddress: {
    city: { required },
    street: { required }
  }
};

interface UserForm {
  name: string;
  address: {
    city: string;
    street: string;
  }
  secondAddress?: {
    city: string;
    street: string;
  }
}

const userForm = ref<UserForm>({
  name: '',
  address: {
    city: '',
    street: ''
  },
  secondAddress: {
    city: '',
    street: ''
  }
})

const v$ = useVuelidate(rules, userForm);
```
<p>How do I prevent typescript from throwing this error on <code>useVuelidate</code>:</p>
```Argument of type 'Ref<{ name: string; address: { city: string; street: string; }; secondAddress?: { city: string; street: string; } | undefined; }>' is not assignable to parameter of type '{ name: any; address: any; secondAddress: any; } | Ref<{ name: any; address: any; secondAddress: any; }> | ToRefs<{ name: any; address: any; secondAddress: any; }>'.
  Type 'Ref<{ name: string; address: { city: string; street: string; }; secondAddress?: { city: string; street: string; } | undefined; }>' is not assignable to type 'Ref<{ name: any; address: any; secondAddress: any; }>'.
```

Repository with minimal reproduction

Is this a limitation of Vuelidate that parents can't be optional?

Body:
How do you make a validator for data with an optional field that has nested fields?

useVuelidate accepts a "rules" object as it's first parameter and there doesn't seem to be a way to mark a property with nested children as optional. Because of this typescript reports an error, since in the data passed as the second parameter to useVuelidate, the field in question is optional.

This is the data structure I'm working with and as you see secondAddress is optional.

const rules = {
  name: {
    required
  },
  address: {
    city: { required },
    street: { required },
  },
  secondAddress: {
    city: { required },
    street: { required }
  }
};

interface UserForm {
  name: string;
  address: {
    city: string;
    street: string;
  }
  secondAddress?: {
    city: string;
    street: string;
  }
}

const userForm = ref<UserForm>({
  name: '',
  address: {
    city: '',
    street: ''
  },
  secondAddress: {
    city: '',
    street: ''
  }
})

const v$ = useVuelidate(rules, userForm);

How do I prevent typescript from throwing this error on useVuelidate:

Argument of type 'Ref<{ name: string; address: { city: string; street: string; }; secondAddress?: { city: string; street: string; } | undefined; }>' is not assignable to parameter of type '{ name: any; address: any; secondAddress: any; } | Ref<{ name: any; address: any; secondAddress: any; }> | ToRefs<{ name: any; address: any; secondAddress: any; }>'.
  Type 'Ref<{ name: string; address: { city: string; street: string; }; secondAddress?: { city: string; street: string; } | undefined; }>' is not assignable to type 'Ref<{ name: any; address: any; secondAddress: any; }>'.

Repository with minimal reproduction

Is this a limitation of Vuelidate that parents can't be optional?


问:
Cannot find method fetch in JoinColumn Interface
I have this jpa entity and I want to add fetch  type EAGER to it

```<code>package com.example.application.data.entity;
import javax.persistence.Entity;
import java.util.*;
import com.example.application.data.AbstractEntity;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import javax.persistence.OneToMany;
import java.util.logging.Logger;
import javax.persistence.*;

@Entity
public class Supplier extends AbstractEntity {
    @NotEmpty
    private String name;
    @NotEmpty
    private String address;

    @OneToMany(fetch = FetchType.EAGER, mappedBy = "supplier")
    @NotNull
    private Set<Category> categories = new LinkedHashSet<>();
</code>```

But when I try to build my application I get the following error

```<code>cannot find symbol
    @JoinColumn(fetch = FetchType.EAGER, name = "supplier_id")
                ^
  symbol:   method fetch()
  location: @interface JoinColumn
1 error

FAILURE: Build failed with an exception.
</code>```

Why am I getting this error?

Body:
I have this jpa entity and I want to add fetch  type EAGER to it

package com.example.application.data.entity;
import javax.persistence.Entity;
import java.util.*;
import com.example.application.data.AbstractEntity;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import javax.persistence.OneToMany;
import java.util.logging.Logger;
import javax.persistence.*;

@Entity
public class Supplier extends AbstractEntity {
    @NotEmpty
    private String name;
    @NotEmpty
    private String address;

    @OneToMany(fetch = FetchType.EAGER, mappedBy = "supplier")
    @NotNull
    private Set<Category> categories = new LinkedHashSet<>();

But when I try to build my application I get the following error

cannot find symbol
    @JoinColumn(fetch = FetchType.EAGER, name = "supplier_id")
                ^
  symbol:   method fetch()
  location: @interface JoinColumn
1 error

FAILURE: Build failed with an exception.

Why am I getting this error?


问:
Issue with the setup code base on local machine swell stores horizon Public repo
Trying to setup an open source repo.

https://github.com/swellstores/horizon

Try to setup this code base on my local machine also try with the GitHub online codebase the issue is the same.

Any one can help me?


问:
Allocation failed: std::bad_alloc with method using isl library methods
The following method is causing bad memory allocation exceptions, I can't seem to find where this is exactly happening, for context the method is using the isl library to construct a map containing a set of iterators names with their number of constraints:

```<code>
    std::unordered_map<std::string, int> utility::get_constraints_map(isl_set *set)
    {
    isl_basic_set_list *bset_list = isl_set_get_basic_set_list(set);
    std::unordered_map<std::string, int> constraints_map{};

    int n_basic_set = isl_set_n_basic_set(set);
    for (int i = 0; i < n_basic_set; i++)
    {
        isl_basic_set *bset = isl_basic_set_list_get_basic_set(bset_list, i);
        isl_constraint_list *cst_list = isl_basic_set_get_constraint_list(bset);
        for (int j = 0; j < isl_constraint_list_n_constraint(cst_list); j++)
        {
            isl_constraint *cst = isl_constraint_list_get_constraint(cst_list, j);

            for (int k = 0; k < isl_set_dim(set, isl_dim_out); k++)
            {
                std::string dim_name = isl_set_get_dim_name(set, isl_dim_out, k);

                if (isl_constraint_involves_dims(cst, isl_dim_set, k, 1))
                {
                    if (constraints_map.find(dim_name) != constraints_map.end())
                    {
                        constraints_map.at(dim_name) = constraints_map[dim_name] + 1;
                    }
                    else
                    {
                        constraints_map.insert({dim_name, 0});
                    }
                    break;
                }
            }
        }

    }
        return constraints_map;

    }
</code>```

I tried to free each object (stil same problem) using the dedicated isl methods:

```<code>    isl_constraint_free
    isl_basic_set_free
    isl_
</code>```

Body:
The following method is causing bad memory allocation exceptions, I can't seem to find where this is exactly happening, for context the method is using the isl library to construct a map containing a set of iterators names with their number of constraints:

    std::unordered_map<std::string, int> utility::get_constraints_map(isl_set *set)
    {
    isl_basic_set_list *bset_list = isl_set_get_basic_set_list(set);
    std::unordered_map<std::string, int> constraints_map{};

    int n_basic_set = isl_set_n_basic_set(set);
    for (int i = 0; i < n_basic_set; i++)
    {
        isl_basic_set *bset = isl_basic_set_list_get_basic_set(bset_list, i);
        isl_constraint_list *cst_list = isl_basic_set_get_constraint_list(bset);
        for (int j = 0; j < isl_constraint_list_n_constraint(cst_list); j++)
        {
            isl_constraint *cst = isl_constraint_list_get_constraint(cst_list, j);

            for (int k = 0; k < isl_set_dim(set, isl_dim_out); k++)
            {
                std::string dim_name = isl_set_get_dim_name(set, isl_dim_out, k);

                if (isl_constraint_involves_dims(cst, isl_dim_set, k, 1))
                {
                    if (constraints_map.find(dim_name) != constraints_map.end())
                    {
                        constraints_map.at(dim_name) = constraints_map[dim_name] + 1;
                    }
                    else
                    {
                        constraints_map.insert({dim_name, 0});
                    }
                    break;
                }
            }
        }

    }
        return constraints_map;

    }

I tried to free each object (stil same problem) using the dedicated isl methods:

    isl_constraint_free
    isl_basic_set_free
    isl_


问:
Error: Cannot find module 'koa' - ECS Fargate
I have a basic node application that I'm building with docker and attempting to utilize with ECS Fargate. When the task is run, however, I see Cannot find module 'koa' in the logs, before the container exits in failure.

I imagine this is an ECS-specific problem and am hoping for advice. This is my first time working with ECS and Fargate.

From the local app directory I can successfully run everything using
npm install ->
npm start .
I can hit a test endpoint that I've configured and get the response that I expect.

On Docker locally, I can run docker build -t myservice . and then docker run -dp 3000:3000 myservice and I am able to access logs, see that things start as expected and I can hit the same test endpoint with success. The docker container running has a node_modules dir which contains koa

Are there environment specific things I should be configuring for this to work with ECS & Fargate?

Dockerfile:

```<code>FROM mhart/alpine-node:7.10.1

WORKDIR /srv
ADD . .
RUN npm install --production --silent
COPY . .
EXPOSE 3000
CMD ["node", "server.js"]
</code>```

Body:
I have a basic node application that I'm building with docker and attempting to utilize with ECS Fargate. When the task is run, however, I see Cannot find module 'koa' in the logs, before the container exits in failure.

I imagine this is an ECS-specific problem and am hoping for advice. This is my first time working with ECS and Fargate.

From the local app directory I can successfully run everything using
npm install ->
npm start .
I can hit a test endpoint that I've configured and get the response that I expect.

On Docker locally, I can run docker build -t myservice . and then docker run -dp 3000:3000 myservice and I am able to access logs, see that things start as expected and I can hit the same test endpoint with success. The docker container running has a node_modules dir which contains koa

Are there environment specific things I should be configuring for this to work with ECS & Fargate?

Dockerfile:

FROM mhart/alpine-node:7.10.1

WORKDIR /srv
ADD . .
RUN npm install --production --silent
COPY . .
EXPOSE 3000
CMD ["node", "server.js"]


问:
View port set but it's being ignored?
I have set the viewport of my website as:

```<code><meta name="viewport" content="width=device-width, initial-scale=1">
</code>```

However, it's not being seen. I use child theme and the viewport is added to my main theme header.

I tried adding this on my main theme, but Google is not seeing it.

My website is TheCityCeleb

Title: View port set but it's being ignored?

Body:
I have set the viewport of my website as:

<meta name="viewport" content="width=device-width, initial-scale=1">

However, it's not being seen. I use child theme and the viewport is added to my main theme header.

I tried adding this on my main theme, but Google is not seeing it.

My website is TheCityCeleb


问:
How can i add a function that goes back to the previous contact information of the api on button click?
i am creating a react app that uses a custom hook to fetch the api from a website. i have a button that displays the next person's contact information in that api on button click. i want to create a back button with an onclick function to go back to the previous person's contact. how do i do that? this is the useFetch custom hook.

this is the useFetch custom hook.
`

```<code>import axios from 'axios'
import { useState,useEffect } from 'react'
function useFetch(url) {
    const [data,setData]=useState(null)
     const [error,setError]=useState(false)
      const [loading,setLoading]=useState(null)
    useEffect(()=>{
        setLoading(true)
axios.get(url).then((response)=>{
   setData(response.data)
}).catch((err)=>{
    setError(err)
}).finally(()=>{
    setLoading(false)
})

},[url])
const refetch=()=>{
    setLoading(true)
axios.get(url).then((response)=>{
   setData(response.data)
}).catch((err)=>{
    setError(err)
}).finally(()=>{
    setLoading(false)
})
  }
 return {data,error,loading,refetch}
}

export default useFetch
</code>```

this is the app page with the render that im trying to create a back function

```<code>import './App.css';
import useFetch from './useFetch';

function App() {
  const {data,error,loading,refetch}=useFetch("https://randomuser.me/api/")

if(loading){ return <h1>Loading..</h1>}
if(error) {console.log(error)}
const image=data.results[0].picture.large
 return (
    <div className="App">
 {data?.results[0].name.first}<br/>
 <button onClick={back}>back</button>
 <button onClick={refetch}>next</button><br/>
 <img src={image} alt="ima"/>
    </div>
  );
}

export default App;

</code>```

`
how do i create a back function that goes back to the previous contact info?

Body:
i am creating a react app that uses a custom hook to fetch the api from a website. i have a button that displays the next person's contact information in that api on button click. i want to create a back button with an onclick function to go back to the previous person's contact. how do i do that? this is the useFetch custom hook.

this is the useFetch custom hook.
`

import axios from 'axios'
import { useState,useEffect } from 'react'
function useFetch(url) {
    const [data,setData]=useState(null)
     const [error,setError]=useState(false)
      const [loading,setLoading]=useState(null)
    useEffect(()=>{
        setLoading(true)
axios.get(url).then((response)=>{
   setData(response.data)
}).catch((err)=>{
    setError(err)
}).finally(()=>{
    setLoading(false)
})

},[url])
const refetch=()=>{
    setLoading(true)
axios.get(url).then((response)=>{
   setData(response.data)
}).catch((err)=>{
    setError(err)
}).finally(()=>{
    setLoading(false)
})
  }
 return {data,error,loading,refetch}
}

export default useFetch

this is the app page with the render that im trying to create a back function

import './App.css';
import useFetch from './useFetch';

function App() {
  const {data,error,loading,refetch}=useFetch("https://randomuser.me/api/")

if(loading){ return
Loading..
}
if(error) {console.log(error)}
const image=data.results[0].picture.large
 return (

 {data?.results[0].name.first}

 <button onClick={back}>back</button>
 <button onClick={refetch}>next</button>

  );
}

export default App;

`
how do i create a back function that goes back to the previous contact info?


问:
How can I automatically load an sqlite extension in sqlite3 for node.js?
I'm using the SQLite3 bindings for Node.js.

I my app I require an sqlite extension.  I'm able to load and use it in my app just fine.

The sqlite3 API has a call to load extensions, but I want the extension(s) loaded without having to make the call.

The issue is that, without the extension, sqlite tools e.g. database browsers can't properly access the database and so far, I haven't found any that allow the user to specify extensions to be loaded.

I've searched for every kind of import/require etc. hook that I can think of but I can't find a place to insert code to be run as part of the initial sqlite3 require() that would allow me to automatically load the extensions needed to access my database, regardless of what app loads sqlite3.

I thought I might be able to just compile the extensions in, but I didn't find anything in the  the compile docs about extensions other than a couple that are supported out of the box.  Nor were there any I could find in the  sqlite3 source install docs.

Is there a way to get sqlite3 extensions automatically loaded by sqlite3, regardless of what app is loading it?


问:
How To Join Two xPaths In One Single Collection?
var processorTitles = document.DocumentNode.SelectNodes("//div[@class='pad-hrz-xs']/a[@data-zone='title']");

var processorsPrices = document.DocumentNode.SelectNodes("//div[@class='card-v2-pricing']/p[@class='product-new-price']");

This will give me two diffrent Lists , I want to Combine This Two Xpaths , so that I can recive One Single List.

I , already tried something Like This : ("//div[@class='pad-hrz-xs']/a[@data-zone='title'] or //div[@class='card-v2-pricing']/p[@class='product-new-price']") , but nothing same result.

I , also tried  with " | " sign instead of "or" : ("//div[@class='pad-hrz-xs']/a[@data-zone='title'] | //div[@class='card-v2-pricing']/p[@class='product-new-price']") , but nothing same result.

I want to combine this two xPath , so that I will recive one single List.


问:
Laravel Dusk retrieve result of a function
I'm writing my first Dusk test, and I am facing some issues:
I need to click on a button on a page, inside a form, that has a onClick() that triggers a JavaScript function. This function show a span#answer = some number.

The URL is: this
As you can see, as clicking on the button, the page reloads to show the answer and that's the answer I need to get on the test.

Let's see some code I have done already:

```<code>    public function testDescobrirResposta()
    {
        $this->browse(function (Browser $browser) {
            $browser->visit('http://applicant-test.us-east-1.elasticbeanstalk.com/');
            $btn = $browser->assertButtonEnabled('Descobrir resposta');
            $btn->click();
        });
    }
</code>```

The result so far is:

```<code>PHPUnit 9.5.27 by Sebastian Bergmann and contributors.

.                                                                   1 / 1 (100%)

Time: 00:02.079, Memory: 20.00 MB

OK (1 test, 1 assertion)
</code>```

Any helps?
Thanks in advance!

Body:
I'm writing my first Dusk test, and I am facing some issues:
I need to click on a button on a page, inside a form, that has a onClick() that triggers a JavaScript function. This function show a span#answer = some number.

The URL is: this
As you can see, as clicking on the button, the page reloads to show the answer and that's the answer I need to get on the test.

Let's see some code I have done already:

    public function testDescobrirResposta()
    {
        $this->browse(function (Browser $browser) {
            $browser->visit('http://applicant-test.us-east-1.elasticbeanstalk.com/');
            $btn = $browser->assertButtonEnabled('Descobrir resposta');
            $btn->click();
        });
    }

The result so far is:

PHPUnit 9.5.27 by Sebastian Bergmann and contributors.

.                                                                   1 / 1 (100%)

Time: 00:02.079, Memory: 20.00 MB

OK (1 test, 1 assertion)

Any helps?
Thanks in advance!


问:
Modify scripts/iFrames on WP site via output buffering
I'm searching for a proper way to use OB to modify a script in my head as well as native WP-embeds for Twitter/Reddit in posts on the fly for guest users.

So far, I'm using this (it works for the head script but not for the embeds, unfortunately):

```<code>if ( !is_admin() ) {

    function change_code($buffer) {

        $find = array(

            'text/javascript" src="https://www.googletagmanager.com/gtag/js?id=XXX"',
            'src="https://platform.twitter.com/widgets.js" charset="utf-8" type="text/javascript"',
            'src="https://embed.redditmedia.com/widgets/platform.js" charset="UTF-8" type="text/javascript"');

        $replace  = array(

            'text/plain" src="https://www.googletagmanager.com/gtag/js?id=XXX"',
            'src="https://platform.twitter.com/widgets.js" charset="utf-8" type="text/plain"',
            'src="https://embed.redditmedia.com/widgets/platform.js" charset="UTF-8" type="text/plain"');

        $buffer = str_replace($find, $replace, $buffer);
        return $buffer;

    }

    add_action('wp_loaded', 'buffer_start'); function buffer_start() { ob_start("change_code"); }
    add_action('shutdown', 'buffer_end'); function buffer_end() { ob_end_flush(); }

}
</code>```

A workaround for the embeds would be to address the iFrame-code they're creating. Tried that too, but didn't have any success on this either.
In addition, when enabling WP-debug, I get the following error pretty often:

PHP Notice:  ob_end_flush(): Failed to delete and flush buffer. No buffer to delete or flush in [...]child/functions.php (using WP 6.0.3, PHP 8.1.13)

Could somebody help me in finding a way to fix this? Not sure if the code I'm using is still following modern/efficient standards - I found this topic as an alternative, but didn't manage to adjust their solutions to any working degree for my use case (made the modification to the GTag-script stop working also).

Thanks for your time,
eC

Body:
I'm searching for a proper way to use OB to modify a script in my head as well as native WP-embeds for Twitter/Reddit in posts on the fly for guest users.

So far, I'm using this (it works for the head script but not for the embeds, unfortunately):

if ( !is_admin() ) {

    function change_code($buffer) {

        $find = array(

            'text/javascript" src="https://www.googletagmanager.com/gtag/js?id=XXX"',
            'src="https://platform.twitter.com/widgets.js" charset="utf-8" type="text/javascript"',
            'src="https://embed.redditmedia.com/widgets/platform.js" charset="UTF-8" type="text/javascript"');

        $replace  = array(

            'text/plain" src="https://www.googletagmanager.com/gtag/js?id=XXX"',
            'src="https://platform.twitter.com/widgets.js" charset="utf-8" type="text/plain"',
            'src="https://embed.redditmedia.com/widgets/platform.js" charset="UTF-8" type="text/plain"');

        $buffer = str_replace($find, $replace, $buffer);
        return $buffer;

    }

    add_action('wp_loaded', 'buffer_start'); function buffer_start() { ob_start("change_code"); }
    add_action('shutdown', 'buffer_end'); function buffer_end() { ob_end_flush(); }

}

A workaround for the embeds would be to address the iFrame-code they're creating. Tried that too, but didn't have any success on this either.
In addition, when enabling WP-debug, I get the following error pretty often:

PHP Notice:  ob_end_flush(): Failed to delete and flush buffer. No buffer to delete or flush in [...]child/functions.php (using WP 6.0.3, PHP 8.1.13)

Could somebody help me in finding a way to fix this? Not sure if the code I'm using is still following modern/efficient standards - I found this topic as an alternative, but didn't manage to adjust their solutions to any working degree for my use case (made the modification to the GTag-script stop working also).

Thanks for your time,
eC


问:
VS Code setup with ROS Extension
First, I am using the MS supplied ROS extension, available at the extension: ms-iot.vscode-ros I mention that because when searching there are lots is lots of noise about ROS and VSCode.

My setup is as follows (very vanilla ros package):

```<code>ws/
  custom_package/
   / src
      /custom_package
        /foo.py -> contain class DoAThing
   / scripts
      myscript.py
  custom_package_msgs/
   /msg
     MyMsg.msg
</code>```

My CMakelists.txt for both projects are correct. I can catkin build and roslaunch fine.

I am trying to figure out the following two issues.

The modules under src are not available for autocomplete/highlighting in the scripts package. Again, these import fine when launching or running a node. I'm simply unable to get any form of intellisense when in the scripts folder. I'm following the convention of

in scripts/myscript.py I import as

```<code>from custom_package.foo import DoAThing

</code>```

There is no intellisense for custom msgs. So in foo.py I import as

```<code>from custom_package_msgs.msg import MyMsg
</code>```

but VSCode doesn't recognize that Msg, and has no intellisense highlighting or features

Title: VS Code setup with ROS Extension

Body:
First, I am using the MS supplied ROS extension, available at the extension: ms-iot.vscode-ros I mention that because when searching there are lots is lots of noise about ROS and VSCode.

My setup is as follows (very vanilla ros package):

ws/
  custom_package/
   / src
      /custom_package
        /foo.py -> contain class DoAThing
   / scripts
      myscript.py
  custom_package_msgs/
   /msg
     MyMsg.msg

My CMakelists.txt for both projects are correct. I can catkin build and roslaunch fine.

I am trying to figure out the following two issues.

The modules under src are not available for autocomplete/highlighting in the scripts package. Again, these import fine when launching or running a node. I'm simply unable to get any form of intellisense when in the scripts folder. I'm following the convention of

in scripts/myscript.py I import as

from custom_package.foo import DoAThing

There is no intellisense for custom msgs. So in foo.py I import as

from custom_package_msgs.msg import MyMsg

but VSCode doesn't recognize that Msg, and has no intellisense highlighting or features


问:
Is there a way to call colors from a SCSS palette?
I have colors defined in my SCSS as:

```<code>@mixin the-themes($theme) {
  $primary: app($theme, primary);
  $accent: app($theme, accent);
  $warn: app($theme, warn);
  $background: app($theme, background);
  $foreground: app($theme, foreground);
</code>```

I have a circle that is drawn in my ts file:

```<code>private circleOptions = {
    color: '#0075B4',
    weight: 3,
    fillColor: '#0075B4',
    fillOpacity: 0.1
  };
</code>```

Is there a way to call the defined colors in the palette into the color option for the circle? Like this:
color: mat.get-color-from-palette($background...
Like you would in the SCSS file?

Body:
I have colors defined in my SCSS as:

@mixin the-themes($theme) {
  $primary: app($theme, primary);
  $accent: app($theme, accent);
  $warn: app($theme, warn);
  $background: app($theme, background);
  $foreground: app($theme, foreground);

I have a circle that is drawn in my ts file:

private circleOptions = {
    color: '#0075B4',
    weight: 3,
    fillColor: '#0075B4',
    fillOpacity: 0.1
  };

Is there a way to call the defined colors in the palette into the color option for the circle? Like this:
color: mat.get-color-from-palette($background...
Like you would in the SCSS file?


问:
Prevent refetching data when resetting redux state on a reroute with next-router
I currently have this piece of code:

```<code>const handleClick = async () => {
    dispatch(resetFilters());
    if (router.pathname !== '/') {
        await router.push('/');
    }
};
</code>```

Where resetFilters() is a function to reset all the state in a slice.
My problem is that wherever I place this function (before or after the reroute), it will cause data to be fetched twice (since what data is fetched depends on the state).

If I place it before, I fetch data based on the reset state on the page I'm rerouting away from (which I won't use)

If I place it after, I fetch data based on the old state on the page I'm rerouting to, which then has to be fetched again with the reset state.

I saw that react-router-redux has a LOCATION_CHANGE action which seems to solve my problem.
Is there an equivalent version for next-router?

I.e. I need something which allows me to update redux state and redirect with next-router in an atomic step.

Body:
I currently have this piece of code:

const handleClick = async () => {
    dispatch(resetFilters());
    if (router.pathname !== '/') {
        await router.push('/');
    }
};

Where resetFilters() is a function to reset all the state in a slice.
My problem is that wherever I place this function (before or after the reroute), it will cause data to be fetched twice (since what data is fetched depends on the state).

If I place it before, I fetch data based on the reset state on the page I'm rerouting away from (which I won't use)

If I place it after, I fetch data based on the old state on the page I'm rerouting to, which then has to be fetched again with the reset state.

I saw that react-router-redux has a LOCATION_CHANGE action which seems to solve my problem.
Is there an equivalent version for next-router?

I.e. I need something which allows me to update redux state and redirect with next-router in an atomic step.


问:
Azure Policies - ARM to Bicep conversion issues
```<code>We are working on creating a custom azure policy with DiNE effect to deploy certain resources based on the tags existence.
Looking at the Built-in policies for tagging, it seems there is a way to determine the tag existence and run deployments using azure policies.

Due to our internal deployments and SDPs, I need to convert the custom policy definition to Bicep and then deploy it.

I have installed Bicep tools/ VS Code and hitting below errors during conversion.
Can you share inputs on how to handle these? Or there any extended production documentation on how to use Scope and resource functions in Biceps as the current product documentation doesn’t have these details?

Issue: Unable to check the subscription tag existence in Bicep azure policy definition file.

[enter image description here] (https://i.stack.imgur.com/MKcGj.jpg)

Policy definitions for tagging resources - Azure Resource Manager | Microsoft Learn
https://portal.azure.com/#blade/Microsoft_Azure_Policy/PolicyDetailBlade/definitionId/%2Fproviders%2FMicrosoft.Authorization%2FpolicyDefinitions%2Fb27a0cbd-a167-4dfa-ae64-4337be671140

</code>```

Tried to escape the subscription function check but it is not working in bicep file.

Body:
We are working on creating a custom azure policy with DiNE effect to deploy certain resources based on the tags existence.
Looking at the Built-in policies for tagging, it seems there is a way to determine the tag existence and run deployments using azure policies.

Due to our internal deployments and SDPs, I need to convert the custom policy definition to Bicep and then deploy it.

I have installed Bicep tools/ VS Code and hitting below errors during conversion.
Can you share inputs on how to handle these? Or there any extended production documentation on how to use Scope and resource functions in Biceps as the current product documentation doesn’t have these details?

Issue: Unable to check the subscription tag existence in Bicep azure policy definition file.

[enter image description here] (https://i.stack.imgur.com/MKcGj.jpg)

Policy definitions for tagging resources - Azure Resource Manager | Microsoft Learn
https://portal.azure.com/#blade/Microsoft_Azure_Policy/PolicyDetailBlade/definitionId/%2Fproviders%2FMicrosoft.Authorization%2FpolicyDefinitions%2Fb27a0cbd-a167-4dfa-ae64-4337be671140

Tried to escape the subscription function check but it is not working in bicep file.


问:
Excel VBA Macro
Using the code below to search a range in Excel and color code the matching string.   How can this be altered so that the string that is searched is matched regardless of case?   So, "yes" and "Yes" and "YES" would all hit successfully and be color coded accordingly for example?  This macro does a great job to highlight the text desired in red for example, but you have to run it multiple times for each iteration of the text in lower and upper case.   How can this be done to highlight the text regardless of the case?

Any direction on the correct command  or switch to use to ignore case when matching text would be very appreciated.

    Public Sub ChangeTextColor()
        Application.ScreenUpdating = False
        Dim Rng As Range
        Dim cFnd As String
        Dim xTmp As String
        Dim x As Long
        Dim m As Long
        Dim y As Long
        cFnd = InputBox("Enter the text string to highlight")
        y = Len(cFnd)
        For Each Rng In Selection
        With Rng
            m = UBound(Split(Rng.Value, cFnd))
            If m > 0 Then
              xTmp = ""
            For x = 0 To m - 1
                xTmp = xTmp & Split(Rng.Value, cFnd)(x)
                .Characters(Start:=Len(xTmp) + 1, Length:=y).Font.ColorIndex = 3
                xTmp = xTmp & cFnd
            Next
            End If
        End With
        Next Rng
        Application.ScreenUpdating = True
    End Sub
```

Unsure where to add a line regarding case sensitivity.  Is there a command or variable that would tell this routine / macro to ignore case and match both upper and lower case characters?

Title: Excel VBA Macro

Body:
Using the code below to search a range in Excel and color code the matching string.   How can this be altered so that the string that is searched is matched regardless of case?   So, "yes" and "Yes" and "YES" would all hit successfully and be color coded accordingly for example?  This macro does a great job to highlight the text desired in red for example, but you have to run it multiple times for each iteration of the text in lower and upper case.   How can this be done to highlight the text regardless of the case?

Any direction on the correct command  or switch to use to ignore case when matching text would be very appreciated.

    Public Sub ChangeTextColor()
        Application.ScreenUpdating = False
        Dim Rng As Range
        Dim cFnd As String
        Dim xTmp As String
        Dim x As Long
        Dim m As Long
        Dim y As Long
        cFnd = InputBox("Enter the text string to highlight")
        y = Len(cFnd)
        For Each Rng In Selection
        With Rng
            m = UBound(Split(Rng.Value, cFnd))
            If m > 0 Then
              xTmp = ""
            For x = 0 To m - 1
                xTmp = xTmp & Split(Rng.Value, cFnd)(x)
                .Characters(Start:=Len(xTmp) + 1, Length:=y).Font.ColorIndex = 3
                xTmp = xTmp & cFnd
            Next
            End If
        End With
        Next Rng
        Application.ScreenUpdating = True
    End Sub

Unsure where to add a line regarding case sensitivity.  Is there a command or variable that would tell this routine / macro to ignore case and match both upper and lower case characters?


问:
Cannot open source file in a CMake Project in Visual Studio
I have a C++ Project in Visual Studio 2022 (Windows 11) that is put together using CMake. I understand that the difference here is, that my project is not a Solution but rather just folders with code and the CMake tells it how to compile it?

But my problem is, that it doesn't seem to find C's standard libraries and shows error "cannot open sourcefile".

Screenshot

The error is definitely not in the project, since it runs just fine on my laptop, just not on the PC I want it to run on.

How can I tell it where these libraries are? Where are they located even?
Any help would be greatly appreciated and I can share more files on request.

Things I have tried:

Going to properties and choose the correct Windows SDK Version - The properties are empty

Comparing every variable of the CMake Settings with the ones on my laptop where it works

completely reinstalling Visual Studio (yes I did that)

looking through lots of StackOverflow questions but none of them describe my problem


问:
How to allow DataContext to pass through to a CustomControl.ContentTemplate
How do I pass the DataContext from a ContentControl to its ContentTemplate?

The following prints "A string" on the designer:

```<code><ContentControl DataContext="A string">
    <Label Content="{Binding}" />
</ContentControl>
</code>```

But the following doesn't print anything:

```<code><ContentControl DataContext="A string">
    <ContentControl.ContentTemplate>
        <DataTemplate>
            <Label Content="{Binding}" />
        </DataTemplate>
    </ContentControl.ContentTemplate>
</ContentControl>
</code>```

This is a minimal repro. The original case uses a DataTemplate that appears as a StaticResource, and the ContentTemplate property is set via a Style.Triggers.DataTrigger.Setter element. The goal there is to change the content based on my trigger, but by using ContentTemplate, the DataContext is lost.

Body:
How do I pass the DataContext from a ContentControl to its ContentTemplate?

The following prints "A string" on the designer:

<ContentControl DataContext="A string">

</ContentControl>

But the following doesn't print anything:

<ContentControl DataContext="A string">
    <ContentControl.ContentTemplate>
        <DataTemplate>

        </DataTemplate>
    </ContentControl.ContentTemplate>
</ContentControl>

This is a minimal repro. The original case uses a DataTemplate that appears as a StaticResource, and the ContentTemplate property is set via a Style.Triggers.DataTrigger.Setter element. The goal there is to change the content based on my trigger, but by using ContentTemplate, the DataContext is lost.