问:
Python Pyadomd query AAS using parameters
I am trying to query AAS using parameters and I have been using Pyadomd module, but I cannot find any way to complete this.

When I'm trying to execute this query, the server responds with the below error:

```<code><Parameters xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="urn:schemas-microsoft-com:xml-analysis">

         <Parameter>
          <Name>FromDate</Name>
          <Value xsi:type="xsd:string">20230111</Value>
        </Parameter>
        <Parameter>
          <Name>ToDate</Name>
          <Value xsi:type="xsd:string">20230111</Value>
        </Parameter>
      </Parameters>

evaluate

        FILTER (
            'Calendar',
            'Calendar'[CalendarID] >= VALUE ( @FromDate )
                && 'Calendar'[CalendarID] <= VALUE ( @ToDate )
        )
</code>```
```<code>AdomdErrorResponseException: The Execute element at line 7, column 24 (namespace urn:schemas-microsoft-com:xml-analysis) cannot appear under Envelope/Body/Execute/Command.

Technical Details:
RootActivityId: 022e8631-2d05-4169-8f93-033312d32f26
Date (UTC): 1/13/2023 1:31:55 PM
   at Microsoft.AnalysisServices.AdomdClient.XmlaClient.CheckForSoapFault(XmlReader reader, XmlaResult xmlaResult, Boolean throwIfError)
   at Microsoft.AnalysisServices.AdomdClient.XmlaClient.CheckForError(XmlReader reader, XmlaResult xmlaResult, Boolean throwIfError)
   at Microsoft.AnalysisServices.AdomdClient.XmlaClient.SendMessage(Boolean endReceivalIfException, Boolean readSession, Boolean readNamespaceCompatibility)
   at Microsoft.AnalysisServices.AdomdClient.XmlaClient.ExecuteStatement(String statement, IDictionary connectionProperties, IDictionary commandProperties, IDataParameterCollection parameters, Boolean isMdx)
   at Microsoft.AnalysisServices.AdomdClient.AdomdConnection.XmlaClientProvider.Microsoft.AnalysisServices.AdomdClient.IExecuteProvider.ExecuteTabular(CommandBehavior behavior, ICommandContentProvider contentProvider, AdomdPropertyCollection commandProperties, IDataParameterCollection parameters)
   at Microsoft.AnalysisServices.AdomdClient.AdomdCommand.ExecuteReader(CommandBehavior behavior)
</code>```

Python with Pyadomd module

Body:
I am trying to query AAS using parameters and I have been using Pyadomd module, but I cannot find any way to complete this.

When I'm trying to execute this query, the server responds with the below error:

<Parameters xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="urn:schemas-microsoft-com:xml-analysis">

         <Parameter>
          <Name>FromDate</Name>
          <Value xsi:type="xsd:string">20230111</Value>
        </Parameter>
        <Parameter>
          <Name>ToDate</Name>
          <Value xsi:type="xsd:string">20230111</Value>
        </Parameter>
      </Parameters>

evaluate

        FILTER (
            'Calendar',
            'Calendar'[CalendarID] >= VALUE ( @FromDate )
                && 'Calendar'[CalendarID] <= VALUE ( @ToDate )
        )

AdomdErrorResponseException: The Execute element at line 7, column 24 (namespace urn:schemas-microsoft-com:xml-analysis) cannot appear under Envelope/Body/Execute/Command.

Technical Details:
RootActivityId: 022e8631-2d05-4169-8f93-033312d32f26
Date (UTC): 1/13/2023 1:31:55 PM
   at Microsoft.AnalysisServices.AdomdClient.XmlaClient.CheckForSoapFault(XmlReader reader, XmlaResult xmlaResult, Boolean throwIfError)
   at Microsoft.AnalysisServices.AdomdClient.XmlaClient.CheckForError(XmlReader reader, XmlaResult xmlaResult, Boolean throwIfError)
   at Microsoft.AnalysisServices.AdomdClient.XmlaClient.SendMessage(Boolean endReceivalIfException, Boolean readSession, Boolean readNamespaceCompatibility)
   at Microsoft.AnalysisServices.AdomdClient.XmlaClient.ExecuteStatement(String statement, IDictionary connectionProperties, IDictionary commandProperties, IDataParameterCollection parameters, Boolean isMdx)
   at Microsoft.AnalysisServices.AdomdClient.AdomdConnection.XmlaClientProvider.Microsoft.AnalysisServices.AdomdClient.IExecuteProvider.ExecuteTabular(CommandBehavior behavior, ICommandContentProvider contentProvider, AdomdPropertyCollection commandProperties, IDataParameterCollection parameters)
   at Microsoft.AnalysisServices.AdomdClient.AdomdCommand.ExecuteReader(CommandBehavior behavior)

Python with Pyadomd module


来源: stackexchange

问:
how to send email in react native automatically using third party email service like emailjs?
I am creating a react native app and i want to send automatic email onpress
i did this in reactjs it is working fine but when applied this in react native, it is not working please tell me how to use in react native

```<code>import { View, Text, Button } from 'react-native'
import React from 'react'
import emailjs from '@emailjs/nodejs';

export default function App() {
  function emailer() {
    const templateParams = {
      name: 'James',
      notes: 'Check this out!',
    };

    emailjs
      .send('service_hw72nhc','template_h5zuoxb', templateParams, {
        publicKey: 'AYhHEr8nhLs3irJSN',
        privateKey: '_6ql6C0rLYo1aWnsCaxKD', // optional, highly recommended for security reasons
      })
      .then(
        (response) => {
          console.log('SUCCESS!', response.status, response.text);
        },
        (err) => {
          console.log('FAILED...', err);
        },
      );
    console.log("buton pressed")
  }
  return (
    <View style={{justifyContent:'center', alignItems:'center'}}>
      <Button title='Send Email' onPress={emailer} />
    </View>
  )
}
</code>```

I have tried this now please help

ContentLicense: CC BY-SA 4.0

Body:
I am creating a react native app and i want to send automatic email onpress
i did this in reactjs it is working fine but when applied this in react native, it is not working please tell me how to use in react native

import { View, Text, Button } from 'react-native'
import React from 'react'
import emailjs from '@emailjs/nodejs';

export default function App() {
  function emailer() {
    const templateParams = {
      name: 'James',
      notes: 'Check this out!',
    };

    emailjs
      .send('service_hw72nhc','template_h5zuoxb', templateParams, {
        publicKey: 'AYhHEr8nhLs3irJSN',
        privateKey: '_6ql6C0rLYo1aWnsCaxKD', // optional, highly recommended for security reasons
      })
      .then(
        (response) => {
          console.log('SUCCESS!', response.status, response.text);
        },
        (err) => {
          console.log('FAILED...', err);
        },
      );
    console.log("buton pressed")
  }
  return (
    <View style={{justifyContent:'center', alignItems:'center'}}>
      <Button title='Send Email' onPress={emailer} />
    </View>
  )
}

I have tried this now please help


问:
Using Test displayname with DynamicDataDisplayName in MSTest
[TestMethod("My Test Name")] can be use to change the name of a test in MSTest.
DynamicData attribute can be used to run the test on a collection of object where you can customize the datadisplayname for each run.

Unfortunately, when you try to use both for the same test like below, the test is not affected by the display name set.
Any idea if it's possible to get the two attributes working at the same time.

```<code>[TestMethod("My Test")]
[DynamicData(nameof(MyTestObject), DynamicDataSourceType.Property, DynamicDataDisplayName = nameof(GetTestDisplayName))]
</code>```

Thanks

Body:
[TestMethod("My Test Name")] can be use to change the name of a test in MSTest.
DynamicData attribute can be used to run the test on a collection of object where you can customize the datadisplayname for each run.

Unfortunately, when you try to use both for the same test like below, the test is not affected by the display name set.
Any idea if it's possible to get the two attributes working at the same time.

[TestMethod("My Test")]
[DynamicData(nameof(MyTestObject), DynamicDataSourceType.Property, DynamicDataDisplayName = nameof(GetTestDisplayName))]

Thanks


问:
Is it possible to get the invitation_id from a Github Webhook event when a user accepts an invitation?
If I send a collaboration invitation for a private Github repository via eMail, I would like to know for which Github-Profile the invitation ends up being used. Currently, an invitation sent via eMail can be used by the owner of the eMail account for any Github-Account.

Unfortunately, there seems to be no information sent in the Webhook Event to cross-reference the Acceptance-Event of an invitation by a user with the sent invitation. This denies me the ability to cross-reference emails with user-accounts for my private repository.

I was unable to find any information inside the Webhook Acceptance-Event for an invitation that would allude to the eMail address for which I created the invitation.

I assume this is due to privacy and works as intended? Or can this be accomplished?


问:
Windows.Networking.Sockets.MessageWebSocket(ConnectAsync) don't refresh host IP (DNS) each time we try to connect
i have an UWP application that try to iniiate a websocket connection to a host test.mydomain.com (note that this host don't exist)

```<code>_websocket = new MessageWebSocket();
_websocket.Control.MessageType = SocketMessageType.Utf8;

_websocket.Closed += _websocket_Closed;
_websocket.MessageReceived += _websocket_MessageReceived;

Uri aoUri = new Uri(url);

_websocket.ConnectAsync(aoUri).Completed = (source, status) =>
{
   OnLog("_websocket.Information: " + _websocket.Information);

    if (status == AsyncStatus.Completed)
    {
        messageWriter = new DataWriter(_websocket.OutputStream);
        IsOpen = true;
        OnOpened();
    }
    else if (status == AsyncStatus.Error)
    {
        RaiseError(source.ErrorCode);
        EndConnection();
    }
};
</code>```

When i start the test, i have in my host file

```<code>1.1.1.1 test.mydomain.com
</code>```

On wireshark side, i can see multiple attempt to connect to host (1.1.1.1 test.mydomain.com)

filter : ip.dst==1.1.1.1 and tcp.port==443

On windows side, if i run ipconfig /display dns all is ok

if i change my host file to

```<code>2.2.2.2 test.mydomain.com
</code>```

On windows side, if i run ipconfig /display dns, i see the change

On wireshark side,

i can NOT see attempt to connect to host (2.2.2.2 test.mydomain.com)
filter : ip.dst==2.2.2.2 and tcp.port==443

i see that component conninue to invoke  (1.1.1.1 test.mydomain.com)
filter : ip.dst==1.1.1.1 and tcp.port==443

it seems that the hostname is not resolved each time we try to connect using MessageWebSocket

does anyone know why?

note :

that at each connection attempt the object is disposed and recreated

if i restart my app, that work and i see attempt to connect to host related to the one setup in my host file

if a request Dns.GetHostEntry(aoUri.Host) before trying to connect, Dns.GetHostEntry return the good value compare to messageWebSocket.

Body:
i have an UWP application that try to iniiate a websocket connection to a host test.mydomain.com (note that this host don't exist)

_websocket = new MessageWebSocket();
_websocket.Control.MessageType = SocketMessageType.Utf8;

_websocket.Closed += _websocket_Closed;
_websocket.MessageReceived += _websocket_MessageReceived;

Uri aoUri = new Uri(url);

_websocket.ConnectAsync(aoUri).Completed = (source, status) =>
{
   OnLog("_websocket.Information: " + _websocket.Information);

    if (status == AsyncStatus.Completed)
    {
        messageWriter = new DataWriter(_websocket.OutputStream);
        IsOpen = true;
        OnOpened();
    }
    else if (status == AsyncStatus.Error)
    {
        RaiseError(source.ErrorCode);
        EndConnection();
    }
};

When i start the test, i have in my host file

1.1.1.1 test.mydomain.com

On wireshark side, i can see multiple attempt to connect to host (1.1.1.1 test.mydomain.com)

filter : ip.dst==1.1.1.1 and tcp.port==443

On windows side, if i run ipconfig /display dns all is ok

if i change my host file to

2.2.2.2 test.mydomain.com

On windows side, if i run ipconfig /display dns, i see the change

On wireshark side,

i can NOT see attempt to connect to host (2.2.2.2 test.mydomain.com)
filter : ip.dst==2.2.2.2 and tcp.port==443

i see that component conninue to invoke  (1.1.1.1 test.mydomain.com)
filter : ip.dst==1.1.1.1 and tcp.port==443

it seems that the hostname is not resolved each time we try to connect using MessageWebSocket

does anyone know why?

note :

that at each connection attempt the object is disposed and recreated

if i restart my app, that work and i see attempt to connect to host related to the one setup in my host file

if a request Dns.GetHostEntry(aoUri.Host) before trying to connect, Dns.GetHostEntry return the good value compare to messageWebSocket.


问:
Why can't the normal module mock.patch in the celery task?
Why does it not continue to apply when I change return_value using moker.patch?

tasks

@shared_task
def send_reminder():
    reminders = Reminder.objects.filter(remind=False)
    for reminder in reminders:
        result = send_reminder(reminder.id)
        if result == 200:
            reminder.remind = True
            reminder.save()
```
<p>send_reminder /
file dir : reminder/kakao/send_reminder.py</p>
<pre class="lang-py prettyprint-override"><code>def send_reminder(reminder_id: int):
    tokens = Token.objects.first()
    reminder = Reminder.objects.get(id=reminder_id)
    url = "https://kapi.kakao.com/v2/api/talk/memo/default/send"
    headers = {"Authorization": "Bearer " + tokens.access_token}

    data = {
        "object_type": "text",
        "text": f"{reminder.notice.title}\n" f"{reminder.notice.school.url}\n\n",
        "link": {
            "web_url": reminder.notice.school.url,
        },
        "button_title": reminder.notice.school.name,
    }

    data = {"template_object": json.dumps(data)}
    response = requests.post(url, headers=headers, data=data)
    print("response : ", response)
    return response.status_code
</code>```

test_send_reminder

from reminder.tasks import send_reminder
from unittest.mock import patch
import pytest

@pytest.mark.django_db(transaction=True)
def test_send_reminder(mocker, school_one, notice_one, reminder_one, celery_app, celery_worker):
    mocker.patch('reminder.kakao.send_reminder.send_reminder', return_value=200)

    # When: start batch job crawling
    result = send_kakao_reminder.delay()
    # Then: result.get() should be None
    assert result.get() is None
```
<p>fail_message</p>
<pre class="lang-bash prettyprint-override"><code>FAILED reminder/tests/test_tasks.py::test_send_reminder - AttributeError: 'NoneType' object has no attribute 'access_token'
</code>```

I want to test that the return_value of the function written in moker.patch is 200 and False is changed to True.

Body:
Why does it not continue to apply when I change return_value using moker.patch?

tasks

@shared_task
def send_reminder():
    reminders = Reminder.objects.filter(remind=False)
    for reminder in reminders:
        result = send_reminder(reminder.id)
        if result == 200:
            reminder.remind = True
            reminder.save()

send_reminder /
file dir : reminder/kakao/send_reminder.py

def send_reminder(reminder_id: int):
    tokens = Token.objects.first()
    reminder = Reminder.objects.get(id=reminder_id)
    url = "https://kapi.kakao.com/v2/api/talk/memo/default/send"
    headers = {"Authorization": "Bearer " + tokens.access_token}

    data = {
        "object_type": "text",
        "text": f"{reminder.notice.title}\n" f"{reminder.notice.school.url}\n\n",
        "link": {
            "web_url": reminder.notice.school.url,
        },
        "button_title": reminder.notice.school.name,
    }

    data = {"template_object": json.dumps(data)}
    response = requests.post(url, headers=headers, data=data)
    print("response : ", response)
    return response.status_code

test_send_reminder

from reminder.tasks import send_reminder
from unittest.mock import patch
import pytest

@pytest.mark.django_db(transaction=True)
def test_send_reminder(mocker, school_one, notice_one, reminder_one, celery_app, celery_worker):
    mocker.patch('reminder.kakao.send_reminder.send_reminder', return_value=200)

    # When: start batch job crawling
    result = send_kakao_reminder.delay()
    # Then: result.get() should be None
    assert result.get() is None

fail_message

FAILED reminder/tests/test_tasks.py::test_send_reminder - AttributeError: 'NoneType' object has no attribute 'access_token'

I want to test that the return_value of the function written in moker.patch is 200 and False is changed to True.


问:
Paypal IPN Verification 404
I posted this in the Paypal community and have heard NADA. I've had Paypal IPN listener set up for years on my site, and until 1/11/23, everything was working fine.

Then on 1/11, I started to see 404 errors when trying to verify an IPN message from paypal. I'm receiving the IPN from paypal, but it's the return verification which is failing with the 404.

The procedure according to their docs is to post back your message prefixed with a "cmd=_notify-validate". I've had this running forever just fine. This procedure is outlined in their developer docs located here:
https://developer.paypal.com/api/nvp-soap/ipn/IPNIntro/

Now when my system tries to verify the message, Paypal responds with a 404 for the following URL:

https://ipnpb.paypal.com/cgi-bin/webscr

I'm also getting a 404 for the sandbox url.

I've searched to see if I missed some changes which were going to be introduced (url change?) but can't find anything anywhere.

Besides a URL change, is there something else I might be missing?

Title: Paypal IPN Verification 404


问:
Committing an image to Github via the Github API
I'm building a small frontend to add content to a Github repository and I'm having trouble uploading images to the repo.

Here's what I'm doing:

Convert my image Blob to base64 and send it to Github to get an SHA:

```<code>const sha = await octokit.request(
  'POST /repos/{owner}/{repo}/git/blobs',
  {
    owner,
    repo,
    content: base64Image,
    encoding: 'base64',
  }
)
</code>```

I've checked the generated base64 string and decoding it does return the original image, this is the base64 string:

```<code>data:image/jpeg;base64,[encoded data, 8144 characters]
</code>```

I then create a git tree from the image that I want to add to github:

```<code>const tree = await octokit.request(
  'POST /repos/{owner}/{repo}/git/trees',
  {
    owner,
    repo,
    tree: [
      {
        path: 'public/images/myImage.jpg',
        mode: '100644',
        type: 'blob',
        // getting the sha from the previous request
        sha: sha.data.sha,
      }
    ],
    // I get the base tree from another request
    base_tree: baseTree,
  }
)
</code>```

I create a commit from my tree:

```<code>const commit = await octokit.request(
  'POST /repos/{owner}/{repo}/git/commits',
  {
    owner,
    repo,
    message: 'Added new image',
    // from the previous request
    tree: tree.data.sha,
    // getting the last commit sha from another request
    parents: [lastCommit],
  }
)
</code>```

Finally I update refs:

```<code>octokit.request('PATCH /repos/{owner}/{repo}/git/refs/{ref}', {
  owner,
  repo,
  ref: `heads/${branch}`,
  sha: commit.data.sha,
})
</code>```

Now this code actually works, the image is committed and pushed to the repo, but it will be broken.

I've successfully used almost the same code (aside from changing encoding: 'utf-8') to update text files, so I'm really confused as to why this wouldn't work.

Any ideas why the image would corrupt when uploaded?

Body:
I'm building a small frontend to add content to a Github repository and I'm having trouble uploading images to the repo.

Here's what I'm doing:

Convert my image Blob to base64 and send it to Github to get an SHA:

const sha = await octokit.request(
  'POST /repos/{owner}/{repo}/git/blobs',
  {
    owner,
    repo,
    content: base64Image,
    encoding: 'base64',
  }
)

I've checked the generated base64 string and decoding it does return the original image, this is the base64 string:

data:image/jpeg;base64,[encoded data, 8144 characters]

I then create a git tree from the image that I want to add to github:

const tree = await octokit.request(
  'POST /repos/{owner}/{repo}/git/trees',
  {
    owner,
    repo,
    tree: [
      {
        path: 'public/images/myImage.jpg',
        mode: '100644',
        type: 'blob',
        // getting the sha from the previous request
        sha: sha.data.sha,
      }
    ],
    // I get the base tree from another request
    base_tree: baseTree,
  }
)

I create a commit from my tree:

const commit = await octokit.request(
  'POST /repos/{owner}/{repo}/git/commits',
  {
    owner,
    repo,
    message: 'Added new image',
    // from the previous request
    tree: tree.data.sha,
    // getting the last commit sha from another request
    parents: [lastCommit],
  }
)

Finally I update refs:

octokit.request('PATCH /repos/{owner}/{repo}/git/refs/{ref}', {
  owner,
  repo,
  ref: `heads/${branch}`,
  sha: commit.data.sha,
})

Now this code actually works, the image is committed and pushed to the repo, but it will be broken.

I've successfully used almost the same code (aside from changing encoding: 'utf-8') to update text files, so I'm really confused as to why this wouldn't work.

Any ideas why the image would corrupt when uploaded?


问:
Managing GCP network endpoint groups with terraform
Is there a way to have terraform use a non-existent data source or perhaps somehow delay looking up a datasource?

I have a GCP GKE cluster and workload being deployed to it which creates network endpoint groups for me automatically. I need to refer to those network endpoint groups in my GCP load balancer backend config:

```<code>  backend {
    group           = data.google_compute_network_endpoint_group.app2-service-80-neg1.id
    balancing_mode  = "RATE"
    max_rate        = 100
    capacity_scaler = 1.0
  }
</code>```

However, since I'm creating the initial infrastructure via terraform, the GKE workload doesn't exist yet which means the network endpoint groups also don't exist.

This seems like a chicken and egg scenario. I want to have my network endpoint groups created automatically via GKE, but I need to refer to an existing network endpoint group to create my load balancer backend. Not sure how to get around this and would be grateful is anyone has a way around this.

Body:
Is there a way to have terraform use a non-existent data source or perhaps somehow delay looking up a datasource?

I have a GCP GKE cluster and workload being deployed to it which creates network endpoint groups for me automatically. I need to refer to those network endpoint groups in my GCP load balancer backend config:

  backend {
    group           = data.google_compute_network_endpoint_group.app2-service-80-neg1.id
    balancing_mode  = "RATE"
    max_rate        = 100
    capacity_scaler = 1.0
  }

However, since I'm creating the initial infrastructure via terraform, the GKE workload doesn't exist yet which means the network endpoint groups also don't exist.

This seems like a chicken and egg scenario. I want to have my network endpoint groups created automatically via GKE, but I need to refer to an existing network endpoint group to create my load balancer backend. Not sure how to get around this and would be grateful is anyone has a way around this.


问:
Unable to sync deleted Azuread user with local AD
When I delete the user from the local AD at that time that user is also delete from AAD, But when i delete user from AAD at that time that user is not deleted from local AD, how to sync delete object from azure ad to local AD

I try to delta sync, full sync and import.


问:
unable to loop writing tables with tab_df
Splitting a large table into smaller ones, I tried to export all my output as .csv and then as .doc files. My code works for the first but not for the second.

```<code>####Given a Tibble called data:

namen <- unique(data$Fundort)
for (i in 1:length(unique(data$Fundort))) {
  dat <- data %>%
    filter(Fundort == namen[i], Familie == 'Apidae', Nachweistyp == 'Fang: Handfang') %>%
    select(c('Art','Anzahl','Datum')) %>%
    group_by(Art) %>%
    summarise (Anzahl = sum (Anzahl)) %>%
    left_join(status, by = 'Art')
  write.table(dat, paste("daten", namen[i],'.csv', sep = ""), sep = ';', na = '', row.names = FALSE)
  tab_df(dat, file = paste("daten", namen[i],'.doc', sep = ""))
}
</code>```

This code outputs a number of '.csv' files, which I expected to be accompanied by '.doc' files. Instead I only get the csv and no trace of the doc

I would like to add that the code in question works for individual files outside of the loop, so I can't see how I can fix this.

Body:
Splitting a large table into smaller ones, I tried to export all my output as .csv and then as .doc files. My code works for the first but not for the second.

####Given a Tibble called data:

namen <- unique(data$Fundort)
for (i in 1:length(unique(data$Fundort))) {
  dat <- data %>%
    filter(Fundort == namen[i], Familie == 'Apidae', Nachweistyp == 'Fang: Handfang') %>%
    select(c('Art','Anzahl','Datum')) %>%
    group_by(Art) %>%
    summarise (Anzahl = sum (Anzahl)) %>%
    left_join(status, by = 'Art')
  write.table(dat, paste("daten", namen[i],'.csv', sep = ""), sep = ';', na = '', row.names = FALSE)
  tab_df(dat, file = paste("daten", namen[i],'.doc', sep = ""))
}

This code outputs a number of '.csv' files, which I expected to be accompanied by '.doc' files. Instead I only get the csv and no trace of the doc

I would like to add that the code in question works for individual files outside of the loop, so I can't see how I can fix this.


问:
Can not upload camera captured images to the server with Xiaomi Android phone in my ASP.NET Core MVC web application, Samsung and others work fine
I have an ASP.NET Core MVC web application that is used to upload camera-captured images to the server.

My problem is when it's uploaded using all the Xiaomi Android phone versions, it's rejected and sends an Internal Server Error 500.

Other phones like Apple, Samsung, Google pixel and other reputed Android mobile phones work just fine with image capturing and upload.

Please, help me solve this.


问:
Nodejs delete file on successful http transfer
I have a function that reads files from a folder and sends the contents via http post.

If the sending was successful, I want to delete the file.
 Now I have the problem that sporadically the error occurs that a file cannot be deleted because it is not found.
 However, this cannot be the case.
I suspect that it has something to do with the Promises.

```<code>async function sendData(config)
{
  const start = Date.now();
  let files = await fsp.readdir(config.sourceDirectory);

  if (files.length > 0) {
      for (let fileName of files) {
          let stats = await fsp.stat(path.join(config.sourceDirectory, fileName));

          if (start - stats.birthtimeMs > 10) {
             let fileContent = await fsp.readFile(path.join(config.sourceDirectory, fileName), 'utf8');

             let response = await axios({
                 method: 'post',
                 url: config.httpEndpoint,
                 httpsAgent: httpsAgent,
                 auth: {
                     username: config.user,
                     password: config.password,
                       },
                 data: {
                 payload: fileContent,
                 topic: fileName,
                       },
                 });

           if (response.status === 200) {
               try {
                   //fs.unlinkSync(path.join(config.sourceDirectory, fileName));
                   await fsp.unlink(path.join(config.sourceDirectory, fileName));
               } catch {
                   log.error(`Could not delete File: ${path.join(config.sourceDirectory, fileName)}`);
               }
           } else {
              //move file to error folder
           }
       }
    }
  }
 }
</code>```

Error message:

```<code>node:internal/process/promises:246
      triggerUncaughtException(err, true /* fromPromise */);
      ^

[Error: ENOENT: no such file or directory, stat 'C:\Home\TempData\HttpClientTesting\test\testfile_84.xml'] {
errno: -4058,
code: 'ENOENT',
syscall: 'stat',
path: 'C:\\Home\\TempData\\HttpClientTesting\\test\\testfile_84.xml'
}
</code>```

Is there a error in my code or am i missing something?

Body:
I have a function that reads files from a folder and sends the contents via http post.

If the sending was successful, I want to delete the file.
 Now I have the problem that sporadically the error occurs that a file cannot be deleted because it is not found.
 However, this cannot be the case.
I suspect that it has something to do with the Promises.

async function sendData(config)
{
  const start = Date.now();
  let files = await fsp.readdir(config.sourceDirectory);

  if (files.length > 0) {
      for (let fileName of files) {
          let stats = await fsp.stat(path.join(config.sourceDirectory, fileName));

          if (start - stats.birthtimeMs > 10) {
             let fileContent = await fsp.readFile(path.join(config.sourceDirectory, fileName), 'utf8');

             let response = await axios({
                 method: 'post',
                 url: config.httpEndpoint,
                 httpsAgent: httpsAgent,
                 auth: {
                     username: config.user,
                     password: config.password,
                       },
                 data: {
                 payload: fileContent,
                 topic: fileName,
                       },
                 });

           if (response.status === 200) {
               try {
                   //fs.unlinkSync(path.join(config.sourceDirectory, fileName));
                   await fsp.unlink(path.join(config.sourceDirectory, fileName));
               } catch {
                   log.error(`Could not delete File: ${path.join(config.sourceDirectory, fileName)}`);
               }
           } else {
              //move file to error folder
           }
       }
    }
  }
 }

Error message:

node:internal/process/promises:246
      triggerUncaughtException(err, true /* fromPromise */);
      ^

[Error: ENOENT: no such file or directory, stat 'C:\Home\TempData\HttpClientTesting\test\testfile_84.xml'] {
errno: -4058,
code: 'ENOENT',
syscall: 'stat',
path: 'C:\\Home\\TempData\\HttpClientTesting\\test\\testfile_84.xml'
}

Is there a error in my code or am i missing something?


问:
Bootstrap 4 - Razor Page Carousel 4 frames at once responsive - Updated to Net 7.0
I have a carousel 4 frames at once responsive runing for a long time, but after I update my razor pages app to Net 7.0, it is not working anymore. It is only showing the first slide. My Bootstrap is 4.3.1 and my implementation is the same showed in the link:
Bootstrap carousel multiple frames at once - item Boostrap 4 (update 2019).
Then, I tried to implement a simple carousel, but the slides are not running too.
And I cannot find any comments from Microsoft about this.
Can anyone help me?</p>


问:
Docker variables from `env_file` in container build stage
I want to use variables in my Docker build stage to emplace secrets in a configuration file within the image. The variables are in docker-variables.env.

./service/Dockerfile

```<code>FROM python:3.10-slim

WORKDIR /service

# Copy configuration, emplace secrets
COPY ./service/settings.conf /service/settings.conf
RUN eval "echo \"$(cat /service/settings.conf\"" > /service/settings.conf

# ...
</code>```

./service/settings.conf

[settings]
url = http://${HOST}:${PORT}/
```
<p><code>./docker-compose.yaml</code></p>
<pre class="lang-yaml prettyprint-override"><code>version: "3.9"
services:

  service:
    build: ./service/
    env_file: ./docker-variables.env
</code>```

./docker-variables.env

```<code>HOST=0.0.0.0
PORT=6800
</code>```

Body:
I want to use variables in my Docker build stage to emplace secrets in a configuration file within the image. The variables are in docker-variables.env.

./service/Dockerfile

FROM python:3.10-slim

WORKDIR /service

# Copy configuration, emplace secrets
COPY ./service/settings.conf /service/settings.conf
RUN eval "echo \"$(cat /service/settings.conf\"" > /service/settings.conf

# ...

./service/settings.conf

[settings]
url = http://${HOST}:${PORT}/

./docker-compose.yaml

version: "3.9"
services:

  service:
    build: ./service/
    env_file: ./docker-variables.env

./docker-variables.env

HOST=0.0.0.0
PORT=6800


问:
When I use the copy/paste buttons on my Typematrix 2030 keyboard when using Intellij IDEA, it instead does an insert 50% of the time

Setup

Device: Laptop

OS: Windows 10 Enterprise

Description

I know this is a weirdly obscure issue and I know I can use ctrl+cxv, but I have a Dvorak layout, so the 'X' 'C' and 'V' are quite far apart. I'm now so used to the other buttons because of this as they're right next to each other, I keep using them unconsciously.

And it's really frustrating seeing my attempt to copy/paste work only 33% of the time and having to redo it over again.

I've understood from a Typematrix forum post that these keys are linked to
key-sequences.

Cut: Shift+Delete,

Copy: Ctrl+Insert,

Paste: Shift+Insert

This impedes on my work and I'm desperate.

Does anyone know how to solve this issue?


问:
How to perform a synchronous task in an asynchronous FastAPI REST endpoint without blocking the event loop?
I have an application setup using FastAPI and Celery for some CPU intensive tasks (basically some synchronous functions defined). One of the REST endpoints is request_data defined as async that users can call to request data. It provides an optional parameter force that if False would simply return the data from Cassandra. But, if force is True, then the REST endpoint has to perform the CPU intensive task in sync and return the results back in the same request.

Here my problem is that, since the function is defined as async, calling the CPU intensive task would block the event loop and hamper FastAPI from handling other requests.

I tried to look for following:

Define two functions (one sync and one async). If FastAPI would allow me to add a middleware that can route my request to respective function but it doesn't seem possible.

Submit the task to celery in async fashion. But it doesn't seem I can await on the result and so waiting otherwise would simply block the event loop.

As a last option, I can make the REST endpoint function as sync but wanted to avoid that. Reason is that I am using Cassandra that provides async support via execute_async on which I can await. Making the REST endpoint function sync would take away async benefits on Cassandra IO.

Does any one has any suggestions on this? I understand that calling a synchronous function in an asynchronous function would eventually mean that event loop would have to perform the CPU intensive task. My only concern is how to do that without blocking the event loop—in other words, without blocking FastAPI from handling other requests?

from fastapi import FastAPI
import cassandra_wrapper  # Class wrapper providing access to Cassandra database

app = FastAPI()

@app.get("/data")
async def request_data(force=False):
    if force:
        # perform computations and return data
        return cpu_intensive_task()
    else:
        return cassandra_wrapper.get_data()

# Can call this celery task to do computations
@celery.task(bind=True, name="cpu_intensive_task")
def cpu_intensive_celery_task():
    return cpu_intensive_task

# Or can call this function directly to do computations
def cpu_intensive_task():
    import time
    time.sleep(5)
```


问:
I'm searching a 3d carousel component for react js like this one: react-carousel3
I'm working with this component: https://github.com/xiaxiangfeng/react-carousel3d#readme and with React JS and Netlify CMS.

It works until I reload the page. As soon as I reload the page the error "ReferenceError: window is not defined" occurs. I could not solve it. Where is the problem or how can I fix this error? The two screenshots I added you can see how its working and then the error.
the working 3d slideshowand the error

I tried to load it differently like instead of
import { Carousel } from 'react-carousel3'; var Carousel = require( 'react-carousel3').Carousel;

and also
if (typeof window !== "undefined") { // Client-side-only code console.log("jetzt nicht undefined") }
before the return ( codeline


问:
Remove the gaps between scatter trace of candelstick plot after updating xaxis to set rangebreaks

```<code>
        df = data

       #candelstick
        fig = go.Figure(data=[go.Candlestick(x=df['timestamp'],
                                     open=df.open,
                                     high=df.high,
                                     low=df.low,
                                     close=df.close),
                      ])

      #adding trace
        fig.add_trace(go.Scatter(x=df['timestamp'], y=df['indicator'],name="SMA",line= {'color': 'rgb(1,0,1)', 'width': 1.5},opacity=0.3),
                    )

        fig.update_xaxes(
                rangeslider_visible=False,
                rangebreaks=[
                    # NOTE: Below values are bound (not single values), ie. hide x to y
                    dict(bounds=["sat", "mon"]),  # hide weekends, eg. hide sat to before mon
                    dict(bounds=[16, 9.5], pattern="hour"),  # hide hours outside of 9.30am-4pm
                    dict(values=["2020-12-25", "2021-01-01"])  # hide holidays (Christmas and New Year's, etc)
                ]
        )

        fig.show()
</code>```

Only after updating the xaxes it creates gaps.

I want the scatter trace to be continuous without any gaps in between .

Body:
        df = data

       #candelstick
        fig = go.Figure(data=[go.Candlestick(x=df['timestamp'],
                                     open=df.open,
                                     high=df.high,
                                     low=df.low,
                                     close=df.close),
                      ])

      #adding trace
        fig.add_trace(go.Scatter(x=df['timestamp'], y=df['indicator'],name="SMA",line= {'color': 'rgb(1,0,1)', 'width': 1.5},opacity=0.3),
                    )

        fig.update_xaxes(
                rangeslider_visible=False,
                rangebreaks=[
                    # NOTE: Below values are bound (not single values), ie. hide x to y
                    dict(bounds=["sat", "mon"]),  # hide weekends, eg. hide sat to before mon
                    dict(bounds=[16, 9.5], pattern="hour"),  # hide hours outside of 9.30am-4pm
                    dict(values=["2020-12-25", "2021-01-01"])  # hide holidays (Christmas and New Year's, etc)
                ]
        )

        fig.show()

Only after updating the xaxes it creates gaps.

I want the scatter trace to be continuous without any gaps in between .


问:
Lazy loading React components doesn't improve performance or reduce bundle size
I have the following code to dynamically import based on routes, however it doesn't actually improve performance or decrease the bundle size in anyway? Am I missing something or is it just a case of code splitting not affecting performance that much?

```<code>const Home = lazy(() => import("./home/index"));
const SignUp = lazy(() => import("./home/sign-up/index"));
const HomeOld = lazy(() => import("./home-old/Home"));
const Demo = lazy(() => import("./home/demo/index"));

const router = createBrowserRouter([
  {
    element: (
      <Suspense fallback={<h1>loading..</h1>}>
        <OfflineWrapper>
          <ScrollToTop />
        </OfflineWrapper>
      </Suspense>
    )
    // ...routes defined
</code>```

ensured the routes were wrapped in Suspense.

I have checked that the components are lazy loading as the pages error if the Suspense is not there.

Body:
I have the following code to dynamically import based on routes, however it doesn't actually improve performance or decrease the bundle size in anyway? Am I missing something or is it just a case of code splitting not affecting performance that much?

const Home = lazy(() => import("./home/index"));
const SignUp = lazy(() => import("./home/sign-up/index"));
const HomeOld = lazy(() => import("./home-old/Home"));
const Demo = lazy(() => import("./home/demo/index"));

const router = createBrowserRouter([
  {
    element: (
      <Suspense fallback={
loading..
}>
        <OfflineWrapper>
          <ScrollToTop />
        </OfflineWrapper>
      </Suspense>
    )
    // ...routes defined

ensured the routes were wrapped in Suspense.

I have checked that the components are lazy loading as the pages error if the Suspense is not there.


问:
MCP3208 ADC readings ripples( unstable ADC reading) this is connected to a Raspi PICO. What should I do to avoid this?
I have connected and external MCP3208 to my raspi PICO since my application requires atleast 8 reading simultaneously I use MCP3208. The problem is that the reading jumps not in the ranges of+/- 10 but 100s.I have to read maximum of 1V. The reference voltage is connected to the 3.3V. Also on measuring the input voltage at ADC it was constant. For example I measured a 0.189V at one of the channel but the ADC reading give values between 120 and 300.</p>


问:
Using Raster Calculator in QGIS produces output with strange values
I am adding a number of raster grids together using the Raster Calculator in QGIS, but my output file displays very large values in the range on the layer Legend e.g. 340,282,346,638,528,859,811,704,183,484,516,925,440 to
-340,282,346,638,528,859,811,704,183,484,516,925,440
(please see the image attached).
raster range

The raster grids that I am using are all Float32. This file also displays no information in the summary statistics.

Any ideas how I can avoid this would be much appreciated. Thanks


问:
How to setup web server using Mongoose, similar to python -m http.server?
Im learning Mongoose and trying to setup webserver in a folder, wishing to achieve result thats calling python -m http.server port does. So Im following this example. Server is running but when Im trying to access it externally on http://server_address:port browser says ERR_CONNECTION_REFUSED.

But when Im trying to run web server using Python everything is fine, I can access folder directory remotly, so port forwarding set up correctly on machine where Im tryig to run web server. So my question is how to setup web server using mongoose exactly in same way python does?


问:
How does Xray detect license of the Docker image? Where should I put the license information in Dockerfile?
I have built a Docker image and scanned it with Xray. Xray reports that my Docker image is missing license (the license of the Docker image itself, not the contents of the Docker image).

How should I write and where should I put the licensing information so that Xray can detect the license and stops reporting of a missing license? I would like to get this arranged in build time and not using the Artifactory Xray "Assign Custom License" tool.

This JFrog article nearly provides the information I need but the relevant part for me would be in place where it is now  "etc." :) https://jfrog.com/knowledge-base/how-xray-detects-package-licenses/

I have tried using a Docker label in Dockerfile like this:

LABEL license="Licenseref-MyFancyLicense"
```

I've also tried putting the license in files named LICENSE, LICENSE.md, License.txt, or Licenses.txt with the license name written in the files.

Body:
I have built a Docker image and scanned it with Xray. Xray reports that my Docker image is missing license (the license of the Docker image itself, not the contents of the Docker image).

How should I write and where should I put the licensing information so that Xray can detect the license and stops reporting of a missing license? I would like to get this arranged in build time and not using the Artifactory Xray "Assign Custom License" tool.

This JFrog article nearly provides the information I need but the relevant part for me would be in place where it is now  "etc." :) https://jfrog.com/knowledge-base/how-xray-detects-package-licenses/

I have tried using a Docker label in Dockerfile like this:

LABEL license="Licenseref-MyFancyLicense"

I've also tried putting the license in files named LICENSE, LICENSE.md, License.txt, or Licenses.txt with the license name written in the files.


问:
Historical number of post submission and/or comments Reddit Crawler
I am looking for a way or an API that is capable of crawling (hourly aggregation) the number of post submissions and/or comments in Reddit after July 2018. Unfortunately, PushShift.io got deprecated and the Reddit API itself can only go back 1000 posts. Does someone know any (free) way to crawl the required data?

I already searched the web, my previous versions became outdated


问:
How to access company's SharePoint using Python from Linux which is in production (offline environment)?
I am try to establish to my company's SharePoint site from Linux which is in production environment (offline). I also used proxies but failed to establish the connection. I was successful in Windows which is connected to internet. Code:

```<code>from office365.runtime.auth.authentication_context import AuthenticationContext
from office365.sharepoint.client_context import ClientContext
from urllib.parse import urlparse, quote, quote_plus

SHAREPOINT_URL = "https://{tenant}.sharepoint.com"
CLIENT_ID = "********"
CLIENT_SECRET = "************"

RELATIVE_URL = "/sites/Path"

proxies = {
    "http": "http://{username@company.com}:quote_plus({password})@{server}:{port}",
    "https": "https://{username@company.com}:quote_plus({password})@{server}:{port}",
}

def __set_proxy(request):
    proxies = proxies
    request.proxies = proxies

def __disable_ssl(request):
    request.verify = False

def _auth() -> ClientContext:
    app = AuthenticationContext(SHAREPOINT_URL)
    app.acquire_token_for_app(CLIENT_ID, CLIENT_SECRET)
    ctx = ClientContext(SHAREPOINT_URL, app)
    ctx.pending_request().beforeExecute += __set_proxy
    ctx.pending_request().beforeExecute += __disable_ssl
    return ctx

if __name__ == "__main__":
    ctx = _auth()
</code>```

Error I'm facing is:

```<code>Traceback (most recent call last):
  File "/opt/test_py39/lib/python3.9/site-packages/urllib3/connection.py", line 174, in _new_conn
    conn = connection.create_connection(
  File "/opt/test_py39/lib/python3.9/site-packages/urllib3/util/connection.py", line 72, in create_connection
    for res in socket.getaddrinfo(host, port, family, socket.SOCK_STREAM):
  File "/opt/python_3.9.12/lib/python3.9/socket.py", line 954, in getaddrinfo
    for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
socket.gaierror: [Errno -2] Name or service not known

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/opt/test_py39/lib/python3.9/site-packages/urllib3/connectionpool.py", line 703, in urlopen
    httplib_response = self._make_request(
  File "/opt/test_py39/lib/python3.9/site-packages/urllib3/connectionpool.py", line 386, in _make_request
    self._validate_conn(conn)
  File "/opt/test_py39/lib/python3.9/site-packages/urllib3/connectionpool.py", line 1040, in _validate_conn
    conn.connect()
  File "/opt/test_py39/lib/python3.9/site-packages/urllib3/connection.py", line 358, in connect
    self.sock = conn = self._new_conn()
  File "/opt/test_py39/lib/python3.9/site-packages/urllib3/connection.py", line 186, in _new_conn
    raise NewConnectionError(
urllib3.exceptions.NewConnectionError: <urllib3.connection.HTTPSConnection object at 0x7f5c54b49970>: Failed to establish a new connection: [Errno -2] Name or service not known

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/opt/test_py39/lib/python3.9/site-packages/requests/adapters.py", line 440, in send
    resp = conn.urlopen(
  File "/opt/test_py39/lib/python3.9/site-packages/urllib3/connectionpool.py", line 785, in urlopen
    retries = retries.increment(
  File "/opt/test_py39/lib/python3.9/site-packages/urllib3/util/retry.py", line 592, in increment
    raise MaxRetryError(_pool, url, error or ResponseError(cause))
urllib3.exceptions.MaxRetryError: HTTPSConnectionPool(host='accounts.accesscontrol.windows.net', port=443): Max retries exceeded with url: /63ce7d59-2f3e-42cd-a8cc-be764cff5eb6/tokens/OAuth/2 (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x7f5c54b49970>: Failed to establish a new connection: [Errno -2] Name or service not known'))

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/opt/test_py39/lib/python3.9/site-packages/office365/runtime/auth/providers/acs_token_provider.py", line 43, in get_app_only_access_token
    return self._get_app_only_access_token(url_info.hostname, realm)
  File "/opt/test_py39/lib/python3.9/site-packages/office365/runtime/auth/providers/acs_token_provider.py", line 64, in _get_app_only_access_token
    response = requests.post(url=sts_url, headers={'Content-Type': 'application/x-www-form-urlencoded'},
  File "/opt/test_py39/lib/python3.9/site-packages/requests/api.py", line 117, in post
    return request('post', url, data=data, json=json, **kwargs)
  File "/opt/test_py39/lib/python3.9/site-packages/requests/api.py", line 61, in request
    return session.request(method=method, url=url, **kwargs)
  File "/opt/test_py39/lib/python3.9/site-packages/requests/sessions.py", line 529, in request
    resp = self.send(prep, **send_kwargs)
  File "/opt/test_py39/lib/python3.9/site-packages/requests/sessions.py", line 645, in send
    r = adapter.send(request, **kwargs)
  File "/opt/test_py39/lib/python3.9/site-packages/requests/adapters.py", line 519, in send
    raise ConnectionError(e, request=request)
requests.exceptions.ConnectionError: HTTPSConnectionPool(host='accounts.accesscontrol.windows.net', port=443): Max retries exceeded with url: /63ce7d59-2f3e-42cd-a8cc-be764cff5eb6/tokens/OAuth/2 (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x7f5c54b49970>: Failed to establish a new connection: [Errno -2] Name or service not known'))

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/projadmin/faker_data/sharepoint_demo/building_sp3.py", line 51, in <module>
    ctx = _auth()
  File "/home/projadmin/faker_data/sharepoint_demo/building_sp3.py", line 21, in _auth
    app.acquire_token_for_app(CLIENT_ID, CLIENT_SECRET)
  File "/opt/test_py39/lib/python3.9/site-packages/office365/runtime/auth/authentication_context.py", line 89, in acquire_token_for_app
    return self._provider.ensure_app_only_access_token()
  File "/opt/test_py39/lib/python3.9/site-packages/office365/runtime/auth/providers/acs_token_provider.py", line 36, in ensure_app_only_access_token
    self._cached_token = self.get_app_only_access_token()
  File "/opt/test_py39/lib/python3.9/site-packages/office365/runtime/auth/providers/acs_token_provider.py", line 45, in get_app_only_access_token
    self.error = e.response.text
AttributeError: 'NoneType' object has no attribute 'text'
</code>```

More info: Python library I'm using: Office365-REST-Python-Client

When I try this command I'm able to get some response (packets) in Linux:
ping {tenant}.sharepoint.com  # no https

Failed cases:
ping {tenant}.sharepoint.com/site/Path
ping https://{tenant}.sharepoint.com

I want to know how to connect to SharePoint site which is in Linux production environment.

Body:
I am try to establish to my company's SharePoint site from Linux which is in production environment (offline). I also used proxies but failed to establish the connection. I was successful in Windows which is connected to internet. Code:

from office365.runtime.auth.authentication_context import AuthenticationContext
from office365.sharepoint.client_context import ClientContext
from urllib.parse import urlparse, quote, quote_plus

SHAREPOINT_URL = "https://{tenant}.sharepoint.com"
CLIENT_ID = "********"
CLIENT_SECRET = "************"

RELATIVE_URL = "/sites/Path"

proxies = {
    "http": "http://{username@company.com}:quote_plus({password})@{server}:{port}",
    "https": "https://{username@company.com}:quote_plus({password})@{server}:{port}",
}

def __set_proxy(request):
    proxies = proxies
    request.proxies = proxies

def __disable_ssl(request):
    request.verify = False

def _auth() -> ClientContext:
    app = AuthenticationContext(SHAREPOINT_URL)
    app.acquire_token_for_app(CLIENT_ID, CLIENT_SECRET)
    ctx = ClientContext(SHAREPOINT_URL, app)
    ctx.pending_request().beforeExecute += __set_proxy
    ctx.pending_request().beforeExecute += __disable_ssl
    return ctx

if __name__ == "__main__":
    ctx = _auth()

Error I'm facing is:

Traceback (most recent call last):
  File "/opt/test_py39/lib/python3.9/site-packages/urllib3/connection.py", line 174, in _new_conn
    conn = connection.create_connection(
  File "/opt/test_py39/lib/python3.9/site-packages/urllib3/util/connection.py", line 72, in create_connection
    for res in socket.getaddrinfo(host, port, family, socket.SOCK_STREAM):
  File "/opt/python_3.9.12/lib/python3.9/socket.py", line 954, in getaddrinfo
    for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
socket.gaierror: [Errno -2] Name or service not known

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/opt/test_py39/lib/python3.9/site-packages/urllib3/connectionpool.py", line 703, in urlopen
    httplib_response = self._make_request(
  File "/opt/test_py39/lib/python3.9/site-packages/urllib3/connectionpool.py", line 386, in _make_request
    self._validate_conn(conn)
  File "/opt/test_py39/lib/python3.9/site-packages/urllib3/connectionpool.py", line 1040, in _validate_conn
    conn.connect()
  File "/opt/test_py39/lib/python3.9/site-packages/urllib3/connection.py", line 358, in connect
    self.sock = conn = self._new_conn()
  File "/opt/test_py39/lib/python3.9/site-packages/urllib3/connection.py", line 186, in _new_conn
    raise NewConnectionError(
urllib3.exceptions.NewConnectionError: <urllib3.connection.HTTPSConnection object at 0x7f5c54b49970>: Failed to establish a new connection: [Errno -2] Name or service not known

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/opt/test_py39/lib/python3.9/site-packages/requests/adapters.py", line 440, in send
    resp = conn.urlopen(
  File "/opt/test_py39/lib/python3.9/site-packages/urllib3/connectionpool.py", line 785, in urlopen
    retries = retries.increment(
  File "/opt/test_py39/lib/python3.9/site-packages/urllib3/util/retry.py", line 592, in increment
    raise MaxRetryError(_pool, url, error or ResponseError(cause))
urllib3.exceptions.MaxRetryError: HTTPSConnectionPool(host='accounts.accesscontrol.windows.net', port=443): Max retries exceeded with url: /63ce7d59-2f3e-42cd-a8cc-be764cff5eb6/tokens/OAuth/2 (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x7f5c54b49970>: Failed to establish a new connection: [Errno -2] Name or service not known'))

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/opt/test_py39/lib/python3.9/site-packages/office365/runtime/auth/providers/acs_token_provider.py", line 43, in get_app_only_access_token
    return self._get_app_only_access_token(url_info.hostname, realm)
  File "/opt/test_py39/lib/python3.9/site-packages/office365/runtime/auth/providers/acs_token_provider.py", line 64, in _get_app_only_access_token
    response = requests.post(url=sts_url, headers={'Content-Type': 'application/x-www-form-urlencoded'},
  File "/opt/test_py39/lib/python3.9/site-packages/requests/api.py", line 117, in post
    return request('post', url, data=data, json=json, **kwargs)
  File "/opt/test_py39/lib/python3.9/site-packages/requests/api.py", line 61, in request
    return session.request(method=method, url=url, **kwargs)
  File "/opt/test_py39/lib/python3.9/site-packages/requests/sessions.py", line 529, in request
    resp = self.send(prep, **send_kwargs)
  File "/opt/test_py39/lib/python3.9/site-packages/requests/sessions.py", line 645, in send
    r = adapter.send(request, **kwargs)
  File "/opt/test_py39/lib/python3.9/site-packages/requests/adapters.py", line 519, in send
    raise ConnectionError(e, request=request)
requests.exceptions.ConnectionError: HTTPSConnectionPool(host='accounts.accesscontrol.windows.net', port=443): Max retries exceeded with url: /63ce7d59-2f3e-42cd-a8cc-be764cff5eb6/tokens/OAuth/2 (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x7f5c54b49970>: Failed to establish a new connection: [Errno -2] Name or service not known'))

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/projadmin/faker_data/sharepoint_demo/building_sp3.py", line 51, in <module>
    ctx = _auth()
  File "/home/projadmin/faker_data/sharepoint_demo/building_sp3.py", line 21, in _auth
    app.acquire_token_for_app(CLIENT_ID, CLIENT_SECRET)
  File "/opt/test_py39/lib/python3.9/site-packages/office365/runtime/auth/authentication_context.py", line 89, in acquire_token_for_app
    return self._provider.ensure_app_only_access_token()
  File "/opt/test_py39/lib/python3.9/site-packages/office365/runtime/auth/providers/acs_token_provider.py", line 36, in ensure_app_only_access_token
    self._cached_token = self.get_app_only_access_token()
  File "/opt/test_py39/lib/python3.9/site-packages/office365/runtime/auth/providers/acs_token_provider.py", line 45, in get_app_only_access_token
    self.error = e.response.text
AttributeError: 'NoneType' object has no attribute 'text'

More info: Python library I'm using: Office365-REST-Python-Client

When I try this command I'm able to get some response (packets) in Linux:
ping {tenant}.sharepoint.com  # no https

Failed cases:
ping {tenant}.sharepoint.com/site/Path
ping https://{tenant}.sharepoint.com

I want to know how to connect to SharePoint site which is in Linux production environment.


问:
Remove Exception in monitor thread while connecting to server localhost:27017 with a Bean
I have a issue with MongoDB log, I need to remove this logh with a viriable on YAML, but this variable will beeing injected only manually.

```<code>2023-01-13 14:03:40.620  INFO 11124 --- [localhost:27017] org.mongodb.driver.cluster               : Exception in monitor thread while connecting to server localhost:27017

com.mongodb.MongoSocketOpenException: Exception opening socket
    at com.mongodb.internal.connection.SocketStream.open(SocketStream.java:70) ~[mongodb-driver-core-4.6.1.jar:na]
    at com.mongodb.internal.connection.InternalStreamConnection.open(InternalStreamConnection.java:180) ~[mongodb-driver-core-4.6.1.jar:na]
    at com.mongodb.internal.connection.DefaultServerMonitor$ServerMonitorRunnable.lookupServerDescription(DefaultServerMonitor.java:193) ~[mongodb-driver-core-4.6.1.jar:na]
    at com.mongodb.internal.connection.DefaultServerMonitor$ServerMonitorRunnable.run(DefaultServerMonitor.java:157) ~[mongodb-driver-core-4.6.1.jar:na]
    at java.base/java.lang.Thread.run(Thread.java:833) ~[na:na]
Caused by: java.net.ConnectException: Connection refused: no further information
    at java.base/sun.nio.ch.Net.pollConnect(Native Method) ~[na:na]
    at java.base/sun.nio.ch.Net.pollConnectNow(Net.java:672) ~[na:na]
    at java.base/sun.nio.ch.NioSocketImpl.timedFinishConnect(NioSocketImpl.java:542) ~[na:na]
    at java.base/sun.nio.ch.NioSocketImpl.connect(NioSocketImpl.java:597) ~[na:na]
    at java.base/java.net.SocksSocketImpl.connect(SocksSocketImpl.java:327) ~[na:na]
    at java.base/java.net.Socket.connect(Socket.java:633) ~[na:na]
    at com.mongodb.internal.connection.SocketStreamHelper.initialize(SocketStreamHelper.java:107) ~[mongodb-driver-core-4.6.1.jar:na]
    at com.mongodb.internal.connection.SocketStream.initializeSocket(SocketStream.java:79) ~[mongodb-driver-core-4.6.1.jar:na]
    at com.mongodb.internal.connection.SocketStream.open(SocketStream.java:65) ~[mongodb-driver-core-4.6.1.jar:na]
    ... 4 common frames omitted
</code>```

I'm try to create a Class of configuration:

```<code>@Configuration
@AutoConfigureBefore(value = MongoAutoConfiguration.class)
@ConditionalOnProperty(prefix = "${mock-server.data.persist-type}", value = "DataType", matchIfMissing = true)
public class MongoDBConfig {
</code>```

and this is a variable on the yaml:

enter image description here

I'm try to you an class configuration to create a Bean method to exclude mongoDB as image when do not exist a variable like "DataType" like a image.

Body:
I have a issue with MongoDB log, I need to remove this logh with a viriable on YAML, but this variable will beeing injected only manually.

2023-01-13 14:03:40.620  INFO 11124 --- [localhost:27017] org.mongodb.driver.cluster               : Exception in monitor thread while connecting to server localhost:27017

com.mongodb.MongoSocketOpenException: Exception opening socket
    at com.mongodb.internal.connection.SocketStream.open(SocketStream.java:70) ~[mongodb-driver-core-4.6.1.jar:na]
    at com.mongodb.internal.connection.InternalStreamConnection.open(InternalStreamConnection.java:180) ~[mongodb-driver-core-4.6.1.jar:na]
    at com.mongodb.internal.connection.DefaultServerMonitor$ServerMonitorRunnable.lookupServerDescription(DefaultServerMonitor.java:193) ~[mongodb-driver-core-4.6.1.jar:na]
    at com.mongodb.internal.connection.DefaultServerMonitor$ServerMonitorRunnable.run(DefaultServerMonitor.java:157) ~[mongodb-driver-core-4.6.1.jar:na]
    at java.base/java.lang.Thread.run(Thread.java:833) ~[na:na]
Caused by: java.net.ConnectException: Connection refused: no further information
    at java.base/sun.nio.ch.Net.pollConnect(Native Method) ~[na:na]
    at java.base/sun.nio.ch.Net.pollConnectNow(Net.java:672) ~[na:na]
    at java.base/sun.nio.ch.NioSocketImpl.timedFinishConnect(NioSocketImpl.java:542) ~[na:na]
    at java.base/sun.nio.ch.NioSocketImpl.connect(NioSocketImpl.java:597) ~[na:na]
    at java.base/java.net.SocksSocketImpl.connect(SocksSocketImpl.java:327) ~[na:na]
    at java.base/java.net.Socket.connect(Socket.java:633) ~[na:na]
    at com.mongodb.internal.connection.SocketStreamHelper.initialize(SocketStreamHelper.java:107) ~[mongodb-driver-core-4.6.1.jar:na]
    at com.mongodb.internal.connection.SocketStream.initializeSocket(SocketStream.java:79) ~[mongodb-driver-core-4.6.1.jar:na]
    at com.mongodb.internal.connection.SocketStream.open(SocketStream.java:65) ~[mongodb-driver-core-4.6.1.jar:na]
    ... 4 common frames omitted

I'm try to create a Class of configuration:

@Configuration
@AutoConfigureBefore(value = MongoAutoConfiguration.class)
@ConditionalOnProperty(prefix = "${mock-server.data.persist-type}", value = "DataType", matchIfMissing = true)
public class MongoDBConfig {

and this is a variable on the yaml:

enter image description here

I'm try to you an class configuration to create a Bean method to exclude mongoDB as image when do not exist a variable like "DataType" like a image.


问:
dictionary inside an array and remove all duplicate keys and values
hello all i have a problem with a problem in python. I have a dictionary inside an array and I want to remove all duplicate keys and values from the array. My code is:

```<code>color=[{"key":"orange","value":1},{"key":"orange","value":1},{"key":"violet","value":2}]
new_color={}
for i in color:
    if i["key"] not in i:
        new_color.setdefault("key",[]).append(i["key"])
        new_color.setdefault("value",[]).append(i["value"])
print(new_color)
</code>```

for example i want the output to be:
color=[{"key":"orange","value":1},{"key":"violet","value":2}]
How can i do?

Body:
hello all i have a problem with a problem in python. I have a dictionary inside an array and I want to remove all duplicate keys and values from the array. My code is:

color=[{"key":"orange","value":1},{"key":"orange","value":1},{"key":"violet","value":2}]
new_color={}
for i in color:
    if i["key"] not in i:
        new_color.setdefault("key",[]).append(i["key"])
        new_color.setdefault("value",[]).append(i["value"])
print(new_color)

for example i want the output to be:
color=[{"key":"orange","value":1},{"key":"violet","value":2}]
How can i do?


问:
A question on AWS RDS Multi-AZ downtime when changing the Instance type
I have an RDS Database serving a production application.

The RDS DB is a db.m3.large and is Multi-AZ Instance Deployment. (Role is "Instance" in the console).

I've been informed by AWS that I have to migrate my Database from an M3 instance to one of the newer types this time next month. This is the first time I have had to touch this Database on the hardware side for quite a while so I would like some validation on my understanding on how best to approach this.

I am aware there is documentation but its a bit vague and I would like a statement in laymans terms.

My current approach/understanding on how to handle this would be:

I modify the instance type

While the instance type is modifed, failover occurs and the traffic is redirected to a standby instance to handle traffic while the changes are modified

The failover will occur from between 60-120 seconds, so that would be the expected amount of downtime.

Once the job is done, the traffic is redirected to original primary instance


问:
Unable to load build.framework.js unity webgl
Trying to build a game for a WebGL, but it always (no matter what I tried) says

Unable to load file Build/build.framework.js! Check that the file exists on the remote server. (also check browser Console and Devtools Network tab to debug)

Unity WebGL Player page

Publishing Settings

Compression Settings

There is no Build/build.framework.js file in export directory.

I already tried to turn off the compression, optimization, engine stripping, nothing works.


问:
Make a dynamic tree with d3 V7
I want to make a tree with d3 v7, which allows me to add nodes on each side. I found a code on Stack Overflow (Tree with children towards multiple side in d3.js (similar to family tree)) that uses V3 but I'd like to adapt it to V7 (something I can't do properly because I don't know enough about this library and I have trouble understanding all the docs)

So I tried to modify the code to work with V7 like the d3.layout.tree() etc but nothing does it I must be doing it wrong. Does anyone know where the code goes wrong? If it is possible or if I have to start from the beginning?

Here is mine

```<code>import { hierarchy, tree } from "https://cdn.skypack.dev/d3-hierarchy@3.1.2"
var treeData = [{
    "name": "Device",
    "parent": "null"
  }

];
var treeData2 = [{
    "name": "Device",
    "parent": "null"
  }

];

$(document).ready(function() {
console.log("=====> READY");
  var margin = {
      top: 20,
      right: 120,
      bottom: 20,
      left: 120
    },
    width = 1260 - margin.right - margin.left,
    height = 500 - margin.top - margin.bottom;

  var i = 0,
    duration = 750,
    root;

  var treeLayout = d3.tree()
    .size([height, width]);

  var diagonal = d3.linkHorizontal()
      .x(d => d.y)
      .y(d => d.x);

  var svg = d3.select("body").append("svg")
    .attr("width", width + margin.right + margin.left)
    .attr("height", height + margin.top + margin.bottom);

  makeRightTree();
  makeLeftTree();
});

function makeRightTree() {
  // ************** Generate the tree diagram  *****************
  var margin = {
      top: 20,
      right: 120,
      bottom: 20,
      left: 120
    },
    width = 1260 - margin.right - margin.left,
    height = 500 - margin.top - margin.bottom;

  var i = 0,
    duration = 750,
    root;

  var treeLayout = d3.tree()
    .size([height, width]);

  var diagonal = d3.linkHorizontal()
      .x(d => d.y)
      .y(d => d.x);

  var svg = d3.select("svg").append("g")
    .attr("transform", "translate(600,0)");

  root = treeData[0];
  var oldrx = root.x0 = height / 2;
  var oldry = root.y0 = 0;

  update(root);

  function update(source) {

    // create a hierarchy from the root
    const treeRoot = d3.hierarchy(root)
    tree(treeRoot)
    // nodes
    const nodes = treeRoot.descendants()
    // links
    const links = treeRoot.links()

    // Normalize for fixed-depth.
    nodes.forEach(function(d) {
      d.y = d.depth * 180;
    });

    // Update the nodes…
    var node = svg.selectAll("g.node")
      .data(nodes, function(d) {
        return d.id || (d.id = ++i);
      });

    // Enter any new nodes at the parent's previous position.
    var nodeEnter = node.enter().append("g")
      .attr("class", function(d) {
        if (d.parent == "null") {
          return "node rightparent" //since its root its parent is null
        } else
          return "node rightchild" //all nodes with parent will have this class
      })
      .attr("transform", function(d) {
        return "translate(" + source.y0 + "," + source.x0 + ")";
      })
      .on("click", click);

    nodeEnter.append("rect")
      .attr("x", "-10")
      .attr("y", "-15")
      .attr("height", 30)
      .attr("width", 100)
      .attr("rx", 15)
      .attr("ry", 15)
      .style("fill", "#f1f1f1");

    nodeEnter.append("text")
      .attr("x", function(d) {
        return d.children || d._children ? -13 : 13;
      })
      .attr("dy", ".35em")
      .attr("text-anchor", function(d) {
        return d.children || d._children ? "end" : "start";
      })
      .text(function(d) {
        return d.name;
      })
      .style("fill-opacity", 1e-6);

    var addRightChild = nodeEnter.append("g");
    addRightChild.append("rect")
      .attr("x", "90")
      .attr("y", "-10")
      .attr("height", 20)
      .attr("width", 20)
      .attr("rx", 10)
      .attr("ry", 10)
      .style("stroke", "#444")
      .style("stroke-width", "2")
      .style("fill", "#ccc");

    addRightChild.append("line")
      .attr("x1", 95)
      .attr("y1", 1)
      .attr("x2", 105)
      .attr("y2", 1)
      .attr("stroke", "#444")
      .style("stroke-width", "2");

    addRightChild.append("line")
      .attr("x1", 100)
      .attr("y1", -4)
      .attr("x2", 100)
      .attr("y2", 6)
      .attr("stroke", "#444")
      .style("stroke-width", "2");

    // Transition nodes to their new position.
    var nodeUpdate = node.transition()
      .duration(duration)
      .attr("transform", function(d) {
        if (d.parent =="null"){
          d.y = oldry;
          d.x = oldrx;
        }

        return "translate(" + d.y + "," + d.x + ")";
      });

    nodeUpdate.select("circle")
      .attr("r", 10)
      .style("fill", function(d) {
        return d._children ? "lightsteelblue" : "#fff";
      });

    nodeUpdate.select("text")
      .style("fill-opacity", 1);

    // Transition exiting nodes to the parent's new position.
    var nodeExit = node.exit().transition()
      .duration(duration)
      .attr("transform", function(d) {
        return "translate(" + source.y + "," + source.x + ")";
      })
      .remove();

    nodeExit.select("circle")
      .attr("r", 1e-6);

    nodeExit.select("text")
      .style("fill-opacity", 1e-6);

    // Update the links…
    var link = svg.selectAll("path.link")
      .data(links, function(d) {
        return d.target.id;
      });

    // Enter any new links at the parent's previous position.
    link.enter().insert("path", "g")
      .attr("class", "link")
      .attr("d", function(d) {
        var o = {
          x: source.x0,
          y: source.y0
        };
        return diagonal({
          source: o,
          target: o
        });
      }).on("click", removelink);

    function removelink(d) {
      //this is the links target node which you want to remove
      var target = d.target;
      //make new set of children
      var children = [];
      //iterate through the children
      target.parent.children.forEach(function(child) {
        if (child.id != target.id) {
          //add to teh child list if target id is not same
          //so that the node target is removed.
          children.push(child);
        }
      });
      //set the target parent with new set of children sans the one which is removed
      target.parent.children = children;
      //redraw the parent since one of its children is removed
      update(d.target.parent)
    }

    // Transition links to their new position.
    link.transition()
      .duration(duration)
      .attr("d", diagonal);

    // Transition exiting nodes to the parent's new position.
    link.exit().transition()
      .duration(duration)
      .attr("d", function(d) {
        var o = {
          x: source.x,
          y: source.y
        };
        return diagonal({
          source: o,
          target: o
        });
      })
      .remove();

    // Stash the old positions for transition.
    nodes.forEach(function(d) {
      d.x0 = d.x;
      d.y0 = d.y;
    });

    addRightChild.on("click", function(d) {

      event.stopPropagation();
      $("#child-info").show();
      $("#child-text").val("");

      $("#btn-add-child").off('click');
      $("#btn-add-child").click(function() {
        var childname = $("#child-text").val();

        if (typeof d.children === 'undefined') {

          var newChild = [{
            "name": childname,
            "parent": "Son Of A",
          }];

          console.log(tree(newChild[0]));
          var newnodes = d3.hierarchy(newChild[0], d => d.children);
          d.children = newnodes;
          console.log(d.children);
          update(d);

        } else {
          var newChild = {
            "name": childname,
            "parent": "Son Of A",
          };
          console.log(d.children);
          d.children.push(newChild);
          console.log(d.children);
          update(d);

        }

        $("#child-info").hide();
      });

    });;

  }

  // Toggle children on click.
  function click(d) {

    // console.log(d);
    // if (d.children) {
    //  d._children = d.children;
    //  d.children = null;
    // } else {
    //  d.children = d._children;
    //  d._children = null;
    // }
    // update(d);
  }

}

function makeLeftTree() {
  // ************** Generate the tree diagram  *****************
  var margin = {
      top: 20,
      right: 120,
      bottom: 20,
      left: 120
    },
    width = 1260 - margin.right - margin.left,
    height = 500 - margin.top - margin.bottom;

  var i = 0,
    duration = 750,
    root;

  var treeLayout = d3.tree()
    .size([height, width]);

  var diagonal = d3.linkHorizontal()
      .x(d => d.y)
      .y(d => d.x);

  var svg = d3.select("svg").append("g")
    .attr("transform", "translate(-421,0)");

  root = treeData2[0];
  var oldlx = root.x0 = height / 2;
  var oldly = root.y0 = width;

  update(root);

  function update(source) {

    // create a hierarchy from the root
    const treeRoot = d3.hierarchy(root)
    tree(treeRoot)
    // nodes
    const nodes = treeRoot.descendants()
    // links
    const links = treeRoot.links()

    // Normalize for fixed-depth.
    nodes.forEach(function(d) {
      d.y = width - (d.depth * 180);
    });

    // Update the nodes…
    var node = svg.selectAll("g.node")
      .data(nodes, function(d) {
        return d.id || (d.id = ++i);
      });

    // Enter any new nodes at the parent's previous position.
    var nodeEnter = node.enter().append("g")
      .attr("class", function(d) {
        if (d.parent == "null") {
          return "node leftparent" //since its root its parent is null
        } else
          return "node leftchild" //all nodes with parent will have this class
      })
      .attr("transform", function(d) {
        return "translate(" + source.y0 + "," + source.x0 + ")";
      })
      .on("click", click);

    nodeEnter.append("rect")
      .attr("x", "-10")
      .attr("y", "-15")
      .attr("height", 30)
      .attr("width", 100)
      .attr("rx", 15)
      .attr("ry", 15)
      .style("fill", "#f1f1f1");

    nodeEnter.append("text")
      .attr("x", function(d) {
        return d.children || d._children ? -13 : 13;
      })
      .attr("dy", ".35em")
      .attr("text-anchor", function(d) {
        return d.children || d._children ? "end" : "start";
      })
      .text(function(d) {
        return d.name;
      })
      .style("fill-opacity", 1e-6);

    var addLeftChild = nodeEnter.append("g");
    addLeftChild.append("rect")
      .attr("x", "-30")
      .attr("y", "-10")
      .attr("height", 20)
      .attr("width", 20)
      .attr("rx", 10)
      .attr("ry", 10)
      .style("stroke", "#444")
      .style("stroke-width", "2")
      .style("fill", "#ccc");

    addLeftChild.append("line")
      .attr("x1", -25)
      .attr("y1", 1)
      .attr("x2", -15)
      .attr("y2", 1)
      .attr("stroke", "#444")
      .style("stroke-width", "2");

    addLeftChild.append("line")
      .attr("x1", -20)
      .attr("y1", -4)
      .attr("x2", -20)
      .attr("y2", 6)
      .attr("stroke", "#444")
      .style("stroke-width", "2");

    // Transition nodes to their new position.
    var nodeUpdate = node.transition()
      .duration(duration)
      .attr("transform", function(d) {
        if (d.parent =="null"){
          d.y = oldly;
          d.x = oldlx;
        }
        return "translate(" + d.y + "," + d.x + ")";
      });

    nodeUpdate.select("circle")
      .attr("r", 10)
      .style("fill", function(d) {
        return d._children ? "lightsteelblue" : "#fff";
      });

    nodeUpdate.select("text")
      .style("fill-opacity", 1);

    // Transition exiting nodes to the parent's new position.
    var nodeExit = node.exit().transition()
      .duration(duration)
      .attr("transform", function(d) {
        return "translate(" + source.y + "," + source.x + ")";
      })
      .remove();

    nodeExit.select("circle")
      .attr("r", 1e-6);

    nodeExit.select("text")
      .style("fill-opacity", 1e-6);

    // Update the links…
    var link = svg.selectAll("path.link")
      .data(links, function(d) {
        return d.target.id;
      });

    // Enter any new links at the parent's previous position.
    link.enter().insert("path", "g")
      .attr("class", "link")
      .attr("d", function(d) {
        var o = {
          x: source.x0,
          y: source.y0
        };
        return diagonal({
          source: o,
          target: o
        });
      }).on("click", removelink);

    function removelink(d) {
      //this is the links target node which you want to remove
      var target = d.target;
      //make new set of children
      var children = [];
      //iterate through the children
      target.parent.children.forEach(function(child) {
        if (child.id != target.id) {
          //add to teh child list if target id is not same
          //so that the node target is removed.
          children.push(child);
        }
      });
      //set the target parent with new set of children sans the one which is removed
      target.parent.children = children;
      //redraw the parent since one of its children is removed
      update(d.target.parent)
    }

    // Transition links to their new position.
    link.transition()
      .duration(duration)
      .attr("d", diagonal);

    // Transition exiting nodes to the parent's new position.
    link.exit().transition()
      .duration(duration)
      .attr("d", function(d) {
        var o = {
          x: source.x,
          y: source.y
        };
        return diagonal({
          source: o,
          target: o
        });
      })
      .remove();

    // Stash the old positions for transition.
    nodes.forEach(function(d) {

      d.x0 = d.x;
      d.y0 = d.y;
    });

    addLeftChild.on("click", function(d) {

      event.stopPropagation();
      $("#child-info").show();
      $("#child-text").val("");

      $("#btn-add-child").off('click');
      $("#btn-add-child").click(function() {
        var childname = $("#child-text").val();

        if (typeof d.children === 'undefined') {

          var newChild = [{
            "name": childname,
            "parent": "Son Of A",
          }];

          console.log(tree(newChild[0]));
          var newnodes = d3.hierarchy(newChild[0], d => d.children);
          d.children = newnodes;
          console.log(d.children);
          update(d);

        } else {
          var newChild = {
            "name": childname,
            "parent": "Son Of A",
          };
          console.log(d.children);
          d.children.push(newChild);
          console.log(d.children);
          update(d);

        }

        $("#child-info").hide();
      });

    });;

  }

  // Toggle children on click.
  function click(d) {

    // console.log(d);
    // if (d.children) {
    //  d._children = d.children;
    //  d.children = null;
    // } else {
    //  d.children = d._children;
    //  d._children = null;
    // }
    // update(d);
  }
}
</code>```
```<code>
#child-info {
  width: 100px;
  height: 50px;
  height: auto;
  position: fixed;
  padding: 10px;
  display: none;
  left: 40%;
}
#btn-add-child {} .control-bar {
  min-height: 50px;
  padding: 10px 0px;
  background: #f1f1f1;
  border-bottom: 1px solid #ccc;
  box-shadow: 0 3px 2px -2px rgba(200, 200, 200, 0.2);
  color: #666;
}
.asset-title {
  padding: 15px;
  float: left;
}
.control-buttons {
  float: right;
  padding: 10px;
}
.control-buttons button {
  border: none;
  border-radius: 0px;
  background: #fff;
  color: #666;
  height: 30px;
  width: 30px;
}
.node {
  cursor: pointer;
}
.node circle {
  fill: #fff;
  stroke: steelblue;
  stroke-width: 3px;
}
.node text {
  font: 12px sans-serif;
}
.link {
  fill: none;
  stroke: #85e0e0;
  stroke-width: 2px;
}
.rightparent>rect {
  display: none;
}
.leftparent>rect {
  fill: #f1f1f1;
  stroke: #ccc;
  stroke-width: 2;
}
</code>```
```<code><div id="child-info" style="display:none">
  <input type="text" id="child-text" placeholder="child name">
  <button id="btn-add-child">add</button>
</div>
</code>```

Title: Make a dynamic tree with d3 V7

Body:
I want to make a tree with d3 v7, which allows me to add nodes on each side. I found a code on Stack Overflow (Tree with children towards multiple side in d3.js (similar to family tree)) that uses V3 but I'd like to adapt it to V7 (something I can't do properly because I don't know enough about this library and I have trouble understanding all the docs)

So I tried to modify the code to work with V7 like the d3.layout.tree() etc but nothing does it I must be doing it wrong. Does anyone know where the code goes wrong? If it is possible or if I have to start from the beginning?

Here is mine

import { hierarchy, tree } from "https://cdn.skypack.dev/d3-hierarchy@3.1.2"
var treeData = [{
    "name": "Device",
    "parent": "null"
  }

];
var treeData2 = [{
    "name": "Device",
    "parent": "null"
  }

];

$(document).ready(function() {
console.log("=====> READY");
  var margin = {
      top: 20,
      right: 120,
      bottom: 20,
      left: 120
    },
    width = 1260 - margin.right - margin.left,
    height = 500 - margin.top - margin.bottom;

  var i = 0,
    duration = 750,
    root;

  var treeLayout = d3.tree()
    .size([height, width]);

  var diagonal = d3.linkHorizontal()
      .x(d => d.y)
      .y(d => d.x);

  var svg = d3.select("body").append("svg")
    .attr("width", width + margin.right + margin.left)
    .attr("height", height + margin.top + margin.bottom);

  makeRightTree();
  makeLeftTree();
});

function makeRightTree() {
  // ************** Generate the tree diagram  *****************
  var margin = {
      top: 20,
      right: 120,
      bottom: 20,
      left: 120
    },
    width = 1260 - margin.right - margin.left,
    height = 500 - margin.top - margin.bottom;

  var i = 0,
    duration = 750,
    root;

  var treeLayout = d3.tree()
    .size([height, width]);

  var diagonal = d3.linkHorizontal()
      .x(d => d.y)
      .y(d => d.x);

  var svg = d3.select("svg").append("g")
    .attr("transform", "translate(600,0)");

  root = treeData[0];
  var oldrx = root.x0 = height / 2;
  var oldry = root.y0 = 0;

  update(root);

  function update(source) {

    // create a hierarchy from the root
    const treeRoot = d3.hierarchy(root)
    tree(treeRoot)
    // nodes
    const nodes = treeRoot.descendants()
    // links
    const links = treeRoot.links()

    // Normalize for fixed-depth.
    nodes.forEach(function(d) {
      d.y = d.depth * 180;
    });

    // Update the nodes…
    var node = svg.selectAll("g.node")
      .data(nodes, function(d) {
        return d.id || (d.id = ++i);
      });

    // Enter any new nodes at the parent's previous position.
    var nodeEnter = node.enter().append("g")
      .attr("class", function(d) {
        if (d.parent == "null") {
          return "node rightparent" //since its root its parent is null
        } else
          return "node rightchild" //all nodes with parent will have this class
      })
      .attr("transform", function(d) {
        return "translate(" + source.y0 + "," + source.x0 + ")";
      })
      .on("click", click);

    nodeEnter.append("rect")
      .attr("x", "-10")
      .attr("y", "-15")
      .attr("height", 30)
      .attr("width", 100)
      .attr("rx", 15)
      .attr("ry", 15)
      .style("fill", "#f1f1f1");

    nodeEnter.append("text")
      .attr("x", function(d) {
        return d.children || d._children ? -13 : 13;
      })
      .attr("dy", ".35em")
      .attr("text-anchor", function(d) {
        return d.children || d._children ? "end" : "start";
      })
      .text(function(d) {
        return d.name;
      })
      .style("fill-opacity", 1e-6);

    var addRightChild = nodeEnter.append("g");
    addRightChild.append("rect")
      .attr("x", "90")
      .attr("y", "-10")
      .attr("height", 20)
      .attr("width", 20)
      .attr("rx", 10)
      .attr("ry", 10)
      .style("stroke", "#444")
      .style("stroke-width", "2")
      .style("fill", "#ccc");

    addRightChild.append("line")
      .attr("x1", 95)
      .attr("y1", 1)
      .attr("x2", 105)
      .attr("y2", 1)
      .attr("stroke", "#444")
      .style("stroke-width", "2");

    addRightChild.append("line")
      .attr("x1", 100)
      .attr("y1", -4)
      .attr("x2", 100)
      .attr("y2", 6)
      .attr("stroke", "#444")
      .style("stroke-width", "2");

    // Transition nodes to their new position.
    var nodeUpdate = node.transition()
      .duration(duration)
      .attr("transform", function(d) {
        if (d.parent =="null"){
          d.y = oldry;
          d.x = oldrx;
        }

        return "translate(" + d.y + "," + d.x + ")";
      });

    nodeUpdate.select("circle")
      .attr("r", 10)
      .style("fill", function(d) {
        return d._children ? "lightsteelblue" : "#fff";
      });

    nodeUpdate.select("text")
      .style("fill-opacity", 1);

    // Transition exiting nodes to the parent's new position.
    var nodeExit = node.exit().transition()
      .duration(duration)
      .attr("transform", function(d) {
        return "translate(" + source.y + "," + source.x + ")";
      })
      .remove();

    nodeExit.select("circle")
      .attr("r", 1e-6);

    nodeExit.select("text")
      .style("fill-opacity", 1e-6);

    // Update the links…
    var link = svg.selectAll("path.link")
      .data(links, function(d) {
        return d.target.id;
      });

    // Enter any new links at the parent's previous position.
    link.enter().insert("path", "g")
      .attr("class", "link")
      .attr("d", function(d) {
        var o = {
          x: source.x0,
          y: source.y0
        };
        return diagonal({
          source: o,
          target: o
        });
      }).on("click", removelink);

    function removelink(d) {
      //this is the links target node which you want to remove
      var target = d.target;
      //make new set of children
      var children = [];
      //iterate through the children
      target.parent.children.forEach(function(child) {
        if (child.id != target.id) {
          //add to teh child list if target id is not same
          //so that the node target is removed.
          children.push(child);
        }
      });
      //set the target parent with new set of children sans the one which is removed
      target.parent.children = children;
      //redraw the parent since one of its children is removed
      update(d.target.parent)
    }

    // Transition links to their new position.
    link.transition()
      .duration(duration)
      .attr("d", diagonal);

    // Transition exiting nodes to the parent's new position.
    link.exit().transition()
      .duration(duration)
      .attr("d", function(d) {
        var o = {
          x: source.x,
          y: source.y
        };
        return diagonal({
          source: o,
          target: o
        });
      })
      .remove();

    // Stash the old positions for transition.
    nodes.forEach(function(d) {
      d.x0 = d.x;
      d.y0 = d.y;
    });

    addRightChild.on("click", function(d) {

      event.stopPropagation();
      $("#child-info").show();
      $("#child-text").val("");

      $("#btn-add-child").off('click');
      $("#btn-add-child").click(function() {
        var childname = $("#child-text").val();

        if (typeof d.children === 'undefined') {

          var newChild = [{
            "name": childname,
            "parent": "Son Of A",
          }];

          console.log(tree(newChild[0]));
          var newnodes = d3.hierarchy(newChild[0], d => d.children);
          d.children = newnodes;
          console.log(d.children);
          update(d);

        } else {
          var newChild = {
            "name": childname,
            "parent": "Son Of A",
          };
          console.log(d.children);
          d.children.push(newChild);
          console.log(d.children);
          update(d);

        }

        $("#child-info").hide();
      });

    });;

  }

  // Toggle children on click.
  function click(d) {

    // console.log(d);
    // if (d.children) {
    //  d._children = d.children;
    //  d.children = null;
    // } else {
    //  d.children = d._children;
    //  d._children = null;
    // }
    // update(d);
  }

}

function makeLeftTree() {
  // ************** Generate the tree diagram  *****************
  var margin = {
      top: 20,
      right: 120,
      bottom: 20,
      left: 120
    },
    width = 1260 - margin.right - margin.left,
    height = 500 - margin.top - margin.bottom;

  var i = 0,
    duration = 750,
    root;

  var treeLayout = d3.tree()
    .size([height, width]);

  var diagonal = d3.linkHorizontal()
      .x(d => d.y)
      .y(d => d.x);

  var svg = d3.select("svg").append("g")
    .attr("transform", "translate(-421,0)");

  root = treeData2[0];
  var oldlx = root.x0 = height / 2;
  var oldly = root.y0 = width;

  update(root);

  function update(source) {

    // create a hierarchy from the root
    const treeRoot = d3.hierarchy(root)
    tree(treeRoot)
    // nodes
    const nodes = treeRoot.descendants()
    // links
    const links = treeRoot.links()

    // Normalize for fixed-depth.
    nodes.forEach(function(d) {
      d.y = width - (d.depth * 180);
    });

    // Update the nodes…
    var node = svg.selectAll("g.node")
      .data(nodes, function(d) {
        return d.id || (d.id = ++i);
      });

    // Enter any new nodes at the parent's previous position.
    var nodeEnter = node.enter().append("g")
      .attr("class", function(d) {
        if (d.parent == "null") {
          return "node leftparent" //since its root its parent is null
        } else
          return "node leftchild" //all nodes with parent will have this class
      })
      .attr("transform", function(d) {
        return "translate(" + source.y0 + "," + source.x0 + ")";
      })
      .on("click", click);

    nodeEnter.append("rect")
      .attr("x", "-10")
      .attr("y", "-15")
      .attr("height", 30)
      .attr("width", 100)
      .attr("rx", 15)
      .attr("ry", 15)
      .style("fill", "#f1f1f1");

    nodeEnter.append("text")
      .attr("x", function(d) {
        return d.children || d._children ? -13 : 13;
      })
      .attr("dy", ".35em")
      .attr("text-anchor", function(d) {
        return d.children || d._children ? "end" : "start";
      })
      .text(function(d) {
        return d.name;
      })
      .style("fill-opacity", 1e-6);

    var addLeftChild = nodeEnter.append("g");
    addLeftChild.append("rect")
      .attr("x", "-30")
      .attr("y", "-10")
      .attr("height", 20)
      .attr("width", 20)
      .attr("rx", 10)
      .attr("ry", 10)
      .style("stroke", "#444")
      .style("stroke-width", "2")
      .style("fill", "#ccc");

    addLeftChild.append("line")
      .attr("x1", -25)
      .attr("y1", 1)
      .attr("x2", -15)
      .attr("y2", 1)
      .attr("stroke", "#444")
      .style("stroke-width", "2");

    addLeftChild.append("line")
      .attr("x1", -20)
      .attr("y1", -4)
      .attr("x2", -20)
      .attr("y2", 6)
      .attr("stroke", "#444")
      .style("stroke-width", "2");

    // Transition nodes to their new position.
    var nodeUpdate = node.transition()
      .duration(duration)
      .attr("transform", function(d) {
        if (d.parent =="null"){
          d.y = oldly;
          d.x = oldlx;
        }
        return "translate(" + d.y + "," + d.x + ")";
      });

    nodeUpdate.select("circle")
      .attr("r", 10)
      .style("fill", function(d) {
        return d._children ? "lightsteelblue" : "#fff";
      });

    nodeUpdate.select("text")
      .style("fill-opacity", 1);

    // Transition exiting nodes to the parent's new position.
    var nodeExit = node.exit().transition()
      .duration(duration)
      .attr("transform", function(d) {
        return "translate(" + source.y + "," + source.x + ")";
      })
      .remove();

    nodeExit.select("circle")
      .attr("r", 1e-6);

    nodeExit.select("text")
      .style("fill-opacity", 1e-6);

    // Update the links…
    var link = svg.selectAll("path.link")
      .data(links, function(d) {
        return d.target.id;
      });

    // Enter any new links at the parent's previous position.
    link.enter().insert("path", "g")
      .attr("class", "link")
      .attr("d", function(d) {
        var o = {
          x: source.x0,
          y: source.y0
        };
        return diagonal({
          source: o,
          target: o
        });
      }).on("click", removelink);

    function removelink(d) {
      //this is the links target node which you want to remove
      var target = d.target;
      //make new set of children
      var children = [];
      //iterate through the children
      target.parent.children.forEach(function(child) {
        if (child.id != target.id) {
          //add to teh child list if target id is not same
          //so that the node target is removed.
          children.push(child);
        }
      });
      //set the target parent with new set of children sans the one which is removed
      target.parent.children = children;
      //redraw the parent since one of its children is removed
      update(d.target.parent)
    }

    // Transition links to their new position.
    link.transition()
      .duration(duration)
      .attr("d", diagonal);

    // Transition exiting nodes to the parent's new position.
    link.exit().transition()
      .duration(duration)
      .attr("d", function(d) {
        var o = {
          x: source.x,
          y: source.y
        };
        return diagonal({
          source: o,
          target: o
        });
      })
      .remove();

    // Stash the old positions for transition.
    nodes.forEach(function(d) {

      d.x0 = d.x;
      d.y0 = d.y;
    });

    addLeftChild.on("click", function(d) {

      event.stopPropagation();
      $("#child-info").show();
      $("#child-text").val("");

      $("#btn-add-child").off('click');
      $("#btn-add-child").click(function() {
        var childname = $("#child-text").val();

        if (typeof d.children === 'undefined') {

          var newChild = [{
            "name": childname,
            "parent": "Son Of A",
          }];

          console.log(tree(newChild[0]));
          var newnodes = d3.hierarchy(newChild[0], d => d.children);
          d.children = newnodes;
          console.log(d.children);
          update(d);

        } else {
          var newChild = {
            "name": childname,
            "parent": "Son Of A",
          };
          console.log(d.children);
          d.children.push(newChild);
          console.log(d.children);
          update(d);

        }

        $("#child-info").hide();
      });

    });;

  }

  // Toggle children on click.
  function click(d) {

    // console.log(d);
    // if (d.children) {
    //  d._children = d.children;
    //  d.children = null;
    // } else {
    //  d.children = d._children;
    //  d._children = null;
    // }
    // update(d);
  }
}

#child-info {
  width: 100px;
  height: 50px;
  height: auto;
  position: fixed;
  padding: 10px;
  display: none;
  left: 40%;
}
#btn-add-child {} .control-bar {
  min-height: 50px;
  padding: 10px 0px;
  background: #f1f1f1;
  border-bottom: 1px solid #ccc;
  box-shadow: 0 3px 2px -2px rgba(200, 200, 200, 0.2);
  color: #666;
}
.asset-title {
  padding: 15px;
  float: left;
}
.control-buttons {
  float: right;
  padding: 10px;
}
.control-buttons button {
  border: none;
  border-radius: 0px;
  background: #fff;
  color: #666;
  height: 30px;
  width: 30px;
}
.node {
  cursor: pointer;
}
.node circle {
  fill: #fff;
  stroke: steelblue;
  stroke-width: 3px;
}
.node text {
  font: 12px sans-serif;
}
.link {
  fill: none;
  stroke: #85e0e0;
  stroke-width: 2px;
}
.rightparent>rect {
  display: none;
}
.leftparent>rect {
  fill: #f1f1f1;
  stroke: #ccc;
  stroke-width: 2;
}

  <input type="text" id="child-text" placeholder="child name">
  <button id="btn-add-child">add</button>