问:
How to htmlify response text
I am getting a response in text as follows

```<code><span class='text-4xl'>description1</span>
</code>```

And when i print it on screen:

import React,{useContext, useEffect} from 'react';
import blogsContext from '../context/blogsContext';
import { useParams } from 'react-router-dom';

export const Blog_read = (props) => {
    const context = useContext(blogsContext)
    const slug = useParams().slug
    const {read_blog,readblog} = context
    useEffect(()=>{read_blog(slug)},[readblog])
    props.changetitle(readblog.title)
    const title = readblog.title
    const description = readblog.description
  return (
      <>
    {title}
    {description}
      </>
  );
};```

Then it prints raw text as shown in

How to render it in html form

ThankYou

答:
You can use this npm package, html-to-react.</p>
```<code>import React,{useContext, useEffect} from 'react';
import { Parser } from "html-to-react";
import blogsContext from '../context/blogsContext';
import { useParams } from 'react-router-dom';

const HtmlToReactParser = new Parser();

export const Blog_read = (props) => {
    const context = useContext(blogsContext)
    const slug = useParams().slug
    const {read_blog,readblog} = context
    useEffect(()=>{read_blog(slug)},[readblog])
    props.changetitle(readblog.title)
    const title = readblog.title
    const description = readblog.description

    return (
      <>
       {title}
       {HtmlToReactParser.parse(description)} /* This will do the job */
      </>
    );
};

</code>```

Title: How to htmlify response text

Body:
I am getting a response in text as follows

description1

And when i print it on screen:

import React,{useContext, useEffect} from 'react';
import blogsContext from '../context/blogsContext';
import { useParams } from 'react-router-dom';

export const Blog_read = (props) => {
    const context = useContext(blogsContext)
    const slug = useParams().slug
    const {read_blog,readblog} = context
    useEffect(()=>{read_blog(slug)},[readblog])
    props.changetitle(readblog.title)
    const title = readblog.title
    const description = readblog.description
  return (
      <>
    {title}
    {description}
      </>
  );
};

Then it prints raw text as shown in

How to render it in html form

ThankYou

Body:
You can use this npm package, html-to-react.

import React,{useContext, useEffect} from 'react';
import { Parser } from "html-to-react";
import blogsContext from '../context/blogsContext';
import { useParams } from 'react-router-dom';

const HtmlToReactParser = new Parser();

export const Blog_read = (props) => {
    const context = useContext(blogsContext)
    const slug = useParams().slug
    const {read_blog,readblog} = context
    useEffect(()=>{read_blog(slug)},[readblog])
    props.changetitle(readblog.title)
    const title = readblog.title
    const description = readblog.description

    return (
      <>
       {title}
       {HtmlToReactParser.parse(description)} /* This will do the job */
      </>
    );
};


来源: stackexchange

问:
RangeError (index): Invalid value: Not in inclusive range 0..1: 2 and app crashing after that
I saw other answers and they got solved by adding itemcount in the listview but I am still getting this error. I am not getting this error for the same code I had for adding images.
In this I am using image picker to upload a video to a list and present it in listview and then upload to firebase

Add_video_screen:

```<code>class _addVideoState extends State<addVideo> {
  bool uploading = false;
  double val = 0;
  CollectionReference? vidRef;
  firebase_storage.Reference? ref;
  File? video;
  VideoPlayerController? videoPlayerController;

  final picker = ImagePicker();

  Future pickVideo(ImageSource source) async {
    final Video = await picker.pickVideo(source: source);

    video = File(Video!.path);

    videoPlayerController = VideoPlayerController.file(video!)
      ..initialize().then((_) {
        setState(() {});
        videoPlayerController!.play();
      });
  }

  List<File> _video = [];
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Add video'),
        actions: [
          ElevatedButton(
            onPressed: () {
              setState(() {
                uploading = true;
              });

              uploadFile().whenComplete(() => Navigator.of(context).pop());
            },
            child: Text(
              'Upload Video',
              style: TextStyle(color: Colors.red),
            ),
          )
        ],
      ),
      body: ListView.builder(
          itemCount: _video.length + 1,
          itemBuilder: (ctx, index) {
            return index == 0
                ? Center(
                    child: ElevatedButton(
                        onPressed: () {
                          !uploading ? chooseVideo() : null;
                        },
                        child: const Text(
                          'Test',
                          style: TextStyle(color: Colors.black),
                        )),
                  )
                : AspectRatio(
                    aspectRatio: videoPlayerController!.value.aspectRatio,

                    // child: VideoPlayer(videoPlayerController!),
                    child: VideoPlayer(VideoPlayerController.file(_video[index])
                      ..initialize().then((_) {
                        setState(() {});
                        videoPlayerController!.play();
                      })),
                  );
          }),
    );
  }

  chooseVideo() async {
    ImagePicker picker = ImagePicker();

    final pickedFile = await picker.pickVideo(source: ImageSource.gallery);

    setState(() {
      _video.add(File(pickedFile!.path));
    });
    videoPlayerController = VideoPlayerController.file(File(pickedFile!.path))
      ..initialize().then((_) {
        setState(() {});
        videoPlayerController!.play();
      });
    if (pickedFile.path == null) retrieveLostData();
  }
</code>```

答:
you are showing an ElevatedButton for index == 0. so your index for accessing _video starts from 1 so you have to decrease 1 index to stay in the right range.

try replace this line:

child: VideoPlayer(VideoPlayerController.file(_video[index - 1])
```

ContentLicense: CC BY-SA 4.0

Body:
I saw other answers and they got solved by adding itemcount in the listview but I am still getting this error. I am not getting this error for the same code I had for adding images.
In this I am using image picker to upload a video to a list and present it in listview and then upload to firebase

Add_video_screen:

class _addVideoState extends State<addVideo> {
  bool uploading = false;
  double val = 0;
  CollectionReference? vidRef;
  firebase_storage.Reference? ref;
  File? video;
  VideoPlayerController? videoPlayerController;

  final picker = ImagePicker();

  Future pickVideo(ImageSource source) async {
    final Video = await picker.pickVideo(source: source);

    video = File(Video!.path);

    videoPlayerController = VideoPlayerController.file(video!)
      ..initialize().then((_) {
        setState(() {});
        videoPlayerController!.play();
      });
  }

  List<File> _video = [];
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Add video'),
        actions: [
          ElevatedButton(
            onPressed: () {
              setState(() {
                uploading = true;
              });

              uploadFile().whenComplete(() => Navigator.of(context).pop());
            },
            child: Text(
              'Upload Video',
              style: TextStyle(color: Colors.red),
            ),
          )
        ],
      ),
      body: ListView.builder(
          itemCount: _video.length + 1,
          itemBuilder: (ctx, index) {
            return index == 0
                ? Center(
                    child: ElevatedButton(
                        onPressed: () {
                          !uploading ? chooseVideo() : null;
                        },
                        child: const Text(
                          'Test',
                          style: TextStyle(color: Colors.black),
                        )),
                  )
                : AspectRatio(
                    aspectRatio: videoPlayerController!.value.aspectRatio,

                    // child: VideoPlayer(videoPlayerController!),
                    child: VideoPlayer(VideoPlayerController.file(_video[index])
                      ..initialize().then((_) {
                        setState(() {});
                        videoPlayerController!.play();
                      })),
                  );
          }),
    );
  }

  chooseVideo() async {
    ImagePicker picker = ImagePicker();

    final pickedFile = await picker.pickVideo(source: ImageSource.gallery);

    setState(() {
      _video.add(File(pickedFile!.path));
    });
    videoPlayerController = VideoPlayerController.file(File(pickedFile!.path))
      ..initialize().then((_) {
        setState(() {});
        videoPlayerController!.play();
      });
    if (pickedFile.path == null) retrieveLostData();
  }


问:
ajax call method sharing question
I have this conceptual question about ajax that I'm not sure if I understand. Say I have a page called original and in original, I use ajax to load another page into orignal called ajaxPage. My question is if original defined a javascript method called testing(), then can ajaxPage use testing()?

To me, it seems that ajaxPage should be able to use testing() because after ajaxPage becomes part of the original page, there is nothing stopping it from having a reference to testing(). But this also means that when coding the ajaxPage, you have a reference to testing() but with just the ajaxPage itself, there is no testing() method defined.

Does anyone have any insight as to what should happen? and why it happens?

答:
Any script loaded into the DOM, whether by AJAX or other means, will have access to code already loaded.  See demo:  http://jsfiddle.net/JAAulde/uCg75/2/

And yes, if you were to load the AJAX content into any context in which testing() is not defined (since it is not defined within itself) you would get an error for reference to undefined function.

ContentLicense: CC BY-SA 3.0

Title: ajax call method sharing question


问:
AWS EBS gp3 volume support on Kubernetes
I have a question regarding support of AWS gp3 on Kubernetes.

AWS announced gp3 EBS volume type which shows better performance than existing gp2: https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-volume-types.html.

But, from Kubernetes docs, I could not see gp3 support by Kubernetes. As I understand, Kubernetes does not support gp3 for AWS yet.

Is my understanding correct or is there other documentation that I might have missed?

答:
We need to manually install the CSI driver into the EKS cluster by using provided Helm chart/manifests.

The official helm chart would also create a StorageClass named ebs-csi whose type is gp3.

Chart link: https://github.com/kubernetes-sigs/aws-ebs-csi-driver/tree/master/charts/aws-ebs-csi-driver


问:
Getting "Uncaught TypeError: callback is not a function" from using timeout with a callback
I want to do a callback with the calculator if successful, and I want it to catch the "Too High" error. But now when it throws the error all i get is "Uncaught TypeError: callback is not a function". No idea what I am doing wrong here</p>
```<code>const calculator = (number, callback) => {
  setTimeout(() => {
    try { if (number > 3) Error('Too high')
      callback(null, number);
    } catch (err) {
      callback(err, null);
    }
  }, 888);
};
</code>```

答: I hope you are passing a callback as a param when calling the calculator function. If you want to catch the error Too High what you can do here instead is add the condition to the callback function you're passing as a param to the calculator function and return it from there since here your if condition is returning undefined. Actually, instead of adding the if one-line condition, use the && operator in the callback function, you are passing to return an error if a number is greater than 3. And just like T.J Crowder is saying you use throw Error('Too High').

Body:
I want to do a callback with the calculator if successful, and I want it to catch the "Too High" error. But now when it throws the error all i get is "Uncaught TypeError: callback is not a function". No idea what I am doing wrong here

const calculator = (number, callback) => {
  setTimeout(() => {
    try { if (number > 3) Error('Too high')
      callback(null, number);
    } catch (err) {
      callback(err, null);
    }
  }, 888);
};


问:
Segregate data by data types
I have some data (mixed data types in column A). How can I split each data type into another column?
I mean numbers to be in column, string in column, dates in column and so on
This is my try till now but I didn't get all the results as expected

```<code>Sub Test()
    Dim a, b(), dic As Object, i As Long, k As Long, ii As Long, n As Long
    a = Range("A1:A10").Value
    Set dic = CreateObject("Scripting.Dictionary")
    For i = LBound(a) To UBound(a)
        If Not dic.Exists(VarType(a(i, 1))) Then
            dic.Item(VarType(a(i, 1))) = Empty
            ReDim Preserve b(UBound(a, 1), k)
            k = k + 1
        End If
        n = 0
        Do Until b(i - 1, k - 1) <> Empty
            b(i - 1, k - 1) = a(i, 1)
        Loop
    Next i
    Range("J1").Resize(UBound(b, 1), UBound(b, 2)).Value = b
End Sub
</code>```

答:
There are a number of things I would do differently in your code

using meaningful names for the variables

specifying the worksheet instead of depending on the implied ActiveSheet

clearing the results area on the worksheet

early binding of the dictionary object

dynamic determination of the range to be processed

etc

but the below code modifies your original code minimally, to obtain the output I think you want, based on your screenshot

```<code>Sub Test()
    Dim a, b(), dic As Object, i As Long, k As Long, ii As Long, n As Long, v
    Dim dataType As String

a = Range("A1:A10").Value
ReDim b(1 To UBound(a))

'first create the dictionary with the datatypes
'since you are maintaining the entries in the same rows,
'   add an empty array as the item
Set dic = CreateObject("Scripting.Dictionary")
    dic.Add Key:="number", Item:=b
    dic.Add Key:="date", Item:=b
    dic.Add Key:="string", Item:=b
    dic.Add Key:="logical", Item:=b

'Add the values to the correct dictionary item
' at the correct spot in the array
For i = LBound(a) To UBound(a)
    Select Case VarType(a(i, 1))
        Case 2 To 6
            dataType = "number"
        Case 7
            dataType = "date"
        Case 8
            dataType = "string"
        Case 11
            dataType = "logical"
        Case Else
            dataType = ""
    End Select

    If dataType <> "" Then
        v = dic(dataType)
        v(i) = a(i, 1)
        dic(dataType) = v
    End If
Next i

'Next create output array
ReDim b(1 To UBound(a), 1 To dic.Count)
k = 0
For Each v In dic.Keys
    k = k + 1
    For i = 1 To UBound(dic(v))
        b(i, k) = dic(v)(i)
    Next i
Next v

Range("J1").Resize(UBound(b, 1), UBound(b, 2)).Value = b

End Sub
</code>```

Edit:

If, as you indicate in your comments, you don't want to set up the data types initially, you can also do that at the time of creation of the dictionary object.  Using the same algorithm of storing the item as an array of the same size as the number of rows in the data base:

```<code>Sub Test()
    Dim a, b(), dic As Object, i As Long, k As Long, ii As Long, n As Long, v
    Dim dataType As Long
a = Range("A1:A10").Value
ReDim b(1 To UBound(a))

Set dic = CreateObject("Scripting.Dictionary")

'Add the values to the correct dictionary item
' at the correct spot in the array
For i = LBound(a) To UBound(a)
    dataType = VarType(a(i, 1))
    If a(i, 1) <> "" Then
        If Not dic.Exists(dataType) Then
            ReDim b(UBound(a))
            b(i) = a(i, 1)
            dic.Add Key:=dataType, Item:=b
        Else
            b = dic(dataType)
            b(i) = a(i, 1)
            dic(dataType) = b
        End If
    End If

Next i

'Next create output array
ReDim b(1 To UBound(a), 1 To dic.Count)
k = 0
For Each v In dic.Keys
    k = k + 1
    For i = 1 To UBound(dic(v))
        b(i, k) = dic(v)(i)
    Next i
Next v

Range("J1").Resize(UBound(b, 1), UBound(b, 2)).Value = b

End Sub
</code>```

Title: Segregate data by data types

Body:
I have some data (mixed data types in column A). How can I split each data type into another column?
I mean numbers to be in column, string in column, dates in column and so on
This is my try till now but I didn't get all the results as expected

Sub Test()
    Dim a, b(), dic As Object, i As Long, k As Long, ii As Long, n As Long
    a = Range("A1:A10").Value
    Set dic = CreateObject("Scripting.Dictionary")
    For i = LBound(a) To UBound(a)
        If Not dic.Exists(VarType(a(i, 1))) Then
            dic.Item(VarType(a(i, 1))) = Empty
            ReDim Preserve b(UBound(a, 1), k)
            k = k + 1
        End If
        n = 0
        Do Until b(i - 1, k - 1) <> Empty
            b(i - 1, k - 1) = a(i, 1)
        Loop
    Next i
    Range("J1").Resize(UBound(b, 1), UBound(b, 2)).Value = b
End Sub

Body:
There are a number of things I would do differently in your code

using meaningful names for the variables

specifying the worksheet instead of depending on the implied ActiveSheet

clearing the results area on the worksheet

early binding of the dictionary object

dynamic determination of the range to be processed

etc

but the below code modifies your original code minimally, to obtain the output I think you want, based on your screenshot

Sub Test()
    Dim a, b(), dic As Object, i As Long, k As Long, ii As Long, n As Long, v
    Dim dataType As String

a = Range("A1:A10").Value
ReDim b(1 To UBound(a))

'first create the dictionary with the datatypes
'since you are maintaining the entries in the same rows,
'   add an empty array as the item
Set dic = CreateObject("Scripting.Dictionary")
    dic.Add Key:="number", Item:=b
    dic.Add Key:="date", Item:=b
    dic.Add Key:="string", Item:=b
    dic.Add Key:="logical", Item:=b

'Add the values to the correct dictionary item
' at the correct spot in the array
For i = LBound(a) To UBound(a)
    Select Case VarType(a(i, 1))
        Case 2 To 6
            dataType = "number"
        Case 7
            dataType = "date"
        Case 8
            dataType = "string"
        Case 11
            dataType = "logical"
        Case Else
            dataType = ""
    End Select

    If dataType <> "" Then
        v = dic(dataType)
        v(i) = a(i, 1)
        dic(dataType) = v
    End If
Next i

'Next create output array
ReDim b(1 To UBound(a), 1 To dic.Count)
k = 0
For Each v In dic.Keys
    k = k + 1
    For i = 1 To UBound(dic(v))
        b(i, k) = dic(v)(i)
    Next i
Next v

Range("J1").Resize(UBound(b, 1), UBound(b, 2)).Value = b

End Sub

Edit:

If, as you indicate in your comments, you don't want to set up the data types initially, you can also do that at the time of creation of the dictionary object.  Using the same algorithm of storing the item as an array of the same size as the number of rows in the data base:

Sub Test()
    Dim a, b(), dic As Object, i As Long, k As Long, ii As Long, n As Long, v
    Dim dataType As Long
a = Range("A1:A10").Value
ReDim b(1 To UBound(a))

Set dic = CreateObject("Scripting.Dictionary")

'Add the values to the correct dictionary item
' at the correct spot in the array
For i = LBound(a) To UBound(a)
    dataType = VarType(a(i, 1))
    If a(i, 1) <> "" Then
        If Not dic.Exists(dataType) Then
            ReDim b(UBound(a))
            b(i) = a(i, 1)
            dic.Add Key:=dataType, Item:=b
        Else
            b = dic(dataType)
            b(i) = a(i, 1)
            dic(dataType) = b
        End If
    End If

Next i

'Next create output array
ReDim b(1 To UBound(a), 1 To dic.Count)
k = 0
For Each v In dic.Keys
    k = k + 1
    For i = 1 To UBound(dic(v))
        b(i, k) = dic(v)(i)
    Next i
Next v

Range("J1").Resize(UBound(b, 1), UBound(b, 2)).Value = b

End Sub


问:
CascadeWindows but except for the caller window
Can I cascade all windows with this method

```<code>        [DllImport("user32.dll")]
        public static extern ushort CascadeWindows(
            HWND hwndParent,
            uint wHow,
            ref RECT lpRect,
            uint cKids,
            ref HWND lpKids
        );
</code>```

but except for the current window that called the method (or a Window that I have an HWND of)?

```<code>CascadeWindows(NULL, MDITILE_ZORDER, NULL, 0, NULL); // "Cascade windows"
</code>```

edit:
I tried this but It only moved the main window instead of all others:

```<code>        Rectangle rect = new Rectangle(0, 0, 1740, 1010);
        var arrayRange = Process.GetProcesses()
            .Where(x =>
                !string.IsNullOrEmpty(x.MainWindowTitle) &&
                !x.MainWindowTitle.Contains("Main Window")
            )
            .Select(x => x.Handle).ToArray();

        user32.CascadeWindows(nullptr, 0, ref rect, 0, ref arrayRange); // "Cascade windows"
</code>```

And also corrected the function declaration

```<code>[DllImport("user32.dll")] public static extern ushort CascadeWindows( IntPtr hwndParent, uint wHow, ref Rectangle lpRect, uint cKids, IntPtr[] lpKids);
</code>```

答:
Using C# this can be done like this:

```<code>        var arrayRange = Process.GetProcesses()
            .Where(x =>
                !string.IsNullOrEmpty(x.MainWindowTitle) &&
                !x.MainWindowTitle.Contains("MainWindow")
            );
            //.Select(x => x.Handle).ToArray();

        int X = 25; int Y = 25;
        foreach (var proc in arrayRange)
        {
            //DLL Import user32.dll
            user32.MoveWindow(proc.MainWindowHandle, X, Y, 335, 335, 1);
            X += 18; Y += 18;
        }
</code>```

I believe that there is an option in C/C++ to do the same with process handles and MoveWindow from user32.DLL.

Body:
Can I cascade all windows with this method

        [DllImport("user32.dll")]
        public static extern ushort CascadeWindows(
            HWND hwndParent,
            uint wHow,
            ref RECT lpRect,
            uint cKids,
            ref HWND lpKids
        );

but except for the current window that called the method (or a Window that I have an HWND of)?

CascadeWindows(NULL, MDITILE_ZORDER, NULL, 0, NULL); // "Cascade windows"

edit:
I tried this but It only moved the main window instead of all others:

        Rectangle rect = new Rectangle(0, 0, 1740, 1010);
        var arrayRange = Process.GetProcesses()
            .Where(x =>
                !string.IsNullOrEmpty(x.MainWindowTitle) &&
                !x.MainWindowTitle.Contains("Main Window")
            )
            .Select(x => x.Handle).ToArray();

        user32.CascadeWindows(nullptr, 0, ref rect, 0, ref arrayRange); // "Cascade windows"

And also corrected the function declaration

[DllImport("user32.dll")] public static extern ushort CascadeWindows( IntPtr hwndParent, uint wHow, ref Rectangle lpRect, uint cKids, IntPtr[] lpKids);

Body:
Using C# this can be done like this:

        var arrayRange = Process.GetProcesses()
            .Where(x =>
                !string.IsNullOrEmpty(x.MainWindowTitle) &&
                !x.MainWindowTitle.Contains("MainWindow")
            );
            //.Select(x => x.Handle).ToArray();

        int X = 25; int Y = 25;
        foreach (var proc in arrayRange)
        {
            //DLL Import user32.dll
            user32.MoveWindow(proc.MainWindowHandle, X, Y, 335, 335, 1);
            X += 18; Y += 18;
        }

I believe that there is an option in C/C++ to do the same with process handles and MoveWindow from user32.DLL.


问:
Generating key pair directly on Smartcard?
This video claims to be able to generate a key pair directly on the Smartcard so the private key never leaves the card. Is this operation common to all smartcards, or do only select smartcards support this?</p>

答:
A smartcard is just a chip on a card, so you probably want to ask about cryptographic smart cards.

I have never worked with cryptographic smart cards but that sounds like a completely reasonable functionality of such smartcards since they are intended usually for authentication and encryption which usally use private keys for that.

The advantage of cryptographic smart cards usually lies in that, that the private key is stored in it. That is intended to prevent the compromise of the keys because even if the computer, that reads the smartcard, is compromised the smartcard is safe and the private key is safe too.


问:
call to external API is getting blocked on Google Cloud Run
I run a Backend written in Python and deployed on Google Cloud Run.For its activity it calls several other API services. The post request to most services works fine, but for one of them, the same code that works fine on my PC, raises an error running in Cloud Run environment. This is a service that has an HTTPS address or an alternative HTTP address and both options are blocked when I try to call from Cloud Run. I use the following line of code:

self.rx_xml = requests.post(url,self.tx_xml).text
```
<p>Result (from Cloud Run only):</p>
```HTTPSConnectionPool(host='secureapi.soprano.co.il', port=443): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x3eb0b155ebb0>: Failed to establish a new connection: [Errno 110] Connection timed out'))
```
<p>Or for the alternative address:</p>
```HTTPConnectionPool(host='api.soprano.co.il', port=80): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x3e10f4f1dbb0>: Failed to establish a new connection: [Errno 110] Connection timed out'))
```

Because this is a local company, the first thing I thought about is that their firewall blocks any IP from outside the country (Israel). In conversations with their customer service they have insisted and again that they are open to the whole world and no IP address is blocked, and they advise me to check if any setting in Cloud Run environment blocks access to them. This sounds very strange to me because access to other addresses works, but since they insist I would be happy to make sure:

Does Cloud Run block access to some outbound connection? Is there a way to see the settings of this block and change them?

Is there a way to clearly check where the connection is blocked?

答:
As guillaume blaquiere said, Cloud run should not block any outgoing request. If there is a problem it is probably because the destination to which the request is sent is blocking the IP address, for example because it is from abroad. Continuing to insist on customer service solved the problem.
Thank!</p>

Body:
I run a Backend written in Python and deployed on Google Cloud Run.For its activity it calls several other API services. The post request to most services works fine, but for one of them, the same code that works fine on my PC, raises an error running in Cloud Run environment. This is a service that has an HTTPS address or an alternative HTTP address and both options are blocked when I try to call from Cloud Run. I use the following line of code:

self.rx_xml = requests.post(url,self.tx_xml).text

Result (from Cloud Run only):

HTTPSConnectionPool(host='secureapi.soprano.co.il', port=443): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x3eb0b155ebb0>: Failed to establish a new connection: [Errno 110] Connection timed out'))

Or for the alternative address:

HTTPConnectionPool(host='api.soprano.co.il', port=80): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x3e10f4f1dbb0>: Failed to establish a new connection: [Errno 110] Connection timed out'))

Because this is a local company, the first thing I thought about is that their firewall blocks any IP from outside the country (Israel). In conversations with their customer service they have insisted and again that they are open to the whole world and no IP address is blocked, and they advise me to check if any setting in Cloud Run environment blocks access to them. This sounds very strange to me because access to other addresses works, but since they insist I would be happy to make sure:

Does Cloud Run block access to some outbound connection? Is there a way to see the settings of this block and change them?

Is there a way to clearly check where the connection is blocked?


问:
How to return an excel file from NestJS Controller
So I am reading lots of data from my mongoose database and writing them into XLSX of SheetJS. I want to return a downloadable file from my controller. I got an object below, question is how can i return this object for download?

const wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'buffer' });
```

答:
you can try to implement it that way:</p>
```<code>import {Readable} from "stream";
import {readFileSync} from 'fs';
import {Response} from 'express';

    @Get('')
    async createFile(@Res() res: Response)
    {
        var buffer = readFileSync('/path_to_file');

        const stream = new Readable();
        stream.push(buffer);
        stream.push(null);

        res.set({
            'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
            'Content-Length': buffer.length,
        });
        stream.pipe(res);
    }
</code>```

Body:
you can try to implement it that way:

import {Readable} from "stream";
import {readFileSync} from 'fs';
import {Response} from 'express';

    @Get('')
    async createFile(@Res() res: Response)
    {
        var buffer = readFileSync('/path_to_file');

        const stream = new Readable();
        stream.push(buffer);
        stream.push(null);

        res.set({
            'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
            'Content-Length': buffer.length,
        });
        stream.pipe(res);
    }


问:
The text doesn't get wrapped in swift UI
Even After setting the  .lineLimit(nil) the text doesn't get wrapped.

```<code>var body: some View {
    VStack(alignment: .center) {
        Text("SwiftUI is a modern way to declare user interfaces for any Apple platform. ")
            .font(.title)
            .color(.red)
            .lineLimit(nil)
        Text("Create beautiful, dynamic apps faster than ever before.")
            .font(.system(size: 20))
            .lineLimit(nil)
    }.padding(EdgeInsets(top: 0, leading: 10, bottom: 0, trailing: 10))
}
</code>```

答:
I just added

```<code>.padding()
</code>```

to my Text instance and it worked

Body:
Even After setting the  .lineLimit(nil) the text doesn't get wrapped.

var body: some View {
    VStack(alignment: .center) {
        Text("SwiftUI is a modern way to declare user interfaces for any Apple platform. ")
            .font(.title)
            .color(.red)
            .lineLimit(nil)
        Text("Create beautiful, dynamic apps faster than ever before.")
            .font(.system(size: 20))
            .lineLimit(nil)
    }.padding(EdgeInsets(top: 0, leading: 10, bottom: 0, trailing: 10))
}

Body:
I just added

.padding()

to my Text instance and it worked


问:
fancybox iframe dimension
In the fancybox homepage (http://fancybox.net/home) there is an example that opens an iFrame dimensioned as the 75% of the screen.

I can't get it by modifying the width and height properties on the .js file as described on the site.

答:
Hi I just read through all of these and I had to take bits and pieces of what everyone else wrote to get it to work. I wanted a window 600 by 410

First change the java script I dealt with the file: jquery.fancybox-1.3.4.js (this may change with later versions)
under defaults set your height and width

width : 600,
height : 410,

*then change the script on your webpage

$("#various3").fancybox({

'width'               : 600,

'height'          : 410,

'autoScale'         : false,

'type'              : 'iframe'

please note the size is not in single quotes!  I wasted an hour before I saw this mistake.

This should help.  Now if someone can tell me how to get this iframe to pop up on page load.

Title: fancybox iframe dimension


问:
Passing image from one screen to another - Flutter
I'm using image picker to get the image , and once it's uploaded , I'd like to pass and display it on a different screen. now I'm getting this error

type 'String' is not a subtype of type 'File'

First screen :

```<code>void _openCamera(BuildContext context) async {
    final pickedFile = await ImagePicker().getImage(
      source: ImageSource.camera,
    );
    Navigator.of(context)
        .push(MaterialPageRoute(builder: (_) => second(image: pickedFile)));
  }
</code>```

second screen :

```<code>class second extends StatelessWidget {
  const second({
    Key? key,
    this.image,
  }) : super(key: key);

  final image;

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      body: SingleChildScrollView(
          child: Container(
              padding: EdgeInsets.all(16),
              child: Card(child: Image.file((image!.path))))),
      bottomNavigationBar: BottomAppBar(
        color: Colors.white,
      ),
      floatingActionButton: const FloatingActionButton(onPressed: null),
    );
  }
}
</code>```

答:
Use XFile?  with pickImage().

  void _openCamera(BuildContext context) async {
    final XFile? pickedFile = await ImagePicker().pickImage(
      source: ImageSource.camera,
    );

    if (pickedFile == null) return;
    Navigator.of(context)
        .push(MaterialPageRoute(builder: (_) => second(image: pickedFile)));
  }
```
<p>And to use it</p>
<pre class="lang-dart prettyprint-override"><code> const second({
    Key? key,
    required this.image,
  }) : super(key: key);

  final XFile image;
 ......

 child: Image.file(File(image.path)),

</code>```

Body:
I'm using image picker to get the image , and once it's uploaded , I'd like to pass and display it on a different screen. now I'm getting this error

type 'String' is not a subtype of type 'File'

First screen :

void _openCamera(BuildContext context) async {
    final pickedFile = await ImagePicker().getImage(
      source: ImageSource.camera,
    );
    Navigator.of(context)
        .push(MaterialPageRoute(builder: (_) => second(image: pickedFile)));
  }

second screen :

class second extends StatelessWidget {
  const second({
    Key? key,
    this.image,
  }) : super(key: key);

  final image;

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      body: SingleChildScrollView(
          child: Container(
              padding: EdgeInsets.all(16),
              child: Card(child: Image.file((image!.path))))),
      bottomNavigationBar: BottomAppBar(
        color: Colors.white,
      ),
      floatingActionButton: const FloatingActionButton(onPressed: null),
    );
  }
}

Body:
Use XFile?  with pickImage().

  void _openCamera(BuildContext context) async {
    final XFile? pickedFile = await ImagePicker().pickImage(
      source: ImageSource.camera,
    );

    if (pickedFile == null) return;
    Navigator.of(context)
        .push(MaterialPageRoute(builder: (_) => second(image: pickedFile)));
  }

And to use it

 const second({
    Key? key,
    required this.image,
  }) : super(key: key);

  final XFile image;
 ......

 child: Image.file(File(image.path)),


问:
Difference between multiple rows in same column in SAS/PROC SQL
I have a dataset temp1 as:

ID
Drug
lob
Timestamp

123
acetam
counter
01JAN22 04:25:17

123
acetam
counter
01JAN22 09:15:13

123
acetam
prescr
02JAN22 15:05:25

123
acetam
counter
03JAN22 23:28:05

234
tylenol
counter
11JAN22 18:12:39

345
aztyr
counter
03FEB22 16:11:19

345
aztyr
counter
03FEB22 16:15:20

for the same ID, Drug, lob and the old timestamp create a flag as 'Yes'

the second record of same ID, Drug, lob will also have a flag of 'Yes' when the timestamp is greater than 5 days compared to timestamp of previous entry.

expected output

ID
Drug
lob
Timestamp
flag

123
acetam
counter
01JAN22 04:25:17
Yes

123
acetam
counter
01JAN22 09:15:13
No

123
acetam
prescr
02JAN22 15:05:25
Yes

123
acetam
counter
11JAN22 23:28:05
Yes

234
tylenol
counter
11JAN22 18:12:39
Yes

345
aztyr
counter
03FEB22 16:11:19
Yes

345
aztyr
counter
03FEB22 16:15:20
No

My Code:

```<code>create table temp2 as
select id, drug,lob, datepart(timestamp)as timestamp format=mmddyy10.
from temp1
order by id, drug,lob
quit;

data temp3;
set temp2;
by id, drug,lob
diff=timestamp-lag(timestamp);
if first.id and first.drug and first.lob  then do diff=.;end;
run;

</code>```

I am first trying to calculate the difference between dates so that I can create a flag, but for the 3rd record for an lob='prescr' the diff I am getting is 1 but since the lob is different from the previous records this has to be considered as new record and flag has to 'yes'. I am stuck here and not able to move. Can anyone help?

答:
I recommend reading up on BY group processing:
https://documentation.sas.com/doc/en/pgmsascdc/9.4_3.5/lrcon/n01a08zkzy5igbn173zjz82zsi1s.htm

Example 1 illustrates how the first. and last. variables are set.

If I understand correctly you probably want to do something like this

```<code>data temp3;
  set temp2;
  by id drug lob;
  diff = timestamp - lag(timestamp);
  if first.lob or diff > 5 then
    flag = 'yes';
  else
    flag = 'no';
run;
</code>```

Body:
I have a dataset temp1 as:

ID
Drug
lob
Timestamp

123
acetam
counter
01JAN22 04:25:17

123
acetam
counter
01JAN22 09:15:13

123
acetam
prescr
02JAN22 15:05:25

123
acetam
counter
03JAN22 23:28:05

234
tylenol
counter
11JAN22 18:12:39

345
aztyr
counter
03FEB22 16:11:19

345
aztyr
counter
03FEB22 16:15:20

for the same ID, Drug, lob and the old timestamp create a flag as 'Yes'

the second record of same ID, Drug, lob will also have a flag of 'Yes' when the timestamp is greater than 5 days compared to timestamp of previous entry.

expected output

ID
Drug
lob
Timestamp
flag

123
acetam
counter
01JAN22 04:25:17
Yes

123
acetam
counter
01JAN22 09:15:13
No

123
acetam
prescr
02JAN22 15:05:25
Yes

123
acetam
counter
11JAN22 23:28:05
Yes

234
tylenol
counter
11JAN22 18:12:39
Yes

345
aztyr
counter
03FEB22 16:11:19
Yes

345
aztyr
counter
03FEB22 16:15:20
No

My Code:

create table temp2 as
select id, drug,lob, datepart(timestamp)as timestamp format=mmddyy10.
from temp1
order by id, drug,lob
quit;

data temp3;
set temp2;
by id, drug,lob
diff=timestamp-lag(timestamp);
if first.id and first.drug and first.lob  then do diff=.;end;
run;

I am first trying to calculate the difference between dates so that I can create a flag, but for the 3rd record for an lob='prescr' the diff I am getting is 1 but since the lob is different from the previous records this has to be considered as new record and flag has to 'yes'. I am stuck here and not able to move. Can anyone help?

Body:
I recommend reading up on BY group processing:
https://documentation.sas.com/doc/en/pgmsascdc/9.4_3.5/lrcon/n01a08zkzy5igbn173zjz82zsi1s.htm

Example 1 illustrates how the first. and last. variables are set.

If I understand correctly you probably want to do something like this

data temp3;
  set temp2;
  by id drug lob;
  diff = timestamp - lag(timestamp);
  if first.lob or diff > 5 then
    flag = 'yes';
  else
    flag = 'no';
run;


问:
Redis: Show database size/size for keys
My redis instance seems to being growing very large and I'd like to find out which of the multiple databases I have in there consumes how much memory. Redis' INFO command just shows me the total size and the number of keys per database which doesn't give me much insight... So any tools/ideas that give me more information when monitoring the redis server would be appreciated.

The Redis documentation doesn't show me any commands that can return the consumed memory of certain keys, so I guess if any buggy code would write a lot of "trash" to redis this could be really hard to find...

答:
One-liner. All redis keys and corresponding used memory.</p>
```<code>redis-cli keys "*" | while read line; do echo -n "$line: "; redis-cli memory usage $line; done
</code>```

Title: Redis: Show database size/size for keys

Body:
One-liner. All redis keys and corresponding used memory.

redis-cli keys "*" | while read line; do echo -n "$line: "; redis-cli memory usage $line; done


问:
Remain authenticated in a mobile application
I am working on an Ionic mobile app and have a django backend. We currently use JWT authentication in order to access the django backend (multiple applications use this backend including a react frontend). So the current auth method needs to stay in tact.

Now that we are working on an app we want the user to stay logged in after entering his credentials once on the app. I've been researching a good way to do this all day but can't seem to find a clear answer.

What is the best option to keep the user authenticated? Should I set a high expiration on the refresh token? (Not sure if that is secure..)

Should I use session auth? I found it that Django mostly supports this on services on the same domain. Seems like you have to relax quite a few security settings which doesn't seem to be the right solution.

I am not sure where to go from here. Do you guys have any suggestions?

答:
I have not tried using ionic but generally what you want to do is to use a HTTP Client on you application which has an interceptor that will be watching for response with 401 Unauthorized  response and you can check if the Authorization Header used was of the JWT if so,  the HTTP client could send a request to your jwt refresh point with the  refresh token and can re-update the jwt access token on the
moble application and retry the request again.

You could store the JWT refresh token on the users device.


问:
How to put pictures or videos next to a plotly plot?
I understand how to create HTML pages with plotly plots.
I also understand how to divide these pages in subplots so that I can put several plots in one page.

I would like to put a video or a picture next to a plot.

Is there a way to do this from a python program or should I just edit manually the HTML file product of plotly?

答:
concept in comments are https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs

these can be used for images within figure in plotly (not demonstrated)

can be used in HTML (demonstrated by adding additional HTML  using BeautifulSoup

same approach can be used for videos

there is only a need to use data URIs if your images / videos are files hence cannot be distributed as a URL, hence require encoding in HTML using data URIs

```<code>import pandas as pd
import plotly.graph_objects as go
import numpy as np
import plotly.express as px
import base64, io, requests
from PIL import Image
from pathlib import Path
import webbrowser
from bs4 import BeautifulSoup

# data for whare images can be found
df_flag = pd.read_csv(
    io.StringIO(
        """country,Alpha-2 code,Alpha-3 code,URL
Australia,AU,AUS,https://www.worldometers.info//img/flags/small/tn_as-flag.gif
New Zealand,NZ,NZL,https://www.worldometers.info//img/flags/small/tn_nz-flag.gif"""
    )
)

# ensure that images exist on your file system...
f = Path.cwd().joinpath("flags")
if not f.exists():
    f.mkdir()

# download some images and use easy to use filenames...
for r in df_flag.iterrows():
    flag_file = f.joinpath(f'{r[1]["Alpha-3 code"]}.gif')
    if not flag_file.exists():
        r = requests.get(r[1]["URL"], stream=True, headers={"User-Agent": "XY"})
        with open(flag_file, "wb") as fd:
            for chunk in r.iter_content(chunk_size=128):
                fd.write(chunk)

# encode
def b64image(country):
    b = io.BytesIO()
    im = Image.open(Path.cwd().joinpath("flags").joinpath(f"{country}.gif"))
    im.save(b, format="PNG")
    b64 = base64.b64encode(b.getvalue())
    return b64.decode("utf-8")

df_flag["image"] = df_flag["Alpha-3 code"].apply(b64image)

# create a figure
fig = px.line(df_flag, x="Alpha-2 code", y=df_flag.index)
fh = Path.cwd().joinpath("html.html")

# add some images to HTML
soup = BeautifulSoup(fig.to_html(include_plotlyjs="cdn", div_id="include image"))
d = soup.body
for i, r in df_flag.iterrows():
    img = soup.new_tag("img", src="data:image/png;base64,"+r["image"])
    d.insert(0, img)

with open(fh, "w") as fp:
    fp.write(str(soup))

# launch it...
webbrowser.open("file://" + str(fh), new=2)

</code>```

Body:
concept in comments are https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs

these can be used for images within figure in plotly (not demonstrated)

can be used in HTML (demonstrated by adding additional HTML  using BeautifulSoup

same approach can be used for videos

there is only a need to use data URIs if your images / videos are files hence cannot be distributed as a URL, hence require encoding in HTML using data URIs

import pandas as pd
import plotly.graph_objects as go
import numpy as np
import plotly.express as px
import base64, io, requests
from PIL import Image
from pathlib import Path
import webbrowser
from bs4 import BeautifulSoup

# data for whare images can be found
df_flag = pd.read_csv(
    io.StringIO(
        """country,Alpha-2 code,Alpha-3 code,URL
Australia,AU,AUS,https://www.worldometers.info//img/flags/small/tn_as-flag.gif
New Zealand,NZ,NZL,https://www.worldometers.info//img/flags/small/tn_nz-flag.gif"""
    )
)

# ensure that images exist on your file system...
f = Path.cwd().joinpath("flags")
if not f.exists():
    f.mkdir()

# download some images and use easy to use filenames...
for r in df_flag.iterrows():
    flag_file = f.joinpath(f'{r[1]["Alpha-3 code"]}.gif')
    if not flag_file.exists():
        r = requests.get(r[1]["URL"], stream=True, headers={"User-Agent": "XY"})
        with open(flag_file, "wb") as fd:
            for chunk in r.iter_content(chunk_size=128):
                fd.write(chunk)

# encode
def b64image(country):
    b = io.BytesIO()
    im = Image.open(Path.cwd().joinpath("flags").joinpath(f"{country}.gif"))
    im.save(b, format="PNG")
    b64 = base64.b64encode(b.getvalue())
    return b64.decode("utf-8")

df_flag["image"] = df_flag["Alpha-3 code"].apply(b64image)

# create a figure
fig = px.line(df_flag, x="Alpha-2 code", y=df_flag.index)
fh = Path.cwd().joinpath("html.html")

# add some images to HTML
soup = BeautifulSoup(fig.to_html(include_plotlyjs="cdn", div_id="include image"))
d = soup.body
for i, r in df_flag.iterrows():
    img = soup.new_tag("img", src="data:image/png;base64,"+r["image"])
    d.insert(0, img)

with open(fh, "w") as fp:
    fp.write(str(soup))

# launch it...
webbrowser.open("file://" + str(fh), new=2)


问:
What is the best way to import SVG using React.JS

My team and I are building a react application and we want to import SVGs not as a string so we'll have the ability to use it as a component.

Since we've installed the project using CRA, SVGR is already installed and is in webpack configuration.

We wanted to know if there's any other way to import the SVG file and not to use the import {ReactComponent as Logo} from '../path' but use something like import Logo from '../path'.

Also is there any benefits from using it that way?
Actually we're able to import it the way we want but we can't use it outside of an image tag.

Thanks.

答:
Usually I'm using this package react-svg, which you can use with Styled Components.

I create a component with it like so:

```<code>import styled, { css } from "styled-components"
import { ReactSVG } from "react-svg"

const IconStyled = styled(ReactSVG)`
    display: inline-flex;
    width: ${props => `${props.size}px`};
    height: ${props => `${props.size}px`};
    align-items: center;
    justify-content: center;

    span {
        display: inline-flex;
        align-items: center;
        justify-content: center;
        width: 100%;
        height: 100%;
    }

    svg {
        fill: black;
        width: 100%;
        height: 100%;
    }

    path {
        fill: ${props => props.color};
    }
`

export default function Icon(props) {
    return (
        <IconStyled
            src= {`/icons/${props.name}.svg`}
            color={props.color || "currentColor"}
            size={props.size}
            wrapper="span"
            {...props}
        />
    )
}
</code>```

Then, put all the .svg files inside the public folder, and just use them like this:

```<code><Icon name="name-of-icon" size={24} />
</code>```

Body:
Usually I'm using this package react-svg, which you can use with Styled Components.

I create a component with it like so:

import styled, { css } from "styled-components"
import { ReactSVG } from "react-svg"

const IconStyled = styled(ReactSVG)`
    display: inline-flex;
    width: ${props => `${props.size}px`};
    height: ${props => `${props.size}px`};
    align-items: center;
    justify-content: center;

    span {
        display: inline-flex;
        align-items: center;
        justify-content: center;
        width: 100%;
        height: 100%;
    }

    svg {
        fill: black;
        width: 100%;
        height: 100%;
    }

    path {
        fill: ${props => props.color};
    }
`

export default function Icon(props) {
    return (
        <IconStyled
            src= {`/icons/${props.name}.svg`}
            color={props.color || "currentColor"}
            size={props.size}
            wrapper="span"
            {...props}
        />
    )
}

Then, put all the .svg files inside the public folder, and just use them like this:

<Icon name="name-of-icon" size={24} />


问:
jar file doesn't do anything when executed (VSCode)
Here I have a short program, which I would like to export as a .jar file. When I use VSCode's "Export Jar..." option (and select Test as the main class), it creates the jar file without any errors, but when I run it (by double clicking), nothing happens. When I run the code from within VSCode however, it works as expected (the window shows up and says "Hello World").
Here's my code:

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;

public class Test {

    public static void main(String[] args) {
        try {
            SwingUtilities.invokeAndWait(new Runnable() {
                @Override
                public void run() {
                    JFrame frame = new JFrame("Test");
                    frame.setSize(600, 400);
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    frame.setLocationRelativeTo(null);
                    frame.getContentPane().add(new JLabel("Hello World!"));
                    frame.setVisible(true);
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
```

答:
If you want to run your java program (when it is compiled in a jar file) you need to do the following:

```<code>java -cp your-jar-name.jar Test
</code>```

Test is a full name (including package name) of your class with main method.

If Main-Class is defined in manifest your can do also this

```<code>java -jar your-jar-name.jar
</code>```

Double click won't work if you click on jar file in some operating systems. You can use .sh script in Linux or .bat script in Windows and click on this script.

Body:
If you want to run your java program (when it is compiled in a jar file) you need to do the following:

java -cp your-jar-name.jar Test

Test is a full name (including package name) of your class with main method.

If Main-Class is defined in manifest your can do also this

java -jar your-jar-name.jar

Double click won't work if you click on jar file in some operating systems. You can use .sh script in Linux or .bat script in Windows and click on this script.


问:
Hide search input field and search results when user clicks outside of them
How to hide both the input field and the search results box when user clicks outside of them?

Currently if you hover your mouse over #search-btn both #search-container and #search-results will appear. If you click anywhere except on #search-container both will disappear.

I want so that I can click on #search-results without both of them disappearing.

Fiddle: https://jsfiddle.net/emils/d2sn7q6L/

HTML:

```<code><div id="search-container">
  <form id="search-form">
    <input id="search" type="search">
  </form>
</div> <!-- End search-box -->

<a id="search-btn" class="search-icon" href="#">search</a>

<div id="search-results"></div> <!-- End search-results -->
</code>```

JS:

```<code>var searchInput = $("#search-container");
var searchResults = $("#search-results");

var showSearchInput = function() {
  searchInput.show();
  searchResults.show();
  if(searchInput.is(":visible")) {
    $("#search").focus();
  }
};
$("#search-btn").hover(showSearchInput);

searchInput.focusout(function(e) {
  searchInput.hide();
  searchResults.hide();
});
</code>```

答:
<pre class="lang-js prettyprint-override"><code>// Hide search result when clicked outside search field
let searchInput = $(".search-container");
let searchResults = $(".search-result");

$(document).click(function(e) {
  if ($(e.target).closest(".search-container, .search-result").length == 0) {
    searchInput.show();
    searchResults.hide();
  } else {
    searchResults.show();
  }
});
</code>```

Body:
How to hide both the input field and the search results box when user clicks outside of them?

Currently if you hover your mouse over #search-btn both #search-container and #search-results will appear. If you click anywhere except on #search-container both will disappear.

I want so that I can click on #search-results without both of them disappearing.

Fiddle: https://jsfiddle.net/emils/d2sn7q6L/

HTML:

  <form id="search-form">
    <input id="search" type="search">
  </form>

search

JS:

var searchInput = $("#search-container");
var searchResults = $("#search-results");

var showSearchInput = function() {
  searchInput.show();
  searchResults.show();
  if(searchInput.is(":visible")) {
    $("#search").focus();
  }
};
$("#search-btn").hover(showSearchInput);

searchInput.focusout(function(e) {
  searchInput.hide();
  searchResults.hide();
});


问:
R Plotly show x-axis value via hoovermode
Following this question

I would like to have the x value visible via hovermode "x"...so I have added an extra add_trace which works, however its depicted in green/red and would like to have it in white

```<code>t <- tibble("one" = c(1,2,3,4,5,6,7,8,9),
            "two" = c(-5,6,9,-8,7,-1,5,2,1),
            "three" = c(2,5,6,9,8,7,8,4,5))

# 'bar' objects don't have these attributes: 'mode', 'line'
Plot <- plot_ly(t, x = ~one, y = ~two, type = 'bar', mode = NULL, line = NULL, name = ~ifelse(two < 0, yes = "two < 0", no = "two > 0"),
                color = ~two < 0, colors = c("#28a745", "#dc3545"),
                yaxis = 'y2') %>%

  add_trace(type = "bar",
            x = ~one, y = 0,
            hoverinfo='text',
            text = ~paste("X:", one),
            yaxis = "y", opacity = 0,
            showlegend=F
  ) %>%

  add_trace(x = ~one, y = ~three, type = 'scatter',  mode = 'lines',
                name = "three", line = list(color = "#ffc107"), color = NULL, yaxis = "y") %>%

  layout(title = "test",
         xaxis = list(titel = "one"),
         yaxis = list(side = 'right',
                      title = 'three',
                      showgrid = F, zeroline = F,
                      showline = T),
         yaxis2 = list(side = 'left', title = 'two',
                       showgrid = F, zeroline = F,
                       showline = T, overlaying = "y"),
         hovermode = "x")
</code>```

答:
We can achive this by defining a marker color for the new trace marker = list(color = "#ffffff")

```<code>library(plotly)
library(dplyr)

t <- tibble("one" = c(1,2,3,4,5,6,7,8,9),
            "two" = c(-5,6,9,-8,7,-1,5,2,1),
            "three" = c(2,5,6,9,8,7,8,4,5))

# 'bar' objects don't have these attributes: 'mode', 'line'
Plot <- plot_ly(t, x = ~one, y = ~two, type = 'bar', mode = NULL, line = NULL, name = ~ifelse(two < 0, yes = "two < 0", no = "two > 0"),
                color = ~two < 0, colors = c("#28a745", "#dc3545"),
                yaxis = 'y2') %>%

  add_trace(type = "bar",
            x = ~one, y = 0,
            hoverinfo='text',
            text = ~paste("X:", one),
            yaxis = "y", opacity = 0,
            showlegend = FALSE,
            marker = list(color = "#ffffff")
  ) %>%

  add_trace(x = ~one, y = ~three, type = 'scatter',  mode = 'lines',
            name = "three", line = list(color = "#ffc107"), color = NULL, yaxis = "y") %>%

  layout(title = "test",
         xaxis = list(titel = "one"),
         yaxis = list(side = 'right',
                      title = 'three',
                      showgrid = F, zeroline = F,
                      showline = T),
         yaxis2 = list(side = 'left', title = 'two',
                       showgrid = F, zeroline = F,
                       showline = T, overlaying = "y"),
         hovermode = "x")

Plot
</code>```

Body:
Following this question

I would like to have the x value visible via hovermode "x"...so I have added an extra add_trace which works, however its depicted in green/red and would like to have it in white

t <- tibble("one" = c(1,2,3,4,5,6,7,8,9),
            "two" = c(-5,6,9,-8,7,-1,5,2,1),
            "three" = c(2,5,6,9,8,7,8,4,5))

# 'bar' objects don't have these attributes: 'mode', 'line'
Plot <- plot_ly(t, x = ~one, y = ~two, type = 'bar', mode = NULL, line = NULL, name = ~ifelse(two < 0, yes = "two < 0", no = "two > 0"),
                color = ~two < 0, colors = c("#28a745", "#dc3545"),
                yaxis = 'y2') %>%

  add_trace(type = "bar",
            x = ~one, y = 0,
            hoverinfo='text',
            text = ~paste("X:", one),
            yaxis = "y", opacity = 0,
            showlegend=F
  ) %>%

  add_trace(x = ~one, y = ~three, type = 'scatter',  mode = 'lines',
                name = "three", line = list(color = "#ffc107"), color = NULL, yaxis = "y") %>%

  layout(title = "test",
         xaxis = list(titel = "one"),
         yaxis = list(side = 'right',
                      title = 'three',
                      showgrid = F, zeroline = F,
                      showline = T),
         yaxis2 = list(side = 'left', title = 'two',
                       showgrid = F, zeroline = F,
                       showline = T, overlaying = "y"),
         hovermode = "x")

Body:
We can achive this by defining a marker color for the new trace marker = list(color = "#ffffff")

library(plotly)
library(dplyr)

t <- tibble("one" = c(1,2,3,4,5,6,7,8,9),
            "two" = c(-5,6,9,-8,7,-1,5,2,1),
            "three" = c(2,5,6,9,8,7,8,4,5))

# 'bar' objects don't have these attributes: 'mode', 'line'
Plot <- plot_ly(t, x = ~one, y = ~two, type = 'bar', mode = NULL, line = NULL, name = ~ifelse(two < 0, yes = "two < 0", no = "two > 0"),
                color = ~two < 0, colors = c("#28a745", "#dc3545"),
                yaxis = 'y2') %>%

  add_trace(type = "bar",
            x = ~one, y = 0,
            hoverinfo='text',
            text = ~paste("X:", one),
            yaxis = "y", opacity = 0,
            showlegend = FALSE,
            marker = list(color = "#ffffff")
  ) %>%

  add_trace(x = ~one, y = ~three, type = 'scatter',  mode = 'lines',
            name = "three", line = list(color = "#ffc107"), color = NULL, yaxis = "y") %>%

  layout(title = "test",
         xaxis = list(titel = "one"),
         yaxis = list(side = 'right',
                      title = 'three',
                      showgrid = F, zeroline = F,
                      showline = T),
         yaxis2 = list(side = 'left', title = 'two',
                       showgrid = F, zeroline = F,
                       showline = T, overlaying = "y"),
         hovermode = "x")

Plot


问:
Using User Profile automatically load information into form fields
In my pervious question I asked how I can automatically save the user submitting the form. I found the form_valid method to be the best in that case. However in my models I also have a user profile model like this

models.py

```<code>....
class Profile(models.Model):
  user = models.OneToOneField(User,on_delete=models.CASCADE)
  title = models.CharField(max_length=24)
  first_name = models.CharField(max_length=35)
  last_name = models.CharField(max_length=35)
  email = models.EmailField(max_length=64)
  phone_number = models.CharField(max_length=12)
  department = models.ForeignKey(Department,null=True,on_delete=models.SET_NULL)
  supervisor = models.ForeignKey('self',blank=True,null=True,on_delete=models.SET_NULL)
...
</code>```

As you can see I used the One to One method to make my UserProfile

As before in my models.py I have my reports model

```<code>...
class Report(models.Model):
  id = models.UUIDField(primary_key=True,default=uuid.uuid1,editable=False)
  department = models.ForeignKey(Company,null=True,on_delete=models.SET_NULL)
  user= models.ForeignKey(User,on_delete=models.PROTECT)
  submission_date= models.DateField(auto_now=True) #invisible to user
  submission_time = models.TimeField(auto_now=True) #invisible to ,user
  date = models.DateField(default=now,blank=False)
  time = models.TimeField(default=now,blank=False,help_text="hh:mm:ss")
  location = PlainLocationField()
  building = models.ForeignKey(bld,null=True,on_delete=models.SET_NULL)
  size = models.PositiveIntegerField()
  notes = models.TextField(blank=True)
   def __str__(self):
     return f'{self.date} {self.time} ({self.department})
...
</code>```

My question how I can make it so that the department field will load from the user profile? I would hope to eventually make it possible for users in the same department to be able to view and update each others Reports.

As before:

form.py

```<code>class ReportForm(forms.ModelForm):
    class Meta:
        model = Report
        fields = '__all__'
        location = PlainLocationField()
    def redirect():
        return redirect("Report")
</code>```

views.py

```<code>class ReportCreate(LoginRequiredMixin,CreateView):
    Template = "templates\reports\Report.html"
    model = Report
    fields = '__all__'
    def form_valid(self, form):
        form.instance.user = self.request.user
        form.instance.save()
        return super(ReportCreate, self).form_valid(form)
    def get_success_url(self):
        return reverse('Report')
    def get_absolute_url(self):
        return reverse('Report', kwargs={'pk':self.pk})
</code>```

答:
I advise you to use related_name in your ForeignKeys. Set the department field of both models as following:

```<code>class Profile(models.Model):
    ...
    department = models.ForeignKey(Department, null=True, on_delete=models.SET_NULL, related_name='profiles')
    ...

class Report(models.Model):
    ...
    department = models.ForeignKey(Department, null=True, on_delete=models.SET_NULL, related_name='reports')
    ...
</code>```

From now on, Department objects that are related to User.Profile you can access like that:

```<code>Department.profiles.all()           # it returns QuerySet of all related to Department Profile objects
Department.reports.all()            # it returns QuerySet of all related to Department Report objects
</code>```

And you can use it in making QuerySet for user:

```<code>Report.objects.filter(department=self.request.user.profile.department)
# it returns all Report objects, that have exactly the same department as the user
</code>```

Or using our new relationship:

```<code>department = self.request.user.profile.department
reports_for_user = department.reports.all()
</code>```

But I can see one problem. You are using Company model for ForeignKey in Report. It has to be the same Department model for both Profile and Report models for such easy option to work. Also you definitely should not mix naming in single project. You can set relation with Company as another field:

```<code>company = models.ForeignKey(Company, null=True, on_delete=models.SET_NULL)
</code>```

Body:
In my pervious question I asked how I can automatically save the user submitting the form. I found the form_valid method to be the best in that case. However in my models I also have a user profile model like this

models.py

....
class Profile(models.Model):
  user = models.OneToOneField(User,on_delete=models.CASCADE)
  title = models.CharField(max_length=24)
  first_name = models.CharField(max_length=35)
  last_name = models.CharField(max_length=35)
  email = models.EmailField(max_length=64)
  phone_number = models.CharField(max_length=12)
  department = models.ForeignKey(Department,null=True,on_delete=models.SET_NULL)
  supervisor = models.ForeignKey('self',blank=True,null=True,on_delete=models.SET_NULL)
...

As you can see I used the One to One method to make my UserProfile

As before in my models.py I have my reports model

...
class Report(models.Model):
  id = models.UUIDField(primary_key=True,default=uuid.uuid1,editable=False)
  department = models.ForeignKey(Company,null=True,on_delete=models.SET_NULL)
  user= models.ForeignKey(User,on_delete=models.PROTECT)
  submission_date= models.DateField(auto_now=True) #invisible to user
  submission_time = models.TimeField(auto_now=True) #invisible to ,user
  date = models.DateField(default=now,blank=False)
  time = models.TimeField(default=now,blank=False,help_text="hh:mm:ss")
  location = PlainLocationField()
  building = models.ForeignKey(bld,null=True,on_delete=models.SET_NULL)
  size = models.PositiveIntegerField()
  notes = models.TextField(blank=True)
   def __str__(self):
     return f'{self.date} {self.time} ({self.department})
...

My question how I can make it so that the department field will load from the user profile? I would hope to eventually make it possible for users in the same department to be able to view and update each others Reports.

As before:

form.py

class ReportForm(forms.ModelForm):
    class Meta:
        model = Report
        fields = '__all__'
        location = PlainLocationField()
    def redirect():
        return redirect("Report")

views.py

class ReportCreate(LoginRequiredMixin,CreateView):
    Template = "templates\reports\Report.html"
    model = Report
    fields = '__all__'
    def form_valid(self, form):
        form.instance.user = self.request.user
        form.instance.save()
        return super(ReportCreate, self).form_valid(form)
    def get_success_url(self):
        return reverse('Report')
    def get_absolute_url(self):
        return reverse('Report', kwargs={'pk':self.pk})

Body:
I advise you to use related_name in your ForeignKeys. Set the department field of both models as following:

class Profile(models.Model):
    ...
    department = models.ForeignKey(Department, null=True, on_delete=models.SET_NULL, related_name='profiles')
    ...

class Report(models.Model):
    ...
    department = models.ForeignKey(Department, null=True, on_delete=models.SET_NULL, related_name='reports')
    ...

From now on, Department objects that are related to User.Profile you can access like that:

Department.profiles.all()           # it returns QuerySet of all related to Department Profile objects
Department.reports.all()            # it returns QuerySet of all related to Department Report objects

And you can use it in making QuerySet for user:

Report.objects.filter(department=self.request.user.profile.department)
# it returns all Report objects, that have exactly the same department as the user

Or using our new relationship:

department = self.request.user.profile.department
reports_for_user = department.reports.all()

But I can see one problem. You are using Company model for ForeignKey in Report. It has to be the same Department model for both Profile and Report models for such easy option to work. Also you definitely should not mix naming in single project. You can set relation with Company as another field:

company = models.ForeignKey(Company, null=True, on_delete=models.SET_NULL)


问:
How do you run a SQL Server query from PowerShell?
Is there a way to execute an arbitrary query on a SQL Server using Powershell on my local machine?</p>

答:
You can even format string and pass parameters as you want.

```<code>case "ADDSQLSERVERUSER":
    //0 = coprorateName;
    //1 = user password
    //2 = servername
    command = @"$sqlQuery = Use JazzUWS_'{0}'
                Create login UWSUser_'{0}' with password='{1}';
                Create user UWSUser_'{0}' for login UWSUser_'{0}';
                Grant Execute to UWSUser_'{0}';

                Use ReportSvrUWS_'{0}'
                Create user UWSUser_'{0}' for login UWSUser_'{0}';
                Grant Execute to UWSUser_'{0}';

                Invoke-Sqlcmd -Query $sqlQuery -ServerInstance '{2}'";
    break;
</code>```

C# Code for remote execution(you can organize your way)

```<code>        string script = PowershellDictionary.GetPowershellCommand("ADDSQLSERVERUSER");
        script = String.Format(script, this.CorporateName, password, this.SQLServerName)
        PowerShellExecution.RunScriptRemote(_credentials.Server, _credentials.Username, _credentials.Password, new List<string> { script });
</code>```

Body:
You can even format string and pass parameters as you want.

case "ADDSQLSERVERUSER":
    //0 = coprorateName;
    //1 = user password
    //2 = servername
    command = @"$sqlQuery = Use JazzUWS_'{0}'
                Create login UWSUser_'{0}' with password='{1}';
                Create user UWSUser_'{0}' for login UWSUser_'{0}';
                Grant Execute to UWSUser_'{0}';

                Use ReportSvrUWS_'{0}'
                Create user UWSUser_'{0}' for login UWSUser_'{0}';
                Grant Execute to UWSUser_'{0}';

                Invoke-Sqlcmd -Query $sqlQuery -ServerInstance '{2}'";
    break;

C# Code for remote execution(you can organize your way)

        string script = PowershellDictionary.GetPowershellCommand("ADDSQLSERVERUSER");
        script = String.Format(script, this.CorporateName, password, this.SQLServerName)
        PowerShellExecution.RunScriptRemote(_credentials.Server, _credentials.Username, _credentials.Password, new List<string> { script });


问:
change words at particular location in javascript string

var str = "Hello world";

str.charAt(2)="P"//instead of l i am assigning the value P

console.log(str)```

I want to replace some Text from the string by checking some coditions but i am getting error i also tried replace function but that return nothing does no changes in the string

答:
In JavaScript, strings are immutable, there are 2 ways you can do this which I have mentioned below

1 way can be to split the string using two substrings and stuff the character between them

```<code>var s = "Hello world";
var index = 2;
s = s.substring(0, index) + 'p' + s.substring(index + 1);
console.log(s)
</code>```

2 way can be to convert the string to character array, replace one array member and join it

```<code>var str="Hello World"
str = str.split('');
str[2] = 'p';
str = str.join('');
console.log(str)
</code>```

Body:
var str = "Hello world";

str.charAt(2)="P"//instead of l i am assigning the value P

console.log(str)

I want to replace some Text from the string by checking some coditions but i am getting error i also tried replace function but that return nothing does no changes in the string

Body:
In JavaScript, strings are immutable, there are 2 ways you can do this which I have mentioned below

1 way can be to split the string using two substrings and stuff the character between them

var s = "Hello world";
var index = 2;
s = s.substring(0, index) + 'p' + s.substring(index + 1);
console.log(s)

2 way can be to convert the string to character array, replace one array member and join it

var str="Hello World"
str = str.split('');
str[2] = 'p';
str = str.join('');
console.log(str)


问:
Change php variable based on javascript value
how can i change/assign a value to php variable depending on a javascript variable?
here is my code.

```<code><select id="reOutcome" name="reOutcome" onchange="OnChange(this.form.reOutcome);">
<option value="1">Value 1</option>
<option value="2">Value 2</option>
<option value="3">Value 3</option>
</select>

<script type="text/javascript">

function OnChange(dropdown)
{
    var myindex  = dropdown.selectedIndex
    var SelValue = dropdown.options[myindex].value
    if(SelValue==2){
     <?php
    $sCOMPFields .= "|"."SreComments";
    $sCOMPFields .= "|"."rePrID";
     ?>
    }
    return true;
}
</script>
</code>```

The onchange function is working fine. I just don't know how to change the php variable. I searched online a lot. All im getting is how to assign php variable to javascript. That is not what im looking for.
Thanks for your help.

答:
that's exactly we use ajax.
make the page loads in default preferences, then update it using ajax</p>

Body:
how can i change/assign a value to php variable depending on a javascript variable?
here is my code.

<select id="reOutcome" name="reOutcome" onchange="OnChange(this.form.reOutcome);">
<option value="1">Value 1</option>
<option value="2">Value 2</option>
<option value="3">Value 3</option>
</select>

The onchange function is working fine. I just don't know how to change the php variable. I searched online a lot. All im getting is how to assign php variable to javascript. That is not what im looking for.
Thanks for your help.


问:
Shall I use transformations on PIL Image or rather on PyTorch tensor?
My inputs are PIL images. Suppose I have the following transformation composition:

```<code> transforms.Compose([
            transforms.RandomResizedCrop(size=224),
            transforms.RandomHorizontalFlip(),
            transforms.ToTensor()])
</code>```

As most of the transforms in PyTorch can work on both PIL images and tensors, I wonder in which order I should use them. Shall I first use all the transformations possible to use on PIL images and then transform to tensor, or shall I first transform to tensor and then apply the other transformations on tensors? Is the one more effective than the other?

答:
In the case of transformation you mentioned, I think order doesn't matter. But for a complete flow of work, the order helps a lot in understanding.

For example, in the given code, first, you are cropping the image, then using random horizontal flip for data augmentation after doing these two operations you are converting it into a PyTorch tensor which makes sense.

Body:
My inputs are PIL images. Suppose I have the following transformation composition:

 transforms.Compose([
            transforms.RandomResizedCrop(size=224),
            transforms.RandomHorizontalFlip(),
            transforms.ToTensor()])

As most of the transforms in PyTorch can work on both PIL images and tensors, I wonder in which order I should use them. Shall I first use all the transformations possible to use on PIL images and then transform to tensor, or shall I first transform to tensor and then apply the other transformations on tensors? Is the one more effective than the other?


问:
Prevent file name changes in chooser of Intent.ACTION_CREATE_DOCUMENT
I am using the following code to have a user select where to export a file:

```<code>private void onChooseFile() {
  SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyyMMdd");
  Intent intent = new Intent()
    .setType("*/*")
    .setAction(Intent.ACTION_CREATE_DOCUMENT)
    .putExtra(Intent.EXTRA_TITLE, dateFormatter.format(new Date()) + "-Whatever.mydb");

  Intent chooser = Intent.createChooser(intent, "Select a file");

  startActivityForResult(chooser, FILE_SELECT_CODE);
}
</code>```

This works unless a user decides to delete my default provided file name... then it creates a file called literally "(invalid)" at the selected location... how do I prevent users changing my default provided name... my real intent is to make sure that the file that I export is never called "(invalid)" and always ends with the "mydb" extension.

答: None of what you want is possible. It is the user's device and the user's content. The user can name it whatever the user wants.</p>

Body:
I am using the following code to have a user select where to export a file:

private void onChooseFile() {
  SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyyMMdd");
  Intent intent = new Intent()
    .setType("*/*")
    .setAction(Intent.ACTION_CREATE_DOCUMENT)
    .putExtra(Intent.EXTRA_TITLE, dateFormatter.format(new Date()) + "-Whatever.mydb");

  Intent chooser = Intent.createChooser(intent, "Select a file");

  startActivityForResult(chooser, FILE_SELECT_CODE);
}

This works unless a user decides to delete my default provided file name... then it creates a file called literally "(invalid)" at the selected location... how do I prevent users changing my default provided name... my real intent is to make sure that the file that I export is never called "(invalid)" and always ends with the "mydb" extension.


问:
Fix my querySelector to add a specific class to it in javaScript
I have built the navigation bar in my web page dynamically as shown below

```<code>NavBuilder = () => {
//to loop from section 1 to 4 and add sections to navigation
for (s = 0; s < sections.length; s++) {
    const liElem = document.createElement('li');
    //const divElem = document.createElement("div");
    const Id = sections[s].id;
    const DataNav = sections[s].dataset.nav;
    liElem.innerHTML = `<a class="menu__link" href="#${Id}">${DataNav}</a>`;
    Menu.appendChild(liElem);
}
}
NavBuilder();
</code>```

and when I want to scroll the page I want to add a specific class "your-active-class" to the section which I created in my html page, and also add the class "active" to the liElem so whenever I scroll in the page and stop on a specific section the navbar should highlight the section I stopped on int the navbar it and also highlight the section itself.

the javaScript function I created to add the class active:

```<code>window.addEventListener('scroll', () => {
sections.forEach(s => {
    const topDistance = s.getBoundingClientRect().top;
    // if the distance to the top is between 0-150px
    if (topDistance >= 0 && topDistance < 150) {
        s.classList.add('your-active-class');
        document.querySelector(`<a class="menu__link" href="#${sections[s].id}"></a>`).classList.add("active");

        // otherwise, remove the class
    } else {
        s.classList.remove('your-active-class');
        document.querySelector(`<a class="menu__link" href="#${sections[s].id}"></a>`).classList.remove("active");

    }
});

});
</code>```

I am still caughting this error "Uncaught TypeError: Cannot read property 'id' of undefined" in the line
document.querySelector().classList.add("active");

What is the mistake i am making that prevent me from highlighting my navbar?

the html code:

```<code>    <!DOCTYPE>
<html lang="en">

<head>
</head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Manipulating the DOM</title>
<!-- Load Google Fonts -->
<link href="https://fonts.googleapis.com/css?family=Fira+Sans:900|Merriweather&display=swap" rel="stylesheet">
<!-- Load Styles -->
<link href="css/styles.css" rel="stylesheet">

<body>
  <!-- HTML Follows BEM naming conventions
  IDs are only used for sections to connect menu achors to sections -->
  <header class="page__header">
    <nav class="navbar__menu">
      <!-- Navigation starts as empty UL that will be populated with JS -->
      <ul id="navbar__list"></ul>
    </nav>
  </header>
  <main>
    <header class="main__hero">
      <h1>Landing Page </h1>
    </header>
    <!-- Each Section has an ID (used for the anchor) and
    a data attribute that will populate the li node.
    Adding more sections will automatically populate nav.
    The first section is set to active class by default -->
    <section id="section1" data-nav="Section 1">
      <div class="landing__container">
        <h2>Section 1</h2>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi fermentum metus faucibus lectus pharetra
          dapibus. Suspendisse potenti. Aenean aliquam elementum mi, ac euismod augue. Donec eget lacinia ex. Phasellus
          imperdiet porta orci eget mollis. Sed convallis sollicitudin mauris ac tincidunt. Donec bibendum, nulla eget
          bibendum consectetur, sem nisi aliquam leo, ut pulvinar quam nunc eu augue. Pellentesque maximus imperdiet
          elit a pharetra. Duis lectus mi, aliquam in mi quis, aliquam porttitor lacus. Morbi a tincidunt felis. Sed leo
          nunc, pharetra et elementum non, faucibus vitae elit. Integer nec libero venenatis libero ultricies molestie
          semper in tellus. Sed congue et odio sed euismod.</p>

        <p>Aliquam a convallis justo. Vivamus venenatis, erat eget pulvinar gravida, ipsum lacus aliquet velit, vel
          luctus diam ipsum a diam. Cras eu tincidunt arcu, vitae rhoncus purus. Vestibulum fermentum consectetur
          porttitor. Suspendisse imperdiet porttitor tortor, eget elementum tortor mollis non.</p>
      </div>
    </section>
    <section id="section2" data-nav="Section 2">
      <div class="landing__container">
        <h2>Section 2</h2>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi fermentum metus faucibus lectus pharetra
          dapibus. Suspendisse potenti. Aenean aliquam elementum mi, ac euismod augue. Donec eget lacinia ex. Phasellus
          imperdiet porta orci eget mollis. Sed convallis sollicitudin mauris ac tincidunt. Donec bibendum, nulla eget
          bibendum consectetur, sem nisi aliquam leo, ut pulvinar quam nunc eu augue. Pellentesque maximus imperdiet
          elit a pharetra. Duis lectus mi, aliquam in mi quis, aliquam porttitor lacus. Morbi a tincidunt felis. Sed leo
          nunc, pharetra et elementum non, faucibus vitae elit. Integer nec libero venenatis libero ultricies molestie
          semper in tellus. Sed congue et odio sed euismod.</p>

        <p>Aliquam a convallis justo. Vivamus venenatis, erat eget pulvinar gravida, ipsum lacus aliquet velit, vel
          luctus diam ipsum a diam. Cras eu tincidunt arcu, vitae rhoncus purus. Vestibulum fermentum consectetur
          porttitor. Suspendisse imperdiet porttitor tortor, eget elementum tortor mollis non.</p>
      </div>
    </section>
    </main>
  <footer class="page__footer">
    <p>&copy Udacity</p>
  </footer>
  <script src="js/app.js"></script>
</body>

</html>
</code>```

and the active class and your-active-class

```<code>.active {
padding: 25px;
background-color: black;
color: white;
</code>```

}

```<code>section.your-active-class {
background: rgb(0, 0, 0);
background: linear-gradient(0deg, rgba(211, 39, 39, 0.356) 0%, rgba(223, 10, 10, 0.548) 100%);
</code>```

}

答:
The basic syntax of foreach loops in JS is: forEach((element) => { /* ... */ } ).

Other syntaxes:

```<code>// Arrow function
forEach((element) => { /* ... */ } )
forEach((element, index) => { /* ... */ } )
forEach((element, index, array) => { /* ... */ } )

// Callback function
forEach(callbackFn)
forEach(callbackFn, thisArg)

// Inline callback function
forEach(function(element) { /* ... */ })
forEach(function(element, index) { /* ... */ })
forEach(function(element, index, array){ /* ... */ })
forEach(function(element, index, array) { /* ... */ }, thisArg)
</code>```

The variable s in your code is already the element, but not the index(key). Use directly ${s.id} directly instead.

Also, we don't use querySelector() in that way (getting the whole element by typing in their HTML in).

Your code can be replaced by:

```<code>document.querySelector(`a[href="#${s.id}"]`)
</code>```

For more info on querySelector(), please visit https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector

P.S. Also, I really wonder if there is really a class in your page called your-active-class, cuz it seems like you copied completely from a website :P
If there is not, you can simply remove the s.classList.add('your-active-class');

Body:
I have built the navigation bar in my web page dynamically as shown below

NavBuilder = () => {
//to loop from section 1 to 4 and add sections to navigation
for (s = 0; s < sections.length; s++) {
    const liElem = document.createElement('li');
    //const divElem = document.createElement("div");
    const Id = sections[s].id;
    const DataNav = sections[s].dataset.nav;
    liElem.innerHTML = `<a class="menu__link" href="#${Id}">${DataNav}</a>`;
    Menu.appendChild(liElem);
}
}
NavBuilder();

and when I want to scroll the page I want to add a specific class "your-active-class" to the section which I created in my html page, and also add the class "active" to the liElem so whenever I scroll in the page and stop on a specific section the navbar should highlight the section I stopped on int the navbar it and also highlight the section itself.

the javaScript function I created to add the class active:

window.addEventListener('scroll', () => {
sections.forEach(s => {
    const topDistance = s.getBoundingClientRect().top;
    // if the distance to the top is between 0-150px
    if (topDistance >= 0 && topDistance < 150) {
        s.classList.add('your-active-class');
        document.querySelector(`<a class="menu__link" href="#${sections[s].id}"></a>`).classList.add("active");

        // otherwise, remove the class
    } else {
        s.classList.remove('your-active-class');
        document.querySelector(`<a class="menu__link" href="#${sections[s].id}"></a>`).classList.remove("active");

    }
});

});

I am still caughting this error "Uncaught TypeError: Cannot read property 'id' of undefined" in the line
document.querySelector().classList.add("active");

What is the mistake i am making that prevent me from highlighting my navbar?

the html code:

    <!DOCTYPE>

<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Manipulating the DOM</title>

<link href="https://fonts.googleapis.com/css?family=Fira+Sans:900|Merriweather&display=swap" rel="stylesheet">

<link href="css/styles.css" rel="stylesheet">

Landing Page

Section 1

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi fermentum metus faucibus lectus pharetra
          dapibus. Suspendisse potenti. Aenean aliquam elementum mi, ac euismod augue. Donec eget lacinia ex. Phasellus
          imperdiet porta orci eget mollis. Sed convallis sollicitudin mauris ac tincidunt. Donec bibendum, nulla eget
          bibendum consectetur, sem nisi aliquam leo, ut pulvinar quam nunc eu augue. Pellentesque maximus imperdiet
          elit a pharetra. Duis lectus mi, aliquam in mi quis, aliquam porttitor lacus. Morbi a tincidunt felis. Sed leo
          nunc, pharetra et elementum non, faucibus vitae elit. Integer nec libero venenatis libero ultricies molestie
          semper in tellus. Sed congue et odio sed euismod.

Aliquam a convallis justo. Vivamus venenatis, erat eget pulvinar gravida, ipsum lacus aliquet velit, vel
          luctus diam ipsum a diam. Cras eu tincidunt arcu, vitae rhoncus purus. Vestibulum fermentum consectetur
          porttitor. Suspendisse imperdiet porttitor tortor, eget elementum tortor mollis non.

Section 2

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi fermentum metus faucibus lectus pharetra
          dapibus. Suspendisse potenti. Aenean aliquam elementum mi, ac euismod augue. Donec eget lacinia ex. Phasellus
          imperdiet porta orci eget mollis. Sed convallis sollicitudin mauris ac tincidunt. Donec bibendum, nulla eget
          bibendum consectetur, sem nisi aliquam leo, ut pulvinar quam nunc eu augue. Pellentesque maximus imperdiet
          elit a pharetra. Duis lectus mi, aliquam in mi quis, aliquam porttitor lacus. Morbi a tincidunt felis. Sed leo
          nunc, pharetra et elementum non, faucibus vitae elit. Integer nec libero venenatis libero ultricies molestie
          semper in tellus. Sed congue et odio sed euismod.

Aliquam a convallis justo. Vivamus venenatis, erat eget pulvinar gravida, ipsum lacus aliquet velit, vel
          luctus diam ipsum a diam. Cras eu tincidunt arcu, vitae rhoncus purus. Vestibulum fermentum consectetur
          porttitor. Suspendisse imperdiet porttitor tortor, eget elementum tortor mollis non.

&copy Udacity

and the active class and your-active-class

.active {
padding: 25px;
background-color: black;
color: white;

}

section.your-active-class {
background: rgb(0, 0, 0);
background: linear-gradient(0deg, rgba(211, 39, 39, 0.356) 0%, rgba(223, 10, 10, 0.548) 100%);

}

Body:
The basic syntax of foreach loops in JS is: forEach((element) => { /* ... */ } ).

Other syntaxes:

// Arrow function
forEach((element) => { /* ... */ } )
forEach((element, index) => { /* ... */ } )
forEach((element, index, array) => { /* ... */ } )

// Callback function
forEach(callbackFn)
forEach(callbackFn, thisArg)

// Inline callback function
forEach(function(element) { /* ... */ })
forEach(function(element, index) { /* ... */ })
forEach(function(element, index, array){ /* ... */ })
forEach(function(element, index, array) { /* ... */ }, thisArg)

The variable s in your code is already the element, but not the index(key). Use directly ${s.id} directly instead.

Also, we don't use querySelector() in that way (getting the whole element by typing in their HTML in).

Your code can be replaced by:

document.querySelector(`a[href="#${s.id}"]`)

For more info on querySelector(), please visit https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector

P.S. Also, I really wonder if there is really a class in your page called your-active-class, cuz it seems like you copied completely from a website :P
If there is not, you can simply remove the s.classList.add('your-active-class');


问:
Absolute positioning makes table wider than window
I'm an iPhone Developer who's quite new to web development so please forgive me if I'm making some stupid mistakes.

My problem can be demonstrated on this jsfiddle (with no js). I have a table at the top which is at 100% width. This displays fine. The table at the bottom is of the same class, has 100% width, but because I set position absolute for it's ID (#footerTable), the width is wider than 100%! - Could you please tell me what I'm doing wrong (the CSS/html is in the link - there's not very much of it).

答:
http://jsfiddle.net/xnhMY/

When you absolute positioned the table, it's 100% width was being calculated as so:

width of body element + padding of body element


问:
type 'String' is not a subtype of type 'File' of 'value'
When I'm trying to add a images to listview dynamically to show a multiple images from camera picker.
How can I add the list of images to list view to show an image.

Code for clicking image:

```<code> Future getImage() async {
File images;
File  _images = await ImagePicker.pickImage(source: ImageSource.camera);
  setState(() {

    images =  _images;
    image.add(images.path);

  });
}
</code>```

Then in futurebuilder:

```<code>                child: new ListView.builder(
                  scrollDirection: Axis.horizontal,
                  itemBuilder: (BuildContext context, int index)
                  {

                    print(image[index].toString());
                    return new UserWidgets(imageURL:
                    image[index].toString());

                  },
                  itemCount: image.length,
                ),
              ),
              ),
</code>```

Then my viewcode like this:

```<code>class UserWidgets extends StatelessWidget
 {
 final String imageURL;
  // final String imageType;
  const UserWidgets  ({Key key, this.imageURL}) : super(key: key);

  @override
   Widget build(BuildContext context) {
  //   print(this.imageType);
   VideoPlayerController playerController;
  VoidCallback listener;
     Widget play=new Icon(Icons.play_arrow);
   Widget pause=new Icon(Icons.pause);

   new Container(
  height: 200.0,
  child: new Card(
      child: new Column(
        children: <Widget>[
          new GestureDetector(
            onTap: ()
            {

            },
            child:
            new  Image.file(  File(imageURL)
              ,fit: BoxFit.cover,
              height: 200.0,
              width: 150.0,

            ),

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

How can I solve this?

答:
Use XFile?  with pickImage() to pick image.

final XFile? image= await ImagePicker().pickImage(
  source: ImageSource.camera,
 );
```
<p>And to display the value use</p>
<pre class="lang-dart prettyprint-override"><code> if(image!=null) Image.file(File(image.path)),
</code>```

Body:
When I'm trying to add a images to listview dynamically to show a multiple images from camera picker.
How can I add the list of images to list view to show an image.

Code for clicking image:

 Future getImage() async {
File images;
File  _images = await ImagePicker.pickImage(source: ImageSource.camera);
  setState(() {

    images =  _images;
    image.add(images.path);

  });
}

Then in futurebuilder:

                child: new ListView.builder(
                  scrollDirection: Axis.horizontal,
                  itemBuilder: (BuildContext context, int index)
                  {

                    print(image[index].toString());
                    return new UserWidgets(imageURL:
                    image[index].toString());

                  },
                  itemCount: image.length,
                ),
              ),
              ),

Then my viewcode like this:

class UserWidgets extends StatelessWidget
 {
 final String imageURL;
  // final String imageType;
  const UserWidgets  ({Key key, this.imageURL}) : super(key: key);

  @override
   Widget build(BuildContext context) {
  //   print(this.imageType);
   VideoPlayerController playerController;
  VoidCallback listener;
     Widget play=new Icon(Icons.play_arrow);
   Widget pause=new Icon(Icons.pause);

   new Container(
  height: 200.0,
  child: new Card(
      child: new Column(
        children: <Widget>[
          new GestureDetector(
            onTap: ()
            {

            },
            child:
            new  Image.file(  File(imageURL)
              ,fit: BoxFit.cover,
              height: 200.0,
              width: 150.0,

            ),

          )
        ],
      )
  ),
)
            },

How can I solve this?

Body:
Use XFile?  with pickImage() to pick image.

final XFile? image= await ImagePicker().pickImage(
  source: ImageSource.camera,
 );

And to display the value use

 if(image!=null) Image.file(File(image.path)),


问:
Delay in json data - Node, Express, MongoDB
I'm fairly new to nodejs and I'm doing a full stack developer challenge from devchallenges.io (Shoppingify). Below, I'm trying to add a new item. However, there's a slight delay between the return value from the request and the actual value in the database. The value updates straight away which is great however, the return value in the request is the previous value rather than being the current quantity value in the database.</p>
```<code>// @route    POST api/category
// @desc     Add category and items
// @access   Private
router.post(
  '/',
  [
    check('name', 'Name is required').notEmpty(),
    check('category', 'Category is required').notEmpty(),
  ],
  auth,
  async (req, res) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({
        errors: errors.array(),
      });
    }

    const { name, note, image, category } = req.body;

    const itemObject = { name, note, image, category };

    try {
      const categoryItem = await Category.find({
        user: req.user.id,
      });
      //   check if category object are empty
      if (categoryItem.length === 0) {
        const newCat = new Category({
          user: req.user.id,
          name: category,
          items: itemObject,
        });
        await newCat.save();
        res.json(categoryItem);
      } else if (categoryItem.length !== 0) {
        //   check if category name already exists
        categoryItem.map(async (cat) => {
          if (cat.name.toLowerCase() === category.toLowerCase()) {
            cat.items.push(itemObject);
            await cat.save();
            res.json(categoryItem);
          } else {
            //   create new category
            const newCat = new Category({
              user: req.user.id,
              name: category,
              items: itemObject,
            });
            await newCat.save();
            res.json(categoryItem);
          }
        });
      }
    } catch (error) {
      console.error(error.message);
      res.status(500).send('Server Error');
    }
  }
);
</code>```

答:
You are not returning the correct item…

Return the result of newcat.save()

Or try a new findById if newCat is not the correct object to return

Body:
I'm fairly new to nodejs and I'm doing a full stack developer challenge from devchallenges.io (Shoppingify). Below, I'm trying to add a new item. However, there's a slight delay between the return value from the request and the actual value in the database. The value updates straight away which is great however, the return value in the request is the previous value rather than being the current quantity value in the database.

// @route    POST api/category
// @desc     Add category and items
// @access   Private
router.post(
  '/',
  [
    check('name', 'Name is required').notEmpty(),
    check('category', 'Category is required').notEmpty(),
  ],
  auth,
  async (req, res) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({
        errors: errors.array(),
      });
    }

    const { name, note, image, category } = req.body;

    const itemObject = { name, note, image, category };

    try {
      const categoryItem = await Category.find({
        user: req.user.id,
      });
      //   check if category object are empty
      if (categoryItem.length === 0) {
        const newCat = new Category({
          user: req.user.id,
          name: category,
          items: itemObject,
        });
        await newCat.save();
        res.json(categoryItem);
      } else if (categoryItem.length !== 0) {
        //   check if category name already exists
        categoryItem.map(async (cat) => {
          if (cat.name.toLowerCase() === category.toLowerCase()) {
            cat.items.push(itemObject);
            await cat.save();
            res.json(categoryItem);
          } else {
            //   create new category
            const newCat = new Category({
              user: req.user.id,
              name: category,
              items: itemObject,
            });
            await newCat.save();
            res.json(categoryItem);
          }
        });
      }
    } catch (error) {
      console.error(error.message);
      res.status(500).send('Server Error');
    }
  }
);