问:
How make automatic ScrollViewReader?
I made two calendars and set them to pick a date.

```<code>import SwiftUI

struct ListScreenView: View {

    @ObservedObject var calendar: CustomCalendar

    var body: some View {
        ZStack {
            VStack(spacing: 0) {
                HStack {
                    ButtonFilterView(calendar: calendar)
                    Spacer()
                }
                .padding(.bottom, 12)
                .background(Color.white)
                /// Here i'm trying to made this
                ScrollViewReader { value in
                    HorizontalCalendarView(calendar: calendar)
                        .onChange(of: calendar.currentDate, perform: { newValue in
                            withAnimation(.easeIn(duration: 0.2)) {
                                value.scrollTo(newValue, anchor: .leading)
                            }
                        })
                }

                ScrollView(showsIndicators: false) {
                    VStack(spacing: 20) {
                        Image(systemName: "text.below.photo.fill")
                            .resizable()
                            .frame(width: 290, height: 350)
                            .padding(32)
                            .overlay(RoundedRectangle(cornerRadius: 15, style: .continuous).stroke(lineWidth: 4))

                        Image(systemName: "text.below.photo.fill")
                            .resizable()
                            .frame(width: 290, height: 350)
                            .padding(32)
                            .overlay(RoundedRectangle(cornerRadius: 15, style: .continuous).stroke(lineWidth: 4))

                        Image(systemName: "text.below.photo.fill")
                            .resizable()
                            .frame(width: 290, height: 350)
                            .padding(32)
                            .overlay(RoundedRectangle(cornerRadius: 15, style: .continuous).stroke(lineWidth: 4))
                    }
                    .padding()
                }
            }
        }
    }
}

struct ListScreenView_Previews: PreviewProvider {
    static var previews: some View {
        ListScreenView(calendar: CustomCalendar())
    }
}
</code>```

When I click on the horizontal calendar, everything works. Date pressed to the left side:

But when I select a date on another calendar:

When returning to the screen, the date is not pressed to the left side:

I put the scrollViewHeader on purpose to change the date. But still doesn't work.

How can I make the date pressed to the left side when returning to the screen?

Title: How make automatic ScrollViewReader?

Body:
I made two calendars and set them to pick a date.

import SwiftUI

struct ListScreenView: View {

    @ObservedObject var calendar: CustomCalendar

    var body: some View {
        ZStack {
            VStack(spacing: 0) {
                HStack {
                    ButtonFilterView(calendar: calendar)
                    Spacer()
                }
                .padding(.bottom, 12)
                .background(Color.white)
                /// Here i'm trying to made this
                ScrollViewReader { value in
                    HorizontalCalendarView(calendar: calendar)
                        .onChange(of: calendar.currentDate, perform: { newValue in
                            withAnimation(.easeIn(duration: 0.2)) {
                                value.scrollTo(newValue, anchor: .leading)
                            }
                        })
                }

                ScrollView(showsIndicators: false) {
                    VStack(spacing: 20) {
                        Image(systemName: "text.below.photo.fill")
                            .resizable()
                            .frame(width: 290, height: 350)
                            .padding(32)
                            .overlay(RoundedRectangle(cornerRadius: 15, style: .continuous).stroke(lineWidth: 4))

                        Image(systemName: "text.below.photo.fill")
                            .resizable()
                            .frame(width: 290, height: 350)
                            .padding(32)
                            .overlay(RoundedRectangle(cornerRadius: 15, style: .continuous).stroke(lineWidth: 4))

                        Image(systemName: "text.below.photo.fill")
                            .resizable()
                            .frame(width: 290, height: 350)
                            .padding(32)
                            .overlay(RoundedRectangle(cornerRadius: 15, style: .continuous).stroke(lineWidth: 4))
                    }
                    .padding()
                }
            }
        }
    }
}

struct ListScreenView_Previews: PreviewProvider {
    static var previews: some View {
        ListScreenView(calendar: CustomCalendar())
    }
}

When I click on the horizontal calendar, everything works. Date pressed to the left side:

But when I select a date on another calendar:

When returning to the screen, the date is not pressed to the left side:

I put the scrollViewHeader on purpose to change the date. But still doesn't work.

How can I make the date pressed to the left side when returning to the screen?


来源: stackexchange

问:
Unity3D game freezes when sending an API request
I'm using an open-source game to write a script, that captures the screen frames in a collection and sends the collection to an API server.

Capturing works fine, but as soon as the API request fires, the game freezes for ~500ms. If I understand correctly, this request blocks the main thread.

I've tried to send the request in a different thread, but get some weird errors.

How can I send requests in a background, so it doesn't block the main thread?

Here's my code:

```<code>using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using UnityEngine;
using UnityEngine.Networking;
using System.Threading.Tasks;

public class Recorder : MonoBehaviour
{
    private float captureInterval = 1f / 24f;
    private readonly List<string> frames = new();

    async void Update()
    {
        if (Time.timeSinceLevelLoad >= captureInterval)
        {
            StartCoroutine(CaptureFrame());

            captureInterval = Time.timeSinceLevelLoad + (1f / 24f);

            if (frames.Count >= 120)
            {
                StartCoroutine(CommitFrames(frames));

                frames.Clear();
            }
        }
    }

    IEnumerator CaptureFrame()
    {
        yield return new WaitForEndOfFrame();

        Texture2D texture = ScreenCapture.CaptureScreenshotAsTexture();
        byte[] jpg = texture.EncodeToJPG();
        string base64 = Convert.ToBase64String(jpg);

        frames.Add(base64);

        Destroy(texture);
    }

    IEnumerator CommitFrames(List<string> framesData)
    {
        var payload = new CommitFramesData() { frames = framesData };

        var www = CreateRequest("http://my-api.test/api/frames", RequestType.POST, payload);

        yield return www.SendWebRequest();

        www.Dispose();
    }

    private UnityWebRequest CreateRequest(string path, RequestType type = RequestType.GET, object data = null)
    {
        var request = new UnityWebRequest(path, type.ToString());

        if (data != null)
        {
            var bodyRaw = Encoding.UTF8.GetBytes(JsonUtility.ToJson(data));
            request.uploadHandler = new UploadHandlerRaw(bodyRaw);
        }

        request.downloadHandler = new DownloadHandlerBuffer();
        request.SetRequestHeader("Content-Type", "application/json");

        return request;
    }
}

public enum RequestType
{
    GET = 0,
    POST = 1,
    PUT = 2
}

[Serializable]
class CommitFramesData
{
    public List<string> frames;
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm using an open-source game to write a script, that captures the screen frames in a collection and sends the collection to an API server.

Capturing works fine, but as soon as the API request fires, the game freezes for ~500ms. If I understand correctly, this request blocks the main thread.

I've tried to send the request in a different thread, but get some weird errors.

How can I send requests in a background, so it doesn't block the main thread?

Here's my code:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using UnityEngine;
using UnityEngine.Networking;
using System.Threading.Tasks;

public class Recorder : MonoBehaviour
{
    private float captureInterval = 1f / 24f;
    private readonly List<string> frames = new();

    async void Update()
    {
        if (Time.timeSinceLevelLoad >= captureInterval)
        {
            StartCoroutine(CaptureFrame());

            captureInterval = Time.timeSinceLevelLoad + (1f / 24f);

            if (frames.Count >= 120)
            {
                StartCoroutine(CommitFrames(frames));

                frames.Clear();
            }
        }
    }

    IEnumerator CaptureFrame()
    {
        yield return new WaitForEndOfFrame();

        Texture2D texture = ScreenCapture.CaptureScreenshotAsTexture();
        byte[] jpg = texture.EncodeToJPG();
        string base64 = Convert.ToBase64String(jpg);

        frames.Add(base64);

        Destroy(texture);
    }

    IEnumerator CommitFrames(List<string> framesData)
    {
        var payload = new CommitFramesData() { frames = framesData };

        var www = CreateRequest("http://my-api.test/api/frames", RequestType.POST, payload);

        yield return www.SendWebRequest();

        www.Dispose();
    }

    private UnityWebRequest CreateRequest(string path, RequestType type = RequestType.GET, object data = null)
    {
        var request = new UnityWebRequest(path, type.ToString());

        if (data != null)
        {
            var bodyRaw = Encoding.UTF8.GetBytes(JsonUtility.ToJson(data));
            request.uploadHandler = new UploadHandlerRaw(bodyRaw);
        }

        request.downloadHandler = new DownloadHandlerBuffer();
        request.SetRequestHeader("Content-Type", "application/json");

        return request;
    }
}

public enum RequestType
{
    GET = 0,
    POST = 1,
    PUT = 2
}

[Serializable]
class CommitFramesData
{
    public List<string> frames;
}


问:
Drone for target pursuit in unity
I've already done the player drone control, now I want to make a bot. The problem is that I don't understand a little how to determine the slope, turn and climb/decrease in height.
I would not like to change the current control method, since it works fine. Also, the bot always knows about the player's position.</p>
```<code>public class DroneFootballAI : MonoBehaviour
{
    public float minMaxPitch;
    public float minMaxRoll;
    public float yawPower;
    public Vector2 cyclic;
    public float pedals;
    public float throttle;
    public float lerpSpeed;
    public Rigidbody rb;
    public Transform playerTransform;
    public CheckNode checkNode;
    public FootballController footballController;

    private float _finalPitch;
    private float _finalRoll;
    private float _yaw;
    private float _finalYaw;
    private float _isMove;
    private List<DroneEngine> _engines;

    private void Awake()
    {
        rb = GetComponent<Rigidbody>();
        _engines = GetComponentsInChildren<DroneEngine>().ToList();
        checkNode = GetComponent<CheckNode>();
    }

    private void FixedUpdate()
    {
        if (footballController.isGameStart)
        {
            GetInput();
            DroneMove();
        }
    }

    private void GetInput()
    {
        _isMove = 0;
        cyclic.x = Input.GetAxis("Horizontal");
        cyclic.y = Input.GetAxis("Vertical");
        pedals = Input.GetAxis("Pedal");
        throttle = Input.GetAxis("Throttle");
        _isMove = cyclic.x + cyclic.y + pedals + throttle;
    }

    private void DroneMove()
    {
        foreach (var engine in _engines)
        {
            engine.UpdateEngine(rb, throttle);
        }

        float pitch = cyclic.y * minMaxPitch;
        float roll = -cyclic.x * minMaxRoll;
        _yaw += pedals * yawPower;

        _finalPitch = Mathf.Lerp(_finalPitch, pitch, Time.deltaTime * lerpSpeed);
        _finalRoll = Mathf.Lerp(_finalRoll, roll, Time.deltaTime * lerpSpeed);
        _finalYaw = Mathf.Lerp(_finalYaw, _yaw, Time.deltaTime * lerpSpeed);

        Quaternion rot = Quaternion.Euler(_finalPitch, _finalYaw, _finalRoll);
        rb.MoveRotation(rot);
    }
}
</code>```

Title: Drone for target pursuit in unity

Body:
I've already done the player drone control, now I want to make a bot. The problem is that I don't understand a little how to determine the slope, turn and climb/decrease in height.
I would not like to change the current control method, since it works fine. Also, the bot always knows about the player's position.

public class DroneFootballAI : MonoBehaviour
{
    public float minMaxPitch;
    public float minMaxRoll;
    public float yawPower;
    public Vector2 cyclic;
    public float pedals;
    public float throttle;
    public float lerpSpeed;
    public Rigidbody rb;
    public Transform playerTransform;
    public CheckNode checkNode;
    public FootballController footballController;

    private float _finalPitch;
    private float _finalRoll;
    private float _yaw;
    private float _finalYaw;
    private float _isMove;
    private List<DroneEngine> _engines;

    private void Awake()
    {
        rb = GetComponent<Rigidbody>();
        _engines = GetComponentsInChildren<DroneEngine>().ToList();
        checkNode = GetComponent<CheckNode>();
    }

    private void FixedUpdate()
    {
        if (footballController.isGameStart)
        {
            GetInput();
            DroneMove();
        }
    }

    private void GetInput()
    {
        _isMove = 0;
        cyclic.x = Input.GetAxis("Horizontal");
        cyclic.y = Input.GetAxis("Vertical");
        pedals = Input.GetAxis("Pedal");
        throttle = Input.GetAxis("Throttle");
        _isMove = cyclic.x + cyclic.y + pedals + throttle;
    }

    private void DroneMove()
    {
        foreach (var engine in _engines)
        {
            engine.UpdateEngine(rb, throttle);
        }

        float pitch = cyclic.y * minMaxPitch;
        float roll = -cyclic.x * minMaxRoll;
        _yaw += pedals * yawPower;

        _finalPitch = Mathf.Lerp(_finalPitch, pitch, Time.deltaTime * lerpSpeed);
        _finalRoll = Mathf.Lerp(_finalRoll, roll, Time.deltaTime * lerpSpeed);
        _finalYaw = Mathf.Lerp(_finalYaw, _yaw, Time.deltaTime * lerpSpeed);

        Quaternion rot = Quaternion.Euler(_finalPitch, _finalYaw, _finalRoll);
        rb.MoveRotation(rot);
    }
}


问:
TypeORM-NestJs join on Json column
I have jsonb column with linkId`s https://prnt.sc/I7Eq2pN8Kn9G

And I have links table https://prnt.sc/ewH1wU9_sFQa

How do i build a query to fetch links using join?

```<code>const results = await this.CollectionRepository.createQueryBuilder('t1')
        .innerJoinAndMapMany(
          't1.Id',
          LinksEntity,
          't2',
          `t2.Id = t1.links->'$.linkId'`,
        )
        .where('t1.Id = :Id', { Id: id })
        .getMany()
        .catch((err) => console.log(err));
</code>```

Result:

No operator matches the given name and argument types. You might need to add explicit type casts.

Title: TypeORM-NestJs join on Json column

Body:
I have jsonb column with linkId`s https://prnt.sc/I7Eq2pN8Kn9G

And I have links table https://prnt.sc/ewH1wU9_sFQa

How do i build a query to fetch links using join?

const results = await this.CollectionRepository.createQueryBuilder('t1')
        .innerJoinAndMapMany(
          't1.Id',
          LinksEntity,
          't2',
          `t2.Id = t1.links->'$.linkId'`,
        )
        .where('t1.Id = :Id', { Id: id })
        .getMany()
        .catch((err) => console.log(err));

Result:

No operator matches the given name and argument types. You might need to add explicit type casts.


问:
Wordpress service is not showing in Traefik
I am trying to deploy Wordpress application on docker swarm stack, behind Traefik reverse proxy, I wanted to use Nginx for reverse proxying but as the the Wordpress is deployed with 2 replicas I am facing session time out issue, therefore I am trying the use Traefik instaed to configure sticky session later.

I have deployed the Traefik service successfully and can access the dashboard, but the Wordpress is not being proxied and it is not showing in the services list on the dashboard.

Traefik Dashboard Screenshot

Traefik Dashboard 2

Traefik Proxy yaml File:

```<code>
version: '3.3'

services:

  traefik:

    image: traefik:v2.2
    ports:
      - 80:80
      - 443:443
    deploy:
      placement:
        constraints:
          # Make the traefik service run only on the node with this label
          # as the node with it has the volume for the certificates

          - node.labels.traefik-public.traefik-public-certificates == true

      labels:

        - traefik.enable=true
        - traefik.docker.network=traefik-public
        - traefik.constraint-label=traefik-public
        - traefik.http.middlewares.admin-auth.basicauth.users=${USERNAME?Variable not set}:${HASHED_PASSWORD?Variable not set}
        - traefik.http.middlewares.https-redirect.redirectscheme.scheme=https
        - traefik.http.middlewares.https-redirect.redirectscheme.permanent=true
        - traefik.http.routers.traefik-public-http.rule=Host(`${DOMAIN?Variable not set}`)
        - traefik.http.routers.traefik-public-http.entrypoints=http
        - traefik.http.routers.traefik-public-http.middlewares=https-redirect
        - traefik.http.routers.traefik-public-https.rule=Host(`${DOMAIN?Variable not set}`)
        - traefik.http.routers.traefik-public-https.entrypoints=https
        - traefik.http.routers.traefik-public-https.tls=true
        - traefik.http.routers.traefik-public-https.service=api@internal
        - traefik.http.routers.traefik-public-https.tls.certresolver=le
        - traefik.http.routers.traefik-public-https.middlewares=admin-auth
        - traefik.http.services.traefik-public.loadbalancer.server.port=8080
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock:ro
      - traefik-public-certificates:/certificates
    command:
      - --providers.docker
      - --providers.docker.constraints=Label(`traefik.constraint-label`, `traefik-public`)
      - --providers.docker.exposedbydefault=false
      - --providers.docker.swarmmode
      - --entrypoints.http.address=:80
      - --entrypoints.https.address=:443
      - --certificatesresolvers.le.acme.email=${EMAIL?Variable not set}
      - --certificatesresolvers.le.acme.storage=/certificates/acme.json
      - --certificatesresolvers.le.acme.tlschallenge=true
      - --accesslog
      - --log
      - --api

    networks:
      - traefik-public

volumes:
  traefik-public-certificates:

networks:
  traefik-public:
    external: true
</code>```

Wordpress yaml File:

```<code>
version: "3.4"
services:

  db:
    image:  mariadb
    secrets:
      - db_user
      - db_pass
    environment:
        MYSQL_ROOT_PASSWORD_FILE: /run/secrets/db_pass
        MYSQL_USER_FILE: /run/secrets/db_user
        MYSQL_PASSWORD_FILE: /run/secrets/db_pass
        MYSQL_DATABASE_NAME: wpdb
    ports:
      - 3306:3306
    networks:
      - backend
    volumes:
      - db-data:/var/lib/mysql
    deploy:
      replicas: 1
      restart_policy:
        condition: on-failure
        delay: 10s
        max_attempts: 3
        window: 60s
  wp:
    image: wordpress
    secrets:
      - db_user
      - db_pass
    depends_on:
      - db
    labels:
      - traefik.enable=true
      - traefik.constraint-label=traefik-public
      - traefik.docker.network=traefik-public
      - traefik.http.middlewares.https-redirect.redirectscheme.scheme=https
      - traefik.http.middlewares.https-redirect.redirectscheme.permanent=true
      - traefik.http.routers.wp.rule=Host(`example.com`)
      - traefik.http.routers.wp.entrypoints=http
      - traefik.http.routers.wp.middlewares=https-redirect
      - traefik.http.routers.wp-secured.rule=Host(`example.com`)
      - traefik.http.routers.wp-secured.entrypoints=https
      - traefik.http.routers.wp-secured.tls=true
      - traefik.http.routers.wp-secured.tls.certresolver=le
      - traefik.http.services.wp.loadbalancer.server.port=8080

    environment:
      WORDPRESS_DB_HOST: 192.168.20.30:3306 # node IP
      WORDPRESS_DB_USER_FILE: /run/secrets/db_user
      WORDPRESS_DB_PASSWORD_FILE: /run/secrets/db_pass
      WORDPRESS_DB_NAME: wpdb
    networks:
      - backend
      - traefik-public
    volumes:
      - wp-data:/var/www/html
    deploy:
      replicas: 2
      restart_policy:
        condition: on-failure
        delay: 10s
        max_attempts: 3
        window: 60s

networks:
  backend:
    external: false
  traefik-public:
    external: true
volumes:
  wp-data:
  db-data:

secrets:
  db_user:
    file: ./db_user.txt
  db_pass:
    file: ./db_pass.txt

```
```

Body:
I am trying to deploy Wordpress application on docker swarm stack, behind Traefik reverse proxy, I wanted to use Nginx for reverse proxying but as the the Wordpress is deployed with 2 replicas I am facing session time out issue, therefore I am trying the use Traefik instaed to configure sticky session later.

I have deployed the Traefik service successfully and can access the dashboard, but the Wordpress is not being proxied and it is not showing in the services list on the dashboard.

Traefik Dashboard Screenshot

Traefik Dashboard 2

Traefik Proxy yaml File:

version: '3.3'

services:

  traefik:

    image: traefik:v2.2
    ports:
      - 80:80
      - 443:443
    deploy:
      placement:
        constraints:
          # Make the traefik service run only on the node with this label
          # as the node with it has the volume for the certificates

          - node.labels.traefik-public.traefik-public-certificates == true

      labels:

        - traefik.enable=true
        - traefik.docker.network=traefik-public
        - traefik.constraint-label=traefik-public
        - traefik.http.middlewares.admin-auth.basicauth.users=${USERNAME?Variable not set}:${HASHED_PASSWORD?Variable not set}
        - traefik.http.middlewares.https-redirect.redirectscheme.scheme=https
        - traefik.http.middlewares.https-redirect.redirectscheme.permanent=true
        - traefik.http.routers.traefik-public-http.rule=Host(`${DOMAIN?Variable not set}`)
        - traefik.http.routers.traefik-public-http.entrypoints=http
        - traefik.http.routers.traefik-public-http.middlewares=https-redirect
        - traefik.http.routers.traefik-public-https.rule=Host(`${DOMAIN?Variable not set}`)
        - traefik.http.routers.traefik-public-https.entrypoints=https
        - traefik.http.routers.traefik-public-https.tls=true
        - traefik.http.routers.traefik-public-https.service=api@internal
        - traefik.http.routers.traefik-public-https.tls.certresolver=le
        - traefik.http.routers.traefik-public-https.middlewares=admin-auth
        - traefik.http.services.traefik-public.loadbalancer.server.port=8080
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock:ro
      - traefik-public-certificates:/certificates
    command:
      - --providers.docker
      - --providers.docker.constraints=Label(`traefik.constraint-label`, `traefik-public`)
      - --providers.docker.exposedbydefault=false
      - --providers.docker.swarmmode
      - --entrypoints.http.address=:80
      - --entrypoints.https.address=:443
      - --certificatesresolvers.le.acme.email=${EMAIL?Variable not set}
      - --certificatesresolvers.le.acme.storage=/certificates/acme.json
      - --certificatesresolvers.le.acme.tlschallenge=true
      - --accesslog
      - --log
      - --api

    networks:
      - traefik-public

volumes:
  traefik-public-certificates:

networks:
  traefik-public:
    external: true

Wordpress yaml File:

version: "3.4"
services:

  db:
    image:  mariadb
    secrets:
      - db_user
      - db_pass
    environment:
        MYSQL_ROOT_PASSWORD_FILE: /run/secrets/db_pass
        MYSQL_USER_FILE: /run/secrets/db_user
        MYSQL_PASSWORD_FILE: /run/secrets/db_pass
        MYSQL_DATABASE_NAME: wpdb
    ports:
      - 3306:3306
    networks:
      - backend
    volumes:
      - db-data:/var/lib/mysql
    deploy:
      replicas: 1
      restart_policy:
        condition: on-failure
        delay: 10s
        max_attempts: 3
        window: 60s
  wp:
    image: wordpress
    secrets:
      - db_user
      - db_pass
    depends_on:
      - db
    labels:
      - traefik.enable=true
      - traefik.constraint-label=traefik-public
      - traefik.docker.network=traefik-public
      - traefik.http.middlewares.https-redirect.redirectscheme.scheme=https
      - traefik.http.middlewares.https-redirect.redirectscheme.permanent=true
      - traefik.http.routers.wp.rule=Host(`example.com`)
      - traefik.http.routers.wp.entrypoints=http
      - traefik.http.routers.wp.middlewares=https-redirect
      - traefik.http.routers.wp-secured.rule=Host(`example.com`)
      - traefik.http.routers.wp-secured.entrypoints=https
      - traefik.http.routers.wp-secured.tls=true
      - traefik.http.routers.wp-secured.tls.certresolver=le
      - traefik.http.services.wp.loadbalancer.server.port=8080

    environment:
      WORDPRESS_DB_HOST: 192.168.20.30:3306 # node IP
      WORDPRESS_DB_USER_FILE: /run/secrets/db_user
      WORDPRESS_DB_PASSWORD_FILE: /run/secrets/db_pass
      WORDPRESS_DB_NAME: wpdb
    networks:
      - backend
      - traefik-public
    volumes:
      - wp-data:/var/www/html
    deploy:
      replicas: 2
      restart_policy:
        condition: on-failure
        delay: 10s
        max_attempts: 3
        window: 60s

networks:
  backend:
    external: false
  traefik-public:
    external: true
volumes:
  wp-data:
  db-data:

secrets:
  db_user:
    file: ./db_user.txt
  db_pass:
    file: ./db_pass.txt

```


问:
Xcode: Is there a way to stop the constantly recurring security prompt when building my project?
Is there a way to avoid the constantly recurring security prompt? It always occurs when I create a new version of my project in Xcode.

I have already allowed myself and "everyone" full access to the folder, but unfortunately that didn't help.
It would be great if I could configure my MacBook or Xcode so, that the security prompt doesn't occur anymore.

I am working on a MacBook Pro M1 with macOS Ventura and Xcode 14.2.


问:
how to check id TCB (Trusted computing base) is enabled in my linux
Trusted computing base (TCB) is the set of all hardware, firmware, and/or software components that are critical to its security, in the sense that bugs or vulnerabilities occurring inside the TCB might jeopardize the security properties of the entire system.
For using SGX DCAP attestation I need to enable TCB on my VM , question is that

how can I check if TCB is enabled?

if so what is the version?

If it is not enabled how can I install or enable it on my Virtual machine OS?


问:
Sonar exclude sonar.properties from all projects
Hi add I'd like to create a rule server ignore sonar.properties so people cannot define custom rules and exclude files, low code quality,...

Is there any manner to do that?

I've tried using Regexp On Filename Template, but I don't get anything. Anybody knows how this rule works? Is this a good solution?


问:
How to do unique constraint works with NULL value in MySQL5.6
I am looking for how to implement unique constraints with NULL check.

MySQL shouldn't allow multiple null value.

Job History:

id
deleted_at

1
null

2
null -> should give error during inserting  2nd row.


问:
Flutter: Error waiting for a debug connection: The log reader stopped unexpectedly. Error launching application on I2019
I'm trying to run my Flutter app on my physical device, it is a mobile phone named IQOO 9 SE but I keep getting this error. The app runs on other physical devices but the problem arises only on my device.
Is there a way to solve this problem.

```<code>#0      throwToolExit (package:flutter_tools/src/base/common.dart:10:3)
#1      RunCommand.runCommand (package:flutter_tools/src/commands/run.dart:615:9)
           <asynchronous suspension>
#2      FlutterCommand.run.<anonymous closure> (package:flutter_tools/src/runner/flutter_command.dart:1209:27)
           <asynchronous suspension>
#3      AppContext.run.<anonymous closure> (package:flutter_tools/src/base/context.dart:150:19)
          <asynchronous suspension>
#4      CommandRunner.runCommand
package:args/command_runner.dart:209
           <asynchronous suspension>
#5      FlutterCommandRunner.runCommand.<anonymous closure> (package:flutter_tools/src/runner/flutter_command_runner.dart:281:9)
           <asynchronous suspension>
#6      AppContext.run.<anonymous closure> (package:flutter_tools/src/base/context.dart:150:19)
         <asynchronous suspension>
#7      FlutterCommandRunner.runCommand (package:flutter_tools/src/runner/flutter_command_runner.dart:229:5)
           <asynchronous suspension>
#8      run.<anonymous closure>.<anonymous closure> (package:flutter_tools/runner.dart:62:9)
           <asynchronous suspension>
#9      AppContext.run.<anonymous closure> (package:flutter_tools/src/base/context.dart:150:19)
           <asynchronous suspension>
#10     main (package:flutter_tools/executable.dart:91:3)
           <asynchronous suspension>
</code>```

This is what I get in the debug console if I run it with Capturing Logs.

First I tried flutter clean and flutter pub get again.

I also tried killing the adb server and restarting it again.

I tried changing the package name of my app and running it.

After trying all that I realised the problem is with my phone so I performed a factory reset and still I got the same issue.

Body:
I'm trying to run my Flutter app on my physical device, it is a mobile phone named IQOO 9 SE but I keep getting this error. The app runs on other physical devices but the problem arises only on my device.
Is there a way to solve this problem.

#0      throwToolExit (package:flutter_tools/src/base/common.dart:10:3)
#1      RunCommand.runCommand (package:flutter_tools/src/commands/run.dart:615:9)
           <asynchronous suspension>
#2      FlutterCommand.run.<anonymous closure> (package:flutter_tools/src/runner/flutter_command.dart:1209:27)
           <asynchronous suspension>
#3      AppContext.run.<anonymous closure> (package:flutter_tools/src/base/context.dart:150:19)
          <asynchronous suspension>
#4      CommandRunner.runCommand
package:args/command_runner.dart:209
           <asynchronous suspension>
#5      FlutterCommandRunner.runCommand.<anonymous closure> (package:flutter_tools/src/runner/flutter_command_runner.dart:281:9)
           <asynchronous suspension>
#6      AppContext.run.<anonymous closure> (package:flutter_tools/src/base/context.dart:150:19)
         <asynchronous suspension>
#7      FlutterCommandRunner.runCommand (package:flutter_tools/src/runner/flutter_command_runner.dart:229:5)
           <asynchronous suspension>
#8      run.<anonymous closure>.<anonymous closure> (package:flutter_tools/runner.dart:62:9)
           <asynchronous suspension>
#9      AppContext.run.<anonymous closure> (package:flutter_tools/src/base/context.dart:150:19)
           <asynchronous suspension>
#10     main (package:flutter_tools/executable.dart:91:3)
           <asynchronous suspension>

This is what I get in the debug console if I run it with Capturing Logs.

First I tried flutter clean and flutter pub get again.

I also tried killing the adb server and restarting it again.

I tried changing the package name of my app and running it.

After trying all that I realised the problem is with my phone so I performed a factory reset and still I got the same issue.


问:
issue with middleware while deployment Nuxt app
Recently I have created Nuxt app with middleware for registration and authorization. My app is static site. After building I deployed it on Netlify. There is an authorization form so that after authorization you can go to the main page and if you haven't yet registered you can click on link in form and go to page with registration form. Problem is that after deployment clicking on the link does not take you to the registration page.
I created the link using NuxtLink. I have read that Nuxt app with middleware ought to be server-side rendering. If so, what hostings should I use for deployment my Nuxt app dnd write a backend for my app</p>


问:
How to group by an array of objects and keep the values of each group into an array using jquery
I have an array of objects. These objects need to be grouped based on the SiteName so that I can use it for my dataset inside chart.js. Below is the array of objects.

```<code> {
     "StaffName": "ABC",
     "SiteName": "Bangalore",
     "Year": 2020,
     "HeadCount": 4,
     "HeadCost": 125
 },
 {
     "StaffName": "ABC",
     "SiteName": "Bangalore",
     "Year": 2021,
     "HeadCount": 2,
     "HeadCost": 62.5
 },
 {
     "StaffName": "ABC",
     "SiteName": "Bangalore",
     "Year": 2022,
     "HeadCount": 1,
     "HeadCost": 31.25
 },
 {
     "StaffName": "ABC",
     "SiteName": "Bangalore",
     "Year": 2023,
     "HeadCount": 6,
     "HeadCost": 187.5
 },
 {
     "StaffName": "ABC",
     "SiteName": "Bangalore",
     "Year": 2024,
     "HeadCount": 10,
     "HeadCost": 312.5
 },
 {
     "StaffName": "ABC",
     "SiteName": "Bangalore",
     "Year": 2025,
     "HeadCount": 5,
     "HeadCost": 156.25
 },
 {
     "StaffName": "XYZ",
     "SiteName": "Pune",
     "Year": 2020,
     "HeadCount": 1,
     "HeadCost": 151.289
 },
 {
     "StaffName": "XYZ",
     "SiteName": "Pune",
     "Year": 2021,
     "HeadCount": 1,
     "HeadCost": 151.289
 },
 {
     "StaffName": "XYZ",
     "SiteName": "Pune",
     "Year": 2022,
     "HeadCount": 1,
     "HeadCost": 151.289
 },
 {
     "StaffName": "XYZ",
     "SiteName": "Pune",
     "Year": 2023,
     "HeadCount": 1,
     "HeadCost": 151.289
 },
 {
     "StaffName": "XYZ",
     "SiteName": "Pune",
     "Year": 2024,
     "HeadCount": 0,
     "HeadCost": 0
 },
 {
     "StaffName": "XYZ",
     "SiteName": "Pune",
     "Year": 2025,
     "HeadCount": 0,
     "HeadCost": 0
 }
];
</code>```

I want to group it by SiteName in such a way that it creates new object with each sitename and all headcosts that belongs to that sitename. Something like below.

```<code>[{
    label: 'Bangalore',
    data: [125.0, 62.5, 31.3, 187.5, 312.5, 156.3], // all Head costs of Bangalore
 },
 {
   label: 'Pune',
   data: [151.3, 151.3, 151.3, 151.3,0,0], // all Head costs of Pune
}];
</code>```

I am trying to create a stacked bar chart using chart.js and need such kind of output to use as my dataset like below.

```<code>myChart = new Chart(ctx, {
                            type: 'bar',
                            data: {
                                labels: uniqueYears,
                                **datasets: [{
                                    label: 'Bangalore',
                                    data: [125.0, 62.5, 31.3, 187.5, 312.5, 156.3],
                                }, {
                                    label: 'Pune',
                                    data: [151.3, 151.3, 151.3,151.3,0,0],
                                }],**
                            },
                            options: {
                                plugins: {
                                    legend: {
                                        display: true,
                                        position: 'right',
                                        align: 'center',
                                        labels: {
                                            //color: 'rgb(255, 99, 132)'
                                        }
                                    },
                                    title: {
                                        display: true,
                                        text: chartTitle
                                    },
                                    scales: {
                                        x: {
                                            stacked: true
                                        },
                                        y: {
                                            stacked: true
                                        }
                                    }
                                }
                            }
                        });
</code>```

Body:
I have an array of objects. These objects need to be grouped based on the SiteName so that I can use it for my dataset inside chart.js. Below is the array of objects.

 {
     "StaffName": "ABC",
     "SiteName": "Bangalore",
     "Year": 2020,
     "HeadCount": 4,
     "HeadCost": 125
 },
 {
     "StaffName": "ABC",
     "SiteName": "Bangalore",
     "Year": 2021,
     "HeadCount": 2,
     "HeadCost": 62.5
 },
 {
     "StaffName": "ABC",
     "SiteName": "Bangalore",
     "Year": 2022,
     "HeadCount": 1,
     "HeadCost": 31.25
 },
 {
     "StaffName": "ABC",
     "SiteName": "Bangalore",
     "Year": 2023,
     "HeadCount": 6,
     "HeadCost": 187.5
 },
 {
     "StaffName": "ABC",
     "SiteName": "Bangalore",
     "Year": 2024,
     "HeadCount": 10,
     "HeadCost": 312.5
 },
 {
     "StaffName": "ABC",
     "SiteName": "Bangalore",
     "Year": 2025,
     "HeadCount": 5,
     "HeadCost": 156.25
 },
 {
     "StaffName": "XYZ",
     "SiteName": "Pune",
     "Year": 2020,
     "HeadCount": 1,
     "HeadCost": 151.289
 },
 {
     "StaffName": "XYZ",
     "SiteName": "Pune",
     "Year": 2021,
     "HeadCount": 1,
     "HeadCost": 151.289
 },
 {
     "StaffName": "XYZ",
     "SiteName": "Pune",
     "Year": 2022,
     "HeadCount": 1,
     "HeadCost": 151.289
 },
 {
     "StaffName": "XYZ",
     "SiteName": "Pune",
     "Year": 2023,
     "HeadCount": 1,
     "HeadCost": 151.289
 },
 {
     "StaffName": "XYZ",
     "SiteName": "Pune",
     "Year": 2024,
     "HeadCount": 0,
     "HeadCost": 0
 },
 {
     "StaffName": "XYZ",
     "SiteName": "Pune",
     "Year": 2025,
     "HeadCount": 0,
     "HeadCost": 0
 }
];

I want to group it by SiteName in such a way that it creates new object with each sitename and all headcosts that belongs to that sitename. Something like below.

[{
    label: 'Bangalore',
    data: [125.0, 62.5, 31.3, 187.5, 312.5, 156.3], // all Head costs of Bangalore
 },
 {
   label: 'Pune',
   data: [151.3, 151.3, 151.3, 151.3,0,0], // all Head costs of Pune
}];

I am trying to create a stacked bar chart using chart.js and need such kind of output to use as my dataset like below.

myChart = new Chart(ctx, {
                            type: 'bar',
                            data: {
                                labels: uniqueYears,
                                **datasets: [{
                                    label: 'Bangalore',
                                    data: [125.0, 62.5, 31.3, 187.5, 312.5, 156.3],
                                }, {
                                    label: 'Pune',
                                    data: [151.3, 151.3, 151.3,151.3,0,0],
                                }],**
                            },
                            options: {
                                plugins: {
                                    legend: {
                                        display: true,
                                        position: 'right',
                                        align: 'center',
                                        labels: {
                                            //color: 'rgb(255, 99, 132)'
                                        }
                                    },
                                    title: {
                                        display: true,
                                        text: chartTitle
                                    },
                                    scales: {
                                        x: {
                                            stacked: true
                                        },
                                        y: {
                                            stacked: true
                                        }
                                    }
                                }
                            }
                        });


问:
How to add watermark with delay in FFmpeg
Am trying to put a gif file in all the edges of the video. So am using this command

```<code>ffmpeg  -y -i film.mp4 -stream_loop -1 -i gif.gif -filter_complex \
"[1]colorchannelmixer=aa=0.8,scale=iw*1:-1[a];[0][a]overlay=
x='if(lt(mod(t\,16)\,8)\,W-w-W*10/200\,W*10/100)':
y='if(lt(mod(t+4\,16)\,8)\,H-h-H*5/200\,H*5/200)':
shortest=1"
 -acodec copy output_task_3.mp4
</code>```

But now am required to put the gif file on each edge with delay of 10 minutes

For exmaple:

1- render gif at top left for only 16 seconds.
Then wait 10 minutes

2- render gif at top right for 16 seconds.
Wait 10 minutes

3- rendder gif at right buttom   for 16 seconds.
Wait 10 minutes

4- render gif at left buttom for 16 secnods.
Wait 10 minutes

This scenario should be repete till the movie ends.

How can i archive this?

Body:
Am trying to put a gif file in all the edges of the video. So am using this command

ffmpeg  -y -i film.mp4 -stream_loop -1 -i gif.gif -filter_complex \
"[1]colorchannelmixer=aa=0.8,scale=iw*1:-1[a];[0][a]overlay=
x='if(lt(mod(t\,16)\,8)\,W-w-W*10/200\,W*10/100)':
y='if(lt(mod(t+4\,16)\,8)\,H-h-H*5/200\,H*5/200)':
shortest=1"
 -acodec copy output_task_3.mp4

But now am required to put the gif file on each edge with delay of 10 minutes

For exmaple:

1- render gif at top left for only 16 seconds.
Then wait 10 minutes

2- render gif at top right for 16 seconds.
Wait 10 minutes

3- rendder gif at right buttom   for 16 seconds.
Wait 10 minutes

4- render gif at left buttom for 16 secnods.
Wait 10 minutes

This scenario should be repete till the movie ends.

How can i archive this?


问:
How to delete object using Django Inline Formset
I am having a trouble with deleting an object in inline formset. The formset is not saving if there are objects to be deleted, but it just works properly when there is not.

Here is my views.py:

```<code>def submission(request):
if request.method == "POST":
    formset = AuthorFormSet(request.POST)
    form = thesisForm(request.POST,  request.FILES)

    if form.is_valid() & formset.is_valid():
        thesis = form.instance.thesis_id
        title = form.instance.title
        form.instance.uploaded_by = request.user  # set the user
        thesis = form.save() # save the form

        for obj in formset.deleted_objects:
            obj.delete()

        for forms in formset:
            forms.instance.thesis = thesis
            forms.save()

else:
    form = thesisForm()
    formset = AuthorFormSet()

return render(request,'StudentSubmitProject.html',{'form':form, 'formset':formset,})
</code>```

And this is my template:

```<code>  <form method="POST" class="mt-5 form-group profile_form" enctype="multipart/form-data">
    {% csrf_token %}

    <h4 class="textmaroon mt-5">Describe the thesis</h4>
    <p>Define the thesis project</p>
    <hr></hr>
    {{form.as_p}}

    <h4 class="textmaroon mt-5">Add Author</h4>
    <p>Input the authors of the thesis</p>
    <hr></hr>
    {% for forms in formset %}
      <div class="d-flex flex-wrap justify-content-between">{{forms.as_p}}</div>
      <hr class="text-muted"></hr>
    {% endfor %}

    {{ formset.management_data }}

    <div class="row mt-5">
      <hr></hr>
      <div class="col-md-12">
        <button type="submit" class="btn btn-danger float-end">Submit</button>
        <button type="reset" class="btn btn-secondary me-2 float-end">Reset</button>
      </div>
    </div>
  </form>
</code>```

Body:
I am having a trouble with deleting an object in inline formset. The formset is not saving if there are objects to be deleted, but it just works properly when there is not.

Here is my views.py:

def submission(request):
if request.method == "POST":
    formset = AuthorFormSet(request.POST)
    form = thesisForm(request.POST,  request.FILES)

    if form.is_valid() & formset.is_valid():
        thesis = form.instance.thesis_id
        title = form.instance.title
        form.instance.uploaded_by = request.user  # set the user
        thesis = form.save() # save the form

        for obj in formset.deleted_objects:
            obj.delete()

        for forms in formset:
            forms.instance.thesis = thesis
            forms.save()

else:
    form = thesisForm()
    formset = AuthorFormSet()

return render(request,'StudentSubmitProject.html',{'form':form, 'formset':formset,})

And this is my template:

  <form method="POST" class="mt-5 form-group profile_form" enctype="multipart/form-data">
    {% csrf_token %}

Describe the thesis

Define the thesis project

    {{form.as_p}}

Add Author

Input the authors of the thesis

    {% for forms in formset %}

{{forms.as_p}}

    {% endfor %}

    {{ formset.management_data }}

        <button type="submit" class="btn btn-danger float-end">Submit</button>
        <button type="reset" class="btn btn-secondary me-2 float-end">Reset</button>

  </form>


问:
nginx(-proxy) configration for a multi docker-compose setup with GitLab and wordpress webserver
I am in the process of configuring my first nginx proxy, which unfortunately does not conform to any standard configuration either.

About the infrastructure:

We have a vServer running a Gitlab including embedded Mattermost. These services are provided via a Docker Compose container. So far, this configuration has been running flawlessly for months. Mattermost is accessible via matterbost.my-domain.de and GitLab via gitlab.my-domain.de. For each of these subdomains an A-record is stored at our domain provider and the redirect is managed via the preconfigured nginx of the GitLab container. I did not have to configure anything here myself.

About the problem:

Now we want to run an additional web server with wordpress on this server. I would like to provide this service with Docker Compose as well. This has also worked without any problems so far and is accessible via port 8080 (my-domain.de:8080). Now, however, I want Wordpress to be accessible without specifying port 8080, i.e. via the URL my-domain.de.

My question:

Can anyone give me some advice on what kind of configuration or setup of the service infrastructure would be ideal for this case? I would prefer not to have to reconfigure the embedded Nginx from Gitlab, as this can certainly be very error-prone.

My attempted solution:

With the domain provider a simple forwarding with the IP address of the server and port, so my-domain.de points to XX.XX.XX.XX:8080. This works so far, but the URL in the Broswer is replaced afterwards by the IP address.


问:
Alert function for 30 minutes - Pinescript
I have a simple if condition which checks the current minute for triggering an alert. But it is not getting triggered.

```<code>if minute(timenow)==30
    alert("ALERT!!",alert.freq_once_per_bar )
</code>```

The alert is getting triggering for other conditions. Is the alert function will not work for a time-based condition?

Thanks.

Body:
I have a simple if condition which checks the current minute for triggering an alert. But it is not getting triggered.

if minute(timenow)==30
    alert("ALERT!!",alert.freq_once_per_bar )

The alert is getting triggering for other conditions. Is the alert function will not work for a time-based condition?

Thanks.


问:
Nginx Proxy Pass and Facebook secure connection problem
I'm trying to implement Facebook login and get the following error;

facebook has detected app isn't using a secure connection to transfer information

I use ssl and sure that it is still valid, however I have realized that my nginx proxy pass was http://localhost:4000. And I assume that that's why Facebook complains that the connection is not secure.

Then I have decided to change it to https://localhost:4001 and this time Facebook threw me 502 Bad Gateway

Finally I have decided to change the Host header to https://test.xxx.com to let Facebook knows that I'm returning the request from this domain but still no luck, I still get 502 Bad Gateway error.

From:

```<code>server {
   listen        443 ssl;
   # SSL
   ssl_certificate /etc/letsencrypt/live/xxx.com/fullchain.pem; # managed by Certbot
   ssl_certificate_key /etc/letsencrypt/live/xxx.com/privkey.pem; # managed by Certbot

   server_name   test.xxx.com;
   #root /var/www/test.xxx;
   # Configure the SignalR Endpoint
   location / {
    proxy_pass         http://localhost:4000;
    proxy_http_version 1.1;
    proxy_set_header   Upgrade $http_upgrade;
    proxy_set_header   Connection keep-alive;
    proxy_set_header   Host $host;
    proxy_cache_bypass $http_upgrade;
    proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header   X-Forwarded-Proto $scheme;
   }
}
</code>```

To:

```<code>server {
listen        443 ssl;
# SSL
ssl_certificate /etc/letsencrypt/live/xxx.com/fullchain.pem; # managed by Certbot
ssl_certificate_key /etc/letsencrypt/live/xxx.com/privkey.pem; # managed by Certbot

server_name   test.xxx.com;
#root /var/www/test.xxx;
# Configure the SignalR Endpoint
location / {
    proxy_pass         https://localhost:4001;
    proxy_http_version 1.1;
    proxy_set_header   Upgrade $http_upgrade;
    proxy_set_header   Connection keep-alive;
    proxy_set_header   Host https://test.xxx.com;
    proxy_cache_bypass $http_upgrade;
    proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header   X-Forwarded-Proto $scheme;
 }
}
</code>```

Body:
I'm trying to implement Facebook login and get the following error;

facebook has detected app isn't using a secure connection to transfer information

I use ssl and sure that it is still valid, however I have realized that my nginx proxy pass was http://localhost:4000. And I assume that that's why Facebook complains that the connection is not secure.

Then I have decided to change it to https://localhost:4001 and this time Facebook threw me 502 Bad Gateway

Finally I have decided to change the Host header to https://test.xxx.com to let Facebook knows that I'm returning the request from this domain but still no luck, I still get 502 Bad Gateway error.

From:

server {
   listen        443 ssl;
   # SSL
   ssl_certificate /etc/letsencrypt/live/xxx.com/fullchain.pem; # managed by Certbot
   ssl_certificate_key /etc/letsencrypt/live/xxx.com/privkey.pem; # managed by Certbot

   server_name   test.xxx.com;
   #root /var/www/test.xxx;
   # Configure the SignalR Endpoint
   location / {
    proxy_pass         http://localhost:4000;
    proxy_http_version 1.1;
    proxy_set_header   Upgrade $http_upgrade;
    proxy_set_header   Connection keep-alive;
    proxy_set_header   Host $host;
    proxy_cache_bypass $http_upgrade;
    proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header   X-Forwarded-Proto $scheme;
   }
}

To:

server {
listen        443 ssl;
# SSL
ssl_certificate /etc/letsencrypt/live/xxx.com/fullchain.pem; # managed by Certbot
ssl_certificate_key /etc/letsencrypt/live/xxx.com/privkey.pem; # managed by Certbot

server_name   test.xxx.com;
#root /var/www/test.xxx;
# Configure the SignalR Endpoint
location / {
    proxy_pass         https://localhost:4001;
    proxy_http_version 1.1;
    proxy_set_header   Upgrade $http_upgrade;
    proxy_set_header   Connection keep-alive;
    proxy_set_header   Host https://test.xxx.com;
    proxy_cache_bypass $http_upgrade;
    proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header   X-Forwarded-Proto $scheme;
 }
}


问:
Using react17 in a lib used inside a react 18 next app
So I have this lib that renders some Component. It uses react17 to do so. In this example it just renders a red square:

Lib.jsx:

```<code>import ReactDOM from 'react-dom';

const LibComponent = () => (
  <div style={{backgroundColor: 'red', width: '200px', height: '200px'}}>Lib Component</div>
)

const Lib = {
  init: (element) => {
    console.log('Element: ', element);
    ReactDOM.render(<LibComponent />, element);
  }
}

export { Lib };
</code>```

This lib uses react@17.0.2 and react-dom@17.0.2 and is built with parcel.

Now when I use this lib in a NextJS app that uses react18, i get the error:

Warning: ReactDOM.render is no longer supported in React 18. Use createRoot instead. Until you switch to the new API, your app will behave as if it's running React 17.

Here is the code for the page:

```<code>import { useRef, useEffect } from 'react';
import { Lib } from 'example-lib';

export default function Home() {
  const ref = useRef(null);
  useEffect(() => {
    if (ref.current) {
      Lib.init(ref.current)
    } else {
      console.log('No Ref');
    }
  })
  return (
    <div
      ref={ref}
      style={{backgroundColor: 'blue', width: '100vw', height: '100vh'}}
    >
      OKOKOKOK
    </div>
  )
}
</code>```

The app uses react@18.2.0 and react-dom@18.2.0

I though this could come from a misconfiguration in my Lib, so when i tried to reproduce the issue, i first used a raw webpack app, but the issue didn't occur.

It was only when i switched to next for the app, that i got this issue.

I guess that when used inside nextjs, the lib uses the react module from the app instead of it's own.
Any way to fix this behaviour ? Or is it intended by Next ?

Body:
So I have this lib that renders some Component. It uses react17 to do so. In this example it just renders a red square:

Lib.jsx:

import ReactDOM from 'react-dom';

const LibComponent = () => (

Lib Component

)

const Lib = {
  init: (element) => {
    console.log('Element: ', element);
    ReactDOM.render(<LibComponent />, element);
  }
}

export { Lib };

This lib uses react@17.0.2 and react-dom@17.0.2 and is built with parcel.

Now when I use this lib in a NextJS app that uses react18, i get the error:

Warning: ReactDOM.render is no longer supported in React 18. Use createRoot instead. Until you switch to the new API, your app will behave as if it's running React 17.

Here is the code for the page:

import { useRef, useEffect } from 'react';
import { Lib } from 'example-lib';

export default function Home() {
  const ref = useRef(null);
  useEffect(() => {
    if (ref.current) {
      Lib.init(ref.current)
    } else {
      console.log('No Ref');
    }
  })
  return (

      OKOKOKOK

  )
}

The app uses react@18.2.0 and react-dom@18.2.0

I though this could come from a misconfiguration in my Lib, so when i tried to reproduce the issue, i first used a raw webpack app, but the issue didn't occur.

It was only when i switched to next for the app, that i got this issue.

I guess that when used inside nextjs, the lib uses the react module from the app instead of it's own.
Any way to fix this behaviour ? Or is it intended by Next ?


问:
@here/maps-api-for-javascript has no exported member H
I am following the Heremap tutorial present at https://developer.here.com/documentation/maps/3.1.30.15/dev_guide/topics/angular-practices.html.

I copy pasted the code mentioned in it in my angular component. But the compiler complains that

@here/maps-api-for-javascript has no exported member H.

Anybody from Heremap developer community please help fix this.

Thanks,
Nealesh


问:
Laravel Socialite Callback URL not approved for this client application
I tried to add Twitter OAuth to my Laravel App, I followed multiple tutorials but always had the same issue.

Received HTTP status code [403] with message "<?xml version='1.0' encoding='UTF-8'?><errors><error code="415">Callback URL not approved for this client application. Approved callback URLs can be adjusted in your application settings</error></errors>" when getting temporary credentials.

In Twitter Developer Portal, I have Elevated access, which seems to be the one that is needed for this.

In my Laravel APP, I created a new fresh one for try this, I have this:

Twitter Controller:

```<code><?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Laravel\Socialite\Facades\Socialite;

class TwitterController extends Controller
{
    public function handle() {
        return Socialite::driver('twitter')->redirect();
    }

    public function callbackHandle() {
        $user = Socialite::driver('twitter')->user();
        dd($user);
    }
}
</code>```

I have also tried in callbackHandle() function:

```<code>public function callbackHandle() {
        $user = Socialite::driver('twitter')->userFromTokenAndSecret('API KEY', 'CLIENT SECRET');;
        dd($user);
    }
</code>```

Also tried to put consumer keys in the step of client id and client secret, but both of them didn't work.

In config/services.php I have:

```<code>    'twitter' => [
        'client_id' => '',
        'client_secret' => '',
        'redirect' => 'miv.test/twitter/callback',
    ],
</code>```

In client_id and client_secret, I also tried the consumer keys, but both of them didn't work.

web.php

```<code>Route::get('twitter', [TwitterController::class,'handle'])->name('twitter');
Route::get('twitter/callback', [TwitterController::class,'callbackHandle'])->name('twitter.callback');
</code>```

In my Twitter Developer Page I have this:

So the thing is that I tried all that is on https://laravel.com/docs/9.x/socialite and when I try to follow any tutorial for any reason this error doesn't appear to them.

Body:
I tried to add Twitter OAuth to my Laravel App, I followed multiple tutorials but always had the same issue.

Received HTTP status code [403] with message "<?xml version='1.0' encoding='UTF-8'?><errors><error code="415">Callback URL not approved for this client application. Approved callback URLs can be adjusted in your application settings</error></errors>" when getting temporary credentials.

In Twitter Developer Portal, I have Elevated access, which seems to be the one that is needed for this.

In my Laravel APP, I created a new fresh one for try this, I have this:

Twitter Controller:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Laravel\Socialite\Facades\Socialite;

class TwitterController extends Controller
{
    public function handle() {
        return Socialite::driver('twitter')->redirect();
    }

    public function callbackHandle() {
        $user = Socialite::driver('twitter')->user();
        dd($user);
    }
}

I have also tried in callbackHandle() function:

public function callbackHandle() {
        $user = Socialite::driver('twitter')->userFromTokenAndSecret('API KEY', 'CLIENT SECRET');;
        dd($user);
    }

Also tried to put consumer keys in the step of client id and client secret, but both of them didn't work.

In config/services.php I have:

    'twitter' => [
        'client_id' => '',
        'client_secret' => '',
        'redirect' => 'miv.test/twitter/callback',
    ],

In client_id and client_secret, I also tried the consumer keys, but both of them didn't work.

web.php

Route::get('twitter', [TwitterController::class,'handle'])->name('twitter');
Route::get('twitter/callback', [TwitterController::class,'callbackHandle'])->name('twitter.callback');

In my Twitter Developer Page I have this:

So the thing is that I tried all that is on https://laravel.com/docs/9.x/socialite and when I try to follow any tutorial for any reason this error doesn't appear to them.


问:
ANR in Alarm Manager Android
[libc.so] __futex_wait_ex(void volatile*, bool, int, bool, timespec const*)
Broadcast of Intent { cmp</p>

Title: ANR in Alarm Manager Android


问:
SignalR allows maximum 10 socket connections
I have a simple SignalR Application, created by steps from latest microsoft update https://learn.microsoft.com/en-us/aspnet/core/signalr/introduction?view=aspnetcore-7.0. I Am using .net 7 and latests signalr. Also I Have one hub that uses only websockets connection.

Below Program.cs code
`

```<code> public static void Main(string[] args)
        {
            Log.Logger = new LoggerConfiguration().WriteTo.Console()
                .CreateLogger();

            var builder = WebApplication.CreateBuilder(args);

            var listenUrl = builder.Configuration.GetValue<string>("ListenUrl");

            if (string.IsNullOrEmpty(listenUrl))
                throw new Exception("Please enter url in appsettings.json -> \"ListenUrl\"");

            builder.WebHost.UseUrls(listenUrl);

            builder.WebHost.ConfigureKestrel(_ =>
            {
                _.Limits.MaxConcurrentConnections = 50000;
                _.Limits.MaxConcurrentUpgradedConnections = 50000;
            });

            builder.Host.UseSerilog(); // <-- Add this line

            builder.Services.AddControllers();
            builder.Services.AddSignalR().AddMessagePackProtocol();
            builder.Services.AddSingleton<IConnectionCollector, ConnectionCollector>();
            builder.Services.AddSingleton<IWorker, WorkerSpammer>();

            var app = builder.Build();
            app.UseAuthorization();

            app.MapControllers();
            app.MapHub<ChatHub>("/chatHub", options =>
            {
                options.Transports = HttpTransportType.WebSockets;
            });

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

`
Starting my application via Kestrel from console line and passing to configuration file ip and port for listening.

Also I Have a console application that creates connections to Hub for stress test,

СonsoleConnector.cs
`

```<code> for (int i = 0; i < GoalConnections; i++)
                {
                    try
                    {
                        var connection = await StartConnection(url);
                        Connections.Add(connection);

                        if (i % 20 == 0)
                        {
                            Console.WriteLine($"Opened {i} connections");
                        }

                        if ((i + 1) == GoalConnections)
                        {
                            connection.On<Message>("ReceiveMessage", async (message) =>
                            {
                                var now = DateTime.Now;
                                Console.WriteLine($"LastConnection {i} received message with date \"{message.Date.ToString("MM/dd/yyyy hh:mm:ss.fff tt")}\", at \"{now.ToString("MM/dd/yyyy hh:mm:ss.fff tt")}\". Difference {(now - message.Date).TotalMilliseconds} MS");
                            });
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"Connection {i + 1} - error");
                        Console.WriteLine(ex.Message);
                        Errors++;
                        Console.ReadLine();
                    }
                }
</code>```

`

And when I have started my server and then from another machine started console connector, my console connector could open only 10 connections. Maybe somebody have conjectures why only 10. Server started on kestrel on windows

I tried to run it on IIS , but on iis there is a limit for 10 connections but in this situation u using kestrel, and when I start everything on localhost on the same machine everything works fine, I able to open around 6000 connections, but when its real networks only 10.

Body:
I have a simple SignalR Application, created by steps from latest microsoft update https://learn.microsoft.com/en-us/aspnet/core/signalr/introduction?view=aspnetcore-7.0. I Am using .net 7 and latests signalr. Also I Have one hub that uses only websockets connection.

Below Program.cs code
`

 public static void Main(string[] args)
        {
            Log.Logger = new LoggerConfiguration().WriteTo.Console()
                .CreateLogger();

            var builder = WebApplication.CreateBuilder(args);

            var listenUrl = builder.Configuration.GetValue<string>("ListenUrl");

            if (string.IsNullOrEmpty(listenUrl))
                throw new Exception("Please enter url in appsettings.json -> \"ListenUrl\"");

            builder.WebHost.UseUrls(listenUrl);

            builder.WebHost.ConfigureKestrel(_ =>
            {
                _.Limits.MaxConcurrentConnections = 50000;
                _.Limits.MaxConcurrentUpgradedConnections = 50000;
            });

            builder.Host.UseSerilog(); // <-- Add this line

            builder.Services.AddControllers();
            builder.Services.AddSignalR().AddMessagePackProtocol();
            builder.Services.AddSingleton<IConnectionCollector, ConnectionCollector>();
            builder.Services.AddSingleton<IWorker, WorkerSpammer>();

            var app = builder.Build();
            app.UseAuthorization();

            app.MapControllers();
            app.MapHub<ChatHub>("/chatHub", options =>
            {
                options.Transports = HttpTransportType.WebSockets;
            });

            app.Run();
        }
    }

`
Starting my application via Kestrel from console line and passing to configuration file ip and port for listening.

Also I Have a console application that creates connections to Hub for stress test,

СonsoleConnector.cs
`

 for (int i = 0; i < GoalConnections; i++)
                {
                    try
                    {
                        var connection = await StartConnection(url);
                        Connections.Add(connection);

                        if (i % 20 == 0)
                        {
                            Console.WriteLine($"Opened {i} connections");
                        }

                        if ((i + 1) == GoalConnections)
                        {
                            connection.On<Message>("ReceiveMessage", async (message) =>
                            {
                                var now = DateTime.Now;
                                Console.WriteLine($"LastConnection {i} received message with date \"{message.Date.ToString("MM/dd/yyyy hh:mm:ss.fff tt")}\", at \"{now.ToString("MM/dd/yyyy hh:mm:ss.fff tt")}\". Difference {(now - message.Date).TotalMilliseconds} MS");
                            });
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"Connection {i + 1} - error");
                        Console.WriteLine(ex.Message);
                        Errors++;
                        Console.ReadLine();
                    }
                }

`

And when I have started my server and then from another machine started console connector, my console connector could open only 10 connections. Maybe somebody have conjectures why only 10. Server started on kestrel on windows

I tried to run it on IIS , but on iis there is a limit for 10 connections but in this situation u using kestrel, and when I start everything on localhost on the same machine everything works fine, I able to open around 6000 connections, but when its real networks only 10.


问:
Configuring FORWARD dispatcher for tomcat's HttpHeaderSecurityFilter throws exception
i have web app with below HttpHeaderSecurityFilter configuration in conf/web.xml

```<code><filter>
    <filter-name>httpHeaderSecurity</filter-name>
    <filter-class>org.apache.catalina.filters.HttpHeaderSecurityFilter</filter-class>
    <async-supported>true</async-supported>
    <init-param>
        <param-name>blockContentTypeSniffingEnabled</param-name>
        <param-value>false</param-value>
    </init-param>
    <init-param>
        <param-name>antiClickJackingEnabled</param-name>
        <param-value>true</param-value>
    </init-param>
    <init-param>
        <param-name>antiClickJackingOption</param-name>
        <param-value>SAMEORIGIN</param-value>
    </init-param>
    <init-param>
        <param-name>xssProtectionEnabled</param-name>
        <param-value>false</param-value>
    </init-param>
    <init-param>
        <param-name>hstsEnabled</param-name>
        <param-value>false</param-value>
    </init-param>
    <init-param>
        <param-name>hstsMaxAgeSeconds</param-name>
        <param-value>60</param-value>
    </init-param>
</filter>
<filter-mapping>
    <filter-name>httpHeaderSecurity</filter-name>
    <url-pattern>/*</url-pattern>
    <dispatcher>REQUEST</dispatcher>
    <dispatcher>FORWARD</dispatcher>
</filter-mapping>
</code>```

with FORWARD dispatcher configuration application throws below issue for all requests

```<code>javax.servlet.ServletException: Unable to add HTTP headers since response is already committed on entry to the HTTP header security Filter
at org.apache.catalina.filters.HttpHeaderSecurityFilter.doFilter(HttpHeaderSecurityFilter.java:101)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
</code>```

but when i remove FORWARD dispatcher configuration no issue occurs.  i have searched everywhere i could not found reason can someone help me with this why this issue occurs ?

Thanks in Advance

Body:
i have web app with below HttpHeaderSecurityFilter configuration in conf/web.xml

<filter>
    <filter-name>httpHeaderSecurity</filter-name>
    <filter-class>org.apache.catalina.filters.HttpHeaderSecurityFilter</filter-class>
    <async-supported>true</async-supported>
    <init-param>
        <param-name>blockContentTypeSniffingEnabled</param-name>
        <param-value>false</param-value>
    </init-param>
    <init-param>
        <param-name>antiClickJackingEnabled</param-name>
        <param-value>true</param-value>
    </init-param>
    <init-param>
        <param-name>antiClickJackingOption</param-name>
        <param-value>SAMEORIGIN</param-value>
    </init-param>
    <init-param>
        <param-name>xssProtectionEnabled</param-name>
        <param-value>false</param-value>
    </init-param>
    <init-param>
        <param-name>hstsEnabled</param-name>
        <param-value>false</param-value>
    </init-param>
    <init-param>
        <param-name>hstsMaxAgeSeconds</param-name>
        <param-value>60</param-value>
    </init-param>
</filter>
<filter-mapping>
    <filter-name>httpHeaderSecurity</filter-name>
    <url-pattern>/*</url-pattern>
    <dispatcher>REQUEST</dispatcher>
    <dispatcher>FORWARD</dispatcher>
</filter-mapping>

with FORWARD dispatcher configuration application throws below issue for all requests

javax.servlet.ServletException: Unable to add HTTP headers since response is already committed on entry to the HTTP header security Filter
at org.apache.catalina.filters.HttpHeaderSecurityFilter.doFilter(HttpHeaderSecurityFilter.java:101)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)

but when i remove FORWARD dispatcher configuration no issue occurs.  i have searched everywhere i could not found reason can someone help me with this why this issue occurs ?

Thanks in Advance


问:
Python Selenium with Proxy is unpredictable
I have been working on a web scraper, it works fine without proxy, but on some website I need a proxy to avoid getting an Access Denied.
The problem is that the proxy is far away from me and the page gets loaded very slowly, it takes around from 80 to 100 seconds to fully load and most of the time it just fails, like if the page is getting renderer partially or just wrong.
I'm not sure whats the problem but it seems pretty unpredictable because sometime an item is being scrapped and sometime not..

Can the slowness of the page loading cause this or there is another problem which I'm not aware of? Without proxy everything is fine and the code is the same.

PS: I'm using the Chrome Driver


问:
Read JSONObject by using java8 stream
Here I have to get matching key and value pair, if it is available in array I have to print whole array without creating the object.

```<code>

This what I'm expecting,
Input :
{
  "key": [
    {
      "k1": "k1v1",
      "k2": "k2v1",
      "k3": "k3v1",
      "k4": "k4v1"
    },
    {
      "k1": "k1v2",
      "k2": "k2v2",
      "k3": "k3v1",
      "k4": "k4v2"
    },
    {
      "k1": "k1v1",
      "k2": "k2v2",
      "k3": "k3v3",
      "k4": "k4v4"
    }
  ]
</code>```

output : search value is : k1v1/k1 (if we are pass key or value the output should be like this)
{"k1": "k1v1","k2": "k2v1","k3": "k3v1","k4": "k4v1"},{"k1": "k1v1","k2": "k2v2","k3": "k3v3","k4": "k4v4"}

I tried this code

```<code>JSONParser jsonParser = new JSONParser();
        JSONObject jsonObject = (JSONObject) jsonParser.parse(new FileReader("keys.json"));
        JSONArray keysArray = (JSONArray) jsonObject.get("key");
        String jsonStr = JSONArray.toJSONString(keysArray);
        List<Object> key = ((Stream<JSONObject>)(keysArray.stream()))
                .map(key1 -> (JSONObject)(key1))
                .map(key1 -> (key1.get(str1)))
                .filter(key1 -> key1.equals(str1))
                .collect(Collectors.toList());
This what I'm getting the output,
key["k1v1","k1v1"]

</code>```

Title: Read JSONObject by using java8 stream

Body:
Here I have to get matching key and value pair, if it is available in array I have to print whole array without creating the object.

This what I'm expecting,
Input :
{
  "key": [
    {
      "k1": "k1v1",
      "k2": "k2v1",
      "k3": "k3v1",
      "k4": "k4v1"
    },
    {
      "k1": "k1v2",
      "k2": "k2v2",
      "k3": "k3v1",
      "k4": "k4v2"
    },
    {
      "k1": "k1v1",
      "k2": "k2v2",
      "k3": "k3v3",
      "k4": "k4v4"
    }
  ]

output : search value is : k1v1/k1 (if we are pass key or value the output should be like this)
{"k1": "k1v1","k2": "k2v1","k3": "k3v1","k4": "k4v1"},{"k1": "k1v1","k2": "k2v2","k3": "k3v3","k4": "k4v4"}

I tried this code

JSONParser jsonParser = new JSONParser();
        JSONObject jsonObject = (JSONObject) jsonParser.parse(new FileReader("keys.json"));
        JSONArray keysArray = (JSONArray) jsonObject.get("key");
        String jsonStr = JSONArray.toJSONString(keysArray);
        List<Object> key = ((Stream<JSONObject>)(keysArray.stream()))
                .map(key1 -> (JSONObject)(key1))
                .map(key1 -> (key1.get(str1)))
                .filter(key1 -> key1.equals(str1))
                .collect(Collectors.toList());
This what I'm getting the output,
key["k1v1","k1v1"]


问:
AWS IAM Inline policy for Password Expiration
I have a AWS account and different departments like Accounts, Developers and QA. I want to have a different password expiration policy for each departments. I tried with customs policy and its applicable for the users in account. Is it possible to change the password expiry groupwise?

Thanks in Advance.

I tried changing the Default to custom password policy but it is applying for all the users in the account.


问:
Expo Project fails to build on android due to an IOS specific feature that is programmatically removed for android devices
The package in question is

```<code>react-native-peripheral
</code>```

and per there documentation. it only supports IOS. I'd still like the rest of the application to work on android devices, since that feature is only on one page that doesn't even render for Platform.OS === "android"

However, gradlew clearly insists that the module must be defined...

here's a simple example if you want to bootstrap an expo project and add the module yourself

```<code>if (Platform.OS === "ios") {
  Peripheral= require("react-native-peripheral").default
}
</code>```

but you'll be greeted with the following error
Unable to resolve module react-native-peripheral
or
A problem occurred evaluating project ':react-native-peripheral'.

Let me know if anyone knows how to handle this edge case.

Body:
The package in question is

react-native-peripheral

and per there documentation. it only supports IOS. I'd still like the rest of the application to work on android devices, since that feature is only on one page that doesn't even render for Platform.OS === "android"

However, gradlew clearly insists that the module must be defined...

here's a simple example if you want to bootstrap an expo project and add the module yourself

if (Platform.OS === "ios") {
  Peripheral= require("react-native-peripheral").default
}

but you'll be greeted with the following error
Unable to resolve module react-native-peripheral
or
A problem occurred evaluating project ':react-native-peripheral'.

Let me know if anyone knows how to handle this edge case.


问:
Woocommerce product page - Disable main image change on variation selection
I use variation photo later in the code, but I don't need the main gallery to be changed.

It seems to be somewhere in add-to-cart-variation.js, but I can't find exact place.


问:
Eclipse Scientific reading from standard input txt file parallel application
I'm trying to set an input file as standard input at run configurations of mpi parallel application, but when I'm using the scanf the father process get stuck. When I'm running the program as regular program and not parallel, it works successfuly..

there's the configurations

Anyone knows how to figure it out?


问:
How to use a newly added tabLayout module as library in a project?
I completed working on an app and now I want to add a tabLayout inside it so I add a new Tabbed Activity module from the presets, I designed the tabLayout as required but now I'm confused how to add the tabLayout in the Oncreate of the MainActivity.kt of the main app module. I am thinking of adding the tablayout activity as companion object. If you have any solution please help!!!

This is my tablayout activity(not sure about the companion object)-

```<code>class MainActivity : AppCompatActivity() {

private lateinit var binding: ActivityMainBinding

companion object tablayout {
    fun launchActivity(aciivity: Activity) {
        val intent = Intent(aciivity.MainActivity::class.java)
        aciivity.startActivity(intent)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        val sectionsPagerAdapter = SectionsPagerAdapter(this, supportFragmentManager)
        val viewPager: ViewPager = binding.viewPager
        viewPager.adapter = sectionsPagerAdapter
        val tabs: TabLayout = binding.tabs
        tabs.setupWithViewPager(viewPager)
    }

}
</code>```

Body:
I completed working on an app and now I want to add a tabLayout inside it so I add a new Tabbed Activity module from the presets, I designed the tabLayout as required but now I'm confused how to add the tabLayout in the Oncreate of the MainActivity.kt of the main app module. I am thinking of adding the tablayout activity as companion object. If you have any solution please help!!!

This is my tablayout activity(not sure about the companion object)-

class MainActivity : AppCompatActivity() {

private lateinit var binding: ActivityMainBinding

companion object tablayout {
    fun launchActivity(aciivity: Activity) {
        val intent = Intent(aciivity.MainActivity::class.java)
        aciivity.startActivity(intent)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        val sectionsPagerAdapter = SectionsPagerAdapter(this, supportFragmentManager)
        val viewPager: ViewPager = binding.viewPager
        viewPager.adapter = sectionsPagerAdapter
        val tabs: TabLayout = binding.tabs
        tabs.setupWithViewPager(viewPager)
    }

}


问:
Qt platform plugin "wayland" not found while running Python in VScode on Ubuntu

I ran into the following problem, which prevents me from plotting figures in VScode.

As a minimal example, I am trying to run the following Python script in VScode:

```<code>from matplotlib import pyplot as plt
plt.plot([1,2,3], [5,4,3])
</code>```

This outputs qt.qpa.plugin: Could not find the Qt platform plugin "wayland" in "".

Python 3.9.15

Anaconda Navigator 2.3.2

conda 22.11.1

matplotlib 3.6.2

Visual Studio Code 1.74.2

OS Name: Ubuntu 22.04.1 LTS

GNOME Version: 42.5

Windowing System: Wayland

So far, I have tried:

Installing qtwayland5 by running sudo apt-get install -y qtwayland5. This is already installed in the newest version (5.15.3-1).

I have tried the following to find where it is installed.

which qtwayland5 -> empty output

whereis qtwayland5 -> qtwayland5:

locate qtwayland5 ->

```<code>/usr/share/doc/qtwayland5
/usr/share/doc/qtwayland5/changelog.Debian.gz
/usr/share/doc/qtwayland5/copyright
/var/cache/apt/archives/qtwayland5_5.15.3-1_amd64.deb
/var/lib/dpkg/info/qtwayland5:amd64.list
/var/lib/dpkg/info/qtwayland5:amd64.md5sums
</code>```

Both locate wayland and locate qt give hundreds of results in various locations.

My plan was to add the directory containing qtwayland5 to the $PATH variable, but now I don't know, which of the many directories is the right one (if this would even solve the problem).

Thank you for taking the time to read through my question. Any help would be greatly appreciated as I have spent a lot of time looking for a solution.

Body:
I ran into the following problem, which prevents me from plotting figures in VScode.

As a minimal example, I am trying to run the following Python script in VScode:

from matplotlib import pyplot as plt
plt.plot([1,2,3], [5,4,3])

This outputs qt.qpa.plugin: Could not find the Qt platform plugin "wayland" in "".

Python 3.9.15

Anaconda Navigator 2.3.2

conda 22.11.1

matplotlib 3.6.2

Visual Studio Code 1.74.2

OS Name: Ubuntu 22.04.1 LTS

GNOME Version: 42.5

Windowing System: Wayland

So far, I have tried:

Installing qtwayland5 by running sudo apt-get install -y qtwayland5. This is already installed in the newest version (5.15.3-1).

I have tried the following to find where it is installed.

which qtwayland5 -> empty output

whereis qtwayland5 -> qtwayland5:

locate qtwayland5 ->

/usr/share/doc/qtwayland5
/usr/share/doc/qtwayland5/changelog.Debian.gz
/usr/share/doc/qtwayland5/copyright
/var/cache/apt/archives/qtwayland5_5.15.3-1_amd64.deb
/var/lib/dpkg/info/qtwayland5:amd64.list
/var/lib/dpkg/info/qtwayland5:amd64.md5sums

Both locate wayland and locate qt give hundreds of results in various locations.

My plan was to add the directory containing qtwayland5 to the $PATH variable, but now I don't know, which of the many directories is the right one (if this would even solve the problem).

Thank you for taking the time to read through my question. Any help would be greatly appreciated as I have spent a lot of time looking for a solution.


问:
how to check whether usb device is mounted or not through my c application in linux
i wanted to detect the USB device in Linux with my c application

im able to execute lsblk command in command line then i can see that my USB device is detecting in /dev/sda directory but how can i get to know this using my c application???

foe any help thanks in advance

OwnerDisplayName: Rajesh


问:
<Mat-select> with formarray is throwing error in template and unable see <mat-options> values
Expecting a dropdown like this with values to save , add and remove
enter image description here(https://i.stack.imgur.com/ENuSN.png)

Component.ts:

i had a user form like this

```<code>form:FormGroup=this.fb.group({
   name:[''],
   Experience:[''],
   skill:this.fb.array([])
});
</code>```

and array of skill options

```<code>allskills=[
    { skillId: 1, skillName: 'java' },
    { skillId: 2, skillName: 'Springboot' },
    { skillId: 3, skillName: 'Spring Microservices' },
    { skillId: 4, skillName: 'Advanced java' },
    { skillId: 5, skillName: 'Aws' },
    { skillId: 6, skillName: 'Azure' },
    { skillId: 7, skillName: 'Angular' }]

get skill(){
 return this.form.get('skills') as FormArray;
}

addnewSkill(){
for(let s of allSkills){
this.skill().push(
this.fb.control(s.skillName));
}
}
</code>```

//like wise for remove a skill

*In Component.html  :

i am trying to do something like this

```<code><form [FormGroup]="form" >
    <mat-label>dropdown</mat-label>
 <div formArrayName="skills" *ngFor="let s of skill.controls; let i = index">
        <mat-form-field>
        <mat-select  placeholder="selectskills" [formControl]="s">
            <mat-option  *ngFor="let d of allskills">
                  {{d.skillName}}
            </mat-option>
        </mat-select>
    </mat-form-field>

</form>
</code>```

While trying to add [formControl]="s" in <mat-select> throwing error:  'AbstractControl' is missing the following properties from type 'FormControl'

Can anyone please help me on this as i am new to angular , unable to proceed forward

Body:
Expecting a dropdown like this with values to save , add and remove
enter image description here(https://i.stack.imgur.com/ENuSN.png)

Component.ts:

i had a user form like this

form:FormGroup=this.fb.group({
   name:[''],
   Experience:[''],
   skill:this.fb.array([])
});

and array of skill options

allskills=[
    { skillId: 1, skillName: 'java' },
    { skillId: 2, skillName: 'Springboot' },
    { skillId: 3, skillName: 'Spring Microservices' },
    { skillId: 4, skillName: 'Advanced java' },
    { skillId: 5, skillName: 'Aws' },
    { skillId: 6, skillName: 'Azure' },
    { skillId: 7, skillName: 'Angular' }]

get skill(){
 return this.form.get('skills') as FormArray;
}

addnewSkill(){
for(let s of allSkills){
this.skill().push(
this.fb.control(s.skillName));
}
}

//like wise for remove a skill

*In Component.html  :

i am trying to do something like this

<form [FormGroup]="form" >
    <mat-label>dropdown</mat-label>

        <mat-form-field>
        <mat-select  placeholder="selectskills" [formControl]="s">
            <mat-option  *ngFor="let d of allskills">
                  {{d.skillName}}
            </mat-option>
        </mat-select>
    </mat-form-field>

</form>

While trying to add [formControl]="s" in <mat-select> throwing error:  'AbstractControl' is missing the following properties from type 'FormControl'

Can anyone please help me on this as i am new to angular , unable to proceed forward


问:
Nodejs - Compare data from CSV with Mysql
What is the fastest way to compare data from a CSV-file with data in MYSQL-db, and then update the changes from CSV -> Mysql.

```<code>`async function readFile(){
  var count = 0;
  var fileStream = fs.createReadStream("./download/CSV.csv")
  .pipe(parse({ delimiter: ";", relax_column_count: true, from_line: 2 }))
  .on("data", async (row) => {
    const found = await mysql_update.updateProduct(row[0], row[3])
    .then((ret) => {count++;
      if(ret > 0){ console.log("Line " + count + "  AffectedRows: " + ret)}});

  })
  .on("end", async function () {
    console.log("Finished!");
    fileStream.end();

  })
  .on("error", function (error) {
   console.log(error.message);
  });
}`

</code>```

And this is from the updateProduct() function:

```<code>module.exports.updateProduct = function (sku, stock){
    return new Promise((resolve, reject) => {
      var stockupdate = new Date();
      var sql = `UPDATE products SET newstock=${mysql.escape(stock)}, stockupdate=${mysql.escape(stockupdate)} WHERE sku=${mysql.escape(sku)}`;
      con.query(sql, function (err, result, fields) {
        if (err) throw err;
        resolve(result.affectedRows);
      });
    })

}
</code>```

This works today, but it takes long time.  I have around 160.000 lines in the CSV-file, and 33.000 elements in my Mysql-table.  And this is a task that will run every hour.

Body:
What is the fastest way to compare data from a CSV-file with data in MYSQL-db, and then update the changes from CSV -> Mysql.

`async function readFile(){
  var count = 0;
  var fileStream = fs.createReadStream("./download/CSV.csv")
  .pipe(parse({ delimiter: ";", relax_column_count: true, from_line: 2 }))
  .on("data", async (row) => {
    const found = await mysql_update.updateProduct(row[0], row[3])
    .then((ret) => {count++;
      if(ret > 0){ console.log("Line " + count + "  AffectedRows: " + ret)}});

  })
  .on("end", async function () {
    console.log("Finished!");
    fileStream.end();

  })
  .on("error", function (error) {
   console.log(error.message);
  });
}`

And this is from the updateProduct() function:

module.exports.updateProduct = function (sku, stock){
    return new Promise((resolve, reject) => {
      var stockupdate = new Date();
      var sql = `UPDATE products SET newstock=${mysql.escape(stock)}, stockupdate=${mysql.escape(stockupdate)} WHERE sku=${mysql.escape(sku)}`;
      con.query(sql, function (err, result, fields) {
        if (err) throw err;
        resolve(result.affectedRows);
      });
    })

}

This works today, but it takes long time.  I have around 160.000 lines in the CSV-file, and 33.000 elements in my Mysql-table.  And this is a task that will run every hour.


问:
How can i open bluetooth service in android emulator?
Hi everyone i developing to bluetooth project with react-native. I need to scanning around device's bluetooth datas. I can execute in a peripheral android device but i want to execute in emulator. So i need to open bluetooth services in android emulator. But i cant open bluetooth services in a bluetooth emulator. How ca i open bluetooth services in android emulator.I already accept all permissions for bluetooth btw.

My emulator : Pixel 4 XL API 24
Android 7-12
Min sdk version: 21
Max sdk version: 31


问:
How to render and update a list of React components dynamically in a performant way?
I am trying to build a simple form builder, with which you can add questions to a list, and each kind of question has a specific component to create the question, and one to set an answer.

These components are contained in an object like this

```<code>{
 longText:{
   create: (initialData, setNewData)=>{...},
   answer: (initialData, setNewData)=>{...}
 },
 multiple:{
   create: (initialData, setNewData)=>{...},
   answer: (initialData, setNewData)=>{...}
 }
 ...
}
</code>```

When a kind of question is selected from a dropdown, the right component should render, showing the initialData.

right now the only way I have found that works is something like this:

```<code>{(() => {
  return React.createElement(components[questionKindName].create,{
     initialData: data,
     setNewData: (v) => setTheData(v),
 });
})()}
</code>```

But this has very poor performance,
as I am updating the data, on every change,
and it triggers a new render of the whole list of forms each time.

this is the code that keeps track of the list of questions.

```<code>const [questions, setQuestions] = useState<Question[]>([]);
const addNewQuestion = (question: Question) => setQuestions([...questions, question]);

// this is the function invoked to set the new data
const editQuestion = (
  questionIndex: Number,
  key: keyof Question,
  value: string
) =>
  setQuestions(
    questions.map((s, i) => {
      if (s && questionIndex === i) {
        s[key] = value;
      }
      return s;
    })
  );
</code>```

how can I make it work nicely?
What is that I am missing here?
Should I put a throttle around the IIFE?
I am learning about lazy and Suspense, might that help?

I know the question could have been clearer,
if you can help, i will be happy to improve it.

Thanks.

PS:
I have tried saving and updating the selected component with a useState and a useEffect hook,
but it just doesn't work.

I always got an error like.. "cannot read "InitialData" on "_ref" as it is undefined" that indicates that it was invoking the function, but not passing the props.

Body:
I am trying to build a simple form builder, with which you can add questions to a list, and each kind of question has a specific component to create the question, and one to set an answer.

These components are contained in an object like this

{
 longText:{
   create: (initialData, setNewData)=>{...},
   answer: (initialData, setNewData)=>{...}
 },
 multiple:{
   create: (initialData, setNewData)=>{...},
   answer: (initialData, setNewData)=>{...}
 }
 ...
}

When a kind of question is selected from a dropdown, the right component should render, showing the initialData.

right now the only way I have found that works is something like this:

{(() => {
  return React.createElement(components[questionKindName].create,{
     initialData: data,
     setNewData: (v) => setTheData(v),
 });
})()}

But this has very poor performance,
as I am updating the data, on every change,
and it triggers a new render of the whole list of forms each time.

this is the code that keeps track of the list of questions.

const [questions, setQuestions] = useState<Question[]>([]);
const addNewQuestion = (question: Question) => setQuestions([...questions, question]);

// this is the function invoked to set the new data
const editQuestion = (
  questionIndex: Number,
  key: keyof Question,
  value: string
) =>
  setQuestions(
    questions.map((s, i) => {
      if (s && questionIndex === i) {
        s[key] = value;
      }
      return s;
    })
  );

how can I make it work nicely?
What is that I am missing here?
Should I put a throttle around the IIFE?
I am learning about lazy and Suspense, might that help?

I know the question could have been clearer,
if you can help, i will be happy to improve it.

Thanks.

PS:
I have tried saving and updating the selected component with a useState and a useEffect hook,
but it just doesn't work.

I always got an error like.. "cannot read "InitialData" on "_ref" as it is undefined" that indicates that it was invoking the function, but not passing the props.


问:
gas not honoring short jump suffix .d8
I want to force gas to emit a relative conditional jump in a short opcode, but it always uses rel32 encoding. Here is my code:

```<code>.text
.org 0x123450
.globl test
test:
je.d8 0x123450
</code>```

Which emits, when compiled:

```<code>$ as x.S -o x && objdump -d x
0000000000123450 <test>:
  123450:   0f 84 00 00 00 00       je     123456 <test+0x6>
</code>```

When I use the label, i.e.

```<code>je test
</code>```

it correctly produces

```<code>  123450:   74 fe                   je     123450 <test>
</code>```

How do I force the latter while still being able to numerically enter the address?

Title: gas not honoring short jump suffix .d8

Body:
I want to force gas to emit a relative conditional jump in a short opcode, but it always uses rel32 encoding. Here is my code:

.text
.org 0x123450
.globl test
test:
je.d8 0x123450

Which emits, when compiled:

$ as x.S -o x && objdump -d x
0000000000123450 <test>:
  123450:   0f 84 00 00 00 00       je     123456 <test+0x6>

When I use the label, i.e.

je test

it correctly produces

  123450:   74 fe                   je     123450 <test>

How do I force the latter while still being able to numerically enter the address?