问:
Dijkstra Shortest Path example To Include weight in each step
Trying to follow the example listed here: QuickGraph Dijkstra example.
I had to change some to of the code to get it to work, not sure if the example was out of date.
'''

```<code>using QuickGraph;
using QuickGraph.Algorithms;
using QuickGraph.Algorithms.Observers;
using QuickGraph.Algorithms.ShortestPath;

namespace Markov
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            AdjacencyGraph<string, Edge<string>> graph = new AdjacencyGraph<string, Edge<string>>(true);

            // Add some vertices to the graph
            graph.AddVertex("A");
            graph.AddVertex("B");
            graph.AddVertex("C");
            graph.AddVertex("D");
            graph.AddVertex("E");
            graph.AddVertex("F");
            graph.AddVertex("G");
            graph.AddVertex("H");
            graph.AddVertex("I");
            graph.AddVertex("J");

            // Create the edges
            Edge<string> a_b = new Edge<string>("A", "B");
            Edge<string> a_d = new Edge<string>("A", "D");
            Edge<string> b_a = new Edge<string>("B", "A");
            Edge<string> b_c = new Edge<string>("B", "C");
            Edge<string> b_e = new Edge<string>("B", "E");
            Edge<string> c_b = new Edge<string>("C", "B");
            Edge<string> c_f = new Edge<string>("C", "F");
            Edge<string> c_j = new Edge<string>("C", "J");
            Edge<string> d_e = new Edge<string>("D", "E");
            Edge<string> d_g = new Edge<string>("D", "G");
            Edge<string> e_d = new Edge<string>("E", "D");
            Edge<string> e_f = new Edge<string>("E", "F");
            Edge<string> e_h = new Edge<string>("E", "H");
            Edge<string> f_i = new Edge<string>("F", "I");
            Edge<string> f_j = new Edge<string>("F", "J");
            Edge<string> g_d = new Edge<string>("G", "D");
            Edge<string> g_h = new Edge<string>("G", "H");
            Edge<string> h_g = new Edge<string>("H", "G");
            Edge<string> h_i = new Edge<string>("H", "I");
            Edge<string> i_f = new Edge<string>("I", "F");
            Edge<string> i_j = new Edge<string>("I", "J");
            Edge<string> i_h = new Edge<string>("I", "H");
            Edge<string> j_f = new Edge<string>("J", "F");

            // Add the edges
            graph.AddEdge(a_b);
            graph.AddEdge(a_d);
            graph.AddEdge(b_a);
            graph.AddEdge(b_c);
            graph.AddEdge(b_e);
            graph.AddEdge(c_b);
            graph.AddEdge(c_f);
            graph.AddEdge(c_j);
            graph.AddEdge(d_e);
            graph.AddEdge(d_g);
            graph.AddEdge(e_d);
            graph.AddEdge(e_f);
            graph.AddEdge(e_h);
            graph.AddEdge(f_i);
            graph.AddEdge(f_j);
            graph.AddEdge(g_d);
            graph.AddEdge(g_h);
            graph.AddEdge(h_g);
            graph.AddEdge(h_i);
            graph.AddEdge(i_f);
            graph.AddEdge(i_h);
            graph.AddEdge(i_j);
            graph.AddEdge(j_f);

            // Define some weights to the edges
            //Because the algorithm takes a delegate as the edge cost, one cannot simply pass a dictionary. QuikGraph provides an helper method, GetIndexer, to make the conversion
            Dictionary<Edge<string>, double> edgeCostDict = new Dictionary<Edge<string>, double>();
            edgeCostDict.Add(a_b, 4);
            edgeCostDict.Add(a_d, 1);
            edgeCostDict.Add(b_a, 74);
            edgeCostDict.Add(b_c, 2);
            edgeCostDict.Add(b_e, 12);
            edgeCostDict.Add(c_b, 12);
            edgeCostDict.Add(c_f, 74);
            edgeCostDict.Add(c_j, 12);
            edgeCostDict.Add(d_e, 32);
            edgeCostDict.Add(d_g, 22);
            edgeCostDict.Add(e_d, 66);
            edgeCostDict.Add(e_f, 76);
            edgeCostDict.Add(e_h, 33);
            edgeCostDict.Add(f_i, 11);
            edgeCostDict.Add(f_j, 21);
            edgeCostDict.Add(g_d, 12);
            edgeCostDict.Add(g_h, 10);
            edgeCostDict.Add(h_g, 2);
            edgeCostDict.Add(h_i, 72);
            edgeCostDict.Add(i_f, 31);
            edgeCostDict.Add(i_h, 18);
            edgeCostDict.Add(i_j, 7);
            edgeCostDict.Add(j_f, 8);
            Func<Edge<string>, double> edgeCost = AlgorithmExtensions.GetIndexer(edgeCostDict);

            // We want to use Dijkstra on this graph
            DijkstraShortestPathAlgorithm<string, Edge<string>> dijkstra = new DijkstraShortestPathAlgorithm<string, Edge<string>>(graph, edgeCost);

            // attach a distance observer to give us the shortest path distances
            VertexDistanceRecorderObserver<string, Edge<string>> distObserver = new VertexDistanceRecorderObserver<string, Edge<string>>(edgeCost);
            distObserver.Attach(dijkstra);

            // Attach a Vertex Predecessor Recorder Observer to give us the paths
            VertexPredecessorRecorderObserver<string, Edge<string>> predecessorObserver = new VertexPredecessorRecorderObserver<string, Edge<string>>();
            predecessorObserver.Attach(dijkstra);

            // Run the algorithm with A set to be the source
            dijkstra.Compute("A");

            foreach (KeyValuePair<string, double> kvp in distObserver.Distances)
                Console.WriteLine("Distance from root (A) to node {0} is {1}", kvp.Key, kvp.Value);

            foreach (KeyValuePair<string, Edge<string>> kvp in predecessorObserver.VertexPredecessors)
                Console.WriteLine("If you want to get to {0} you have to enter through the in edge {1}", kvp.Key, kvp.Value);

            PrintShortestPath("A", "H", graph, edgeCost);
        }
        private static void PrintShortestPath(string @from, string to, AdjacencyGraph<string, Edge<string>> graph, Func<Edge<string>, double> edgeCost)
        {

            var tryGetPath = graph.ShortestPathsDijkstra(edgeCost, @from);
            //var pathDistance = graph.
            IEnumerable<Edge<string>> path;
            if (tryGetPath(to, out path))
            {
                foreach (var item in path)
                {
                    Console.WriteLine($"{@from}, {to}, {item}");
                }

            }
            else
            {
                Console.WriteLine($"No path found from {@from} to {to}.");
            }
        }
    }
}
</code>```

'''

The Function ShortestPathsDijkstra provides the path, but is there a way to follow the cost along with the path? Print out 1 ,22, 10?

Body:
Trying to follow the example listed here: QuickGraph Dijkstra example.
I had to change some to of the code to get it to work, not sure if the example was out of date.
'''

using QuickGraph;
using QuickGraph.Algorithms;
using QuickGraph.Algorithms.Observers;
using QuickGraph.Algorithms.ShortestPath;

namespace Markov
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            AdjacencyGraph<string, Edge<string>> graph = new AdjacencyGraph<string, Edge<string>>(true);

            // Add some vertices to the graph
            graph.AddVertex("A");
            graph.AddVertex("B");
            graph.AddVertex("C");
            graph.AddVertex("D");
            graph.AddVertex("E");
            graph.AddVertex("F");
            graph.AddVertex("G");
            graph.AddVertex("H");
            graph.AddVertex("I");
            graph.AddVertex("J");

            // Create the edges
            Edge<string> a_b = new Edge<string>("A", "B");
            Edge<string> a_d = new Edge<string>("A", "D");
            Edge<string> b_a = new Edge<string>("B", "A");
            Edge<string> b_c = new Edge<string>("B", "C");
            Edge<string> b_e = new Edge<string>("B", "E");
            Edge<string> c_b = new Edge<string>("C", "B");
            Edge<string> c_f = new Edge<string>("C", "F");
            Edge<string> c_j = new Edge<string>("C", "J");
            Edge<string> d_e = new Edge<string>("D", "E");
            Edge<string> d_g = new Edge<string>("D", "G");
            Edge<string> e_d = new Edge<string>("E", "D");
            Edge<string> e_f = new Edge<string>("E", "F");
            Edge<string> e_h = new Edge<string>("E", "H");
            Edge<string> f_i = new Edge<string>("F", "I");
            Edge<string> f_j = new Edge<string>("F", "J");
            Edge<string> g_d = new Edge<string>("G", "D");
            Edge<string> g_h = new Edge<string>("G", "H");
            Edge<string> h_g = new Edge<string>("H", "G");
            Edge<string> h_i = new Edge<string>("H", "I");
            Edge<string> i_f = new Edge<string>("I", "F");
            Edge<string> i_j = new Edge<string>("I", "J");
            Edge<string> i_h = new Edge<string>("I", "H");
            Edge<string> j_f = new Edge<string>("J", "F");

            // Add the edges
            graph.AddEdge(a_b);
            graph.AddEdge(a_d);
            graph.AddEdge(b_a);
            graph.AddEdge(b_c);
            graph.AddEdge(b_e);
            graph.AddEdge(c_b);
            graph.AddEdge(c_f);
            graph.AddEdge(c_j);
            graph.AddEdge(d_e);
            graph.AddEdge(d_g);
            graph.AddEdge(e_d);
            graph.AddEdge(e_f);
            graph.AddEdge(e_h);
            graph.AddEdge(f_i);
            graph.AddEdge(f_j);
            graph.AddEdge(g_d);
            graph.AddEdge(g_h);
            graph.AddEdge(h_g);
            graph.AddEdge(h_i);
            graph.AddEdge(i_f);
            graph.AddEdge(i_h);
            graph.AddEdge(i_j);
            graph.AddEdge(j_f);

            // Define some weights to the edges
            //Because the algorithm takes a delegate as the edge cost, one cannot simply pass a dictionary. QuikGraph provides an helper method, GetIndexer, to make the conversion
            Dictionary<Edge<string>, double> edgeCostDict = new Dictionary<Edge<string>, double>();
            edgeCostDict.Add(a_b, 4);
            edgeCostDict.Add(a_d, 1);
            edgeCostDict.Add(b_a, 74);
            edgeCostDict.Add(b_c, 2);
            edgeCostDict.Add(b_e, 12);
            edgeCostDict.Add(c_b, 12);
            edgeCostDict.Add(c_f, 74);
            edgeCostDict.Add(c_j, 12);
            edgeCostDict.Add(d_e, 32);
            edgeCostDict.Add(d_g, 22);
            edgeCostDict.Add(e_d, 66);
            edgeCostDict.Add(e_f, 76);
            edgeCostDict.Add(e_h, 33);
            edgeCostDict.Add(f_i, 11);
            edgeCostDict.Add(f_j, 21);
            edgeCostDict.Add(g_d, 12);
            edgeCostDict.Add(g_h, 10);
            edgeCostDict.Add(h_g, 2);
            edgeCostDict.Add(h_i, 72);
            edgeCostDict.Add(i_f, 31);
            edgeCostDict.Add(i_h, 18);
            edgeCostDict.Add(i_j, 7);
            edgeCostDict.Add(j_f, 8);
            Func<Edge<string>, double> edgeCost = AlgorithmExtensions.GetIndexer(edgeCostDict);

            // We want to use Dijkstra on this graph
            DijkstraShortestPathAlgorithm<string, Edge<string>> dijkstra = new DijkstraShortestPathAlgorithm<string, Edge<string>>(graph, edgeCost);

            // attach a distance observer to give us the shortest path distances
            VertexDistanceRecorderObserver<string, Edge<string>> distObserver = new VertexDistanceRecorderObserver<string, Edge<string>>(edgeCost);
            distObserver.Attach(dijkstra);

            // Attach a Vertex Predecessor Recorder Observer to give us the paths
            VertexPredecessorRecorderObserver<string, Edge<string>> predecessorObserver = new VertexPredecessorRecorderObserver<string, Edge<string>>();
            predecessorObserver.Attach(dijkstra);

            // Run the algorithm with A set to be the source
            dijkstra.Compute("A");

            foreach (KeyValuePair<string, double> kvp in distObserver.Distances)
                Console.WriteLine("Distance from root (A) to node {0} is {1}", kvp.Key, kvp.Value);

            foreach (KeyValuePair<string, Edge<string>> kvp in predecessorObserver.VertexPredecessors)
                Console.WriteLine("If you want to get to {0} you have to enter through the in edge {1}", kvp.Key, kvp.Value);

            PrintShortestPath("A", "H", graph, edgeCost);
        }
        private static void PrintShortestPath(string @from, string to, AdjacencyGraph<string, Edge<string>> graph, Func<Edge<string>, double> edgeCost)
        {

            var tryGetPath = graph.ShortestPathsDijkstra(edgeCost, @from);
            //var pathDistance = graph.
            IEnumerable<Edge<string>> path;
            if (tryGetPath(to, out path))
            {
                foreach (var item in path)
                {
                    Console.WriteLine($"{@from}, {to}, {item}");
                }

            }
            else
            {
                Console.WriteLine($"No path found from {@from} to {to}.");
            }
        }
    }
}

'''

The Function ShortestPathsDijkstra provides the path, but is there a way to follow the cost along with the path? Print out 1 ,22, 10?


来源: stackexchange

问:
Cannot find name 'useRuntimeConfig'
I'm trying to use some environment variables in one of the TS files in my project.
The nuxt.config.js file looks like this:

```<code>export default {
    head: {
        title: 'frontend',
        htmlAttrs: {
            lang: 'en'
        },
        meta: [{
            charset: 'utf-8'
        }, {
            name: 'viewport',
            content: 'width=device-width, initial-scale=1'
        }, {
            hid: 'description',
            name: 'description',
            content: ''
        }, {
            name: 'format-detection',
            content: 'telephone=no'
        }, ],
        link: [{
            rel: 'icon',
            type: 'image/x-icon',
            href: '/favicon.ico'
        }]
    },
    runtimeConfig: {
        clientId: process.env.CLIENT_ID,
        clientSecret: process.env.CLIENT_SECRET
    },

    css: [],
    plugins: [],
    components: true,
    buildModules: [
        '@nuxt/typescript-build',
    ],

    modules: [
        'nuxt-buefy',
    ],

    build: {}
}
</code>```

I want to use the environment variebles in a file which is located in the root/server/api folder.

The code is the following here:

```<code>const Client= require('client_package');
const { clientId, clientSecret } = useRuntimeConfig();
export const client= new Client({
  clientId: clientId,
  clientSecret: clientSecret
});
</code>```

Here I got the error, that Cannot find name 'useRuntimeConfig'.

What am I doing wrong?

ContentLicense: CC BY-SA 4.0

Title: Cannot find name 'useRuntimeConfig'

Body:
I'm trying to use some environment variables in one of the TS files in my project.
The nuxt.config.js file looks like this:

export default {
    head: {
        title: 'frontend',
        htmlAttrs: {
            lang: 'en'
        },
        meta: [{
            charset: 'utf-8'
        }, {
            name: 'viewport',
            content: 'width=device-width, initial-scale=1'
        }, {
            hid: 'description',
            name: 'description',
            content: ''
        }, {
            name: 'format-detection',
            content: 'telephone=no'
        }, ],
        link: [{
            rel: 'icon',
            type: 'image/x-icon',
            href: '/favicon.ico'
        }]
    },
    runtimeConfig: {
        clientId: process.env.CLIENT_ID,
        clientSecret: process.env.CLIENT_SECRET
    },

    css: [],
    plugins: [],
    components: true,
    buildModules: [
        '@nuxt/typescript-build',
    ],

    modules: [
        'nuxt-buefy',
    ],

    build: {}
}

I want to use the environment variebles in a file which is located in the root/server/api folder.

The code is the following here:

const Client= require('client_package');
const { clientId, clientSecret } = useRuntimeConfig();
export const client= new Client({
  clientId: clientId,
  clientSecret: clientSecret
});

Here I got the error, that Cannot find name 'useRuntimeConfig'.

What am I doing wrong?


问:
trying to seamlessly loop video with audio in a browser
I have a perfect video loop (zero crossings, loops in editing software perfectly). Once I export/compress I am running into the issue of the slight hiccup on loop reset in both browsers and players (vlc, quicktime etc). If the audio track is removed the loop is perfect. My initial research seems to point to the issue of lossy audio encoding adding some samples of silence to the start/end. Is there any modern browser compatible video settings/formats that will allow a perfect loop with audio?

I have tried several audio/video compression settings. All result in a slight stall when the video restarts.


问:
How to change the shape of Points from ThreeJS from a square into a circle?
I am using React, Three JS, React-Three-Fibre

Here is what I have:

```<code>// Texture for Points
    const getTexture = (size, color) => {
        const matCanvas = document.createElement('canvas');
        matCanvas.width = matCanvas.height = size;
        const matContext = matCanvas.getContext('2d');
        const texture = new THREE.Texture(matCanvas);

        const center = size / 2;
        matContext.beginPath();
        matContext.arc(center, center, size/2, 0, 2 * Math.PI, false);
        matContext.closePath();
        matContext.fillStyle = color;
        matContext.fill();

        //texture.minFilter = THREE.NearestFilter;
        texture.needsUpdate = true;
        return texture;
    }

    const vertices = [];

    for ( let i = 0; i < 10; i ++ ) {

        const x = THREE.MathUtils.randFloatSpread( 10 );
        const y = THREE.MathUtils.randFloatSpread( 10 );
        const z = THREE.MathUtils.randFloatSpread( 10 );

        vertices.push( x, y, z );

    }

    const geometry = new THREE.BufferGeometry();
    geometry.setAttribute( 'position', new THREE.Float32BufferAttribute( vertices, 3 ) );

    const material = new THREE.PointsMaterial( { color: 0x123684 } );
    const points = new THREE.Points( geometry, material );
</code>```

And here is the R3F

```<code>return (
        <points args={[geometry]}>
            <pointsMaterial
                size={1}
                map={getTexture(10, 'red')}
            />
        </points>
    )
</code>```

The problem is instead of the points changing shape from square to circle, instead they are the picture of a circle inside of a square

enter image description here

Body:
I am using React, Three JS, React-Three-Fibre

Here is what I have:

// Texture for Points
    const getTexture = (size, color) => {
        const matCanvas = document.createElement('canvas');
        matCanvas.width = matCanvas.height = size;
        const matContext = matCanvas.getContext('2d');
        const texture = new THREE.Texture(matCanvas);

        const center = size / 2;
        matContext.beginPath();
        matContext.arc(center, center, size/2, 0, 2 * Math.PI, false);
        matContext.closePath();
        matContext.fillStyle = color;
        matContext.fill();

        //texture.minFilter = THREE.NearestFilter;
        texture.needsUpdate = true;
        return texture;
    }

    const vertices = [];

    for ( let i = 0; i < 10; i ++ ) {

        const x = THREE.MathUtils.randFloatSpread( 10 );
        const y = THREE.MathUtils.randFloatSpread( 10 );
        const z = THREE.MathUtils.randFloatSpread( 10 );

        vertices.push( x, y, z );

    }

    const geometry = new THREE.BufferGeometry();
    geometry.setAttribute( 'position', new THREE.Float32BufferAttribute( vertices, 3 ) );

    const material = new THREE.PointsMaterial( { color: 0x123684 } );
    const points = new THREE.Points( geometry, material );

And here is the R3F

return (
        <points args={[geometry]}>
            <pointsMaterial
                size={1}
                map={getTexture(10, 'red')}
            />
        </points>
    )

The problem is instead of the points changing shape from square to circle, instead they are the picture of a circle inside of a square

enter image description here


问:
Get subtitle info with iTunes Search API
I am trying to use iTunes API to get information about subtitle languages currently available of a movie.
I'm using this API: https://developer.apple.com/library/archive/documentation/AudioVideo/Conceptual/iTuneSearchAPI/Searching.html#//apple_ref/doc/uid/TP40017632-CH5-SW1

I can get everything related to the movie, like its title, director, country but I can't get any subtitle information.

Using Bones and All as example: https://itunes.apple.com/us/movie/bones-and-all/id1651952453

I tried this: http://itunes.apple.com/search?term=bones+and+all&country=us&entity=movie&limit=1 I get info like "trackName: Bones And All"; "country":"USA", "currency":"USD", "releaseDate":"2022-11-23T08:00:00Z", etc. but

it doesn't show anything about subtitle languages available. Checking the iTunes page of the movie, there are more than 10 subtitle languages available.

Also, don't know if I have to use any "entity" or "attribute" parameters.


问:
AttributeError: 'builtin_function_or_method' object has no attribute 'acquire'
In this video: https://www.youtube.com/watch?v=HGOBQPFzWKo, around 4:16:00, it's talked about how to implement a lock for threading issues. But as opposed to the video, I get a debug message when trying to acquire the lock.

This is a part of the code I tried out for myself:

```<code>def increase(lock):
    global database_value

    lock.acquire()
    local_copy = database_value
    local_copy += 1
    time.sleep(0.1)
    database_value = local_copy
    lock.release()
</code>```

And this is the debug message:

```<code>Exception in thread Thread-32:
Traceback (most recent call last):
  File "C:\Users\Gebruiker\miniconda3\lib\threading.py", line 973, in _bootstrap_inner
Exception in thread Thread-33:
Traceback (most recent call last):
  File "C:\Users\Gebruiker\miniconda3\lib\threading.py", line 973, in _bootstrap_inner
    self.run()
  File "C:\Users\Gebruiker\miniconda3\lib\threading.py", line 910, in run
    self.run()
  File "C:\Users\Gebruiker\miniconda3\lib\threading.py", line 910, in run
    self._target(*self._args, **self._kwargs)
  File "C:\Users\Gebruiker\AppData\Local\Temp\ipykernel_75580\1082204269.py", line 14, in increase
    self._target(*self._args, **self._kwargs)
  File "C:\Users\Gebruiker\AppData\Local\Temp\ipykernel_75580\1082204269.py", line 14, in increase
AttributeError: 'builtin_function_or_method' object has no attribute 'acquire'
AttributeError: 'builtin_function_or_method' object has no attribute 'acquire'
</code>```

In the Jupyter Notebook, there seems to be raised an exception when I try to run the thread.

What's going wrong here?

Thanks in advance!

I tried to do what the video did, I expected it to work, but there's something not working in the thread apparently.

Body:
In this video: https://www.youtube.com/watch?v=HGOBQPFzWKo, around 4:16:00, it's talked about how to implement a lock for threading issues. But as opposed to the video, I get a debug message when trying to acquire the lock.

This is a part of the code I tried out for myself:

def increase(lock):
    global database_value

    lock.acquire()
    local_copy = database_value
    local_copy += 1
    time.sleep(0.1)
    database_value = local_copy
    lock.release()

And this is the debug message:

Exception in thread Thread-32:
Traceback (most recent call last):
  File "C:\Users\Gebruiker\miniconda3\lib\threading.py", line 973, in _bootstrap_inner
Exception in thread Thread-33:
Traceback (most recent call last):
  File "C:\Users\Gebruiker\miniconda3\lib\threading.py", line 973, in _bootstrap_inner
    self.run()
  File "C:\Users\Gebruiker\miniconda3\lib\threading.py", line 910, in run
    self.run()
  File "C:\Users\Gebruiker\miniconda3\lib\threading.py", line 910, in run
    self._target(*self._args, **self._kwargs)
  File "C:\Users\Gebruiker\AppData\Local\Temp\ipykernel_75580\1082204269.py", line 14, in increase
    self._target(*self._args, **self._kwargs)
  File "C:\Users\Gebruiker\AppData\Local\Temp\ipykernel_75580\1082204269.py", line 14, in increase
AttributeError: 'builtin_function_or_method' object has no attribute 'acquire'
AttributeError: 'builtin_function_or_method' object has no attribute 'acquire'

In the Jupyter Notebook, there seems to be raised an exception when I try to run the thread.

What's going wrong here?

Thanks in advance!

I tried to do what the video did, I expected it to work, but there's something not working in the thread apparently.


问:
How to fix Invalid OperationException: Multiple constructors accepting all given argument types have been found in type 'System.Collections.Generic
I have seen variations to this question asked. But none of the answers seem to help me.
When trying to view a list of roles in my view after hitting the AddOrRemoveUsers  button(see picture)

I get the following error message.

I cant find where the multiple constructors error seem to be. Am I missing something.

```<code>
@page
@using ThreeTierAdvisementApp.Areas.Identity.Pages.Account.Administration
@using ThreeTierAdvisementApp.Data
@model List<UserRole>

<form method="post">
    <div class="card">
        <div class="card-header">
            <h2>Add or remove users from this role</h2>
        </div>
        <div class="card-body">
      @for(int i = 0; i<Model.Count; i++){
                <div class="form-check m-1">
                    <input asp-for="@Model[i].IsSelected" class="form-check-input" />
                    <label class="form-check-label">
                        @Model[i].UserName
                    </label>
                </div>
      }

        </div>
        <div class="card-footer">
            <input type="submit" value="Update" class="btn btn-primary"
                   style="width:auto" />
            <a asp-action="EditRole" asp-route-id="UserId"
               class="btn btn-primary" style="width:auto">Cancel</a>
        </div>
    </div>
</form>
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using ThreeTierAdvisementApp.Data;

namespace ThreeTierAdvisementApp.Areas.Identity.Pages.Account.Administration
{
    public class EditUsersInRoleModel : PageModel
    {
        private readonly RoleManager<IdentityRole> _roleManager;
        private readonly UserManager<DefaultUser> _userManager;

        public EditUsersInRoleModel(RoleManager<IdentityRole> roleManager, UserManager<DefaultUser> userManager)
        {
            _roleManager = roleManager;
            _userManager = userManager;
        }

        [BindProperty]
        public UserRole RoleView { get; set; }

        public async Task<IActionResult> OnGet(string roleId)
        {
            RoleView = new UserRole { UserId = roleId };
            var role = await _roleManager.FindByIdAsync(roleId);
            if (role == null)
            {
                return NotFound();
            }

            var model = new List<UserRole>();

            foreach (var user in _userManager.Users)
            {
                var userRoleViewModel = new UserRole
                {
                    UserId = user.Id,
                    UserName = user.UserName,
                };

                if (await _userManager.IsInRoleAsync(user, role.Name))
                {
                    userRoleViewModel.IsSelected = true;
                }
                else
                {
                    userRoleViewModel.IsSelected = false;
                }
                model.Add(userRoleViewModel);
            }
            return Page();
        }
    }
}
using Microsoft.AspNetCore.Identity;
using System.Security.Principal;

namespace ThreeTierAdvisementApp.Data
{
    public class UserRole
    {

        public string UserId { get; set; }
        public string UserName { get; set; }
        public bool IsSelected { get; set; }

    }
}

</code>```

I am using asp.net 6 Razor page pattern but all the examples online are using the MVC pattern. Would appreciate some feedback on how to handle this.

Body:
I have seen variations to this question asked. But none of the answers seem to help me.
When trying to view a list of roles in my view after hitting the AddOrRemoveUsers  button(see picture)

I get the following error message.

I cant find where the multiple constructors error seem to be. Am I missing something.

@page
@using ThreeTierAdvisementApp.Areas.Identity.Pages.Account.Administration
@using ThreeTierAdvisementApp.Data
@model List<UserRole>

<form method="post">

Add or remove users from this role

      @for(int i = 0; i<Model.Count; i++){

                    <input asp-for="@Model[i].IsSelected" class="form-check-input" />

                        @Model[i].UserName

      }

            <input type="submit" value="Update" class="btn btn-primary"
                   style="width:auto" />
            Cancel

</form>
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using ThreeTierAdvisementApp.Data;

namespace ThreeTierAdvisementApp.Areas.Identity.Pages.Account.Administration
{
    public class EditUsersInRoleModel : PageModel
    {
        private readonly RoleManager<IdentityRole> _roleManager;
        private readonly UserManager<DefaultUser> _userManager;

        public EditUsersInRoleModel(RoleManager<IdentityRole> roleManager, UserManager<DefaultUser> userManager)
        {
            _roleManager = roleManager;
            _userManager = userManager;
        }

        [BindProperty]
        public UserRole RoleView { get; set; }

        public async Task<IActionResult> OnGet(string roleId)
        {
            RoleView = new UserRole { UserId = roleId };
            var role = await _roleManager.FindByIdAsync(roleId);
            if (role == null)
            {
                return NotFound();
            }

            var model = new List<UserRole>();

            foreach (var user in _userManager.Users)
            {
                var userRoleViewModel = new UserRole
                {
                    UserId = user.Id,
                    UserName = user.UserName,
                };

                if (await _userManager.IsInRoleAsync(user, role.Name))
                {
                    userRoleViewModel.IsSelected = true;
                }
                else
                {
                    userRoleViewModel.IsSelected = false;
                }
                model.Add(userRoleViewModel);
            }
            return Page();
        }
    }
}
using Microsoft.AspNetCore.Identity;
using System.Security.Principal;

namespace ThreeTierAdvisementApp.Data
{
    public class UserRole
    {

        public string UserId { get; set; }
        public string UserName { get; set; }
        public bool IsSelected { get; set; }

    }
}

I am using asp.net 6 Razor page pattern but all the examples online are using the MVC pattern. Would appreciate some feedback on how to handle this.


问:
Problems installing Node.JS 10 or later on Linux MInt
World!
I'm following a step by step tutorial on how to install React.Js on Linux Mint. If you wish, you can check out the tutorial at this link.
When I reach the step:
sudo npm install -g create-react-app
I get the following message from the terminal:
node: /lib/x86_64-linux-gnu/libc.so.6: versionGLIBC_2.28' not found (required by node)
`

Please, how can I find my ideal version of Node.Js that meets my needs (Node.Js 10 or higher) and how to resolve this message?

Some details about my OS:

Linux Mint 19.3 Cinnamon;

4.4.8 Cinnamon version;

5.4.0-135-generic Kernel.

Also, I'm having troubles for updating my OS but this is another topic and I'm just a curious newbie.

(fail) With apt-get
`

```<code>$ sudo apt-get install -y nodejs
Lendo listas de pacotes... Pronto
Construindo árvore de dependências
Lendo informação de estado... Pronto
nodejs is already the newest version (19.3.0-deb-1nodesource1).
0 pacotes atualizados, 0 pacotes novos instalados, 0 a serem removidos e 0 não atualizados.
$ node -v
node: /lib/x86_64-linux-gnu/libc.so.6: version `GLIBC_2.28' not found (required by node)
$ npm -v
node: /lib/x86_64-linux-gnu/libc.so.6: version `GLIBC_2.28' not found (required by node)
</code>```

2. (fail) With nvm because my machine don't found 'nvm' deb name. 3. (fail) curl -fsSL https://deb.nodesource.com/setup_19.x | sudo -E bash - &&

sudo apt-get install -y nodejs`

Body:
World!
I'm following a step by step tutorial on how to install React.Js on Linux Mint. If you wish, you can check out the tutorial at this link.
When I reach the step:
sudo npm install -g create-react-app
I get the following message from the terminal:
node: /lib/x86_64-linux-gnu/libc.so.6: versionGLIBC_2.28' not found (required by node)
`

Please, how can I find my ideal version of Node.Js that meets my needs (Node.Js 10 or higher) and how to resolve this message?

Some details about my OS:

Linux Mint 19.3 Cinnamon;

4.4.8 Cinnamon version;

5.4.0-135-generic Kernel.

Also, I'm having troubles for updating my OS but this is another topic and I'm just a curious newbie.

(fail) With apt-get
`

$ sudo apt-get install -y nodejs
Lendo listas de pacotes... Pronto
Construindo árvore de dependências
Lendo informação de estado... Pronto
nodejs is already the newest version (19.3.0-deb-1nodesource1).
0 pacotes atualizados, 0 pacotes novos instalados, 0 a serem removidos e 0 não atualizados.
$ node -v
node: /lib/x86_64-linux-gnu/libc.so.6: version `GLIBC_2.28' not found (required by node)
$ npm -v
node: /lib/x86_64-linux-gnu/libc.so.6: version `GLIBC_2.28' not found (required by node)

2. (fail) With nvm because my machine don't found 'nvm' deb name. 3. (fail) curl -fsSL https://deb.nodesource.com/setup_19.x | sudo -E bash - &&

sudo apt-get install -y nodejs`


问:
how to get notified when app is installed on system - flutter
I have an launcher app in flutter, and I need to update the applications list when some application get's installed or uninstalled. There's some way to "watch" the applications list change from the system using flutter?

I tried to use timer.periodic but it is not efficient because if I put a very small time like a second, it will keep updating the list all the time, but at the same time if I put a longer time like 5, or 10 seconds, it would take a long time to update if I just finished install something and go check in the app.


问:
Why Does React Re-Render Children with No Props when Parent Re-renders?
I understand how to avoid renders through memo, useMemo, and useCallback, my question is not about that. Rather:

Why does React, by default, choose to rerender children that don’t receive props, when the parent updates? It seems like bad separation of responsibility and unnecessary computation. It feels like the child rerender should be left to the jurisdiction of the child.

Why does React, by default, choose to rerender children whose props haven’t changed by value? Essentially I’m asking why aren’t useCallback and useMemo built in by default. Again it seems like an odd design decision.

I am not asking for solutions to make performant React code, rather trying to understand the design decisions. Kindly note most similar questions just have answers where people mention to use the 3 memoize functions. I would just like to understand why React was built the way it was. Thanks!


问:
Elastic Search Exception for a multi match query of type phrase when using a combination of number and alphabate without space
I am getting exception for below query:

```<code> "multi_match": {
                                    "query": "\"73a\"",
                                    "fields": [],
                                    "type": "phrase",
                                    "operator": "AND",
                                    "analyzer": "custom_analyzer",
                                    "slop": 0,
                                    "prefix_length": 0,
                                    "max_expansions": 50,
                                    "zero_terms_query": "NONE",
                                    "auto_generate_synonyms_phrase_query": true,
                                    "fuzzy_transpositions": true,
                                    "boost": 1.0
                                }

</code>```

Exception I am getting:

```<code>error" : {
    "root_cause" : [
      {
        "type" : "illegal_state_exception",
        "reason" : "field \"log_no.keyword\" was indexed without position data; cannot run SpanTermQuery (term=73)"
      },
      {
        "type" : "illegal_state_exception",
        "reason" : "field \"airplanes_data.keyword\" was indexed without position data; cannot run SpanTermQuery (term=73)"
      }
    ],
</code>```

Note: 1) When I am changing the type from "phrase" to "best_fields", I am not getting any error and getting proper results for "query": ""73a"".
2) Using type as "phrase" and giving space between number and alphabet ex: "query": ""73 a"" also gives results without error.

My question is why with type as "phrase", I am getting error when there is no space between a number and alphabet combo in a query. Ex - "query": ""443abx"", "query": ""73222aaa"".

I am new to elastic search. Any help is appreciated. Thanks :)

Body:
I am getting exception for below query:

 "multi_match": {
                                    "query": "\"73a\"",
                                    "fields": [],
                                    "type": "phrase",
                                    "operator": "AND",
                                    "analyzer": "custom_analyzer",
                                    "slop": 0,
                                    "prefix_length": 0,
                                    "max_expansions": 50,
                                    "zero_terms_query": "NONE",
                                    "auto_generate_synonyms_phrase_query": true,
                                    "fuzzy_transpositions": true,
                                    "boost": 1.0
                                }

Exception I am getting:

error" : {
    "root_cause" : [
      {
        "type" : "illegal_state_exception",
        "reason" : "field \"log_no.keyword\" was indexed without position data; cannot run SpanTermQuery (term=73)"
      },
      {
        "type" : "illegal_state_exception",
        "reason" : "field \"airplanes_data.keyword\" was indexed without position data; cannot run SpanTermQuery (term=73)"
      }
    ],

Note: 1) When I am changing the type from "phrase" to "best_fields", I am not getting any error and getting proper results for "query": ""73a"".
2) Using type as "phrase" and giving space between number and alphabet ex: "query": ""73 a"" also gives results without error.

My question is why with type as "phrase", I am getting error when there is no space between a number and alphabet combo in a query. Ex - "query": ""443abx"", "query": ""73222aaa"".

I am new to elastic search. Any help is appreciated. Thanks :)


问:
Pipenv Install in AWS Lambda Function
I am attempting to run the Algolia Docsearch scraper in a lambda environment at set intervals. Described here. I've got the docker container uploaded to ECR and attached to a lambda function, but when I run it the lambda errors because the entrypoint of the container is pipenv run python -m src.index. Pipenv is attempting to create a directory OSError: [Errno 30] Read-only file system: '/home/sbx_user1051'.

To combat this I created a EFS with an access point that the lambda has access to. The issue is the volume gets mounted at /mnt/... which is not where pipenv is trying to write. I'm a bit stuck here. Is there a clever way to get pipenv pointed at the EFS mount point?

Title: Pipenv Install in AWS Lambda Function


问:
wrong indentation for constructors using neovim on dart file
My setup is neovim 0.8.2 with the nvim-cmp plugin and the nvim-lsp source.
How can I change the autocompletion behaviour for constructors (in my case a dart file using the flutter framework).
For example, when the code line is

```<code>ListT
</code>```

my goal is to get

```<code>ListTile(
  _
)
</code>```

where _ should be the position of the cursor (with correct indentation level).
Currently, I get

```<code>ListTile(_)
</code>```

On enter, I get

```<code>ListTile(
  _)
</code>```

Body:
My setup is neovim 0.8.2 with the nvim-cmp plugin and the nvim-lsp source.
How can I change the autocompletion behaviour for constructors (in my case a dart file using the flutter framework).
For example, when the code line is

ListT

my goal is to get

ListTile(
  _
)

where _ should be the position of the cursor (with correct indentation level).
Currently, I get

ListTile(_)

On enter, I get

ListTile(
  _)


问:
trigger callback without user interaction with serenity-rs discord API crate
I'm working on making a simple discord bot which would take messages from user, and schedule them for dispatch later.

I first tried to make callback function poll until the specified time was elapsed. For obvious reasons, this is not very nice implementation since it's not very efficient when multiple function calls wait, and if process is dead then it has no way to resume with all messages intact.

My new idea is to serialize message struct using ser-de, store them into a file, and have a separate thread which would manage the dispatch. Then, on every startup I could also check for existence of file and load the unhandled messages.

My issues is that not being familiar with serenity (or discord API in general) I'm struggling to find how to send the message without it being magically mapped as a callback by the proc macro.

While I guess eventually Ill figure that out, I hope it's a common enough problem somebody already figured out.

Eventually my question boils down to:

How to procedurally send a message to a user or into a guild channel without it being a response to a user message

Is there a nice way to delegate something to be executed once after client initialization (similar to Druid crate AppLauncher's ::delegate method)

(it seems serenity-rs doesn't have it's own tag)


问:
I can't use "timeframe" argument when I'm using the "table.new" function in Pinescript
my indicator has a "timeframe" argument in the "indicator()" function.
for example:

indicator(title="RSI Heikinashi", format=format.price, precision=2, timeframe = "")

and it seems the "timeframe" is incompatible with the "table.new" function

because every time I use the "table.new" function, my code gives me a compilation error(like the one in my image)

I can solve the problem by removing the "timeframe" argument

but how can I use both of them in my indicator?


问:
to_mysql inserts more rows in SQL table than there are in pandas dataframe
So I have a MySQL database, let's call it "MySQLDB". When trying to create a new table (let's call it datatable) and insert data from a pandas dataframe, my code keeps adding rows to the SQL table, and I'm not sure if they are duplicates or not. For reference, there are around 50,000 rows in my pandas dataframe, but after running my code, the SQL table contains over 1 million rows. Note that I am using XAMPP to run a local MySQL server on which the database "MYSQLDB" is stored. Below is a simplified/generic version of what I am running. Note I have removed the port number and replaced it with generic [port] in this post.

```<code>import pandas as pd
from sqlalchemy import create_engine
import mysql.connector

pandas_db = pd.read_csv('filename.csv', index_col = [0])

engine = create_engine('mysql+mysqlconnector://root:@localhost:[port]/MySQLDB', echo=False)

pandas_db.to_sql(name='datatable', con=engine, if_exists = 'replace', chunksize = 100, index=False)
</code>```

Is something wrong with the code? Or could it be something to do with XAMPP or the way I set up my database? If there is anything I could improve, please let me know.

I haven't found any other good posts that describe having the same issue.

Body:
So I have a MySQL database, let's call it "MySQLDB". When trying to create a new table (let's call it datatable) and insert data from a pandas dataframe, my code keeps adding rows to the SQL table, and I'm not sure if they are duplicates or not. For reference, there are around 50,000 rows in my pandas dataframe, but after running my code, the SQL table contains over 1 million rows. Note that I am using XAMPP to run a local MySQL server on which the database "MYSQLDB" is stored. Below is a simplified/generic version of what I am running. Note I have removed the port number and replaced it with generic [port] in this post.

import pandas as pd
from sqlalchemy import create_engine
import mysql.connector

pandas_db = pd.read_csv('filename.csv', index_col = [0])

engine = create_engine('mysql+mysqlconnector://root:@localhost:[port]/MySQLDB', echo=False)

pandas_db.to_sql(name='datatable', con=engine, if_exists = 'replace', chunksize = 100, index=False)

Is something wrong with the code? Or could it be something to do with XAMPP or the way I set up my database? If there is anything I could improve, please let me know.

I haven't found any other good posts that describe having the same issue.


问:
Accessing mediaDevices.getUserMedia in InAppBrowser / Cordova
I'm building a Cordova hybrid app and trying to access the local camera & microphone using javascript mediaDevices.getUserMedia which is in a page on my website. I am opening it via InAppBrowser but access to the camera & microphone is not working.
The InappBorwser code is,

```<code>open_url = 'https://example.com/index.php';
var ref = cordova.InAppBrowser.open(open_url, "_blank", "location=no,zoom=no,EnableViewPortScale=no,toolbar=no");
</code>```

I have set the following Android user permissions in AndoidManifest.xml

```<code><uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.MICROPHONE" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.RECORD_VIDEO" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
</code>```

but I am seeing a permissions problem 'DOMException: Permission denied' when the following code is run.

```<code>navigator.mediaDevices.getUserMedia({ audio: true, video: true });
</code>```

I have tried running InAPPBrowser with '_system' and this works but it pops the browser window outside of the app which is not what I want. I have also tried setting app permissions manually in Android to no avail. If i run 'navigator.mediaDevices.getUserMedia({ audio: true, video: true });' locally in the app, access seems to be ok but I require to bring the code in via browsing.

Body:
I'm building a Cordova hybrid app and trying to access the local camera & microphone using javascript mediaDevices.getUserMedia which is in a page on my website. I am opening it via InAppBrowser but access to the camera & microphone is not working.
The InappBorwser code is,

open_url = 'https://example.com/index.php';
var ref = cordova.InAppBrowser.open(open_url, "_blank", "location=no,zoom=no,EnableViewPortScale=no,toolbar=no");

I have set the following Android user permissions in AndoidManifest.xml

<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.MICROPHONE" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.RECORD_VIDEO" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />

but I am seeing a permissions problem 'DOMException: Permission denied' when the following code is run.

navigator.mediaDevices.getUserMedia({ audio: true, video: true });

I have tried running InAPPBrowser with '_system' and this works but it pops the browser window outside of the app which is not what I want. I have also tried setting app permissions manually in Android to no avail. If i run 'navigator.mediaDevices.getUserMedia({ audio: true, video: true });' locally in the app, access seems to be ok but I require to bring the code in via browsing.


问:
How to add a marker where user tapps on map in Flutter?
I am making a community surveillance app in Flutter. My app uses the google_maps_flutter package to display maps and mongo_dart for providing database services.

Users should be able to report events/incidents that happen on a map, similar to how one can report an accident in Waze. After entering report mode the user is shown a full screen map, he/she must then tap on a location on the map, and a pin marker should drop where he/she tapped. Furthermore, I'd then like to extract the pin's lat/long values so I can later store them in a database so other users can be notified of the event taking place at that location.

How can I implement the marker to be dropped where the user taps and extract the lat/long information?

I have created a new page that is opened which displays a full screen map so users can select a location, the so-called report mode. I have not had much luck going further than this, unfortunately.


问:
Python, trouble installing "provers" via pip
I installed Python and pip today (so they are up-to-date).  I tried to install "provers", and got the following error message.

```<code>C:\Users\pace_nielsen>pip install provers
Collecting provers
  Using cached provers-0.1.18.tar.gz (23 kB)
  Preparing metadata (setup.py) ... done
Building wheels for collected packages: provers
  Building wheel for provers (setup.py) ... error
  error: subprocess-exited-with-error

  × python setup.py bdist_wheel did not run successfully.
  │ exit code: 1
  ╰─> [6 lines of output]
      C:\Users\pace_nielsen\AppData\Local\Programs\Python\Python311\Lib\site-packages\setuptools\installer.py:27: SetuptoolsDeprecationWarning: setuptools.installer is deprecated. Requirements should be satisfied by a PEP 517 installer.
        warnings.warn(
      running bdist_wheel
      running build
      running build_py
      error: [WinError 2] The system cannot find the file specified
      [end of output]

  note: This error originates from a subprocess, and is likely not a problem with pip.
  ERROR: Failed building wheel for provers
  Running setup.py clean for provers
Failed to build provers
Installing collected packages: provers
  Running setup.py install for provers ... error
  error: subprocess-exited-with-error

  × Running setup.py install for provers did not run successfully.
  │ exit code: 1
  ╰─> [8 lines of output]
      C:\Users\pace_nielsen\AppData\Local\Programs\Python\Python311\Lib\site-packages\setuptools\installer.py:27: SetuptoolsDeprecationWarning: setuptools.installer is deprecated. Requirements should be satisfied by a PEP 517 installer.
        warnings.warn(
      running install
      C:\Users\pace_nielsen\AppData\Local\Programs\Python\Python311\Lib\site-packages\setuptools\command\install.py:34: SetuptoolsDeprecationWarning: setup.py install is deprecated. Use build and pip and other standards-based tools.
        warnings.warn(
      running build
      running build_py
      error: [WinError 2] The system cannot find the file specified
      [end of output]

  note: This error originates from a subprocess, and is likely not a problem with pip.
error: legacy-install-failure

× Encountered error while trying to install package.
╰─> provers

note: This is an issue with the package mentioned above, not pip.
hint: See above for output from the failure.
</code>```

I've looked online for any clue how to fix this problem, and tried some basic trouble-shooting.  I've seen suggestions to install other packages (like cmake) and have done that without problem.  But I don't know what to try next.

Body:
I installed Python and pip today (so they are up-to-date).  I tried to install "provers", and got the following error message.

C:\Users\pace_nielsen>pip install provers
Collecting provers
  Using cached provers-0.1.18.tar.gz (23 kB)
  Preparing metadata (setup.py) ... done
Building wheels for collected packages: provers
  Building wheel for provers (setup.py) ... error
  error: subprocess-exited-with-error

  × python setup.py bdist_wheel did not run successfully.
  │ exit code: 1
  ╰─> [6 lines of output]
      C:\Users\pace_nielsen\AppData\Local\Programs\Python\Python311\Lib\site-packages\setuptools\installer.py:27: SetuptoolsDeprecationWarning: setuptools.installer is deprecated. Requirements should be satisfied by a PEP 517 installer.
        warnings.warn(
      running bdist_wheel
      running build
      running build_py
      error: [WinError 2] The system cannot find the file specified
      [end of output]

  note: This error originates from a subprocess, and is likely not a problem with pip.
  ERROR: Failed building wheel for provers
  Running setup.py clean for provers
Failed to build provers
Installing collected packages: provers
  Running setup.py install for provers ... error
  error: subprocess-exited-with-error

  × Running setup.py install for provers did not run successfully.
  │ exit code: 1
  ╰─> [8 lines of output]
      C:\Users\pace_nielsen\AppData\Local\Programs\Python\Python311\Lib\site-packages\setuptools\installer.py:27: SetuptoolsDeprecationWarning: setuptools.installer is deprecated. Requirements should be satisfied by a PEP 517 installer.
        warnings.warn(
      running install
      C:\Users\pace_nielsen\AppData\Local\Programs\Python\Python311\Lib\site-packages\setuptools\command\install.py:34: SetuptoolsDeprecationWarning: setup.py install is deprecated. Use build and pip and other standards-based tools.
        warnings.warn(
      running build
      running build_py
      error: [WinError 2] The system cannot find the file specified
      [end of output]

  note: This error originates from a subprocess, and is likely not a problem with pip.
error: legacy-install-failure

× Encountered error while trying to install package.
╰─> provers

note: This is an issue with the package mentioned above, not pip.
hint: See above for output from the failure.

I've looked online for any clue how to fix this problem, and tried some basic trouble-shooting.  I've seen suggestions to install other packages (like cmake) and have done that without problem.  But I don't know what to try next.


问:
Emitting a singal from QChartViews mouseMoveEvent
I am trying to pass the variable "event" from QChartView::mouseMoveEvent(QMouseEvent* event) to my MainWindow, so I can use it in my MainWindow. Since I am new to Qt and dont know exactly how to do it, I tried to subclass QChartView and override the function mouseMoveEvent, but I can only call static functions from this method, which are in my MainWindow class, but I need to call a non static function, so I can access variables and functions in my MainWindow class.
Is it possible to solve this problem with signals? My first attempt was this:

```<code>connect(this, ChartView::mouseMoveEvent(QMouseEvent* event), ui->chartView, SLOT(showInformation(QMouseEvent*)));
</code>```

But it didnt work. Is there a way to emit a signal which executes a function in my MainWindow every time when ChartView::mouseMoveEvent(QMouseEvent* event) is called?

Body:
I am trying to pass the variable "event" from QChartView::mouseMoveEvent(QMouseEvent* event) to my MainWindow, so I can use it in my MainWindow. Since I am new to Qt and dont know exactly how to do it, I tried to subclass QChartView and override the function mouseMoveEvent, but I can only call static functions from this method, which are in my MainWindow class, but I need to call a non static function, so I can access variables and functions in my MainWindow class.
Is it possible to solve this problem with signals? My first attempt was this:

connect(this, ChartView::mouseMoveEvent(QMouseEvent* event), ui->chartView, SLOT(showInformation(QMouseEvent*)));

But it didnt work. Is there a way to emit a signal which executes a function in my MainWindow every time when ChartView::mouseMoveEvent(QMouseEvent* event) is called?


问:
Matplotlib -- how to retreive polygons colors from choropleth map
I made the choropleth map using GeoPandas and Matplotlib. I want to add value labels to each polygon of the map in a way that font label color must be a contrast to polygon fill color (white on a darker color and black on a lighter).

Thus, I need to know every polygon's fill color. I found the solution (see minimal working example code below).

But I suppose that a more simple and clear solution exists, so I post this question with the hope to find it with community help.

import geopandas as gpd
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from itertools import islice, pairwise
from matplotlib.collections import PatchCollection

def contrast_color(color):
    d = 0
    r, g, b = (round(x*255, 0) for x in color[:3])
    luminance = 1 - (0.299 * r + 0.587 * g + 0.114 * b) / 255
    d = 0 if luminance < 0.5 else 255
    return (d, d, d)

def get_colors(ax):
    # get childrens
    # to obtain a PatchCollection
    _ = ax.axes.get_children()
    collection = _[0]  # suppose it is first element
    if not isinstance(collection, PatchCollection):
        raise TypeError("This is not Collection")
    # get information about polygons fill colors
    # .get_facecolors() returns ALL colors for ALL polygons
    # that belongs to one multipolygon
    # e. g. if we have two multipolygons,
    # and the first consists of two polygons
    # and second consists of one polygon
    # we obtain THREE colors
    poly_colors = collection.get_facecolors()
    return poly_colors.tolist()

gpd.read_file("https://gist.githubusercontent.com/ap-Codkelden/72f988e2bcc90ea3c6c9d6d989d8eb3b/raw/c91927bdb6b199c4dd6df6759200a5a1e4b820f0/obl_sample.geojson")
dfm['coords'] = [x[0] for x in dfm['geometry'].apply(lambda x: x.representative_point().coords[:])]

fig, ax = plt.subplots(1, figsize=(10, 6))
ax.axis('off')
ax.set_title('Title', fontdict={'fontsize': '12', 'fontweight' : '3'})
dfm.plot(
    ax=ax,
    column='Average', cmap='Blues_r',
    linewidth=0.5, edgecolor='k',
    scheme='FisherJenks', k=2,
    legend=True
)

out = []  # empty container for colors
# count polygons for every multipolygon
# since it can contains more than one
poly_count = dfm.geometry.apply(lambda x: len(x.geoms)).to_list()
poly_colors = get_colors(ax)
# we need split the polygon's colors list into sublists,
# where every sublist will contain all colors for
# every polygon that belongs to one multipolygon
slices = [(0, poly_count[0])] + [x for x in pairwise(np.cumsum(poly_count))]
# splitting
for s in slices:
    out.append(
        set(tuple(x) for x in islice(poly_colors, *s)),)
# remove transparensy info
out = [next(iter(x))[:3] for x in out]
dfm['color'] = [tuple([y/255 for y in x]) for x in map(contrast_color, out)]

for idx, row in dfm.iterrows():
    plt.annotate(
        f"{row['reg_en']}\n{row['Average']:.2f}",
        xy=row['coords'], horizontalalignment='center',
        color=row['color'], size=9)
```

Desired labels are:

Body:
I made the choropleth map using GeoPandas and Matplotlib. I want to add value labels to each polygon of the map in a way that font label color must be a contrast to polygon fill color (white on a darker color and black on a lighter).

Thus, I need to know every polygon's fill color. I found the solution (see minimal working example code below).

But I suppose that a more simple and clear solution exists, so I post this question with the hope to find it with community help.

import geopandas as gpd
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from itertools import islice, pairwise
from matplotlib.collections import PatchCollection

def contrast_color(color):
    d = 0
    r, g, b = (round(x*255, 0) for x in color[:3])
    luminance = 1 - (0.299 * r + 0.587 * g + 0.114 * b) / 255
    d = 0 if luminance < 0.5 else 255
    return (d, d, d)

def get_colors(ax):
    # get childrens
    # to obtain a PatchCollection
    _ = ax.axes.get_children()
    collection = _[0]  # suppose it is first element
    if not isinstance(collection, PatchCollection):
        raise TypeError("This is not Collection")
    # get information about polygons fill colors
    # .get_facecolors() returns ALL colors for ALL polygons
    # that belongs to one multipolygon
    # e. g. if we have two multipolygons,
    # and the first consists of two polygons
    # and second consists of one polygon
    # we obtain THREE colors
    poly_colors = collection.get_facecolors()
    return poly_colors.tolist()

gpd.read_file("https://gist.githubusercontent.com/ap-Codkelden/72f988e2bcc90ea3c6c9d6d989d8eb3b/raw/c91927bdb6b199c4dd6df6759200a5a1e4b820f0/obl_sample.geojson")
dfm['coords'] = [x[0] for x in dfm['geometry'].apply(lambda x: x.representative_point().coords[:])]

fig, ax = plt.subplots(1, figsize=(10, 6))
ax.axis('off')
ax.set_title('Title', fontdict={'fontsize': '12', 'fontweight' : '3'})
dfm.plot(
    ax=ax,
    column='Average', cmap='Blues_r',
    linewidth=0.5, edgecolor='k',
    scheme='FisherJenks', k=2,
    legend=True
)

out = []  # empty container for colors
# count polygons for every multipolygon
# since it can contains more than one
poly_count = dfm.geometry.apply(lambda x: len(x.geoms)).to_list()
poly_colors = get_colors(ax)
# we need split the polygon's colors list into sublists,
# where every sublist will contain all colors for
# every polygon that belongs to one multipolygon
slices = [(0, poly_count[0])] + [x for x in pairwise(np.cumsum(poly_count))]
# splitting
for s in slices:
    out.append(
        set(tuple(x) for x in islice(poly_colors, *s)),)
# remove transparensy info
out = [next(iter(x))[:3] for x in out]
dfm['color'] = [tuple([y/255 for y in x]) for x in map(contrast_color, out)]

for idx, row in dfm.iterrows():
    plt.annotate(
        f"{row['reg_en']}\n{row['Average']:.2f}",
        xy=row['coords'], horizontalalignment='center',
        color=row['color'], size=9)

Desired labels are:


问:
Runtime error when my DbContext file inherits from IdentityDbContext and not DbContext
I am trying to add authorization and and authentication to an ASP.NET entity framework program. I'm new to it and it's doing my head in.

I originally had a Context class that inherited from DbContext. Now that I'm trying to add security I have to inherit from IdentityDbContext but when I do this I get an exception in my Program.cs file on the line context.Database.EnsureCreated();

My DbContext which is SchoolContext.cs

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using AdvisementApp.Models;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;

namespace AdvisementApp.Data
{
public class SchoolContext : IdentityDbContext //Inheriting
{
    public SchoolContext (DbContextOptions<SchoolContext> options)
        : base(options)
    {
    }

    public DbSet<AdvisementApp.Models.Student> Students { get; set; } = default!;
    public DbSet<Advisor> Advisors { get; set; }
    public DbSet<Major> Majors { get; set; }
    public DbSet<Course> Courses { get; set; }
    public DbSet<StudentCourse> StudentCourses { get; set; }
    public DbSet<MajorCourse> MajorCourses { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Student>().ToTable("Student");
        modelBuilder.Entity<Course>().ToTable("Course");
        modelBuilder.Entity<StudentCourse>().ToTable("StudentCourse");
        modelBuilder.Entity<Major>().ToTable("Major");
        modelBuilder.Entity<Advisor>().ToTable("Advisor");
        modelBuilder.Entity<MajorCourse>().ToTable("MajorCourse");

        modelBuilder.Entity<Advisor>()
           .HasMany(a => a.Students)
           .WithOne(s => s.Advisor)
           .HasForeignKey(s => s.AdvisorId);
    }
}
}
</code>```

Program.cs

```<code>using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using AdvisementApp.Data;
using Microsoft.AspNetCore.Identity;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddRazorPages();

builder.Services.AddDbContext<SchoolContext>(options =>
options.UseSqlite(builder.Configuration.GetConnectionString("SchoolContext") ?? throw new InvalidOperationException("Connection string 'SchoolContext' not found.")));
builder.Services.AddIdentity<IdentityUser, IdentityRole>().AddEntityFrameworkStores<SchoolContext>();
builder.Services.AddDatabaseDeveloperPageExceptionFilter();
builder.Services.AddControllersWithViews();
builder.Services.Configure<IdentityOptions>(options =>
{
// Password settings.
options.Password.RequireDigit = true;
options.Password.RequireLowercase = true;
options.Password.RequireNonAlphanumeric = true;
options.Password.RequireUppercase = true;
options.Password.RequiredLength = 6;
options.Password.RequiredUniqueChars = 1;

// Lockout settings.
options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(5);
options.Lockout.MaxFailedAccessAttempts = 5;
options.Lockout.AllowedForNewUsers = true;

// User settings.
options.User.AllowedUserNameCharacters =
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@+";
options.User.RequireUniqueEmail = false;
});

builder.Services.ConfigureApplicationCookie(options =>
{
// Cookie settings
options.Cookie.HttpOnly = true;
options.ExpireTimeSpan = TimeSpan.FromMinutes(5);

options.LoginPath = "/Identity/Account/Login";
options.AccessDeniedPath = "/Identity/Account/AccessDenied";
options.SlidingExpiration = true;
});
var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
else
{
app.UseDeveloperExceptionPage();
app.UseMigrationsEndPoint();
}

using (var scope = app.Services.CreateScope())
{
 var services = scope.ServiceProvider;

 var context = services.GetRequiredService<SchoolContext>();
 context.Database.EnsureCreated();//This is where I am getting the error.
 DbInitializer.Initialize(context);
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapDefaultControllerRoute();
});
app.UseAuthentication();
//app.UseAuthorization();

app.MapRazorPages();

app.Run();
</code>```

This is the error:

Am I intending to do something incorrectly?

Body:
I am trying to add authorization and and authentication to an ASP.NET entity framework program. I'm new to it and it's doing my head in.

I originally had a Context class that inherited from DbContext. Now that I'm trying to add security I have to inherit from IdentityDbContext but when I do this I get an exception in my Program.cs file on the line context.Database.EnsureCreated();

My DbContext which is SchoolContext.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using AdvisementApp.Models;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;

namespace AdvisementApp.Data
{
public class SchoolContext : IdentityDbContext //Inheriting
{
    public SchoolContext (DbContextOptions<SchoolContext> options)
        : base(options)
    {
    }

    public DbSet<AdvisementApp.Models.Student> Students { get; set; } = default!;
    public DbSet<Advisor> Advisors { get; set; }
    public DbSet<Major> Majors { get; set; }
    public DbSet<Course> Courses { get; set; }
    public DbSet<StudentCourse> StudentCourses { get; set; }
    public DbSet<MajorCourse> MajorCourses { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Student>().ToTable("Student");
        modelBuilder.Entity<Course>().ToTable("Course");
        modelBuilder.Entity<StudentCourse>().ToTable("StudentCourse");
        modelBuilder.Entity<Major>().ToTable("Major");
        modelBuilder.Entity<Advisor>().ToTable("Advisor");
        modelBuilder.Entity<MajorCourse>().ToTable("MajorCourse");

        modelBuilder.Entity<Advisor>()
           .HasMany(a => a.Students)
           .WithOne(s => s.Advisor)
           .HasForeignKey(s => s.AdvisorId);
    }
}
}

Program.cs

using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using AdvisementApp.Data;
using Microsoft.AspNetCore.Identity;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddRazorPages();

builder.Services.AddDbContext<SchoolContext>(options =>
options.UseSqlite(builder.Configuration.GetConnectionString("SchoolContext") ?? throw new InvalidOperationException("Connection string 'SchoolContext' not found.")));
builder.Services.AddIdentity<IdentityUser, IdentityRole>().AddEntityFrameworkStores<SchoolContext>();
builder.Services.AddDatabaseDeveloperPageExceptionFilter();
builder.Services.AddControllersWithViews();
builder.Services.Configure<IdentityOptions>(options =>
{
// Password settings.
options.Password.RequireDigit = true;
options.Password.RequireLowercase = true;
options.Password.RequireNonAlphanumeric = true;
options.Password.RequireUppercase = true;
options.Password.RequiredLength = 6;
options.Password.RequiredUniqueChars = 1;

// Lockout settings.
options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(5);
options.Lockout.MaxFailedAccessAttempts = 5;
options.Lockout.AllowedForNewUsers = true;

// User settings.
options.User.AllowedUserNameCharacters =
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@+";
options.User.RequireUniqueEmail = false;
});

builder.Services.ConfigureApplicationCookie(options =>
{
// Cookie settings
options.Cookie.HttpOnly = true;
options.ExpireTimeSpan = TimeSpan.FromMinutes(5);

options.LoginPath = "/Identity/Account/Login";
options.AccessDeniedPath = "/Identity/Account/AccessDenied";
options.SlidingExpiration = true;
});
var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
else
{
app.UseDeveloperExceptionPage();
app.UseMigrationsEndPoint();
}

using (var scope = app.Services.CreateScope())
{
 var services = scope.ServiceProvider;

 var context = services.GetRequiredService<SchoolContext>();
 context.Database.EnsureCreated();//This is where I am getting the error.
 DbInitializer.Initialize(context);
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapDefaultControllerRoute();
});
app.UseAuthentication();
//app.UseAuthorization();

app.MapRazorPages();

app.Run();

This is the error:

Am I intending to do something incorrectly?


问:
end to end testing React, puppeteer serve command fails
I am following the tutorial react e2e testing.

https://blog.logrocket.com/end-to-end-testing-react-jest-puppeteer/#:~:text=To%20run%20the%20end%2Dto,%2Dscripts%20test%20%2D%2DtestPathIgnorePatterns%3D.

I get stuck in the line serve -s buildserve command not working as shown in the attached image.

```<code>C:\tutorials\react-puppeteer>yarn global add serve
yarn global v1.22.19
[1/4] Resolving packages...
[2/4] Fetching packages...
[3/4] Linking dependencies...
[4/4] Building fresh packages...
success Installed "serve@14.1.2" with binaries:
      - serve
Done in 0.81s.

C:\tutorials\react-puppeteer>serve -s build
'serve' is not recognized as an internal or external command,
operable program or batch file.
</code>```

I am using windows 11 with vscode as my ide. My node version is 16.19.0. '

I have tried another stack overflow suggest which said using "npx serve -s" instead of "serve -s build" with no success.
'serve' is not recognized as an internal or external command to run react app

I was expecting that the server will run on localhost:5000 but that did not happen.

Body:
I am following the tutorial react e2e testing.

https://blog.logrocket.com/end-to-end-testing-react-jest-puppeteer/#:~:text=To%20run%20the%20end%2Dto,%2Dscripts%20test%20%2D%2DtestPathIgnorePatterns%3D.

I get stuck in the line serve -s buildserve command not working as shown in the attached image.

C:\tutorials\react-puppeteer>yarn global add serve
yarn global v1.22.19
[1/4] Resolving packages...
[2/4] Fetching packages...
[3/4] Linking dependencies...
[4/4] Building fresh packages...
success Installed "serve@14.1.2" with binaries:
      - serve
Done in 0.81s.

C:\tutorials\react-puppeteer>serve -s build
'serve' is not recognized as an internal or external command,
operable program or batch file.

I am using windows 11 with vscode as my ide. My node version is 16.19.0. '

I have tried another stack overflow suggest which said using "npx serve -s" instead of "serve -s build" with no success.
'serve' is not recognized as an internal or external command to run react app

I was expecting that the server will run on localhost:5000 but that did not happen.


问:
Typeorm - Is there any way to set null as default using escapequerywithparameters function?
I use escapeQueryWithParameters function which is belong to entityManager connection driver to set parameters to query. What I want is setting null for not given parameters dynamically.

Example:

query:

select * from table1 where status = :givenStatus and name = :givenName
```
<p>code:</p>
<pre class="lang-js prettyprint-override"><code>manager.connection.driver.escapeQueryWithParameters(query, {givanStatus: 1, givenName: 'john'}, {})
</code>```

result:

select * from table1 where status = 1 and name = 'john'
```
<p>I want to give parameters like:</p>
<pre class="lang-js prettyprint-override"><code>manager.connection.driver.escapeQueryWithParameters(query, {givanStatus: 1},{})
</code>```

and expected result:

select * from table1 where status = 1 and name is null
```
<p>actual result:</p>
<pre class="lang-sql prettyprint-override"><code>select * from table1 where status = 1 and name = :givenName
</code>```

any idea how to achieve this?

Thank you.

Body:
I use escapeQueryWithParameters function which is belong to entityManager connection driver to set parameters to query. What I want is setting null for not given parameters dynamically.

Example:

query:

select * from table1 where status = :givenStatus and name = :givenName

code:

manager.connection.driver.escapeQueryWithParameters(query, {givanStatus: 1, givenName: 'john'}, {})

result:

select * from table1 where status = 1 and name = 'john'

I want to give parameters like:

manager.connection.driver.escapeQueryWithParameters(query, {givanStatus: 1},{})

and expected result:

select * from table1 where status = 1 and name is null

actual result:

select * from table1 where status = 1 and name = :givenName

any idea how to achieve this?

Thank you.


问:
Bluetooth: high quality audio recording on Android possible?
As stated here, BT classic can only record audio with 8 kHz bitrate and a single channel.

Since there are numerous bluetooth headsets on the market with stereo microphones, I cannot believe there's not alternative to BT Audio with SCO. A2DP seems to do a much better job but is not bi-directional, i.e. can only used for playback and not recording if I'm not mistaken.

Is there an alternative that is compatible with Android versions below 13 (where BLE Audio is available)?

Please forgive me if this is a stupid question, I'm new to the field


问:
Rect rotating, surface is not. How do I fix this disconnect?
I have spent three days changing my code into OOP. Im completely new to python and pygame or coding in general. Many hours of trial and error have gone into this little bit I've got. Now i've hit a point where ive created a rectangle that is changing properly, but the Surface isn't rotating with the rect. I'll insert my code here and can someone tell me what i'm doing wrong. The general idea is, for my OOP/Sprites, I want to have ONE set of animation images/Sprite map, and simply ROTATE that to face the direction pressed. I can get the RECT to work, the surface always looks up. I am FULLY aware, I could make a batch of images/animations for [up/down/left/right] and have it cycle per key press and I did this once successfully but it seems EXCEPTIONALLY redundant. Can anyone work with me on this?

```<code># imports
import pygame
import sys

class Ant(pygame.sprite.Sprite):

    def __init__(self, pos_x, pos_y):
        super().__init__()
        self.image = pygame.image.load('../Invasive Ants/Images/Ants/Space Ants/Space Ant/SALU.png').convert_alpha()
        rotated_image = self.image
        self.rect = rotated_image.get_rect()
        self.angle = 0
        self.rect.center = [pos_x, pos_y]
        self.is_animating = False
        self.angle = 0

    # def animate(self):
        # self.is_animating = True

    def move(self):
        self.image = pygame.image.load('../Invasive Ants/Images/Ants/Space Ants/Space Ant/SALU.png').convert_alpha()
        rotated_image = self.image
        self.rect = rotated_image.get_rect()
        self.angle = 0
        ant_speed = 5

        if event.key == pygame.K_w:
            pygame.transform.rotate(rotated_image, 45)
            self.rect.centery -= ant_speed
            print('the ant moved up')

        if event.key == pygame.K_s:
            pygame.transform.rotate(rotated_image, 45)
            self.rect.centery += ant_speed
            print('the ant moved down')

        if event.key == pygame.K_a:
            pygame.transform.rotate(rotated_image, 45)
            self.rect.centerx -= ant_speed
            print('the ant moved left')

        if event.key == pygame.K_d:
            pygame.transform.rotate(rotated_image, 45)
            self.rect.centerx += ant_speed
            print('the ant moved right')
        return rotated_image

# game init
pygame.init()
clock = pygame.time.Clock()

# set up your game window
pygame.display.set_mode()
pygame.display.set_caption('Invasive Ants')
x, y = pygame.display.get_window_size()
game_window = pygame.display.set_mode((x, y))

# make groups
moving_ant = pygame.sprite.GroupSingle()

# make instance of object class -ex. ant = Ant()
player_ant = Ant(x/2, y/2)
moving_ant.add(moving_ant, player_ant)
# add instances to groups -ex. moving_ant.add(moving_ant,player)

# while true game loop
while True:

    # Check for game close
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

        # Check for key press
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_ESCAPE:
                pygame.quit()
                sys.exit()

            if event.key == pygame.K_w:
                player_ant.move()
                pygame.key.set_repeat(1, 10)

            if event.key == pygame.K_s:
                player_ant.move()
                pygame.key.set_repeat(1, 10)

            if event.key == pygame.K_a:
                player_ant.move()
                pygame.key.set_repeat(1, 10)

            if event.key == pygame.K_d:
                player_ant.move()
                pygame.key.set_repeat(1, 10)

    # make objects seen
    game_window.fill((65, 65, 65))
    moving_ant.draw(game_window)
    moving_ant.update()

    pygame.display.update()
    clock.tick(60)

</code>```

I have spent three days changing my code into OOP. Im completely new to python and pygame or coding in general. Many hours of trial and error have gone into this little bit I've got. Now i've hit a point where ive created a rectangle that is changing properly, but the Surface isn't rotating with the rect. I'll insert my code here and can someone tell me what i'm doing wrong. The general idea is, for my OOP/Sprites, I want to have ONE set of animation images/Sprite map, and simply ROTATE that to face the direction pressed. I can get the RECT to work, the surface always looks up. I am FULLY aware, I could make a batch of images/animations for [up/down/left/right] and have it cycle per key press and I did this once successfully but it seems EXCEPTIONALLY redundant. Can anyone work with me on this?

Body:
I have spent three days changing my code into OOP. Im completely new to python and pygame or coding in general. Many hours of trial and error have gone into this little bit I've got. Now i've hit a point where ive created a rectangle that is changing properly, but the Surface isn't rotating with the rect. I'll insert my code here and can someone tell me what i'm doing wrong. The general idea is, for my OOP/Sprites, I want to have ONE set of animation images/Sprite map, and simply ROTATE that to face the direction pressed. I can get the RECT to work, the surface always looks up. I am FULLY aware, I could make a batch of images/animations for [up/down/left/right] and have it cycle per key press and I did this once successfully but it seems EXCEPTIONALLY redundant. Can anyone work with me on this?

# imports
import pygame
import sys

class Ant(pygame.sprite.Sprite):

    def __init__(self, pos_x, pos_y):
        super().__init__()
        self.image = pygame.image.load('../Invasive Ants/Images/Ants/Space Ants/Space Ant/SALU.png').convert_alpha()
        rotated_image = self.image
        self.rect = rotated_image.get_rect()
        self.angle = 0
        self.rect.center = [pos_x, pos_y]
        self.is_animating = False
        self.angle = 0

    # def animate(self):
        # self.is_animating = True

    def move(self):
        self.image = pygame.image.load('../Invasive Ants/Images/Ants/Space Ants/Space Ant/SALU.png').convert_alpha()
        rotated_image = self.image
        self.rect = rotated_image.get_rect()
        self.angle = 0
        ant_speed = 5

        if event.key == pygame.K_w:
            pygame.transform.rotate(rotated_image, 45)
            self.rect.centery -= ant_speed
            print('the ant moved up')

        if event.key == pygame.K_s:
            pygame.transform.rotate(rotated_image, 45)
            self.rect.centery += ant_speed
            print('the ant moved down')

        if event.key == pygame.K_a:
            pygame.transform.rotate(rotated_image, 45)
            self.rect.centerx -= ant_speed
            print('the ant moved left')

        if event.key == pygame.K_d:
            pygame.transform.rotate(rotated_image, 45)
            self.rect.centerx += ant_speed
            print('the ant moved right')
        return rotated_image

# game init
pygame.init()
clock = pygame.time.Clock()

# set up your game window
pygame.display.set_mode()
pygame.display.set_caption('Invasive Ants')
x, y = pygame.display.get_window_size()
game_window = pygame.display.set_mode((x, y))

# make groups
moving_ant = pygame.sprite.GroupSingle()

# make instance of object class -ex. ant = Ant()
player_ant = Ant(x/2, y/2)
moving_ant.add(moving_ant, player_ant)
# add instances to groups -ex. moving_ant.add(moving_ant,player)

# while true game loop
while True:

    # Check for game close
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

        # Check for key press
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_ESCAPE:
                pygame.quit()
                sys.exit()

            if event.key == pygame.K_w:
                player_ant.move()
                pygame.key.set_repeat(1, 10)

            if event.key == pygame.K_s:
                player_ant.move()
                pygame.key.set_repeat(1, 10)

            if event.key == pygame.K_a:
                player_ant.move()
                pygame.key.set_repeat(1, 10)

            if event.key == pygame.K_d:
                player_ant.move()
                pygame.key.set_repeat(1, 10)

    # make objects seen
    game_window.fill((65, 65, 65))
    moving_ant.draw(game_window)
    moving_ant.update()

    pygame.display.update()
    clock.tick(60)

I have spent three days changing my code into OOP. Im completely new to python and pygame or coding in general. Many hours of trial and error have gone into this little bit I've got. Now i've hit a point where ive created a rectangle that is changing properly, but the Surface isn't rotating with the rect. I'll insert my code here and can someone tell me what i'm doing wrong. The general idea is, for my OOP/Sprites, I want to have ONE set of animation images/Sprite map, and simply ROTATE that to face the direction pressed. I can get the RECT to work, the surface always looks up. I am FULLY aware, I could make a batch of images/animations for [up/down/left/right] and have it cycle per key press and I did this once successfully but it seems EXCEPTIONALLY redundant. Can anyone work with me on this?


问:
Best way to create and run typescript files in a electron project with sveltekit
I recently started a project with this template (https://github.com/FractalHQ/sveltekit-electron).
However i noticed that in the src directory all typescript files seem to be treated as 'pages', indicated by a vite log [svelte] 11:45:18 PM [vite] page reload src/main.ts, hence its not running, as well as it would seem they get compiled to, well, im not very sure.., i would guess somewhere in the .sveltekit folder, however i cannot seem to find the compiled contents anywhere.

I would very much like to run typescript files, as well as rewrite the electron.cjs file to a typescript file.

I already did try some approaches, i tried very simply with tsc running tsc ./src/main.ts, and while it did sortof work, i would like it to be in some sort of directory, e.g compiled and also it had added the line ['default'] in font of all dependency imports, which I had to manually remove. All and all this is sortof doable, however a more hands off approach would be preferable, if possible.

How could I go about going around this problem ?


问:
Router to the hostname itself through Traefik instead of its ingress controller
I started creating infrastructure with guides from https://dockerswarm.rocks.
I have no previous experience with reverse proxies but I figured out how to route domain names to my Docker Swarm services ports like that:

```<code>api.dev.mydomain.com       -> 8080
web.dev.mydomain.com       -> 8081
portainer.dev.mydomain.com -> 9000
... etc.
</code>```

where dev.mydomain.com is my host name.

Another service I want to deploy is based on wordpress docker image that exposes port 80, but I want to route my host domain name which is dev.mydomain.com to this service. From what I understand the 80 and 443 are Traefik's entrypoints so I can't simply point Traefik's load balancer to these ports.

How can I configure Traefik to deploy wordpress on dev.mydomain.com?

Body:
I started creating infrastructure with guides from https://dockerswarm.rocks.
I have no previous experience with reverse proxies but I figured out how to route domain names to my Docker Swarm services ports like that:

api.dev.mydomain.com       -> 8080
web.dev.mydomain.com       -> 8081
portainer.dev.mydomain.com -> 9000
... etc.

where dev.mydomain.com is my host name.

Another service I want to deploy is based on wordpress docker image that exposes port 80, but I want to route my host domain name which is dev.mydomain.com to this service. From what I understand the 80 and 443 are Traefik's entrypoints so I can't simply point Traefik's load balancer to these ports.

How can I configure Traefik to deploy wordpress on dev.mydomain.com?


问:
I can't get error squiggles to work in VSCode
I have activated in the configuration the red underline on errors in C++ in VSC but it does not appear when I am programming, not even in errors as simple as forgetting a semicolon, and I do not understand why. Before it was working, but today I opened two files to write a program and there was no error signal, but the compiler detected it later.

This is what I have in the settings.json file:

{
    "workbench.colorTheme": "Default High Contrast",
    "workbench.iconTheme": "vs-minimal",
    "[python]": {
        "editor.formatOnType": true
    },
    "editor.tabSize": 2,
    "C_Cpp.errorSquiggles": "enabled",
    "C_Cpp.intelliSenseEngineFallback": "enabled",
    "C_Cpp.autocompleteAddParentheses": true
}
```

I have searched all over the configuration and searched several forums but have not found a solution to this error.

Body:
I have activated in the configuration the red underline on errors in C++ in VSC but it does not appear when I am programming, not even in errors as simple as forgetting a semicolon, and I do not understand why. Before it was working, but today I opened two files to write a program and there was no error signal, but the compiler detected it later.

This is what I have in the settings.json file:

{
    "workbench.colorTheme": "Default High Contrast",
    "workbench.iconTheme": "vs-minimal",
    "[python]": {
        "editor.formatOnType": true
    },
    "editor.tabSize": 2,
    "C_Cpp.errorSquiggles": "enabled",
    "C_Cpp.intelliSenseEngineFallback": "enabled",
    "C_Cpp.autocompleteAddParentheses": true
}

I have searched all over the configuration and searched several forums but have not found a solution to this error.


问:
mpdf not rendering some pdf images
I was building a pdf file from layout. PNG files rendered without problem. But when I tried to render JPG files, I failed. Tried locally, tried with link to file. No luck! But the thing is when I tried to render jpg files from example it rendered.

Here, the square before the tiger contains the failed image. Code is here:

```<code>require_once __DIR__ . '/vendor/autoload.php';

use Mpdf\Mpdf;

$mpdf = new Mpdf([
    'tempDir' => __DIR__ . '/tmp',
    'margin_left' => 20,
    'margin_right' => 15,
    'margin_top' => 5,
    'margin_bottom' => 25,
    'margin_header' => 10,
    'margin_footer' => 10,
    'table_error_report' => false,
    'table_error_report_param' => '',
    'allow_charset_conversion' => true,
    'showImageErrors' => true,
    'debug' => true,
]);
$mpdf->curlAllowUnsafeSslRequests = true;
$html = '
<div style="text-align: left; width: 100%;border: 1px solid blue">
            <img src="https://sgvsbws.mycontent.ch/IS111341/pb/thumbnail_onlinekatalog" style="border: 1px solid red">
            <img src="https://mpdf.github.io/files/images/tiger.jpg" width="150" style="border: 1px solid red">
        </div>';
$mpdf->WriteHTML($html);
$mpdf->Output();
exit();
</code>```

My environment: php8.1-fpm, nginx, mpdf8.1

Title: mpdf not rendering some pdf images

Body:
I was building a pdf file from layout. PNG files rendered without problem. But when I tried to render JPG files, I failed. Tried locally, tried with link to file. No luck! But the thing is when I tried to render jpg files from example it rendered.

Here, the square before the tiger contains the failed image. Code is here:

require_once __DIR__ . '/vendor/autoload.php';

use Mpdf\Mpdf;

$mpdf = new Mpdf([
    'tempDir' => __DIR__ . '/tmp',
    'margin_left' => 20,
    'margin_right' => 15,
    'margin_top' => 5,
    'margin_bottom' => 25,
    'margin_header' => 10,
    'margin_footer' => 10,
    'table_error_report' => false,
    'table_error_report_param' => '',
    'allow_charset_conversion' => true,
    'showImageErrors' => true,
    'debug' => true,
]);
$mpdf->curlAllowUnsafeSslRequests = true;
$html = '

';
$mpdf->WriteHTML($html);
$mpdf->Output();
exit();

My environment: php8.1-fpm, nginx, mpdf8.1


问:
How to wait the page load until the next click with Selenium Python
I trying to make the Selenium python click on each link that I got but I just wanna the code click on the next link after the page loads. Could someone help?

The time.sleep() doesn't work because each link has a different time to load.

```<code> for link in range(list_count, links_len):
    links[list_count].click()

</code>```

Body:
I trying to make the Selenium python click on each link that I got but I just wanna the code click on the next link after the page loads. Could someone help?

The time.sleep() doesn't work because each link has a different time to load.

 for link in range(list_count, links_len):
    links[list_count].click()


问:
Using GraphQL together with MongoDB and abstract classes throws an error while deserializing object
When I use GraphQL (hot chocolate) together with MongoDB and abstract classes, I receive the following error message:

```<code>An error occurred while deserializing the Resource property of class
MyClass:
Cannot create an instance of MySampleClass because it is an abstract class.
</code>```

MySampleClass is abstract but there is a registered type map. Querying data normally works, but using it together with a GraphQL throws the following exception:

```<code>at MongoDB.Bson.Serialization.BsonClassMapSerializer`1.DeserializeMemberValue(BsonDeserializationContext context, BsonMemberMap memberMap)
at MongoDB.Bson.Serialization.BsonClassMapSerializer`1.DeserializeClass(BsonDeserializationContext context)
at MongoDB.Bson.Serialization.BsonClassMapSerializer`1.Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
at MongoDB.Bson.Serialization.IBsonSerializerExtensions.Deserialize[TValue](IBsonSerializer`1 serializer, BsonDeserializationContext context)    at
MongoDB.Driver.Core.Operations.CursorBatchDeserializationHelper.DeserializeBatch[TDocument](RawBsonArray batch, IBsonSerializer`1 documentSerializer,
MessageEncoderSettings messageEncoderSettings)    at MongoDB.Driver.Core.Operations.FindOperation`1.CreateFirstCursorBatch(BsonDocument cursorDocument)
at MongoDB.Driver.Core.Operations.FindOperation`1.CreateCursor(IChannelSourceHandle channelSource, IChannelHandle channel, BsonDocument commandResult)    at
MongoDB.Driver.Core.Operations.FindOperation`1.ExecuteAsync(RetryableReadContext context, CancellationToken cancellationToken)    at
MongoDB.Driver.Core.Operations.FindOperation`1.ExecuteAsync(IReadBinding binding, CancellationToken cancellationToken)    at
MongoDB.Driver.OperationExecutor.ExecuteReadOperationAsync[TResult](IReadBinding binding, IReadOperation`1 operation, CancellationToken cancellationToken)    at
MongoDB.Driver.MongoCollectionImpl`1.ExecuteReadOperationAsync[TResult](IClientSessionHandle session, IReadOperation`1 operation, ReadPreference readPreference, CancellationToken cancellationToken)
at MongoDB.Driver.MongoCollectionImpl`1.UsingImplicitSessionAsync[TResult](Func`2 funcAsync, CancellationToken cancellationToken)
at MongoDB.Driver.IAsyncCursorSourceExtensions.ToListAsync[TDocument](IAsyncCursorSource`1 source, CancellationToken cancellationToken)
at HotChocolate.Data.MongoDb.MongoDbFindFluentExecutable`1.ToListAsync(CancellationToken cancellationToken)
at HotChocolate.Execution.Processing.Tasks.ResolverTask.ExecuteResolverPipelineAsync(CancellationToken cancellationToken)
at HotChocolate.Execution.Processing.Tasks.ResolverTask.TryExecuteAsync(CancellationToken cancellationToken)
</code>```

I've tried several types of registration and setting a deserialization context, but could not find any way to solve the problem.

Body:
When I use GraphQL (hot chocolate) together with MongoDB and abstract classes, I receive the following error message:

An error occurred while deserializing the Resource property of class
MyClass:
Cannot create an instance of MySampleClass because it is an abstract class.

MySampleClass is abstract but there is a registered type map. Querying data normally works, but using it together with a GraphQL throws the following exception:

at MongoDB.Bson.Serialization.BsonClassMapSerializer`1.DeserializeMemberValue(BsonDeserializationContext context, BsonMemberMap memberMap)
at MongoDB.Bson.Serialization.BsonClassMapSerializer`1.DeserializeClass(BsonDeserializationContext context)
at MongoDB.Bson.Serialization.BsonClassMapSerializer`1.Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
at MongoDB.Bson.Serialization.IBsonSerializerExtensions.Deserialize[TValue](IBsonSerializer`1 serializer, BsonDeserializationContext context)    at
MongoDB.Driver.Core.Operations.CursorBatchDeserializationHelper.DeserializeBatch[TDocument](RawBsonArray batch, IBsonSerializer`1 documentSerializer,
MessageEncoderSettings messageEncoderSettings)    at MongoDB.Driver.Core.Operations.FindOperation`1.CreateFirstCursorBatch(BsonDocument cursorDocument)
at MongoDB.Driver.Core.Operations.FindOperation`1.CreateCursor(IChannelSourceHandle channelSource, IChannelHandle channel, BsonDocument commandResult)    at
MongoDB.Driver.Core.Operations.FindOperation`1.ExecuteAsync(RetryableReadContext context, CancellationToken cancellationToken)    at
MongoDB.Driver.Core.Operations.FindOperation`1.ExecuteAsync(IReadBinding binding, CancellationToken cancellationToken)    at
MongoDB.Driver.OperationExecutor.ExecuteReadOperationAsync[TResult](IReadBinding binding, IReadOperation`1 operation, CancellationToken cancellationToken)    at
MongoDB.Driver.MongoCollectionImpl`1.ExecuteReadOperationAsync[TResult](IClientSessionHandle session, IReadOperation`1 operation, ReadPreference readPreference, CancellationToken cancellationToken)
at MongoDB.Driver.MongoCollectionImpl`1.UsingImplicitSessionAsync[TResult](Func`2 funcAsync, CancellationToken cancellationToken)
at MongoDB.Driver.IAsyncCursorSourceExtensions.ToListAsync[TDocument](IAsyncCursorSource`1 source, CancellationToken cancellationToken)
at HotChocolate.Data.MongoDb.MongoDbFindFluentExecutable`1.ToListAsync(CancellationToken cancellationToken)
at HotChocolate.Execution.Processing.Tasks.ResolverTask.ExecuteResolverPipelineAsync(CancellationToken cancellationToken)
at HotChocolate.Execution.Processing.Tasks.ResolverTask.TryExecuteAsync(CancellationToken cancellationToken)

I've tried several types of registration and setting a deserialization context, but could not find any way to solve the problem.