问:
Flutter- Issue when passing the value and return it's value
I have class CTAButton which extend BaseStatelessWidget<HomeBloc, IGeneralState>,from this class I use a variable called isLoading which passing to the CTAButton class to make the CircularProgressIndicator shown. When I click on CTAButton it called an event from BaseStatelessWidget the event at first be as Loading then Success, during the loading time I need to let the isLoading = true to let the CircularProgressIndicator shown, and after the event become Success it move to next page and return the isLoading = flase and CircularProgressIndicator disappere, but always I recieve the value of isLoading =flase.

Here some of the classes I used :

```<code>class BaseStatelessWidget<B extends Bloc<dynamic, T>, T> extends StatelessWidget {
  bool isLoading = false;
@override
  BlocProvider<B> build(BuildContext context) {
    return BlocProvider.value(
      value: onCreate(context),
      child: WillPopScope(
        onWillPop: () {
          dispose();

          return Future.value(true);
        },
        child: _buildBaseView(context),
      ),
    );
  }
// continue the code ...etc

// when press the button an call the event.
  @protected
  void _onListener(context, state) {
    // printLog('[BaseState] onListener $state');
    if (state is Loading) {
      isLoading = true;
      onLoadingListener(state);
    } else if (state is Success) {
      isLoading = false;
      onSuccessListener(state);
    } else if (state is Exception) {
      isLoading = false;
      onExceptionListener(state);
    }
  }
}
</code>```
```<code>class CTAButton extends BaseStatelessWidget<HomeBloc<HomeState>, IGeneralState<HomeState>> {
 return Center(
      child: Container(
        alignment: Alignment.center,
        child: PhysicalModel(
          elevation: 4,
          shadowColor: Colors.black,
          color: mainColor,
          borderRadius: BorderRadius.circular(25),
          child: SizedBox(
              height: 328,
              width: 50,
              child: ElevatedButton(
                  elevation: MaterialStateProperty.all<double>(0),
                  shape: MaterialStateProperty.all(
                    RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(radius),
                      side: border,
                    ),
                  ),
                ),
                child: setUpButtonChild(context),
                onPressed: onPressed == null
                    ? null
                    : () {
                        if (onPressed != null) {
                          onPressed!();
                        }
                      },
              )),
return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        if (isLoading)
          SizedBox(
            height: indicator,
            width: indicator,
            child: const Padding(
              padding: EdgeInsets.all(10.0),
              child: CircularProgressIndicator(
                value: null,
                valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
              ),
            ),
          ),
        if (isLoading) const SizedBox(width: 10),
        text
      ],
    );
}
</code>```

Here using the CTAButton in class and called it on somewhere in the code:

```<code>class HomeScreen extends BaseStatelessWidget<HomeBloc<HomeState>, IGeneralState<HomeState>> {
 //code
// Details it's a widget that containe the CTAButton.
  return Details(
                        key: Key("DetailsStart"),
                        onTap: () {
                         // Event call the method of _onListener from BaseStatelessWidget
                          broadcastEvent(
                            ArriveToLocationEvent(
                              //code of event some args
                            ),
                          );
                          broadcastEvent(RefreshMarkersEvent(pageBloc.homeState.homeMarkers));
                        },
                      );
}
</code>```

I passing isLoading to show CircularProgressIndicator but always I recieved isLoading =show, and I want to take it's value in correct way to show CircularProgressIndicator when click the CTAButton

Body:
I have class CTAButton which extend BaseStatelessWidget<HomeBloc, IGeneralState>,from this class I use a variable called isLoading which passing to the CTAButton class to make the CircularProgressIndicator shown. When I click on CTAButton it called an event from BaseStatelessWidget the event at first be as Loading then Success, during the loading time I need to let the isLoading = true to let the CircularProgressIndicator shown, and after the event become Success it move to next page and return the isLoading = flase and CircularProgressIndicator disappere, but always I recieve the value of isLoading =flase.

Here some of the classes I used :

class BaseStatelessWidget<B extends Bloc<dynamic, T>, T> extends StatelessWidget {
  bool isLoading = false;
@override
  BlocProvider build(BuildContext context) {
    return BlocProvider.value(
      value: onCreate(context),
      child: WillPopScope(
        onWillPop: () {
          dispose();

          return Future.value(true);
        },
        child: _buildBaseView(context),
      ),
    );
  }
// continue the code ...etc

// when press the button an call the event.
  @protected
  void _onListener(context, state) {
    // printLog('[BaseState] onListener $state');
    if (state is Loading) {
      isLoading = true;
      onLoadingListener(state);
    } else if (state is Success) {
      isLoading = false;
      onSuccessListener(state);
    } else if (state is Exception) {
      isLoading = false;
      onExceptionListener(state);
    }
  }
}

class CTAButton extends BaseStatelessWidget<HomeBloc<HomeState>, IGeneralState<HomeState>> {
 return Center(
      child: Container(
        alignment: Alignment.center,
        child: PhysicalModel(
          elevation: 4,
          shadowColor: Colors.black,
          color: mainColor,
          borderRadius: BorderRadius.circular(25),
          child: SizedBox(
              height: 328,
              width: 50,
              child: ElevatedButton(
                  elevation: MaterialStateProperty.all<double>(0),
                  shape: MaterialStateProperty.all(
                    RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(radius),
                      side: border,
                    ),
                  ),
                ),
                child: setUpButtonChild(context),
                onPressed: onPressed == null
                    ? null
                    : () {
                        if (onPressed != null) {
                          onPressed!();
                        }
                      },
              )),
return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        if (isLoading)
          SizedBox(
            height: indicator,
            width: indicator,
            child: const Padding(
              padding: EdgeInsets.all(10.0),
              child: CircularProgressIndicator(
                value: null,
                valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
              ),
            ),
          ),
        if (isLoading) const SizedBox(width: 10),
        text
      ],
    );
}

Here using the CTAButton in class and called it on somewhere in the code:

class HomeScreen extends BaseStatelessWidget<HomeBloc<HomeState>, IGeneralState<HomeState>> {
 //code
// Details it's a widget that containe the CTAButton.
  return Details(
                        key: Key("DetailsStart"),
                        onTap: () {
                         // Event call the method of _onListener from BaseStatelessWidget
                          broadcastEvent(
                            ArriveToLocationEvent(
                              //code of event some args
                            ),
                          );
                          broadcastEvent(RefreshMarkersEvent(pageBloc.homeState.homeMarkers));
                        },
                      );
}

I passing isLoading to show CircularProgressIndicator but always I recieved isLoading =show, and I want to take it's value in correct way to show CircularProgressIndicator when click the CTAButton


来源: stackexchange

问:
Select newest Telegram message with selenium
I want to code a bot which automatically selects the newest message send in a Telegram Group. This message should then be used as a link where to bot goes to.
So far I coded this but it looks like the newest message cannot be found with this class name.
I would appreciate any support!

```<code>while True:

    # Find newest message

    message = driver.find_element(by=By.CLASS_NAME,value="text-content with-meta")

    # save message

    message_text = message.text

    # use as link
    link = message_text
    driver.get("https://key-drop.com/en/?code="+link)
    time.sleep(5)
</code>```

I also tried to put all messages in a list but that does not seem to work either.
Edit: This is the html code for telegram message in a group:
Foto of html code

I thought about using the xpath of the element which looks like this:

//*[@id="message1650"]/div[3]/div/div[1]/div/text()

Can I then  just tell the program to go to the newest xpath by adding a 1 to the message id in the xpath. like: //*[@id="message1651"]/div[3]/div/div[1]/div/text()
and if yes how do I do that?

ContentLicense: CC BY-SA 4.0

Body:
I want to code a bot which automatically selects the newest message send in a Telegram Group. This message should then be used as a link where to bot goes to.
So far I coded this but it looks like the newest message cannot be found with this class name.
I would appreciate any support!

while True:

    # Find newest message

    message = driver.find_element(by=By.CLASS_NAME,value="text-content with-meta")

    # save message

    message_text = message.text

    # use as link
    link = message_text
    driver.get("https://key-drop.com/en/?code="+link)
    time.sleep(5)

I also tried to put all messages in a list but that does not seem to work either.
Edit: This is the html code for telegram message in a group:
Foto of html code

I thought about using the xpath of the element which looks like this:

//*[@id="message1650"]/div[3]/div/div[1]/div/text()

Can I then  just tell the program to go to the newest xpath by adding a 1 to the message id in the xpath. like: //*[@id="message1651"]/div[3]/div/div[1]/div/text()
and if yes how do I do that?


问:
Backtesting a volume weighted average price based trading system in TradingView (pinescript v5)
(my first post in stack overflow)

I am trying to compile my first bunch of code in an attempt to create a trading strategy based on volume weighted average price( (VWAP) trading.

So far i have:

//@version=5
strategy('Pine Script Tutorial Example Strategy 1', overlay=true, initial_capital=1000, default_qty_value=100, default_qty_type=strategy.percent_of_equity)

// Input options
averageData = input.source(hlc3, title="Average Data Source")
band1Offset = input.float(0.0799, title="Price Band1 Offset (%)", step=0.0799) / 100
band2Offset = input.float(0.0475, title="Price Band1 Offset (%)", step=0.0475) / 100

// Calculate the volume-weighted average price and its 'noise' bands
vwapData  = ta.vwap(averageData)
upperBand1 = vwapData * (1 + band1Offset)
lowerBand1 = vwapData * (1 - band1Offset)
upperBand2 = vwapData * (1 + band2Offset)
lowerBand2 = vwapData * (1 - band2Offset)

// Plot the average and its band
plot(vwapData, color=color.orange, title="VWAP")
plot(upperBand1, color=color.blue, title="Upper band1")
plot(lowerBand1, color=color.blue, title="Lower band1")
plot(upperBand2, color=color.red, title="Upper band2")
plot(lowerBand2, color=color.red, title="Lower band2")

upperBand1 = vwapData * (1 + band1Offset)
lowerBand1 = vwapData * (1 - band1Offset)
upperBand2 = vwapData * (1 + band2Offset)
lowerBand2 = vwapData * (1 - band2Offset)

// Plot the average and its band
plot(vwapData, color=color.orange, title="VWAP")
plot(upperBand1, color=color.blue, title="Upper band1")
plot(lowerBand1, color=color.blue, title="Lower band1")
plot(upperBand2, color=color.red, title="Upper band2")
plot(lowerBand2, color=color.red, title="Lower band2")

And now i would like to run a strategy test so that long conditions for entry are following:

price above VWAP AND

price has recently touched upperband 2 in last 150 ticks AND

price becomes equal with VWAP

how could I implement it?

thanks in advance!

I googled how to implement longconditions but my variables differ a lot from examples given.


问:
grpc serverReflection implementation in Java client

Need a document or a working sample project reference of how serverreflection can be implemented in a Java client to call the grpc endpoints on server(not through grpc_cli). The current documentation is not enough to understand the flow & implement it. It would be very helpful if any reference can be shared.

Does grpc_ui & grpcurl use server reflection internally?

Can server reflection be used from version v1 instead of v1alpha now?


问:
.htaccess rewrite using session variables as RewriteBase
I'm currently using sub-domains to segment clients to their own websites - this is only for appearance to show the client name in the URL. However, there is no need to use Subdomains. Instead, I'd like to have 1 website and rewrite the url so they each client's name appears like this in the URL like this:
https://test.com/CLIENT_NAME/index.php

When the client first visits https://test.com/CLIENT_NAME/ if the session variable "CLIENT_NAME" !isset, I'd like to route them to test.com/index.php?id=CLIENT_NAME (but keep the URL showing as https://test.com/CLIENT_NAME/) so I can use the $_GET variable from "id" to get their data from the database and set the session variables.

Once logged in and the session variable of CLIENT_NAME is set, I'd just like to rewrite each URL to have /CLIENT_NAME/ after the base domain, but effectly the site will all pages as though it's just the base domain (without /CLIENT_NAME/).

For example once logged in:
the URL will appear as test.com/CLIENT_NAME/page_1 but the server will access the file stored in the root public_html folder that would usually be accessed by visiting test.com/page_1.php.

At the same time, it would be great to remove ".php" from the end of each webpage (like in the above example).

Thanks for your assistance!

I've tried all sorts of other examples found on here, but it seems everyone uses a fixed parameter for the RewriteBase, instead of checking the session variables to see if something is set there and then using that value as the RewriteBase if it is, or redirecting the user to a GET request (with the url masked) to set the session variables.


问:
signature does not match, bingx api in nodejs
Here's my code to generate a signature for bingx api and send a post request.

But i get error: signature does not match

My code:

```<code>const axios = require('axios');
const crypto = require('crypto');

const APIKEY = "My_API_Key";
const SECRETKEY = "My_Secret_key";

const getSign = () => {
    const timestamp = Date.now();
    const originString = `POST/api/v1/user/getBalanceapiKey=${APIKEY}&currency=USDT&timestamp=${timestamp}`;
    const b64Hmac = crypto.createHmac('sha256', SECRETKEY).update(originString).digest('base64');
    const urlB64Hmac = encodeURIComponent(b64Hmac).replace(/%2F/g, "/");
    return urlB64Hmac;
}

const genSignature = () => {

    const signature = getSign();
    const timestamp = Date.now();
    const url = `https://api-swap-rest.bingbon.pro/api/v1/user/getBalance`;

    const body = `apiKey=${APIKEY}&currency=USDT&timestamp=${timestamp}&sign=${signature}`;

    axios.post(url, body, { headers: {'User-Agent': 'Mozilla/5.0'} })
    .then(function (response) {
        console.log(response);
    })
    .catch(function (error) {
        console.log(error);
    });
}

genSignature();
</code>```

Here's the Bingx api documentation: Link

Body:
Here's my code to generate a signature for bingx api and send a post request.

But i get error: signature does not match

My code:

const axios = require('axios');
const crypto = require('crypto');

const APIKEY = "My_API_Key";
const SECRETKEY = "My_Secret_key";

const getSign = () => {
    const timestamp = Date.now();
    const originString = `POST/api/v1/user/getBalanceapiKey=${APIKEY}&currency=USDT&timestamp=${timestamp}`;
    const b64Hmac = crypto.createHmac('sha256', SECRETKEY).update(originString).digest('base64');
    const urlB64Hmac = encodeURIComponent(b64Hmac).replace(/%2F/g, "/");
    return urlB64Hmac;
}

const genSignature = () => {

    const signature = getSign();
    const timestamp = Date.now();
    const url = `https://api-swap-rest.bingbon.pro/api/v1/user/getBalance`;

    const body = `apiKey=${APIKEY}&currency=USDT&timestamp=${timestamp}&sign=${signature}`;

    axios.post(url, body, { headers: {'User-Agent': 'Mozilla/5.0'} })
    .then(function (response) {
        console.log(response);
    })
    .catch(function (error) {
        console.log(error);
    });
}

genSignature();

Here's the Bingx api documentation: Link


问:
Implementation for communication client server in distributed architecture
I want to communicate client and server located in different machines and being connected as the cleint via wireless cellular technology (LTE) and the server connected to internet. The client and the server are exchanging information in both direcctions client-->server and server-->client. The questions raised by this setup is:

Which implementation should fit the best for this architecture? I read about RPC or REST API but not sure this implementation would work

As normally the network operators do not allow the UE (in this case the client) to be accessible, it is the client whhich should start the communication.

Which solution of protocol/implementation would fit the best for this situation?


问:
MariaDB10.10 container keeps always restarting
I am trying to get a misp image running on CentOS 7 by using Docker, I have a problem with the mysql database container because it always keeps on restarting and that's why I can't access it.

I have tried to change the configuration password but anyway it doesn't work. The error I am getting is because the web application misp it's unable to connect to the database. There is another error because misp-mysql keeps failing, when I check the log it outputs: mariadb failed while attemppting to check config command was: mariadb --verbose --help Can't initialize timers

config file (docker-compose.yml)

version: '3.3'

services:
  mysql:
    image: mariadb:10.10
    restart: always
    container_name: misp-mysql
    tmpfs:
      - /tmp
    environment:
      MYSQL_DATABASE: misp
      MYSQL_USER: misp
      MYSQL_PASSWORD: password
      MYSQL_ROOT_PASSWORD: password

  redis:
    image: redis:7.0
    restart: always
    container_name: misp-redis

  misp-modules:
    image: ghcr.io/nukib/misp-modules:latest
    restart: always
    container_name: misp-modules
    cap_drop:
      - NET_RAW
      - SYS_CHROOT
      - MKNOD
      - NET_BIND_SERVICE
      - AUDIT_WRITE
      - SETFCAP

  misp:
    image: ${MISP_IMAGE-ghcr.io/nukib/misp:latest}
    restart: always
    container_name: misp
    depends_on:
      - mysql
      - redis
    tmpfs:
      - /tmp
    cap_drop:
      - NET_RAW
      - SYS_CHROOT
      - MKNOD
      - AUDIT_WRITE
      - SETFCAP
    environment:
      MYSQL_HOST: mysql
      MYSQL_LOGIN: misp
      MYSQL_PASSWORD: password # Please change for production
      MYSQL_DATABASE: misp
      REDIS_HOST: redis
      MISP_BASEURL: http://localhost:8080
      MISP_UUID: 0a674a5a-c4cb-491d-80cf-5adb48b5c1cd # Please change for production
      MISP_ORG: Testing org # Please change for production
      MISP_MODULE_URL: http://misp-modules
      MISP_EMAIL: ahoj@example.com # Please change for production
      SECURITY_SALT: PleaseChangeForProduction # Please change for production
      ZEROMQ_ENABLED: "yes"
    ports:
      - 127.0.0.1:8080:80
      - 127.0.0.1:50000:50000

```


问:
BFFF0071 error code while trying to discover an instrument
I'm getting BFFF0071 error while using visa32.vb as a module in my vb.net project.
this error is generated by the following code :

```<code>   `Debug.WriteLine("Hello")
    Dim Session As Long = VI_NULL
    viOpenDefaultRM(Session)
    'Dim searching As String = "PXI?*::INSTR"
    Dim searching As String = "?*"
    Dim findPort As Long = VI_NULL
    Dim count As Long = 0
    Dim Thelist As System.Text.StringBuilder
    Dim Status As Integer = viFindRsrc(Session, searching, findPort, count, Thelist)
    Console.WriteLine(Thelist)
    Console.WriteLine(Status)
    If (Status = VI_SUCCESS And count > 0) Then
        Do
            Console.WriteLine(Thelist)
            Status = viFindNext(findPort, Thelist)
        Loop While (Status = VI_SUCCESS)
        viClose(findPort)
    ElseIf (count = 0) Then
        Console.WriteLine("No PXI instrument found")
        viClose(findPort)
    End If`
</code>```

I tried to create this code in vb.net from a working code of C++, the C++ code is actually working however the code above is generating : A specified user buffer is not valid or cannot be accessed for the required size. What does that mean, and how to overcome this?

I tried the following code to discover whatever instrument, but I can't find the right address:

```<code>   `Dim devices As IEnumerable(Of String)
    Dim ADRESSES As String
    Try

        ' Finding all devices And interfaces Is straightforward
        Console.WriteLine("Find all devices and interfaces:")
        devices = GlobalResourceManager.Find()

        For Each device As String In devices

            Console.WriteLine(vbTab + "Address: {0}, Alias: {1}", device, GlobalResourceManager.Parse(device).AliasIfExists)
            'Console.WriteLine(device)
            'ADRESSES = vbTab + "Address: {0}, Alias: {1}"
            'INSTRUMENTS.Items.Add(ADDRESSES)
        Next

    Catch ex As VisaException

        Console.WriteLine("Didn't find any devices!")

    End Try

    Console.WriteLine()

    ' You can specify other device types using different search strings. Here are some common examples

    ' All instruments (no INTFC, BACKPLANE Or MEMACC)
    Find("PXI?*INSTR")
 Sub Find(searchString As String)

    Dim devices As IEnumerable(Of String)
    Try

        Console.WriteLine("Find with search string """ + searchString + """")
        devices = GlobalResourceManager.Find(searchString)

        For Each device As String In devices
            Console.WriteLine(vbTab + "Address: {0}, Alias: {1}", device, GlobalResourceManager.Parse(device).AliasIfExists)
        Next

    Catch ex As VisaException
        Console.WriteLine("... didn't find anything!")
    End Try

    Console.WriteLine()

End Sub`
</code>```

Body:
I'm getting BFFF0071 error while using visa32.vb as a module in my vb.net project.
this error is generated by the following code :

   `Debug.WriteLine("Hello")
    Dim Session As Long = VI_NULL
    viOpenDefaultRM(Session)
    'Dim searching As String = "PXI?*::INSTR"
    Dim searching As String = "?*"
    Dim findPort As Long = VI_NULL
    Dim count As Long = 0
    Dim Thelist As System.Text.StringBuilder
    Dim Status As Integer = viFindRsrc(Session, searching, findPort, count, Thelist)
    Console.WriteLine(Thelist)
    Console.WriteLine(Status)
    If (Status = VI_SUCCESS And count > 0) Then
        Do
            Console.WriteLine(Thelist)
            Status = viFindNext(findPort, Thelist)
        Loop While (Status = VI_SUCCESS)
        viClose(findPort)
    ElseIf (count = 0) Then
        Console.WriteLine("No PXI instrument found")
        viClose(findPort)
    End If`

I tried to create this code in vb.net from a working code of C++, the C++ code is actually working however the code above is generating : A specified user buffer is not valid or cannot be accessed for the required size. What does that mean, and how to overcome this?

I tried the following code to discover whatever instrument, but I can't find the right address:

   `Dim devices As IEnumerable(Of String)
    Dim ADRESSES As String
    Try

        ' Finding all devices And interfaces Is straightforward
        Console.WriteLine("Find all devices and interfaces:")
        devices = GlobalResourceManager.Find()

        For Each device As String In devices

            Console.WriteLine(vbTab + "Address: {0}, Alias: {1}", device, GlobalResourceManager.Parse(device).AliasIfExists)
            'Console.WriteLine(device)
            'ADRESSES = vbTab + "Address: {0}, Alias: {1}"
            'INSTRUMENTS.Items.Add(ADDRESSES)
        Next

    Catch ex As VisaException

        Console.WriteLine("Didn't find any devices!")

    End Try

    Console.WriteLine()

    ' You can specify other device types using different search strings. Here are some common examples

    ' All instruments (no INTFC, BACKPLANE Or MEMACC)
    Find("PXI?*INSTR")
 Sub Find(searchString As String)

    Dim devices As IEnumerable(Of String)
    Try

        Console.WriteLine("Find with search string """ + searchString + """")
        devices = GlobalResourceManager.Find(searchString)

        For Each device As String In devices
            Console.WriteLine(vbTab + "Address: {0}, Alias: {1}", device, GlobalResourceManager.Parse(device).AliasIfExists)
        Next

    Catch ex As VisaException
        Console.WriteLine("... didn't find anything!")
    End Try

    Console.WriteLine()

End Sub`


问:
Issue using the 'comtypes' package in Python with a COM component (created in .NET 6) that returns an array of COM classes
I have created a COM component in .NET 6. The COM component contains the COM class 'ComObject' which in turn contains a COM class 'Results'. Finally, the 'Results' class contains an array of coordinates. These coordinates are a COM class too. Now when I try to access the array of coordinates in Python with the 'comtypes' package I get the follwoing error/debug output:

```<code>Stack trace:
 >  File "C:\Users\MicRum00\source\repos\PythonCoordsComClient\PythonCoordsComClient\PythonCoordsComClient.py", line 13, in Init
 >    coords = ComObject.Coordinates()
 >  File "C:\Users\MicRum00\source\repos\PythonCoordsComClient\PythonCoordsComClient\PythonCoordsComClient.py", line 20, in <module> (Current frame)
 >    Init()
Loaded 'comtypes.automation'
Loaded 'comtypes.client.dynamic'
Loaded '__main__'
Loaded 'runpy'
</code>```

I am not very proficient with Python and therefore this error is not very helpful to me.

The following repositories can be used to replicate the issue:

The exact structure of the COM project can be found in the following repository Spikxzy/ComObjectPython. To build the project in Visual Studio Code the project file may require some adaptation. The MIDL compiler is used to compile a 'comhost.dll' that can be registered with 'regsvr32' through the Windows console.

This path 'C:$(VSLocation)\Microsoft Visual Studio$(VSVersion)\VC\Tools\MSVC$(CLVersion)\bin\Hostx64\x64' inside the project file has to point to a 'cl.exe' compiler on your PC for the build to work (the VSVersion or the CLVersion might be different). It is also possible that the 'KitsVersion' in the project file is different (it can be found under the following path: 'C:\Program Files (x86)\Windows Kits\10\include$(KitsVersion)' on your PC).

The COM client in python that generates this issue can be found in this repository Spikxzy/PythonComClient. The Python client was created in Visual Studio and it can just be run to replicate issue mentioned above.

Body:
I have created a COM component in .NET 6. The COM component contains the COM class 'ComObject' which in turn contains a COM class 'Results'. Finally, the 'Results' class contains an array of coordinates. These coordinates are a COM class too. Now when I try to access the array of coordinates in Python with the 'comtypes' package I get the follwoing error/debug output:

Stack trace:
 >  File "C:\Users\MicRum00\source\repos\PythonCoordsComClient\PythonCoordsComClient\PythonCoordsComClient.py", line 13, in Init
 >    coords = ComObject.Coordinates()
 >  File "C:\Users\MicRum00\source\repos\PythonCoordsComClient\PythonCoordsComClient\PythonCoordsComClient.py", line 20, in <module> (Current frame)
 >    Init()
Loaded 'comtypes.automation'
Loaded 'comtypes.client.dynamic'
Loaded '__main__'
Loaded 'runpy'

I am not very proficient with Python and therefore this error is not very helpful to me.

The following repositories can be used to replicate the issue:

The exact structure of the COM project can be found in the following repository Spikxzy/ComObjectPython. To build the project in Visual Studio Code the project file may require some adaptation. The MIDL compiler is used to compile a 'comhost.dll' that can be registered with 'regsvr32' through the Windows console.

This path 'C:$(VSLocation)\Microsoft Visual Studio$(VSVersion)\VC\Tools\MSVC$(CLVersion)\bin\Hostx64\x64' inside the project file has to point to a 'cl.exe' compiler on your PC for the build to work (the VSVersion or the CLVersion might be different). It is also possible that the 'KitsVersion' in the project file is different (it can be found under the following path: 'C:\Program Files (x86)\Windows Kits\10\include$(KitsVersion)' on your PC).

The COM client in python that generates this issue can be found in this repository Spikxzy/PythonComClient. The Python client was created in Visual Studio and it can just be run to replicate issue mentioned above.


问:
Handle dependencies between git feature branches
I am part of a software developer team, where we are using a simple git branching strategy consisting of one long living main branch and arbitrarily many short living feature branches. To keep the history of the main branch as linear as possible, we finish feature branches by squashing them into single commits on top of the main branch and deleting them afterwards. This works nicely as long as we do not have dependencies between different feature branches.

In some rare situations however, we cannot avoid ending up like this

```<code>    o---o---o---o---o  main
         \   \       \
          \   o---o---o  feature1
           \       \   \
            o---o---o---o  feature2
</code>```

where some branch feature2 depends on another branch feature1. Ideally, we would like to finish feature1 without losing connection to feature2. That is, we would like to squash-commit feature1 on top of main but also rewrite the history of feature2 to still being dependent of that squashed commit. After finishing feature1 the history should look like that:

```<code>    o---o---o--o--o--o'  main
         \            \
          o---o---o'---o'  feature2
</code>```

Is this achievable without having to deal with (avoidable) merge conflicts?

Added later: I just realized that something very similar is possible in the following way:

squash-commit feature1 onto main

merge main into feature1

merge feature1 into feature2

delete feature1

This has the advantage of not rewriting the history of feature2 while still keeping the history of main linear.

Do you think this could be the ideal solution?

Body:
I am part of a software developer team, where we are using a simple git branching strategy consisting of one long living main branch and arbitrarily many short living feature branches. To keep the history of the main branch as linear as possible, we finish feature branches by squashing them into single commits on top of the main branch and deleting them afterwards. This works nicely as long as we do not have dependencies between different feature branches.

In some rare situations however, we cannot avoid ending up like this

    o---o---o---o---o  main
         \   \       \
          \   o---o---o  feature1
           \       \   \
            o---o---o---o  feature2

where some branch feature2 depends on another branch feature1. Ideally, we would like to finish feature1 without losing connection to feature2. That is, we would like to squash-commit feature1 on top of main but also rewrite the history of feature2 to still being dependent of that squashed commit. After finishing feature1 the history should look like that:

    o---o---o--o--o--o'  main
         \            \
          o---o---o'---o'  feature2

Is this achievable without having to deal with (avoidable) merge conflicts?

Added later: I just realized that something very similar is possible in the following way:

squash-commit feature1 onto main

merge main into feature1

merge feature1 into feature2

delete feature1

This has the advantage of not rewriting the history of feature2 while still keeping the history of main linear.

Do you think this could be the ideal solution?


问:
Jenkins running in docker is restarting when gitlab-ce docker instance is running
I'm running Jenkins and Gitlab CE in my local docker containers. Jenkins is running on 50000:50000 and 8080:8080 port and Gitlab CE on 80:80, 443:443 and 2222:22 ports. I've added self-signed certificate for Gitlab.

The issue I'm facing is the Jenkins container is getting restarted whenever I'm accessing it through web, while the Gitlab container is running. If I stop the Gitlab, Jenkins will work fine.

I'm using Jenkins 2.375.1, Gitlab CE 15.7.3 Image, Docker Desktop 4.14.0, macOS Ventura on M1


问:
Custom labels/constants in Alertmanager config
I have an Alertmanager config file which defines many alerts. All of these alerts use the same time range in their Prometheus expressions and messaging. Is there way I can define a constant once in the file, which is then used throughout. That way, if I ever change the value of this constant, it's only required to be changed in one place?

Here's an illustration of what I am trying to achieve:

apiVersion: monitoring.coreos.com/v1
kind: PrometheusRule
metadata:
  name: kube-prometheus-stack-services
  namespace: monitoring
  labels:
    app: kube-prometheus-stack
    release: kube-prometheus-stack
customer_variables:
  time_range: 5m # CUSTOM VARIABLE DEFINED HERE
spec:
  groups:
  - name: Service1
      rules:
        - alert: Service1Alert1
          annotations:
            summary: "Some summary of alert1"
            message: "Some error rate has increased to {{ $value }}% in the last {{ $customer_variables.time_range }}." # CUSTOM VARIABLE USED HERE
          expr: # some expression using my_metric_1{label="..."}[{{ $customer_variables.time_range }}] # CUSTOM VARIABLE USED HERE
          for: {{ $customer_variables.time_range }} # CUSTOM VARIABLE USED HERE
          labels:
            severity: critical
        - alert: Service1Alert2
          annotations:
            summary: "Some summary of alert2"
            message: "Some other error rate has increased to {{ $value }}% in the last {{ $customer_variables.time_range }}." # CUSTOM VARIABLE USED HERE
          expr: # some expression using my_metric_1{label="..."}[{{ $customer_variables.time_range }}] # CUSTOM VARIABLE USED HERE
          for: {{ $customer_variables.time_range }} # CUSTOM VARIABLE USED HERE
          labels:
            severity: critical
```


问:
Structured Exception Handling and MinGW
I want to catch a system exception "ACCESS_VIOLATION" from my native code, in MS VS I do this:

#define PROTECTED_START() __try { \
#define PROTECTED_END(ONERR) } __except(EXCEPTION_EXECUTE_HANDLER) {ONERR;}
```
<p>What is the equivalent in mingw?</p>
<p>I tried this and is not working:</p>
<pre class="lang-c prettyprint-override"><code>#define PROTECTED_START() __try1(EXCEPTION_DISPOSITION) { \
#define PROTECTED_END(ONERR) } __except1 { ONERR; }
</code>```

Title: Structured Exception Handling and MinGW

Body:
I want to catch a system exception "ACCESS_VIOLATION" from my native code, in MS VS I do this:

#define PROTECTED_START() __try { \
#define PROTECTED_END(ONERR) } __except(EXCEPTION_EXECUTE_HANDLER) {ONERR;}

What is the equivalent in mingw?

I tried this and is not working:

#define PROTECTED_START() __try1(EXCEPTION_DISPOSITION) { \
#define PROTECTED_END(ONERR) } __except1 { ONERR; }


问:
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xbe in position 72: invalid start byte
```<code>def make_example(img_str, source_id, filename):
    # Create a dictionary with features that may be relevant.
    feature = {'image/source_id': _int64_feature(source_id), # label
               'image/filename': _bytes_feature(filename), # label+image(.png)
               'image/encoded': _bytes_feature(img_str)} # image

    return tf.train.Example(features=tf.train.Features(feature=feature))

def main(dataset_path, output_path):
    samples = []

    i = 1
    for id_name in tqdm(os.listdir(dataset_path)):
        img_paths = glob(os.path.join(dataset_path, id_name, '*.png'))
        print("img_path:",img_paths)
        for img_path in img_paths:
            filename = os.path.join(str(i), os.path.basename(img_path))
            samples.append((img_path, str(i) , filename))
        i = i+1

    # print("Writing tfrecord files...")
    with tf.io.TFRecordWriter(output_path) as writer:
        for img_path, id_name, filename in tqdm(samples):
            tf_example = make_example(img_str=open(img_path, 'rb').read(),
                                      source_id=int(id_name),
                                      filename=str.encode(filename))
            writer.write(tf_example.SerializeToString())

if __name__ == "__main__":
    dataset_path = "./image_data/indoor_train/train/All_rgb(10)"
    output_path = "./image_data/indoor_train/tfrecord/"
    main(dataset_path, output_path)
</code>```

Traceback (most recent call last): File "tfrecord2.py", line 59, in
 main(dataset_path, output_path) File "tfrecord2.py", line 48,
in main with tf.io.TFRecordWriter(output_path) as writer: File
"C:\Users\82105\anaconda3\envs\tensorflow_v2.2\lib\site-packages\tensorflow\python\lib\io\tf_record.py",
line 298, in init super(TFRecordWriter, self).init(
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xbe in position
72: invalid start byte

The dataset is using a png file, and a unicodecode error occurred while executing the code to create the tfrecord file.
I knew it as an error that usually appears when using a csv file, but I don't understand why the utf-8 codec can't decode even though I used an image file.
I would be grateful if anyone who knows can solve it.

Adding the encoding = 'cp949' parameter to the open function did not solve the problem.

Body:
def make_example(img_str, source_id, filename):
    # Create a dictionary with features that may be relevant.
    feature = {'image/source_id': _int64_feature(source_id), # label
               'image/filename': _bytes_feature(filename), # label+image(.png)
               'image/encoded': _bytes_feature(img_str)} # image

    return tf.train.Example(features=tf.train.Features(feature=feature))

def main(dataset_path, output_path):
    samples = []

    i = 1
    for id_name in tqdm(os.listdir(dataset_path)):
        img_paths = glob(os.path.join(dataset_path, id_name, '*.png'))
        print("img_path:",img_paths)
        for img_path in img_paths:
            filename = os.path.join(str(i), os.path.basename(img_path))
            samples.append((img_path, str(i) , filename))
        i = i+1

    # print("Writing tfrecord files...")
    with tf.io.TFRecordWriter(output_path) as writer:
        for img_path, id_name, filename in tqdm(samples):
            tf_example = make_example(img_str=open(img_path, 'rb').read(),
                                      source_id=int(id_name),
                                      filename=str.encode(filename))
            writer.write(tf_example.SerializeToString())

if __name__ == "__main__":
    dataset_path = "./image_data/indoor_train/train/All_rgb(10)"
    output_path = "./image_data/indoor_train/tfrecord/"
    main(dataset_path, output_path)

Traceback (most recent call last): File "tfrecord2.py", line 59, in
 main(dataset_path, output_path) File "tfrecord2.py", line 48,
in main with tf.io.TFRecordWriter(output_path) as writer: File
"C:\Users\82105\anaconda3\envs\tensorflow_v2.2\lib\site-packages\tensorflow\python\lib\io\tf_record.py",
line 298, in init super(TFRecordWriter, self).init(
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xbe in position
72: invalid start byte

The dataset is using a png file, and a unicodecode error occurred while executing the code to create the tfrecord file.
I knew it as an error that usually appears when using a csv file, but I don't understand why the utf-8 codec can't decode even though I used an image file.
I would be grateful if anyone who knows can solve it.

Adding the encoding = 'cp949' parameter to the open function did not solve the problem.


问:
Liquid error: Error - Illegal template path
I am facing this issue in c# code. While using liquid templates include formula.

string liquidTemplateContent = System.IO.File.ReadAllText("wwwroot/template/example.liquid");
LocalFileSystem fileSys = new DotLiquid.FileSystems.LocalFileSystem("wwwroot\\template");
Template.FileSystem = fileSys;
Template template = Template.Parse(liquidTemplateContent);
```
<p>In following liquid file for <code>{% include  'function' -%}</code> this part, I'm facing this issue. Whenever the path coming under the error is valid path
And that _function.liquid file is also present over there.</p>
<blockquote>
<p>error with path: <strong>Liquid error: Error - Illegal template path 'D:\Include Trial1\DotLiquidTest\wwwroot\template\_function.liquid</strong>'</p>
</blockquote>
```

  Email: {{ employee.email }}

  Phone: {{ employee.phone }}

Addresses:

  {% include  'function' -%}

```

I am not sure what is missing here. I am using dotliquid NuGet package for the same.

Body:
I am facing this issue in c# code. While using liquid templates include formula.

string liquidTemplateContent = System.IO.File.ReadAllText("wwwroot/template/example.liquid");
LocalFileSystem fileSys = new DotLiquid.FileSystems.LocalFileSystem("wwwroot\\template");
Template.FileSystem = fileSys;
Template template = Template.Parse(liquidTemplateContent);

In following liquid file for {% include  'function' -%} this part, I'm facing this issue. Whenever the path coming under the error is valid path
And that _function.liquid file is also present over there.

error with path: Liquid error: Error - Illegal template path 'D:\Include Trial1\DotLiquidTest\wwwroot\template\_function.liquid'

  Email: {{ employee.email }}

  Phone: {{ employee.phone }}

Addresses:

  {% include  'function' -%}

I am not sure what is missing here. I am using dotliquid NuGet package for the same.


问:
find the cpu core in which virtual machine is running
I have 6 virtual machine when i am running kmeans workload.
And i extract the trace of the storage's characteristics (CPU ID, Device number, PID, Number of sector) by blktrace while i was running kmeans workload.

I want to know each VM request's characteristics by the trace of blktrace
So, i think that i should match (1VM - 1CPU) or know which CPU is allocated to VM.

Openstack documentation said that use vcpu-pinning or numa but i think it's such a complex thing.

Can I specify only certain cpu that are not shared by one VM?

Or is there a way to check the VM's request with cpuid or pid?

I want to know each VM request's characteristics by the trace of blktrace
So, i think that i should match (1VM - 1CPU) or know which CPU is allocated to VM.


问:
Is it possible to have a Spark DataFrame partitioned by multiple columns, and at the same time partitioned by all the individual columns?
To get more efficient joins in pyspark, I would like to repartition my dataframes on multiple columns at the same time.

This is not what the repartition function already does. For example, if I am partitioning on columns 'c1' and 'c2', the reparition function only ensures that all rows with the pairs of values (c1, c2) fall in the same partition. Instead, I would like to have a partitioning that ensures that that all rows with the same value of c1 fall on the same parition, and the same for c2.

With this, I would like to optimize my pipeline when doing a join on c1 and then another join on c2, without having to reparition (implicitly or explicitely) 2 times.

Is it possible to achieve this?


问:
SQL count without group by to return zero when no matches
I am using SQL Server. This is part of a stored procedure.

If I have a query like this:

```<code>SELECT COUNT(a) AS countA, b
FROM [dbo].[tbl] AS TBL
WHERE TBL.site='100'
  AND TBL.status='status'
  AND TBL.b IN (SELECT b FROM @tbTemp)
GROUP BY TBL.b
</code>```

@tbTemp contains a list of ids 1,2,3,4 etc.

I need to return column b with my count, so am forced to use a group by.

This now returns no records when the where condition fails.

How can I return both count(a) and b, and if the WHERE condition fails return a 0?

Thank you

Body:
I am using SQL Server. This is part of a stored procedure.

If I have a query like this:

SELECT COUNT(a) AS countA, b
FROM [dbo].[tbl] AS TBL
WHERE TBL.site='100'
  AND TBL.status='status'
  AND TBL.b IN (SELECT b FROM @tbTemp)
GROUP BY TBL.b

@tbTemp contains a list of ids 1,2,3,4 etc.

I need to return column b with my count, so am forced to use a group by.

This now returns no records when the where condition fails.

How can I return both count(a) and b, and if the WHERE condition fails return a 0?

Thank you


问:
Make a loop functions
I was wondering how I could create a loop to calculate the predicted values and then calculate MSE for various models and then sort the models according to the calculate MSE. I need to see which model has the least MSE. Thanks for the help in advance

```<code> y_pred1 <-predict(m1,newdata=test,type="response")
    MSE11  <- test %>%  summarise(MSE = mean( (y_pred1-y)^2))

    y_pred2 <-predict(m2,newdata=test,type="response")
    MSE2  <- test %>%  summarise(MSE = mean( (y_pred2-y)^2))

    y_pred3<-predict(m3,newdata=test,type="response")
    MSE3  <- test %>%  summarise(MSE = mean( (y_pred3-y)^2))
</code>```

Title: Make a loop functions

Body:
I was wondering how I could create a loop to calculate the predicted values and then calculate MSE for various models and then sort the models according to the calculate MSE. I need to see which model has the least MSE. Thanks for the help in advance

 y_pred1 <-predict(m1,newdata=test,type="response")
    MSE11  <- test %>%  summarise(MSE = mean( (y_pred1-y)^2))

    y_pred2 <-predict(m2,newdata=test,type="response")
    MSE2  <- test %>%  summarise(MSE = mean( (y_pred2-y)^2))

    y_pred3<-predict(m3,newdata=test,type="response")
    MSE3  <- test %>%  summarise(MSE = mean( (y_pred3-y)^2))


问:
AttributeError: module 'pyminizip' has no attribute 'compress' in aws lambda
pyminizip library only has pyminizip-0.2.6.dist-info and pyminizip.cpython-310-x86_64-linux-gnu.so file. I see no python files in there. First I failed to use it thought it was added as lambda layers. So I was able to get rid of no module found error when I uploaded the lambda_function.py and the library file together as a zip I was able to get rid of the module not found error. But now new problem emerged.

This is probably the most important method it has. Now I'm getting the error of compress attribute is not found. Which is not correct. I have used this library in python 10 in my laptop it works. My python version on aws is 9. I don't know if that is the reason or not.

Here is the documentation below

#Documentation
#     pyminizip.compress("/srcfile/path.txt", "file_path_prefix", "/distfile/path.zip", "password", int(compress_level))
# ```</p>
```#     Args:
#     1. src file path (string)
#     2. src file prefix path (string) or None (path to prepend to file)
#     3. dst file path (string)
#     4. password (string) or None (to create no-password zip)
#     5. compress_level(int) between 1 to 9, 1 (more fast) <---> 9 (more compress) or 0 (default)
```

Please helm me out on this. I don't know how to solve it.

Body:
pyminizip library only has pyminizip-0.2.6.dist-info and pyminizip.cpython-310-x86_64-linux-gnu.so file. I see no python files in there. First I failed to use it thought it was added as lambda layers. So I was able to get rid of no module found error when I uploaded the lambda_function.py and the library file together as a zip I was able to get rid of the module not found error. But now new problem emerged.

This is probably the most important method it has. Now I'm getting the error of compress attribute is not found. Which is not correct. I have used this library in python 10 in my laptop it works. My python version on aws is 9. I don't know if that is the reason or not.

Here is the documentation below

#Documentation
#     pyminizip.compress("/srcfile/path.txt", "file_path_prefix", "/distfile/path.zip", "password", int(compress_level))
# ```

#     Args:
#     1. src file path (string)
#     2. src file prefix path (string) or None (path to prepend to file)
#     3. dst file path (string)
#     4. password (string) or None (to create no-password zip)
#     5. compress_level(int) between 1 to 9, 1 (more fast) <---> 9 (more compress) or 0 (default)

Please helm me out on this. I don't know how to solve it.


问:
The flask server is not showing the OpenCV webcam frame to HTML page for Real Time Number Plate detection
The code is for Real time number Plate Recognition using YOLOv5 and easyocr. I am trying to build the flask server and to embed the live streaming webcam to the HTML Page.

The model is trained with YOLOv5 which is used for number plate localization.
The flask server is not showing the OpenCV webcam frame to HTML page for Real Time Number Plate detection.

```<code>import torch
import cv2
import time
import numpy as np
import easyocr
from flask import Flask, render_template, Response
app = Flask(name, template_folder='yolov5/templates')

def generate_frames():
    # DEFINING GLOBAL VARIABLE
    EASY_OCR = easyocr.Reader(['en'])  # initiating easyocr
    OCR_TH = 0.2

    print(f"[INFO] Loading model... ")
    # loading the custom trained model
    model = torch.hub.load('.', 'custom', source='local', path='runs/train/Model5/weights/best.pt',
                           force_reload=True)  ### The repo is stored locally

    classes = model.names  # class names in string format
    # -------------------------------------- function to run detection ---------------------------------------------------------
    def detectx(frame, model):
        frame = [frame]
        print(f"[INFO] Detecting. . . ")
        results = model(frame)
        # results.show()
        # print( results.xyxyn[0])
        # print(results.xyxyn[0][:, -1])
        # print(results.xyxyn[0][:, :-1])

        labels, cordinates = results.xyxyn[0][:, -1], results.xyxyn[0][:, :-1]

        return labels, cordinates

    # ------------------------------------ to plot the BBox and results --------------------------------------------------------
    def plot_boxes(results, frame, classes):
        """
        --> This function takes results, frame and classes
        --> results: contains labels and coordinates predicted by model on the given frame
        --> classes: contains the strting labels

        """
        labels, cord = results
        n = len(labels)
        x_shape, y_shape = frame.shape[1], frame.shape[0]

        print(f"[INFO] Total {n} detections. . . ")
        print(f"[INFO] Looping through all detections. . . ")

        # looping through the detections
        for i in range(n):
            row = cord[i]
            if row[4] >= 0.55:  ### threshold value for detection. We are discarding everything below this value
                print(f"[INFO] Extracting BBox coordinates. . . ")
                x1, y1, x2, y2 = int(row[0] * x_shape), int(row[1] * y_shape), int(row[2] * x_shape), int(
                    row[3] * y_shape)  ## BBOx coordniates
                text_d = classes[int(labels[i])]
                # cv2.imwrite("./output/dp.jpg",frame[int(y1):int(y2), int(x1):int(x2)])

                coords = [x1, y1, x2, y2]

                plate_num = recognize_plate_easyocr(img=frame, coords=coords, reader=EASY_OCR, region_threshold=OCR_TH)
                print("Detected number is: " + plate_num + "\n")

                # if text_d == 'mask':
                cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 0), 2)  # BBox
                cv2.rectangle(frame, (x1, y1 - 20), (x2, y1), (0, 255, 0), -1)  # for text label background
                cv2.putText(frame, f"{plate_num}", (x1, y1), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2)

                # cv2.imwrite("./output/np.jpg",frame[int(y1)-25:int(y2)+25, int(x1)-25:int(x2)+25])

        return frame

    # ---------------------------- function to recognize license plate --------------------------------------

    # function to recognize license plate numbers using Tesseract OCR
    def recognize_plate_easyocr(img, coords, reader, region_threshold):
        # separate coordinates from box
        xmin, ymin, xmax, ymax = coords
        # get the subimage that makes up the bounded region and take an additional 5 pixels on each side
        # nplate = img[int(ymin)-5:int(ymax)+5, int(xmin)-5:int(xmax)+5]
        nplate = img[int(ymin):int(ymax), int(xmin):int(xmax)]  ### cropping the number plate from the whole image

        ocr_result = reader.readtext(nplate)

        text = filter_text(region=nplate, ocr_result=ocr_result, region_threshold=region_threshold)

        if len(text) == 1:
            text = text[0].upper()
        return text

    # to filter out wrong detections

    def filter_text(region, ocr_result, region_threshold):
        rectangle_size = region.shape[0] * region.shape[1]

        plate = []
        print(ocr_result)
        for result in ocr_result:
            length = np.sum(np.subtract(result[0][1], result[0][0]))
            height = np.sum(np.subtract(result[0][2], result[0][1]))

            if length * height / rectangle_size > region_threshold:
                plate.append(result[1])
        return plate

    # --------------- for detection on video --------------------
    print(f"[INFO] Working with video: {0}")

    # reading the video
    cap = cv2.VideoCapture(0)
    vid_out = "webcam_facemask_result.mp4"
    if vid_out != None:  # creating the video writer if video output path is given
        # by default VideoCapture returns float instead of int
        width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
        height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
        fps = int(cap.get(cv2.CAP_PROP_FPS))
        codec = cv2.VideoWriter_fourcc(*'mp4v')  # (*'XVID')
        out = cv2.VideoWriter(vid_out, codec, fps, (width, height))

    # assert cap.isOpened()
    frame_no = 1

    cv2.namedWindow("vid_out", cv2.WINDOW_NORMAL)
    while True:
        # start_time = time.time()
        ret, frame = cap.read()
        if ret and frame_no % 1 == 0:
            print(f"[INFO] Working with frame {frame_no} ")

            frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
            results = detectx(frame, model=model)
            frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)

            frame = plot_boxes(results, frame, classes=classes)

            cv2.imshow("vid_out", frame)
            if vid_out:
                print(f"[INFO] Saving output video. . . ")
                out.write(frame)

            if cv2.waitKey(5) & 0xFF == 27:
                break
            frame_no += 1

        ret, buffer = cv2.imencode('.jpg', frame)
        frame = buffer.tobytes()

        yield (b'--frame\r\n'
               b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')
    # print(f"[INFO] Cleaning up. . . ")
    # # releaseing the writer
    # out.release()
    #
    # # closing all windows
    # cv2.destroyAllWindows()

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/video')
def video():
    return Response(generate_frames(), mimetype='multipart/x-mixed-replace; boundary=frame')

if name == "main": app.run(debug=True)
</code>```

Body:
The code is for Real time number Plate Recognition using YOLOv5 and easyocr. I am trying to build the flask server and to embed the live streaming webcam to the HTML Page.

The model is trained with YOLOv5 which is used for number plate localization.
The flask server is not showing the OpenCV webcam frame to HTML page for Real Time Number Plate detection.

import torch
import cv2
import time
import numpy as np
import easyocr
from flask import Flask, render_template, Response
app = Flask(name, template_folder='yolov5/templates')

def generate_frames():
    # DEFINING GLOBAL VARIABLE
    EASY_OCR = easyocr.Reader(['en'])  # initiating easyocr
    OCR_TH = 0.2

    print(f"[INFO] Loading model... ")
    # loading the custom trained model
    model = torch.hub.load('.', 'custom', source='local', path='runs/train/Model5/weights/best.pt',
                           force_reload=True)  ### The repo is stored locally

    classes = model.names  # class names in string format
    # -------------------------------------- function to run detection ---------------------------------------------------------
    def detectx(frame, model):
        frame = [frame]
        print(f"[INFO] Detecting. . . ")
        results = model(frame)
        # results.show()
        # print( results.xyxyn[0])
        # print(results.xyxyn[0][:, -1])
        # print(results.xyxyn[0][:, :-1])

        labels, cordinates = results.xyxyn[0][:, -1], results.xyxyn[0][:, :-1]

        return labels, cordinates

    # ------------------------------------ to plot the BBox and results --------------------------------------------------------
    def plot_boxes(results, frame, classes):
        """
        --> This function takes results, frame and classes
        --> results: contains labels and coordinates predicted by model on the given frame
        --> classes: contains the strting labels

        """
        labels, cord = results
        n = len(labels)
        x_shape, y_shape = frame.shape[1], frame.shape[0]

        print(f"[INFO] Total {n} detections. . . ")
        print(f"[INFO] Looping through all detections. . . ")

        # looping through the detections
        for i in range(n):
            row = cord[i]
            if row[4] >= 0.55:  ### threshold value for detection. We are discarding everything below this value
                print(f"[INFO] Extracting BBox coordinates. . . ")
                x1, y1, x2, y2 = int(row[0] * x_shape), int(row[1] * y_shape), int(row[2] * x_shape), int(
                    row[3] * y_shape)  ## BBOx coordniates
                text_d = classes[int(labels[i])]
                # cv2.imwrite("./output/dp.jpg",frame[int(y1):int(y2), int(x1):int(x2)])

                coords = [x1, y1, x2, y2]

                plate_num = recognize_plate_easyocr(img=frame, coords=coords, reader=EASY_OCR, region_threshold=OCR_TH)
                print("Detected number is: " + plate_num + "\n")

                # if text_d == 'mask':
                cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 0), 2)  # BBox
                cv2.rectangle(frame, (x1, y1 - 20), (x2, y1), (0, 255, 0), -1)  # for text label background
                cv2.putText(frame, f"{plate_num}", (x1, y1), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2)

                # cv2.imwrite("./output/np.jpg",frame[int(y1)-25:int(y2)+25, int(x1)-25:int(x2)+25])

        return frame

    # ---------------------------- function to recognize license plate --------------------------------------

    # function to recognize license plate numbers using Tesseract OCR
    def recognize_plate_easyocr(img, coords, reader, region_threshold):
        # separate coordinates from box
        xmin, ymin, xmax, ymax = coords
        # get the subimage that makes up the bounded region and take an additional 5 pixels on each side
        # nplate = img[int(ymin)-5:int(ymax)+5, int(xmin)-5:int(xmax)+5]
        nplate = img[int(ymin):int(ymax), int(xmin):int(xmax)]  ### cropping the number plate from the whole image

        ocr_result = reader.readtext(nplate)

        text = filter_text(region=nplate, ocr_result=ocr_result, region_threshold=region_threshold)

        if len(text) == 1:
            text = text[0].upper()
        return text

    # to filter out wrong detections

    def filter_text(region, ocr_result, region_threshold):
        rectangle_size = region.shape[0] * region.shape[1]

        plate = []
        print(ocr_result)
        for result in ocr_result:
            length = np.sum(np.subtract(result[0][1], result[0][0]))
            height = np.sum(np.subtract(result[0][2], result[0][1]))

            if length * height / rectangle_size > region_threshold:
                plate.append(result[1])
        return plate

    # --------------- for detection on video --------------------
    print(f"[INFO] Working with video: {0}")

    # reading the video
    cap = cv2.VideoCapture(0)
    vid_out = "webcam_facemask_result.mp4"
    if vid_out != None:  # creating the video writer if video output path is given
        # by default VideoCapture returns float instead of int
        width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
        height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
        fps = int(cap.get(cv2.CAP_PROP_FPS))
        codec = cv2.VideoWriter_fourcc(*'mp4v')  # (*'XVID')
        out = cv2.VideoWriter(vid_out, codec, fps, (width, height))

    # assert cap.isOpened()
    frame_no = 1

    cv2.namedWindow("vid_out", cv2.WINDOW_NORMAL)
    while True:
        # start_time = time.time()
        ret, frame = cap.read()
        if ret and frame_no % 1 == 0:
            print(f"[INFO] Working with frame {frame_no} ")

            frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
            results = detectx(frame, model=model)
            frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)

            frame = plot_boxes(results, frame, classes=classes)

            cv2.imshow("vid_out", frame)
            if vid_out:
                print(f"[INFO] Saving output video. . . ")
                out.write(frame)

            if cv2.waitKey(5) & 0xFF == 27:
                break
            frame_no += 1

        ret, buffer = cv2.imencode('.jpg', frame)
        frame = buffer.tobytes()

        yield (b'--frame\r\n'
               b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')
    # print(f"[INFO] Cleaning up. . . ")
    # # releaseing the writer
    # out.release()
    #
    # # closing all windows
    # cv2.destroyAllWindows()

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/video')
def video():
    return Response(generate_frames(), mimetype='multipart/x-mixed-replace; boundary=frame')

if name == "main": app.run(debug=True)


问:
angular p-inputNumber invalid state red border not activating for input when it should
My p-inputNumber primeng component invalid state is not triggering when i type in numbers less then i set in the custom validator. it should apply red border as its doing for my second input which doesnt have custom validator. I needed to make custom validator because i have dropdown with celsius and fahrenheit options so when celsius is selected the min number must be 26 and when fahrenheit is selected min number must be 80
(p-inputNumber have an invalid state style to display the validation errors when ng-invalid ng-dirty combination is applied by Angular.)
component ts

```<code>this.heatIndexForm = new FormGroup(
      {
        temperature: new FormControl(null, [
          Validators.required,
          Validators.pattern(/^-?[0-9]\d*(\.\d+)?$/),
        ]),
        humidity: new FormControl(null, [
          Validators.required,
          Validators.pattern(/^-?[0-9]\d*(\.\d+)?$/),
          Validators.min(0),
          Validators.max(100),
        ]),
        temperatureUnit: new FormControl(new Temperature('Celsius', 'C')),
      },
      { validators: this.heatIndexService.selectedTemperatureValidator() }
    );
</code>```

custom validator

```<code>selectedTemperatureValidator(): ValidatorFn {
    return (form: FormGroup): { [key: string]: any } => {
      const temperatureControl = form.controls['temperature'];
      const selectedTemperatureControl = form.controls['temperatureUnit'];
      const temperature = temperatureControl.value;

      if (selectedTemperatureControl.value.code === 'F' && temperature < 80) {
        return { minTemperature: true };
      } else if (
        selectedTemperatureControl.value.code === 'C' &&
        temperature < 26
      ) {
        return { minTemperature: true };
      }
      return null;
    };
  }
</code>```

and html

```<code> <p-inputNumber formControlName="temperature" class="form-control" ></p-inputNumber>
          <div class="validation-error"
            *ngIf="temperatureUnit.value.code === 'F' &&
            heatIndexForm.hasError('minTemperature') &&
            heatIndexForm.controls['temperature'].dirty &&
            heatIndexForm.controls['temperature'].value">
            Temperature must be 80°F or higher!
          </div>
          <div class="validation-error"
            *ngIf="temperatureUnit.value.code === 'C' &&
            heatIndexForm.hasError('minTemperature') &&
            heatIndexForm.controls['temperature'].dirty &&
            heatIndexForm.controls['temperature'].value">
            Temperature must be 26°C or higher!
          </div>
          <div class="validation-error"
            *ngIf="heatIndexForm.get('temperature').hasError('pattern') &&
            heatIndexForm.controls['temperature'].dirty &&
            heatIndexForm.controls['temperature'].value">
            Temperature must be a number!
          </div>

        <!-- here is humidity input   -->
 <p-inputNumber formControlName="humidity" class="form-control"></p-inputNumber>
        <div class="unit">%</div>
        <div class="validation-error"
          *ngIf="heatIndexForm.get('humidity').hasError('min') ||
          heatIndexForm.get('humidity').hasError('max') &&
          heatIndexForm.get('humidity').touched">
          Humidity must be 0% - 100%
        </div>
        <div class="validation-error"
          *ngIf="heatIndexForm.get('humidity').hasError('pattern') &&
          heatIndexForm.get('humidity').touched">
          Humidity must be a number!
        </div>
<!-- and button   -->
 <button
        class="form-control"
        [disabled]="heatIndexForm.invalid"
        pButton
        label="Calculate">
      </button>
</code>```

for the second humidity input the red border is applying as it should when i type above 100 or under 0.
if i remove the custom validator and apply a Validator.min(26) and type less then 26 the border red is applying so issue should be somewhere in the customvalidator i think or the implementation in the formGroup.
can i make it work or do i have to use ngClass and set the border manually ??

Body:
My p-inputNumber primeng component invalid state is not triggering when i type in numbers less then i set in the custom validator. it should apply red border as its doing for my second input which doesnt have custom validator. I needed to make custom validator because i have dropdown with celsius and fahrenheit options so when celsius is selected the min number must be 26 and when fahrenheit is selected min number must be 80
(p-inputNumber have an invalid state style to display the validation errors when ng-invalid ng-dirty combination is applied by Angular.)
component ts

this.heatIndexForm = new FormGroup(
      {
        temperature: new FormControl(null, [
          Validators.required,
          Validators.pattern(/^-?[0-9]\d*(\.\d+)?$/),
        ]),
        humidity: new FormControl(null, [
          Validators.required,
          Validators.pattern(/^-?[0-9]\d*(\.\d+)?$/),
          Validators.min(0),
          Validators.max(100),
        ]),
        temperatureUnit: new FormControl(new Temperature('Celsius', 'C')),
      },
      { validators: this.heatIndexService.selectedTemperatureValidator() }
    );

custom validator

selectedTemperatureValidator(): ValidatorFn {
    return (form: FormGroup): { [key: string]: any } => {
      const temperatureControl = form.controls['temperature'];
      const selectedTemperatureControl = form.controls['temperatureUnit'];
      const temperature = temperatureControl.value;

      if (selectedTemperatureControl.value.code === 'F' && temperature < 80) {
        return { minTemperature: true };
      } else if (
        selectedTemperatureControl.value.code === 'C' &&
        temperature < 26
      ) {
        return { minTemperature: true };
      }
      return null;
    };
  }

and html

            Temperature must be 80°F or higher!

            Temperature must be 26°C or higher!

            Temperature must be a number!

%

          Humidity must be 0% - 100%

          Humidity must be a number!

 <button
        class="form-control"
        [disabled]="heatIndexForm.invalid"
        pButton
        label="Calculate">
      </button>

for the second humidity input the red border is applying as it should when i type above 100 or under 0.
if i remove the custom validator and apply a Validator.min(26) and type less then 26 the border red is applying so issue should be somewhere in the customvalidator i think or the implementation in the formGroup.
can i make it work or do i have to use ngClass and set the border manually ??


问:
Algorithm to create all edges between a bunch of nodes in a 3d space?
I have a bunch of points in a 3d environment that I want to solve the traveling salesman problem with, for that I first need to convert the game world to a graph.

The world is around 1km wide, 1.5 km long and 250m high = 375 000 000 possible location. Each location either has an obstacle or is walkable.

There are 150 location that I want to connect in this world. What would be the best approach to solve this?

Here is how the pathfinder looks right now, which is the bidirectional a* that also takes into account telporters

```<code>package me.mmaxi.pathfinder;

import me.mmaxi.utils.Location;
import me.mmaxi.utils.TeleportDirection;

import java.util.*;

public class PathFinder {
private final Map<Location, Block> blocks = new HashMap<>();

public List<Location> getPath(Location start, Location goal, IWalkHandler walkHandler, ITeleportHandler teleportHandler) {
    // initializing start queue
    PriorityQueue<PathFindStep> queueFromStart = new PriorityQueue<>();
    Block startBlock = getBlock(start);
    startBlock.distanceFromStart = 0;
    startBlock.fScore = start.h(goal, teleportHandler, TeleportDirection.FORWARD);
    queueFromStart.add(new PathFindStep(startBlock, startBlock.fScore));
    // initializing goal queue
    PriorityQueue<PathFindStep> queueFromGoal = new PriorityQueue<>();
    Block goalBlock = getBlock(goal);
    goalBlock.distanceFromGoal = 0;
    goalBlock.fScore = goal.h(start, teleportHandler, TeleportDirection.BACKWARD);
    queueFromGoal.add(new PathFindStep(goalBlock, goalBlock.fScore));
    // here we will store the meeting point
    Block meetingPoint = null;
    // for debug purposes
    int furthestAwayFromStartSoFar = 0;
    int furthestAwayFromGoalSoFar = 0;
    // working on the queues
    while (!queueFromStart.isEmpty() || !queueFromGoal.isEmpty()) {
        // coming from start
        PathFindStep currentStepFromStart = queueFromStart.poll();
        if (currentStepFromStart == null) {
            throw new RuntimeException("We can no longer reach any blocks from the start. Maybe it's inside a wall?");
        } else {
            Block current = currentStepFromStart.toVisit;
            if (Double.compare(currentStepFromStart.fScore, current.fScore) != 0) {
                // we already found a better fScore in the meantime
                continue;
            }
            if (current.location.equals(goal) || current.lastComingFromGoal != null) {
                // we found the goal or meeting point
                System.out.println("Breaking condition:\n" +
                        "* current.location.equals(goal):" + current.location.equals(goal) + "\n" +
                        "* current.lastComingFromGoal != null:" + (current.lastComingFromGoal != null));
                meetingPoint = current;
                break;
            }
            Set<Block> neighbours = getNeighbours(current);
            Location teleportTarget = teleportHandler.getDestination(current.location);
            if (teleportTarget != null) {
                System.out.println("Found teleport target: " + teleportTarget);
                neighbours.add(getBlock(teleportTarget));
            }
            for (Block neighbour : neighbours) {
                if (!walkHandler.canWalk(neighbour.location) && !neighbour.location.equals(goal)) {
                    // we can't go there so ignoring this neighbour but only if it's not the goal
                    continue;
                }
                int pendingDistanceFromStart = current.distanceFromStart + 1;
                if (pendingDistanceFromStart < neighbour.distanceFromStart) {
                    neighbour.lastComingFromStart = current;
                    neighbour.distanceFromStart = pendingDistanceFromStart;
                    neighbour.fScore = neighbour.location.h(goal, teleportHandler, TeleportDirection.FORWARD) + pendingDistanceFromStart;
                    queueFromStart.add(new PathFindStep(neighbour, neighbour.fScore));
                    if (pendingDistanceFromStart > furthestAwayFromStartSoFar) {
                        furthestAwayFromStartSoFar = pendingDistanceFromStart;
                        if (pendingDistanceFromStart % 25 == 0) {
                            System.out.println("Furthest from start: " + pendingDistanceFromStart);
                        }
                    }
                }
            }
        }

        // coming from goal
        PathFindStep currentStepFromGoal = queueFromGoal.poll();
        if (currentStepFromGoal == null) {
            throw new RuntimeException("We can no longer reach any blocks from the goal. Maybe it's inside a wall?");
        } else {
            Block current = currentStepFromGoal.toVisit;
            if (Double.compare(currentStepFromGoal.fScore, current.fScore) != 0) {
                // we already found a better fScore in the meantime
                continue;
            }
            if (current.location.equals(start) || current.lastComingFromStart != null) {
                // we found the start or meeting point
                System.out.println("Breaking condition:\n" +
                        "* current.location.equals(start):" + current.location.equals(start) + "\n" +
                        "* current.lastComingFromStart != null:" + (current.lastComingFromStart != null));
                meetingPoint = current;
                break;
            }
            Set<Block> neighbours = getNeighbours(current);
            Location teleportStart = teleportHandler.getStart(current.location);
            if (teleportStart != null) {
                System.out.println("Found teleport start: " + teleportStart);
                neighbours.add(getBlock(teleportStart));
            }
            for (Block neighbour : neighbours) {
                if (!walkHandler.canWalk(neighbour.location) && !neighbour.location.equals(start)) {
                    // we can't go there so ignoring this neighbour but only if it's not the start
                    continue;
                }
                int pendingDistanceFromGoal = current.distanceFromGoal + 1;
                if (pendingDistanceFromGoal < neighbour.distanceFromGoal) {
                    neighbour.lastComingFromGoal = current;
                    neighbour.distanceFromGoal = pendingDistanceFromGoal;
                    neighbour.fScore = neighbour.location.h(start, teleportHandler, TeleportDirection.BACKWARD) + pendingDistanceFromGoal;
                    queueFromGoal.add(new PathFindStep(neighbour, neighbour.fScore));
                    if (pendingDistanceFromGoal > furthestAwayFromGoalSoFar) {
                        furthestAwayFromGoalSoFar = pendingDistanceFromGoal;
                        if (pendingDistanceFromGoal % 25 == 0) {
                            System.out.println("Furthest from goal: " + pendingDistanceFromGoal);
                        }
                    }
                }
            }
        }
    }
    if (meetingPoint == null) {
        throw new RuntimeException("Could not find a meeting point.");
    }
    System.out.println("Found a meeting point! " + meetingPoint.location);
    // reversing the one side coming from the goal, so we can then backtrack
    System.out.println("Reversing side that started from goal.");
    while (meetingPoint.lastComingFromGoal != null) {
        meetingPoint.lastComingFromGoal.lastComingFromStart = meetingPoint;
        meetingPoint = meetingPoint.lastComingFromGoal;
    }
    // now we can backtrack
    System.out.println("Backtracking.");
    Block tmp = goalBlock;
    if (tmp.lastComingFromStart == null) {
        throw new RuntimeException("Could not find the target block from that start block.");
    }
    System.out.println("Found goal. Starting to backtrack.");
    List<Location> path = new ArrayList<>();
    while (tmp != null) {
        path.add(tmp.location);
        tmp = tmp.lastComingFromStart;
    }
    Collections.reverse(path);
    return path;
}

private Block getBlock(Location location) {
    return blocks.computeIfAbsent(location, block -> new Block(location));
}

private Set<Block> getNeighbours(Block block) {
    Set<Block> neighbours = new HashSet<>();
    for (BlockFace blockFace : BlockFace.values()) {
        Location targetLocation = block.location.clone().add(blockFace.vector);
        if (targetLocation.getBlockY() > 255 || targetLocation.getBlockY() < 0) {
            continue;
        }
        neighbours.add(getBlock(targetLocation));
    }
    return neighbours;
}

static class PathFindStep implements Comparable<PathFindStep> {
    Block toVisit;
    double fScore;

    public PathFindStep(Block toVisit, double fScore) {
        this.toVisit = toVisit;
        this.fScore = fScore;
    }

    @Override
    public int compareTo(PathFindStep o) {
        return Double.compare(fScore, o.fScore);
    }
}

static class Block {
    Location location;

    Block lastComingFromStart;
    Block lastComingFromGoal;
    double fScore;
    int distanceFromStart = Integer.MAX_VALUE;
    int distanceFromGoal = Integer.MAX_VALUE;

    public Block(Location location) {
        this.location = location;
    }
}

enum BlockFace {
    POS_Y(new Location(+0, +1, +0)),
    NEG_Y(new Location(+0, -1, +0)),
    POS_X(new Location(+1, +0, +0)),
    NEG_X(new Location(-1, +0, +0)),
    POS_Z(new Location(+0, +0, +1)),
    NEG_Z(new Location(+0, +0, -1));

    final Location vector;

    BlockFace(Location vector) {
        this.vector = vector;
    }
}
</code>```

}

```<code>public class Location implements Cloneable {
private double x, y, z;

public Location(double x, double y, double z) {
    this.x = x;
    this.y = y;
    this.z = z;
}

public double getX() {
    return x;
}

public double getY() {
    return y;
}

public double getZ() {
    return z;
}

public int getBlockX() {
    return (int) x;
}

public int getBlockY() {
    return (int) y;
}

public int getBlockZ() {
    return (int) z;
}

public Location add(double x, double y, double z) {
    this.x += x;
    this.y += y;
    this.z += z;
    return this;
}

public Location add(Location other) {
    this.x += other.x;
    this.y += other.y;
    this.z += other.z;
    return this;
}

public double distanceSquared(Location other) {
    double dx = x - other.x;
    double dy = y - other.y;
    double dz = z - other.z;
    return dx * dx + dy * dy + dz * dz;
}

public double mhd(Location other) {
    double dx = Math.abs(x - other.x);
    double dy = Math.abs(y - other.y);
    double dz = Math.abs(z - other.z);
    return Math.max(dx, Math.max(dy, dz));
}

public double h(Location other, ITeleportHandler teleportHandler, TeleportDirection teleportDirection) {
    double h = mhd(other);
    if (teleportHandler != null) {
        Location[] closestTeleport = teleportHandler.getClosestTeleport(this, teleportDirection);
        if (closestTeleport != null) {
            if (teleportDirection == TeleportDirection.FORWARD) {
                h = Math.min(h, mhd(closestTeleport[0]) + closestTeleport[1].mhd(other));
            } else {
                h = Math.min(h, mhd(closestTeleport[1]) + closestTeleport[0].mhd(other));
            }
        }
    }
    return h;
}

@Override
public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;
    Location location = (Location) o;
    return Double.compare(location.x, x) == 0 && Double.compare(location.y, y) == 0 && Double.compare(location.z, z) == 0;
}

@Override
public int hashCode() {
    return Objects.hash(x, y, z);
}

@Override
public String toString() {
    String xString = Double.compare(x, (int) x) == 0 ? Integer.toString((int) x) : Double.toString(x);
    String yString = Double.compare(y, (int) y) == 0 ? Integer.toString((int) y) : Double.toString(y);
    String zString = Double.compare(z, (int) z) == 0 ? Integer.toString((int) z) : Double.toString(z);
    return "[" + xString + " " + yString + " " + zString + "]";
}

@Override
public Location clone() {
    try {
        return (Location) super.clone();
    } catch (CloneNotSupportedException e) {
        throw new AssertionError();
    }
}
</code>```

}

Body:
I have a bunch of points in a 3d environment that I want to solve the traveling salesman problem with, for that I first need to convert the game world to a graph.

The world is around 1km wide, 1.5 km long and 250m high = 375 000 000 possible location. Each location either has an obstacle or is walkable.

There are 150 location that I want to connect in this world. What would be the best approach to solve this?

Here is how the pathfinder looks right now, which is the bidirectional a* that also takes into account telporters

package me.mmaxi.pathfinder;

import me.mmaxi.utils.Location;
import me.mmaxi.utils.TeleportDirection;

import java.util.*;

public class PathFinder {
private final Map<Location, Block> blocks = new HashMap<>();

public List<Location> getPath(Location start, Location goal, IWalkHandler walkHandler, ITeleportHandler teleportHandler) {
    // initializing start queue
    PriorityQueue<PathFindStep> queueFromStart = new PriorityQueue<>();
    Block startBlock = getBlock(start);
    startBlock.distanceFromStart = 0;
    startBlock.fScore = start.h(goal, teleportHandler, TeleportDirection.FORWARD);
    queueFromStart.add(new PathFindStep(startBlock, startBlock.fScore));
    // initializing goal queue
    PriorityQueue<PathFindStep> queueFromGoal = new PriorityQueue<>();
    Block goalBlock = getBlock(goal);
    goalBlock.distanceFromGoal = 0;
    goalBlock.fScore = goal.h(start, teleportHandler, TeleportDirection.BACKWARD);
    queueFromGoal.add(new PathFindStep(goalBlock, goalBlock.fScore));
    // here we will store the meeting point
    Block meetingPoint = null;
    // for debug purposes
    int furthestAwayFromStartSoFar = 0;
    int furthestAwayFromGoalSoFar = 0;
    // working on the queues
    while (!queueFromStart.isEmpty() || !queueFromGoal.isEmpty()) {
        // coming from start
        PathFindStep currentStepFromStart = queueFromStart.poll();
        if (currentStepFromStart == null) {
            throw new RuntimeException("We can no longer reach any blocks from the start. Maybe it's inside a wall?");
        } else {
            Block current = currentStepFromStart.toVisit;
            if (Double.compare(currentStepFromStart.fScore, current.fScore) != 0) {
                // we already found a better fScore in the meantime
                continue;
            }
            if (current.location.equals(goal) || current.lastComingFromGoal != null) {
                // we found the goal or meeting point
                System.out.println("Breaking condition:\n" +
                        "* current.location.equals(goal):" + current.location.equals(goal) + "\n" +
                        "* current.lastComingFromGoal != null:" + (current.lastComingFromGoal != null));
                meetingPoint = current;
                break;
            }
            Set<Block> neighbours = getNeighbours(current);
            Location teleportTarget = teleportHandler.getDestination(current.location);
            if (teleportTarget != null) {
                System.out.println("Found teleport target: " + teleportTarget);
                neighbours.add(getBlock(teleportTarget));
            }
            for (Block neighbour : neighbours) {
                if (!walkHandler.canWalk(neighbour.location) && !neighbour.location.equals(goal)) {
                    // we can't go there so ignoring this neighbour but only if it's not the goal
                    continue;
                }
                int pendingDistanceFromStart = current.distanceFromStart + 1;
                if (pendingDistanceFromStart < neighbour.distanceFromStart) {
                    neighbour.lastComingFromStart = current;
                    neighbour.distanceFromStart = pendingDistanceFromStart;
                    neighbour.fScore = neighbour.location.h(goal, teleportHandler, TeleportDirection.FORWARD) + pendingDistanceFromStart;
                    queueFromStart.add(new PathFindStep(neighbour, neighbour.fScore));
                    if (pendingDistanceFromStart > furthestAwayFromStartSoFar) {
                        furthestAwayFromStartSoFar = pendingDistanceFromStart;
                        if (pendingDistanceFromStart % 25 == 0) {
                            System.out.println("Furthest from start: " + pendingDistanceFromStart);
                        }
                    }
                }
            }
        }

        // coming from goal
        PathFindStep currentStepFromGoal = queueFromGoal.poll();
        if (currentStepFromGoal == null) {
            throw new RuntimeException("We can no longer reach any blocks from the goal. Maybe it's inside a wall?");
        } else {
            Block current = currentStepFromGoal.toVisit;
            if (Double.compare(currentStepFromGoal.fScore, current.fScore) != 0) {
                // we already found a better fScore in the meantime
                continue;
            }
            if (current.location.equals(start) || current.lastComingFromStart != null) {
                // we found the start or meeting point
                System.out.println("Breaking condition:\n" +
                        "* current.location.equals(start):" + current.location.equals(start) + "\n" +
                        "* current.lastComingFromStart != null:" + (current.lastComingFromStart != null));
                meetingPoint = current;
                break;
            }
            Set<Block> neighbours = getNeighbours(current);
            Location teleportStart = teleportHandler.getStart(current.location);
            if (teleportStart != null) {
                System.out.println("Found teleport start: " + teleportStart);
                neighbours.add(getBlock(teleportStart));
            }
            for (Block neighbour : neighbours) {
                if (!walkHandler.canWalk(neighbour.location) && !neighbour.location.equals(start)) {
                    // we can't go there so ignoring this neighbour but only if it's not the start
                    continue;
                }
                int pendingDistanceFromGoal = current.distanceFromGoal + 1;
                if (pendingDistanceFromGoal < neighbour.distanceFromGoal) {
                    neighbour.lastComingFromGoal = current;
                    neighbour.distanceFromGoal = pendingDistanceFromGoal;
                    neighbour.fScore = neighbour.location.h(start, teleportHandler, TeleportDirection.BACKWARD) + pendingDistanceFromGoal;
                    queueFromGoal.add(new PathFindStep(neighbour, neighbour.fScore));
                    if (pendingDistanceFromGoal > furthestAwayFromGoalSoFar) {
                        furthestAwayFromGoalSoFar = pendingDistanceFromGoal;
                        if (pendingDistanceFromGoal % 25 == 0) {
                            System.out.println("Furthest from goal: " + pendingDistanceFromGoal);
                        }
                    }
                }
            }
        }
    }
    if (meetingPoint == null) {
        throw new RuntimeException("Could not find a meeting point.");
    }
    System.out.println("Found a meeting point! " + meetingPoint.location);
    // reversing the one side coming from the goal, so we can then backtrack
    System.out.println("Reversing side that started from goal.");
    while (meetingPoint.lastComingFromGoal != null) {
        meetingPoint.lastComingFromGoal.lastComingFromStart = meetingPoint;
        meetingPoint = meetingPoint.lastComingFromGoal;
    }
    // now we can backtrack
    System.out.println("Backtracking.");
    Block tmp = goalBlock;
    if (tmp.lastComingFromStart == null) {
        throw new RuntimeException("Could not find the target block from that start block.");
    }
    System.out.println("Found goal. Starting to backtrack.");
    List<Location> path = new ArrayList<>();
    while (tmp != null) {
        path.add(tmp.location);
        tmp = tmp.lastComingFromStart;
    }
    Collections.reverse(path);
    return path;
}

private Block getBlock(Location location) {
    return blocks.computeIfAbsent(location, block -> new Block(location));
}

private Set<Block> getNeighbours(Block block) {
    Set<Block> neighbours = new HashSet<>();
    for (BlockFace blockFace : BlockFace.values()) {
        Location targetLocation = block.location.clone().add(blockFace.vector);
        if (targetLocation.getBlockY() > 255 || targetLocation.getBlockY() < 0) {
            continue;
        }
        neighbours.add(getBlock(targetLocation));
    }
    return neighbours;
}

static class PathFindStep implements Comparable<PathFindStep> {
    Block toVisit;
    double fScore;

    public PathFindStep(Block toVisit, double fScore) {
        this.toVisit = toVisit;
        this.fScore = fScore;
    }

    @Override
    public int compareTo(PathFindStep o) {
        return Double.compare(fScore, o.fScore);
    }
}

static class Block {
    Location location;

    Block lastComingFromStart;
    Block lastComingFromGoal;
    double fScore;
    int distanceFromStart = Integer.MAX_VALUE;
    int distanceFromGoal = Integer.MAX_VALUE;

    public Block(Location location) {
        this.location = location;
    }
}

enum BlockFace {
    POS_Y(new Location(+0, +1, +0)),
    NEG_Y(new Location(+0, -1, +0)),
    POS_X(new Location(+1, +0, +0)),
    NEG_X(new Location(-1, +0, +0)),
    POS_Z(new Location(+0, +0, +1)),
    NEG_Z(new Location(+0, +0, -1));

    final Location vector;

    BlockFace(Location vector) {
        this.vector = vector;
    }
}

}

public class Location implements Cloneable {
private double x, y, z;

public Location(double x, double y, double z) {
    this.x = x;
    this.y = y;
    this.z = z;
}

public double getX() {
    return x;
}

public double getY() {
    return y;
}

public double getZ() {
    return z;
}

public int getBlockX() {
    return (int) x;
}

public int getBlockY() {
    return (int) y;
}

public int getBlockZ() {
    return (int) z;
}

public Location add(double x, double y, double z) {
    this.x += x;
    this.y += y;
    this.z += z;
    return this;
}

public Location add(Location other) {
    this.x += other.x;
    this.y += other.y;
    this.z += other.z;
    return this;
}

public double distanceSquared(Location other) {
    double dx = x - other.x;
    double dy = y - other.y;
    double dz = z - other.z;
    return dx * dx + dy * dy + dz * dz;
}

public double mhd(Location other) {
    double dx = Math.abs(x - other.x);
    double dy = Math.abs(y - other.y);
    double dz = Math.abs(z - other.z);
    return Math.max(dx, Math.max(dy, dz));
}

public double h(Location other, ITeleportHandler teleportHandler, TeleportDirection teleportDirection) {
    double h = mhd(other);
    if (teleportHandler != null) {
        Location[] closestTeleport = teleportHandler.getClosestTeleport(this, teleportDirection);
        if (closestTeleport != null) {
            if (teleportDirection == TeleportDirection.FORWARD) {
                h = Math.min(h, mhd(closestTeleport[0]) + closestTeleport[1].mhd(other));
            } else {
                h = Math.min(h, mhd(closestTeleport[1]) + closestTeleport[0].mhd(other));
            }
        }
    }
    return h;
}

@Override
public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;
    Location location = (Location) o;
    return Double.compare(location.x, x) == 0 && Double.compare(location.y, y) == 0 && Double.compare(location.z, z) == 0;
}

@Override
public int hashCode() {
    return Objects.hash(x, y, z);
}

@Override
public String toString() {
    String xString = Double.compare(x, (int) x) == 0 ? Integer.toString((int) x) : Double.toString(x);
    String yString = Double.compare(y, (int) y) == 0 ? Integer.toString((int) y) : Double.toString(y);
    String zString = Double.compare(z, (int) z) == 0 ? Integer.toString((int) z) : Double.toString(z);
    return "[" + xString + " " + yString + " " + zString + "]";
}

@Override
public Location clone() {
    try {
        return (Location) super.clone();
    } catch (CloneNotSupportedException e) {
        throw new AssertionError();
    }
}

}


问:
no errors thrown when running pipenv install, but running a python manage.py migrate after results in errors
```<code>ModuleNotFoundError: No module named 'django_on_heroku'
</code>```

I've got a new machine at work and I'm attempting to run an old project which I've cloned. Cannot get the api server up and running.

(ps, my first stack overflow post -- sorry if the format isn't great or specific enough!)

Have tried installing django on heroku in the pipenv - that is sucesfull, the error reoccurs though on the next dependency when i attempt a migrate and then run server.

Body:
ModuleNotFoundError: No module named 'django_on_heroku'

I've got a new machine at work and I'm attempting to run an old project which I've cloned. Cannot get the api server up and running.

(ps, my first stack overflow post -- sorry if the format isn't great or specific enough!)

Have tried installing django on heroku in the pipenv - that is sucesfull, the error reoccurs though on the next dependency when i attempt a migrate and then run server.


问:
How to get confirmation from rabbitmq after publishing a message
I'm trying in python to get an acknowledgment from rabbitmq after publishing a message to a queue.

I am using this example for test.
https://pika.readthedocs.io/en/stable/examples/blocking_delivery_confirmations.html
But the desired result is not obtained.


问:
How do i use sublime text find and replace files to only find and replace .html files only
I am using Sublime Text to edit HTML markup. I need some markup to be added only to HTML files in the project, e.g.:

Find:

```<code><head>
</code>```

Replace:

```<code><head>
<!-- Here is a script -->
</code>```

Is it possible to make the Find & Replace tool ignore non-HTML files?

I have done a Find and Replace in files search but it has changed another file which I do not want it to change.

Body:
I am using Sublime Text to edit HTML markup. I need some markup to be added only to HTML files in the project, e.g.:

Find:

Replace:

Is it possible to make the Find & Replace tool ignore non-HTML files?

I have done a Find and Replace in files search but it has changed another file which I do not want it to change.