问:
pyuic5 - aviod generating connectSlotsByName() automatically
I am using pyuic5 to generate py-files from ui-files (created with the qt-designer) this way:

```<code>pyuic5 my_form.ui -o my_form_UI.py
</code>```

I have no signals and slots defined in my ui-file. So I uncheck the option 'Connect slots by name' in the 'Form Settings' (Form/Form Settings) to connect the signals and slots manually in my python code.

But after generating the py-file, I have this code in the file 'my_form_UI.py':

```<code>QtCore.QMetaObject.connectSlotsByName(MyForm)
</code>```

In the qt-designer I have also the possibility to save the form direct as py-file, the 'connectSlotsByName'-handling is here correct, but the generated module uses the 'PySide' package and I want to use 'PyQt5'.

I also would like to use this methode, because it is very handy to convert a bunch of files and use them in the python-ide.

Here is a simple example:

```<code>import sys
from PyQt5 import QtCore, QtWidgets
from PyQt5.QtWidgets import QWidget, QMessageBox

class Ui_MyForm(object):
    def setupUi(self, MyForm):
        MyForm.setObjectName("MyForm")
        MyForm.resize(192, 86)
        self.verticalLayout = QtWidgets.QVBoxLayout(MyForm)
        self.verticalLayout.setObjectName("verticalLayout")
        self.gridLayout = QtWidgets.QGridLayout()
        self.gridLayout.setObjectName("gridLayout")
        self.ui_name = QtWidgets.QLineEdit(MyForm)
        self.ui_name.setObjectName("ui_name")
        self.gridLayout.addWidget(self.ui_name, 0, 1, 1, 1)
        self.label = QtWidgets.QLabel(MyForm)
        self.label.setObjectName("label")
        self.gridLayout.addWidget(self.label, 0, 0, 1, 1)
        self.ui_show = QtWidgets.QPushButton(MyForm)
        self.ui_show.setObjectName("ui_show")
        self.gridLayout.addWidget(self.ui_show, 1, 0, 1, 2)
        self.verticalLayout.addLayout(self.gridLayout)

        self.retranslateUi(MyForm)
        QtCore.QMetaObject.connectSlotsByName(MyForm)

    def retranslateUi(self, MyForm):
        _translate = QtCore.QCoreApplication.translate
        MyForm.setWindowTitle(_translate("MyForm", "Form"))
        self.label.setText(_translate("MyForm", "name:"))
        self.ui_show.setText(_translate("MyForm", "show"))

class MyForm(Ui_MyForm, QWidget):

    _name = ''

    @property
    def name(self):

        print(f'--> I am the name-getter!!')

        self._name = self.ui_name.text()
        return self._name

    @name.setter
    def name(self, value):

        self.ui_name.setText(value)
        self._name = value

    def __init__(self, parent=None):
        super(__class__, self).__init__(parent)
        self.setupUi(self)

        self.signals()

    def signals(self):

        self.ui_show.clicked.connect(self.show_name)

    def show_name(self):

        msg_box = QMessageBox()
        msg_box.setWindowTitle("Name")
        msg_box.setInformativeText(f'My name is {self.name}')
        msg_box.exec()

if __name__ == '__main__':

    app = QtWidgets.QApplication(sys.argv)

    form = MyForm()
    form.show()

    sys.exit(app.exec_())
</code>```

Explaination of the above code:

The class Ui_MyForm is the generated py-file from my my_form.ui. You can see here also the line with the connectSlotsByName command, although I deselected the option 'Connect slots by name' in the qt-designer. Here you have the content of my_form.ui:

```<code><?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0" connectslotsbyname="false">
 <class>MyForm</class>
 <widget class="QWidget" name="MyForm">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>192</width>
    <height>86</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>Form</string>
  </property>
  <layout class="QVBoxLayout" name="verticalLayout">
   <item>
    <layout class="QGridLayout" name="gridLayout">
     <item row="0" column="1">
      <widget class="QLineEdit" name="ui_name"/>
     </item>
     <item row="0" column="0">
      <widget class="QLabel" name="label">
       <property name="text">
        <string>name:</string>
       </property>
      </widget>
     </item>
     <item row="1" column="0" colspan="2">
      <widget class="QPushButton" name="ui_show">
       <property name="text">
        <string>show</string>
       </property>
      </widget>
     </item>
    </layout>
   </item>
  </layout>
 </widget>
 <resources/>
 <connections/>
</ui>
</code>```

When I execute my example, the command QtCore.QMetaObject.connectSlotsByName(MyForm) calls my name-getter immediately.

I have only found this information about the issue: https://forum.qt.io/topic/134578/is-there-a-way-to-avoid-pyuic5-generating-connectslotsbyname-automatically

Is there a way to exclude the 'connectSlotsByName'-command in files generated with the pyuic5 tool?

Do I use the name getter wrong? (I do not have a broad coding experience)

Body:
I am using pyuic5 to generate py-files from ui-files (created with the qt-designer) this way:

pyuic5 my_form.ui -o my_form_UI.py

I have no signals and slots defined in my ui-file. So I uncheck the option 'Connect slots by name' in the 'Form Settings' (Form/Form Settings) to connect the signals and slots manually in my python code.

But after generating the py-file, I have this code in the file 'my_form_UI.py':

QtCore.QMetaObject.connectSlotsByName(MyForm)

In the qt-designer I have also the possibility to save the form direct as py-file, the 'connectSlotsByName'-handling is here correct, but the generated module uses the 'PySide' package and I want to use 'PyQt5'.

I also would like to use this methode, because it is very handy to convert a bunch of files and use them in the python-ide.

Here is a simple example:

import sys
from PyQt5 import QtCore, QtWidgets
from PyQt5.QtWidgets import QWidget, QMessageBox

class Ui_MyForm(object):
    def setupUi(self, MyForm):
        MyForm.setObjectName("MyForm")
        MyForm.resize(192, 86)
        self.verticalLayout = QtWidgets.QVBoxLayout(MyForm)
        self.verticalLayout.setObjectName("verticalLayout")
        self.gridLayout = QtWidgets.QGridLayout()
        self.gridLayout.setObjectName("gridLayout")
        self.ui_name = QtWidgets.QLineEdit(MyForm)
        self.ui_name.setObjectName("ui_name")
        self.gridLayout.addWidget(self.ui_name, 0, 1, 1, 1)
        self.label = QtWidgets.QLabel(MyForm)
        self.label.setObjectName("label")
        self.gridLayout.addWidget(self.label, 0, 0, 1, 1)
        self.ui_show = QtWidgets.QPushButton(MyForm)
        self.ui_show.setObjectName("ui_show")
        self.gridLayout.addWidget(self.ui_show, 1, 0, 1, 2)
        self.verticalLayout.addLayout(self.gridLayout)

        self.retranslateUi(MyForm)
        QtCore.QMetaObject.connectSlotsByName(MyForm)

    def retranslateUi(self, MyForm):
        _translate = QtCore.QCoreApplication.translate
        MyForm.setWindowTitle(_translate("MyForm", "Form"))
        self.label.setText(_translate("MyForm", "name:"))
        self.ui_show.setText(_translate("MyForm", "show"))

class MyForm(Ui_MyForm, QWidget):

    _name = ''

    @property
    def name(self):

        print(f'--> I am the name-getter!!')

        self._name = self.ui_name.text()
        return self._name

    @name.setter
    def name(self, value):

        self.ui_name.setText(value)
        self._name = value

    def __init__(self, parent=None):
        super(__class__, self).__init__(parent)
        self.setupUi(self)

        self.signals()

    def signals(self):

        self.ui_show.clicked.connect(self.show_name)

    def show_name(self):

        msg_box = QMessageBox()
        msg_box.setWindowTitle("Name")
        msg_box.setInformativeText(f'My name is {self.name}')
        msg_box.exec()

if __name__ == '__main__':

    app = QtWidgets.QApplication(sys.argv)

    form = MyForm()
    form.show()

    sys.exit(app.exec_())

Explaination of the above code:

The class Ui_MyForm is the generated py-file from my my_form.ui. You can see here also the line with the connectSlotsByName command, although I deselected the option 'Connect slots by name' in the qt-designer. Here you have the content of my_form.ui:

<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0" connectslotsbyname="false">
 <class>MyForm</class>
 <widget class="QWidget" name="MyForm">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>192</width>
    <height>86</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>Form</string>
  </property>
  <layout class="QVBoxLayout" name="verticalLayout">
   <item>
    <layout class="QGridLayout" name="gridLayout">
     <item row="0" column="1">
      <widget class="QLineEdit" name="ui_name"/>
     </item>
     <item row="0" column="0">
      <widget class="QLabel" name="label">
       <property name="text">
        <string>name:</string>
       </property>
      </widget>
     </item>
     <item row="1" column="0" colspan="2">
      <widget class="QPushButton" name="ui_show">
       <property name="text">
        <string>show</string>
       </property>
      </widget>
     </item>
    </layout>
   </item>
  </layout>
 </widget>
 <resources/>
 <connections/>
</ui>

When I execute my example, the command QtCore.QMetaObject.connectSlotsByName(MyForm) calls my name-getter immediately.

I have only found this information about the issue: https://forum.qt.io/topic/134578/is-there-a-way-to-avoid-pyuic5-generating-connectslotsbyname-automatically

Is there a way to exclude the 'connectSlotsByName'-command in files generated with the pyuic5 tool?

Do I use the name getter wrong? (I do not have a broad coding experience)


来源: stackexchange

问:
Android build error when using Wikitude Sdk
I can't build my Wikitude project and the issue sounds to be in the Wikitude Sdk because whenever i use it the build crashes launching these two build errors

Building Library\Bee\artifacts\Android\iz17e\n8fd_barcode.o failed with output:
In file included from C:/Users/brahim/My project (3)/Library/Bee/artifacts/Android/il2cppOutput/cpp/barcode.cpp:3:
C:\Users\brahim\My project (3)\Library\Bee\artifacts\Android\il2cppOutput\cpp\zbar.h(1301,11): fatal error: 'zbar/Exception.h' file not found

include "zbar/Exception.h"

Building Library\Bee\artifacts\Android\d8kzr\n8fd_barcode.o failed with output:
In file included from C:/Users/brahim/My project (3)/Library/Bee/artifacts/Android/il2cppOutput/cpp/barcode.cpp:3:
C:\Users\brahim\My project (3)\Library\Bee\artifacts\Android\il2cppOutput\cpp\zbar.h(1301,11): fatal error: 'zbar/Exception.h' file not found

include "zbar/Exception.h"

i tried to export my Wikitude Apk but this error won't go away

am building for android using IL2cpp backend

ContentLicense: CC BY-SA 4.0


问:
I don't know what to do next with this exception when i run
```<code>An error occurred while starting the application.
FileNotFoundException: Could not find file 'D:\UNICEC_BE-master\UniCEC.API\unics-e46a4-firebase-adminsdk-td0dr-86cc1f1def.json'.
System.IO.FileStream.ValidateFileHandle(SafeFileHandle fileHandle)

FileNotFoundException: Could not find file 'D:\UNICEC_BE-master\UniCEC.API\unics-e46a4-firebase-adminsdk-td0dr-86cc1f1def.json'.
System.IO.FileStream.ValidateFileHandle(SafeFileHandle fileHandle)
System.IO.FileStream.CreateFileOpenHandle(FileMode mode, FileShare share, FileOptions options)
System.IO.FileStream..ctor(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, FileOptions options)
System.IO.FileStream..ctor(string path, FileMode mode, FileAccess access, FileShare share)
System.IO.File.OpenRead(string path)
Google.Apis.Auth.OAuth2.GoogleCredential.FromFile(string path)
UniCEC.API.Startup.ConfigureServices(IServiceCollection services) in Startup.cs
+
            FirebaseApp.Create(new AppOptions()
System.RuntimeMethodHandle.InvokeMethod(object target, object[] arguments, Signature sig, bool constructor, bool wrapExceptions)
System.Reflection.RuntimeMethodInfo.Invoke(object obj, BindingFlags invokeAttr, Binder binder, object[] parameters, CultureInfo culture)
Microsoft.AspNetCore.Hosting.ConfigureServicesBuilder.InvokeCore(object instance, IServiceCollection services)
Microsoft.AspNetCore.Hosting.ConfigureServicesBuilder+<>c__DisplayClass9_0.<Invoke>g__Startup|0(IServiceCollection serviceCollection)
Microsoft.AspNetCore.Hosting.ConfigureServicesBuilder.Invoke(object instance, IServiceCollection services)
Microsoft.AspNetCore.Hosting.ConfigureServicesBuilder+<>c__DisplayClass8_0.<Build>b__0(IServiceCollection services)
Microsoft.AspNetCore.Hosting.GenericWebHostBuilder.UseStartup(Type startupType, HostBuilderContext context, IServiceCollection services, object instance)
Microsoft.AspNetCore.Hosting.GenericWebHostBuilder+<>c__DisplayClass13_0.<UseStartup>b__0(HostBuilderContext context, IServiceCollection services)
Microsoft.Extensions.Hosting.HostBuilder.CreateServiceProvider()
Microsoft.Extensions.Hosting.HostBuilder.Build()
UniCEC.API.Program.Main(string[] args) in Program.cs
+
            CreateHostBuilder(args).Build().Run();[enter image description here]
</code>```

(https://i.stack.imgur.com/7Dx1m.png)

I received a project and it seems that it is not connected to the server. And I don't know what's in the other .json file.

Body:
An error occurred while starting the application.
FileNotFoundException: Could not find file 'D:\UNICEC_BE-master\UniCEC.API\unics-e46a4-firebase-adminsdk-td0dr-86cc1f1def.json'.
System.IO.FileStream.ValidateFileHandle(SafeFileHandle fileHandle)

FileNotFoundException: Could not find file 'D:\UNICEC_BE-master\UniCEC.API\unics-e46a4-firebase-adminsdk-td0dr-86cc1f1def.json'.
System.IO.FileStream.ValidateFileHandle(SafeFileHandle fileHandle)
System.IO.FileStream.CreateFileOpenHandle(FileMode mode, FileShare share, FileOptions options)
System.IO.FileStream..ctor(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, FileOptions options)
System.IO.FileStream..ctor(string path, FileMode mode, FileAccess access, FileShare share)
System.IO.File.OpenRead(string path)
Google.Apis.Auth.OAuth2.GoogleCredential.FromFile(string path)
UniCEC.API.Startup.ConfigureServices(IServiceCollection services) in Startup.cs
+
            FirebaseApp.Create(new AppOptions()
System.RuntimeMethodHandle.InvokeMethod(object target, object[] arguments, Signature sig, bool constructor, bool wrapExceptions)
System.Reflection.RuntimeMethodInfo.Invoke(object obj, BindingFlags invokeAttr, Binder binder, object[] parameters, CultureInfo culture)
Microsoft.AspNetCore.Hosting.ConfigureServicesBuilder.InvokeCore(object instance, IServiceCollection services)
Microsoft.AspNetCore.Hosting.ConfigureServicesBuilder+<>c__DisplayClass9_0.<Invoke>g__Startup|0(IServiceCollection serviceCollection)
Microsoft.AspNetCore.Hosting.ConfigureServicesBuilder.Invoke(object instance, IServiceCollection services)
Microsoft.AspNetCore.Hosting.ConfigureServicesBuilder+<>c__DisplayClass8_0.<Build>b__0(IServiceCollection services)
Microsoft.AspNetCore.Hosting.GenericWebHostBuilder.UseStartup(Type startupType, HostBuilderContext context, IServiceCollection services, object instance)
Microsoft.AspNetCore.Hosting.GenericWebHostBuilder+<>c__DisplayClass13_0.<UseStartup>b__0(HostBuilderContext context, IServiceCollection services)
Microsoft.Extensions.Hosting.HostBuilder.CreateServiceProvider()
Microsoft.Extensions.Hosting.HostBuilder.Build()
UniCEC.API.Program.Main(string[] args) in Program.cs
+
            CreateHostBuilder(args).Build().Run();[enter image description here]

(https://i.stack.imgur.com/7Dx1m.png)

I received a project and it seems that it is not connected to the server. And I don't know what's in the other .json file.


问:
Tailwind Calendar - How to make rows default height if no events?
In the below example I am struggling to do a couple of things.

1.) How to set the squares of the calendar to a default height if there are no events. In the example the squares are all tiny, then expand if there are events. I would essentially want the calendar to fill the screen as close as I can.

2.) Not sure if this is possible, but if there are events only expand the row where the events are. So in the example, If the row starting with 1/10 and there were no events that week, the height of the squares would be the default height. If the week starting on 1/24 though had a bunch of events, the squares in that row would size to accomodate the max height of the events. Is that possible?

Tailwind Play Example


问:
What way to add rightclick menu inside react-three/fiber <Canvas />?
I did experiement with "import useContextMenu from "react-use-context-menu";" but when not included directly inside the canvas tags then some buggs occure. I put it inside the div before the canvas and it works semi fine but sometimes it just pops up etc.
in the app.js

```<code>
const [
        bindMenu,
        bindMenuItem,
        useContextTrigger,
        { data, coords, setVisible }
      ] = useContextMenu();
      const [bindTrigger] = useContextTrigger({
        collect: () => "Title"
      });
      const [clickedCmd, setClickedCmd] = useState();
      const hideMenu = () => setVisible(false);
</code>```

in the return

```<code><Menu
        bindMenu={bindMenu}
        data={data}
        bindMenuItem={bindMenuItem}
        coords={coords}
        setClickedCmd={setClickedCmd}
        hideMenu={hideMenu}
      />

</code>```

Menu.js:

```<code>import React from "react";
import '../index.css';

const Menu = props => {
  const {
    bindMenu,
    data,
    bindMenuItem,
    coords,
    setClickedCmd,
    hideMenu
  } = props;

  const handleMenuItemClick = n => () => {
    setClickedCmd(n);
    hideMenu();
  };
  return (
    <div {...bindMenu} className="menu">
       <p
        {...bindMenuItem}
        onFocus={() => console.log("focused")}
        onClick={handleMenuItemClick("first")}
      >
        some stuff
      </p>
      <p
        {...bindMenuItem}
        onFocus={() => console.log("focused")}
        onClick={handleMenuItemClick("first")}
      >
        some stuff
      </p>
      <p
        {...bindMenuItem}
        onFocus={() => console.log("focused")}
        onClick={handleMenuItemClick("first")}
      >
       some stuff
      </p>
      <p
        {...bindMenuItem}
        onFocus={() => console.log("focused")}
        onClick={handleMenuItemClick("first")}
      >
        some stuff
      </p>
      <hr />
      <p>
        <span>Click coords: {JSON.stringify(coords)}</span>
      </p>

      <hr />

    </div>
  );
};

export default Menu;
</code>```

I tried using context-menu from https://github.com/cluk3/use-context-menu#readme
I was hoping for a right-click menu for navigation on a website in a react-three/fiber lib

Body:
I did experiement with "import useContextMenu from "react-use-context-menu";" but when not included directly inside the canvas tags then some buggs occure. I put it inside the div before the canvas and it works semi fine but sometimes it just pops up etc.
in the app.js

const [
        bindMenu,
        bindMenuItem,
        useContextTrigger,
        { data, coords, setVisible }
      ] = useContextMenu();
      const [bindTrigger] = useContextTrigger({
        collect: () => "Title"
      });
      const [clickedCmd, setClickedCmd] = useState();
      const hideMenu = () => setVisible(false);

in the return

<Menu
        bindMenu={bindMenu}
        data={data}
        bindMenuItem={bindMenuItem}
        coords={coords}
        setClickedCmd={setClickedCmd}
        hideMenu={hideMenu}
      />

Menu.js:

import React from "react";
import '../index.css';

const Menu = props => {
  const {
    bindMenu,
    data,
    bindMenuItem,
    coords,
    setClickedCmd,
    hideMenu
  } = props;

  const handleMenuItemClick = n => () => {
    setClickedCmd(n);
    hideMenu();
  };
  return (

 console.log("focused")}
        onClick={handleMenuItemClick("first")}
      >
        some stuff

 console.log("focused")}
        onClick={handleMenuItemClick("first")}
      >
        some stuff

 console.log("focused")}
        onClick={handleMenuItemClick("first")}
      >
       some stuff

 console.log("focused")}
        onClick={handleMenuItemClick("first")}
      >
        some stuff

        Click coords: {JSON.stringify(coords)}

  );
};

export default Menu;

I tried using context-menu from https://github.com/cluk3/use-context-menu#readme
I was hoping for a right-click menu for navigation on a website in a react-three/fiber lib


问:
Smoothly change text and width on hover
So I have a span element whose textContent changes when I hover over it.
I want the old text to fade out, then fade in the new text.
Also, since the new text is longer than the old one, the width of the span needs to increase smoothly to the new value.

The solution below basically does what I want, but I am not satisfied with it for two reasons:

It splits the animation effect in two Animations that are played one after another.
This is not elegant and it causes a slight glitch in some browsers (Chrome and Edge, but not Firefox) at the point where the first animation finishes.

Determining the old and new width "manually", by simply changing the text and using getComputedStyle, also seems quite ugly.
Also I'm not sure it will always work because getComputedStyle might not return the width in pixels.

Concerning (1), there is a different solution where I only have one Animation and the text gets changed in the middle using setTimeout.
This doesn't have the glitch, but it is likewise not elegant.

Question: What is the best way to achieve the effect described above?

Below is my current solution:

const initialText = "Hover here";
const finalText = "Text changed on hover";
const dur = 1500; // in milliseconds

const element = document.getElementById("my-element");

element.textContent = finalText;
const finalWidth = parseFloat(window.getComputedStyle(element).width);

element.textContent = initialText;
const initialWidth = parseFloat(window.getComputedStyle(element).width);

const intermediateWidth = ( initialWidth + finalWidth ) / 2;

const keyframes_0 = new KeyframeEffect(
  element,
  [{ opacity: 1, width: initialWidth + "px" }, { opacity: 0, width: intermediateWidth + "px" }],
  { duration: dur / 2 }
);

const keyframes_1 = new KeyframeEffect(
  element,
  [{ opacity: 0, width: intermediateWidth + "px" }, { opacity: 1, width: finalWidth + "px" }],
  { duration: dur / 2 }
);

const animation_0 = new Animation( keyframes_0, document.timeline );
const animation_1 = new Animation( keyframes_1, document.timeline );

element.addEventListener('mouseenter', () => {
  animateTextChange(element, animation_1, animation_0, finalText, 1.0);
});

element.addEventListener('mouseleave', () => {
  animateTextChange(element, animation_0, animation_1, initialText, -1.0);
});

function animateTextChange(elem, anim0, anim1, text, rate) {
  if( anim0.playState === "running" ) {
    anim0.onfinish = () => { };
    anim0.playbackRate = rate;
    anim0.play();
  } else {
    anim0.onfinish = () => { };
    anim1.onfinish = () => {
      elem.textContent = text;
      anim0.playbackRate = rate;
      anim0.play();
    };
    anim1.playbackRate = rate;
    anim1.play();
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><span id="my-element" style="display:inline-block; white-space:nowrap; overflow:clip">
Hover here
</span>
… more text</code>```

Title: Smoothly change text and width on hover

Body:
So I have a span element whose textContent changes when I hover over it.
I want the old text to fade out, then fade in the new text.
Also, since the new text is longer than the old one, the width of the span needs to increase smoothly to the new value.

The solution below basically does what I want, but I am not satisfied with it for two reasons:

It splits the animation effect in two Animations that are played one after another.
This is not elegant and it causes a slight glitch in some browsers (Chrome and Edge, but not Firefox) at the point where the first animation finishes.

Determining the old and new width "manually", by simply changing the text and using getComputedStyle, also seems quite ugly.
Also I'm not sure it will always work because getComputedStyle might not return the width in pixels.

Concerning (1), there is a different solution where I only have one Animation and the text gets changed in the middle using setTimeout.
This doesn't have the glitch, but it is likewise not elegant.

Question: What is the best way to achieve the effect described above?

Below is my current solution:

const initialText = "Hover here";
const finalText = "Text changed on hover";
const dur = 1500; // in milliseconds

const element = document.getElementById("my-element");

element.textContent = finalText;
const finalWidth = parseFloat(window.getComputedStyle(element).width);

element.textContent = initialText;
const initialWidth = parseFloat(window.getComputedStyle(element).width);

const intermediateWidth = ( initialWidth + finalWidth ) / 2;

const keyframes_0 = new KeyframeEffect(
  element,
  [{ opacity: 1, width: initialWidth + "px" }, { opacity: 0, width: intermediateWidth + "px" }],
  { duration: dur / 2 }
);

const keyframes_1 = new KeyframeEffect(
  element,
  [{ opacity: 0, width: intermediateWidth + "px" }, { opacity: 1, width: finalWidth + "px" }],
  { duration: dur / 2 }
);

const animation_0 = new Animation( keyframes_0, document.timeline );
const animation_1 = new Animation( keyframes_1, document.timeline );

element.addEventListener('mouseenter', () => {
  animateTextChange(element, animation_1, animation_0, finalText, 1.0);
});

element.addEventListener('mouseleave', () => {
  animateTextChange(element, animation_0, animation_1, initialText, -1.0);
});

function animateTextChange(elem, anim0, anim1, text, rate) {
  if( anim0.playState === "running" ) {
    anim0.onfinish = () => { };
    anim0.playbackRate = rate;
    anim0.play();
  } else {
    anim0.onfinish = () => { };
    anim1.onfinish = () => {
      elem.textContent = text;
      anim0.playbackRate = rate;
      anim0.play();
    };
    anim1.playbackRate = rate;
    anim1.play();
  }
}

Hover here

… more text


问:
How do I display an interactive bubble chart using Chart.js that includes a time slider
I am relatively new to Chart.js and I'd describe myself as an amateur when it comes to coding in general. I am wondering if someone could point me in the right direction when it comes to implementing the following plan as I am having a real hard time in wrapping my head around it. (tbh I don't even know if Chart.js is capable of this or if I should use another framework)

I want to create an interactive bubble chart with two "layers" that gives me a consolidated and a detailed overview of Data that changes over time. The time can be controlled via a slider below the chart. I am also planning to add info cards below that update according to the data that is currently shown. So my UI consists of three main components: The Chart itself with the two "layers", the slider that controls which data is shown and the stack of cards that can be scrolled trough horizontally.

Here is an overview of the planned functionality

The first layer/view would be the consolidated overview:

The size of the bubbles is influenced by the number of underlying sub topics that are shown at each given time

The X and Y Value is the average of all the X and Y values of the sub topics that are shown at the given time

e.g.: 1 AM, 1 Subtopic (X1=30, Y1=20) --> Size 1, X=30, Y=20; 5AM, 2 Subtopics (X1=30, Y1=20; X2=10, Y2=10) --> Size 3, X=20, Y=15)

Under the chart and the time slider is a card that shows more information about the Topic itself

A click on one of the cards or one the bubbles displays the subtopics that are underlying each bubble (the second layer)

The second layer/view is the detailed view:

The bubbles of the consolidated overview are hidden or reduced in opacity

The bubbles on the sub topics are shown

The cards below the chart now show a description of each sub topic

The size for all the sub topic bubbles is the same

The X and Y value of each bubble is fixed and doesn’t change over time

Only the number of displayed bubbles is changed over time, which influences (as described above) the value of the according topic bubble in the consolidated view

A click on one of the bubbles highlights it and scrolls to the corresponding card that is highlighted as well

A click outside of the the bubbles (in the chart area) brings you back to the consolidated overview)

Here is another visualization of the change in data over time

My main questions are:
How should I structure the data to make this work?
Where should I start when it comes to implementing all the different elements?

I am really struggling with this one, any help would be greatly appreciated! Thank you so much in advance!

I already implemented a basic bubble chart but don't know how to proceed from here


问:
How I can work with SVG files in Qt creator?
I have some problem. I need to read SVG files and place content on the QGraphicsView scene. I read documentation about QSvgWidget and QSvgRenderer, but don't understand how get all shapes from file, point coordinates, where place they and have a posibillity to change color, size and other properties. Who can suggest methods, how I can do this? Thanks in advance!

I tried create QSvgWidget and I managed draw one figure with his color, but if figures more than one, they all dye in black color, and I don't know, how I can control this.

```<code>ui->setupUi(this);
scene = new QGraphicsScene;
scene->setSceneRect(-200, -100, 400, 200);
svg_widget = new QSvgWidget(":/resources/Test3.svg");
svg_widget->renderer();
svg_rend = new QSvgRenderer;
painter = new QPainter;
svg_rend->render(painter);
svg_widget->render(painter);
scene->addWidget(svg_widget);
ui->graphicsView->setScene(scene);
</code>```

I understood that after creating QSvgWidget and call renderer(), QSvgRenderer does not affect on work with SVG. Can I combine svg_rend with svg_widget? Or does it make no sense?

Body:
I have some problem. I need to read SVG files and place content on the QGraphicsView scene. I read documentation about QSvgWidget and QSvgRenderer, but don't understand how get all shapes from file, point coordinates, where place they and have a posibillity to change color, size and other properties. Who can suggest methods, how I can do this? Thanks in advance!

I tried create QSvgWidget and I managed draw one figure with his color, but if figures more than one, they all dye in black color, and I don't know, how I can control this.

ui->setupUi(this);
scene = new QGraphicsScene;
scene->setSceneRect(-200, -100, 400, 200);
svg_widget = new QSvgWidget(":/resources/Test3.svg");
svg_widget->renderer();
svg_rend = new QSvgRenderer;
painter = new QPainter;
svg_rend->render(painter);
svg_widget->render(painter);
scene->addWidget(svg_widget);
ui->graphicsView->setScene(scene);

I understood that after creating QSvgWidget and call renderer(), QSvgRenderer does not affect on work with SVG. Can I combine svg_rend with svg_widget? Or does it make no sense?


问:
Problem with tensor shape when implementing a custom loss function for my model in Tensorflow
I picked up the idea of triplet loss and  global orthogonal regularization from this paper http://cs230.stanford.edu/projects_fall_2019/reports/26251543.pdf. However, I keep getting caught up in an tensor shape error.
After I define modelv1 as the base model (modelv1 take input of shape (None,224,224,3) and return tensor of shape (None,64)), the complete model will be defined as follow:

```<code>input_shape=(3,224,224,3)
input_all=Input(shape=input_shape)
input_anchor=input_all[:,0,:]
input_pos=input_all[:,1,:]
input_neg=input_all[:,2,:]
output_anchor=modelv1(input_anchor)
output_pos=modelv1(input_pos)
output_neg=modelv1(input_neg)
model=Model(inputs=input_all,outputs=[output_anchor,output_pos,output_neg])
</code>```

The formula for triplet loss with global orthogonal regularization, as provided in the paper I mentioned above is:
Formular for the loss function

I implemented this formular as follow:

```<code>def triplet_loss_with_margin(margin=0.4,d=64,alpha=1.1):
    def triplet_loss(y_true,y_pred):

        """
         Implementation of the triplet loss as defined by formula (3)

            Arguments:
            y_true -- true labels, required when you define a loss in Keras, you don't need it in this function.
            y_pred -- python list containing three objects:
                    anchor -- the encodings for the anchor images, of shape (None, 64)
                    positive -- the encodings for the positive images, of shape (None, 64)
                    negative -- the encodings for the negative images, of shape (None, 64)

        Returns:
        loss -- real number, value of the loss
        """
        anchor, positive, negative = y_pred[0], y_pred[1], y_pred[2]

        # Step 1: Compute the (encoding) distance between the anchor and the positive
        pos_dist = tf.math.reduce_sum(tf.math.square(tf.math.subtract(anchor,positive)),axis=-1)
        # Step 2: Compute the (encoding) distance between the anchor and the negative
        neg_dist = tf.math.reduce_sum(tf.math.square(tf.math.subtract(anchor,negative)),axis=-1)
        # Step 3: subtract the two previous distances and add alpha.
        basic_loss = tf.math.add(tf.math.subtract(pos_dist,neg_dist),margin)
        # Step 4: Take the maximum of basic_loss and 0.0. Sum over the training examples.
        loss = tf.math.reduce_sum(tf.math.maximum(basic_loss,0.0))

        # add regularization term
        dot_product=tf.matmul(anchor,tf.transpose(negative))
        multiply_2_vectors_value=tf.linalg.diag_part(dot_product)

        M1=tf.math.reduce_sum(multiply_2_vectors_value,axis=-1)

        M2=tf.math.square(multiply_2_vectors_value)
        M2=tf.math.maximum(tf.math.subtract(M2,1/d),0.0)
        M2=tf.math.reduce_sum(M2,axis=-1)

        loss+=alpha*(tf.math.square(M1)+M2)

        return loss

    return triplet_loss
</code>```

I assumed that since anchor and negative all have shape (None,64), this approach should work. However, when I trained the model, I encoutered the error bellow

```<code>ValueError: in user code:

    /opt/conda/lib/python3.7/site-packages/keras/engine/training.py:853 train_function  *
        return step_function(self, iterator)
    /tmp/ipykernel_24/1319124991.py:34 triplet_loss  *
        dot_product=tf.matmul(anchor,tf.transpose(negative))
    /opt/conda/lib/python3.7/site-packages/tensorflow/python/util/dispatch.py:206 wrapper  **
        return target(*args, **kwargs)
    /opt/conda/lib/python3.7/site-packages/tensorflow/python/ops/math_ops.py:3655 matmul
        a, b, transpose_a=transpose_a, transpose_b=transpose_b, name=name)
    /opt/conda/lib/python3.7/site-packages/tensorflow/python/ops/gen_math_ops.py:5714 mat_mul
        name=name)
    /opt/conda/lib/python3.7/site-packages/tensorflow/python/framework/op_def_library.py:750 _apply_op_helper
        attrs=attr_protos, op_def=op_def)
    /opt/conda/lib/python3.7/site-packages/tensorflow/python/framework/func_graph.py:601 _create_op_internal
        compute_device)
    /opt/conda/lib/python3.7/site-packages/tensorflow/python/framework/ops.py:3569 _create_op_internal
        op_def=op_def)
    /opt/conda/lib/python3.7/site-packages/tensorflow/python/framework/ops.py:2042 __init__
        control_input_ops, op_def)
    /opt/conda/lib/python3.7/site-packages/tensorflow/python/framework/ops.py:1883 _create_c_op
        raise ValueError(str(e))

    ValueError: Shape must be rank 2 but is rank 1 for '{{node triplet_loss/MatMul}} = MatMul[T=DT_FLOAT, transpose_a=false, transpose_b=false](triplet_loss/strided_slice, triplet_loss/transpose)' with input shapes: [64], [64].
</code>```

From what I understand, the error is caused because when implementing dot_product=tf.matmul(anchor,tf.transpose(negative)), anchor and negative only has shape (64) so it caused the error. But should anchor and negative is of shape (batch_size,64)? I really could not understand what I did wrong. Could you please enlighten me about this? Thank you

I tried to debug by implementing an independent funct to test

```<code>def triplet_loss(y_pred):

        """
         Implementation of the triplet loss as defined by formula (3)

            Arguments:
            y_true -- true labels, required when you define a loss in Keras, you don't need it in this function.
            y_pred -- python list containing three objects:
                    anchor -- the encodings for the anchor images, of shape (None, 64)
                    positive -- the encodings for the positive images, of shape (None, 64)
                    negative -- the encodings for the negative images, of shape (None, 64)

        Returns:
        loss -- real number, value of the loss
        """
        anchor, positive, negative = y_pred[0], y_pred[1], y_pred[2]

        # Step 1: Compute the (encoding) distance between the anchor and the positive
        pos_dist = tf.math.reduce_sum(tf.math.square(tf.math.subtract(anchor,positive)),axis=-1)
        # Step 2: Compute the (encoding) distance between the anchor and the negative
        neg_dist = tf.math.reduce_sum(tf.math.square(tf.math.subtract(anchor,negative)),axis=-1)
        # Step 3: subtract the two previous distances and add alpha.
        basic_loss = tf.math.add(tf.math.subtract(pos_dist,neg_dist),0.4)
        # Step 4: Take the maximum of basic_loss and 0.0. Sum over the training examples.
        loss = tf.math.reduce_sum(tf.math.maximum(basic_loss,0.0))

        # add regularization term

        print("anchor shape: ",anchor.shape)
        print("neg shape: ",negative.shape)

        dot_product=tf.matmul(anchor,tf.transpose(negative))
        multiply_2_vectors_value=tf.linalg.diag_part(dot_product)

        M1=tf.math.reduce_sum(multiply_2_vectors_value,axis=-1)

        M2=tf.math.square(multiply_2_vectors_value)
        mask=tf.math.maximum(tf.math.subtract(M2,1/64),0.0)

        M2=tf.math.reduce_sum(M2,axis=-1)

        loss+=1.1*(tf.math.square(M1)+M2)

        return loss

</code>```

And it works fine with dummy tensor I passed to it

```<code>dummy=tf.random.uniform((1,3,224,224,3))
re_dum=model.predict(dummy)
test=triplet_loss(re_dum)
</code>```

re_dum is a list of 3 elements, each is a tensor of shape (1,64),test is a number. So this little test shows that there is no problem with my implementing. But why the error keeps showing up?

Besides, when I replace

```<code> dot_product=tf.matmul(anchor,tf.transpose(negative))
</code>```

with

```<code>dot_product=tf.matmul(tf.expand_dims(anchor,axis=0),tf.transpose(tf.expand_dims(negative,axis=0)))

</code>```

The error disappeared, but it seems very perplexing for me why it works.

Body:
I picked up the idea of triplet loss and  global orthogonal regularization from this paper http://cs230.stanford.edu/projects_fall_2019/reports/26251543.pdf. However, I keep getting caught up in an tensor shape error.
After I define modelv1 as the base model (modelv1 take input of shape (None,224,224,3) and return tensor of shape (None,64)), the complete model will be defined as follow:

input_shape=(3,224,224,3)
input_all=Input(shape=input_shape)
input_anchor=input_all[:,0,:]
input_pos=input_all[:,1,:]
input_neg=input_all[:,2,:]
output_anchor=modelv1(input_anchor)
output_pos=modelv1(input_pos)
output_neg=modelv1(input_neg)
model=Model(inputs=input_all,outputs=[output_anchor,output_pos,output_neg])

The formula for triplet loss with global orthogonal regularization, as provided in the paper I mentioned above is:
Formular for the loss function

I implemented this formular as follow:

def triplet_loss_with_margin(margin=0.4,d=64,alpha=1.1):
    def triplet_loss(y_true,y_pred):

        """
         Implementation of the triplet loss as defined by formula (3)

            Arguments:
            y_true -- true labels, required when you define a loss in Keras, you don't need it in this function.
            y_pred -- python list containing three objects:
                    anchor -- the encodings for the anchor images, of shape (None, 64)
                    positive -- the encodings for the positive images, of shape (None, 64)
                    negative -- the encodings for the negative images, of shape (None, 64)

        Returns:
        loss -- real number, value of the loss
        """
        anchor, positive, negative = y_pred[0], y_pred[1], y_pred[2]

        # Step 1: Compute the (encoding) distance between the anchor and the positive
        pos_dist = tf.math.reduce_sum(tf.math.square(tf.math.subtract(anchor,positive)),axis=-1)
        # Step 2: Compute the (encoding) distance between the anchor and the negative
        neg_dist = tf.math.reduce_sum(tf.math.square(tf.math.subtract(anchor,negative)),axis=-1)
        # Step 3: subtract the two previous distances and add alpha.
        basic_loss = tf.math.add(tf.math.subtract(pos_dist,neg_dist),margin)
        # Step 4: Take the maximum of basic_loss and 0.0. Sum over the training examples.
        loss = tf.math.reduce_sum(tf.math.maximum(basic_loss,0.0))

        # add regularization term
        dot_product=tf.matmul(anchor,tf.transpose(negative))
        multiply_2_vectors_value=tf.linalg.diag_part(dot_product)

        M1=tf.math.reduce_sum(multiply_2_vectors_value,axis=-1)

        M2=tf.math.square(multiply_2_vectors_value)
        M2=tf.math.maximum(tf.math.subtract(M2,1/d),0.0)
        M2=tf.math.reduce_sum(M2,axis=-1)

        loss+=alpha*(tf.math.square(M1)+M2)

        return loss

    return triplet_loss

I assumed that since anchor and negative all have shape (None,64), this approach should work. However, when I trained the model, I encoutered the error bellow

ValueError: in user code:

    /opt/conda/lib/python3.7/site-packages/keras/engine/training.py:853 train_function  *
        return step_function(self, iterator)
    /tmp/ipykernel_24/1319124991.py:34 triplet_loss  *
        dot_product=tf.matmul(anchor,tf.transpose(negative))
    /opt/conda/lib/python3.7/site-packages/tensorflow/python/util/dispatch.py:206 wrapper  **
        return target(*args, **kwargs)
    /opt/conda/lib/python3.7/site-packages/tensorflow/python/ops/math_ops.py:3655 matmul
        a, b, transpose_a=transpose_a, transpose_b=transpose_b, name=name)
    /opt/conda/lib/python3.7/site-packages/tensorflow/python/ops/gen_math_ops.py:5714 mat_mul
        name=name)
    /opt/conda/lib/python3.7/site-packages/tensorflow/python/framework/op_def_library.py:750 _apply_op_helper
        attrs=attr_protos, op_def=op_def)
    /opt/conda/lib/python3.7/site-packages/tensorflow/python/framework/func_graph.py:601 _create_op_internal
        compute_device)
    /opt/conda/lib/python3.7/site-packages/tensorflow/python/framework/ops.py:3569 _create_op_internal
        op_def=op_def)
    /opt/conda/lib/python3.7/site-packages/tensorflow/python/framework/ops.py:2042 __init__
        control_input_ops, op_def)
    /opt/conda/lib/python3.7/site-packages/tensorflow/python/framework/ops.py:1883 _create_c_op
        raise ValueError(str(e))

    ValueError: Shape must be rank 2 but is rank 1 for '{{node triplet_loss/MatMul}} = MatMul[T=DT_FLOAT, transpose_a=false, transpose_b=false](triplet_loss/strided_slice, triplet_loss/transpose)' with input shapes: [64], [64].

From what I understand, the error is caused because when implementing dot_product=tf.matmul(anchor,tf.transpose(negative)), anchor and negative only has shape (64) so it caused the error. But should anchor and negative is of shape (batch_size,64)? I really could not understand what I did wrong. Could you please enlighten me about this? Thank you

I tried to debug by implementing an independent funct to test

def triplet_loss(y_pred):

        """
         Implementation of the triplet loss as defined by formula (3)

            Arguments:
            y_true -- true labels, required when you define a loss in Keras, you don't need it in this function.
            y_pred -- python list containing three objects:
                    anchor -- the encodings for the anchor images, of shape (None, 64)
                    positive -- the encodings for the positive images, of shape (None, 64)
                    negative -- the encodings for the negative images, of shape (None, 64)

        Returns:
        loss -- real number, value of the loss
        """
        anchor, positive, negative = y_pred[0], y_pred[1], y_pred[2]

        # Step 1: Compute the (encoding) distance between the anchor and the positive
        pos_dist = tf.math.reduce_sum(tf.math.square(tf.math.subtract(anchor,positive)),axis=-1)
        # Step 2: Compute the (encoding) distance between the anchor and the negative
        neg_dist = tf.math.reduce_sum(tf.math.square(tf.math.subtract(anchor,negative)),axis=-1)
        # Step 3: subtract the two previous distances and add alpha.
        basic_loss = tf.math.add(tf.math.subtract(pos_dist,neg_dist),0.4)
        # Step 4: Take the maximum of basic_loss and 0.0. Sum over the training examples.
        loss = tf.math.reduce_sum(tf.math.maximum(basic_loss,0.0))

        # add regularization term

        print("anchor shape: ",anchor.shape)
        print("neg shape: ",negative.shape)

        dot_product=tf.matmul(anchor,tf.transpose(negative))
        multiply_2_vectors_value=tf.linalg.diag_part(dot_product)

        M1=tf.math.reduce_sum(multiply_2_vectors_value,axis=-1)

        M2=tf.math.square(multiply_2_vectors_value)
        mask=tf.math.maximum(tf.math.subtract(M2,1/64),0.0)

        M2=tf.math.reduce_sum(M2,axis=-1)

        loss+=1.1*(tf.math.square(M1)+M2)

        return loss

And it works fine with dummy tensor I passed to it

dummy=tf.random.uniform((1,3,224,224,3))
re_dum=model.predict(dummy)
test=triplet_loss(re_dum)

re_dum is a list of 3 elements, each is a tensor of shape (1,64),test is a number. So this little test shows that there is no problem with my implementing. But why the error keeps showing up?

Besides, when I replace

 dot_product=tf.matmul(anchor,tf.transpose(negative))

with

dot_product=tf.matmul(tf.expand_dims(anchor,axis=0),tf.transpose(tf.expand_dims(negative,axis=0)))

The error disappeared, but it seems very perplexing for me why it works.


问:
Image Processing Binary images - tag connected components
I write a function for tag connection, but I get a wrong answer from the function. instead of getting 2 zones I get 5 zones.
the function description:

This function receives a binary image and finds the connected components
in it and returns a matrix with the same size in which each connected componnent is tagged with a different label. The tags should be sequential.

Args:
img: image in float format (range: 0..1) - the source binary image

Returns:
img_new: in float format (range: 0..1) - the image with components
tagging in a 2 dimensional matrice

```<code>def tag_connected_components(img: np.array) -> np.array:
img_new = img.copy()
tag = 1
label_map = {}
for r in range(len(img)):
    for c in range(len(img[0])):
        if img_new[r][c] != 0:
            # Find the labels of the non-zero neighbors
            neighbors = [img_new[r, c-1], img_new[r-1, c-1], img_new[r-1, c], img_new[r-1, c+1]]
            nonzero_labels = [label for label in neighbors if label > 0]
            if len(nonzero_labels) == 0:
                # No non-zero neighbors, assign a new label
                img_new[r][c] = tag
                tag += 1
            else:
                # Update the label map to include all the non-zero labels
                for label in nonzero_labels:
                    if label in label_map:
                        label_map[label] = label_map[label] | {smallest_label}
                    else:
                        label_map[label] = {smallest_label}
                # Use the smallest label in the label map as the new label
                img_new[r][c] = min(label for label_set in label_map.values() for label in label_set)

return img_new
</code>```

the results I get:

Body:
I write a function for tag connection, but I get a wrong answer from the function. instead of getting 2 zones I get 5 zones.
the function description:

This function receives a binary image and finds the connected components
in it and returns a matrix with the same size in which each connected componnent is tagged with a different label. The tags should be sequential.

Args:
img: image in float format (range: 0..1) - the source binary image

Returns:
img_new: in float format (range: 0..1) - the image with components
tagging in a 2 dimensional matrice

def tag_connected_components(img: np.array) -> np.array:
img_new = img.copy()
tag = 1
label_map = {}
for r in range(len(img)):
    for c in range(len(img[0])):
        if img_new[r][c] != 0:
            # Find the labels of the non-zero neighbors
            neighbors = [img_new[r, c-1], img_new[r-1, c-1], img_new[r-1, c], img_new[r-1, c+1]]
            nonzero_labels = [label for label in neighbors if label > 0]
            if len(nonzero_labels) == 0:
                # No non-zero neighbors, assign a new label
                img_new[r][c] = tag
                tag += 1
            else:
                # Update the label map to include all the non-zero labels
                for label in nonzero_labels:
                    if label in label_map:
                        label_map[label] = label_map[label] | {smallest_label}
                    else:
                        label_map[label] = {smallest_label}
                # Use the smallest label in the label map as the new label
                img_new[r][c] = min(label for label_set in label_map.values() for label in label_set)

return img_new

the results I get:


问:
My returned value is not the same as the one inside function scope

Issue description:

Hey I ran into a super weird issue I've never previously ran across.

```<code>// In the code example below you can see the actual functions called
// here is just a pseudo-code for better issue understanding

const checkErrors = (input) => {
  const data = invokeCheckFunction(input)
  console.log('wtf ==>', data) // [{ foo: 'bar'}]
  return data
}
</code>```

and then in a function that just calls it

```<code>const test = checkErrors(myInput)
console.log('why is it empty', test) // []
</code>```

The only effect in my wrapper function (second code block) - is a useState so I'm super baffled as to what could be causing this desync out of nowhere - never ran into a similar issue. Anyone got any idea what could be the culprit?

Here's the (relevant excerpt) of the actual code:

Error checking:

Error check internal handler:

```<code>import type { CheckFunction, Config, FieldError } from '../types'

type ErrorWithInternal<T, E = Error> = {
  INTENRAL_IS_ERROR: true
} & FieldError<T, E>

export const invokeCheckFunction = <T, C extends CheckFunction<T>, E = Error>(
  value: T,
  name: string,
  checkFunction: C,
) => {
  let result: ReturnType<C> | ErrorWithInternal<T, E>
  try {
    result = checkFunction(value)
  } catch (error) {
    const fieldError: ErrorWithInternal<T, E> = {
      error: error as E,
      message: (error as Error)?.message,
      name,
      value,
      INTENRAL_IS_ERROR: true,
    }
    result = fieldError
  }
  return result
}
</code>```

and the main handler:

```<code>const isError = <T, C extends CheckFunction<T>, E = Error>(
  error: ErrorWithInternal<T, E> | ReturnType<C>,
): error is ErrorWithInternal<T, E> => !!(error as ErrorWithInternal<T, E>)?.INTENRAL_IS_ERROR

const isPassed = <T, C extends CheckFunction<T>, E = Error>(
  error: ErrorWithInternal<T, E> | ReturnType<C>,
): error is ReturnType<C> => !isError(error)

export const checkErrors = <T, C extends CheckFunction<T>, E = Error>(
  value: T,
  name: string,
  checkFunctions: C[],
): [FieldError<T, E>[], ReturnType<C>[]] => {
  const results = checkFunctions.map((checkfn) =>
    invokeCheckFunction<T, C, E>(value, name, checkfn),
  )

  const internalErrors: ErrorWithInternal<T, E>[] = results.filter((e) => isError(e))
  const passed = results.filter((e) => isPassed(e)) as ReturnType<C>[]
  const errors: FieldError<T, E>[] = internalErrors.map((e) => {
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    const { INTENRAL_IS_ERROR, ...rest } = e
    return rest as FieldError<T, E>
  })

  console.log('wtf => ', errors, passed)
  return [errors, passed]
}

</code>```

The hook logic (where the issue happens)

```<code>export const useField = <T, E = Error, C extends CheckFunction<T> = CheckFunction<T>>(
  name: string,
  initialValue: T,
  configOrCheckFunction?: C | Partial<Config>,
  ...checkFunctions: C[]
) => {
  const [value, setValue] = useState<T>(initialValue)
  // Note: not a useState, not to get confused due to similar syntax
  const [initialErrors, initialCheckResults] = checkErrors<T, C, E>(value, name, checks, config)
  const [errors, setErrors] = useState<FieldError<T, E>[]>(initialErrors)
  const [checkResults, setCheckResults] = useState(initialCheckResults)

  const onChange = (event: ChangeEvent<HTMLInputElement>) => {
    const { value: newVal } = event.target
    const [newErrors, newChecked] = checkErrors<T, C, E>(
        newVal as T,
        name,
        checkFunctions,
    )
    console.log('why is it empty', newErrors)
    setErrors(newErrors)
    setValue(newVal)
  }
}
</code>```

Now I omitted some unnecessary parts for the sake of readability, but this is pretty much what it all comes down to and I have no clue what could be causing this as I never ever encountered this sort of behaviour before.

For the sake of complete reproduction, you can find the repository I'm talking about here

https://github.com/samuelhulla/eformless/tree/master/src

Two most relevant files will be

helpers/errorChecking.ts - The first block

useField.ts - The second block

Then I just used a simple react (vite) app with input for testing i.e.

```<code>import { useField } from 'eformless'

const App = () => {
  // Example of error handler
  const nonEmpty = (val: string) => {
    if (val.length === 0) {
      throw new Error('Cannot be empty')
    }
    return val
  }

  const test = useField('example', '', nonEmpty)

  return (
    <input name={test.name} value={test.value} onChange={test.onChange} />
  )
}
</code>```

Body:
Issue description:

Hey I ran into a super weird issue I've never previously ran across.

// In the code example below you can see the actual functions called
// here is just a pseudo-code for better issue understanding

const checkErrors = (input) => {
  const data = invokeCheckFunction(input)
  console.log('wtf ==>', data) // [{ foo: 'bar'}]
  return data
}

and then in a function that just calls it

const test = checkErrors(myInput)
console.log('why is it empty', test) // []

The only effect in my wrapper function (second code block) - is a useState so I'm super baffled as to what could be causing this desync out of nowhere - never ran into a similar issue. Anyone got any idea what could be the culprit?

Here's the (relevant excerpt) of the actual code:

Error checking:

Error check internal handler:

import type { CheckFunction, Config, FieldError } from '../types'

type ErrorWithInternal<T, E = Error> = {
  INTENRAL_IS_ERROR: true
} & FieldError<T, E>

export const invokeCheckFunction = <T, C extends CheckFunction<T>, E = Error>(
  value: T,
  name: string,
  checkFunction: C,
) => {
  let result: ReturnType<C> | ErrorWithInternal<T, E>
  try {
    result = checkFunction(value)
  } catch (error) {
    const fieldError: ErrorWithInternal<T, E> = {
      error: error as E,
      message: (error as Error)?.message,
      name,
      value,
      INTENRAL_IS_ERROR: true,
    }
    result = fieldError
  }
  return result
}

and the main handler:

const isError = <T, C extends CheckFunction<T>, E = Error>(
  error: ErrorWithInternal<T, E> | ReturnType<C>,
): error is ErrorWithInternal<T, E> => !!(error as ErrorWithInternal<T, E>)?.INTENRAL_IS_ERROR

const isPassed = <T, C extends CheckFunction<T>, E = Error>(
  error: ErrorWithInternal<T, E> | ReturnType<C>,
): error is ReturnType<C> => !isError(error)

export const checkErrors = <T, C extends CheckFunction<T>, E = Error>(
  value: T,
  name: string,
  checkFunctions: C[],
): [FieldError<T, E>[], ReturnType<C>[]] => {
  const results = checkFunctions.map((checkfn) =>
    invokeCheckFunction<T, C, E>(value, name, checkfn),
  )

  const internalErrors: ErrorWithInternal<T, E>[] = results.filter((e) => isError(e))
  const passed = results.filter((e) => isPassed(e)) as ReturnType<C>[]
  const errors: FieldError<T, E>[] = internalErrors.map((e) => {
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    const { INTENRAL_IS_ERROR, ...rest } = e
    return rest as FieldError<T, E>
  })

  console.log('wtf => ', errors, passed)
  return [errors, passed]
}

The hook logic (where the issue happens)

export const useField = <T, E = Error, C extends CheckFunction<T> = CheckFunction<T>>(
  name: string,
  initialValue: T,
  configOrCheckFunction?: C | Partial<Config>,
  ...checkFunctions: C[]
) => {
  const [value, setValue] = useState<T>(initialValue)
  // Note: not a useState, not to get confused due to similar syntax
  const [initialErrors, initialCheckResults] = checkErrors<T, C, E>(value, name, checks, config)
  const [errors, setErrors] = useState<FieldError<T, E>[]>(initialErrors)
  const [checkResults, setCheckResults] = useState(initialCheckResults)

  const onChange = (event: ChangeEvent<HTMLInputElement>) => {
    const { value: newVal } = event.target
    const [newErrors, newChecked] = checkErrors<T, C, E>(
        newVal as T,
        name,
        checkFunctions,
    )
    console.log('why is it empty', newErrors)
    setErrors(newErrors)
    setValue(newVal)
  }
}

Now I omitted some unnecessary parts for the sake of readability, but this is pretty much what it all comes down to and I have no clue what could be causing this as I never ever encountered this sort of behaviour before.

For the sake of complete reproduction, you can find the repository I'm talking about here

https://github.com/samuelhulla/eformless/tree/master/src

Two most relevant files will be

helpers/errorChecking.ts - The first block

useField.ts - The second block

Then I just used a simple react (vite) app with input for testing i.e.

import { useField } from 'eformless'

const App = () => {
  // Example of error handler
  const nonEmpty = (val: string) => {
    if (val.length === 0) {
      throw new Error('Cannot be empty')
    }
    return val
  }

  const test = useField('example', '', nonEmpty)

  return (
    <input name={test.name} value={test.value} onChange={test.onChange} />
  )
}


问:
How can I fix a type error with msal-configuration and process.env mismatch?
I'm getting a type error in the last line of code here:

```<code>import * as msal from '@azure/msal-browser'
import * as dotenv from "dotenv";
dotenv.config()

const msalConfig = {
        auth: {
            clientId: process.env.AZ_CLIENT_ID,
            authority: process.env.AZ_AUTHORITY,
            redirectUri: process.env.AZ_REDIRECT_URI,
        },
    }
    console.log(msalConfig)
    const msalInstance = new msal.PublicClientApplication(msalConfig)
</code>```

It appears, that process.env can either return a string or undefined. How can I fix this?

Body:
I'm getting a type error in the last line of code here:

import * as msal from '@azure/msal-browser'
import * as dotenv from "dotenv";
dotenv.config()

const msalConfig = {
        auth: {
            clientId: process.env.AZ_CLIENT_ID,
            authority: process.env.AZ_AUTHORITY,
            redirectUri: process.env.AZ_REDIRECT_URI,
        },
    }
    console.log(msalConfig)
    const msalInstance = new msal.PublicClientApplication(msalConfig)

It appears, that process.env can either return a string or undefined. How can I fix this?


问:
Reducing the size of a figure saved in .EPS/.SVG format in R
Whenever saving a figure in R in .EPS or .SVG format, the size of the file is too large to be incorporated in an environment like Overleaf. How can I reduce the size? It feels rather unnecessary for a simple figure to be 141 mb (!).

This involves figures from the ComplexUpset package which formats via ggplot2

```<code>upset(
  M1_BinaryMatrix,
  colnames(M1_BinaryMatrix),
  sort_intersections_by='ratio',
  intersections='all',
  min_degree=2,

  set_sizes=(
    upset_set_size(position='right')
    + geom_text(aes(label=paste0(round((..count../nrow(M1_BinaryMatrix))*100), '%')), hjust=1.1, stat='count', color='white')
    + expand_limits(y=1000)
    + ylab("")
    + theme(axis.text.x = element_blank())
  ),
  #
  base_annotations=list(
    'Intersection ratio'=intersection_ratio(text_mapping=aes(label=!!upset_text_percentage()))
#    'Intersection ratio'= intersection_ratio(text_mapping=aes(label=paste0(round(
#      !!get_size_mode('inclusive_intersection')/!!nrow(head(M1_BinaryMatrix, 1000)) * 100
#    ), '%')))
    + ylab("")
    + theme(axis.text.y=element_blank())
  ),
  #
  name="",
  wrap=TRUE,
  stripes=c(alpha('grey90', 0.45), alpha('white', 0.3)),
  matrix = intersection_matrix(
    geom=geom_point(
      shape='square',
      size=4
    ),
    segment=geom_segment(
      linetype='solid'
    ),
    outline_color=list(
      active='darkorange3',
      inactive='grey70'
    )
  )
) + labs(title = "", caption = "")
</code>```

The data frame has 10 M rows and 3 columns.

Body:
Whenever saving a figure in R in .EPS or .SVG format, the size of the file is too large to be incorporated in an environment like Overleaf. How can I reduce the size? It feels rather unnecessary for a simple figure to be 141 mb (!).

This involves figures from the ComplexUpset package which formats via ggplot2

upset(
  M1_BinaryMatrix,
  colnames(M1_BinaryMatrix),
  sort_intersections_by='ratio',
  intersections='all',
  min_degree=2,

  set_sizes=(
    upset_set_size(position='right')
    + geom_text(aes(label=paste0(round((..count../nrow(M1_BinaryMatrix))*100), '%')), hjust=1.1, stat='count', color='white')
    + expand_limits(y=1000)
    + ylab("")
    + theme(axis.text.x = element_blank())
  ),
  #
  base_annotations=list(
    'Intersection ratio'=intersection_ratio(text_mapping=aes(label=!!upset_text_percentage()))
#    'Intersection ratio'= intersection_ratio(text_mapping=aes(label=paste0(round(
#      !!get_size_mode('inclusive_intersection')/!!nrow(head(M1_BinaryMatrix, 1000)) * 100
#    ), '%')))
    + ylab("")
    + theme(axis.text.y=element_blank())
  ),
  #
  name="",
  wrap=TRUE,
  stripes=c(alpha('grey90', 0.45), alpha('white', 0.3)),
  matrix = intersection_matrix(
    geom=geom_point(
      shape='square',
      size=4
    ),
    segment=geom_segment(
      linetype='solid'
    ),
    outline_color=list(
      active='darkorange3',
      inactive='grey70'
    )
  )
) + labs(title = "", caption = "")

The data frame has 10 M rows and 3 columns.


问:
Multiple headers in sap.m table
Please help me in how to set multiple headers and headerSpan in sap.m.table

I have to create a table using sap.m library only and my table should like below image

I tried using vboxes in column->header->vbox

But unable to group columns and i need underline

Title: Multiple headers in sap.m table


问:
Spring boot + hibernate - save a descendant from an abstract object
I can't save the object to the database.

```<code>@Entity
public abstract class Participant {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;
    @ManyToOne
    @JoinColumn(name = "parent_id", nullable=false)
    private Participant parent;

    private String surname;

    private String name;

    private String patronymic;

    private String birthday;

    private String address;

    private int age;

....
}
</code>```
```<code>@Entity
@Table(name = "agreements_participant_child")
public class ParticipantChild extends Participant{
    private String certSerial;
    private String certNumber;
    private String certIssuedDate;
    private String certIssuedBy;
...
}
</code>```
```<code>@Entity
@Table(name = "agreements_participants")
public class Participants {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;

    @OneToOne
    ParticipantAdult mother;
    @OneToOne
    ParticipantAdult father;
    @OneToMany(mappedBy = "id")
    ArrayList<Participant> children;

</code>```

I get an error

```<code>Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed: org.springframework.orm.jpa.JpaSystemException: Could not set value of type [org.hibernate.collection.spi.PersistentBag] : `ru.thebestsoft.lawtreaty3.employees.participants.Participants.children` (setter)] with root cause
</code>```

I understand that the problem is inheritance from an abstract class and I need to tell hibernate that the class is abstract, but I don't know how.

Body:
I can't save the object to the database.

@Entity
public abstract class Participant {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;
    @ManyToOne
    @JoinColumn(name = "parent_id", nullable=false)
    private Participant parent;

    private String surname;

    private String name;

    private String patronymic;

    private String birthday;

    private String address;

    private int age;

....
}

@Entity
@Table(name = "agreements_participant_child")
public class ParticipantChild extends Participant{
    private String certSerial;
    private String certNumber;
    private String certIssuedDate;
    private String certIssuedBy;
...
}

@Entity
@Table(name = "agreements_participants")
public class Participants {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;

    @OneToOne
    ParticipantAdult mother;
    @OneToOne
    ParticipantAdult father;
    @OneToMany(mappedBy = "id")
    ArrayList<Participant> children;

I get an error

Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed: org.springframework.orm.jpa.JpaSystemException: Could not set value of type [org.hibernate.collection.spi.PersistentBag] : `ru.thebestsoft.lawtreaty3.employees.participants.Participants.children` (setter)] with root cause

I understand that the problem is inheritance from an abstract class and I need to tell hibernate that the class is abstract, but I don't know how.


问:
Retrieve list of cities while typing - OpenWeatherApi

Goal

I'm building a weather app with vite and openweatherapi, and I want to display a list of all matching cities when I type text in input.

What I do

I created an input, with a useEffect that fetch data on input text change.
I retrieve datas, but instead of getting an array of cities that match my string, I get cities that match exactly.

Example

I type "Lon", and of course I want "London" in my response, but I get 5 cities with name: "Lon"

I saw in the doc the find endpoint, but maybe I am on the wrong path ?

PS

GenericApi is just an axios.create and an option setter. It basically return the response.data

Code

```<code>export function Search() {
    const [inputValue, setInputValue] = useState<string>("");
    const [citiesInSearch, setCitiesInSearch] = useState<[] | null>(null);

    const getCities = async () => {
        const response: AxiosResponse = await GenericApi.get(
            `${import.meta.env.VITE_WEATHER_API}/data/2.5/find?q=${inputValue}&units=metric&appid=${import.meta.env.VITE_WEATHER_API_KEY}`
        );

        if (response.data) {
            setCitiesInSearch(response.data.list);
        }
    };

    useEffect(() => {
        if (inputValue.length > 2) getCities();
    }, [inputValue]);

    return (
        <div>
            <input value={inputValue} onChange={(e) => setInputValue(e.target.value)} />
            <ul>
                {citiesInSearch &&
                    citiesInSearch.map((city) => {
                        return <li>{city}</li>;
                    })}
            </ul>
        </div>
    );
</code>```

Body:
Goal

I'm building a weather app with vite and openweatherapi, and I want to display a list of all matching cities when I type text in input.

What I do

I created an input, with a useEffect that fetch data on input text change.
I retrieve datas, but instead of getting an array of cities that match my string, I get cities that match exactly.

Example

I type "Lon", and of course I want "London" in my response, but I get 5 cities with name: "Lon"

I saw in the doc the find endpoint, but maybe I am on the wrong path ?

PS

GenericApi is just an axios.create and an option setter. It basically return the response.data

Code

export function Search() {
    const [inputValue, setInputValue] = useState<string>("");
    const [citiesInSearch, setCitiesInSearch] = useState<[] | null>(null);

    const getCities = async () => {
        const response: AxiosResponse = await GenericApi.get(
            `${import.meta.env.VITE_WEATHER_API}/data/2.5/find?q=${inputValue}&units=metric&appid=${import.meta.env.VITE_WEATHER_API_KEY}`
        );

        if (response.data) {
            setCitiesInSearch(response.data.list);
        }
    };

    useEffect(() => {
        if (inputValue.length > 2) getCities();
    }, [inputValue]);

    return (

            <input value={inputValue} onChange={(e) => setInputValue(e.target.value)} />

                {citiesInSearch &&
                    citiesInSearch.map((city) => {
                        return
{city}
;
                    })}

    );


问:
Mutex is defying the very idea of threads: parallel processing
I'm recent to learning threads and there's a thought that I have in my mind.
Let's say I have the following code:

#include <iostream>
#include <thread>
#include <mutex>
using namespace std;

int myAmount = 0;
std::mutex m;

void addMoney(){
    m.lock();
    myAmount++;
    m.unlock();
}

int main(){
    thread t1(addMoney);
    thread t2(addMoney);
    t1.join();
    t2.join();
    cout<<addMoney<<endl;
    return 0;
}
```

Here mutex prevents the race condition by locking the thread application until it gets finished. Till the thread is working, another thread t2 is kept in a queue. Once thread t1 is finished, the variable in the data segment of the memory gets updated and the queue passes on permitting thread t2 to work.
We know we use threads for parallel processing, but here the processing of the threads is sequential rather than parallel. So if I write a single thread version of the above code, which would run faster? The multi-threaded one or the single-threaded one?

Please correct me where I'm wrong about the concept.

Body:
I'm recent to learning threads and there's a thought that I have in my mind.
Let's say I have the following code:

#include <iostream>
#include <thread>
#include <mutex>
using namespace std;

int myAmount = 0;
std::mutex m;

void addMoney(){
    m.lock();
    myAmount++;
    m.unlock();
}

int main(){
    thread t1(addMoney);
    thread t2(addMoney);
    t1.join();
    t2.join();
    cout<<addMoney<<endl;
    return 0;
}

Here mutex prevents the race condition by locking the thread application until it gets finished. Till the thread is working, another thread t2 is kept in a queue. Once thread t1 is finished, the variable in the data segment of the memory gets updated and the queue passes on permitting thread t2 to work.
We know we use threads for parallel processing, but here the processing of the threads is sequential rather than parallel. So if I write a single thread version of the above code, which would run faster? The multi-threaded one or the single-threaded one?

Please correct me where I'm wrong about the concept.


问:
How can I open an R Markdown file from GitHub in Google Colab?
I´d like to create links for R markdown files (.Rmd) in a GitHub repo so that these directly open in Google Colab.

I can do this with Python Jupyter notebooks. However, I haven't found any way to achieve the same with R Markdown files.

How can I do this?

Thanks for any help or pointer in the right direction.

PS: One of the few hints I found online mentions this link format, which unfortunately doesn't work:

```<code>https://colab.research.google.com/github/<GITHUB ACCOUNT NAME>/<REPO NAME>/blob/master/example.Rmd
</code>```

Colab yields this error message:

```<code>Notebook loading error
The file has been corrupted or is not a valid notebook file.
</code>```

However, the notebooks that I tested work properly on any other platform, e.g. RStudio etc.

Body:
I´d like to create links for R markdown files (.Rmd) in a GitHub repo so that these directly open in Google Colab.

I can do this with Python Jupyter notebooks. However, I haven't found any way to achieve the same with R Markdown files.

How can I do this?

Thanks for any help or pointer in the right direction.

PS: One of the few hints I found online mentions this link format, which unfortunately doesn't work:

https://colab.research.google.com/github/<GITHUB ACCOUNT NAME>/<REPO NAME>/blob/master/example.Rmd

Colab yields this error message:

Notebook loading error
The file has been corrupted or is not a valid notebook file.

However, the notebooks that I tested work properly on any other platform, e.g. RStudio etc.


问:
Using an API in Maven
I have an API for Java that I've been messing around with. It is a maven project. I want to be able to test that it works. Is there a way I can make a new Java project and using maven to import that API into my project?

(Not that it should matter but I am using IntelliJ)

Example:

API is CommandAPI. Now I want to make a "CommandAPITester" project where I import the API using maven and play around with some tests.

Thank you!

Please let me know if you need any more info to answer the question.

Title: Using an API in Maven


问:
How to play Android's textToSpeech text through speakers even when headphones are plugged in?
The following code forces the app to play sound through speaker when headphones are plugged in:

```<code> AudioManager audioManager = (AudioManager)getContext().getSystemService(Context.AUDIO_SERVICE);
audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);
audioManager.setSpeakerphoneOn(true/false);
soundPlayer.setAudioStreamType(AudioManager.MODE_IN_COMMUNICATION);

soundPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
</code>```

But what about TextToSpeech class? Is there a way to implement such a logic with it? You can see my textToSpeech code below.

```<code>  String utteranceId = UUID.randomUUID().toString();//unique id
  textToSpeech.speak(toSpeak, TextToSpeech.QUEUE_FLUSH, null, utteranceId);
</code>```

Body:
The following code forces the app to play sound through speaker when headphones are plugged in:

 AudioManager audioManager = (AudioManager)getContext().getSystemService(Context.AUDIO_SERVICE);
audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);
audioManager.setSpeakerphoneOn(true/false);
soundPlayer.setAudioStreamType(AudioManager.MODE_IN_COMMUNICATION);

soundPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);

But what about TextToSpeech class? Is there a way to implement such a logic with it? You can see my textToSpeech code below.

  String utteranceId = UUID.randomUUID().toString();//unique id
  textToSpeech.speak(toSpeak, TextToSpeech.QUEUE_FLUSH, null, utteranceId);


问:
Win32 GetSysColor(): Many colours now say: Windows 10 or greater: This value is not supported
Background: I am trying to reimplement Qt widget "QSizeGrip" as a custom control using the native Win32 C API.  Ref: https://doc.qt.io/qt-6/qsizegrip.html

Super zoomed screenshot from GIMP:

From the official docs for GetSysColor() here: https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getsyscolor, many colours now have the warning: "Windows 10 or greater: This value is not supported."

Example: COLOR_BTNFACE -- This was my original choice for the background.

What three system colours should I use on Win10+ to re-create this Qt widget?

For the most modern solution, my guess: Call HTHEME GetWindowTheme(hWnd), then call HBRUSH GetThemeSysColorBrush(HTHEME, int iColorIdFromGetSysColor), but I don't know which iColorId values to choose.


问:
Android application crashes in Debug mode with FORTIFY: fread: null FILE*
I am trying to run Android application on Paired Device via Wifi and it fail to run with following error:

I guess it is due to the audit warning that it cannot read respective file in /mnt/vendor folder, but Android is not my main technology field so I am at wits end what the solution might be.

It also look like the application is not trusted, but it have all the permissions as I am using example application from someone else and the AndroidManifest.xml permissions are the same.

Thanks a lot in advance!


问:
TypeScript types -- Merge keys and values into record
I'm trying to combine keys and values into a record:

```<code>type Keys = ["a", "b"];
type Values = ["alpha", "bravo"]

type Expected = {
  a: "alpha",
  b: "bravo"
}
</code>```

I have the following attempt at it:

```<code>type Actual = { [K in Keys[number]]: Values }
</code>```

but I'm unsure about how I can extract the index from the mapped type to index the Values tuple.

TypeScript Playground

Body:
I'm trying to combine keys and values into a record:

type Keys = ["a", "b"];
type Values = ["alpha", "bravo"]

type Expected = {
  a: "alpha",
  b: "bravo"
}

I have the following attempt at it:

type Actual = { [K in Keys[number]]: Values }

but I'm unsure about how I can extract the index from the mapped type to index the Values tuple.

TypeScript Playground


问:
Docker Build Error: executor failed running [/bin/sh -c npm run build]: exit code: 1 with NextJS and npm
I have a NextJS app with the following Dockerfile.production:

```<code>FROM node:16-alpine AS deps

ENV NODE_ENV=production

RUN apk add --no-cache libc6-compat
WORKDIR /app

COPY package.json yarn.lock* package-lock.json* pnpm-lock.yaml* ./
RUN \
    if [ -f yarn.lock ]; then yarn --frozen-lockfile; \
    elif [ -f package-lock.json ]; then npm ci; \
    elif [ -f pnpm-lock.yaml ]; then yarn global add pnpm && pnpm i --frozen-lockfile; \
    else echo "Lockfile not found." && exit 1; \
    fi

FROM node:16-alpine AS builder

ENV NODE_ENV=production

WORKDIR /app

COPY --from=deps /app/node_modules ./node_modules
COPY . .

RUN npm run build

FROM node:16-alpine AS runner
WORKDIR /app

ENV NODE_ENV production

RUN addgroup --system --gid 1001 nodejs
RUN adduser --system --uid 1001 nextjs

COPY --from=builder /app/public ./public

COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./
COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static

USER nextjs

CMD ["node", "server.js"]
</code>```

This is my docker-compose.production.yml:

```<code>
services:
  app:
    image: wayve
    build:
      dockerfile: Dockerfile.production
    ports:
      - 3000:3000
</code>```

When I run docker-compose -f docker-compose.production.yml up --build --force-recreate in my terminal (at the root) I get the following build error:
failed to solve: executor failed running [/bin/sh -c npm run build]: exit code: 1

I do not see any issues with my docker-compose file or my Dockerfile. How can I fix this issue? TYA

Body:
I have a NextJS app with the following Dockerfile.production:

FROM node:16-alpine AS deps

ENV NODE_ENV=production

RUN apk add --no-cache libc6-compat
WORKDIR /app

COPY package.json yarn.lock* package-lock.json* pnpm-lock.yaml* ./
RUN \
    if [ -f yarn.lock ]; then yarn --frozen-lockfile; \
    elif [ -f package-lock.json ]; then npm ci; \
    elif [ -f pnpm-lock.yaml ]; then yarn global add pnpm && pnpm i --frozen-lockfile; \
    else echo "Lockfile not found." && exit 1; \
    fi

FROM node:16-alpine AS builder

ENV NODE_ENV=production

WORKDIR /app

COPY --from=deps /app/node_modules ./node_modules
COPY . .

RUN npm run build

FROM node:16-alpine AS runner
WORKDIR /app

ENV NODE_ENV production

RUN addgroup --system --gid 1001 nodejs
RUN adduser --system --uid 1001 nextjs

COPY --from=builder /app/public ./public

COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./
COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static

USER nextjs

CMD ["node", "server.js"]

This is my docker-compose.production.yml:

services:
  app:
    image: wayve
    build:
      dockerfile: Dockerfile.production
    ports:
      - 3000:3000

When I run docker-compose -f docker-compose.production.yml up --build --force-recreate in my terminal (at the root) I get the following build error:
failed to solve: executor failed running [/bin/sh -c npm run build]: exit code: 1

I do not see any issues with my docker-compose file or my Dockerfile. How can I fix this issue? TYA


问:
Docker Swarm mix private and public networks
I have multiple Raspberry Pi's at home and would like to make a Docker Swarm cluster out of it.
Each have it own private ip on my home network.
That part is working fine.

But to make it more reliable I would like to add a VPS to the cluster. The issue is with the networks, the raspberry are on a private network and the VPS on public one.

I'd like to avoid using VPN or other services.

Is it possible to add it to the cluster ?

What is the process to do so ?

I tried with the following steps :

Forward ports 7946, 4789 and 2377 to the master of my cluster

Init the swarm on Pi4 with public IP specifying --listen-addr HOME_IP

Pi3 joins the cluster using private IP

VPS joins the cluster using public IP specifying --advertise-addr VPS_IP

But the overlay network is not working properly, when a service is on the VPS, the published port is not responding on any of the raspberry and vice-versa


问:
Problems with login and authentication in Laravel
I need help with my login and authentication of admin.

In the database I have a table called 'admins' with columns of 'name', 'surname', 'password' in my native language.

Every time I press the login button when I try to log in, I get an error:

"Undefined index: password"

where password is in English in folder:

```<code>C:\wamp\www\app\vendor\laravel\framework\src\Illuminate\Auth\EloquentUserProvider.php
</code>```

and I don't know why.

My custom controller AuthController:

```<code><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Hash;
use Session;
use App\Models\Admin;
use Illuminate\Support\Facades\Auth;
class AuthController extends Controller
{
    public function index()
    {
        return view('auth.login');
    }

    public function customLogin(Request $request)
    {
        $request->validate([
            'name' => 'required',
            'surname' => 'required',
            'passw' => 'required',
        ]);

        $credentials = $request->only('name', 'surname', 'passw');
        if (Auth::attempt($credentials)) {
            return redirect()->intended('');
        }

        return redirect("login")->withSuccess('Wrong input data.');
    }

    public function dashboard()
    {
        if(Auth::check()){
            return view('');
        }

        return redirect("login")->withSuccess('Wrong input data.');
    }

    public function signOut() {
        Session::flush();
        Auth::logout();

        return Redirect('');
    }
}
</code>```

My route:

```<code>Auth::routes();
Route::post('/login', 'AuthController@customLogin');
</code>```

I consulted with an acquaintance that specialises in web-programming and she said I should do a custom AuthController, which I did, but the problem is either still not fixed or this is a different error.

And from web sources I used:

https://www.positronx.io/laravel-custom-authentication-login-and-registration-tutorial/

Body:
I need help with my login and authentication of admin.

In the database I have a table called 'admins' with columns of 'name', 'surname', 'password' in my native language.

Every time I press the login button when I try to log in, I get an error:

"Undefined index: password"

where password is in English in folder:

C:\wamp\www\app\vendor\laravel\framework\src\Illuminate\Auth\EloquentUserProvider.php

and I don't know why.

My custom controller AuthController:

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Hash;
use Session;
use App\Models\Admin;
use Illuminate\Support\Facades\Auth;
class AuthController extends Controller
{
    public function index()
    {
        return view('auth.login');
    }

    public function customLogin(Request $request)
    {
        $request->validate([
            'name' => 'required',
            'surname' => 'required',
            'passw' => 'required',
        ]);

        $credentials = $request->only('name', 'surname', 'passw');
        if (Auth::attempt($credentials)) {
            return redirect()->intended('');
        }

        return redirect("login")->withSuccess('Wrong input data.');
    }

    public function dashboard()
    {
        if(Auth::check()){
            return view('');
        }

        return redirect("login")->withSuccess('Wrong input data.');
    }

    public function signOut() {
        Session::flush();
        Auth::logout();

        return Redirect('');
    }
}

My route:

Auth::routes();
Route::post('/login', 'AuthController@customLogin');

I consulted with an acquaintance that specialises in web-programming and she said I should do a custom AuthController, which I did, but the problem is either still not fixed or this is a different error.

And from web sources I used:

https://www.positronx.io/laravel-custom-authentication-login-and-registration-tutorial/


问:
Fetch records as batches in Postgres using a cursor
I need to fetch data as 100 of records batches from a PostgresSQL table. I have tried the following function,

```<code>CREATE OR REPLACE FUNCTION fetch_compare_prices(n integer)
RETURNS SETOF varchar AS $$
DECLARE
  curs CURSOR FOR SELECT * FROM compareprices LIMIT n;
  row  RECORD;
BEGIN
  open curs;
  LOOP
    FETCH FROM curs INTO row;
    EXIT WHEN NOT FOUND;
    return next row.deal_id;
  END LOOP;
END; $$ LANGUAGE plpgsql;
</code>```

I ran this query to get results from the above function.select fetch_compare_prices(100); But this gives me only same 100 records always. Is there a way to fetch 100 records as batches using a cursor.

also with this return next row.deal_id; statement I can only return just the deal_id but no other columns. Is there a way to get all the columns/row?

Also, It should work like when I run select fetch_compare_prices(100); this for the 1st time, it should return first 100 rows, when I run it 2nd time, it should give rows from 100 to 200(next 100). What's the correct usage of cursor to do this?

Body:
I need to fetch data as 100 of records batches from a PostgresSQL table. I have tried the following function,

CREATE OR REPLACE FUNCTION fetch_compare_prices(n integer)
RETURNS SETOF varchar AS $$
DECLARE
  curs CURSOR FOR SELECT * FROM compareprices LIMIT n;
  row  RECORD;
BEGIN
  open curs;
  LOOP
    FETCH FROM curs INTO row;
    EXIT WHEN NOT FOUND;
    return next row.deal_id;
  END LOOP;
END; $$ LANGUAGE plpgsql;

I ran this query to get results from the above function.select fetch_compare_prices(100); But this gives me only same 100 records always. Is there a way to fetch 100 records as batches using a cursor.

also with this return next row.deal_id; statement I can only return just the deal_id but no other columns. Is there a way to get all the columns/row?

Also, It should work like when I run select fetch_compare_prices(100); this for the 1st time, it should return first 100 rows, when I run it 2nd time, it should give rows from 100 to 200(next 100). What's the correct usage of cursor to do this?