问:
Extract more objects from an array stored in a state
```<code>import "./App.css";
import { MapContainer, TileLayer, Marker, Popup } from "react-leaflet";
import { useEffect, useState } from "react";
import * as L from "leaflet";

function App() {
  const markerIcon = new L.Icon({
    iconUrl:
      "https://cdn.rawgit.com/pointhi/leaflet-color-markers/master/img/marker-icon-green.png", //change icon color to grey
    iconSize: [25, 41],
    iconAnchor: [12, 41],
    popupAnchor: [1, -34],
    shadowUrl:
      "https://cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.7/images/marker-shadow.png",
    shadowSize: [41, 41],
  });

  const [countryList, setCountryList] = useState(null);
  const [filteredCountries, setFilteredCountries] = useState(null); // add a new state to store the filtered list
  const [mapRef, setMapRef] = useState(null); //map reference stored in state to call the API from leaflet

  useEffect(() => {
    fetch("https://restcountries.com/v3.1/all")
      .then((res) => res.json())
      .then((data) => {
        setCountryList(data);
        setFilteredCountries(data); // set the initial value of filteredCountries to be equal to countryList
      })
      .catch((err) => console.log("Error:", err));
  }, []);
  function filterItems(countryList, query) {
    return countryList.filter(
      (el) => el.name.common.toLowerCase().includes(query.toLowerCase()) //filters out the names from the fetch API into a new function
    );
  }

  function zoomCountryMap(latlng, filteredCountries) {
    const marker = L.marker(latlng).addTo(mapRef); // Create a new marker at the specified latlng coordinates'

    const popup = L.popup().setContent(`<p>${filteredCountries}</p>`);
    marker.bindPopup(popup).openPopup();

    mapRef.setView(latlng, 6);
  }
  //console.log(filteritems);

  return (
    <div className="App">
      <input
        type="text"
        placeholder="Search by country..."
        style={{
          backgroundColor: "lightgrey",
          padding: "1em",
          paddingLeft: "2.5em",
          fontSize: "16px",
          backgroundImage:
            "url(data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiA/PjwhRE9DVFlQRSBzdmcgIFBVQkxJQyAnLS8vVzNDLy9EVEQgU1ZHIDEuMC8vRU4nICAnaHR0cDovL3d3dy53My5vcmcvVFIvMjAwMS9SRUMtU1ZHLTIwMDEwOTA0L0RURC9zdmcxMC5kdGQnPjxzdmcgZW5hYmxlLWJhY2tncm91bmQ9Im5ldyAwIDAgMjQgMjQiIGlkPSJMYXllcl8xIiB2ZXJzaW9uPSIxLjAiIHZpZXdCb3g9IjAgMCAyNCAyNCIgeG1sOnNwYWNlPSJwcmVzZXJ2ZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayI+PGc+PGc+PHBhdGggZD0iTTksNGMyLjgsMCw1LDIuMiw1LDVzLTIuMiw1LTUsNXMtNS0yLjItNS01UzYuMiw0LDksNCBNOSwyQzUuMSwyLDIsNS4xLDIsOWMwLDMuOSwzLjEsNyw3LDdzNy0zLjEsNy03QzE2LDUuMSwxMi45LDIsOSwyICAgIEw5LDJ6Ii8+PC9nPjwvZz48Zz48cG9seWdvbiBwb2ludHM9IjIyLDIwLjMgMjAuMywyMiAxNCwxNS43IDE0LDE0IDE1LjcsMTQgICIvPjxyZWN0IGhlaWdodD0iMy42IiB0cmFuc2Zvcm09Im1hdHJpeCgwLjcwNzEgLTAuNzA3MSAwLjcwNzEgMC43MDcxIC01Ljk3NDEgMTQuNDIyNykiIHdpZHRoPSIxLjIiIHg9IjEzLjgiIHk9IjEyLjYiLz48L2c+PC9zdmc+)",
          backgroundSize: "2.5em 2.5em",
          backgroundPosition: "12em center",
          backgroundRepeat: "no-repeat",
        }}
        onChange={(e) => {
          setFilteredCountries(filterItems(countryList, e.target.value));
          console.log(filterItems(countryList, e.target.value));
        }}
      />

      <div style={{ height: "100vh", width: "700px", overflow: "scroll" }}>
        <table id="country">
          <thead>
            <tr className="sticky-heading">
              <th className="table-cell" style={{ width: "200px" }}>
                Country
              </th>
              <th className="table-cell" style={{ width: "200px" }}>
                Capital
              </th>
              <th className="table-cell" style={{ width: "200px" }}>
                Region
              </th>
            </tr>
          </thead>
          <tbody>
            {filteredCountries ? ( // check if filteredCountryList is not null
              filteredCountries.map(
                (
                  table // iterate over the filtered list
                ) => (
                  <tr
                    key={table.name.common}
                    onClick={() =>
                      zoomCountryMap(
                        //this function is called with 3 arguments
                        table.latlng,
                        table.name.common,
                        table.region
                      )
                    }
                  >
                    <td>{table.name.common}</td>
                    <td>{table.capital}</td>
                    <td>{table.region}</td>
                  </tr>
                )
              )
            ) : (
              <tr>
                <td colSpan="3">Search for country...</td>
              </tr>
            )}
          </tbody>
        </table>
      </div>

      <MapContainer
        center={[51.505, -0.09]}
        zoom={3}
        scrollWheelZoom={false}
        whenReady={({ target }) => setMapRef(target)}
      >
        <TileLayer
          attribution='© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
          url="https://server.arcgisonline.com/ArcGIS/rest/services/Canvas/World_Light_Gray_Base/MapServer/tile/{z}/{y}/{x}"
        />
        {/* {countryList &&
          countryList.map((markers) => (
            <Marker
              key={markers.name.common}
              position={[markers.latlng[0], markers.latlng[1]]} //iterate over countrylist and mapping out the markers
              icon={markerIcon}
            >
              <Popup>
                <h1> {markers.name.common} </h1>
                <h3>
                  <p> Capital: {markers.capital}</p>
                  <p> Region: {markers.region}</p>
                  <p> Subregion: {markers.subregion}</p>
                  <p>
                    {" "}
                    Currencies:{" "}
                    {Object.keys(markers.currencies ?? {}) // looping trough all currencies, then getting name from    object in value

                      .map((key) => markers.currencies[key]["name"])
                      .join(", ")}{" "}
                  </p>
                </h3>
              </Popup>
            </Marker>
          ))} */}
      </MapContainer>
    </div>
  );
}

export default App;

</code>```

this is my total code, and I'm struggling quite massive with this one function

```<code>  function zoomCountryMap(latlng, filteredCountries) {
    const marker = L.marker(latlng).addTo(mapRef); // Create a new marker at the specified latlng coordinates'

    const popup = L.popup().setContent(`<p>${filteredCountries}</p>`);
    marker.bindPopup(popup).openPopup();

    mapRef.setView(latlng, 6);
  }
</code>```

in this function i want to access more data from filteredcountries (API stored) to the popup, like the capital, flag image etc. But I can't figured it out.

im completely new to javascript so any help is good. Ive tried to access the data with passing arguments, indexing and so on. since I already have the data stored in filteredcountries, it should not be neccessary to iterate over the API again?

what is the best solution here?

I think i need to do something with this function, but i' not 100% sure.

```<code>  function filterItems(countryList, query) {
    return countryList.filter(
      (el) => el.name.common.toLowerCase().includes(query.toLowerCase()) //filters out the names from the fetch API into a new function
    );
</code>```

I think im struggling a bit with datatypes and how to access them properly

im completely new to javascript so any help is good. Ive tried to access the data with passing arguments, indexing and so on. since I already have the data stored in filteredcountries, it should not be neccessary to iterate over the API again?

Body:
import "./App.css";
import { MapContainer, TileLayer, Marker, Popup } from "react-leaflet";
import { useEffect, useState } from "react";
import * as L from "leaflet";

function App() {
  const markerIcon = new L.Icon({
    iconUrl:
      "https://cdn.rawgit.com/pointhi/leaflet-color-markers/master/img/marker-icon-green.png", //change icon color to grey
    iconSize: [25, 41],
    iconAnchor: [12, 41],
    popupAnchor: [1, -34],
    shadowUrl:
      "https://cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.7/images/marker-shadow.png",
    shadowSize: [41, 41],
  });

  const [countryList, setCountryList] = useState(null);
  const [filteredCountries, setFilteredCountries] = useState(null); // add a new state to store the filtered list
  const [mapRef, setMapRef] = useState(null); //map reference stored in state to call the API from leaflet

  useEffect(() => {
    fetch("https://restcountries.com/v3.1/all")
      .then((res) => res.json())
      .then((data) => {
        setCountryList(data);
        setFilteredCountries(data); // set the initial value of filteredCountries to be equal to countryList
      })
      .catch((err) => console.log("Error:", err));
  }, []);
  function filterItems(countryList, query) {
    return countryList.filter(
      (el) => el.name.common.toLowerCase().includes(query.toLowerCase()) //filters out the names from the fetch API into a new function
    );
  }

  function zoomCountryMap(latlng, filteredCountries) {
    const marker = L.marker(latlng).addTo(mapRef); // Create a new marker at the specified latlng coordinates'

    const popup = L.popup().setContent(`<p>${filteredCountries}</p>`);
    marker.bindPopup(popup).openPopup();

    mapRef.setView(latlng, 6);
  }
  //console.log(filteritems);

  return (

      <input
        type="text"
        placeholder="Search by country..."
        style={{
          backgroundColor: "lightgrey",
          padding: "1em",
          paddingLeft: "2.5em",
          fontSize: "16px",
          backgroundImage:
            "url(data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiA/PjwhRE9DVFlQRSBzdmcgIFBVQkxJQyAnLS8vVzNDLy9EVEQgU1ZHIDEuMC8vRU4nICAnaHR0cDovL3d3dy53My5vcmcvVFIvMjAwMS9SRUMtU1ZHLTIwMDEwOTA0L0RURC9zdmcxMC5kdGQnPjxzdmcgZW5hYmxlLWJhY2tncm91bmQ9Im5ldyAwIDAgMjQgMjQiIGlkPSJMYXllcl8xIiB2ZXJzaW9uPSIxLjAiIHZpZXdCb3g9IjAgMCAyNCAyNCIgeG1sOnNwYWNlPSJwcmVzZXJ2ZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayI+PGc+PGc+PHBhdGggZD0iTTksNGMyLjgsMCw1LDIuMiw1LDVzLTIuMiw1LTUsNXMtNS0yLjItNS01UzYuMiw0LDksNCBNOSwyQzUuMSwyLDIsNS4xLDIsOWMwLDMuOSwzLjEsNyw3LDdzNy0zLjEsNy03QzE2LDUuMSwxMi45LDIsOSwyICAgIEw5LDJ6Ii8+PC9nPjwvZz48Zz48cG9seWdvbiBwb2ludHM9IjIyLDIwLjMgMjAuMywyMiAxNCwxNS43IDE0LDE0IDE1LjcsMTQgICIvPjxyZWN0IGhlaWdodD0iMy42IiB0cmFuc2Zvcm09Im1hdHJpeCgwLjcwNzEgLTAuNzA3MSAwLjcwNzEgMC43MDcxIC01Ljk3NDEgMTQuNDIyNykiIHdpZHRoPSIxLjIiIHg9IjEzLjgiIHk9IjEyLjYiLz48L2c+PC9zdmc+)",
          backgroundSize: "2.5em 2.5em",
          backgroundPosition: "12em center",
          backgroundRepeat: "no-repeat",
        }}
        onChange={(e) => {
          setFilteredCountries(filterItems(countryList, e.target.value));
          console.log(filterItems(countryList, e.target.value));
        }}
      />

                Country

                Capital

                Region

            {filteredCountries ? ( // check if filteredCountryList is not null
              filteredCountries.map(
                (
                  table // iterate over the filtered list
                ) => (

                      zoomCountryMap(
                        //this function is called with 3 arguments
                        table.latlng,
                        table.name.common,
                        table.region
                      )
                    }
                  >
                    {table.name.common}
                    {table.capital}
                    {table.region}

                )
              )
            ) : (

                Search for country...

            )}

      <MapContainer
        center={[51.505, -0.09]}
        zoom={3}
        scrollWheelZoom={false}
        whenReady={({ target }) => setMapRef(target)}
      >
        <TileLayer
          attribution='© OpenStreetMap contributors'
          url="https://server.arcgisonline.com/ArcGIS/rest/services/Canvas/World_Light_Gray_Base/MapServer/tile/{z}/{y}/{x}"
        />
        {/* {countryList &&
          countryList.map((markers) => (
            <Marker
              key={markers.name.common}
              position={[markers.latlng[0], markers.latlng[1]]} //iterate over countrylist and mapping out the markers
              icon={markerIcon}
            >
              <Popup>

 {markers.name.common}

 Capital: {markers.capital}

 Region: {markers.region}

 Subregion: {markers.subregion}

                    {" "}
                    Currencies:{" "}
                    {Object.keys(markers.currencies ?? {}) // looping trough all currencies, then getting name from    object in value

                      .map((key) => markers.currencies[key]["name"])
                      .join(", ")}{" "}

              </Popup>
            </Marker>
          ))} */}
      </MapContainer>

  );
}

export default App;

this is my total code, and I'm struggling quite massive with this one function

  function zoomCountryMap(latlng, filteredCountries) {
    const marker = L.marker(latlng).addTo(mapRef); // Create a new marker at the specified latlng coordinates'

    const popup = L.popup().setContent(`<p>${filteredCountries}</p>`);
    marker.bindPopup(popup).openPopup();

    mapRef.setView(latlng, 6);
  }

in this function i want to access more data from filteredcountries (API stored) to the popup, like the capital, flag image etc. But I can't figured it out.

im completely new to javascript so any help is good. Ive tried to access the data with passing arguments, indexing and so on. since I already have the data stored in filteredcountries, it should not be neccessary to iterate over the API again?

what is the best solution here?

I think i need to do something with this function, but i' not 100% sure.

  function filterItems(countryList, query) {
    return countryList.filter(
      (el) => el.name.common.toLowerCase().includes(query.toLowerCase()) //filters out the names from the fetch API into a new function
    );

I think im struggling a bit with datatypes and how to access them properly

im completely new to javascript so any help is good. Ive tried to access the data with passing arguments, indexing and so on. since I already have the data stored in filteredcountries, it should not be neccessary to iterate over the API again?


来源: stackexchange

问:
How to map o365 libraries to Win10 quick access links w/o IE
We have the Powershell script below which allows us to map a Sharepoint library and the user's Onedrive to user's quick access links in Windows 10. This requires IE and since that's no longer supported I'm wondering if there is a similar solution using Edge or Chrome?</p>
```<code>$ie = Start-Process -file iexplore -arg 'https://mycompanyname.sharepoint.com/sites/Archived' -PassThru -WindowStyle Minimized
sleep 8
$ie.Kill()
$ie = Start-Process -file iexplore -arg "https://mycompanyname-my.sharepoint.com/personal/${env:username}_mycompanyname_org\Documents" -Passthru -WindowStyle Minimized
sleep 8
$ie.Kill()
$folder = '\\mycompanyname.sharepoint.com@SSL\DavWWWRoot\sites\Archived'
$folder2 = '\\mycompanyname-my.sharepoint.com@SSL\DavWWWRoot\personal\' + $env:username + '_mycompanyname_org\Documents'
$QuickAccess = New-Object -ComObject shell.application
$QuickAccess.Namespace($folder).Self.InvokeVerb("pintohome")
$QuickAccess.Namespace($folder1).Self.InvokeVerb("pintohome")
</code>```

ContentLicense: CC BY-SA 4.0

Body:
We have the Powershell script below which allows us to map a Sharepoint library and the user's Onedrive to user's quick access links in Windows 10. This requires IE and since that's no longer supported I'm wondering if there is a similar solution using Edge or Chrome?

$ie = Start-Process -file iexplore -arg 'https://mycompanyname.sharepoint.com/sites/Archived' -PassThru -WindowStyle Minimized
sleep 8
$ie.Kill()
$ie = Start-Process -file iexplore -arg "https://mycompanyname-my.sharepoint.com/personal/${env:username}_mycompanyname_org\Documents" -Passthru -WindowStyle Minimized
sleep 8
$ie.Kill()
$folder = '\\mycompanyname.sharepoint.com@SSL\DavWWWRoot\sites\Archived'
$folder2 = '\\mycompanyname-my.sharepoint.com@SSL\DavWWWRoot\personal\' + $env:username + '_mycompanyname_org\Documents'
$QuickAccess = New-Object -ComObject shell.application
$QuickAccess.Namespace($folder).Self.InvokeVerb("pintohome")
$QuickAccess.Namespace($folder1).Self.InvokeVerb("pintohome")


问:
Error in `[.data.frame`(predict.exercise, , i) : undefined columns selected
Hi i am trying to run this code and am getting this error.
code-   for(i in variables) prediction.exercise[, paste0(i,"_lag")] <- shift(prediction.exercise[,i],n=1,type="lag")

error- Error in [.data.frame(prediction.exercise, , i) :
undefined columns selected

```<code>prediction.exercise= refers to the dataset

I tried to create a lag in the data set
</code>```

Body:
Hi i am trying to run this code and am getting this error.
code-   for(i in variables) prediction.exercise[, paste0(i,"_lag")] <- shift(prediction.exercise[,i],n=1,type="lag")

error- Error in [.data.frame(prediction.exercise, , i) :
undefined columns selected

prediction.exercise= refers to the dataset

I tried to create a lag in the data set


问:
Remove space at the bottom of a react-native Text element
I have a Text element and need to position another Text element directly below it.  However, there appears to be space at the bottom of the Text element that keeps me from doing this.  How can I remove the space at the bottom of the Text element with "14.45366" so that the text element with "Current Balance" can then be positioned so it is almost touching "14.45366"?

The purple colored background is to show the amount of space that can be found within the Text element itself.

```<code><Text style={{ fontSize: 56, fontFamily: 'TitilliumWeb_600SemiBold', textAlign: 'center', backgroundColor: 'purple' }}>14.45366</Text>
<Text style={{ fontSize: 16, fontFamily: 'TitilliumWeb_400Regular', textAlign: 'center', color: '#979797' }}>Current Balance</Text>

</code>```

I did try adding lineHeight to the styling but it cuts the text off from the top.

```<code>                    <Text style={{ fontSize: 56, fontFamily: 'TitilliumWeb_600SemiBold', textAlign: 'center', backgroundColor: 'purple', lineHeight: 56 }}>14.45366</Text>

</code>```

Body:
I have a Text element and need to position another Text element directly below it.  However, there appears to be space at the bottom of the Text element that keeps me from doing this.  How can I remove the space at the bottom of the Text element with "14.45366" so that the text element with "Current Balance" can then be positioned so it is almost touching "14.45366"?

The purple colored background is to show the amount of space that can be found within the Text element itself.

<Text style={{ fontSize: 56, fontFamily: 'TitilliumWeb_600SemiBold', textAlign: 'center', backgroundColor: 'purple' }}>14.45366</Text>
<Text style={{ fontSize: 16, fontFamily: 'TitilliumWeb_400Regular', textAlign: 'center', color: '#979797' }}>Current Balance</Text>

I did try adding lineHeight to the styling but it cuts the text off from the top.

                    <Text style={{ fontSize: 56, fontFamily: 'TitilliumWeb_600SemiBold', textAlign: 'center', backgroundColor: 'purple', lineHeight: 56 }}>14.45366</Text>


问:
How to use find_library when cross-compiling a project for Android with CMake?
I'm trying to compile my application for Android using CMake. To do this first I made sure that I installed the Android NDK and then loaded the needed toolchain file:

```<code>cmake_minimum_required(VERSION 3.20)

set(CMAKE_TOOLCHAIN_FILE ${NDK_TOOLCHAIN_FILE_PATH} CACHE STRING "" FORCE)

project(MyApp VERSION 0.1.0 LANGUAGES CXX)

if(ANDROID)
    add_library(MyApp SHARED main.cpp)
else()
    add_executable(MyApp main.cpp)
endif()

</code>```

Now I have a prebuilt .so shared library file that is built for Android ARM architecture. I want to link this against my app. The file is located under the android_arm/lib directory under the master source directory and is called libpdfium.so. So I called the following:

```<code>if(${CMAKE_SYSTEM_NAME} MATCHES "Android")
  find_library(PDFium_LIBRARY
    NAMES "pdfium"
    PATHS "${CMAKE_CURRENT_LIST_DIR}/android_arm"
    PATH_SUFFIXES "lib")

  if(PDFium_LIBRARY)
    message("PDFium_LIBRARY: ${PDFium_LIBRARY}")
  else()
    message("PDFium_LIBRARY NOT FOUND")
  endif()
endif()
</code>```

However, it seems that CMake is unable to find the library as I always get "PDFium_LIBRARY NOT FOUND". When using the find_library function to compile for the host machine, everything works as expected but somehow this doesn't succeed when cross-compiling for Android (I'm using a Windows 11 machine as the host machine).

Body:
I'm trying to compile my application for Android using CMake. To do this first I made sure that I installed the Android NDK and then loaded the needed toolchain file:

cmake_minimum_required(VERSION 3.20)

set(CMAKE_TOOLCHAIN_FILE ${NDK_TOOLCHAIN_FILE_PATH} CACHE STRING "" FORCE)

project(MyApp VERSION 0.1.0 LANGUAGES CXX)

if(ANDROID)
    add_library(MyApp SHARED main.cpp)
else()
    add_executable(MyApp main.cpp)
endif()

Now I have a prebuilt .so shared library file that is built for Android ARM architecture. I want to link this against my app. The file is located under the android_arm/lib directory under the master source directory and is called libpdfium.so. So I called the following:

if(${CMAKE_SYSTEM_NAME} MATCHES "Android")
  find_library(PDFium_LIBRARY
    NAMES "pdfium"
    PATHS "${CMAKE_CURRENT_LIST_DIR}/android_arm"
    PATH_SUFFIXES "lib")

  if(PDFium_LIBRARY)
    message("PDFium_LIBRARY: ${PDFium_LIBRARY}")
  else()
    message("PDFium_LIBRARY NOT FOUND")
  endif()
endif()

However, it seems that CMake is unable to find the library as I always get "PDFium_LIBRARY NOT FOUND". When using the find_library function to compile for the host machine, everything works as expected but somehow this doesn't succeed when cross-compiling for Android (I'm using a Windows 11 machine as the host machine).


问:
podman mounted volume issue
Bottom line: output from container is not appearing in mounted local directory
I have read the documentation for bind mounts and  on another project had success with this.

My docker file:

```<code>FROM ubuntu:18.04

RUN apt-get update && apt-get install -yq build-essential autoconf libnetcdf-dev libxml2-dev libproj-dev valgrind wget unzip git nano

# pulls ADBM from github and unzips in folder ADMBcode
RUN mkdir /ADMBcode
RUN wget https://github.com/admb-project/admb/releases/download/admb-12.2/admb-12.2-linux.zip
RUN mv admb-12.2-linux.zip /ADMBcode
RUN unzip ADMBcode/admb-12.2-linux.zip -d /ADMBcode

# pulls hydra repo from github into folder HYDRA
RUN mkdir /HYDRA
RUN git clone https://github.com/NOAA-EDAB/hydra_sim.git /HYDRA

# compiles and runs model
WORKDIR /HYDRA
RUN /ADMBcode/admb-12.2/admb hydra_sim.tpl
RUN ./hydra_sim

# create dir for output and move output
#RUN mkdir -p /HYDRA/output/diagnostics
#RUN mkdir  /HYDRA/output/indices

# moves output to folder to be mounted
RUN mv *.out /HYDRA/output/diagnostics
RUN mv *.txt /HYDRA/output/indices
</code>```

I build the image

```<code>podman build -t hydra .
</code>```

and run the container using the following :

```<code>podman run --rm  --name hydra --mount "type=bind,src=/path_on_local_machine/test,dst=/HYDRA/output" hydra
</code>```

I have test folder on my local machine but the output is not mounted.

I have entered the container

```<code>podman run -it hydra
</code>```

and checked that the output is there

I have done this before for another model and everything behaved. Not sure why this is not.
Any ideas what i am doing wrong?
Thanks
However

Title: podman mounted volume issue

Body:
Bottom line: output from container is not appearing in mounted local directory
I have read the documentation for bind mounts and  on another project had success with this.

My docker file:

FROM ubuntu:18.04

RUN apt-get update && apt-get install -yq build-essential autoconf libnetcdf-dev libxml2-dev libproj-dev valgrind wget unzip git nano

# pulls ADBM from github and unzips in folder ADMBcode
RUN mkdir /ADMBcode
RUN wget https://github.com/admb-project/admb/releases/download/admb-12.2/admb-12.2-linux.zip
RUN mv admb-12.2-linux.zip /ADMBcode
RUN unzip ADMBcode/admb-12.2-linux.zip -d /ADMBcode

# pulls hydra repo from github into folder HYDRA
RUN mkdir /HYDRA
RUN git clone https://github.com/NOAA-EDAB/hydra_sim.git /HYDRA

# compiles and runs model
WORKDIR /HYDRA
RUN /ADMBcode/admb-12.2/admb hydra_sim.tpl
RUN ./hydra_sim

# create dir for output and move output
#RUN mkdir -p /HYDRA/output/diagnostics
#RUN mkdir  /HYDRA/output/indices

# moves output to folder to be mounted
RUN mv *.out /HYDRA/output/diagnostics
RUN mv *.txt /HYDRA/output/indices

I build the image

podman build -t hydra .

and run the container using the following :

podman run --rm  --name hydra --mount "type=bind,src=/path_on_local_machine/test,dst=/HYDRA/output" hydra

I have test folder on my local machine but the output is not mounted.

I have entered the container

podman run -it hydra

and checked that the output is there

I have done this before for another model and everything behaved. Not sure why this is not.
Any ideas what i am doing wrong?
Thanks
However


问:
Read UIColor value from a function
I have a func to retrieve the RGB of an image. In the playground, the function return value as an array  [r 0.0 g 0.459 b 0.761 a 1.0]

```<code>import Foundation

func findColors(_ image: UIImage) -> [UIColor] {
  let pixelsWide = Int(image.size.width)
  let pixelsHigh = Int(image.size.height)

  guard let pixelData = image.cgImage?.dataProvider?.data else { return [] }
  let data: UnsafePointer<UInt8> = CFDataGetBytePtr(pixelData)

  var imageColors: [UIColor] = []
  for x in 0..<1 {
    for y in 0..<1 {
      let point = CGPoint(x: x, y: y)
      let pixelInfo: Int = ((pixelsWide * Int(point.y)) + Int(point.x)) * 4
      let color = UIColor(red: CGFloat(data[pixelInfo]) / 255.0,
                green: CGFloat(data[pixelInfo + 1]) / 255.0,
                blue: CGFloat(data[pixelInfo + 2]) / 255.0,
                alpha: CGFloat(data[pixelInfo + 3]) / 255.0)
      imageColors.append(color)
    }
  }
  return imageColors
}
</code>```

I tried to display the color based on this RGB array in the ContentView but it gives me an error. Could you please advise?

```<code>import SwiftUI

let image = UIImage(named: "Fish.jpg")!

struct ContentView: View {

  var body: some View {
      Color(findColors(image))
        .frame(width:10, height: 10)
        .position(x: 40, y: 40)
  }
}

struct ContentView_Previews: PreviewProvider {
  static var previews: some View {
    ContentView()
  }
}
</code>```

i tried to called the function in ContentView but it gives error

Title: Read UIColor value from a function

Body:
I have a func to retrieve the RGB of an image. In the playground, the function return value as an array  [r 0.0 g 0.459 b 0.761 a 1.0]

import Foundation

func findColors(_ image: UIImage) -> [UIColor] {
  let pixelsWide = Int(image.size.width)
  let pixelsHigh = Int(image.size.height)

  guard let pixelData = image.cgImage?.dataProvider?.data else { return [] }
  let data: UnsafePointer<UInt8> = CFDataGetBytePtr(pixelData)

  var imageColors: [UIColor] = []
  for x in 0..<1 {
    for y in 0..<1 {
      let point = CGPoint(x: x, y: y)
      let pixelInfo: Int = ((pixelsWide * Int(point.y)) + Int(point.x)) * 4
      let color = UIColor(red: CGFloat(data[pixelInfo]) / 255.0,
                green: CGFloat(data[pixelInfo + 1]) / 255.0,
                blue: CGFloat(data[pixelInfo + 2]) / 255.0,
                alpha: CGFloat(data[pixelInfo + 3]) / 255.0)
      imageColors.append(color)
    }
  }
  return imageColors
}

I tried to display the color based on this RGB array in the ContentView but it gives me an error. Could you please advise?

import SwiftUI

let image = UIImage(named: "Fish.jpg")!

struct ContentView: View {

  var body: some View {
      Color(findColors(image))
        .frame(width:10, height: 10)
        .position(x: 40, y: 40)
  }
}

struct ContentView_Previews: PreviewProvider {
  static var previews: some View {
    ContentView()
  }
}

i tried to called the function in ContentView but it gives error


问:
Azure Redis Cache - add_ServerMaintenanceEvent from StackExchange.Redis ConnectionMultiplexer pool does not have an implementation
I was creating a library in .net core 6 for using with other projects.I am trying to add cache pooling using StackExchange.Redis.MultiplexerPool in that library.

```<code>public class Library1 : ILibrary1
{
      public Library1(IConfiguration configuration, string azureOptionsKey)
    {
        configuration.Bind(azureOptionsKey, azureOptions);

        //redis client
        _redisClient = new LibraryRedisCacheService();
    }
}
</code>```

below is my CacheService

```<code>public class LibraryRedisCacheService
{
    private readonly IConnectionMultiplexerPool _connectionMultiplexerPool;
    private readonly int[] _connectionsErrorCount;

    public LibraryRedisCacheService()
    {
        var configureOptions = ConfigurationOptions.Parse("Cache connection string");
        configureOptions.AllowAdmin = true;
        configureOptions.AsyncTimeout = 10000;

        _connectionMultiplexerPool = ConnectionMultiplexerPoolFactory.Create(
            poolSize: 10,
            configurationOptions: configureOptions,
            connectionSelectionStrategy: ConnectionSelectionStrategy.RoundRobin);

        _connectionsErrorCount = new int[_connectionMultiplexerPool.PoolSize];
    }

    public async Task<TResult> QueryRedisAsync<TResult>(Func<IDatabase, Task<TResult>> op)
    {
        var connection = await _connectionMultiplexerPool.GetAsync();

        try
        {
            return await op(connection.Connection.GetDatabase());
        }
        catch (RedisConnectionException)
        {
            _connectionsErrorCount[connection.ConnectionIndex]++;

            if (_connectionsErrorCount[connection.ConnectionIndex] < 3)
            {
                throw;
            }

            await connection.ReconnectAsync();

            return await op(connection.Connection.GetDatabase());
        }
    }

    public async Task SetCacheAsync<T>(string key, T value, TimeSpan? expiry = null, int retryCount = 0)
    {
        try
        {
            await QueryRedisAsync(async db => await db.StringSetAsync(key, JsonConvert.SerializeObject(value), expiry ?? TimeSpan.FromHours(12)));
        }
        catch (Exception)
        {
            if (retryCount < 3)
            {
                await Task.Delay(3000);
                await SetCacheAsync(key, value, expiry, retryCount + 1);
            }
        }
    }

    public async Task<T?> GetCacheAsync<T>(string key, int retryCount = 0)
    {
        try
        {
            var value = await QueryRedisAsync(async db => await db.StringGetAsync(key));
            return !value.HasValue ? default(T) : JsonConvert.DeserializeObject<T>(value);

        }
        catch (Exception)
        {
            if (retryCount < 3)
            {
                await Task.Delay(3000);
                await GetCacheAsync<T>(key, retryCount + 1);
            }
        }
        return default;
    }

    public async Task<TResult> RetryCachConnectAsync<TResult>(Func<IConnectionMultiplexer, TResult> op)
    {
        var connection = await _connectionMultiplexerPool.GetAsync();

        try
        {
            return op(connection.Connection);
        }

        catch (RedisConnectionException)
        {
            _connectionsErrorCount[connection.ConnectionIndex]++;

            if (_connectionsErrorCount[connection.ConnectionIndex] < 3)
            {
                throw;
            }

            await connection.ReconnectAsync();

            return op(connection.Connection);
        }
    }

    }
}
</code>```

and in my project startup i am adding this library like this

```<code>services.AddSingleton<ILibrary1, Library1>(
           _ => new Library1(Configuration, "KeyvaultReference"));
</code>```

after that i am getting run time exception in my application like below

```<code>Unable to load one or more of the requested types.
Method 'add_ServerMaintenanceEvent' in type 'StackExchange.Redis.MultiplexerPool.Multiplexers.InternalDisposableConnectionMultiplexer' from assembly 'StackExchange.Redis.MultiplexerPool, Version=1.0.2.0, Culture=neutral, PublicKeyToken=null' does not have an implementation.
</code>```

How to add this method implementation, Or I am doing something wrong in the library implementation

Body:
I was creating a library in .net core 6 for using with other projects.I am trying to add cache pooling using StackExchange.Redis.MultiplexerPool in that library.

public class Library1 : ILibrary1
{
      public Library1(IConfiguration configuration, string azureOptionsKey)
    {
        configuration.Bind(azureOptionsKey, azureOptions);

        //redis client
        _redisClient = new LibraryRedisCacheService();
    }
}

below is my CacheService

public class LibraryRedisCacheService
{
    private readonly IConnectionMultiplexerPool _connectionMultiplexerPool;
    private readonly int[] _connectionsErrorCount;

    public LibraryRedisCacheService()
    {
        var configureOptions = ConfigurationOptions.Parse("Cache connection string");
        configureOptions.AllowAdmin = true;
        configureOptions.AsyncTimeout = 10000;

        _connectionMultiplexerPool = ConnectionMultiplexerPoolFactory.Create(
            poolSize: 10,
            configurationOptions: configureOptions,
            connectionSelectionStrategy: ConnectionSelectionStrategy.RoundRobin);

        _connectionsErrorCount = new int[_connectionMultiplexerPool.PoolSize];
    }

    public async Task<TResult> QueryRedisAsync<TResult>(Func<IDatabase, Task<TResult>> op)
    {
        var connection = await _connectionMultiplexerPool.GetAsync();

        try
        {
            return await op(connection.Connection.GetDatabase());
        }
        catch (RedisConnectionException)
        {
            _connectionsErrorCount[connection.ConnectionIndex]++;

            if (_connectionsErrorCount[connection.ConnectionIndex] < 3)
            {
                throw;
            }

            await connection.ReconnectAsync();

            return await op(connection.Connection.GetDatabase());
        }
    }

    public async Task SetCacheAsync<T>(string key, T value, TimeSpan? expiry = null, int retryCount = 0)
    {
        try
        {
            await QueryRedisAsync(async db => await db.StringSetAsync(key, JsonConvert.SerializeObject(value), expiry ?? TimeSpan.FromHours(12)));
        }
        catch (Exception)
        {
            if (retryCount < 3)
            {
                await Task.Delay(3000);
                await SetCacheAsync(key, value, expiry, retryCount + 1);
            }
        }
    }

    public async Task<T?> GetCacheAsync<T>(string key, int retryCount = 0)
    {
        try
        {
            var value = await QueryRedisAsync(async db => await db.StringGetAsync(key));
            return !value.HasValue ? default(T) : JsonConvert.DeserializeObject<T>(value);

        }
        catch (Exception)
        {
            if (retryCount < 3)
            {
                await Task.Delay(3000);
                await GetCacheAsync<T>(key, retryCount + 1);
            }
        }
        return default;
    }

    public async Task<TResult> RetryCachConnectAsync<TResult>(Func<IConnectionMultiplexer, TResult> op)
    {
        var connection = await _connectionMultiplexerPool.GetAsync();

        try
        {
            return op(connection.Connection);
        }

        catch (RedisConnectionException)
        {
            _connectionsErrorCount[connection.ConnectionIndex]++;

            if (_connectionsErrorCount[connection.ConnectionIndex] < 3)
            {
                throw;
            }

            await connection.ReconnectAsync();

            return op(connection.Connection);
        }
    }

    }
}

and in my project startup i am adding this library like this

services.AddSingleton<ILibrary1, Library1>(
           _ => new Library1(Configuration, "KeyvaultReference"));

after that i am getting run time exception in my application like below

Unable to load one or more of the requested types.
Method 'add_ServerMaintenanceEvent' in type 'StackExchange.Redis.MultiplexerPool.Multiplexers.InternalDisposableConnectionMultiplexer' from assembly 'StackExchange.Redis.MultiplexerPool, Version=1.0.2.0, Culture=neutral, PublicKeyToken=null' does not have an implementation.

How to add this method implementation, Or I am doing something wrong in the library implementation


问:
How to show a label prometheus Gauge as Grafana times series or state timeline with instant value (no range)?

The Problem

Context

I'm trying to display the differents values of my Prometheus Gauge over times (depending on label). I opted for State Timeline

Entry Data

Actualy the entry data are the following Gauge:

{"metric":{"__name__":"xxxx","instance":"xxxxx","name":"eck-operator","domain":"xxxxxx","infra":"xxx","productname":"xxxx","state":"Success","version":"x.x.x"},"values":[1,1,1,1,...],"timestamps":[....]}

{"metric":{"__name__":"xxxxx","instance":"xxxxxxx","name":"eck-operator","domain":"xxxxxxx","infra":"xx","productname":"xxxxxx","state":"OpenShift-fr01: Request timeout","version":"x.x.x"},"values":[0,0],"timestamps":[<VALUE>,<VALUE2>]}

{"metric":{"__name__":"xxxxx","instance":"xxxxxxx","name":"eck-operator","domain":"xxxxxxx","infra":"xx","productname":"xxxxxx","state":"Helm Client: Helm repo add failled","version":"x.x.x"},"values":[0],"timestamps":[<VALUE>]}
```

As you can see over the last 90 days there are only two timestamps set to 0 for the state OpenShift-fr01: Request timeout and one for Helm Client: Helm repo add failled. That why there are two KO Row on different state.

Expected behavior

Data is send every minutes so the red row should not fill the space but only a little bar?

Can someone explein me what i did wrong ?

Thanks ~

Body:
The Problem

Context

I'm trying to display the differents values of my Prometheus Gauge over times (depending on label). I opted for State Timeline

Entry Data

Actualy the entry data are the following Gauge:

{"metric":{"__name__":"xxxx","instance":"xxxxx","name":"eck-operator","domain":"xxxxxx","infra":"xxx","productname":"xxxx","state":"Success","version":"x.x.x"},"values":[1,1,1,1,...],"timestamps":[....]}

{"metric":{"__name__":"xxxxx","instance":"xxxxxxx","name":"eck-operator","domain":"xxxxxxx","infra":"xx","productname":"xxxxxx","state":"OpenShift-fr01: Request timeout","version":"x.x.x"},"values":[0,0],"timestamps":[<VALUE>,<VALUE2>]}

{"metric":{"__name__":"xxxxx","instance":"xxxxxxx","name":"eck-operator","domain":"xxxxxxx","infra":"xx","productname":"xxxxxx","state":"Helm Client: Helm repo add failled","version":"x.x.x"},"values":[0],"timestamps":[<VALUE>]}

As you can see over the last 90 days there are only two timestamps set to 0 for the state OpenShift-fr01: Request timeout and one for Helm Client: Helm repo add failled. That why there are two KO Row on different state.

Expected behavior

Data is send every minutes so the red row should not fill the space but only a little bar?

Can someone explein me what i did wrong ?

Thanks ~


问:
automatically message forwarder
id like to make an app to forward some of my sms(messages) which received from specific numbers to another number automatically? please help me

forward automatically to another number

Title: automatically message forwarder


问:
Can I clear contents of a JavaScript Blob or limit the number of items inside the blob?
Please bear with me as I'm relatively new to JavaScript.

We have a website that utilises JW Player and need the user to be able to download the current audio track.
I have written a script which largely achieves that but I'm having one major issue.

Every time I load a different track into the player it seems to accumulate these in the blob.
So if I load a fresh page and load Track 1 in the JW Player, then I hit the Download button it will download Track 1.
But then I load Track 2 into the JW Player, hit the download button and it will download Track 1 and Track 2, and so on and so on.

So my question is how can I ensure only one item is "in the blob" at any given time?

Ideally whenever the jwplayer on play event is triggered it clears the blob and starts a fresh, is this possible?

Here is my code so far, thanks in advance!

```<code>document.addEventListener('DOMContentLoaded', (event) => {

    jwplayer().on('play', function() {
        //Get URL of track from Video HTML tag
        var vid = document.querySelector(".jw-video");
        var trackURL = vid.getAttribute("src");
        var btn = document.getElementById('download-track');

        //Check if audio file
        if (trackURL.includes('.m4a')) {
            btn.style.display = 'block';
            var filename = document.querySelector('.video-description');
            var file2 = filename.innerText;

            console.log(`Filename --- ${file2}`);
            document.getElementById('download-track').addEventListener("click", () => {

                fetch(trackURL)
                    .then(response => response.blob())
                    .then(blob => {
                        download(blob, file2, 'audio/mp4');
                    })
            });

        } else {
            btn.style.display = 'none';
        }

    });

});
</code>```

Body:
Please bear with me as I'm relatively new to JavaScript.

We have a website that utilises JW Player and need the user to be able to download the current audio track.
I have written a script which largely achieves that but I'm having one major issue.

Every time I load a different track into the player it seems to accumulate these in the blob.
So if I load a fresh page and load Track 1 in the JW Player, then I hit the Download button it will download Track 1.
But then I load Track 2 into the JW Player, hit the download button and it will download Track 1 and Track 2, and so on and so on.

So my question is how can I ensure only one item is "in the blob" at any given time?

Ideally whenever the jwplayer on play event is triggered it clears the blob and starts a fresh, is this possible?

Here is my code so far, thanks in advance!

document.addEventListener('DOMContentLoaded', (event) => {

    jwplayer().on('play', function() {
        //Get URL of track from Video HTML tag
        var vid = document.querySelector(".jw-video");
        var trackURL = vid.getAttribute("src");
        var btn = document.getElementById('download-track');

        //Check if audio file
        if (trackURL.includes('.m4a')) {
            btn.style.display = 'block';
            var filename = document.querySelector('.video-description');
            var file2 = filename.innerText;

            console.log(`Filename --- ${file2}`);
            document.getElementById('download-track').addEventListener("click", () => {

                fetch(trackURL)
                    .then(response => response.blob())
                    .then(blob => {
                        download(blob, file2, 'audio/mp4');
                    })
            });

        } else {
            btn.style.display = 'none';
        }

    });

});


问:
Chart.js: Sort the stacked bars by value
I have the following stacked bar chart with the sample data. I want that per year (label) the individual stacked bars are sorted by the value. E.g. for 2019 the bar should be (form top to bottom) red (50), blue (20) and black (10).

https://jsfiddle.net/7rna08dm/2/

How can I achieve this? Is there the possibility to do this with the datasets property? Or is there any bar sorting property?

Currenctly I'm using the following data structure and didn't find a solution to achieve the expected behaviour with sorting the data:

data: {
  labels: ['2017', '2018', '2019', '2020', '2021', '2022'],
  datasets: [
    {
      label: 'Max',
      data: [0, 0, 50, 10, 0, 70],
      backgroundColor: 'red',
    },
    {
      label: 'Peter',
      data: [10, 0, 20, 30, 0, 0],
      backgroundColor: 'blue',
    },
    {
      label: 'Dave',
      data: [0, 0, 10, 20, 0, 30],
      backgroundColor: 'black',
    },
  ],
},
```


问:
How to track website users using call button on website when the calls go to Twilio?
I have a website which has a call button which allows users to call my contact center which receives calls via Twilio numbers.

Here's the issue. I cannot figure out how to track a lead from the website to a call. If I could somehow have the same unique ID for a user on Google Analytics and have that same unique ID for the caller who called using the call button, that would be exactly what I am looking for. Looking for programming solutions or 3rd party app solutions.

I need to see how successful leads behave on my website so that I can reinforce my business's strengths.

Thanks,
Saquib

A bit lost. Don't know where to start.


问:
Most reliable way to get the repo name?
I'm not seeing anything in the docs for how to just get the repo name: https://www.pygit2.org/repository.html

Is reading the origin remote and parsing it out the only way pygit supports this or is there a more reliable or specific property for this?

```<code>myrepo = Repository(".")
for remote in myrepo.remotes:
    if remote.name == "origin":
        print(remote.url)
        # now parse git@bitbucket.org:mybb-workspace/myrepo.git ??
</code>```

Title: Most reliable way to get the repo name?

Body:
I'm not seeing anything in the docs for how to just get the repo name: https://www.pygit2.org/repository.html

Is reading the origin remote and parsing it out the only way pygit supports this or is there a more reliable or specific property for this?

myrepo = Repository(".")
for remote in myrepo.remotes:
    if remote.name == "origin":
        print(remote.url)
        # now parse git@bitbucket.org:mybb-workspace/myrepo.git ??


问:
How to mark Airflow DAG failed if a function return false value inside?

GOAL

I am building  a DAG that if it returns a false value at the end I want to make that DAG run a failure if it returns true than it can finish as a succesful run.


问:
Azure Iot SDK with MQTT: Many build errors when implementing in Angular application
I've npm installed (into my Angular 13 project) azure-iot-device-mqtt v1.16.1 from here: https://www.npmjs.com/package/azure-iot-device-mqtt

I've also cloned the Azure IoT device SDK project for node, and got it running successfully on my local box. It connects to my Azure portal and sends/receives messages to/from my test device on Azure.
https://github.com/Azure/azure-iot-sdk-node/tree/main/device/samples

If I run any of the TypeScript-compiled-to-JavaScript files with node, it runs fine as a standalone program. However, integrating into my angular project throws tons of errors.

In my ng project's package.json, I've npm installed the following:

```<code>"azure-iot-common": "^1.13.1",
"azure-iot-device": "^1.18.1",
"azure-iot-device-mqtt": "^1.16.1",
"azure-iot-provisioning-device": "^1.9.1",
"azure-iot-provisioning-device-mqtt": "^1.8.1",
"azure-iot-security-symmetric-key": "^1.8.1",
</code>```

As I said, this works if I run node iot-device-test.js (see the javascript dir within samples: https://github.com/Azure/azure-iot-sdk-node/tree/main/device/samples)

// Choose a protocol by uncommenting one of these transports.
import { Mqtt as Protocol } from 'azure-iot-device-mqtt';
import { Client, Message } from 'azure-iot-device';

const deviceConnectionString: string = "{MY_STRING_HERE}";
let sendInterval: NodeJS.Timeout;

const client: Client = Client.fromConnectionString(deviceConnectionString, Protocol);

async function asyncMain(): Promise<void> {
  client.on('connect', connectHandler);
  client.on('error', errorHandler);
  client.on('disconnect', disconnectHandler);
  client.on('message', messageHandler);

  client.open().catch((err) => {
    console.error('Could not connect: ' + err.message);
  });
}

function disconnectHandler(): void {
  clearInterval(sendInterval);
  sendInterval = (null as unknown as NodeJS.Timer);

  client.open().catch((err) => {
    console.error(err.message);
  });
}

function connectHandler(): void {
  console.log('Client connected');
  // Create a message and send it to the IoT Hub every two seconds
  if (!sendInterval) {
    sendInterval = setInterval(() => {
      const message = generateMessage();
      console.log('Sending message: ' + message.getData());
      client.sendEvent(message, printResultFor('send'));
    }, 10000);
  }
}

function messageHandler(msg: any): void {
  console.log('Id: ' + msg.messageId + ' Body: ' + msg.data);
  client.complete(msg, printResultFor('completed'));
}

function errorHandler(err: any): void {
  console.error(err.message);
}

function printResultFor(op: any): (err: any, res: any) => void {
  return function printResult(err: any, res: any): void {
    if (err) console.log(op + ' error: ' + err.toString());
    if (res) console.log(op + ' status: ' + res.constructor.name);
  };
}

function generateMessage(): Message {
  const windSpeed: number = 10 + Math.random() * 4; // range: [10, 14]
  const temperature: number = 20 + Math.random() * 10; // range: [20, 30]
  const humidity: number = 60 + Math.random() * 20; // range: [60, 80]
  const data: string = JSON.stringify({
    deviceId: 'myFirstDevice',
    windSpeed: windSpeed,
    temperature: temperature,
    humidity: humidity,
  });
  const message: Message = new Message(data);

  message.properties.add(
    'temperatureAlert',
    temperature > 28 ? 'true' : 'false'
  );

  return message;
}

asyncMain().catch((err: any): void => {
  console.log('error code: ', err.code);
  console.log('error message: ', err.message);
  console.log('error stack: ', err.stack);
});```
</div>
</div>
</p>
<p>However my Angular service will NOT run. There are many build errors:</p>
<p>SERVICE:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import { Injectable } from '@angular/core';
import { Mqtt as Protocol }  from 'azure-iot-device-mqtt';
import { Client, Message } from 'azure-iot-device';

@Injectable({
    providedIn: 'root',
})
export class NotificationIotService {
    // see https://www.npmjs.com/package/azure-iot-device-mqtt
    deviceConnectionString = 'MY-CONN-STR';
    client: Client;

    constructor() {
        // open a connection to the device
        if (this.deviceConnectionString === '') {
            console.log('device connection string has not been set');
            process.exit(-1);
        }

        this.client = Client.fromConnectionString(this.deviceConnectionString, Protocol);
        this.client.open(this.onConnect);
    }

    async asyncMain(): Promise<void> {
      this.client.on('connect', this.connectHandler);

      this.client.open().catch((err) => {
        console.error('Could not connect: ' + err.message);
      });
    }

    onConnect(err?: Error, _result1?: any): void {
        if (err) {
            console.error('Could not connect: ' + err.message);
        } else {
            console.log('Connected to device. Registering handlers for methods.');

            // register handlers for all the method names we are interested in
            this.client.onDeviceMethod('getDeviceLog', this.onGetDeviceLog);
            this.client.onDeviceMethod('lockDoor', this.onLockDoor);
        }
    }

    connectHandler(): void {
      console.log('Client connected');
    }

    // TODO:
    onGetDeviceLog(request: any, response: any): void {

    }

    onLockDoor(request: any, response: any): void {

    }
}</code>```

ERRORS:

× Failed to compile.
√ Browser application bundle generation complete.

Initial Chunk Files | Names   |     Size
main.js             | main    | 21.14 MB
runtime.js          | runtime | 14.31 kB

17 unchanged chunks

Build at: 2022-12-22T15:16:42.794Z - Hash: 760540b389a8403f - Time: 9805ms

./node_modules/azure-iot-common/dist/authorization.js:7:15-32 - Error: Module not found: Error: Can't resolve 'crypto' in 'C:\dev\git-projects\harmony\WebApp\Harmony\node_modules\azure-iot-common\dist'

BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.

If you want to include a polyfill, you need to:
        - add a fallback 'resolve.fallback: { "crypto": require.resolve("crypto-browserify") }'
        - install 'crypto-browserify'
If you don't want to include a polyfill, you can use an empty module like this:
        resolve.fallback: { "crypto": false }

./node_modules/azure-iot-common/dist/utils.js:6:11-24 - Error: Module not found: Error: Can't resolve 'os' in 'C:\dev\git-projects\harmony\WebApp\Harmony\node_modules\azure-iot-common\dist'

BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.

If you want to include a polyfill, you need to:
        - add a fallback 'resolve.fallback: { "os": require.resolve("os-browserify/browser") }'
        - install 'os-browserify'
If you don't want to include a polyfill, you can use an empty module like this:
        resolve.fallback: { "os": false }

./node_modules/azure-iot-device-mqtt/dist/mqtt.js:12:13-28 - Error: Module not found: Error: Can't resolve 'util' in 'C:\dev\git-projects\harmony\WebApp\Harmony\node_modules\azure-iot-device-mqtt\dist'

BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.

If you want to include a polyfill, you need to:
        - add a fallback 'resolve.fallback: { "util": require.resolve("util/") }'
        - install 'util'
If you don't want to include a polyfill, you can use an empty module like this:
        resolve.fallback: { "util": false }

./node_modules/azure-iot-device/dist/internal_client.js:7:11-24 - Error: Module not found: Error: Can't resolve 'fs' in 'C:\dev\git-projects\harmony\WebApp\Harmony\node_modules\azure-iot-device\dist'

./node_modules/azure-iot-device/dist/iotedge_authentication_provider.js:8:15-30 - Error: Module not found: Error: Can't resolve 'http' in 'C:\dev\git-projects\harmony\WebApp\Harmony\node_modules\azure-iot-device\dist'

BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.```

Body:
I've npm installed (into my Angular 13 project) azure-iot-device-mqtt v1.16.1 from here: https://www.npmjs.com/package/azure-iot-device-mqtt

I've also cloned the Azure IoT device SDK project for node, and got it running successfully on my local box. It connects to my Azure portal and sends/receives messages to/from my test device on Azure.
https://github.com/Azure/azure-iot-sdk-node/tree/main/device/samples

If I run any of the TypeScript-compiled-to-JavaScript files with node, it runs fine as a standalone program. However, integrating into my angular project throws tons of errors.

In my ng project's package.json, I've npm installed the following:

"azure-iot-common": "^1.13.1",
"azure-iot-device": "^1.18.1",
"azure-iot-device-mqtt": "^1.16.1",
"azure-iot-provisioning-device": "^1.9.1",
"azure-iot-provisioning-device-mqtt": "^1.8.1",
"azure-iot-security-symmetric-key": "^1.8.1",

As I said, this works if I run node iot-device-test.js (see the javascript dir within samples: https://github.com/Azure/azure-iot-sdk-node/tree/main/device/samples)

// Choose a protocol by uncommenting one of these transports.
import { Mqtt as Protocol } from 'azure-iot-device-mqtt';
import { Client, Message } from 'azure-iot-device';

const deviceConnectionString: string = "{MY_STRING_HERE}";
let sendInterval: NodeJS.Timeout;

const client: Client = Client.fromConnectionString(deviceConnectionString, Protocol);

async function asyncMain(): Promise<void> {
  client.on('connect', connectHandler);
  client.on('error', errorHandler);
  client.on('disconnect', disconnectHandler);
  client.on('message', messageHandler);

  client.open().catch((err) => {
    console.error('Could not connect: ' + err.message);
  });
}

function disconnectHandler(): void {
  clearInterval(sendInterval);
  sendInterval = (null as unknown as NodeJS.Timer);

  client.open().catch((err) => {
    console.error(err.message);
  });
}

function connectHandler(): void {
  console.log('Client connected');
  // Create a message and send it to the IoT Hub every two seconds
  if (!sendInterval) {
    sendInterval = setInterval(() => {
      const message = generateMessage();
      console.log('Sending message: ' + message.getData());
      client.sendEvent(message, printResultFor('send'));
    }, 10000);
  }
}

function messageHandler(msg: any): void {
  console.log('Id: ' + msg.messageId + ' Body: ' + msg.data);
  client.complete(msg, printResultFor('completed'));
}

function errorHandler(err: any): void {
  console.error(err.message);
}

function printResultFor(op: any): (err: any, res: any) => void {
  return function printResult(err: any, res: any): void {
    if (err) console.log(op + ' error: ' + err.toString());
    if (res) console.log(op + ' status: ' + res.constructor.name);
  };
}

function generateMessage(): Message {
  const windSpeed: number = 10 + Math.random() * 4; // range: [10, 14]
  const temperature: number = 20 + Math.random() * 10; // range: [20, 30]
  const humidity: number = 60 + Math.random() * 20; // range: [60, 80]
  const data: string = JSON.stringify({
    deviceId: 'myFirstDevice',
    windSpeed: windSpeed,
    temperature: temperature,
    humidity: humidity,
  });
  const message: Message = new Message(data);

  message.properties.add(
    'temperatureAlert',
    temperature > 28 ? 'true' : 'false'
  );

  return message;
}

asyncMain().catch((err: any): void => {
  console.log('error code: ', err.code);
  console.log('error message: ', err.message);
  console.log('error stack: ', err.stack);
});

However my Angular service will NOT run. There are many build errors:

SERVICE:

import { Injectable } from '@angular/core';
import { Mqtt as Protocol }  from 'azure-iot-device-mqtt';
import { Client, Message } from 'azure-iot-device';

@Injectable({
    providedIn: 'root',
})
export class NotificationIotService {
    // see https://www.npmjs.com/package/azure-iot-device-mqtt
    deviceConnectionString = 'MY-CONN-STR';
    client: Client;

    constructor() {
        // open a connection to the device
        if (this.deviceConnectionString === '') {
            console.log('device connection string has not been set');
            process.exit(-1);
        }

        this.client = Client.fromConnectionString(this.deviceConnectionString, Protocol);
        this.client.open(this.onConnect);
    }

    async asyncMain(): Promise<void> {
      this.client.on('connect', this.connectHandler);

      this.client.open().catch((err) => {
        console.error('Could not connect: ' + err.message);
      });
    }

    onConnect(err?: Error, _result1?: any): void {
        if (err) {
            console.error('Could not connect: ' + err.message);
        } else {
            console.log('Connected to device. Registering handlers for methods.');

            // register handlers for all the method names we are interested in
            this.client.onDeviceMethod('getDeviceLog', this.onGetDeviceLog);
            this.client.onDeviceMethod('lockDoor', this.onLockDoor);
        }
    }

    connectHandler(): void {
      console.log('Client connected');
    }

    // TODO:
    onGetDeviceLog(request: any, response: any): void {

    }

    onLockDoor(request: any, response: any): void {

    }
}

ERRORS:

× Failed to compile.
√ Browser application bundle generation complete.

Initial Chunk Files | Names   |     Size
main.js             | main    | 21.14 MB
runtime.js          | runtime | 14.31 kB

17 unchanged chunks

Build at: 2022-12-22T15:16:42.794Z - Hash: 760540b389a8403f - Time: 9805ms

./node_modules/azure-iot-common/dist/authorization.js:7:15-32 - Error: Module not found: Error: Can't resolve 'crypto' in 'C:\dev\git-projects\harmony\WebApp\Harmony\node_modules\azure-iot-common\dist'

BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.

If you want to include a polyfill, you need to:
        - add a fallback 'resolve.fallback: { "crypto": require.resolve("crypto-browserify") }'
        - install 'crypto-browserify'
If you don't want to include a polyfill, you can use an empty module like this:
        resolve.fallback: { "crypto": false }

./node_modules/azure-iot-common/dist/utils.js:6:11-24 - Error: Module not found: Error: Can't resolve 'os' in 'C:\dev\git-projects\harmony\WebApp\Harmony\node_modules\azure-iot-common\dist'

BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.

If you want to include a polyfill, you need to:
        - add a fallback 'resolve.fallback: { "os": require.resolve("os-browserify/browser") }'
        - install 'os-browserify'
If you don't want to include a polyfill, you can use an empty module like this:
        resolve.fallback: { "os": false }

./node_modules/azure-iot-device-mqtt/dist/mqtt.js:12:13-28 - Error: Module not found: Error: Can't resolve 'util' in 'C:\dev\git-projects\harmony\WebApp\Harmony\node_modules\azure-iot-device-mqtt\dist'

BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.

If you want to include a polyfill, you need to:
        - add a fallback 'resolve.fallback: { "util": require.resolve("util/") }'
        - install 'util'
If you don't want to include a polyfill, you can use an empty module like this:
        resolve.fallback: { "util": false }

./node_modules/azure-iot-device/dist/internal_client.js:7:11-24 - Error: Module not found: Error: Can't resolve 'fs' in 'C:\dev\git-projects\harmony\WebApp\Harmony\node_modules\azure-iot-device\dist'

./node_modules/azure-iot-device/dist/iotedge_authentication_provider.js:8:15-30 - Error: Module not found: Error: Can't resolve 'http' in 'C:\dev\git-projects\harmony\WebApp\Harmony\node_modules\azure-iot-device\dist'

BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.


问:
Handling Nested JSON configurations based on form data in React
I am building a react app with multiple tabs of forms in it. All these fields are required to populated or bind with a JSON configuration file.

Or in other words this application is for building above JSON configuration file (Nested and bit complicated) based on values entered by User on this UI

Since my experience was in Angular before I defined a tsx files with interfaces for my nested JSON

```<code>export interface Mycompany{
  taxonomy: Taxonomy;
  objectStore: ObjectStore;
}

export interface ConfigurationPayload {
  mycompany: Mycompany;
}

export default interface RecipeRoot {
  id: string;
  isActive: number;
  originalRequestBy: string;
  templateName: string;
  primaryObjectName: string;
  processType: string;
  workflowName: string;
  perRun: PerRun;
  auditDetail: AuditDetail;
  configurationPayload: ConfigurationPayload;
}
export interface ObjectStore {
  location: Location;
  serviceExecutionSequence: ServiceExecutionSequence;
  services: Services;
  filemetadata: Filemetadata;
}
// and many
</code>```

I created it as data.module.tsx file

But I have no idea how to approach next. I thought about following this way

https://www.agirl.codes/how-to-build-forms-with-multiple-input-fields-using-react-hooks

```<code>import React, { useState } from "react";

export default function Register() {
  const [user, setUser] = useState({ fullname: "", email: "", password: "" });

  const handleChange = (event) => {
    setUser({ ...user, [event.target.name]: event.target.value });
  };
  const handleSubmit = (event) => {
    event.preventDefault();
  };
  return (
    <form onSubmit={handleSubmit}>
      <label htmlFor="fullname">Full Name</label>
      <input type="text" name="fullname" onChange={handleChange} />
      <label htmlFor="email">Email</label>
      <input type="email" name="email" onChange={handleChange} />
      <label htmlFor="password">Passoword</label>
      <input type="password" name="password" onChange={handleChange} />
      <button>Register</button>
    </form>
  );
}
</code>```

But I am not sure by this approach how can I build mine such a complicated Object.

Also I am confused do I need to create such module.tsx file for this situation.

I am really getting confused because of my little angular background getting clash here.

Please help

Body:
I am building a react app with multiple tabs of forms in it. All these fields are required to populated or bind with a JSON configuration file.

Or in other words this application is for building above JSON configuration file (Nested and bit complicated) based on values entered by User on this UI

Since my experience was in Angular before I defined a tsx files with interfaces for my nested JSON

export interface Mycompany{
  taxonomy: Taxonomy;
  objectStore: ObjectStore;
}

export interface ConfigurationPayload {
  mycompany: Mycompany;
}

export default interface RecipeRoot {
  id: string;
  isActive: number;
  originalRequestBy: string;
  templateName: string;
  primaryObjectName: string;
  processType: string;
  workflowName: string;
  perRun: PerRun;
  auditDetail: AuditDetail;
  configurationPayload: ConfigurationPayload;
}
export interface ObjectStore {
  location: Location;
  serviceExecutionSequence: ServiceExecutionSequence;
  services: Services;
  filemetadata: Filemetadata;
}
// and many

I created it as data.module.tsx file

But I have no idea how to approach next. I thought about following this way

https://www.agirl.codes/how-to-build-forms-with-multiple-input-fields-using-react-hooks

import React, { useState } from "react";

export default function Register() {
  const [user, setUser] = useState({ fullname: "", email: "", password: "" });

  const handleChange = (event) => {
    setUser({ ...user, [event.target.name]: event.target.value });
  };
  const handleSubmit = (event) => {
    event.preventDefault();
  };
  return (
    <form onSubmit={handleSubmit}>
      Full Name
      <input type="text" name="fullname" onChange={handleChange} />
      Email
      <input type="email" name="email" onChange={handleChange} />
      Passoword
      <input type="password" name="password" onChange={handleChange} />
      <button>Register</button>
    </form>
  );
}

But I am not sure by this approach how can I build mine such a complicated Object.

Also I am confused do I need to create such module.tsx file for this situation.

I am really getting confused because of my little angular background getting clash here.

Please help


问:
How would I create dynamic boundary limits based on maximum ranking?
I have a script currently running in Python which uses Pandas and Pyspark. The source data is very large, so I have to break down the run into limits based on a ranking column in the source data. Essentially this column just numbers the rows and then I split the runs, compiling the data at the end. Example code below:

```<code>limits = ['<=1000000', 'between 1000001 and 2000000', 'between 2000001 and 3000000', etc..]

For limit in limits:

    cmd_1 =  '''
    select * from table where dt = ''' + dt + ''' and rank = ''' + limit
</code>```

Now the issue is, the dataset can vary from between 3m-5m rows. As this is a ML model, when the dataset falls outside the limits - it throws errors due to (rightly) not having data to work with.

E.G - select * from table where dt = '20221220' and limit = between '4000000' and '5000001' when the table only has 3m rows causes problems.

I need a more elegant solution to approach this. Perhaps something along the line of selecting max(rank) from the table and generating limits based on this.

Any suggestions would be greatly appreciated.

Body:
I have a script currently running in Python which uses Pandas and Pyspark. The source data is very large, so I have to break down the run into limits based on a ranking column in the source data. Essentially this column just numbers the rows and then I split the runs, compiling the data at the end. Example code below:

limits = ['<=1000000', 'between 1000001 and 2000000', 'between 2000001 and 3000000', etc..]

For limit in limits:

    cmd_1 =  '''
    select * from table where dt = ''' + dt + ''' and rank = ''' + limit

Now the issue is, the dataset can vary from between 3m-5m rows. As this is a ML model, when the dataset falls outside the limits - it throws errors due to (rightly) not having data to work with.

E.G - select * from table where dt = '20221220' and limit = between '4000000' and '5000001' when the table only has 3m rows causes problems.

I need a more elegant solution to approach this. Perhaps something along the line of selecting max(rank) from the table and generating limits based on this.

Any suggestions would be greatly appreciated.


问:
Omnipay Autentication error inside laravel
I'm using Omnipay Paypal Rest api for Laravel and getting this:
"Authentication failed due to invalid authentication credentials or a missing Authorization header."
here is my code :

```<code>public function PayWithPaypal(Request $request)
    {
        // Initialize the Omnipay PayPal_Rest gateway
        $gateway = Omnipay::create('PayPal_Rest');
        $gateway->setClientId(env('PAYPAL_SANDBOX_CLIENT_ID'));
        $gateway->setSecret(env('PAYPAL_SANDBOX_CLIENT_SECRET'));
        $gateway->setTestMode(true);

        // Prepare the payment request
        $request = $gateway->purchase([
            'amount' => 1,
            'returnUrl' => route('payment.success'),
            'cancelUrl' => route('payment.cancel'),
        ]);

        // Send the payment request
        $response = $request->send();

        // Process the payment response
        if ($response->isRedirect()) {
            // Redirect the customer to the payment gateway
            $response->redirect();
        } else {
            // Payment failed, display an error message to the customer
            Log::alert($response->getMessage());
            return redirect()->route('payment.error')->with('error', $response->getMessage());
        }
    }
</code>```

Any way to solve this error ?

Body:
I'm using Omnipay Paypal Rest api for Laravel and getting this:
"Authentication failed due to invalid authentication credentials or a missing Authorization header."
here is my code :

public function PayWithPaypal(Request $request)
    {
        // Initialize the Omnipay PayPal_Rest gateway
        $gateway = Omnipay::create('PayPal_Rest');
        $gateway->setClientId(env('PAYPAL_SANDBOX_CLIENT_ID'));
        $gateway->setSecret(env('PAYPAL_SANDBOX_CLIENT_SECRET'));
        $gateway->setTestMode(true);

        // Prepare the payment request
        $request = $gateway->purchase([
            'amount' => 1,
            'returnUrl' => route('payment.success'),
            'cancelUrl' => route('payment.cancel'),
        ]);

        // Send the payment request
        $response = $request->send();

        // Process the payment response
        if ($response->isRedirect()) {
            // Redirect the customer to the payment gateway
            $response->redirect();
        } else {
            // Payment failed, display an error message to the customer
            Log::alert($response->getMessage());
            return redirect()->route('payment.error')->with('error', $response->getMessage());
        }
    }

Any way to solve this error ?


问:
How to get Autodesk Forge Viewer Levels Tree?
This Documentation page doesn’t exist
how to get levels tree information.

LevelsTree

https://forge.autodesk.com/en/docs/dataviz/v1/reference/UI/LevelsTree

A tree component used to display a list of levels. Parameters Expand all props * Object data * Array. Array of TreeNode representing levels in the model. onMouseOver * OnMouseEvent Called

I would like to hear the answer to my question


问:
Winforms BindingSource .AddNew() works but .CancelNew() does nothing
Per screen capture below:

bindingSource1.AddNew() works as expected. A new item appears and becomes current.

bindingSource1.CancelNew() does nothing. Per debug messages my button handler is clearly being called, and it correctly attempts to cancel list index 3, but the new user is not actually removed.

The same problem occurs regardless of whether bindingSource1 is backed by BindingList<User> or List<User> (shown).


问:
Chart.Js and Callbacks in Blazor, are they possible?
I am using Chart.JS in a Blazor project and seem to have run into a limitation, there seems to be no obvious way to pass a callback, for example a callback for the tick to modify the tick text displayed:

```<code>Scales = new
{
    y = new
    {
        ticks = new
        {
            color = "white",
            callback = How do I pass a calback here??
        },
    }
},
</code>```

Any ideas on how to accomplish this in Blazor?

Body:
I am using Chart.JS in a Blazor project and seem to have run into a limitation, there seems to be no obvious way to pass a callback, for example a callback for the tick to modify the tick text displayed:

Scales = new
{
    y = new
    {
        ticks = new
        {
            color = "white",
            callback = How do I pass a calback here??
        },
    }
},

Any ideas on how to accomplish this in Blazor?


问:
How to use rapidonvif library in VS Code?
How do I use rapidonvif library in VS Code and write simple ONVIF tasks like camera discovery and video streaming in C++?

I didn't find any tutorial.


问:
PySimpleGUI generates error message when started from command line
When starting a simple PySimpleGUI app from command line, the following error message is sent to stderr:

Mac OS Version is 13.1 and patch enabled so applying the patch

Applyting Mac OS 12.3+ Alpha Channel fix.  Your default Alpha Channel is now 0.99

Here is the simple code that exhibits the issue:

```<code>#!/usr/bin/env python3

import PySimpleGUI as sg

sg.Window(title="Hello World", layout=[[]], margins=(100, 50)).read()
</code>```

I have run the following after installing Mac OS 13.1:

```<code>brew upgrade
brew reinstall python
brew reinstall python-tk
pip install pysimplegui
</code>```

None of these actions had any effect.

I've run searches for the error message in quotes, and there are no hits.

I assumed that the error above was caused by something being out of date.  However the error doesn't indicate what generated it, so I am chasing a ghost right now.

Body:
When starting a simple PySimpleGUI app from command line, the following error message is sent to stderr:

Mac OS Version is 13.1 and patch enabled so applying the patch

Applyting Mac OS 12.3+ Alpha Channel fix.  Your default Alpha Channel is now 0.99

Here is the simple code that exhibits the issue:

#!/usr/bin/env python3

import PySimpleGUI as sg

sg.Window(title="Hello World", layout=[[]], margins=(100, 50)).read()

I have run the following after installing Mac OS 13.1:

brew upgrade
brew reinstall python
brew reinstall python-tk
pip install pysimplegui

None of these actions had any effect.

I've run searches for the error message in quotes, and there are no hits.

I assumed that the error above was caused by something being out of date.  However the error doesn't indicate what generated it, so I am chasing a ghost right now.


问:
How do Mapping Templates Work With AWS CDK and AppSync?
I am looking to build queries that get one item from the EmployerAccount table, and am struggling to understanding what props are required, and their meaning, for .createResolver.

Code:

```<code>employerAccountTable.createResolver("QueryEmployerAccount", {
  typeName: "Query",
  fieldName: "addEmployerAccount",
  requestMappingTemplate: appsync.MappingTemplate.dynamoDbGetItem(appsync.PrimaryKey.partition("id").auto(), appsync.Values.projecting("query"),
  responseMappingTemplate: appsync.MappingTemplate.dynamoDbResultItem(),
});
</code>```

Questions:

What do all these key/values mean?

What would I need to put for the responseMappingTemplate? As it is currently underlined red.

Have I built the requestMappingTemplate correctly?

Useful Links:

CDK Docs

@aws-cdk/aws-appsync-alpha library on npm

Body:
I am looking to build queries that get one item from the EmployerAccount table, and am struggling to understanding what props are required, and their meaning, for .createResolver.

Code:

employerAccountTable.createResolver("QueryEmployerAccount", {
  typeName: "Query",
  fieldName: "addEmployerAccount",
  requestMappingTemplate: appsync.MappingTemplate.dynamoDbGetItem(appsync.PrimaryKey.partition("id").auto(), appsync.Values.projecting("query"),
  responseMappingTemplate: appsync.MappingTemplate.dynamoDbResultItem(),
});

Questions:

What do all these key/values mean?

What would I need to put for the responseMappingTemplate? As it is currently underlined red.

Have I built the requestMappingTemplate correctly?

Useful Links:

CDK Docs

@aws-cdk/aws-appsync-alpha library on npm


问:
React native expo-sqlite | Row too big to fit into CursorWindow
I encounter an error when I want to retrieve data from my expo-sqlite database

```<code>Row too big to fit into CursorWindow requiredPos=0, totalRows=1
</code>```

Data are images in base64 format, I am using react native and expo.

Is it possible to increase this memory parameter? Or recover the data another way? but I don't know in advance the size of what I'm going to fetch exactly, and here there is one row but other functions fetch more rows at a time

```<code>export function getLastReponseJustificationPhoto(auditId,idAuditSite,idQuestionSite) {
        return new Promise((resolve, reject) => {
            db.transaction(tx => {
                tx.executeSql(
                    "SELECT * FROM JustificationsReponsesAudit WHERE auditId = ? AND questionId = ? AND idAuditSite = ? AND idQuestionSite = ? ORDER BY id DESC LIMIT 1",
                    [auditId, idQuestionSite, idAuditSite, idQuestionSite],
                    (_, { rows }) => {
                        resolve(rows);
                    },
                    (_, error) => {
                        alert('ERROR')
                        console.log(error)
                    },
                )
            })
        }
    )
}
</code>```

The table in question is very simple, the other elements are some id and this column with the base64.

Table "JustificationsReponsesAudit"

```<code>"JustificationsReponsesAudit("
         "id INTEGER PRIMARY KEY NOT NULL,"
         "auditId INTEGER,"
         "questionId INTEGER,"
         "idAuditSite INTEGER,"
         "idQuestionSite INTEGER,"
         "justificationImage TEXT," // -> base64
         "justificationInitialeId INTEGER,"
         "type TEXT" // -> Very short text
 ")",

</code>```

I see that it is sometimes advisable to divide your data but I don't see how to divide such a long character string, it seems complicated to me, especially since I don't know its exact length each time. I would like to avoid that.

No error on IOS, only on Android

Thank you.

Body:
I encounter an error when I want to retrieve data from my expo-sqlite database

Row too big to fit into CursorWindow requiredPos=0, totalRows=1

Data are images in base64 format, I am using react native and expo.

Is it possible to increase this memory parameter? Or recover the data another way? but I don't know in advance the size of what I'm going to fetch exactly, and here there is one row but other functions fetch more rows at a time

export function getLastReponseJustificationPhoto(auditId,idAuditSite,idQuestionSite) {
        return new Promise((resolve, reject) => {
            db.transaction(tx => {
                tx.executeSql(
                    "SELECT * FROM JustificationsReponsesAudit WHERE auditId = ? AND questionId = ? AND idAuditSite = ? AND idQuestionSite = ? ORDER BY id DESC LIMIT 1",
                    [auditId, idQuestionSite, idAuditSite, idQuestionSite],
                    (_, { rows }) => {
                        resolve(rows);
                    },
                    (_, error) => {
                        alert('ERROR')
                        console.log(error)
                    },
                )
            })
        }
    )
}

The table in question is very simple, the other elements are some id and this column with the base64.

Table "JustificationsReponsesAudit"

"JustificationsReponsesAudit("
         "id INTEGER PRIMARY KEY NOT NULL,"
         "auditId INTEGER,"
         "questionId INTEGER,"
         "idAuditSite INTEGER,"
         "idQuestionSite INTEGER,"
         "justificationImage TEXT," // -> base64
         "justificationInitialeId INTEGER,"
         "type TEXT" // -> Very short text
 ")",

I see that it is sometimes advisable to divide your data but I don't see how to divide such a long character string, it seems complicated to me, especially since I don't know its exact length each time. I would like to avoid that.

No error on IOS, only on Android

Thank you.


问:
momentjs aws-lambda wrong timezone at +12:00
I have this following node js code:

```<code>let pureDate = new Date('2022-12-22T00:00:00.000Z')
console.log(pureDate)
let formatted1 = moment(pureDate).format('YYYY-MM-DDTHH:00:00+hh:mm')
console.log(formatted1)
let formatted2 = moment.utc(pureDate).local().format('YYYY-MM-DDTHH:00:00+hh:mm')
console.log(formatted2)
</code>```

When I run it at my Windows 10 local machine (+07:00), it print to console:

```<code>2022-12-22T00:00:00.000Z
2022-12-22T07:00:00+07:00
2022-12-22T07:00:00+07:00
</code>```

Now I change timezone to +12:00 and rerun the code, it print:

```<code>2022-12-22T00:00:00.000Z
2022-12-22T12:00:00+12:00
2022-12-22T12:00:00+12:00
</code>```

Everything were fine

Now I deploy it to aws lambda using cloudformation:

```<code>Resources:
  timerHandler:
    Type: AWS::Serverless::Function
    Properties:
      Handler: src.timerHandler
      Runtime: nodejs16.x
      Environment:
        Variables:
          NODE_ENV: lc
      Timeout: 100
      Events:
        ScheduledEvent:
          Type: Schedule
          Properties:
            Schedule: "rate(15 minutes)"
</code>```

After sometime, I access the log and see (please scroll to right-end):

```<code>2022-12-22T22:47:04.451+07:00   2022-12-22T15:47:04.451Z e55ee401-87fd-4614-a7c6-971973ccccc6 INFO pureDate: 2022-12-22T00:00:00.000Z

2022-12-22T22:47:04.451+07:00   2022-12-22T15:47:04.451Z e55ee401-87fd-4614-a7c6-971973ccccc6 INFO formatted1: 2022-12-22T00:00:00+12:00

2022-12-22T22:47:04.451+07:00   2022-12-22T15:47:04.451Z e55ee401-87fd-4614-a7c6-971973ccccc6 INFO formatted2: 2022-12-22T00:00:00+12:00
</code>```

The time 00:00:00 is correct, but the zone +12:00 is not.
I would expect the formatted should be 2022-12-22T12:00:00+12:00 or 2022-12-22T00:00:00+00:00

Is that the problem of momentjs, or my code, or lambda? How can I fix it?

moment version: "^2.29.4"

=============================================================================

UPDATE:

This is zone information of the lambda execution:

```<code>2022-12-22T23:46:32.052+07:00   2022-12-22T16:46:32.052Z f1d04019-44e7-463a-af1d-faf2a5043887 INFO zone_name: Africa/Abidjan

2022-12-22T23:46:32.052+07:00   2022-12-22T16:46:32.052Z f1d04019-44e7-463a-af1d-faf2a5043887 INFO timezone: GMT
</code>```

=============================================================================

UPDATE:

Also tried to set TZ variable to UTC but the same issue

Body:
I have this following node js code:

let pureDate = new Date('2022-12-22T00:00:00.000Z')
console.log(pureDate)
let formatted1 = moment(pureDate).format('YYYY-MM-DDTHH:00:00+hh:mm')
console.log(formatted1)
let formatted2 = moment.utc(pureDate).local().format('YYYY-MM-DDTHH:00:00+hh:mm')
console.log(formatted2)

When I run it at my Windows 10 local machine (+07:00), it print to console:

2022-12-22T00:00:00.000Z
2022-12-22T07:00:00+07:00
2022-12-22T07:00:00+07:00

Now I change timezone to +12:00 and rerun the code, it print:

2022-12-22T00:00:00.000Z
2022-12-22T12:00:00+12:00
2022-12-22T12:00:00+12:00

Everything were fine

Now I deploy it to aws lambda using cloudformation:

Resources:
  timerHandler:
    Type: AWS::Serverless::Function
    Properties:
      Handler: src.timerHandler
      Runtime: nodejs16.x
      Environment:
        Variables:
          NODE_ENV: lc
      Timeout: 100
      Events:
        ScheduledEvent:
          Type: Schedule
          Properties:
            Schedule: "rate(15 minutes)"

After sometime, I access the log and see (please scroll to right-end):

2022-12-22T22:47:04.451+07:00   2022-12-22T15:47:04.451Z e55ee401-87fd-4614-a7c6-971973ccccc6 INFO pureDate: 2022-12-22T00:00:00.000Z

2022-12-22T22:47:04.451+07:00   2022-12-22T15:47:04.451Z e55ee401-87fd-4614-a7c6-971973ccccc6 INFO formatted1: 2022-12-22T00:00:00+12:00

2022-12-22T22:47:04.451+07:00   2022-12-22T15:47:04.451Z e55ee401-87fd-4614-a7c6-971973ccccc6 INFO formatted2: 2022-12-22T00:00:00+12:00

The time 00:00:00 is correct, but the zone +12:00 is not.
I would expect the formatted should be 2022-12-22T12:00:00+12:00 or 2022-12-22T00:00:00+00:00

Is that the problem of momentjs, or my code, or lambda? How can I fix it?

moment version: "^2.29.4"

=============================================================================

UPDATE:

This is zone information of the lambda execution:

2022-12-22T23:46:32.052+07:00   2022-12-22T16:46:32.052Z f1d04019-44e7-463a-af1d-faf2a5043887 INFO zone_name: Africa/Abidjan

2022-12-22T23:46:32.052+07:00   2022-12-22T16:46:32.052Z f1d04019-44e7-463a-af1d-faf2a5043887 INFO timezone: GMT

=============================================================================

UPDATE:

Also tried to set TZ variable to UTC but the same issue


问:
need help on understand why my customized repository work
I have customized repository to include query methods and customized method. I get it working as blow.

public interface UserRepository extends ElasticsearchRepository<User, String>{
        query_method_A();
        query_method_B();
        My_customized_method();
 }
```
<pre class="lang-java prettyprint-override"><code>public class UserRepositoryImpl{

   My_customized_method(){
   //my real implementation
   }
 }
</code>```

I don't need to add any annotation. Spring creates two beans.

```<code>userRepository : class com.sun.proxy.$Proxy150

userRepositoryImpl : class com.*.repository.impl.userRepositoryImpl
</code>```

UserRepositoryImpl can't have implements UserRepository , otherwise it complains that it needs to implement those query methods. It works fine.

I was reading a document about Customizing Individual Repositories https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.single-repository-behavior

It seems that the correct way is to use a fragment repository like below. No annotation is needed. Tested and worked.

public interface UserRepository extends ElasticsearchRepository<User, String>, MyTestRepository
    {
        query_method_A();
        query_method_B();
    }

    public interface MyTestRepository {

        My_customized_method();
    }
```
<pre class="lang-java prettyprint-override"><code>public class MyTestRepositoryImpl implements MyTestRepository {
  My_customized_method(){
   //my real implementation
 }
}
</code>```

My question is why does my first custom repository work? It seems more convenient to use though since I only need one Impl class per repository.

Body:
I have customized repository to include query methods and customized method. I get it working as blow.

public interface UserRepository extends ElasticsearchRepository<User, String>{
        query_method_A();
        query_method_B();
        My_customized_method();
 }

public class UserRepositoryImpl{

   My_customized_method(){
   //my real implementation
   }
 }

I don't need to add any annotation. Spring creates two beans.

userRepository : class com.sun.proxy.$Proxy150

userRepositoryImpl : class com.*.repository.impl.userRepositoryImpl

UserRepositoryImpl can't have implements UserRepository , otherwise it complains that it needs to implement those query methods. It works fine.

I was reading a document about Customizing Individual Repositories https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.single-repository-behavior

It seems that the correct way is to use a fragment repository like below. No annotation is needed. Tested and worked.

public interface UserRepository extends ElasticsearchRepository<User, String>, MyTestRepository
    {
        query_method_A();
        query_method_B();
    }

    public interface MyTestRepository {

        My_customized_method();
    }

public class MyTestRepositoryImpl implements MyTestRepository {
  My_customized_method(){
   //my real implementation
 }
}

My question is why does my first custom repository work? It seems more convenient to use though since I only need one Impl class per repository.


问:
Python/Selenium web automation
I am working on my first project while learning Python/Selenium. I want to automate a web form but I keep running in to the problem of ( element not intractable ) on the login screen. I have tried implicit wait and sleep. What can I do to interact with the element?

implicit wait - no change
Sleep - no change

Title: Python/Selenium web automation


问:
How do I require a user to enter a name when using Intent.ACTION_CREATE_DOCUMENT?
When I use Intent.ACTION_CREATE_DOCUMENT, the file picker that appears has no name filled in, but I can still tap the Save button. The result is I get a Uri where the filename is "(invalid)".

What I'd like to do is require the name to be filled in by the user. I was hoping to find a flag or extra that covers this, but no luck.

I can mitigate this somewhat by including a default name via Intent.EXTRA_TITLE. Or detecting "(invalid)" and starting over. But I was hoping for something better.

Thoughts?


问:
ZipArchieve fails with ArgumentException when stream position is reset
I have multiple Stream instances and would like to zip them up using ZipArchive. This is the code I'm using:

```<code>using var memoryStream = new MemoryStream();
using (var zipArchive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true))
{
    foreach (var stream in streams)
    {
        var entry = zipArchive.CreateEntry($"{Guid.NewGuid()}.jpeg");

        using var entryStream = entry.Open();
        stream.CopyTo(entryStream);
    }
}

memoryStream.Seek(0, SeekOrigin.Begin);
// memoryStream.Position = 0; // this throws the same exception
</code>```

This code works fine when streams has a few items, but it fails with 10 items. The error is coming from the last line when I try to rewind back to the initial position.

{System.ArgumentException: Offset and length were out of bounds for
the array or count is greater than the number of elements from index
to the end of the source collection.   at System.IO.MemoryStream.Read
(System.Byte[] buffer, System.Int32 offset, System.Int…}

This is the memory stream state in debugger:

```<code>CanRead: true
CanSeek: true
CanWrite: true
Capacity: 8534016
Length: 6853402
Position: 6853402
</code>```

Note that this code is running on a physical iOS device written in Xamarin iOS.

What's causing this error to be thrown?

Body:
I have multiple Stream instances and would like to zip them up using ZipArchive. This is the code I'm using:

using var memoryStream = new MemoryStream();
using (var zipArchive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true))
{
    foreach (var stream in streams)
    {
        var entry = zipArchive.CreateEntry($"{Guid.NewGuid()}.jpeg");

        using var entryStream = entry.Open();
        stream.CopyTo(entryStream);
    }
}

memoryStream.Seek(0, SeekOrigin.Begin);
// memoryStream.Position = 0; // this throws the same exception

This code works fine when streams has a few items, but it fails with 10 items. The error is coming from the last line when I try to rewind back to the initial position.

{System.ArgumentException: Offset and length were out of bounds for
the array or count is greater than the number of elements from index
to the end of the source collection.   at System.IO.MemoryStream.Read
(System.Byte[] buffer, System.Int32 offset, System.Int…}

This is the memory stream state in debugger:

CanRead: true
CanSeek: true
CanWrite: true
Capacity: 8534016
Length: 6853402
Position: 6853402

Note that this code is running on a physical iOS device written in Xamarin iOS.

What's causing this error to be thrown?


问:
How to force OpenAPI Generator CLI to use pre-downloaded .jar file?
I have installed (via npm) openapi-generator-cli on my WSL running Ubuntu 22.04 image, with correctly configured HTTP_PROXY and HTTPS_PROXY environment variables.

The problem is, running any command (including sudo openapi-generator-cli help) results in OAG-CLI attempting to download the .jar file from maven.org, which end with connection getting refused for unknown reason (SSL cert not listed as trusted? WSL-exclusive bug? corporate proxy having an edge case?).

Instead of dealing with all that, I realised I can just download the latest (as per official website) .jar file:

https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/6.2.1/openapi-generator-cli-6.2.1.jar

via browser and place it manually for OAG-CLI to use.

I have edited the auto-generated openapitools.json just so:

```<code>{
  "$schema": "node_modules/@openapitools/openapi-generator-cli/config.schema.json",
  "spaces": 2,
  "generator-cli": {
    "version": "6.2.1",//same version as .jar
    "storageDir": "."//see below
  }
}
</code>```

Unfortunately, despite placing two copies of the .jar file (one named openapi-generator-cli-6.2.1.jar, one named openapi-generator-cli.jar) in both the "current" folder and /usr/libs/openapi, and trying the following values for storageDir:

.

./

/usr/libs/openapi

/usr/libs/openapi/

~/usr/libs/openapi

~/usr/libs/openapi/

every single run of sudo openapi-generator-cli help resulted in an immediate Downloading 6.2.1 ... message (followed by connection refused error some time later).

What else do I need to do to make OAG-CLI use the .jar within storageDir instead of trying to download a new copy?

(Answer containing just the structure and contents of a folder created by "storageDir": "~/foo" would allow me to reverse-engineer a working setup.)

Body:
I have installed (via npm) openapi-generator-cli on my WSL running Ubuntu 22.04 image, with correctly configured HTTP_PROXY and HTTPS_PROXY environment variables.

The problem is, running any command (including sudo openapi-generator-cli help) results in OAG-CLI attempting to download the .jar file from maven.org, which end with connection getting refused for unknown reason (SSL cert not listed as trusted? WSL-exclusive bug? corporate proxy having an edge case?).

Instead of dealing with all that, I realised I can just download the latest (as per official website) .jar file:

https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/6.2.1/openapi-generator-cli-6.2.1.jar

via browser and place it manually for OAG-CLI to use.

I have edited the auto-generated openapitools.json just so:

{
  "$schema": "node_modules/@openapitools/openapi-generator-cli/config.schema.json",
  "spaces": 2,
  "generator-cli": {
    "version": "6.2.1",//same version as .jar
    "storageDir": "."//see below
  }
}

Unfortunately, despite placing two copies of the .jar file (one named openapi-generator-cli-6.2.1.jar, one named openapi-generator-cli.jar) in both the "current" folder and /usr/libs/openapi, and trying the following values for storageDir:

.

./

/usr/libs/openapi

/usr/libs/openapi/

~/usr/libs/openapi

~/usr/libs/openapi/

every single run of sudo openapi-generator-cli help resulted in an immediate Downloading 6.2.1 ... message (followed by connection refused error some time later).

What else do I need to do to make OAG-CLI use the .jar within storageDir instead of trying to download a new copy?

(Answer containing just the structure and contents of a folder created by "storageDir": "~/foo" would allow me to reverse-engineer a working setup.)


问:
select a specifique field that match a condition in Java/Spring mongo
I've a document of type:

```<code>{...
  "array1": [
    {
      "id": "id1",
      "value": "v1"
    },
    {
      "id": "id2",
      "value": "v2"
    }
  ],
  "array2": [
    {
      "id": "id-1",
      "value": "value1"
    },
    {
      "id": "id-2",
      "value": "value2"
    }
  ]
}
</code>```

to get only the value that matches my conditions from the array1 and array2 in js we can do this,

```<code>db.mydb.find({...},{  _id: 0,  "array1" : {$elemMatch: {"id" :"id1"}},"array2" : {$elemMatch: {"id" :"id-2"}}})
</code>```

but I wonder how to do the same thing in Spring boot
my expected answer :

```<code>{
  "array1": [
    {
      "id": "id1",
      "value": "v1"
    }
  ],
  "array2": [
    {
      "id": "id-2",
      "value": "value2"
    }
  ]
}
</code>```

Body:
I've a document of type:

{...
  "array1": [
    {
      "id": "id1",
      "value": "v1"
    },
    {
      "id": "id2",
      "value": "v2"
    }
  ],
  "array2": [
    {
      "id": "id-1",
      "value": "value1"
    },
    {
      "id": "id-2",
      "value": "value2"
    }
  ]
}

to get only the value that matches my conditions from the array1 and array2 in js we can do this,

db.mydb.find({...},{  _id: 0,  "array1" : {$elemMatch: {"id" :"id1"}},"array2" : {$elemMatch: {"id" :"id-2"}}})

but I wonder how to do the same thing in Spring boot
my expected answer :

{
  "array1": [
    {
      "id": "id1",
      "value": "v1"
    }
  ],
  "array2": [
    {
      "id": "id-2",
      "value": "value2"
    }
  ]
}