问:
JQuery: Why Unobtrusive JavaScript / Document Ready function rather than OnClick event?
I've just started looking at JQuery. I don't have any AJAX in my web application at present.

My existing JavaScript in my HTML looks like:

```<code><form ...>
<p>Find what? <input ...></p>
<div class="ButtonArray">
  <a href="AddRecord.ASP&Action=ADD">ADD</a>
  <a href="#" onClick="return MyFormSubmit();">FIND</a>
</div>
</form>
</code>```

This displays Buttons for [Add] and [Find].  For Find it is necessary to Submit the form, and I use MyFormSubmit() which validates the data, adds a visual effect to the page, and then POSTs the data.

I could add a CLASS or ID to the  for the Find button and in JQuery I could write something like:

```<code>$(function() {
  $(".MySearchButtonClass").click(function() {
    // validate and process form here
  });
});
</code>```

At my "novice" stage of understanding with JQuery I don't get why I would do it this way

My old way identifies the Method near the object. There may be a risk that the JS has not loaded before the user presses the button (is there? The LOAD for the JS is right at the top of the page).

The JQuery Document Ready method won't be activated until the document is loaded (which I assume guarantees that the JS is all present and ready to be run?), but it moves the code to a separate part of my HTML file - so when I see the MyButtonArray DIV in the HTML source it isn't obvious to me which objects have methods, and which do not.

Can you please help me understand what my options are and the benefits / gotchas that I should look out for?

Edit: I'm comfortable that DOM manipulation - such as a LightBox that can appear when any thumbnail with class "LightBoxThumb" is clicked - would use Unobtrusive Javascript.

However I am struggling to persuade myself that a button that has a specific action should have its method applied in that way. (I certainly wouldn't put any code on the button other than a single function call to something "elsewhere", but to my mind that is my best clue as to what that button does, and layers of Unobtrusive Javascript may make that much harder to determine.)

Edit2 - Accepted Answer

I've taken Russ Cams answer. It describes Unobtrusive Javascript in a way that has been helpful to me in understanding more about how & when that should be used.

For the moment (may change when I have more experience!) I'll stick with an OnClick event for a single, non-changing, action on an object as I feel that will be easier for me to debug - and diagnose if problems arise. For ZebraStripes on a table that allows click on heading column to sort (and situations of that type) I can see the benefits of the Unobtrusive Javascript approach

Russ's final comment was particularly helpful, repeated here:

"@Kristen - You're right, like a lot
  of programming topics, there is more
  than one approach and people will
  vehemently stand by their beliefs! If
  we're talking about a single method
  for a single button, I totally
  understand where you're coming from...

If we're talking about lots of
  JavaScript, with same function calls
  for more than one element, different
  function calls for different methods,
  etc. I think that it would be more
  difficult for oneself to mix inline
  and unobtrusive approaches, and it
  would be better to adopt one or the
  other approach"

答:
the document ready event is well before the document load event. document ready occurs once the DOM is loaded which is so that all the elements exist before you start working on them.

So yes the JS will be ready as the document is rendered. The other point about binding is that it is useful for changing bindings to elements when cetain actions occur.

You can still declare the action on the element if you prefer though.

OwnerDisplayName: Kristen

ContentLicense: CC BY-SA 2.5

Body:
I've just started looking at JQuery. I don't have any AJAX in my web application at present.

My existing JavaScript in my HTML looks like:

<form ...>

Find what? <input ...>

  ADD
  FIND

</form>

This displays Buttons for [Add] and [Find].  For Find it is necessary to Submit the form, and I use MyFormSubmit() which validates the data, adds a visual effect to the page, and then POSTs the data.

I could add a CLASS or ID to the  for the Find button and in JQuery I could write something like:

$(function() {
  $(".MySearchButtonClass").click(function() {
    // validate and process form here
  });
});

At my "novice" stage of understanding with JQuery I don't get why I would do it this way

My old way identifies the Method near the object. There may be a risk that the JS has not loaded before the user presses the button (is there? The LOAD for the JS is right at the top of the page).

The JQuery Document Ready method won't be activated until the document is loaded (which I assume guarantees that the JS is all present and ready to be run?), but it moves the code to a separate part of my HTML file - so when I see the MyButtonArray DIV in the HTML source it isn't obvious to me which objects have methods, and which do not.

Can you please help me understand what my options are and the benefits / gotchas that I should look out for?

Edit: I'm comfortable that DOM manipulation - such as a LightBox that can appear when any thumbnail with class "LightBoxThumb" is clicked - would use Unobtrusive Javascript.

However I am struggling to persuade myself that a button that has a specific action should have its method applied in that way. (I certainly wouldn't put any code on the button other than a single function call to something "elsewhere", but to my mind that is my best clue as to what that button does, and layers of Unobtrusive Javascript may make that much harder to determine.)

Edit2 - Accepted Answer

I've taken Russ Cams answer. It describes Unobtrusive Javascript in a way that has been helpful to me in understanding more about how & when that should be used.

For the moment (may change when I have more experience!) I'll stick with an OnClick event for a single, non-changing, action on an object as I feel that will be easier for me to debug - and diagnose if problems arise. For ZebraStripes on a table that allows click on heading column to sort (and situations of that type) I can see the benefits of the Unobtrusive Javascript approach

Russ's final comment was particularly helpful, repeated here:

"@Kristen - You're right, like a lot
  of programming topics, there is more
  than one approach and people will
  vehemently stand by their beliefs! If
  we're talking about a single method
  for a single button, I totally
  understand where you're coming from...

If we're talking about lots of
  JavaScript, with same function calls
  for more than one element, different
  function calls for different methods,
  etc. I think that it would be more
  difficult for oneself to mix inline
  and unobtrusive approaches, and it
  would be better to adopt one or the
  other approach"

LastEditorDisplayName: Kristen


来源: stackexchange

问:
Decode Nested JSON REST Api Response in to Array of Structs
I am trying to parse the response of  https://swapi.dev/api/people/ in to a List but I can't seem to get it work due to the nested response structure instead of a flat response.

This is my ContentView:

```<code>struct ContentView: View {

    private let charactersURL = URL(string: "https://swapi.dev/api/people/")!

    @State private var characters: [Character] = []

    var body: some View {

        NavigationView {

            VStack {

                List {
                    ForEach(characters, id: \.self) { character in
                        NavigationLink(destination: CharacterView(character: character)) {
                            Text(character.name)
                        }
                    }
                }
                .onAppear(perform: loadCharacter)
            }
            .navigationBarTitle("Swapi Api Client")

        }

    }

    private func loadCharacter() {

        let request = URLRequest(url: charactersURL)
        URLSession.shared.dataTask(with: request) { data, response, error in
            if let data = data {
                if let charactersResponse = try? JSONDecoder().decode([Character].self, from: data.results) {
                    withAnimation {
                        self.characters = charactersResponse.results
                    }
                }
            }

        }.resume()
    }

}
</code>```

I have a CharactersResponse struct:

```<code>struct CharactersResponse {
    let count: Int
    let next: String
    let previous: NSNull
    let results: [Character]
}
</code>```

and a Character struct:

```<code>struct Character: Decodable, Hashable {
    let name: String
    let height: Int
    let mass: String
    let hairColor: String
    let skinColor: String
    let eyeColor: String
    let birthYear: String
    let gender: String
    let homeworld: String
    let films: [String]
    let species: [String]
    let vehicles : [String]
    let starships: [String]
    let created: String
    let edited: String
    let url: String
}
</code>```

The error I get is Value of type 'Data' has no member 'results' but I'm not sure how to fix it so that the CharactersResponse results are parsed in to an array of Character structs.

答:
You are mixing up the raw data and the deserialized structs

Replace

```<code>if let charactersResponse = try? JSONDecoder().decode([Character].self, from: data.results) { ...
</code>```

with

```<code>if let charactersResponse = try? JSONDecoder().decode(CharactersResponse.self, from: data) { ...
</code>```

And adopt Decodable in CharactersResponse

```<code>struct CharactersResponse : Decodable { ...
</code>```

You might also replace NSNull with an optional of the expected type

Never try? in a JSONDecoder context. catch a potential error and print it.

```<code>do {
    let charactersResponse = try JSONDecoder().decode(CharactersResponse.self, from: data) { ...

} catch { print(error) }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to parse the response of  https://swapi.dev/api/people/ in to a List but I can't seem to get it work due to the nested response structure instead of a flat response.

This is my ContentView:

struct ContentView: View {

    private let charactersURL = URL(string: "https://swapi.dev/api/people/")!

    @State private var characters: [Character] = []

    var body: some View {

        NavigationView {

            VStack {

                List {
                    ForEach(characters, id: \.self) { character in
                        NavigationLink(destination: CharacterView(character: character)) {
                            Text(character.name)
                        }
                    }
                }
                .onAppear(perform: loadCharacter)
            }
            .navigationBarTitle("Swapi Api Client")

        }

    }

    private func loadCharacter() {

        let request = URLRequest(url: charactersURL)
        URLSession.shared.dataTask(with: request) { data, response, error in
            if let data = data {
                if let charactersResponse = try? JSONDecoder().decode([Character].self, from: data.results) {
                    withAnimation {
                        self.characters = charactersResponse.results
                    }
                }
            }

        }.resume()
    }

}

I have a CharactersResponse struct:

struct CharactersResponse {
    let count: Int
    let next: String
    let previous: NSNull
    let results: [Character]
}

and a Character struct:

struct Character: Decodable, Hashable {
    let name: String
    let height: Int
    let mass: String
    let hairColor: String
    let skinColor: String
    let eyeColor: String
    let birthYear: String
    let gender: String
    let homeworld: String
    let films: [String]
    let species: [String]
    let vehicles : [String]
    let starships: [String]
    let created: String
    let edited: String
    let url: String
}

The error I get is Value of type 'Data' has no member 'results' but I'm not sure how to fix it so that the CharactersResponse results are parsed in to an array of Character structs.

Body:
You are mixing up the raw data and the deserialized structs

Replace

if let charactersResponse = try? JSONDecoder().decode([Character].self, from: data.results) { ...

with

if let charactersResponse = try? JSONDecoder().decode(CharactersResponse.self, from: data) { ...

And adopt Decodable in CharactersResponse

struct CharactersResponse : Decodable { ...

You might also replace NSNull with an optional of the expected type

Never try? in a JSONDecoder context. catch a potential error and print it.

do {
    let charactersResponse = try JSONDecoder().decode(CharactersResponse.self, from: data) { ...

} catch { print(error) }


问:
Set height to container in Gridview.builder
I am working with the following code and got struck. I wanted to set the height to the container so that the images which are displayed inside it will be fitted well. In the present condition the image gets fitted inside the container and it does not look good. I have used a grid view to display images from firebase.

```<code>class Catview extends StatefulWidget {
  @override
  _CatviewState createState() => _CatviewState();
}

class _CatviewState extends State<Catview> {
  StreamSubscription<QuerySnapshot> subscription;
  List<DocumentSnapshot> wallpaperList;
  final CollectionReference collectionReference =
      Firestore.instance.collection("pubg");

  @override
  void initState() {
    super.initState();
    subscription = collectionReference.snapshots().listen((datasnapshot) {
      setState(() {
        wallpaperList = datasnapshot.documents;
      });
    });
  }

  @override
  void dispose() {
    super.dispose();
    subscription?.cancel();
  }

  @override
  Widget build(BuildContext context) {
    return (SafeArea(
      child: Scaffold(
        body: wallpaperList != null
            ? GridView.builder(
                gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: 2,
                  crossAxisSpacing: 2,
                  mainAxisSpacing: 4,
                ),
                itemCount: wallpaperList.length,
                itemBuilder: (context, index) {
                  String image = wallpaperList[index].data['image'];
                  return Container(
                    color: Colors.red,
                    child: Image.network(
                      image,
                    ),
                  );
                },
              )
            : Center(
                child: CircularProgressIndicator(),
              ),
      ),
    ));
  }
}
</code>```

thank you!

答:
You'll have to use the childAspectRatio property present in the GridView.builder class

```<code>GridView.builder(
                gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: 2,
                  crossAxisSpacing: 8.0,
                  mainAxisSpacing: 8.0,
                  childAspectRatio: 2/3,
                ),
....
</code>```

I like to use the popular aspect ratios present in photography which are the 2/3 (2:3) or the 3/4 (3:4) to get the kind of look I normally like.

If you want a wider width in relation to the height, use the aspect ratio in reverse (i.e. 3/2 or 4/3) depending on your need.

Hope it helps! :)

Body:
I am working with the following code and got struck. I wanted to set the height to the container so that the images which are displayed inside it will be fitted well. In the present condition the image gets fitted inside the container and it does not look good. I have used a grid view to display images from firebase.

class Catview extends StatefulWidget {
  @override
  _CatviewState createState() => _CatviewState();
}

class _CatviewState extends State<Catview> {
  StreamSubscription<QuerySnapshot> subscription;
  List<DocumentSnapshot> wallpaperList;
  final CollectionReference collectionReference =
      Firestore.instance.collection("pubg");

  @override
  void initState() {
    super.initState();
    subscription = collectionReference.snapshots().listen((datasnapshot) {
      setState(() {
        wallpaperList = datasnapshot.documents;
      });
    });
  }

  @override
  void dispose() {
    super.dispose();
    subscription?.cancel();
  }

  @override
  Widget build(BuildContext context) {
    return (SafeArea(
      child: Scaffold(
        body: wallpaperList != null
            ? GridView.builder(
                gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: 2,
                  crossAxisSpacing: 2,
                  mainAxisSpacing: 4,
                ),
                itemCount: wallpaperList.length,
                itemBuilder: (context, index) {
                  String image = wallpaperList[index].data['image'];
                  return Container(
                    color: Colors.red,
                    child: Image.network(
                      image,
                    ),
                  );
                },
              )
            : Center(
                child: CircularProgressIndicator(),
              ),
      ),
    ));
  }
}

thank you!

Body:
You'll have to use the childAspectRatio property present in the GridView.builder class

GridView.builder(
                gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: 2,
                  crossAxisSpacing: 8.0,
                  mainAxisSpacing: 8.0,
                  childAspectRatio: 2/3,
                ),
....

I like to use the popular aspect ratios present in photography which are the 2/3 (2:3) or the 3/4 (3:4) to get the kind of look I normally like.

If you want a wider width in relation to the height, use the aspect ratio in reverse (i.e. 3/2 or 4/3) depending on your need.

Hope it helps! :)


问:
CSS back slash and forward slash in 'calling' out photos from directories
This cursor css code that uses back slash for directory generates net::ERR_FILE_NOT_FOUND

```<code>cursor: url("C:\Users\Ken\projects\JavascriptGames\images\bird.png"), auto;
</code>```

This cursor css code that uses forward slash for directory successfully customizes the cursor

```<code>cursor: url("C:/Users/Ken/projects/JavascriptGames/images/bird.png"), auto;
</code>```

Why is it like that?

答: Because URL syntax is not the same as Windows filepath syntax. The path separator in URLs is / (as is the directory seperator character in UNIX and UNIX-like filesystems).

Body:
This cursor css code that uses back slash for directory generates net::ERR_FILE_NOT_FOUND

cursor: url("C:\Users\Ken\projects\JavascriptGames\images\bird.png"), auto;

This cursor css code that uses forward slash for directory successfully customizes the cursor

cursor: url("C:/Users/Ken/projects/JavascriptGames/images/bird.png"), auto;

Why is it like that?


问:
Use array to define indices for multidimensional numpy array
I have a multidimensional Numpy array; let's say it's

```<code> myArray = array([[[ 0,  1,  2],
                   [ 3,  4,  5],
                   [ 6,  7,  8]],

                  [[ 9, 10, 11],
                   [12, 13, 14],
                   [15, 16, 17]],

                  [[18, 19, 20],
                   [21, 22, 23],
                   [24, 25, 26]]])
</code>```

I know that running myArray[1,1,1], for instance, will return 13. However, I want to define indx = [1,1,1] then call something to the effect ofmyArray[indx].
However, this does some other multidimensional indexing stuff.

I have also tried myArray[*indx] but that understandably throws a syntax error.

Currently my very ugly workaround is to define

```<code>def array_as_indices(array, matrix):
    st = ''
    for i in array:
        st += '%s,' % i
    st = st[:-1]

    return matrix[eval(st)]
</code>```

which works but is quite inelegant and presumably slow.

Is there a more pythonic way to do what I'm looking for?

答:
The indices of a numpy array are addressed by tuples, not lists. Use indx = (1, 1, 1).

As an extension, if you want to call the indices (1, 1, 1) and (2, 2, 2), you can use

```<code>>>> indx = ([1, 2], [1, 2], [1, 2])
>>> x[indx]
array([13, 26])
</code>```

The rationale behind the behavior with lists is that numpy treats lists sequentially, so

```<code>>>> indx = [1, 1, 1]
>>> x[indx]
array([[[ 9, 10, 11],
        [12, 13, 14],
        [15, 16, 17]],
       [[ 9, 10, 11],
        [12, 13, 14],
        [15, 16, 17]],
       [[ 9, 10, 11],
        [12, 13, 14],
        [15, 16, 17]]])
</code>```

It returns a list of three elements, each equal to x[1].

Body:
I have a multidimensional Numpy array; let's say it's

 myArray = array([[[ 0,  1,  2],
                   [ 3,  4,  5],
                   [ 6,  7,  8]],

                  [[ 9, 10, 11],
                   [12, 13, 14],
                   [15, 16, 17]],

                  [[18, 19, 20],
                   [21, 22, 23],
                   [24, 25, 26]]])

I know that running myArray[1,1,1], for instance, will return 13. However, I want to define indx = [1,1,1] then call something to the effect ofmyArray[indx].
However, this does some other multidimensional indexing stuff.

I have also tried myArray[*indx] but that understandably throws a syntax error.

Currently my very ugly workaround is to define

def array_as_indices(array, matrix):
    st = ''
    for i in array:
        st += '%s,' % i
    st = st[:-1]

    return matrix[eval(st)]

which works but is quite inelegant and presumably slow.

Is there a more pythonic way to do what I'm looking for?

Body:
The indices of a numpy array are addressed by tuples, not lists. Use indx = (1, 1, 1).

As an extension, if you want to call the indices (1, 1, 1) and (2, 2, 2), you can use

>>> indx = ([1, 2], [1, 2], [1, 2])
>>> x[indx]
array([13, 26])

The rationale behind the behavior with lists is that numpy treats lists sequentially, so

>>> indx = [1, 1, 1]
>>> x[indx]
array([[[ 9, 10, 11],
        [12, 13, 14],
        [15, 16, 17]],
       [[ 9, 10, 11],
        [12, 13, 14],
        [15, 16, 17]],
       [[ 9, 10, 11],
        [12, 13, 14],
        [15, 16, 17]]])

It returns a list of three elements, each equal to x[1].


问:
Is there a default C++ comparator for user defined structure?
```<code>#include<bits/stdc++.h>
using namespace std;
struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
int main() {
    map<TreeNode*,int> mp;
    TreeNode* x=new TreeNode(4);
    TreeNode* y=new TreeNode(5);
    TreeNode* z=new TreeNode(6);
    mp[x]=1;
    mp[y]=2;
    mp[z]=3;

    cout<<mp[x]<<endl;

    return 0;
}
</code>```

The above code compiles and gives the desired outut but why don't we need to define a custom comparator to create the map mp; Does C++ does it itself? Same with unordered_map the code works fine.

答:
You have a map of TreeNode*, not TreeNode.  A TreeNode* is just a pointer and like all other non-class member pointers, the default comparator for std::map, std::less,  will handle them in a implementation defined manner.

If you had a map<TreeNode,int> mp;, then it would fail to compile as there is no operator < defined for TreeNode.

Body:
#include<bits/stdc++.h>
using namespace std;
struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
int main() {
    map<TreeNode*,int> mp;
    TreeNode* x=new TreeNode(4);
    TreeNode* y=new TreeNode(5);
    TreeNode* z=new TreeNode(6);
    mp[x]=1;
    mp[y]=2;
    mp[z]=3;

    cout<<mp[x]<<endl;

    return 0;
}

The above code compiles and gives the desired outut but why don't we need to define a custom comparator to create the map mp; Does C++ does it itself? Same with unordered_map the code works fine.


问:
Install gdal using conda?
I used

conda install gdal
```

<p>to install the GDAL packages. But I had the following error when importing the packages.</p>

```>>> from osgeo import gdal
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/danqing0703/anaconda/lib/python2.7/site-packages/osgeo/__init__.py", line 21, in <module>
    _gdal = swig_import_helper()
  File "/Users/danqing0703/anaconda/lib/python2.7/site-packages/osgeo/__init__.py", line 17, in swig_import_helper
    _mod = imp.load_module('_gdal', fp, pathname, description)
ImportError: dlopen(/Users/danqing0703/anaconda/lib/python2.7/site-packages/osgeo/_gdal.so, 2): Library not loaded: libgdal.20.dylib
  Referenced from: /Users/danqing0703/anaconda/lib/python2.7/site-packages/osgeo/_gdal.so
  Reason: image not found
>>> from osgeo import ogr
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/danqing0703/anaconda/lib/python2.7/site-packages/osgeo/__init__.py", line 21, in <module>
    _gdal = swig_import_helper()
  File "/Users/danqing0703/anaconda/lib/python2.7/site-packages/osgeo/__init__.py", line 17, in swig_import_helper
    _mod = imp.load_module('_gdal', fp, pathname, description)
ImportError: dlopen(/Users/danqing0703/anaconda/lib/python2.7/site-packages/osgeo/_gdal.so, 2): Library not loaded: libgdal.20.dylib
  Referenced from: /Users/danqing0703/anaconda/lib/python2.7/site-packages/osgeo/_gdal.so
  Reason: image not found
```

What should I do to have GDAL imported in Python?

答:
I just made the mistake of executing the previously proposed command in the base environment of Conda:

```<code>conda install -c conda-forge gdal
</code>```

This took ages to "solve environment" and, in the end, found numerous conflicts which halted the installation.

Given that, I instead created a separate environment with:

```<code>conda create -n gdal python=3.8
</code>```

And activated it with:

```<code>conda activate gdal
</code>```

And then executed the first command (as well as all others listed in the documentation). This worked fast and without any errors.

ContentLicense: CC BY-SA 3.0

Title: Install gdal using conda?

Body:
I used

conda install gdal

to install the GDAL packages. But I had the following error when importing the packages.

>>> from osgeo import gdal
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/danqing0703/anaconda/lib/python2.7/site-packages/osgeo/__init__.py", line 21, in <module>
    _gdal = swig_import_helper()
  File "/Users/danqing0703/anaconda/lib/python2.7/site-packages/osgeo/__init__.py", line 17, in swig_import_helper
    _mod = imp.load_module('_gdal', fp, pathname, description)
ImportError: dlopen(/Users/danqing0703/anaconda/lib/python2.7/site-packages/osgeo/_gdal.so, 2): Library not loaded: libgdal.20.dylib
  Referenced from: /Users/danqing0703/anaconda/lib/python2.7/site-packages/osgeo/_gdal.so
  Reason: image not found
>>> from osgeo import ogr
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/danqing0703/anaconda/lib/python2.7/site-packages/osgeo/__init__.py", line 21, in <module>
    _gdal = swig_import_helper()
  File "/Users/danqing0703/anaconda/lib/python2.7/site-packages/osgeo/__init__.py", line 17, in swig_import_helper
    _mod = imp.load_module('_gdal', fp, pathname, description)
ImportError: dlopen(/Users/danqing0703/anaconda/lib/python2.7/site-packages/osgeo/_gdal.so, 2): Library not loaded: libgdal.20.dylib
  Referenced from: /Users/danqing0703/anaconda/lib/python2.7/site-packages/osgeo/_gdal.so
  Reason: image not found

What should I do to have GDAL imported in Python?

Body:
I just made the mistake of executing the previously proposed command in the base environment of Conda:

conda install -c conda-forge gdal

This took ages to "solve environment" and, in the end, found numerous conflicts which halted the installation.

Given that, I instead created a separate environment with:

conda create -n gdal python=3.8

And activated it with:

conda activate gdal

And then executed the first command (as well as all others listed in the documentation). This worked fast and without any errors.


问:
In React functional Component , test internal functional using jest and enzyme
I am using functional Component in React , I need to write unit test case for a method in functional component.

import React from 'react';
function print(){
  console.log('hello');
}

function Welcome(props){
  return
{props.name}
;
}

export default Welcome;

```
<p>In jest and enzyme :</p>
<pre class="lang-js prettyprint-override"><code>test (method print , ()=> {
  const container =  shallow(<Welcome />).instance().print()
}
</code>```

instance : TypeError Cannot read property of null

I have read functional component don't have an instance in React 16+ . Would someone help in suggesting a way to write unit test cases for methods in functional component.

答:
print function is defined in module scope. As with any other scoped values, it cannot be accessed outside the scope.

In order to be accessible, it should be exported:

```<code>export function print(){  console.log('hello');  }
</code>```

It cannot be mocked when being declared in the same module it's used. print is not a method and functional components don't have instances that could have methods. It cannot be accessed as instance().print, unless it was exposed with useImperativeHandle.

Body:
I am using functional Component in React , I need to write unit test case for a method in functional component.

import React from 'react';
function print(){
  console.log('hello');
}

function Welcome(props){
  return
{props.name}
;
}

export default Welcome;

In jest and enzyme :

test (method print , ()=> {
  const container =  shallow(<Welcome />).instance().print()
}

instance : TypeError Cannot read property of null

I have read functional component don't have an instance in React 16+ . Would someone help in suggesting a way to write unit test cases for methods in functional component.

Body:
print function is defined in module scope. As with any other scoped values, it cannot be accessed outside the scope.

In order to be accessible, it should be exported:

export function print(){  console.log('hello');  }

It cannot be mocked when being declared in the same module it's used. print is not a method and functional components don't have instances that could have methods. It cannot be accessed as instance().print, unless it was exposed with useImperativeHandle.


问:
getBoundingClientRect is not a function on vueJs
I would like to find the top and bottom edge of a div when i move my cursor over it. The div is generated dynamically. However, it produced error message

getBoundingClientRect is not a function

<template>

                This is div {{ index }}

</template>

```

答:
You can handle this problem by accessing the target element in the event:

```

Body:
You can handle this problem by accessing the target element in the event:

<script>
export default{
  methods: {
    divDragOver(e){
      var divTop = e.target.getBoundingClientRect();
      console.log(divTop);
    }
  }
}
</script>


问:
How to prevent direct access to private members outside of getters/setters in the same class?

Challenge

Given a class with a non-trivial getter and some other internal method accessing the same private member field:

Valid Example

class TestType {
    private String value;

    public String getValue() {
        return this.value == null || this.value.isEmpty() ? "default" : this.value;
    }

    public void setValue(String newValue) {
        this.value = newValue;
    }

    public int getValueLength() {
        return this.getValue().length();
    }
}
```

<p>I want to forbid the by-passing of the getter in the <code>getValueLength()</code> method.
The following implementation of <code>getValueLength()</code> should produce some kind of error (unit test failure, checkstyle error, or whatever else can be automated in a generic way):</p>

<h3>Invalid Method</h3>

<pre class="lang-java prettyprint-override"><code>    public int getValueLength() {
        // ERROR: possible NullPointerException
        return this.value.length();
    }
</code>```

Background

In my real-life code there is some lazy-loading going on inside the getter that only loads the actual value when it is being accessed for the first time. Calling getValueLength() first may result in a NullPointerException directly or perform wrong actions based on the missing value.

The motivation is to ensure that future developers don't forget to only use the getter method and never access the member directly. Since this is an isolated issue (i.e. only where this kind of lazy-loaded is being specifically added) it is acceptable if some extra annotations are required, e.g. on the member itself that it should only be accessed in selected methods and those methods to be marked as well -- or specific checkstyle comments enabling/disabling specific rules.

答:
There is no way to enforce this in code.

However, since you mention in a comment, “Hopefully there is some way to achieve it via some tool,” and the question is tagged with checkstyle, I believe you can create a custom rule:

<module name="Regexp">
    <property name="id" value="valueField"/>
    <property name="format" value="\bvalue\b"/>
    <property name="illegalPattern" value="true"/>
    <property name="ignoreComments" value="true"/>
    <property name="message" value="Do not use 'value' field directly;  use getValue() instead."/>
</module>
```

<p>You would then want to suppress that check for your own “valid” lines:</p>

<pre class="lang-xml prettyprint-override"><code><module name="SuppressWithNearbyCommentFilter">
    <property name="idFormat" value="valueField"/>
</module>
</code>```

And in the code:

```<code>private String value;   // SUPPRESS CHECKSTYLE

public String getValue() {
    return this.value == null || this.value.isEmpty() ? "default" : this.value; // SUPPRESS CHECKSTYLE
}

public void setValue(String newValue) {
    this.value = newValue;  // SUPPRESS CHECKSTYLE
}
</code>```

(There are other ways to suppress Checkstyle’s checks with comments, which you may find more visually pleasing.  See the filters documentation.)

When actually running Checkstyle, you probably want to restrict it to that one source file.  For instance, if using Ant, you might do:

<taskdef resource="com/puppycrawl/tools/checkstyle/ant/checkstyle-ant-task.properties"
     classpath="tools/checkstyle-8.33-all.jar"/>

<checkstyle config="checkstyle.xml">
    <fileset dir="src/main/java" includes="**/TestType.java"/>
</checkstyle>
```

Body:
Challenge

Given a class with a non-trivial getter and some other internal method accessing the same private member field:

Valid Example

class TestType {
    private String value;

    public String getValue() {
        return this.value == null || this.value.isEmpty() ? "default" : this.value;
    }

    public void setValue(String newValue) {
        this.value = newValue;
    }

    public int getValueLength() {
        return this.getValue().length();
    }
}

I want to forbid the by-passing of the getter in the getValueLength() method.
The following implementation of getValueLength() should produce some kind of error (unit test failure, checkstyle error, or whatever else can be automated in a generic way):

Invalid Method

    public int getValueLength() {
        // ERROR: possible NullPointerException
        return this.value.length();
    }

Background

In my real-life code there is some lazy-loading going on inside the getter that only loads the actual value when it is being accessed for the first time. Calling getValueLength() first may result in a NullPointerException directly or perform wrong actions based on the missing value.

The motivation is to ensure that future developers don't forget to only use the getter method and never access the member directly. Since this is an isolated issue (i.e. only where this kind of lazy-loaded is being specifically added) it is acceptable if some extra annotations are required, e.g. on the member itself that it should only be accessed in selected methods and those methods to be marked as well -- or specific checkstyle comments enabling/disabling specific rules.

Body:
There is no way to enforce this in code.

However, since you mention in a comment, “Hopefully there is some way to achieve it via some tool,” and the question is tagged with checkstyle, I believe you can create a custom rule:

<module name="Regexp">
    <property name="id" value="valueField"/>
    <property name="format" value="\bvalue\b"/>
    <property name="illegalPattern" value="true"/>
    <property name="ignoreComments" value="true"/>
    <property name="message" value="Do not use 'value' field directly;  use getValue() instead."/>
</module>

You would then want to suppress that check for your own “valid” lines:

<module name="SuppressWithNearbyCommentFilter">
    <property name="idFormat" value="valueField"/>
</module>

And in the code:

private String value;   // SUPPRESS CHECKSTYLE

public String getValue() {
    return this.value == null || this.value.isEmpty() ? "default" : this.value; // SUPPRESS CHECKSTYLE
}

public void setValue(String newValue) {
    this.value = newValue;  // SUPPRESS CHECKSTYLE
}

(There are other ways to suppress Checkstyle’s checks with comments, which you may find more visually pleasing.  See the filters documentation.)

When actually running Checkstyle, you probably want to restrict it to that one source file.  For instance, if using Ant, you might do:

<taskdef resource="com/puppycrawl/tools/checkstyle/ant/checkstyle-ant-task.properties"
     classpath="tools/checkstyle-8.33-all.jar"/>

<checkstyle config="checkstyle.xml">
    <fileset dir="src/main/java" includes="**/TestType.java"/>
</checkstyle>


问:
does a inout port work as both in and out in same appplication
I am trying to write a vhdl code including inout port and have this doubt that wheather a inout port act as both input and output in same program.Like i know reason to use inout pin is so that it works both ways,but my doubt is if you consider practical example like in microcontroller i see the pin act as input for one program or application and as output in another.Can the pin work ask both in and out in same program ?is that possible?(like in 1 clock cycle its in and in other another its out)
practically it seems like it cant happen.But can someone help with an answer</p>

答:
Since you have tagged your question with "avr", the answer in "Not at the same time."

You already think:

like in 1 clock cycle its in and in other another its out

If the program in the AVR changes the direction of the pin while running, it is possible that one time the pin is an output while another time it is an input.

For some completeness:

In example the 8051 family of microcontrollers actually use their pins in both directions at the same time, from a physical view. The pins don't have a direction control. Instead their "high" level is kind of weak like a pull-up resistor. You can drive it "low" if you want. To accelerate the rising edge, on a change from low to high the microcontroller activates a not-so-weak transistor for 2 clock cycles.


问:
How to see who created the record?
How to see who created the record?

For example,

```<code>"Contact" model=res.partner
</code>```

In Odoo I can't find where such data is stored

答:
There are various places to look:

1) If you have database access, you can look at: create_uid and create_date.

```<code>SELECT id,create_uid,create_date FROM table_name;
</code>```

2) If you go into debug mode, i.e. https://yourdatabase.odoo.com/web?debug=true then in the debug menu you choose "View Metadata"

3) Like @CZoellner suggested, the chatter will show this if it is enabled on the model and view. The image below shows OdooBot created 7 days ago for example.

Title: How to see who created the record?

Body:
How to see who created the record?

For example,

"Contact" model=res.partner

In Odoo I can't find where such data is stored

Body:
There are various places to look:

1) If you have database access, you can look at: create_uid and create_date.

SELECT id,create_uid,create_date FROM table_name;

2) If you go into debug mode, i.e. https://yourdatabase.odoo.com/web?debug=true then in the debug menu you choose "View Metadata"

3) Like @CZoellner suggested, the chatter will show this if it is enabled on the model and view. The image below shows OdooBot created 7 days ago for example.


答:
Try something like that:

<template>

        This is div {{ index }}

</template>

```

Your code doesn't work, because the this.refs return an Array.

Title: getBoundingClientRect is not a function on vueJs

Body:
I would like to find the top and bottom edge of a div when i move my cursor over it. The div is generated dynamically. However, it produced error message

getBoundingClientRect is not a function

<template>

                This is div {{ index }}

</template>

Body:
Try something like that:

<template>
  <div>
    <div v-for="index in divs" :key="index">
      <div :ref="'ref_' + index" @mouseover="divDragOver($event, index)">
        This is div {{ index }}
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'App',
  data: () => ({
    divs: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
  }),
  methods: {
    divDragOver(e, i) {
      let [div] = this.$refs['ref_' + i];
      let top = div.getBoundingClientRect().top;
      console.log(top);
    },
  },
};
</script>

Your code doesn't work, because the this.refs return an Array.


问:
Protobuf-net bug - serializing fixed array that is set to null
I'm using protobuf-net library to serialize some objects. I have a field

```<code>[ProtoMember(3, DataFormat = DataFormat.FixedSize, IsPacked = true)]
ushort[] foo;
</code>```

When I set it to say ushort[] { 3 } and then serialize the whole object and read it back it's fine. Then when I set foo to either an empty array or null and serialize and read it back again, it's not erased. I end up getting the array with 3 in it. To make sure it's not some file system problem I changed other properties and did the roundtrip and they all behaved as expected.

Does anyone know if this is a bug in the implementation or a feature?

答:
It isn't entirely clear without a reproducible example, but IMO the most likely answer here is that you are overwriting an output stream (such as a file) without truncating it. Because the protobuf spec does not include terminators (etc) for the root object, it reads to the end of the file. If you then overwrite with less data, any contents not truncated are garbage.

Now, if the change means the garbage at the end doesn't parse as protobuf, you'll get an exception, like this. However, if the data is still valid (because, for example foo is the last item in the stream) then it'll just read it and process it. In particular, setting a collection results in that item not being written, hence why setting it to null still leaves a valid stream (if it is the final field to be serialized).

If you aren't already doing so, ensure you trim your outputs (2 simple ways of doing this are shown in the post linked above).

If this is unrelated, then I apologise - but without further information / a reproducible example I have to use a little guesswork ;p

Body:
I'm using protobuf-net library to serialize some objects. I have a field

[ProtoMember(3, DataFormat = DataFormat.FixedSize, IsPacked = true)]
ushort[] foo;

When I set it to say ushort[] { 3 } and then serialize the whole object and read it back it's fine. Then when I set foo to either an empty array or null and serialize and read it back again, it's not erased. I end up getting the array with 3 in it. To make sure it's not some file system problem I changed other properties and did the roundtrip and they all behaved as expected.

Does anyone know if this is a bug in the implementation or a feature?


问:
Using eval() to execute string of PHP that contains SimpleHTML
I'm trying to use eval() to execute a string of SimpleHTML. I'm fully aware of the dangers of eval() and will not be using any user input for the string that is to be executed.

```<code>$my_data = str_get_html('<html><body><a href=\"https://www.example.com\">Hello!</a></body></html>');

$str = '$my_data->find(\'a\', 0)->attr[\'href\']';

eval ("\$str = \"$str\";");

echo $str;
</code>```

The above code doesn't execute, and after echoing $str, I get:

```<code>('a', 0)->attr['href']
</code>```

What happened to the first part of the $str string (i.e. $my_data->find )? How can I actually execute the code from the $str string?

答:
The code you are passing to the eval is wrong. You are trying to eval the following code:

```<code>$str = "$my_data->find('a', 0)->attr['href']";
</code>```

The correct code would be:

```<code>$str = $my_data->find('a', 0)->attr['href'];
</code>```

Or:

```<code>$str = "{$my_data->find('a', 0)->attr['href']}";
</code>```

This code works:

```<code><?php

require __DIR__ . '/simplehtmldom_1_9_1/simple_html_dom.php';

$my_data = str_get_html('<html><body><a href=\"https://www.example.com\">Hello!</a></body></html>');

$str = '$my_data->find(\'a\', 0)->attr[\'href\']';

eval ("\$str = $str;");

echo $str;
</code>```

Body:
I'm trying to use eval() to execute a string of SimpleHTML. I'm fully aware of the dangers of eval() and will not be using any user input for the string that is to be executed.

$my_data = str_get_html('Hello!');

$str = '$my_data->find(\'a\', 0)->attr[\'href\']';

eval ("\$str = \"$str\";");

echo $str;

The above code doesn't execute, and after echoing $str, I get:

('a', 0)->attr['href']

What happened to the first part of the $str string (i.e. $my_data->find )? How can I actually execute the code from the $str string?

Body:
The code you are passing to the eval is wrong. You are trying to eval the following code:

$str = "$my_data->find('a', 0)->attr['href']";

The correct code would be:

$str = $my_data->find('a', 0)->attr['href'];

Or:

$str = "{$my_data->find('a', 0)->attr['href']}";

This code works:

<?php

require __DIR__ . '/simplehtmldom_1_9_1/simple_html_dom.php';

$my_data = str_get_html('<html><body><a href=\"https://www.example.com\">Hello!</a></body></html>');

$str = '$my_data->find(\'a\', 0)->attr[\'href\']';

eval ("\$str = $str;");

echo $str;


问:
Retrieving NotesDocumentCollection during QueryPaste
Is this possible in Notes? I am currently using version 11.
I have a form with an embedded view in it. This view has code in the QueryPaste function.
For example it has the code:

```<code>Sub Querypaste(Source As Notesuiview, Continue As Variant)
    Dim ndcRegel As NotesDocumentCollection
    Dim docRegel As NotesDocument

    Set ndcRegel = source.Documents
    Msgbox "1"
    Msgbox source.Documents.Count
    etc...
</code>```

When copy and pasting a document in the embedded view, it triggers Msgbox 1 first and then for the count I get the result 0. While there are documents in the embedded view.

When I am copy pasting in the view itself then it correctly works and does find a ndc collection..

Why is this so? And can this be fixed? Because I want to block my users to copy paste documents in an embedded view.

答:
@Teleman's comment was going to be my reaction, but QueryPaste is only defined for the view, not for the form or for the embedded view. At least that's true in R9, anyhow.

In any case, the source parameter for QueryPaste is a NotesUIView object, and the Documents property is defined as the collection containing the selected documents, and I suspect that during a paste operation there are, effectively, no selected documents. In fact, the documentation says this:

In the QueryPaste event, Documents does not contain a list of the
  documents being pasted. You can use the Documents property in the
  Postpaste event to access thelist after the documents are pasted, or
  you can create an agent to process pasted documents.

Body:
Is this possible in Notes? I am currently using version 11.
I have a form with an embedded view in it. This view has code in the QueryPaste function.
For example it has the code:

Sub Querypaste(Source As Notesuiview, Continue As Variant)
    Dim ndcRegel As NotesDocumentCollection
    Dim docRegel As NotesDocument

    Set ndcRegel = source.Documents
    Msgbox "1"
    Msgbox source.Documents.Count
    etc...

When copy and pasting a document in the embedded view, it triggers Msgbox 1 first and then for the count I get the result 0. While there are documents in the embedded view.

When I am copy pasting in the view itself then it correctly works and does find a ndc collection..

Why is this so? And can this be fixed? Because I want to block my users to copy paste documents in an embedded view.


问:
creating an envelope icon and its link on html code
I successfully added my LinkedIn, Github accounts to my webpage but couldn't do the same for my Gmail account. Do you know what I am missing here? I think I am picking the wrong class combination:</p>

```<code><li><a href="https://www.linkedin.com/in/.../" target="_blank" class="icon brands fa-linkedin"><span class="label">LinkedIn</span></a></li>
<li><a href="https://github.com/..." target="_blank" class="icon brands fa-github"><span class="label">GitHub</span></a></li>
<li><a href="https://medium.com/@..." target="_blank" class="icon brands fa-medium"><span class="label">Medium</span></a></li>
<li><a href="mailto:...@gmail.com" target="_blank" class="fa fa-envelope-o"><span class="icons">email</span></a></li>

</code>```

答:
Change to (Open envelopes): far fa-envelope-open

or: fas fa-envelope-open

Closed envelopes:

fas fa-envelope

far fa-envelope

Body:
I successfully added my LinkedIn, Github accounts to my webpage but couldn't do the same for my Gmail account. Do you know what I am missing here? I think I am picking the wrong class combination:

LinkedIn

GitHub

Medium

email


问:
Memory managment C++ when return from function
I just start learning C++ and have some question related to memory managment.

I will write only part today because i have many question and hope i understand it with your help.

Suppose i have class A:

```<code>typedef ... DATA;

Class A{
   public:
     ...(contructor, destructor);
     DATA foo(){
       create DATA;
     }

}
</code>```

Now suppose i want return DATA to outer scope.

My questions are:

1.how create DATA inside function foo in better way? (examples of foo body)

a)

```<code>DATA a;
....action with a;
return a;
</code>```

Questions of this way:

1.1 what does it mean DATA a;?

different source - different answers:

1.1 a) Object "a" was created on stack

My understanding: it means it was craeted not in heap but somewhere in memory what have quick access to resource and have LIFO structure, it local  as it created in this function's stack frame and will be destroyed when programm goes out of function scope (frame).

1.1 b) Object "a" was created in automatic memory

My understanding: Its not a stack, but will be destroyed like in case with stack.

Who are right or, where object "a" was created? What will be if DATA is std::container (e.g vector<>),
as i understand vector<> use dinamic allocation of memory (implicitly use of new operator and it means  - on heap?)? Will vector be created on heap, and will it be destroyed automaticly like in case of on stack (or in automatic memory) and i could not warried to destroy "a" and dellocate memory? If so - in case of std::containers the difference between DATA a; and DATA* ptr = new DATA();is only who responsible for  -destroy and dellocate  - me or auto?

1.2 How "a" will be returned?

I heard compiller knows what in case of returning local var by value coppy constructor will create a coppy place it on stack and calling scope will take it from there. In case of huge object i should use move semantic. For ex. in calling scope:

```<code>A a;
DATA b = a.foo();
</code>```

Is it mean to not to coppy huge object i should define move
operator=(&& DATA)?

What if DATA just struct (huge struct), but not a class?

What should i do if DATA is std::container ?

答:
Lots of good questions, here's some quick answers, really you should be reading a C++ text book.

1)

```<code>DATA a;
</code>```

Both answers are right because they mean the same thing. Automatic storage is the technically correct term, but in practise every compiler uses a stack for automatic storage. Whatever term you use a will be destroyed when it goes out of scope.

2)

```<code>vector<DATA> v;
</code>```

There's a vital thing to understand here. The vector contents (the DATA objects) are created on the heap, but the vector itself is created on the stack. This means that just like DATA a; v will be destroyed when it goes out of scope. At that point all the dynamically allocated memory will be freed and so all the DATA objects will be destroyed as well.

Body:
I just start learning C++ and have some question related to memory managment.

I will write only part today because i have many question and hope i understand it with your help.

Suppose i have class A:

typedef ... DATA;

Class A{
   public:
     ...(contructor, destructor);
     DATA foo(){
       create DATA;
     }

}

Now suppose i want return DATA to outer scope.

My questions are:

1.how create DATA inside function foo in better way? (examples of foo body)

a)

DATA a;
....action with a;
return a;

Questions of this way:

1.1 what does it mean DATA a;?

different source - different answers:

1.1 a) Object "a" was created on stack

My understanding: it means it was craeted not in heap but somewhere in memory what have quick access to resource and have LIFO structure, it local  as it created in this function's stack frame and will be destroyed when programm goes out of function scope (frame).

1.1 b) Object "a" was created in automatic memory

My understanding: Its not a stack, but will be destroyed like in case with stack.

Who are right or, where object "a" was created? What will be if DATA is std::container (e.g vector<>),
as i understand vector<> use dinamic allocation of memory (implicitly use of new operator and it means  - on heap?)? Will vector be created on heap, and will it be destroyed automaticly like in case of on stack (or in automatic memory) and i could not warried to destroy "a" and dellocate memory? If so - in case of std::containers the difference between DATA a; and DATA* ptr = new DATA();is only who responsible for  -destroy and dellocate  - me or auto?

1.2 How "a" will be returned?

I heard compiller knows what in case of returning local var by value coppy constructor will create a coppy place it on stack and calling scope will take it from there. In case of huge object i should use move semantic. For ex. in calling scope:

A a;
DATA b = a.foo();

Is it mean to not to coppy huge object i should define move
operator=(&& DATA)?

What if DATA just struct (huge struct), but not a class?

What should i do if DATA is std::container ?

Body:
Lots of good questions, here's some quick answers, really you should be reading a C++ text book.

1)

DATA a;

Both answers are right because they mean the same thing. Automatic storage is the technically correct term, but in practise every compiler uses a stack for automatic storage. Whatever term you use a will be destroyed when it goes out of scope.

2)

vector<DATA> v;

There's a vital thing to understand here. The vector contents (the DATA objects) are created on the heap, but the vector itself is created on the stack. This means that just like DATA a; v will be destroyed when it goes out of scope. At that point all the dynamically allocated memory will be freed and so all the DATA objects will be destroyed as well.


问:
Functions not recognised when using R2D3
I have similar code using just javascript which works fine, but when I try to run it from a flexdashboard using R2D3, additional functions included in scripts are not recognised.

I have simplified my code below to focus on the ScaleRadial function (which I include in the htmltools::tag$script) which produces the error TypeError: d3.scaleRadial is not a function.

I have a similar issue with d3.tip, but have not included the code for that.

I've tried everything I can think of but to no avail.  Any help warmly welcomed.

dashboard.Rmd

```<code>---
title: "Dashboard"
output:
  flexdashboard::flex_dashboard:
    orientation: rows

---

Tab 1
=====================================
  <div id="map" style="width: 800px; height: 800px"></div>

  ```{r}

library(r2d3)
htmltools::tagList(
  htmltools::tags$script(src = "https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.17/d3.min.js"),
  htmltools::tags$script(src = "https://d19vzq90twjlae.cloudfront.net/leaflet-0.7/leaflet.js"),
  htmltools::tags$script(src = "https://cdn.jsdelivr.net/gh/holtzy/D3-graph-gallery@master/LIB/d3-scale-radial.js"),
)

r2d3(script = "bbmapchartSO.js")

```
</code>```

bbmapchartSO.js

```<code>// set the dimensions and margins of the graph
var size = 800;
var margin = {top: 100, right: 0, bottom: 0, left: 0},
    width = size - margin.left - margin.right,
    height = size - margin.top - margin.bottom,
    innerRadius = 240,
    outerRadius = Math.min(width, height) / 2;   // the outerRadius goes from the middle of the SVG area to the border,

    var places = [
      {
          "id": 1,
          "value": 15
      },
      {
          "id": 2,
          "value": 50
      },
      {
          "id": 3,
          "value": 36
      },
      {
          "id": 4,
          "value": 65
      }]

  var mapCenter = new L.LatLng(52.482672, -1.897517);

  var map = L.map('map').setView(mapCenter, 15);
        mapLink =
            '<a href="http://openstreetmap.org">OpenStreetMap</a>';
        L.tileLayer(
            'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
            attribution: '© ' + mapLink + ' Contributors',
            maxZoom: 18,
            dragging: false
            }).addTo(map);

    /* Initialize the SVG layer */
    map._initPathRoot();

    /* We simply pick up the SVG from the map object */
    var leaflet_svg = d3.select("#map").select("svg"),
        central_map_svg = leaflet_svg.append("g"),
      chart_svg = leaflet_svg.append("g")
        .attr("transform", "translate(" + (width / 2 + margin.left) + "," + (height / 2 + margin.top) + ")");

  function plotBBChartOnMap(data) {

  // X scale
  var x = d3.scaleBand()
      .range([0, 2 * Math.PI])    // X axis goes from 0 to 2pi = all around the circle.
      .align(0)                  // This does nothing
      .domain(data.map(function(d) { return d.id; })); // The domain of the X axis is the list of Stations.

  // Y scale outer variable
  var y= d3.scaleRadial()
      .range([innerRadius, outerRadius])   // Domain will be define later.
      .domain([0, 68]); // Domain of Y is from 0 to the max seen in the data

  // Add the bars
  chart_svg.append("g")
    .selectAll("path")
    .data(data)
    .enter()
    .append("path")
      .attr("d", d3.arc()     // imagine your doing a part of a donut plot
          .innerRadius(y(0))
          .outerRadius(function(d) { return y(d['value']); })
          .startAngle(function(d) { return x(d.id); })
          .endAngle(function(d) { return x(d.id) + x.bandwidth(); })
          .padAngle(0.02)
          .padRadius(innerRadius))
}

plotBBChartOnMap(places)
</code>```

答:
The dependencies parameter from the r2d3 package describes:

Additional HTML dependencies. These can take the form of paths to JavaScript or CSS files, or alternatively can be fully specified dependencies created with htmltools::htmlDependency.

So only files are supported, not URL unfortunately and same for htmlDependency. So instead you can do:

library(r2d3)

download.file("https://d19vzq90twjlae.cloudfront.net/leaflet-0.7/leaflet.js", "leaflet-0.7.js")
download.file("https://cdn.jsdelivr.net/gh/holtzy/D3-graph-gallery@master/LIB/d3-scale-radial.js", "d3-scale-radial.js")
download.file("https://cdnjs.cloudflare.com/ajax/libs/d3-tip/0.7.1/d3-tip.min.js", "d3-tip.min.js")

r2d3(script = "bbmapchartSO.js",
     dependencies = list("leaflet-0.7.js",
                         "d3-scale-radial.js",
                         "d3-tip.min.js"))
```

Body:
I have similar code using just javascript which works fine, but when I try to run it from a flexdashboard using R2D3, additional functions included in scripts are not recognised.

I have simplified my code below to focus on the ScaleRadial function (which I include in the htmltools::tag$script) which produces the error TypeError: d3.scaleRadial is not a function.

I have a similar issue with d3.tip, but have not included the code for that.

I've tried everything I can think of but to no avail.  Any help warmly welcomed.

dashboard.Rmd

---
title: "Dashboard"
output:
  flexdashboard::flex_dashboard:
    orientation: rows

---

Tab 1
=====================================

  ```{r}

library(r2d3)
htmltools::tagList(
  htmltools::tags$script(src = "https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.17/d3.min.js"),
  htmltools::tags$script(src = "https://d19vzq90twjlae.cloudfront.net/leaflet-0.7/leaflet.js"),
  htmltools::tags$script(src = "https://cdn.jsdelivr.net/gh/holtzy/D3-graph-gallery@master/LIB/d3-scale-radial.js"),
)

r2d3(script = "bbmapchartSO.js")

```

bbmapchartSO.js

// set the dimensions and margins of the graph
var size = 800;
var margin = {top: 100, right: 0, bottom: 0, left: 0},
    width = size - margin.left - margin.right,
    height = size - margin.top - margin.bottom,
    innerRadius = 240,
    outerRadius = Math.min(width, height) / 2;   // the outerRadius goes from the middle of the SVG area to the border,

    var places = [
      {
          "id": 1,
          "value": 15
      },
      {
          "id": 2,
          "value": 50
      },
      {
          "id": 3,
          "value": 36
      },
      {
          "id": 4,
          "value": 65
      }]

  var mapCenter = new L.LatLng(52.482672, -1.897517);

  var map = L.map('map').setView(mapCenter, 15);
        mapLink =
            'OpenStreetMap';
        L.tileLayer(
            'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
            attribution: '© ' + mapLink + ' Contributors',
            maxZoom: 18,
            dragging: false
            }).addTo(map);

    /* Initialize the SVG layer */
    map._initPathRoot();

    /* We simply pick up the SVG from the map object */
    var leaflet_svg = d3.select("#map").select("svg"),
        central_map_svg = leaflet_svg.append("g"),
      chart_svg = leaflet_svg.append("g")
        .attr("transform", "translate(" + (width / 2 + margin.left) + "," + (height / 2 + margin.top) + ")");

  function plotBBChartOnMap(data) {

  // X scale
  var x = d3.scaleBand()
      .range([0, 2 * Math.PI])    // X axis goes from 0 to 2pi = all around the circle.
      .align(0)                  // This does nothing
      .domain(data.map(function(d) { return d.id; })); // The domain of the X axis is the list of Stations.

  // Y scale outer variable
  var y= d3.scaleRadial()
      .range([innerRadius, outerRadius])   // Domain will be define later.
      .domain([0, 68]); // Domain of Y is from 0 to the max seen in the data

  // Add the bars
  chart_svg.append("g")
    .selectAll("path")
    .data(data)
    .enter()
    .append("path")
      .attr("d", d3.arc()     // imagine your doing a part of a donut plot
          .innerRadius(y(0))
          .outerRadius(function(d) { return y(d['value']); })
          .startAngle(function(d) { return x(d.id); })
          .endAngle(function(d) { return x(d.id) + x.bandwidth(); })
          .padAngle(0.02)
          .padRadius(innerRadius))
}

plotBBChartOnMap(places)


问:
HTML Text Input Value not changing in Backend JavaScript
I am new to web development . I have a question I am trying to build a website that takes input on the front end from the HTML page and actively changes the value on the backend javascript file . The functions I have on the backend rely on the front end input . The input never changes it just stays the default value "google.com".  For Reference here is some code of what I am trying to accomplish .

HTML WebPage

```<code><input type="text"  id="input" value="google.com" placeholder="somewebsite.com">
</code>```

Backend JavaScript File

```<code>var ajaxWebSiteValue = document.getElementById("input");

function getURL(){
    var URL = "http://" + ajaxWebSiteValue.value ;
    return URL;
}
</code>```

答:
is that is what you want to achive??

var ajaxWebSiteValue;

function myFunction(){
  ajaxWebSiteValue = document.getElementById('input').value;

document.getElementById("ajaxWebSiteValue").innerText = ajaxWebSiteValue;

document.getElementById("returnedURL").innerText = getURL();
}

function getURL(){
    var URL = "http://" + ajaxWebSiteValue;
    return URL;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="text"  id="input" value="google.com" placeholder="somewebsite.com" />

<p id="ajaxWebSiteValue"></p>

<p id="returnedURL"></p>

<button id="change" onclick="myFunction()">change</button></code>```

Body:
I am new to web development . I have a question I am trying to build a website that takes input on the front end from the HTML page and actively changes the value on the backend javascript file . The functions I have on the backend rely on the front end input . The input never changes it just stays the default value "google.com".  For Reference here is some code of what I am trying to accomplish .

HTML WebPage

<input type="text"  id="input" value="google.com" placeholder="somewebsite.com">

Backend JavaScript File

var ajaxWebSiteValue = document.getElementById("input");

function getURL(){
    var URL = "http://" + ajaxWebSiteValue.value ;
    return URL;
}

Body:
is that is what you want to achive??

var ajaxWebSiteValue;

function myFunction(){
  ajaxWebSiteValue = document.getElementById('input').value;

document.getElementById("ajaxWebSiteValue").innerText = ajaxWebSiteValue;

document.getElementById("returnedURL").innerText = getURL();
}

function getURL(){
    var URL = "http://" + ajaxWebSiteValue;
    return URL;
}

<input type="text"  id="input" value="google.com" placeholder="somewebsite.com" />

<p id="ajaxWebSiteValue"></p>

<p id="returnedURL"></p>

<button id="change" onclick="myFunction()">change</button>


问:
PHP calculation returns NAN
I'm trying to perform some calculation on Data retrieved from database ,
but evertime I run this code I get  NAN as output.

```<code>function calculateNPS()
    {
        $queryTotal = "SELECT count(*) as total FROM message";
        $resullTotal = mysqli_query($link ,$queryTotal);

        $queryYes= "SELECT count(visit) as  yes FROM message WHERE visit='Yes'";
        $resultYes = mysqli_query($link ,$queryYes);

         $queryNo = "SELECT *count(visit) as no FROM message WHERE visit='No'";
        $resultNo = mysqli_query($link ,$queryNo);

        $yescount = mysqli_fetch_assoc($resultTotal);
        $nocount=mysqli_fetch_assoc($resultNo);
        $totalcount=mysqli_fetch_assoc($resultYes);

        $nps = ((float)($yescount['yes'])/(float)($totalcount['total'])*100)-((float)($nocount['no'])/(float)($totalcount['total'])*100);
        echo $nps;

}
</code>```

答:
I hope thats just a test-script, because there are a lot of issues you could fall into ;-)

but your problem: i guess its just a typing-mistake. you name the result-var "resullTotal", below you are requesting another var called "resultTotal" ;-)

Title: PHP calculation returns NAN

Body:
I'm trying to perform some calculation on Data retrieved from database ,
but evertime I run this code I get  NAN as output.

function calculateNPS()
    {
        $queryTotal = "SELECT count(*) as total FROM message";
        $resullTotal = mysqli_query($link ,$queryTotal);

        $queryYes= "SELECT count(visit) as  yes FROM message WHERE visit='Yes'";
        $resultYes = mysqli_query($link ,$queryYes);

         $queryNo = "SELECT *count(visit) as no FROM message WHERE visit='No'";
        $resultNo = mysqli_query($link ,$queryNo);

        $yescount = mysqli_fetch_assoc($resultTotal);
        $nocount=mysqli_fetch_assoc($resultNo);
        $totalcount=mysqli_fetch_assoc($resultYes);

        $nps = ((float)($yescount['yes'])/(float)($totalcount['total'])*100)-((float)($nocount['no'])/(float)($totalcount['total'])*100);
        echo $nps;

}


问:
Material Ui popover is not on right position
I am working on a project of web application with react. Where I used material ui for navbar. there is a show more icon on right side for mobile devices. But when I open it the popover opened at left side and showing an error Material-UI: The anchorEl prop provided to the component is invalid. I want it on top right side. but couldn't do it. What should I do?

Here is the code

```<code>import React, { useState } from 'react';
import './Navbar.css'
import { useScrollTrigger, Slide, AppBar, Toolbar, IconButton, makeStyles, Divider, List, ListItem, ListItemIcon, ListItemText, Hidden, Drawer, useTheme, Menu, MenuItem } from '@material-ui/core';
import MenuIcon from '@material-ui/icons/Menu';
import InboxIcon from '@material-ui/icons/MoveToInbox';
import MailIcon from '@material-ui/icons/Mail';
import MoreIcon from '@material-ui/icons/MoreVert';
import Logo from '../../images/logo.png';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faGithub, faLinkedinIn } from '@fortawesome/free-brands-svg-icons';

const drawerWidth = 240;

const useStyles = makeStyles((theme) => ({
    toolbar: theme.mixins.toolbar,
    grow: {
        flexGrow: 1,
    },
    menuButton: {
        marginRight: theme.spacing(2),
    },
    sectionDesktop: {
        display: 'none',
        [theme.breakpoints.up('md')]: {
            display: 'flex',
        },
    },
    sectionMobile: {
        display: 'flex',
        [theme.breakpoints.up('md')]: {
            display: 'none',
        },
    },
    drawer: {
        [theme.breakpoints.up('sm')]: {
            width: drawerWidth,
            flexShrink: 0,
        },
    },
    drawerPaper: {
        width: drawerWidth,
    },
}));

const Navbar = (props) => {
    const { window } = props;
    const classes = useStyles();
    const theme = useTheme();
    const [mobileOpen, setMobileOpen] = useState(false);
    const [mobileMoreAnchorEl, setMobileMoreAnchorEl] = useState(null);
    console.log(mobileMoreAnchorEl);

    const HideOnScroll = (props) => {
        const { children, window } = props;
        const trigger = useScrollTrigger({ target: window ? window() : undefined });
        return (
            <Slide appear={false} direction="down" in={!trigger}>
                {children}
            </Slide>
        )
    }

    const handleDrawerToggle = () => {
        setMobileOpen(!mobileOpen);
    };

    const isMobileMenuOpen = Boolean(mobileMoreAnchorEl);

    const handleMobileMenuClose = () => {
        setMobileMoreAnchorEl(null);
    }

    const handleMobileMenuOpen = (event) => {
        setMobileMoreAnchorEl(event.currentTarget);
    }

    const mobileMenuId = 'primary-search-account-menu-mobile';
    const renderMobileMenu = (
        <Menu
            anchorEl={mobileMoreAnchorEl}
            anchorOrigin={{ vertical: 'top', horizontal: 'right' }}
            id={mobileMenuId}
            keepMounted
            transformOrigin={{ vertical: 'top', horizontal: 'right' }}
            open={isMobileMenuOpen}
            onClose={handleMobileMenuClose}
        >
            <MenuItem>
                <IconButton color="inherit">
                    <FontAwesomeIcon icon={faGithub} />
                </IconButton>
            </MenuItem>
            <MenuItem>
                <IconButton color="inherit">
                    <FontAwesomeIcon icon={faLinkedinIn} />
                </IconButton>
            </MenuItem>
        </Menu>
    );

    const drawer = (
        <div>
            <div className={classes.toolbar} />
            <Divider />
            <List>
                {['GitHub', 'Started', 'Send email', 'Drafts'].map((text, index) => (
                    <ListItem button key={text}>
                        <ListItemIcon>{index % 2 === 0 ? <InboxIcon /> : <MailIcon />}</ListItemIcon>
                        <ListItemText primary={text} />
                    </ListItem>
                ))}
            </List>
        </div>
    )

    const container = window !== undefined ? () => window().document.body : undefined;

    return (
        <div className={classes.grow}>
            <div>
                <HideOnScroll {...props}>
                    <AppBar>
                        <Toolbar>
                            <IconButton
                                edge="start"
                                className={classes.menuButton}
                                color="inherit"
                                aria-label="open drawer"
                                onClick={handleDrawerToggle}
                            >
                                <MenuIcon />
                            </IconButton>
                            <img className="logo" src={Logo} alt="" />
                            <div className={classes.grow} />
                            <div className={classes.sectionDesktop}>
                                <a style={{ textDecoration: 'none' }} href="https://github.com/muhidhossain">
                                    <IconButton style={{ color: 'aqua', outline: 'none' }}>
                                        <FontAwesomeIcon icon={faGithub} />
                                    </IconButton>
                                </a>
                                <IconButton style={{ color: 'aqua', outline: 'none' }}>
                                    <FontAwesomeIcon icon={faLinkedinIn} />
                                </IconButton>
                            </div>
                            <div className={classes.sectionMobile}>
                                <IconButton
                                    aria-label="show more"
                                    aria-controls={mobileMenuId}
                                    aria-haspopup="true"
                                    onClick={handleMobileMenuOpen}
                                    color="inherit"
                                >
                                    <MoreIcon />
                                </IconButton>
                            </div>
                        </Toolbar>
                    </AppBar>
                </HideOnScroll>
                {renderMobileMenu}
            </div>
            <nav className={classes.drawer} aria-label="mailbox folders">
                <Hidden smUp implementation="css">
                    <Drawer
                        container={container}
                        variant="temporary"
                        anchor={theme.direction === 'rtl' ? 'right' : 'left'}
                        open={mobileOpen}
                        onClose={handleDrawerToggle}
                        classes={{ paper: classes.drawPaper }}
                        ModalProps={{ keepMounted: true }}
                    >
                        {drawer}
                    </Drawer>
                </Hidden>
            </nav>
        </div>
    );
};

export default Navbar;
</code>```

答:
The HideOnScroll component is creating this issue. For every re-render, the component is recreated. As the anchorel is pointed to the HTML element, which is no longer present it throws an error. If we move the component outside of the Navbar component, the issue will be fixed.</p>

```<code>import React, { useState } from 'react';
import './Navbar.css'
import { useScrollTrigger, Slide, AppBar, Toolbar, IconButton, makeStyles, Divider, List, ListItem, ListItemIcon, ListItemText, Hidden, Drawer, useTheme, Menu, MenuItem } from '@material-ui/core';
import MenuIcon from '@material-ui/icons/Menu';
import InboxIcon from '@material-ui/icons/MoveToInbox';
import MailIcon from '@material-ui/icons/Mail';
import MoreIcon from '@material-ui/icons/MoreVert';
import Logo from '../../images/logo.png';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faGithub, faLinkedinIn } from '@fortawesome/free-brands-svg-icons';

const drawerWidth = 240;

const useStyles = makeStyles((theme) => ({
    toolbar: theme.mixins.toolbar,
    grow: {
        flexGrow: 1,
    },
    menuButton: {
        marginRight: theme.spacing(2),
    },
    sectionDesktop: {
        display: 'none',
        [theme.breakpoints.up('md')]: {
            display: 'flex',
        },
    },
    sectionMobile: {
        display: 'flex',
        [theme.breakpoints.up('md')]: {
            display: 'none',
        },
    },
    drawer: {
        [theme.breakpoints.up('sm')]: {
            width: drawerWidth,
            flexShrink: 0,
        },
    },
    drawerPaper: {
        width: drawerWidth,
    },
}));

    const HideOnScroll = (props) => {
        const { children, window } = props;
        const trigger = useScrollTrigger({ target: window ? window() : undefined });
        return (
            <Slide appear={false} direction="down" in={!trigger}>
                {children}
            </Slide>
        )
    }

const Navbar = (props) => {
    const { window } = props;
    const classes = useStyles();
    const theme = useTheme();
    const [mobileOpen, setMobileOpen] = useState(false);
    const [mobileMoreAnchorEl, setMobileMoreAnchorEl] = useState(null);
    console.log(mobileMoreAnchorEl);

    const handleDrawerToggle = () => {
        setMobileOpen(!mobileOpen);
    };

    const isMobileMenuOpen = Boolean(mobileMoreAnchorEl);

    const handleMobileMenuClose = () => {
        setMobileMoreAnchorEl(null);
    }

    const handleMobileMenuOpen = (event) => {
        setMobileMoreAnchorEl(event.currentTarget);
    }

    const mobileMenuId = 'primary-search-account-menu-mobile';
    const renderMobileMenu = (
        <Menu
            anchorEl={mobileMoreAnchorEl}
            anchorOrigin={{ vertical: 'top', horizontal: 'right' }}
            id={mobileMenuId}
            keepMounted
            transformOrigin={{ vertical: 'top', horizontal: 'right' }}
            open={isMobileMenuOpen}
            onClose={handleMobileMenuClose}
        >
            <MenuItem>
                <IconButton color="inherit">
                    <FontAwesomeIcon icon={faGithub} />
                </IconButton>
            </MenuItem>
            <MenuItem>
                <IconButton color="inherit">
                    <FontAwesomeIcon icon={faLinkedinIn} />
                </IconButton>
            </MenuItem>
        </Menu>
    );

    const drawer = (
        <div>
            <div className={classes.toolbar} />
            <Divider />
            <List>
                {['GitHub', 'Started', 'Send email', 'Drafts'].map((text, index) => (
                    <ListItem button key={text}>
                        <ListItemIcon>{index % 2 === 0 ? <InboxIcon /> : <MailIcon />}</ListItemIcon>
                        <ListItemText primary={text} />
                    </ListItem>
                ))}
            </List>
        </div>
    )

    const container = window !== undefined ? () => window().document.body : undefined;

    return (
        <div className={classes.grow}>
            <div>
                <HideOnScroll {...props}>
                    <AppBar>
                        <Toolbar>
                            <IconButton
                                edge="start"
                                className={classes.menuButton}
                                color="inherit"
                                aria-label="open drawer"
                                onClick={handleDrawerToggle}
                            >
                                <MenuIcon />
                            </IconButton>
                            <img className="logo" src={Logo} alt="" />
                            <div className={classes.grow} />
                            <div className={classes.sectionDesktop}>
                                <a style={{ textDecoration: 'none' }} href="https://github.com/muhidhossain">
                                    <IconButton style={{ color: 'aqua', outline: 'none' }}>
                                        <FontAwesomeIcon icon={faGithub} />
                                    </IconButton>
                                </a>
                                <IconButton style={{ color: 'aqua', outline: 'none' }}>
                                    <FontAwesomeIcon icon={faLinkedinIn} />
                                </IconButton>
                            </div>
                            <div className={classes.sectionMobile}>
                                <IconButton
                                    aria-label="show more"
                                    aria-controls={mobileMenuId}
                                    aria-haspopup="true"
                                    onClick={handleMobileMenuOpen}
                                    color="inherit"
                                >
                                    <MoreIcon />
                                </IconButton>
                            </div>
                        </Toolbar>
                    </AppBar>
                </HideOnScroll>
                {renderMobileMenu}
            </div>
            <nav className={classes.drawer} aria-label="mailbox folders">
                <Hidden smUp implementation="css">
                    <Drawer
                        container={container}
                        variant="temporary"
                        anchor={theme.direction === 'rtl' ? 'right' : 'left'}
                        open={mobileOpen}
                        onClose={handleDrawerToggle}
                        classes={{ paper: classes.drawPaper }}
                        ModalProps={{ keepMounted: true }}
                    >
                        {drawer}
                    </Drawer>
                </Hidden>
            </nav>
        </div>
    );
};

export default Navbar;
</code>```

Body:
I am working on a project of web application with react. Where I used material ui for navbar. there is a show more icon on right side for mobile devices. But when I open it the popover opened at left side and showing an error Material-UI: The anchorEl prop provided to the component is invalid. I want it on top right side. but couldn't do it. What should I do?

Here is the code

import React, { useState } from 'react';
import './Navbar.css'
import { useScrollTrigger, Slide, AppBar, Toolbar, IconButton, makeStyles, Divider, List, ListItem, ListItemIcon, ListItemText, Hidden, Drawer, useTheme, Menu, MenuItem } from '@material-ui/core';
import MenuIcon from '@material-ui/icons/Menu';
import InboxIcon from '@material-ui/icons/MoveToInbox';
import MailIcon from '@material-ui/icons/Mail';
import MoreIcon from '@material-ui/icons/MoreVert';
import Logo from '../../images/logo.png';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faGithub, faLinkedinIn } from '@fortawesome/free-brands-svg-icons';

const drawerWidth = 240;

const useStyles = makeStyles((theme) => ({
    toolbar: theme.mixins.toolbar,
    grow: {
        flexGrow: 1,
    },
    menuButton: {
        marginRight: theme.spacing(2),
    },
    sectionDesktop: {
        display: 'none',
        [theme.breakpoints.up('md')]: {
            display: 'flex',
        },
    },
    sectionMobile: {
        display: 'flex',
        [theme.breakpoints.up('md')]: {
            display: 'none',
        },
    },
    drawer: {
        [theme.breakpoints.up('sm')]: {
            width: drawerWidth,
            flexShrink: 0,
        },
    },
    drawerPaper: {
        width: drawerWidth,
    },
}));

const Navbar = (props) => {
    const { window } = props;
    const classes = useStyles();
    const theme = useTheme();
    const [mobileOpen, setMobileOpen] = useState(false);
    const [mobileMoreAnchorEl, setMobileMoreAnchorEl] = useState(null);
    console.log(mobileMoreAnchorEl);

    const HideOnScroll = (props) => {
        const { children, window } = props;
        const trigger = useScrollTrigger({ target: window ? window() : undefined });
        return (
            <Slide appear={false} direction="down" in={!trigger}>
                {children}
            </Slide>
        )
    }

    const handleDrawerToggle = () => {
        setMobileOpen(!mobileOpen);
    };

    const isMobileMenuOpen = Boolean(mobileMoreAnchorEl);

    const handleMobileMenuClose = () => {
        setMobileMoreAnchorEl(null);
    }

    const handleMobileMenuOpen = (event) => {
        setMobileMoreAnchorEl(event.currentTarget);
    }

    const mobileMenuId = 'primary-search-account-menu-mobile';
    const renderMobileMenu = (
        <Menu
            anchorEl={mobileMoreAnchorEl}
            anchorOrigin={{ vertical: 'top', horizontal: 'right' }}
            id={mobileMenuId}
            keepMounted
            transformOrigin={{ vertical: 'top', horizontal: 'right' }}
            open={isMobileMenuOpen}
            onClose={handleMobileMenuClose}
        >
            <MenuItem>
                <IconButton color="inherit">
                    <FontAwesomeIcon icon={faGithub} />
                </IconButton>
            </MenuItem>
            <MenuItem>
                <IconButton color="inherit">
                    <FontAwesomeIcon icon={faLinkedinIn} />
                </IconButton>
            </MenuItem>
        </Menu>
    );

    const drawer = (

            <Divider />
            <List>
                {['GitHub', 'Started', 'Send email', 'Drafts'].map((text, index) => (
                    <ListItem button key={text}>
                        <ListItemIcon>{index % 2 === 0 ? <InboxIcon /> : <MailIcon />}</ListItemIcon>
                        <ListItemText primary={text} />
                    </ListItem>
                ))}
            </List>

    )

    const container = window !== undefined ? () => window().document.body : undefined;

    return (

                <HideOnScroll {...props}>
                    <AppBar>
                        <Toolbar>
                            <IconButton
                                edge="start"
                                className={classes.menuButton}
                                color="inherit"
                                aria-label="open drawer"
                                onClick={handleDrawerToggle}
                            >
                                <MenuIcon />
                            </IconButton>

                                    <IconButton style={{ color: 'aqua', outline: 'none' }}>
                                        <FontAwesomeIcon icon={faGithub} />
                                    </IconButton>

                                <IconButton style={{ color: 'aqua', outline: 'none' }}>
                                    <FontAwesomeIcon icon={faLinkedinIn} />
                                </IconButton>

                                <IconButton
                                    aria-label="show more"
                                    aria-controls={mobileMenuId}
                                    aria-haspopup="true"
                                    onClick={handleMobileMenuOpen}
                                    color="inherit"
                                >
                                    <MoreIcon />
                                </IconButton>

                        </Toolbar>
                    </AppBar>
                </HideOnScroll>
                {renderMobileMenu}

                <Hidden smUp implementation="css">
                    <Drawer
                        container={container}
                        variant="temporary"
                        anchor={theme.direction === 'rtl' ? 'right' : 'left'}
                        open={mobileOpen}
                        onClose={handleDrawerToggle}
                        classes={{ paper: classes.drawPaper }}
                        ModalProps={{ keepMounted: true }}
                    >
                        {drawer}
                    </Drawer>
                </Hidden>

    );
};

export default Navbar;

Body:
The HideOnScroll component is creating this issue. For every re-render, the component is recreated. As the anchorel is pointed to the HTML element, which is no longer present it throws an error. If we move the component outside of the Navbar component, the issue will be fixed.

import React, { useState } from 'react';
import './Navbar.css'
import { useScrollTrigger, Slide, AppBar, Toolbar, IconButton, makeStyles, Divider, List, ListItem, ListItemIcon, ListItemText, Hidden, Drawer, useTheme, Menu, MenuItem } from '@material-ui/core';
import MenuIcon from '@material-ui/icons/Menu';
import InboxIcon from '@material-ui/icons/MoveToInbox';
import MailIcon from '@material-ui/icons/Mail';
import MoreIcon from '@material-ui/icons/MoreVert';
import Logo from '../../images/logo.png';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faGithub, faLinkedinIn } from '@fortawesome/free-brands-svg-icons';

const drawerWidth = 240;

const useStyles = makeStyles((theme) => ({
    toolbar: theme.mixins.toolbar,
    grow: {
        flexGrow: 1,
    },
    menuButton: {
        marginRight: theme.spacing(2),
    },
    sectionDesktop: {
        display: 'none',
        [theme.breakpoints.up('md')]: {
            display: 'flex',
        },
    },
    sectionMobile: {
        display: 'flex',
        [theme.breakpoints.up('md')]: {
            display: 'none',
        },
    },
    drawer: {
        [theme.breakpoints.up('sm')]: {
            width: drawerWidth,
            flexShrink: 0,
        },
    },
    drawerPaper: {
        width: drawerWidth,
    },
}));

    const HideOnScroll = (props) => {
        const { children, window } = props;
        const trigger = useScrollTrigger({ target: window ? window() : undefined });
        return (
            <Slide appear={false} direction="down" in={!trigger}>
                {children}
            </Slide>
        )
    }

const Navbar = (props) => {
    const { window } = props;
    const classes = useStyles();
    const theme = useTheme();
    const [mobileOpen, setMobileOpen] = useState(false);
    const [mobileMoreAnchorEl, setMobileMoreAnchorEl] = useState(null);
    console.log(mobileMoreAnchorEl);

    const handleDrawerToggle = () => {
        setMobileOpen(!mobileOpen);
    };

    const isMobileMenuOpen = Boolean(mobileMoreAnchorEl);

    const handleMobileMenuClose = () => {
        setMobileMoreAnchorEl(null);
    }

    const handleMobileMenuOpen = (event) => {
        setMobileMoreAnchorEl(event.currentTarget);
    }

    const mobileMenuId = 'primary-search-account-menu-mobile';
    const renderMobileMenu = (
        <Menu
            anchorEl={mobileMoreAnchorEl}
            anchorOrigin={{ vertical: 'top', horizontal: 'right' }}
            id={mobileMenuId}
            keepMounted
            transformOrigin={{ vertical: 'top', horizontal: 'right' }}
            open={isMobileMenuOpen}
            onClose={handleMobileMenuClose}
        >
            <MenuItem>
                <IconButton color="inherit">
                    <FontAwesomeIcon icon={faGithub} />
                </IconButton>
            </MenuItem>
            <MenuItem>
                <IconButton color="inherit">
                    <FontAwesomeIcon icon={faLinkedinIn} />
                </IconButton>
            </MenuItem>
        </Menu>
    );

    const drawer = (
        <div>
            <div className={classes.toolbar} />
            <Divider />
            <List>
                {['GitHub', 'Started', 'Send email', 'Drafts'].map((text, index) => (
                    <ListItem button key={text}>
                        <ListItemIcon>{index % 2 === 0 ? <InboxIcon /> : <MailIcon />}</ListItemIcon>
                        <ListItemText primary={text} />
                    </ListItem>
                ))}
            </List>
        </div>
    )

    const container = window !== undefined ? () => window().document.body : undefined;

    return (
        <div className={classes.grow}>
            <div>
                <HideOnScroll {...props}>
                    <AppBar>
                        <Toolbar>
                            <IconButton
                                edge="start"
                                className={classes.menuButton}
                                color="inherit"
                                aria-label="open drawer"
                                onClick={handleDrawerToggle}
                            >
                                <MenuIcon />
                            </IconButton>
                            <img className="logo" src={Logo} alt="" />
                            <div className={classes.grow} />
                            <div className={classes.sectionDesktop}>
                                <a style={{ textDecoration: 'none' }} href="https://github.com/muhidhossain">
                                    <IconButton style={{ color: 'aqua', outline: 'none' }}>
                                        <FontAwesomeIcon icon={faGithub} />
                                    </IconButton>
                                </a>
                                <IconButton style={{ color: 'aqua', outline: 'none' }}>
                                    <FontAwesomeIcon icon={faLinkedinIn} />
                                </IconButton>
                            </div>
                            <div className={classes.sectionMobile}>
                                <IconButton
                                    aria-label="show more"
                                    aria-controls={mobileMenuId}
                                    aria-haspopup="true"
                                    onClick={handleMobileMenuOpen}
                                    color="inherit"
                                >
                                    <MoreIcon />
                                </IconButton>
                            </div>
                        </Toolbar>
                    </AppBar>
                </HideOnScroll>
                {renderMobileMenu}
            </div>
            <nav className={classes.drawer} aria-label="mailbox folders">
                <Hidden smUp implementation="css">
                    <Drawer
                        container={container}
                        variant="temporary"
                        anchor={theme.direction === 'rtl' ? 'right' : 'left'}
                        open={mobileOpen}
                        onClose={handleDrawerToggle}
                        classes={{ paper: classes.drawPaper }}
                        ModalProps={{ keepMounted: true }}
                    >
                        {drawer}
                    </Drawer>
                </Hidden>
            </nav>
        </div>
    );
};

export default Navbar;


问:
Conditional formatting django css
I pretty new to Python and Django. My first Project is a MS Teams Status Call Monitor.
Its working so far. But I asked myself if its possible to format the Table different when having a change in my Status.

```<code>Available = Green
Away = Yellow
Busy = Red
</code>```

How can I do that with Django / CSS?

```<code>{% extends "tutorial/layout.html" %}
{% block content %}
<h1>Teams</h1>
<table class="table">
  <thead>
    <tr>
     <th scope="col">Activity</th>
     <th scope="col">Availability</th>
    </tr>
  </thead>
  <tbody>
     <tr>
        <td>{{ status.status }}</td>
        <td>{{ status.availability }}</td>
     </tr>
  </tbody>
  </table>
{% endblock %}
</code>```

Thanks :)

答:
Try this:

var input = $('.input').text()
console.log(input)

if (input == 'Busy') {
    $('.input').css('color', 'red')
} else if (input == 'Away') {
    $('.input').css('color', 'yellow')
} else if (input == 'Available') {
    $('.input').css('color', 'green')
} else {}
    ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table">
  <thead>
    <tr>
     <th scope="col">Activity</th>
     <th scope="col">Availability</th>
    </tr>
  </thead>
  <tbody>
     <tr>
        <td class="input">Available</td>
     </tr>
  </tbody>
  </table></code>```

Title: Conditional formatting django css

Body:
I pretty new to Python and Django. My first Project is a MS Teams Status Call Monitor.
Its working so far. But I asked myself if its possible to format the Table different when having a change in my Status.

Available = Green
Away = Yellow
Busy = Red

How can I do that with Django / CSS?

{% extends "tutorial/layout.html" %}
{% block content %}

Teams

     Activity
     Availability

        {{ status.status }}
        {{ status.availability }}

{% endblock %}

Thanks :)

Body:
Try this:

var input = $('.input').text()
console.log(input)

if (input == 'Busy') {
    $('.input').css('color', 'red')
} else if (input == 'Away') {
    $('.input').css('color', 'yellow')
} else if (input == 'Available') {
    $('.input').css('color', 'green')
} else {}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table">
  <thead>
    <tr>
     <th scope="col">Activity</th>
     <th scope="col">Availability</th>
    </tr>
  </thead>
  <tbody>
     <tr>
        <td class="input">Available</td>
     </tr>
  </tbody>
  </table>


问:
PostgreSQL - Declaring a variable that can store multiple values
I need a way to declare a variable that can store multiple values. My first attempt was to declare a variable using the TABLE type:

```<code>DECLARE __id TABLE(results_id integer);
</code>```

However this didnt go as planned, giving me type-declaration errors. My next attempt was to make an integer[] type

```<code>DECLARE __id integer[];
</code>```

but it ended up giving me an error of that values needs to be inserted using curly braces whenever i attempted to insert them with a select function.

```<code>SELECT p.id FROM files.main p
WHERE p.reference = __reference
AND p.platform = __platform_id
INTO __id;
</code>```

I wonder if there is any way to solve this problem?

答:
If you have a table name t you can declare a variable of the type t

```<code>create or replace function tf1() returns int as
$BODY$
DECLARE
 var  public.t;
BEGIN
    select * from public.t into var limit 1;

  return var.id;
END;
$BODY$
LANGUAGE plpgsql ;

select * from tf1();
</code>```

Body:
I need a way to declare a variable that can store multiple values. My first attempt was to declare a variable using the TABLE type:

DECLARE __id TABLE(results_id integer);

However this didnt go as planned, giving me type-declaration errors. My next attempt was to make an integer[] type

DECLARE __id integer[];

but it ended up giving me an error of that values needs to be inserted using curly braces whenever i attempted to insert them with a select function.

SELECT p.id FROM files.main p
WHERE p.reference = __reference
AND p.platform = __platform_id
INTO __id;

I wonder if there is any way to solve this problem?

Body:
If you have a table name t you can declare a variable of the type t

create or replace function tf1() returns int as
$BODY$
DECLARE
 var  public.t;
BEGIN
    select * from public.t into var limit 1;

  return var.id;
END;
$BODY$
LANGUAGE plpgsql ;

select * from tf1();