问:
Issue when pull request on GitHub
Commit Merge branch dev from my-branch

2 pull requests from my-branch to dev and master branch

Hi everyone,
I have problem when pull request from my branch to dev and master branch. It was occured 1 commit is Merge branch dev into my branch - I hadn't pull request it yet. That's odd.

Base on first image, you can see the title is commit dev from my branch (So, It means I created a pull request). But in the commit, we can see a commit named "Merge branch dev into ...".

And I don't know how to check it, because it only has one Pull request to merge code (into dev from my-branch).

My process is :

Switch master (git checkout master)

Pull from master (git fetch -p and git pull)

Create new local branch from (git checkout -b my branch)

Push to GitHub (git push origin -u HEAD)

Pull request (first is into dev from my branch, second is into master from my branch)

The different with other my pull requests is this pull request have many conflicts I need to fix manually.

I'm not sure if I wrong at what step?
And I have last question, how we can block pull request from dev to another branch?
Thanks so much.

I just wonder why it has Merge branch dev, It makes code was wrong.
And could anyone tell me know how to block pull request from dev to another branch?

Title: Issue when pull request on GitHub


来源: stackexchange

问:
Unity doesn't receive all the information given from another software by udp
My problem is that Unity doesn't read or process all the information from another software, in this case is Anylogic, how you can see in the pictures, the print of both software are not matching, I also sent the code of the UDP in Unity, if it's necessary I can also send the code of udp in Anylogic.

Print in Anylogic:

Print in Unity

NEW UNITY DEBUG

```<code>using UnityEngine;
using System.Collections;

using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Collections.Generic;
using System.Globalization;
using UnityEditor;
using static JSONReader;

[Serializable]
public class RealTimeItem
{
    public GameObject Object;
    public int NetID;
    public Vector3 Position;
    public Vector3 Target;
    public float TimeReach;
    public float TimeReachNext;
    public bool change;

    public Agente agent;
}

public class UDPClient : MonoBehaviour
{
    public List<RealTimeItem> items;

    public static UDPClient instance;
    public int portListen = 4444;
    public string ipSend = "";
    public int portSend = 5555;

    public GameObject[]  notifyObjects;
    public string messageToNotify;

    private string received = "";

    private UdpClient client;
    private Thread receiveThread;
    private IPEndPoint remoteEndPoint;
    private IPAddress ipAddressSend;

    public float TimeStamp = 1;

    public bool SetData(Agente ag)
    {
        if (getObjWithID(ag.id) == null)
            return false;

        RealTimeItem itemUse = items[GetID(ag.id)];
        int id = Convert.ToInt32(ag.id);

        GameObject obj = getObjWithID(id);

        /*
        if (ag.coordenadas.Count > (ag.coordenadas.Count - 2))
        {
            itemUse.Position = ag.coordenadas[ag.coordenadas.Count - 2];
        }
        */

        itemUse.Position = ag.coordenadas[ag.coordenadas.Count - 1];
        itemUse.Target = ag.coordenadas[ag.coordenadas.Count - 1];

        itemUse.TimeReach = ag.tiempos[ag.tiempos.Count - 1];
        itemUse.TimeReachNext = ag.tiempos[ag.tiempos.Count - 1];
        itemUse.change = true;

        // Debug.LogError("Checking: " + itemUse.NetID + "|||AGID: " + ag.id);
        //  obj.transform.position = itemUse.Position;
        return true;
    }

    private void FixedUpdate()
    {
        foreach(var xItem in items)
        {
            //  xItem.Object.transform.position = Vector3.MoveTowards(xItem.Object.transform.position, xItem.Position, TimeStamp * Time.deltaTime);
            //  xItem.Object.transform.LookAt(xItem.Target);
        }
    }

    public int GetID(int SearchID)
    {
        foreach (var item in items)
        {
            if (item.NetID.Equals(SearchID))
                return items.IndexOf(item);
        }

        return 0;
    }

    public GameObject getObjWithID(int SearchID)
    {
        foreach (var item in items)
        {
            if (item.NetID.Equals(SearchID))
                return item.Object;
        }

        return null;
    }

    public void Awake ()
    {
        instance = this;

        //Check if the ip address entered is valid. If not, sendMessage will broadcast to all ip addresses
        IPAddress ip;

        if (IPAddress.TryParse (ipSend, out ip))
        {
            remoteEndPoint = new IPEndPoint (ip, portSend);
        }
        else
        {
            remoteEndPoint = new IPEndPoint (IPAddress.Broadcast, portSend);
        }

        //Initialize client and thread for receiving

        client = new UdpClient (portListen);

        receiveThread = new Thread (new ThreadStart (ReceiveData));
        receiveThread.IsBackground = true;
        receiveThread.Start ();
    }

    void Update ()
    {
        // Check if a message has been received
        if (received != "")
        {
            //Debug.Log("UDPClient: message received \'" + received + "\'");

            // Notify each object defined in the array with the message received
            foreach (GameObject g in notifyObjects)
            {
                g.SendMessage(messageToNotify, received, SendMessageOptions.DontRequireReceiver);
            }

            // Clear message
            received = "";
        }
    }

    // Call this method to send a message from this app to ipSend using portSend
    public void SendValue (string valueToSend)
    {
        try
        {
            if (valueToSend != "")
            {
                // Get bytes from string
                byte[] data = Encoding.UTF8.GetBytes (valueToSend);

                // Send bytes to remote client
                client.Send (data, data.Length, remoteEndPoint);
                Debug.Log ("UDPClient: send \'" + valueToSend + "\'");

                // Clear message
                valueToSend = "";
            }
        }
        catch (Exception err)
        {
            Debug.LogError ("Error udp send : " + err.Message);
        }
    }

    // This method checks if the app receives any message
    public void ReceiveData ()
    {
        while (true)
        {
            try
            {
                // Bytes received
                IPEndPoint anyIP = new IPEndPoint (IPAddress.Any, 0);
                byte[] data = client.Receive (ref anyIP);

                // Bytes into text
                string text = "";
                text = Encoding.UTF8.GetString (data);

                received = text;
                Debug.Log("UDPClient: message received \'" + received + "\'");

            }
            catch (Exception err)
            {
                Debug.Log ("Error:" + err.ToString ());
            }
        }
    }

    // Exit UDP client
    public void OnDisable ()
    {
        if (receiveThread != null)
        {
            receiveThread.Abort ();
            receiveThread = null;
        }

        client.Close ();
        Debug.Log ("UDPClient: exit");
    }
}
</code>```

So, I tried nothing at this moment, because I'm inexperienced in this area, but this was working good until I put a library thing in Anylogic, maybe that is the problem, but I´m  not sure, so, anything will be welcome, and my expected results are that all the information is processed.

UPDATE
In the function ReceiveData after received = text; I put Debug.Log("UDPClient: message received \'" + received + "\'"); and deleted from function Update, and now the Debugs from both software are the same, now the question is, Where is the error that does not allow the updating of the data since they are read by Unity correctly.

ContentLicense: CC BY-SA 4.0

Body:
My problem is that Unity doesn't read or process all the information from another software, in this case is Anylogic, how you can see in the pictures, the print of both software are not matching, I also sent the code of the UDP in Unity, if it's necessary I can also send the code of udp in Anylogic.

Print in Anylogic:

Print in Unity

NEW UNITY DEBUG

using UnityEngine;
using System.Collections;

using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Collections.Generic;
using System.Globalization;
using UnityEditor;
using static JSONReader;

[Serializable]
public class RealTimeItem
{
    public GameObject Object;
    public int NetID;
    public Vector3 Position;
    public Vector3 Target;
    public float TimeReach;
    public float TimeReachNext;
    public bool change;

    public Agente agent;
}

public class UDPClient : MonoBehaviour
{
    public List<RealTimeItem> items;

    public static UDPClient instance;
    public int portListen = 4444;
    public string ipSend = "";
    public int portSend = 5555;

    public GameObject[]  notifyObjects;
    public string messageToNotify;

    private string received = "";

    private UdpClient client;
    private Thread receiveThread;
    private IPEndPoint remoteEndPoint;
    private IPAddress ipAddressSend;

    public float TimeStamp = 1;

    public bool SetData(Agente ag)
    {
        if (getObjWithID(ag.id) == null)
            return false;

        RealTimeItem itemUse = items[GetID(ag.id)];
        int id = Convert.ToInt32(ag.id);

        GameObject obj = getObjWithID(id);

        /*
        if (ag.coordenadas.Count > (ag.coordenadas.Count - 2))
        {
            itemUse.Position = ag.coordenadas[ag.coordenadas.Count - 2];
        }
        */

        itemUse.Position = ag.coordenadas[ag.coordenadas.Count - 1];
        itemUse.Target = ag.coordenadas[ag.coordenadas.Count - 1];

        itemUse.TimeReach = ag.tiempos[ag.tiempos.Count - 1];
        itemUse.TimeReachNext = ag.tiempos[ag.tiempos.Count - 1];
        itemUse.change = true;

        // Debug.LogError("Checking: " + itemUse.NetID + "|||AGID: " + ag.id);
        //  obj.transform.position = itemUse.Position;
        return true;
    }

    private void FixedUpdate()
    {
        foreach(var xItem in items)
        {
            //  xItem.Object.transform.position = Vector3.MoveTowards(xItem.Object.transform.position, xItem.Position, TimeStamp * Time.deltaTime);
            //  xItem.Object.transform.LookAt(xItem.Target);
        }
    }

    public int GetID(int SearchID)
    {
        foreach (var item in items)
        {
            if (item.NetID.Equals(SearchID))
                return items.IndexOf(item);
        }

        return 0;
    }

    public GameObject getObjWithID(int SearchID)
    {
        foreach (var item in items)
        {
            if (item.NetID.Equals(SearchID))
                return item.Object;
        }

        return null;
    }

    public void Awake ()
    {
        instance = this;

        //Check if the ip address entered is valid. If not, sendMessage will broadcast to all ip addresses
        IPAddress ip;

        if (IPAddress.TryParse (ipSend, out ip))
        {
            remoteEndPoint = new IPEndPoint (ip, portSend);
        }
        else
        {
            remoteEndPoint = new IPEndPoint (IPAddress.Broadcast, portSend);
        }

        //Initialize client and thread for receiving

        client = new UdpClient (portListen);

        receiveThread = new Thread (new ThreadStart (ReceiveData));
        receiveThread.IsBackground = true;
        receiveThread.Start ();
    }

    void Update ()
    {
        // Check if a message has been received
        if (received != "")
        {
            //Debug.Log("UDPClient: message received \'" + received + "\'");

            // Notify each object defined in the array with the message received
            foreach (GameObject g in notifyObjects)
            {
                g.SendMessage(messageToNotify, received, SendMessageOptions.DontRequireReceiver);
            }

            // Clear message
            received = "";
        }
    }

    // Call this method to send a message from this app to ipSend using portSend
    public void SendValue (string valueToSend)
    {
        try
        {
            if (valueToSend != "")
            {
                // Get bytes from string
                byte[] data = Encoding.UTF8.GetBytes (valueToSend);

                // Send bytes to remote client
                client.Send (data, data.Length, remoteEndPoint);
                Debug.Log ("UDPClient: send \'" + valueToSend + "\'");

                // Clear message
                valueToSend = "";
            }
        }
        catch (Exception err)
        {
            Debug.LogError ("Error udp send : " + err.Message);
        }
    }

    // This method checks if the app receives any message
    public void ReceiveData ()
    {
        while (true)
        {
            try
            {
                // Bytes received
                IPEndPoint anyIP = new IPEndPoint (IPAddress.Any, 0);
                byte[] data = client.Receive (ref anyIP);

                // Bytes into text
                string text = "";
                text = Encoding.UTF8.GetString (data);

                received = text;
                Debug.Log("UDPClient: message received \'" + received + "\'");

            }
            catch (Exception err)
            {
                Debug.Log ("Error:" + err.ToString ());
            }
        }
    }

    // Exit UDP client
    public void OnDisable ()
    {
        if (receiveThread != null)
        {
            receiveThread.Abort ();
            receiveThread = null;
        }

        client.Close ();
        Debug.Log ("UDPClient: exit");
    }
}

So, I tried nothing at this moment, because I'm inexperienced in this area, but this was working good until I put a library thing in Anylogic, maybe that is the problem, but I´m  not sure, so, anything will be welcome, and my expected results are that all the information is processed.

UPDATE
In the function ReceiveData after received = text; I put Debug.Log("UDPClient: message received \'" + received + "\'"); and deleted from function Update, and now the Debugs from both software are the same, now the question is, Where is the error that does not allow the updating of the data since they are read by Unity correctly.


问:
How To Predict Value Inside Model Loss With Using Current Model Weights?
I want to get other predicted value rather than y_true and y_pred inside model loss function. I have tried something but they didn't work so how can I use model.predict inside loss function in Tensorflow?</p>
```<code>class CustomLoss(tf.keras.losses.Loss):
  def __init__(self, anchor, positive, model):
    super().__init__()
    self.anchor=anchor
    self.positive=positive
    self.model=model
  def convert(self, image):
    c_im=self.model(image.reshape(1, 160, 160, 3))
    print(c_im)
    c_im=tf.make_ndarray(c_im)
    return c_im/np.linalg.norm(c_im, ord=2)
  def call(self, y_true, y_pred):
    y_pred_c=tf.cast(y_pred, dtype=tf.float32)
    anchor, positive = self.convert(self.anchor), self.convert(self.positive)
    anchor, positive = tf.convert_to_tensor(anchor, dtype=tf.float32), tf.convert_to_tensor(positive, dtype=tf.float32)
    pos_d=tf.reduce_sum(tf.square(tf.subtract(anchor, positive)), axis=-1)
    neg_d=tf.reduce_sum(tf.square(tf.subtract(anchor, y_pred_c)), axis=-1)
    basic_l=tf.add(tf.subtract(pos_d, neg_d), 0.2)
    print(basic_l)
    del anchor
    del positive
    return tf.reduce_sum(tf.maximum(basic_l, 0), axis=None)
</code>```

Body:
I want to get other predicted value rather than y_true and y_pred inside model loss function. I have tried something but they didn't work so how can I use model.predict inside loss function in Tensorflow?

class CustomLoss(tf.keras.losses.Loss):
  def __init__(self, anchor, positive, model):
    super().__init__()
    self.anchor=anchor
    self.positive=positive
    self.model=model
  def convert(self, image):
    c_im=self.model(image.reshape(1, 160, 160, 3))
    print(c_im)
    c_im=tf.make_ndarray(c_im)
    return c_im/np.linalg.norm(c_im, ord=2)
  def call(self, y_true, y_pred):
    y_pred_c=tf.cast(y_pred, dtype=tf.float32)
    anchor, positive = self.convert(self.anchor), self.convert(self.positive)
    anchor, positive = tf.convert_to_tensor(anchor, dtype=tf.float32), tf.convert_to_tensor(positive, dtype=tf.float32)
    pos_d=tf.reduce_sum(tf.square(tf.subtract(anchor, positive)), axis=-1)
    neg_d=tf.reduce_sum(tf.square(tf.subtract(anchor, y_pred_c)), axis=-1)
    basic_l=tf.add(tf.subtract(pos_d, neg_d), 0.2)
    print(basic_l)
    del anchor
    del positive
    return tf.reduce_sum(tf.maximum(basic_l, 0), axis=None)


问:
Mounting FS from Kernel
I am experimenting eCryptfs. It is quite good. I have encrypted one directory which is having some confidential data. I can view/edit this data by mounting it via ecrypts tools. While mounting it does ask me password. So I write a short script which will be non-interactive. All is good so far.

Now I am afraid that if someone reads this script then he might see that confidential data. So thinking if I write a short and simple kernel module, which will mount this directory for me OR this module will create a script upon insertion, which I can execute while boot up from initramfs itself and delete this script immediately once it's work done.

I am not sure that is this possible at all! If possible then is it ethical to do so?
If possible then it will be really helpful if someone guides me in proper direction.

Underlying OS is Ubuntu-22.04 and I am using custom kernel i.e. 5.15.85

Title: Mounting FS from Kernel


问:
Could not find or load main class Main.class in Multi Module Maven Project
I have a mulit-module Maven Project (with SpringBoot) where one submodule contains a Main class and the others do not.
Now, when I attempt to start the application I keep getting a Could not find or load main class Main.class error.

My folder looks as following:

```<code>root
\-- Submodule-1
   \-- src
     \-- main
       \-- java
         \-- com.company.package.blabla
           \-- Main.java
\-- Submodule-2
\-- Submodule-3
</code>```

The error appears by using the following command in the root directory: $java com.company.package.blabla.Main (I also tried it with backslashes instead of fullstops)

Funnily, this command works (while in the root directory): $java /Users/username/IdeaProjects/Work/projectName/Submodule-1/src/main/java/com/company/package/blabla/Main.java

What am I missing here?

Body:
I have a mulit-module Maven Project (with SpringBoot) where one submodule contains a Main class and the others do not.
Now, when I attempt to start the application I keep getting a Could not find or load main class Main.class error.

My folder looks as following:

root
\-- Submodule-1
   \-- src
     \-- main
       \-- java
         \-- com.company.package.blabla
           \-- Main.java
\-- Submodule-2
\-- Submodule-3

The error appears by using the following command in the root directory: $java com.company.package.blabla.Main (I also tried it with backslashes instead of fullstops)

Funnily, this command works (while in the root directory): $java /Users/username/IdeaProjects/Work/projectName/Submodule-1/src/main/java/com/company/package/blabla/Main.java

What am I missing here?


问:
react-native-app-auth Handling authorization Issue
I am using react-native-app-auth getting this error while implementing the authorization.

```<code>2023-01-03 18:48:45.395 17596-17631/com.appName E/AppAuth: Network error when retrieving discovery document
java.io.FileNotFoundException: https://com.example.com/login/oauth/authorize/.well-known/openid-configuration
com.android.okhttp.internal.huc.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:255) com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.getInputStream(DelegatingHttpsURLConnection.java:211)
com.android.okhttp.internal.huc.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:30)
</code>```

My Authorization Url looks like-
https://YOUR_DOMAIN/authorize?response_type=code&client_id=YOUR_CLIENT_ID&redirect_uri=https://YOUR_APP/callback&scope={scope}&audience={apiAudience}&state={state}

I have followed this (https://authguidance.com/android-setup/) below document to implement for android.

Body:
I am using react-native-app-auth getting this error while implementing the authorization.

2023-01-03 18:48:45.395 17596-17631/com.appName E/AppAuth: Network error when retrieving discovery document
java.io.FileNotFoundException: https://com.example.com/login/oauth/authorize/.well-known/openid-configuration
com.android.okhttp.internal.huc.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:255) com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.getInputStream(DelegatingHttpsURLConnection.java:211)
com.android.okhttp.internal.huc.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:30)

My Authorization Url looks like-
https://YOUR_DOMAIN/authorize?response_type=code&client_id=YOUR_CLIENT_ID&redirect_uri=https://YOUR_APP/callback&scope={scope}&audience={apiAudience}&state={state}

I have followed this (https://authguidance.com/android-setup/) below document to implement for android.


问:
Manage Database on iPad Swift Playgrounds
I need a little help if anyone wants to explain to me how to use properly a database on the Swift Playground.

I am programming from an iPad and not from a Mac, either way, it is my first contact with Swift, so I’m lost trying to use a database in this environment.

I just want to do an app for personal use, I am not planning on publishing the app.

So basically what I want is an app to have a database where I can export and import from iPad to Windows.

I am using sqlite3, and an SQLite database.

What I have tried is to connect to the database from resources, but I was not able to write, I did some research and I understand that from resources it can’t be modified if the app is running.

What I was gonna try to do next is use the applicationSupportDirectory and use it from there.

I didn't do the test yet but I understand there objectively it works, but I don’t know how to export the database from that path.

I tried exporting and opening the project on Windows with .rar, but I didn’t find the documents folder.

Another option I tested is to copy the database from resources to the applicationSupportDirectory, but next, I don’t know how to export it from there, an option I have seen is to export in a CSV, but I prefer if the database file if it’s possible.

Another thing I tried is making the database read/write with multiple connections with PRAGMA journal_wal=wal, I think the command it’s like that. But I was getting an error making any query like select or insert.

And last, I did research if the app can access the system files, like Downloads, to try to export there or connect direct the connection from there, but I didn’t find anything about having access to the system.

Thanks in advance.


问:
Generic type with keyof not accepted
I have a function which is called either with a record or an interface, but using a generic type does not work:

```<code>interface Iface {
  add?: string;
  create?: string;
}

// TS2322: Type 'string' is not assignable to type 'T[keyof T]'.
function f<T extends Iface|Record<string, string>>(key:keyof T, obj:T){
  obj[key] = 'something';
}

function fi(key: keyof Iface, obj: Iface) {
  obj[key] = 'something';
}

function fr(key: string, obj: Record<string, string>) {
  obj[key] = 'something';
}
</code>```

typescript complains about function f. Why?

-- Edit --

What's wrong with this?

```<code>function f3<T extends Record<string, string>>(key:string, obj:T){
  obj[key] = 'something';
}
</code>```

Title: Generic type with keyof not accepted

Body:
I have a function which is called either with a record or an interface, but using a generic type does not work:

interface Iface {
  add?: string;
  create?: string;
}

// TS2322: Type 'string' is not assignable to type 'T[keyof T]'.
function f<T extends Iface|Record<string, string>>(key:keyof T, obj:T){
  obj[key] = 'something';
}

function fi(key: keyof Iface, obj: Iface) {
  obj[key] = 'something';
}

function fr(key: string, obj: Record<string, string>) {
  obj[key] = 'something';
}

typescript complains about function f. Why?

-- Edit --

What's wrong with this?

function f3<T extends Record<string, string>>(key:string, obj:T){
  obj[key] = 'something';
}


问:
I am facing a problem while importing and build base project in eclipse for castle enviroment
I found a problem while importing project in castle eclipse enviroment

```<code>> Task :compileJava FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':compileJava'.
> Could not resolve all files for configuration ':compileClasspath'.
   > Could not download systems-common-java8.jar (systems.uom:systems-common-java8:1.0)
      > Could not get resource 'https://jcenter.bintray.com/systems/uom/systems-common-java8/1.0/systems-common-java8-1.0.jar'.
         > Could not HEAD 'https://jcenter.bintray.com/systems/uom/systems-common-java8/1.0/systems-common-java8-1.0.jar'.
            > sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
   > Could not download si-units-java8.jar (si.uom:si-units-java8:1.2)
      > Could not get resource 'https://jcenter.bintray.com/si/uom/si-units-java8/1.2/si-units-java8-1.2.jar'.
</code>```

the error while build the project using command gradlew build

Body:
I found a problem while importing project in castle eclipse enviroment

> Task :compileJava FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':compileJava'.
> Could not resolve all files for configuration ':compileClasspath'.
   > Could not download systems-common-java8.jar (systems.uom:systems-common-java8:1.0)
      > Could not get resource 'https://jcenter.bintray.com/systems/uom/systems-common-java8/1.0/systems-common-java8-1.0.jar'.
         > Could not HEAD 'https://jcenter.bintray.com/systems/uom/systems-common-java8/1.0/systems-common-java8-1.0.jar'.
            > sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
   > Could not download si-units-java8.jar (si.uom:si-units-java8:1.2)
      > Could not get resource 'https://jcenter.bintray.com/si/uom/si-units-java8/1.2/si-units-java8-1.2.jar'.

the error while build the project using command gradlew build


问:
Trying to use Same column as primary key in multiple tables, ''invalid field definition of index or relationship fix" error appears
I am new to MS Access. I have created 5 tables and this is my relationship view:

relationship

But when I am trying to establish a relationship between tblCard.CardID and tblFacilities.CardID, I get an error

invalid field definition of index or relationship fix

All the CardID columns are autonumber.

Can anyone please tell me why this problem is appearing?

Thanks in advance

I checked the indexing of all the CardID columns. I don't understand why this is happening.


问:
Issue while switching to speaker on Android mobile web application
I am using WEBRTC for implementing Voice calling chat APP. When I call from PC to Android Mobile using chrome application, both are able to listen each other voice. But on switching to speaker in Mobile by replacing Media stream track the mobile is able to listen his voice as well as computer one's and the computer one is not able to listen the voice of android mobile one's. For improving this issue ,I implemented ReplaceTrack method. This improved the previous issue but Now the scenario is, on switching for the first time to speaker works properly. But on switching 2nd time to speaker create the same problem.

I have tried ReplaceTrack method for improving this problem. But it work good for the 1st time and again on switching to speaker both are not able to listen each other's voice.


问:
Simulating non-linear ARX model doesn't work
I estimated a non-linear ARX model with the sytem identification toolbox in matlab and tried to simulate the response to a validation data set. Unfortunatly the response seems to be not stable and doesn't lead to the results obtained from the compare fcn.

nlarx2 is my model:

opt3=simOptions("InputOffset",4,"InitialCondition",IO); sim(nlarx2,Data_val1.InputData,opt3)

The initial condition is obtained from the estimation data set from the compare fcn

I dont know if I have to add the discretness of the model or what else could be wrong. The error message says:

">> sim(nlarx2,Data_val1.InputData,opt3)
Warning: Model output became non-finite at time 58 seconds. Aborting the rest of the simulation.

In idnlarx/utsim>localInfNanWarn (line 79)
In idnlarx/utsim (line 61)
In idnlarx/sim_ (line 129)
In idmodel/sim (line 113) "

I obtain a figure, but not a useful one.

Thank you for your help


问:
Response objects get serialized as Strings if I use 3rd party response types

The issue

I'm implementing a GraphQL api and have ran into the issue that whenever I'm using any java type not defined in the local source code as part of the response then the whole response gets serialized as a String instead of as the proper json object I'm expecting. I see this same issue using two different java server/grapql implementations (OpenLiberty/Microprofile & KumuluzEE). This leads me to think that there is some key reason for this that I just fail to understand. Would greatly appreciate some enlightenment on this.

In more detail

Let's say I have a class User that looks like this:

```<code>{
    String id;
    String name;
}
</code>```

If I define this in the source of the project that has the graphql api impl the response gets serialized properly to something like this:

```<code>{
  "data": {
    "getUser": {
      "id": "12345",
      "name": "John Doe"
    }
  }
}
</code>```

But if I pull in User as a dependency to my api impl project then the response will instead be something like this:

```<code>{
  "data": {
    "getUser": "{\"id\":\"12345\", \"name\":\"John Doe\"}"
  }
}
</code>```

Essentially useless. This leads to having to duplicate a bunch of types across microservices in the namespace. Any explanation for this behaviour or way around it would be very helpful. As mentioned at first I just guessed it was some limitation in the particular graphql impl I was using (OpenLiberty/Microprofile) but I've now seen the same issue manifest with a different one also.

Many thanks.

Body:
The issue

I'm implementing a GraphQL api and have ran into the issue that whenever I'm using any java type not defined in the local source code as part of the response then the whole response gets serialized as a String instead of as the proper json object I'm expecting. I see this same issue using two different java server/grapql implementations (OpenLiberty/Microprofile & KumuluzEE). This leads me to think that there is some key reason for this that I just fail to understand. Would greatly appreciate some enlightenment on this.

In more detail

Let's say I have a class User that looks like this:

{
    String id;
    String name;
}

If I define this in the source of the project that has the graphql api impl the response gets serialized properly to something like this:

{
  "data": {
    "getUser": {
      "id": "12345",
      "name": "John Doe"
    }
  }
}

But if I pull in User as a dependency to my api impl project then the response will instead be something like this:

{
  "data": {
    "getUser": "{\"id\":\"12345\", \"name\":\"John Doe\"}"
  }
}

Essentially useless. This leads to having to duplicate a bunch of types across microservices in the namespace. Any explanation for this behaviour or way around it would be very helpful. As mentioned at first I just guessed it was some limitation in the particular graphql impl I was using (OpenLiberty/Microprofile) but I've now seen the same issue manifest with a different one also.

Many thanks.


问:
Go to Symbol doesn't seem to work in VSCode for Sass files, how do I get it to work?
I have a .scss file and also I have the Sass extension installed but Go to Symbol... doesn't seem to understand the sass structure. When I type @pre .super i it shows no results. Am I missing some configuration or some extension?


问:
Jest Mockup ldap in nodejs
Here is my AD class code I am using ldapjs library and trying to mock its add method but facing some warning which cause code coverage issue

```<code>const ldap = require('ldapjs');
    class AD {
     /**
     * Create Connection Active Directory
     */
     async createConnection(){
        return new Promise((resolve, reject) => {

            var options = {
                'rejectUnauthorized': false,
            };

            this.ADConnnection = ldap.createClient({
                url: [
                    process.env.LDAP_SERVER_1 + ':' + process.env.LDAP_SERVER_PORT,
                ],
                reconnect: true,
                tlsOptions: options
            });

            this.ADConnnection.on('error', (err) => {
                reject(err)
            })

            this.ADConnnection.bind(this.ldapUsername, this.ldapPassword, async (err) => {
                if (err) {
                    reject(err)
                }
            });

            resolve(true)
        });
    }

    /**
     * Create Record in Active Directory
     * @param {*} oRequest
     * @param {*} oEntry
     */
    async create(oRequest, oADCreateUserDT) {
        const sUsername = oRequest.vpnUsername;
        this.adOu = oRequest.apiUser;
        let oEntry = oADCreateUserDT.ADCreateUserData();

        if(oEntry.hasOwnProperty('msRADIUSFramedIPAddress')){
            this.adOu = ADConstant.AD_PARAMS.OU_DED;
            oADCreateUserDT.setTitle(ADConstant.AD_PARAMS.OU_DED);
            oEntry = oADCreateUserDT.ADCreateUserData();
        }

        return new Promise(async (resolve, reject) => {
            this.ADConnnection.add('cn=' + sUsername + ',ou=' + this.adOu + ',' + this.dc, oEntry, (err) => {
                if (err) {
                    reject(err);
                } else {
                    resolve(true);
                }
            });
            await this.closeConnection()
        });

    }

    async closeConnection() {
        this.ADConnnection.unbind(err => {
            if (err) {
                reject(err)
            }
        }, () => {
            this.ADConnnection.destroy();
        });
    }
   }

module.exports = AD;
</code>```

Now this is my test class (I am using jest for nodejs testing)

```<code>const AD = require("../../app/libraries/AD");
const ldap = require('ldapjs');

jest.mock('ldapjs', () => {
    return jest.fn().mockImplementation(() => {
        return {
            createClient: jest.fn(),
            add: jest.fn(() => Promise.resolve(true)),
        }
    })
});

const isDedicatedIP = true;
const oRequest = { uuid: "vpn00s01" }
const oEntry = { UserAccountControl: ADConstant.AD_PARAMS.AD_ACC_CONTROL_ENABLE }
const oSearch = { attributes: ["cn", "Accountexpires", "UserAccountControl"], scope: "sub", filter: "" }

describe('should test all cases of ldap function', () => {

    test('should test constructor', async () => {
        const oAD = new AD()
        const response = oAD
        expect(JSON.stringify(response)).toBe(JSON.stringify({ "dc": "dc=undefined,dc=undefined", "adOu": "purevpn", "objectclass": "user" }));
    });

    test('should set Adu', async () => {
        const oAD = new AD()
        const response = oAD.setAdOu(isDedicatedIP)
        expect(JSON.stringify(response)).toBe(JSON.stringify({}));
    });

    test('should test create form ldap', async () => {
        const oAD = new AD()
        const response = oAD.create(oRequest, oADCreateUserDT)
        expect(JSON.stringify(response)).toBe(JSON.stringify({}));
    });
});
</code>```

While running this jest test facing this issue

I don't understand how to mock my ldapjs methods. Even after adding in in mock implementation still having the same issue

Title: Jest Mockup ldap in nodejs

Body:
Here is my AD class code I am using ldapjs library and trying to mock its add method but facing some warning which cause code coverage issue

const ldap = require('ldapjs');
    class AD {
     /**
     * Create Connection Active Directory
     */
     async createConnection(){
        return new Promise((resolve, reject) => {

            var options = {
                'rejectUnauthorized': false,
            };

            this.ADConnnection = ldap.createClient({
                url: [
                    process.env.LDAP_SERVER_1 + ':' + process.env.LDAP_SERVER_PORT,
                ],
                reconnect: true,
                tlsOptions: options
            });

            this.ADConnnection.on('error', (err) => {
                reject(err)
            })

            this.ADConnnection.bind(this.ldapUsername, this.ldapPassword, async (err) => {
                if (err) {
                    reject(err)
                }
            });

            resolve(true)
        });
    }

    /**
     * Create Record in Active Directory
     * @param {*} oRequest
     * @param {*} oEntry
     */
    async create(oRequest, oADCreateUserDT) {
        const sUsername = oRequest.vpnUsername;
        this.adOu = oRequest.apiUser;
        let oEntry = oADCreateUserDT.ADCreateUserData();

        if(oEntry.hasOwnProperty('msRADIUSFramedIPAddress')){
            this.adOu = ADConstant.AD_PARAMS.OU_DED;
            oADCreateUserDT.setTitle(ADConstant.AD_PARAMS.OU_DED);
            oEntry = oADCreateUserDT.ADCreateUserData();
        }

        return new Promise(async (resolve, reject) => {
            this.ADConnnection.add('cn=' + sUsername + ',ou=' + this.adOu + ',' + this.dc, oEntry, (err) => {
                if (err) {
                    reject(err);
                } else {
                    resolve(true);
                }
            });
            await this.closeConnection()
        });

    }

    async closeConnection() {
        this.ADConnnection.unbind(err => {
            if (err) {
                reject(err)
            }
        }, () => {
            this.ADConnnection.destroy();
        });
    }
   }

module.exports = AD;

Now this is my test class (I am using jest for nodejs testing)

const AD = require("../../app/libraries/AD");
const ldap = require('ldapjs');

jest.mock('ldapjs', () => {
    return jest.fn().mockImplementation(() => {
        return {
            createClient: jest.fn(),
            add: jest.fn(() => Promise.resolve(true)),
        }
    })
});

const isDedicatedIP = true;
const oRequest = { uuid: "vpn00s01" }
const oEntry = { UserAccountControl: ADConstant.AD_PARAMS.AD_ACC_CONTROL_ENABLE }
const oSearch = { attributes: ["cn", "Accountexpires", "UserAccountControl"], scope: "sub", filter: "" }

describe('should test all cases of ldap function', () => {

    test('should test constructor', async () => {
        const oAD = new AD()
        const response = oAD
        expect(JSON.stringify(response)).toBe(JSON.stringify({ "dc": "dc=undefined,dc=undefined", "adOu": "purevpn", "objectclass": "user" }));
    });

    test('should set Adu', async () => {
        const oAD = new AD()
        const response = oAD.setAdOu(isDedicatedIP)
        expect(JSON.stringify(response)).toBe(JSON.stringify({}));
    });

    test('should test create form ldap', async () => {
        const oAD = new AD()
        const response = oAD.create(oRequest, oADCreateUserDT)
        expect(JSON.stringify(response)).toBe(JSON.stringify({}));
    });
});

While running this jest test facing this issue

I don't understand how to mock my ldapjs methods. Even after adding in in mock implementation still having the same issue


问:
Spring Boot sort by nested Entity
I am trying to sort my API result by a nested entity field.

My Entities look like that:

@Entity
@Table(name = "book_item")
public class BookItem {

    @Id
    @Column(name = "id", nullable = false)
    @GeneratedValue(strategy = GenerationType.AUTO)
    private UUID id;

    @ManyToOne
    @NotNull
    private Book book;

    ...
}
```
<pre class="lang-java prettyprint-override"><code>@Entity
@Table(name = "book")
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class Book {

    @Id
    @Column(name = "id")
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator")
    @SequenceGenerator(name = "sequenceGenerator")
    private Long id;

    @Column(name = "title", nullable = false)
    private String title;

    private String subtitle;

    @ManyToMany(fetch = FetchType.EAGER, cascade = { CascadeType.PERSIST, CascadeType.MERGE })
    @JoinTable(name = "rel_book_author", joinColumns = @JoinColumn(name = "book_id"), inverseJoinColumns = @JoinColumn(name = "author_id"))
    @Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
    @JsonIgnoreProperties(value = { "books" }, allowSetters = true)
    private Set<Author> authors = new HashSet<>();

    @Column(name = "isbn", nullable = false)
    private String isbn;

    @Column(name = "pages", nullable = false)
    private Integer pages;
    ...
}
</code>```

Now I want to query all BookItems sorted by the Book titles.

My repository lloks like that:

public interface BookItemRepository extends JpaRepository<BookItem, UUID> {
    @Query(
        "select distinct b from BookItem b left join b.book.authors authors where (upper(authors.name) like upper(concat('%', ?2, '%')) or authors is NULL ) and upper(b.book.title) like upper(concat('%', ?1, '%'))"
    )
    Page<BookItem> findAllByTitleAndAuthor(String title, String name, Pageable pageable);
}
```
<p>I've implemented an Angular component which does the following request:</p>
<pre class="lang-http prettyprint-override"><code>GET http://localhost:9000/api/book/items?size=5&sort=title,asc
</code>```

I get a 500 error code:

```<code>org.hibernate.QueryException: could not resolve property: title of: org.pickwicksoft.libraary.domain.BookItem [select distinct b from org.pickwicksoft.libraary.domain.BookItem b left join b.book.authors authors where (upper(authors.name) like upper(concat('%', ?2, '%')) or authors is NULL ) and upper(b.book.title) like upper(concat('%', ?1, '%')) order by b.title asc, b.id asc]; nested exception is java.lang.IllegalArgumentException
</code>```

I also tried the following and it also does not work:

GET http://localhost:9000/api/book/items?size=5&sort=book_title,asc
```

How can I solve this problem?

Title: Spring Boot sort by nested Entity

Body:
I am trying to sort my API result by a nested entity field.

My Entities look like that:

@Entity
@Table(name = "book_item")
public class BookItem {

    @Id
    @Column(name = "id", nullable = false)
    @GeneratedValue(strategy = GenerationType.AUTO)
    private UUID id;

    @ManyToOne
    @NotNull
    private Book book;

    ...
}

@Entity
@Table(name = "book")
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class Book {

    @Id
    @Column(name = "id")
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator")
    @SequenceGenerator(name = "sequenceGenerator")
    private Long id;

    @Column(name = "title", nullable = false)
    private String title;

    private String subtitle;

    @ManyToMany(fetch = FetchType.EAGER, cascade = { CascadeType.PERSIST, CascadeType.MERGE })
    @JoinTable(name = "rel_book_author", joinColumns = @JoinColumn(name = "book_id"), inverseJoinColumns = @JoinColumn(name = "author_id"))
    @Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
    @JsonIgnoreProperties(value = { "books" }, allowSetters = true)
    private Set<Author> authors = new HashSet<>();

    @Column(name = "isbn", nullable = false)
    private String isbn;

    @Column(name = "pages", nullable = false)
    private Integer pages;
    ...
}

Now I want to query all BookItems sorted by the Book titles.

My repository lloks like that:

public interface BookItemRepository extends JpaRepository<BookItem, UUID> {
    @Query(
        "select distinct b from BookItem b left join b.book.authors authors where (upper(authors.name) like upper(concat('%', ?2, '%')) or authors is NULL ) and upper(b.book.title) like upper(concat('%', ?1, '%'))"
    )
    Page<BookItem> findAllByTitleAndAuthor(String title, String name, Pageable pageable);
}

I've implemented an Angular component which does the following request:

GET http://localhost:9000/api/book/items?size=5&sort=title,asc

I get a 500 error code:

org.hibernate.QueryException: could not resolve property: title of: org.pickwicksoft.libraary.domain.BookItem [select distinct b from org.pickwicksoft.libraary.domain.BookItem b left join b.book.authors authors where (upper(authors.name) like upper(concat('%', ?2, '%')) or authors is NULL ) and upper(b.book.title) like upper(concat('%', ?1, '%')) order by b.title asc, b.id asc]; nested exception is java.lang.IllegalArgumentException

I also tried the following and it also does not work:

GET http://localhost:9000/api/book/items?size=5&sort=book_title,asc

How can I solve this problem?


问:
Is it possible to make a server respond to only a single particular loopback address?
Loopback addresses fall in the exclusive range of 127.0.0.0/8.

What I'm trying to ascertain is that whether it's possible to program any server to respond only to a single/select few loopback addresses among those.

The idea here is to have multiple servers running on the same machine. Lets say there are two. One of them responds only to something like 127.0.0.1:8080/route/to/content while the other only responds to something like 127.0.0.2:8080/route/to/content.

So you could have two servers running on the same machine, listening on the same port, even have identical route names which their routing code is programmed to handle.

But the user of the machine that the two servers are running on, can choose which one of them responds by specifying 127.0.0.1 or 127.0.0.2 in 127.0.0.x:8080/route/to/content.

Can this be accomplished (in all backend tech stacks)?

Thanks and apologies in advance if this is a noob question. I have exactly zero experience in backend development. I looked around for information on this but couldn't find any posts that said anything clearly on this specific issue per se.


问:
NodeJS Scripting issue with value sum definition
The home gas-meter is providing the actual gas count. With the subtraction (last minus before) I get 'Delta_Gas'. This is working.
Now I am trying to sum up gas these consumption values greater 0. In a typical cycle after gas burner ON max.10 values need to be summed up every minute. With burner OFF gas consumption should be set to zero(0).

Finally I want to see the gas consumption values for each single burner ON/OFF cycle.
Who can support my approach as I am a little bit lost?

```<code>var v1 = dp('/User Registers/Delta_Gas');
var sum = dp('/User Registers/Sum_Gas')
var s1;

AddValues(s1);
setInterval(AddValues, 3600000, s1); //1h Laufzeit

function AddValues(s1)
const add = add + v1
const sum = add
{
if(v1 > 0) { for (var i = 0; i < 10; i++) {
  console.log(sum)
}else{
  console.log(0)
}
</code>```

Body:
The home gas-meter is providing the actual gas count. With the subtraction (last minus before) I get 'Delta_Gas'. This is working.
Now I am trying to sum up gas these consumption values greater 0. In a typical cycle after gas burner ON max.10 values need to be summed up every minute. With burner OFF gas consumption should be set to zero(0).

Finally I want to see the gas consumption values for each single burner ON/OFF cycle.
Who can support my approach as I am a little bit lost?

var v1 = dp('/User Registers/Delta_Gas');
var sum = dp('/User Registers/Sum_Gas')
var s1;

AddValues(s1);
setInterval(AddValues, 3600000, s1); //1h Laufzeit

function AddValues(s1)
const add = add + v1
const sum = add
{
if(v1 > 0) { for (var i = 0; i < 10; i++) {
  console.log(sum)
}else{
  console.log(0)
}


问:
chromium always shows "about:blank" and stops working on raspberry pi 3A+
on raspberry pi 3A+ chromium always shows "about:blank" and stops working unless I close the tab manually and enable new tab

```<code>const puppeteer = require("puppeteer");

async function test() {
    const browser = await puppeteer.launch({
        headless: false,
        executablePath: "chromium-browser",
    });
    const [page] = await browser.pages();
    await page.evaluate(() => window.open("https://www.example.com/"));
    const page1 = await browser.newPage();
    page.close();
    await page1.goto("https://allegro.pl/");
    await page1.screenshot({ path: "hello.png" });
    await browser.close();
}
test();
</code>```

enter image description here

try to working code on my raspberry pi 3A+

Body:
on raspberry pi 3A+ chromium always shows "about:blank" and stops working unless I close the tab manually and enable new tab

const puppeteer = require("puppeteer");

async function test() {
    const browser = await puppeteer.launch({
        headless: false,
        executablePath: "chromium-browser",
    });
    const [page] = await browser.pages();
    await page.evaluate(() => window.open("https://www.example.com/"));
    const page1 = await browser.newPage();
    page.close();
    await page1.goto("https://allegro.pl/");
    await page1.screenshot({ path: "hello.png" });
    await browser.close();
}
test();

enter image description here

try to working code on my raspberry pi 3A+


问:
Cannot access ec2 Free tier instance from SSH
I'm trying to create a EC2 instance(t2.micro) but after lunching the instance there is no remote SSH access.

I created VPC and subnet

Public IPv4 address is assigned.

I created key pair and use it with putty

Network configuration

But when I create the instance there is no SSH access from my PC. I get connection timeout.

Also when I try to connect using connect feature I get: Failed to connect to your instance EC2 Instance Connect is unable to connect to your instance. Ensure your instance network settings are configured correctly for EC2 Instance Connect. For more information, see Set up EC2 Instance Connect at https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-connect-set-up.html.

Can you advise how I can fix this issue?


问:
Prisma solution to avoid n+1 with findUnique performs mutiple select id from table
I am using apollo server and nexus with Prisma.
I followed this guide to avoid n+1 problem:
https://www.prisma.io/docs/guides/performance-and-optimization/query-optimization-performance.
This is my User type:

```<code>const User = objectType({
    name: 'User',
    definition(t) {
      t.nonNull.id('id');
      t.nonNull.string('name');
      t.list.field('articles', {
        type: nonNull(Article),
        async resolve(parent, _args, ctx) {
          return ctx.prisma.user.findUnique({ where: { id: parent.id } }).articles();
        },
      });
      t.list.field('posts', {
        type: nonNull(Post),
        async resolve(parent, _args, ctx) {
          return ctx.prisma.user.findUnique({ where: { id: parent.id } }).posts();
        },
      });

    },
  });
</code>```

When invoking the following query:

```<code>query usersByName($names: [String]!) {
  users(names: $names) {
    id
    name
    articles {
      id
      name
    }
    posts {
      id
      name
    }
  }
}
</code>```

Prisma performs the following queries:

```<code>[server] prisma:query SELECT "public"."User"."id", "public"."User"."name" FROM "public"."User" WHERE "public"."User"."id" IN ($1,$2) OFFSET $3
[server] prisma:query SELECT "public"."User"."id" FROM "public"."User" WHERE "public"."User"."id" IN ($1,$2) OFFSET $3
[server] prisma:query SELECT "public"."User"."id" FROM "public"."User" WHERE "public"."User"."id" IN ($1,$2) OFFSET $3
[server] prisma:query SELECT "public"."User"."id" FROM "public"."User" WHERE "public"."User"."id" IN ($1,$2) OFFSET $3
[server] prisma:query SELECT "public"."Article"."id", "public"."Article"."userId", "public"."Article"."name" FROM "public"."Article" WHERE "public"."Article"."userId" IN ($1,$2) OFFSET $3
[server] prisma:query SELECT "public"."Post"."id", "public"."Post"."userId", "public"."Post"."name" FROM "public"."Post" WHERE "public"."Post"."userId" IN ($1,$2) OFFSET $3
</code>```

Why does prisma performs unneeded SELECT "public"."User"."id" FROM "public"."User" queries?
How can I avoid that?

Body:
I am using apollo server and nexus with Prisma.
I followed this guide to avoid n+1 problem:
https://www.prisma.io/docs/guides/performance-and-optimization/query-optimization-performance.
This is my User type:

const User = objectType({
    name: 'User',
    definition(t) {
      t.nonNull.id('id');
      t.nonNull.string('name');
      t.list.field('articles', {
        type: nonNull(Article),
        async resolve(parent, _args, ctx) {
          return ctx.prisma.user.findUnique({ where: { id: parent.id } }).articles();
        },
      });
      t.list.field('posts', {
        type: nonNull(Post),
        async resolve(parent, _args, ctx) {
          return ctx.prisma.user.findUnique({ where: { id: parent.id } }).posts();
        },
      });

    },
  });

When invoking the following query:

query usersByName($names: [String]!) {
  users(names: $names) {
    id
    name
    articles {
      id
      name
    }
    posts {
      id
      name
    }
  }
}

Prisma performs the following queries:

[server] prisma:query SELECT "public"."User"."id", "public"."User"."name" FROM "public"."User" WHERE "public"."User"."id" IN ($1,$2) OFFSET $3
[server] prisma:query SELECT "public"."User"."id" FROM "public"."User" WHERE "public"."User"."id" IN ($1,$2) OFFSET $3
[server] prisma:query SELECT "public"."User"."id" FROM "public"."User" WHERE "public"."User"."id" IN ($1,$2) OFFSET $3
[server] prisma:query SELECT "public"."User"."id" FROM "public"."User" WHERE "public"."User"."id" IN ($1,$2) OFFSET $3
[server] prisma:query SELECT "public"."Article"."id", "public"."Article"."userId", "public"."Article"."name" FROM "public"."Article" WHERE "public"."Article"."userId" IN ($1,$2) OFFSET $3
[server] prisma:query SELECT "public"."Post"."id", "public"."Post"."userId", "public"."Post"."name" FROM "public"."Post" WHERE "public"."Post"."userId" IN ($1,$2) OFFSET $3

Why does prisma performs unneeded SELECT "public"."User"."id" FROM "public"."User" queries?
How can I avoid that?


问:
AWS CDK How can I add an existing usage plan to api stage
CDK documentation define that I can import an external usage plan through the static function named fromUsagePlanId but this returns an Interface IUsagePlan but which interface doesn't have the method addApiStage to attach my Api and its stage.

my snippet code:

```<code>import * as apigateway from 'aws-cdk-lib/aws-apigateway';

export class CdkApiGwTemplateStack extends cdk.Stack {
  constructor(scope: Construct, id: string, props?: cdk.StackProps) {
    super(scope, id, props);

    const api = new apigateway.RestApi(this,`${domain.toLowerCase()}-${subDomain.toLowerCase()}`,
      {
        restApiName: `${domain.toLowerCase()}-${subDomain.toLowerCase()}`,
        description: apiDescription,
        binaryMediaTypes: binaryMediaTypes,
        deployOptions: {
          accessLogDestination: new LogGroupLogDestination(logGroup),
          loggingLevel:
            cloudwatchLoggingLevel.toUpperCase() as MethodLoggingLevel,
          stageName: environment.toLowerCase(),
          variables: variables,
        },
      }
    );

    const key = api.addApiKey('ApiKey', {
      apiKeyName: apikeyName,
      description: apiKeyDescription,
    });

    const plan = apigateway.UsagePlan.fromUsagePlanId(this, 'getExternalUsagePlan', usagePlanId);

    plan.addApiKey(key);

</code>```

I tried to search a cfn level 1 of cloudformation to do that, but I couldn't find out. How can I use method addApiStage of the constructor Usage Plan with the interface IUsagePlan or some idea of how can I add mi api to Usage plan existing?

Body:
CDK documentation define that I can import an external usage plan through the static function named fromUsagePlanId but this returns an Interface IUsagePlan but which interface doesn't have the method addApiStage to attach my Api and its stage.

my snippet code:

import * as apigateway from 'aws-cdk-lib/aws-apigateway';

export class CdkApiGwTemplateStack extends cdk.Stack {
  constructor(scope: Construct, id: string, props?: cdk.StackProps) {
    super(scope, id, props);

    const api = new apigateway.RestApi(this,`${domain.toLowerCase()}-${subDomain.toLowerCase()}`,
      {
        restApiName: `${domain.toLowerCase()}-${subDomain.toLowerCase()}`,
        description: apiDescription,
        binaryMediaTypes: binaryMediaTypes,
        deployOptions: {
          accessLogDestination: new LogGroupLogDestination(logGroup),
          loggingLevel:
            cloudwatchLoggingLevel.toUpperCase() as MethodLoggingLevel,
          stageName: environment.toLowerCase(),
          variables: variables,
        },
      }
    );

    const key = api.addApiKey('ApiKey', {
      apiKeyName: apikeyName,
      description: apiKeyDescription,
    });

    const plan = apigateway.UsagePlan.fromUsagePlanId(this, 'getExternalUsagePlan', usagePlanId);

    plan.addApiKey(key);

I tried to search a cfn level 1 of cloudformation to do that, but I couldn't find out. How can I use method addApiStage of the constructor Usage Plan with the interface IUsagePlan or some idea of how can I add mi api to Usage plan existing?


问:
pivot table in pandas
I have a dataframe such as :

```<code>Groups Species Value
G1     SP1     YES
G1     SP2     YES
G1     SP3     NO
G1     SP4     YES
G2     SP1     NO
G2     SP2     NO
G2     SP4     YES
G3     SP1     YES
G3     SP2     YES
G4     SP1     NO
</code>```

And I would liek simply to pivot the table such as :

```<code>Species  G1  G2  G3  G4
SP1      YES NO  YES NO
SP2      YES NO  YES NA
SP3      NO  NA  NA  NA
SP4      YES YES NA  NA
</code>```

So far I tried :

```<code>df.pivot(columns='Groups',index='Species',values=Value)
</code>```

But I get :

```<code>ValueError: Index contains duplicate entries, cannot reshape
</code>```

Title: pivot table in pandas

Body:
I have a dataframe such as :

Groups Species Value
G1     SP1     YES
G1     SP2     YES
G1     SP3     NO
G1     SP4     YES
G2     SP1     NO
G2     SP2     NO
G2     SP4     YES
G3     SP1     YES
G3     SP2     YES
G4     SP1     NO

And I would liek simply to pivot the table such as :

Species  G1  G2  G3  G4
SP1      YES NO  YES NO
SP2      YES NO  YES NA
SP3      NO  NA  NA  NA
SP4      YES YES NA  NA

So far I tried :

df.pivot(columns='Groups',index='Species',values=Value)

But I get :

ValueError: Index contains duplicate entries, cannot reshape


问:
Shopify orders/create webhook doesn't work
I'm trying to build a shopify app which users(customers) get automatically notified with e-mail, to achive this I'm trying to use orders/create webhook and test it by buying an item for free in the development store that my app is installed. But it doesn't work without giving an error in the console.

Here's my related code in the main index.js file;

```<code>import nodemailer from "nodemailer";

const smtpTransport = nodemailer.createTransport({
  service: "gmail",
  auth: {
    user: "*****@gmail.com",
    pass: "*******"
  }
});

async function sendEmail(to, subject, html) {
  const mailOptions = {
    from: "*****@gmail.com",
    to,
    subject,
    html
  };

  return smtpTransport.sendMail(mailOptions, (err, data)=>{
    if(err) console.log(err)
    else console.log("mail sent.")
  });
}
</code>```
```<code>
import { Shopify } from "@shopify/shopify-api";

Shopify.Webhooks.Registry.addHandler("ORDERS_CREATE", {
  path: "/api/webhooks",
  webhookHandler: async (_topic, _shop, body) => {
    // Parse the request body
    const payload = JSON.parse(body);

    // Get the email and name of the customer who made the purchase
    const { email, customer: { first_name, last_name } } = payload.customer;

    // Get the shipping address of the order
    const {
      address1,
      address2,
      city,
      province,
      country,
      zip
    } = payload.shipping_address;

    // Compose the email message
    const html = `
      <p>Dear ${first_name} ${last_name},</p>
      <p>Thank you for your purchase! Your order will be shipped to the following address:</p>
      <p>
        ${address1}<br>
        ${address2 ? address2 + "<br>" : ""}
        ${city}, ${province} ${zip}<br>
        ${country}
      </p>
      <p>We hope you enjoy your purchase!</p>
    `;

    // Send the email
    await sendEmail(
      email,
      "Thank you for your purchase!",
      html
    );
  },
});
</code>```
```<code> app.post("/api/webhooks", async (req, res) => {
    try {
      await Shopify.Webhooks.Registry.process(req, res);
      console.log(`Webhook processed, returned status code 200`);
    } catch (e) {
      console.log(`Failed to process webhook: ${e.message}`);
      if (!res.headersSent) {
        res.status(500).send(e.message);
      }
    }
  });
</code>```

Body:
I'm trying to build a shopify app which users(customers) get automatically notified with e-mail, to achive this I'm trying to use orders/create webhook and test it by buying an item for free in the development store that my app is installed. But it doesn't work without giving an error in the console.

Here's my related code in the main index.js file;

import nodemailer from "nodemailer";

const smtpTransport = nodemailer.createTransport({
  service: "gmail",
  auth: {
    user: "*****@gmail.com",
    pass: "*******"
  }
});

async function sendEmail(to, subject, html) {
  const mailOptions = {
    from: "*****@gmail.com",
    to,
    subject,
    html
  };

  return smtpTransport.sendMail(mailOptions, (err, data)=>{
    if(err) console.log(err)
    else console.log("mail sent.")
  });
}

import { Shopify } from "@shopify/shopify-api";

Shopify.Webhooks.Registry.addHandler("ORDERS_CREATE", {
  path: "/api/webhooks",
  webhookHandler: async (_topic, _shop, body) => {
    // Parse the request body
    const payload = JSON.parse(body);

    // Get the email and name of the customer who made the purchase
    const { email, customer: { first_name, last_name } } = payload.customer;

    // Get the shipping address of the order
    const {
      address1,
      address2,
      city,
      province,
      country,
      zip
    } = payload.shipping_address;

    // Compose the email message
    const html = `

Dear ${first_name} ${last_name},

Thank you for your purchase! Your order will be shipped to the following address:

        ${address1}

        ${address2 ? address2 + "
" : ""}
        ${city}, ${province} ${zip}

        ${country}

We hope you enjoy your purchase!

    `;

    // Send the email
    await sendEmail(
      email,
      "Thank you for your purchase!",
      html
    );
  },
});

 app.post("/api/webhooks", async (req, res) => {
    try {
      await Shopify.Webhooks.Registry.process(req, res);
      console.log(`Webhook processed, returned status code 200`);
    } catch (e) {
      console.log(`Failed to process webhook: ${e.message}`);
      if (!res.headersSent) {
        res.status(500).send(e.message);
      }
    }
  });


问:
Error: Illegal arguments: undefined, string
error in bcrypt with hashing password

```<code>password: bcrypt.hashSync(req.body.password, 8),
confirmpassword: bcrypt.hashSync(req.body.confirmpassword, 8)
</code>```

how to solve the error
tell about it

Body:
error in bcrypt with hashing password

password: bcrypt.hashSync(req.body.password, 8),
confirmpassword: bcrypt.hashSync(req.body.confirmpassword, 8)

how to solve the error
tell about it


问:
Mock pandas read_csv using pytest
I have a python function that takes a BigQuery bucket name & file path as inputs and does the following:

Check if the bucket it exists

Check if the file is in the bucket

Read the file into a dataframe and return the dataframe

The function looks something like this:

```<code>def function_to_test(client, bucket_name, delimiter, full_path=None, header=None):
    try:
        bucket = client.get_bucket(bucket_name)
        assert bucket is not None
    except (gcp_exceptions.GoogleCloudError, AssertionError) as ex:
        raise AirflowFailException(f"Failed to access bucket: {bucket_name}") from ex

    try:
        blob = bucket.get_blob(full_path)
        assert blob is not None
        if blob.size == 0:
            print(f'File is empty')
            return None
        df = pd.read_csv(f"gs://{bucket_name}/{full_path}", sep=delimiter, dtype='str', header=header)
        return df
    except(gcp_exceptions.GoogleCloudError, AssertionError) as ex:
        raise AirflowFailException(f"Failed to retrieve blob from bucket: {bucket_name}") from ex

</code>```

I am trying to write pytest tests for this function and so far I have the following:

```<code>def test_func(mocker, generic_df):
    bucket_name = 'test_bucket'
    full_path = 'test_path'
    mock_client = mocker.patch('google.cloud.storage.Client', autospec=True)
    mock_bucket = mock_client.get_bucket(bucket_name)
    actual_df =  function_to_test(client=mock_client,bucket_name=bucket_name, delimiter=',', full_path=full_path, header=0)
</code>```

Currently, the above mocking of the bucket is sufficient to pass the bucket requirements in the function.

However, I am unable to figure out how to mock the read_csv functionality and as such, the dataframe creation is failing.

Is there a way I can mock this function so that the dataframe is mocked too?

Title: Mock pandas read_csv using pytest

Body:
I have a python function that takes a BigQuery bucket name & file path as inputs and does the following:

Check if the bucket it exists

Check if the file is in the bucket

Read the file into a dataframe and return the dataframe

The function looks something like this:

def function_to_test(client, bucket_name, delimiter, full_path=None, header=None):
    try:
        bucket = client.get_bucket(bucket_name)
        assert bucket is not None
    except (gcp_exceptions.GoogleCloudError, AssertionError) as ex:
        raise AirflowFailException(f"Failed to access bucket: {bucket_name}") from ex

    try:
        blob = bucket.get_blob(full_path)
        assert blob is not None
        if blob.size == 0:
            print(f'File is empty')
            return None
        df = pd.read_csv(f"gs://{bucket_name}/{full_path}", sep=delimiter, dtype='str', header=header)
        return df
    except(gcp_exceptions.GoogleCloudError, AssertionError) as ex:
        raise AirflowFailException(f"Failed to retrieve blob from bucket: {bucket_name}") from ex

I am trying to write pytest tests for this function and so far I have the following:

def test_func(mocker, generic_df):
    bucket_name = 'test_bucket'
    full_path = 'test_path'
    mock_client = mocker.patch('google.cloud.storage.Client', autospec=True)
    mock_bucket = mock_client.get_bucket(bucket_name)
    actual_df =  function_to_test(client=mock_client,bucket_name=bucket_name, delimiter=',', full_path=full_path, header=0)

Currently, the above mocking of the bucket is sufficient to pass the bucket requirements in the function.

However, I am unable to figure out how to mock the read_csv functionality and as such, the dataframe creation is failing.

Is there a way I can mock this function so that the dataframe is mocked too?


问:
Webpack fail when running next build in gitlab ci (works fine locally) typescript
Trying to setup a ci/cd for the frontend team (I did not work on the frontend code directly, so I may be missing some things).

The frontend is made with next.js 13 and typescript.

I created a dockerfile which looks like this.

```<code>FROM node:16.17.1-alpine as builder

WORKDIR /app

COPY package*.json ./

RUN npm ci

COPY . .

RUN npm run build

FROM node:16.17.1-alpine as production

WORKDIR /app

COPY --from=builder /app/next.config.js ./
COPY --from=builder /app/public ./public
COPY --from=builder /app/.next ./.next
COPY --from=builder /app/node_modules ./node_modules
COPY --from=builder /app/package.json ./package.json

EXPOSE 80

CMD ["npm", "run", "start"]
</code>```

This works fine when I try building on my computer (MacBook M1 latest OS)

But this doesn't work on Gitlab CI. It gives me the "can't resolve module ...." error. Mainly with the @components module in the code.(not a problem locally btw)

My gitlab ci file looks like this (left some part out for security purposes)

```<code>build_and_push:
  only:
    - main
  stage: build
  image:
    name: amazon/aws-cli
    entrypoint: [""]
  services:
    - docker:dind
  before_script:
    - amazon-linux-extras install docker
    - aws --version
    - docker --version
    - docker login -u AWS -p $(aws ecr get-login-password --region $AWS_DEFAULT_REGION) $DOCKER_REGISTRY
  script:
    - docker build -t $DOCKER_REGISTRY/$REPO_NAME:$CI_COMMIT_TITLE --file Dockerfile.staging .
    - docker push $DOCKER_REGISTRY/$REPO_NAME:$CI_COMMIT_TITLE
</code>```

And here is my tsconfig.json

```<code>{
  "compilerOptions": {
    "target": "es5",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noEmit": true,
    "esModuleInterop": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "preserve",
    "baseUrl": ".",
    "paths": {
      "@components/*": [
        "components/*"
      ],
      "@utils/*": [
        "utils/*"
      ],
      "@lib/*": [
        "lib/*"
      ],
      "@services/*": [
        "services/*"
      ]
    },
    "incremental": true
  },
  "include": [
    "next-env.d.ts",
    "**/*.ts",
    "**/*.tsx"
  ],
  "exclude": [
    "node_modules"
  ]
}
</code>```

As you can see, the path has been added already and produced no problem when building locally.

here is the next.config.js

```<code>/** @type {import('next').NextConfig} */
const nextConfig = {
  // reactStrictMode: true,
  swcMinify: true,
  images: {
    domains: ['images.unsplash.com'],
  },
  eslint: {
    ignoreDuringBuilds: true
  },
  // typescript:{
  //   ignoreBuildErrors: true
  // }
};

module.exports = nextConfig;
</code>```

I am not sure what is causing the CI pipeline to not work. Has anyone faced this issue before?

Body:
Trying to setup a ci/cd for the frontend team (I did not work on the frontend code directly, so I may be missing some things).

The frontend is made with next.js 13 and typescript.

I created a dockerfile which looks like this.

FROM node:16.17.1-alpine as builder

WORKDIR /app

COPY package*.json ./

RUN npm ci

COPY . .

RUN npm run build

FROM node:16.17.1-alpine as production

WORKDIR /app

COPY --from=builder /app/next.config.js ./
COPY --from=builder /app/public ./public
COPY --from=builder /app/.next ./.next
COPY --from=builder /app/node_modules ./node_modules
COPY --from=builder /app/package.json ./package.json

EXPOSE 80

CMD ["npm", "run", "start"]

This works fine when I try building on my computer (MacBook M1 latest OS)

But this doesn't work on Gitlab CI. It gives me the "can't resolve module ...." error. Mainly with the @components module in the code.(not a problem locally btw)

My gitlab ci file looks like this (left some part out for security purposes)

build_and_push:
  only:
    - main
  stage: build
  image:
    name: amazon/aws-cli
    entrypoint: [""]
  services:
    - docker:dind
  before_script:
    - amazon-linux-extras install docker
    - aws --version
    - docker --version
    - docker login -u AWS -p $(aws ecr get-login-password --region $AWS_DEFAULT_REGION) $DOCKER_REGISTRY
  script:
    - docker build -t $DOCKER_REGISTRY/$REPO_NAME:$CI_COMMIT_TITLE --file Dockerfile.staging .
    - docker push $DOCKER_REGISTRY/$REPO_NAME:$CI_COMMIT_TITLE

And here is my tsconfig.json

{
  "compilerOptions": {
    "target": "es5",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noEmit": true,
    "esModuleInterop": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "preserve",
    "baseUrl": ".",
    "paths": {
      "@components/*": [
        "components/*"
      ],
      "@utils/*": [
        "utils/*"
      ],
      "@lib/*": [
        "lib/*"
      ],
      "@services/*": [
        "services/*"
      ]
    },
    "incremental": true
  },
  "include": [
    "next-env.d.ts",
    "**/*.ts",
    "**/*.tsx"
  ],
  "exclude": [
    "node_modules"
  ]
}

As you can see, the path has been added already and produced no problem when building locally.

here is the next.config.js

/** @type {import('next').NextConfig} */
const nextConfig = {
  // reactStrictMode: true,
  swcMinify: true,
  images: {
    domains: ['images.unsplash.com'],
  },
  eslint: {
    ignoreDuringBuilds: true
  },
  // typescript:{
  //   ignoreBuildErrors: true
  // }
};

module.exports = nextConfig;

I am not sure what is causing the CI pipeline to not work. Has anyone faced this issue before?


问:
stack overflow eror in c++
i am trying to make sand simulation but u get stack overflow Eror:

Unhandled exception at 0x00007FF66B384BD7 in Project2.exe: 0xC00000FD: Stack overflow (parameters: 0x0000000000000001, 0x000000D975E03000).
```
<p>And that is my code:</p>
```
#include <SFML/Window.hpp>
#include <SFML/Graphics.hpp>
#include <vector>
#include <iostream>
#include <Windows.h>

using std::vector;

const int Width = 1000;
const int Height = 800;

int main() {

    sf::RenderWindow window(sf::VideoMode(Width, Height), "title");

    vector <sf::CircleShape> Draw;
    float Platform[Width][Height];
    for (int i = 0; i < Width; i++) {
        for (int j = 0; j < Height; j++) {
            Platform[i][j] = 0;
        }
    }

    while (window.isOpen()) {

        sf::Event event;
        while (window.pollEvent(event)) {

            switch (event.type) {

            case sf::Event::Closed:
                window.close();
                break;

            default:
                break;

            } // event check

        } // while Event

        window.clear(sf::Color::Black);
        //////////////////////////

        if (sf::Mouse::isButtonPressed(sf::Mouse::Left)) {
            sf::Vector2i mousePosition{ sf::Mouse::getPosition(window) };
            sf::Vector2f mouseCoord{ window.mapPixelToCoords(mousePosition) };

            float x1 = mouseCoord.x;
            float y1 = mouseCoord.y;
            int x = (int)x1;
            int y = (int)y1;

            Platform[x][y] = 1;

        } // Mouse Pressed

        /////////////////////////
        window.display();

    }// main While

    return 0;
}
```

i try new option , but its not work and i use vector but get another eror

Title: stack overflow eror in c++

Body:
i am trying to make sand simulation but u get stack overflow Eror:

Unhandled exception at 0x00007FF66B384BD7 in Project2.exe: 0xC00000FD: Stack overflow (parameters: 0x0000000000000001, 0x000000D975E03000).

And that is my code:

#include <SFML/Window.hpp>
#include <SFML/Graphics.hpp>
#include <vector>
#include <iostream>
#include <Windows.h>

using std::vector;

const int Width = 1000;
const int Height = 800;

int main() {

    sf::RenderWindow window(sf::VideoMode(Width, Height), "title");

    vector <sf::CircleShape> Draw;
    float Platform[Width][Height];
    for (int i = 0; i < Width; i++) {
        for (int j = 0; j < Height; j++) {
            Platform[i][j] = 0;
        }
    }

    while (window.isOpen()) {

        sf::Event event;
        while (window.pollEvent(event)) {

            switch (event.type) {

            case sf::Event::Closed:
                window.close();
                break;

            default:
                break;

            } // event check

        } // while Event

        window.clear(sf::Color::Black);
        //////////////////////////

        if (sf::Mouse::isButtonPressed(sf::Mouse::Left)) {
            sf::Vector2i mousePosition{ sf::Mouse::getPosition(window) };
            sf::Vector2f mouseCoord{ window.mapPixelToCoords(mousePosition) };

            float x1 = mouseCoord.x;
            float y1 = mouseCoord.y;
            int x = (int)x1;
            int y = (int)y1;

            Platform[x][y] = 1;

        } // Mouse Pressed

        /////////////////////////
        window.display();

    }// main While

    return 0;
}

i try new option , but its not work and i use vector but get another eror


问:
How to use modelMapper to map to a nested DTO class
Here is the class that I want to map to a DTO class using modelMapper. UserDTO class has property AddressDTO

```<code>public class UserDTO {
    @NotNull
    private Long id;

    @NotNull
    private String username;

    @NotNull
    private String email;

    @NotNull
    private Boolean isActive;

    private AddressDTO address;
}
</code>```
```<code>public class AddressDTO {

    public Long addressId;

    public String homeNumber;

    private City city;

    private District district;

    private Ward ward;
}
</code>```

Please note that each user will have 0 or 1 address so that AdressDTO can be null. But when I use ModelMapper, it turns out to be null for all Users.

At first, I use constructor to map DTO manually.

```<code>private UserDTO mapToUserDTO(User user){
    UserDTO userDTO = new UserDTO();

    userDTO.setId(user.getId());
    userDTO.setUsername(user.getUsername());
    userDTO.setEmail(user.getEmail());
    userDTO.setIsActive(user.getIsActive());

    Address address = addressRepository.findAddressByUser(user);
    if (address == null)
        userDTO.setAddress(null);
    else {
        AddressDTO addressDTO = mapper.mapToDTO(address, AddressDTO.class);
        userDTO.setAddress(addressDTO);
    }
    return userDTO;
}
</code>```

The second time, I try fully with ModelMapper:

```<code>public DataResponse<List<UserDTO>> getAll() {
    List<User> users = userRepository.findAll();
    List<UserDTO> userDTOs = userMapper.mapToDTOList(users, UserDTO.class);

    return new DataResponse<>(userDTOs);
}
</code>```

So this time I try with ModelMapper and the AddressDTO appears to be null as I said before. Can anyone show me the way to fix it?

[Edited 1]
Here is the abstract class I create generic functions to mapToDTO

```<code>public class AbstractModelMapper <E,D>{
    @Autowired
    ModelMapper mapper;

    public D mapToDTO(E e, Class<D> d){ return e != null ? mapper.map(e,d) : null;}

    public E mapToEntity(D d, Class<E> e){ return d!= null ? mapper.map(d, e) : null;}

    public List<D> mapToDTOList(List<E> eList, Class<D> d){
        return eList != null ? eList.stream().map(e -> mapper.map(e,d)).collect(Collectors.toList()) : null;
    }
}
</code>```

Then I create Component Class for each entity. Example:

```<code>@Component
public class UserMapper extends AbstractModelMapper<User, UserDTO> {
}
</code>```

Lastly, I use it by using DI technique:

```<code>  @Autowired
    UserMapper userMapper;
</code>```

I am wondering whether create another configuration class for a specific situation like this.

Body:
Here is the class that I want to map to a DTO class using modelMapper. UserDTO class has property AddressDTO

public class UserDTO {
    @NotNull
    private Long id;

    @NotNull
    private String username;

    @NotNull
    private String email;

    @NotNull
    private Boolean isActive;

    private AddressDTO address;
}

public class AddressDTO {

    public Long addressId;

    public String homeNumber;

    private City city;

    private District district;

    private Ward ward;
}

Please note that each user will have 0 or 1 address so that AdressDTO can be null. But when I use ModelMapper, it turns out to be null for all Users.

At first, I use constructor to map DTO manually.

private UserDTO mapToUserDTO(User user){
    UserDTO userDTO = new UserDTO();

    userDTO.setId(user.getId());
    userDTO.setUsername(user.getUsername());
    userDTO.setEmail(user.getEmail());
    userDTO.setIsActive(user.getIsActive());

    Address address = addressRepository.findAddressByUser(user);
    if (address == null)
        userDTO.setAddress(null);
    else {
        AddressDTO addressDTO = mapper.mapToDTO(address, AddressDTO.class);
        userDTO.setAddress(addressDTO);
    }
    return userDTO;
}

The second time, I try fully with ModelMapper:

public DataResponse<List<UserDTO>> getAll() {
    List<User> users = userRepository.findAll();
    List<UserDTO> userDTOs = userMapper.mapToDTOList(users, UserDTO.class);

    return new DataResponse<>(userDTOs);
}

So this time I try with ModelMapper and the AddressDTO appears to be null as I said before. Can anyone show me the way to fix it?

[Edited 1]
Here is the abstract class I create generic functions to mapToDTO

public class AbstractModelMapper <E,D>{
    @Autowired
    ModelMapper mapper;

    public D mapToDTO(E e, Class<D> d){ return e != null ? mapper.map(e,d) : null;}

    public E mapToEntity(D d, Class<E> e){ return d!= null ? mapper.map(d, e) : null;}

    public List<D> mapToDTOList(List<E> eList, Class<D> d){
        return eList != null ? eList.stream().map(e -> mapper.map(e,d)).collect(Collectors.toList()) : null;
    }
}

Then I create Component Class for each entity. Example:

@Component
public class UserMapper extends AbstractModelMapper<User, UserDTO> {
}

Lastly, I use it by using DI technique:

  @Autowired
    UserMapper userMapper;

I am wondering whether create another configuration class for a specific situation like this.


问:
Do i need to delete newP (temp) after using it?
I asked a question about a code and someone recommended i used newP to add a class to a vector, it works, but i dont fully understand the concept behind that way of doing.

```<code>string creaPersoFini("y");
    vector<Personnage> tableauPerso;    // Tableau de Personnage, pas de string
    string nomPerso;
    int nbPerso(3);

    cout << "Trois personnages maximum, pour l'instant." << endl;
    while(creaPersoFini!="n" && nbPerso < 4)
    {
        cout << "Entrez le nom du personnage : ";
        cin >> nomPerso;
        Personnage newP(nomPerso);              // new temp person
        tableauPerso.push_back(newP);           // add the person
        cout << "Voulez vous creer un autre personnage ? y/n ";
        cin >> creaPersoFini;
    }
</code>```

Is this correct ? Do i need to delete the newP after adding it to the vector ? I know that if you create a pointer with new it is necessary to delete it afterward, is this what is happening here or not at all ?

I tried to look on internet and stackoverflow for an answer, but i only found parts of answers or quesitons/answers that are too complex for my current knowledge of C++.

If someone could explain to me in a simple way the difference between new/delete, newP and temporary using like these (or point me in a direction where i can find an answer) i'd be grateful !

Here is the link to the question where he recommended it, i used it because it works but since there was disagrement in the comments i'm not sure, and i'd like to be.

Body:
I asked a question about a code and someone recommended i used newP to add a class to a vector, it works, but i dont fully understand the concept behind that way of doing.

string creaPersoFini("y");
    vector<Personnage> tableauPerso;    // Tableau de Personnage, pas de string
    string nomPerso;
    int nbPerso(3);

    cout << "Trois personnages maximum, pour l'instant." << endl;
    while(creaPersoFini!="n" && nbPerso < 4)
    {
        cout << "Entrez le nom du personnage : ";
        cin >> nomPerso;
        Personnage newP(nomPerso);              // new temp person
        tableauPerso.push_back(newP);           // add the person
        cout << "Voulez vous creer un autre personnage ? y/n ";
        cin >> creaPersoFini;
    }

Is this correct ? Do i need to delete the newP after adding it to the vector ? I know that if you create a pointer with new it is necessary to delete it afterward, is this what is happening here or not at all ?

I tried to look on internet and stackoverflow for an answer, but i only found parts of answers or quesitons/answers that are too complex for my current knowledge of C++.

If someone could explain to me in a simple way the difference between new/delete, newP and temporary using like these (or point me in a direction where i can find an answer) i'd be grateful !

Here is the link to the question where he recommended it, i used it because it works but since there was disagrement in the comments i'm not sure, and i'd like to be.


问:
Request session ID is different every time ExpressJS and ReactJS
This is my front end code with react where I try to make a simple login

  const serverUrl = 'http://localhost:4000'

  async function login(email,password){
      const data = {
        Email: email,
        Password: password
      }
    const response = await  fetch(serverUrl+'/login',{
      method:'POST',
      credentials:'include',
      headers:{
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(data)
    })

    const outcome = await response.json()
    console.log(response.status)
    if(response.status === 200) {
      dispatch(authActions.login())

    }
    if(response.status === 404) {
      error(outcome.message)
    }
  }```
</div>
</div>
</p>
<p>Now the issue I have is every single time I press on the login button the session ID is different, which now gives me issue when I try to make session</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>app.use(
  cors({
    origin: 'http://localhost:3000',
    credentials: true,
    optionsSuccessStatus: 200
}))

//Method to login a user
app.use('/login', (request,response)=>{
  console.log(request.session)
  console.log(request.sessionID)
  console.log(request.session.id)
})</code>```

Body:
This is my front end code with react where I try to make a simple login

  const serverUrl = 'http://localhost:4000'

  async function login(email,password){
      const data = {
        Email: email,
        Password: password
      }
    const response = await  fetch(serverUrl+'/login',{
      method:'POST',
      credentials:'include',
      headers:{
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(data)
    })

    const outcome = await response.json()
    console.log(response.status)
    if(response.status === 200) {
      dispatch(authActions.login())

    }
    if(response.status === 404) {
      error(outcome.message)
    }
  }

Now the issue I have is every single time I press on the login button the session ID is different, which now gives me issue when I try to make session

app.use(
  cors({
    origin: 'http://localhost:3000',
    credentials: true,
    optionsSuccessStatus: 200
}))

//Method to login a user
app.use('/login', (request,response)=>{
  console.log(request.session)
  console.log(request.sessionID)
  console.log(request.session.id)
})


问:
How to load two fields from ListItemCollection into Datatable
Below I am accessing a SharePoint list and feeding it into a ListItemCollection which is working, but what I would like to do is feed two fields from the list into a DataTable (so the dt would have two columns), but I couldn't find anything that meets my requirements online. I'm also new to this. What would be the best way to do this?</p>
```<code>static void Main(string[] args)
{
    string siteUrl = ConfigurationManager.AppSettings["SiteUrl"];
    string clientID = ConfigurationManager.AppSettings["ClientId"];
    string clientSecret = ConfigurationManager.AppSettings["ClientSecret"];
    using (ClientContext cc = new AuthenticationManager().GetACSAppOnlyContext(siteUrl, clientID, clientSecret))
    {
        Web site = cc.Web;
        List targetList = site.Lists.GetByTitle("Companies");

        CamlQuery query = new CamlQuery();
        query.ViewXml = "<View><Query><Where><Contains><FieldRef Name='CompanyID'/><Value Type='Text'>Cumbria</Value></Contains></Where></Query></View>";
        ListItemCollection collListItem = targetList.GetItems(query);

        cc.Load(collListItem);
        cc.ExecuteQuery();

        if (collListItem.Count == 0)
        {
            Console.WriteLine("No items found.");
        }
        else
        {
            Console.WriteLine("Items found:\n");
            foreach (ListItem targetListItem in collListItem)
                Console.WriteLine(targetListItem["Reference"]);
            Console.ReadLine();
        }
    }
}
</code>```

Body:
Below I am accessing a SharePoint list and feeding it into a ListItemCollection which is working, but what I would like to do is feed two fields from the list into a DataTable (so the dt would have two columns), but I couldn't find anything that meets my requirements online. I'm also new to this. What would be the best way to do this?

static void Main(string[] args)
{
    string siteUrl = ConfigurationManager.AppSettings["SiteUrl"];
    string clientID = ConfigurationManager.AppSettings["ClientId"];
    string clientSecret = ConfigurationManager.AppSettings["ClientSecret"];
    using (ClientContext cc = new AuthenticationManager().GetACSAppOnlyContext(siteUrl, clientID, clientSecret))
    {
        Web site = cc.Web;
        List targetList = site.Lists.GetByTitle("Companies");

        CamlQuery query = new CamlQuery();
        query.ViewXml = "<View><Query><Where><Contains><FieldRef Name='CompanyID'/><Value Type='Text'>Cumbria</Value></Contains></Where></Query></View>";
        ListItemCollection collListItem = targetList.GetItems(query);

        cc.Load(collListItem);
        cc.ExecuteQuery();

        if (collListItem.Count == 0)
        {
            Console.WriteLine("No items found.");
        }
        else
        {
            Console.WriteLine("Items found:\n");
            foreach (ListItem targetListItem in collListItem)
                Console.WriteLine(targetListItem["Reference"]);
            Console.ReadLine();
        }
    }
}


问:
Method not found: '!!0 System.Text.Json.JsonSerializer.Deserialize(System.ReadOnlySpan`1<Byte>, System.Text.Json.JsonSerializerOptions)'
Just tried to create a new web api .net 6.0 and on first build/run getting error:

1>obj\Debug\net6.0\staticwebassets.build.json : error : MissingMethodException: Method not found: '!!0 System.Text.Json.JsonSerializer.Deserialize(System.ReadOnlySpan`1, System.Text.Json.JsonSerializerOptions)'.

Any Idea?!


问:
iwr : Unable to connect to the remote server
I have a problem in downloading spicetify from github trought powershell. I have tried enabling remote access and a few other things from this video:https://youtu.be/FzbqtmURcJo. But it doesnt work while trying to donwload the github file. The error shows this:

I have tried few solutions but it doesnt seem to work. Please help me and thanks in advance.


问:
unit test for custom email confirmation validator
I'm pretty new at programming and in need of a unit test for my email confirmation validator.
I use this validator for email confirmation. It's in a validation.ts file I use for all kinds of validators.

```<code>export function ConfirmEmailValidator(confirmEmailInput: string) {
  let confirmEmailControl: FormControl;
  let emailControl: FormControl;

  return (control: FormControl) => {
    if (!control.parent) {
      return null;
    }

    if (!confirmEmailControl) {
      confirmEmailControl = control;
      emailControl = control.parent.get(confirmEmailInput) as FormControl;
      emailControl.valueChanges.subscribe(() => {
        confirmEmailControl.updateValueAndValidity();
      });
    }

    if (emailControl.value?.toLocaleLowerCase() !==
      confirmEmailControl.value?.toLocaleLowerCase()
    ) {
      return { notMatch: true };
    }

    return null;
  };
}
</code>```

This is a snippet of my form group in my personaldetails.component.ts file. I use the validator like this:

```<code>email: [undefined, {
  validators: [Validators.required, Validators.email],
  asyncValidators: [some async validators],
  updateOn: 'blur'}],
confirmEmail: [undefined, {
  validators: [Validators.required, Validators.email, ConfirmEmailValidator('email')],
  updateOn: 'blur'}],
</code>```

Everything works as intended. I just need a unit test for it because SonarQube complains about missing tests for the validator, but I dont really know where to begin.
Maybe you guys have some Ideas

Body:
I'm pretty new at programming and in need of a unit test for my email confirmation validator.
I use this validator for email confirmation. It's in a validation.ts file I use for all kinds of validators.

export function ConfirmEmailValidator(confirmEmailInput: string) {
  let confirmEmailControl: FormControl;
  let emailControl: FormControl;

  return (control: FormControl) => {
    if (!control.parent) {
      return null;
    }

    if (!confirmEmailControl) {
      confirmEmailControl = control;
      emailControl = control.parent.get(confirmEmailInput) as FormControl;
      emailControl.valueChanges.subscribe(() => {
        confirmEmailControl.updateValueAndValidity();
      });
    }

    if (emailControl.value?.toLocaleLowerCase() !==
      confirmEmailControl.value?.toLocaleLowerCase()
    ) {
      return { notMatch: true };
    }

    return null;
  };
}

This is a snippet of my form group in my personaldetails.component.ts file. I use the validator like this:

email: [undefined, {
  validators: [Validators.required, Validators.email],
  asyncValidators: [some async validators],
  updateOn: 'blur'}],
confirmEmail: [undefined, {
  validators: [Validators.required, Validators.email, ConfirmEmailValidator('email')],
  updateOn: 'blur'}],

Everything works as intended. I just need a unit test for it because SonarQube complains about missing tests for the validator, but I dont really know where to begin.
Maybe you guys have some Ideas


问:
How to extract a sub-column from a pandas DataFrame?
I have several data frames namely df and df_new. I obtained df_new by these line of code where it checks any consecutive values in df[Rowcounter] column and group them together. The following code are as below:

```<code>
df = df.assign(group_no = (df.Rowcounter.diff() != 1).cumsum())
df.group_no.iat[0] = 1 if df.Rowcounter.iat[0] + 1 == df.Rowcounter.iat[1] else 0
df_new = df.groupby('group_no').agg(
    {'shopA_date_receive': ['first', 'last'],
     'shopB_date_receive': ['first', 'last']})

</code>```

Below are results obtained for df_new dataframe:

shopA_date_receive

shopB_date_receive

group_no
first
last
first

1
2019-09-01 00:03:22
2019-09-01 03:44:08
2019-09-01 00:09:52

2
2019-09-01 04:00:18
2019-09-01 08:28:03
2019-09-01 03:49:52

3
2019-09-01 08:59:41
2019-09-01 08:59:41
2019-09-01 08:49:52

4
2019-09-01 09:15:21
2019-09-01 14:14:35
2019-09-01 09:09:52

Now I want to create a new sets of data frame using loop and by making the ShopA_date_receive , first as conditions for the new sets of dataframe. The code would be something like:

```<code>for i in range of (len(df_new))
   df[i] =  df.loc[(df['shopA_date_receive'] >= df_new['shopA_date_receive','first']) & (df['shopA_date_receive'] <= df_new['shopA_date_receive','last'])]

###  kind of code  ###
</code>```

However, I failed to retrieve the single value of each 'first' and 'last' shopA_date_receive

I've made some reading and some actually suggest to look for multi-indexing and slicing but I cant seem quite to understand how the slices work in multi-index. These are my failed attempts to obtained the single value for either shopA_date_receive,first or shopA_date_receive,last:

1)

```<code>df_new.loc[:1,(slice(None), 'first')]
</code>```

resulting in:

shopA_date_receive

shopB_date_receive

group_no
first

first

1
2019-09-01 00:03:22

2019-09-01 00:09:52

2)

```<code>df_new.loc[:1,(slice(None), 'last')]
</code>```

resulting in:

shopA_date_receive

shopB_date_receive

group_no

last

1

2019-09-01 03:44:08

(the last date value still exist in the table shopB_date_receive,last but it seems invinsible when I type them down here)

Anyone have any ideas on how to tackle this problem? or maybe some better ways to sort the data out?  or maybe share any answered question that I might have missed. Appreciate your help.

Body:
I have several data frames namely df and df_new. I obtained df_new by these line of code where it checks any consecutive values in df[Rowcounter] column and group them together. The following code are as below:

df = df.assign(group_no = (df.Rowcounter.diff() != 1).cumsum())
df.group_no.iat[0] = 1 if df.Rowcounter.iat[0] + 1 == df.Rowcounter.iat[1] else 0
df_new = df.groupby('group_no').agg(
    {'shopA_date_receive': ['first', 'last'],
     'shopB_date_receive': ['first', 'last']})

Below are results obtained for df_new dataframe:

shopA_date_receive

shopB_date_receive

group_no
first
last
first

1
2019-09-01 00:03:22
2019-09-01 03:44:08
2019-09-01 00:09:52

2
2019-09-01 04:00:18
2019-09-01 08:28:03
2019-09-01 03:49:52

3
2019-09-01 08:59:41
2019-09-01 08:59:41
2019-09-01 08:49:52

4
2019-09-01 09:15:21
2019-09-01 14:14:35
2019-09-01 09:09:52

Now I want to create a new sets of data frame using loop and by making the ShopA_date_receive , first as conditions for the new sets of dataframe. The code would be something like:

for i in range of (len(df_new))
   df[i] =  df.loc[(df['shopA_date_receive'] >= df_new['shopA_date_receive','first']) & (df['shopA_date_receive'] <= df_new['shopA_date_receive','last'])]

###  kind of code  ###

However, I failed to retrieve the single value of each 'first' and 'last' shopA_date_receive

I've made some reading and some actually suggest to look for multi-indexing and slicing but I cant seem quite to understand how the slices work in multi-index. These are my failed attempts to obtained the single value for either shopA_date_receive,first or shopA_date_receive,last:

1)

df_new.loc[:1,(slice(None), 'first')]

resulting in:

shopA_date_receive

shopB_date_receive

group_no
first

first

1
2019-09-01 00:03:22

2019-09-01 00:09:52

2)

df_new.loc[:1,(slice(None), 'last')]

resulting in:

shopA_date_receive

shopB_date_receive

group_no

last

1

2019-09-01 03:44:08

(the last date value still exist in the table shopB_date_receive,last but it seems invinsible when I type them down here)

Anyone have any ideas on how to tackle this problem? or maybe some better ways to sort the data out?  or maybe share any answered question that I might have missed. Appreciate your help.