问:
Getting Parsing error: Unexpected token, expected "," in Vue
I am trying to do an axios request but whatever I do I get the same error message.

The message is:

Parsing error: Unexpected token, expected ",". The error points at axios.get  (it points at the dot between "axios" and "get" in the error message). It gives the same message if I put something like console.log in the code.

I am basically just using a regular default vue project and the only thing I have done is to add the following code in HelloWorld.vue.

```<code><script type="text/javascript">
   import axios from 'axios';
 //  const axios = require('axios');

  export default {
    name: 'HelloWorld',  //  console.log("hi"),
    props: {
      msg: String //response
    },
    methods: {
      axios.get('https://swapi.co/api/people/1')
        .then(function(response){
            console.log(response)
        })
    }
  }

</script>
</code>```

Can someone please tell me why this error keeps coming up, I am guessing this is pretty simple but I am losing my mind at this point. Thank you

答:
axios must be globalized in your root file.</p>

```<code>    const axios = require('axios');
global.axios = axios;
</code>```

Body:
I am trying to do an axios request but whatever I do I get the same error message.

The message is:

Parsing error: Unexpected token, expected ",". The error points at axios.get  (it points at the dot between "axios" and "get" in the error message). It gives the same message if I put something like console.log in the code.

I am basically just using a regular default vue project and the only thing I have done is to add the following code in HelloWorld.vue.

Can someone please tell me why this error keeps coming up, I am guessing this is pretty simple but I am losing my mind at this point. Thank you

Body:
axios must be globalized in your root file.

    const axios = require('axios');
global.axios = axios;


来源: stackexchange

问:
Pandas apply operation on each pair of rows
Same value is repeating in the dataframe column while calculating the distance between langitude and longitude . I have created a dynamic column for finding the distance between every source to destination but all the values of each column is repeating.

```<code>for a,b,x in zip(df.Longitude,df.Latitude,df.index):
    for c,d in zip(df.Longitude,df.Latitude):
        df['distance_'+str(x)]=haversine(a,b,c,d)
</code>```

suppose this is the dataframe

```<code>  index   name   lat     long

    0      a     74.299104  31.481188

    1      b     74.351619  39.481188

    2      c     73.351619  39.481188
</code>```

now i want the expected result like this

```<code>  index   name   lat          long     distanceA      distanceB     distanceC

    0      a     74.299104  31.481188      0             4.5          2.4

    1      b     74.351619  39.481188     5.7             0           5.8

    2      c     73.351619  39.481188     3.8            1.3           0
</code>```

答:
Consider a vectorized version of the haversine formula and avoid for or apply loops. For example, assuming you use this version, swap out the scalar functions for numpy versions:

```<code>import numpy as np

def haversine(lon1, lat1, lon2, lat2):
    """
    Calculate the great circle distance between two points
    on the earth (specified in decimal degrees)
    """
    # convert decimal degrees to radians
    lon1, lat1, lon2, lat2 = map(np.radians, [lon1, lat1, lon2, lat2])

    # haversine formula
    dlon = lon2 - lon1
    dlat = lat2 - lat1
    a = np.sin(dlat/2)**2 + np.cos(lat1) * np.cos(lat2) * np.sin(dlon/2)**2
    c = 2 * np.arcsin(np.sqrt(a))
    r = 3956 # Radius of earth in miles. Use 6371 for kilometers.

    return c * r
</code>```

Then, run cross join with pivot_table:

```<code>cj_df = (df.assign(key=1)
           .merge(df.assign(key=1), on=['key'], suffixes=['', '_'])
        )

cj_df['distance'] = haversine(cj_df['long'], cj_df['lat'],
                              cj_df['long_'], cj_df['lat_'])

cj_df.pivot_table(index=['name', 'lat', 'long'],
                  columns = 'name_',
                  values = 'distance',
                  aggfunc = 'max')

# name_                              a           b           c
# name lat       long
# a    74.299104 31.481188    0.000000  149.165464  167.033556
# b    74.351619 39.481188  149.165464    0.000000   69.045225
# c    73.351619 39.481188  167.033556   69.045225    0.000000
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Same value is repeating in the dataframe column while calculating the distance between langitude and longitude . I have created a dynamic column for finding the distance between every source to destination but all the values of each column is repeating.

for a,b,x in zip(df.Longitude,df.Latitude,df.index):
    for c,d in zip(df.Longitude,df.Latitude):
        df['distance_'+str(x)]=haversine(a,b,c,d)

suppose this is the dataframe

  index   name   lat     long

    0      a     74.299104  31.481188

    1      b     74.351619  39.481188

    2      c     73.351619  39.481188

now i want the expected result like this

  index   name   lat          long     distanceA      distanceB     distanceC

    0      a     74.299104  31.481188      0             4.5          2.4

    1      b     74.351619  39.481188     5.7             0           5.8

    2      c     73.351619  39.481188     3.8            1.3           0

Body:
Consider a vectorized version of the haversine formula and avoid for or apply loops. For example, assuming you use this version, swap out the scalar functions for numpy versions:

import numpy as np

def haversine(lon1, lat1, lon2, lat2):
    """
    Calculate the great circle distance between two points
    on the earth (specified in decimal degrees)
    """
    # convert decimal degrees to radians
    lon1, lat1, lon2, lat2 = map(np.radians, [lon1, lat1, lon2, lat2])

    # haversine formula
    dlon = lon2 - lon1
    dlat = lat2 - lat1
    a = np.sin(dlat/2)**2 + np.cos(lat1) * np.cos(lat2) * np.sin(dlon/2)**2
    c = 2 * np.arcsin(np.sqrt(a))
    r = 3956 # Radius of earth in miles. Use 6371 for kilometers.

    return c * r

Then, run cross join with pivot_table:

cj_df = (df.assign(key=1)
           .merge(df.assign(key=1), on=['key'], suffixes=['', '_'])
        )

cj_df['distance'] = haversine(cj_df['long'], cj_df['lat'],
                              cj_df['long_'], cj_df['lat_'])

cj_df.pivot_table(index=['name', 'lat', 'long'],
                  columns = 'name_',
                  values = 'distance',
                  aggfunc = 'max')

# name_                              a           b           c
# name lat       long
# a    74.299104 31.481188    0.000000  149.165464  167.033556
# b    74.351619 39.481188  149.165464    0.000000   69.045225
# c    73.351619 39.481188  167.033556   69.045225    0.000000


问:
Mount vfat image win linux using C
I'm trying to mount a vfat disk image from DOS, using .C

```<code>if( mount( "/mypath/disk.img", "/mypath/img/", "vfat", MS_DIRSYNC | MS_SYNCHRONOUS, "utf8" ) ) {
  printf( "Error mount %s errno=%d %s\n", dst.c_str(), errno, strerror( errno ) );
}
</code>```

I get all the times the error "Block device required". Should i add some parameter or flag?

Note:I can mount from the bash the same file in the same target without any error.

UPDATE:
I had some good result using the function to mount an ISO. When I run the program, it remains stacked on the call ioctl(loop_device_fd, LOOP_CLR_FD, 0);. When I exit from the program (ctrl-c), the image is mounted. Is  LOOP_CLR_FD necessary to complete all the steps? In additional,it is mounted in read only and seems not possible to change it in read/write.

```<code>const auto loop_control = std::fopen( "/dev/loop-control", "r" );
const auto loop_control_fd = fileno(loop_control);
const auto devnr = ioctl(loop_control_fd, LOOP_CTL_GET_FREE);
std::stringstream loopname;
loopname << "/dev/loop" << devnr;
const auto loop_device_name = loopname.str();
const auto loop_device = std::fopen(loop_device_name.c_str(), "r");
const auto loop_device_fd = fileno(loop_device);
const auto image = std::fopen( dst.c_str(), "r" );
const auto image_fd = fileno(image);
//Associate the loop device with the open file whose file descriptor is passed as the (third) ioctl(2) argument.
ioctl(loop_device_fd, LOOP_SET_FD, image_fd);
const auto result = mount(loop_device_name.c_str(), dst_path_img.c_str(), "vfat", MS_RDONLY, NULL);
if( result ) {
printf( "Error mount %s errno=%d %s\n", dst.c_str(), errno, strerror( errno ) );
return;
}
ioctl(loop_device_fd, LOOP_CLR_FD, 0);
</code>```

答:
The problem here is you're trying to mount an image as you you would do with a block device. A block device has more bindings to the operating system than an image file would, so you need to find a way around this.

Try a loopback device! A loopback device can give you the operating system reference to that image /mypath/disk.img as a block device. You can create a loopback device in bash like so:

# set up a block device
losetup -fP /mypath/disk.img
# now list the loopback devices
losetup -a
```

Anyway, this solution is in bash, but certainly there is a library out there somewhere for c.

Title: Mount vfat image win linux using C

Body:
I'm trying to mount a vfat disk image from DOS, using .C

if( mount( "/mypath/disk.img", "/mypath/img/", "vfat", MS_DIRSYNC | MS_SYNCHRONOUS, "utf8" ) ) {
  printf( "Error mount %s errno=%d %s\n", dst.c_str(), errno, strerror( errno ) );
}

I get all the times the error "Block device required". Should i add some parameter or flag?

Note:I can mount from the bash the same file in the same target without any error.

UPDATE:
I had some good result using the function to mount an ISO. When I run the program, it remains stacked on the call ioctl(loop_device_fd, LOOP_CLR_FD, 0);. When I exit from the program (ctrl-c), the image is mounted. Is  LOOP_CLR_FD necessary to complete all the steps? In additional,it is mounted in read only and seems not possible to change it in read/write.

const auto loop_control = std::fopen( "/dev/loop-control", "r" );
const auto loop_control_fd = fileno(loop_control);
const auto devnr = ioctl(loop_control_fd, LOOP_CTL_GET_FREE);
std::stringstream loopname;
loopname << "/dev/loop" << devnr;
const auto loop_device_name = loopname.str();
const auto loop_device = std::fopen(loop_device_name.c_str(), "r");
const auto loop_device_fd = fileno(loop_device);
const auto image = std::fopen( dst.c_str(), "r" );
const auto image_fd = fileno(image);
//Associate the loop device with the open file whose file descriptor is passed as the (third) ioctl(2) argument.
ioctl(loop_device_fd, LOOP_SET_FD, image_fd);
const auto result = mount(loop_device_name.c_str(), dst_path_img.c_str(), "vfat", MS_RDONLY, NULL);
if( result ) {
printf( "Error mount %s errno=%d %s\n", dst.c_str(), errno, strerror( errno ) );
return;
}
ioctl(loop_device_fd, LOOP_CLR_FD, 0);

Body:
The problem here is you're trying to mount an image as you you would do with a block device. A block device has more bindings to the operating system than an image file would, so you need to find a way around this.

Try a loopback device! A loopback device can give you the operating system reference to that image /mypath/disk.img as a block device. You can create a loopback device in bash like so:

# set up a block device
losetup -fP /mypath/disk.img
# now list the loopback devices
losetup -a

Anyway, this solution is in bash, but certainly there is a library out there somewhere for c.


问:
Google Cloud Platform project is being suspended, I tried to submit an appeal but not working
About 2 weeks ago, I found that my GCP project (using YouTube API) is being suspended for violating Google Cloud Platform Terms of Service or Acceptable Use Policy by circumventing quota restrictions via multiple projects acting as one.

I've deleted all other projects and submitted an appeal for 12 days ago, but the main project is still locked and no response from Google support.

I just keep receiving 2 emails from Google system when I submit an appeal again:

Thank you for your follow up. A member of our team will review the appeal for your Google Cloud Project and get back to you within two business days.

and

We have recently detected your Google Cloud / APIs Projects have been circumventing our quota restrictions via multiple projects acting as one and appears to be violating YouTube API Terms of Service (III.D.1.c).

You can fix the problem by taking the following steps:

Consolidate your projects behind one single project ID and delete the remaining projects

Once you've completed step 1, sign in to your remaining active project and submit an appeal

How can I solve the problem?

Thank you.

答: You have to wait and check constantly your email for any requested information from the Google side. Try to be as detailed as you can and try to provide as much evidence as possible. This process sometimes can take some time to be reviewed. If you have submitted an appeal, you just can wait and keep monitoring your mail. On the other hand, you can create a new Project.</p>


问:
There is no 'Renderer' attached to the "robot2" game object, but a script is trying to access it

MissingComponentException: There is no 'Renderer' attached to the
  "robot2" game object, but a script is trying to access it. You
  probably need to add a Renderer to the game object "robot2". Or your
  script needs to check if the component is attached before using it.
  UnityEngine.Renderer.get_material () (at
  <94c5f4c38cdc42d2b006f8badef04394>:0) ColorChange.Start () (at
  Assets/ColorChange.cs:21)

I have a fbx robot2 in my Unity program, it have been imported as a Asset. I want change the color when program start, but I get this message. How could I render my fbx in Unity?

```<code>public Color colorStart = Color.red;
public Color colorEnd = Color.green;
public Renderer rend;

// Start is called before the first frame update
void Start()
{
    rend = GetComponent<Renderer>();
    rend.material.color = colorStart;
}
</code>```

答:
Basically the error message says it all:

GetComponent only returns a component attached to the same GameObject as your script.

But your robo2 has no mesh and therefore also no Renderer.

What you rather want to do in your case would be using GetComponentsInChildren which rather returns all according components attached to the GameObject itself your script is attached to or any child object nested under it recursively

```<code>void Start()
{
    // pass true in order to also include disabled or inactive child Renderer
    foreach(var rend in GetComponentsInChildren<Renderer>(true))
    {
        rend.material.color = colorStart;
    }
}
</code>```

Body:
MissingComponentException: There is no 'Renderer' attached to the
  "robot2" game object, but a script is trying to access it. You
  probably need to add a Renderer to the game object "robot2". Or your
  script needs to check if the component is attached before using it.
  UnityEngine.Renderer.get_material () (at
  <94c5f4c38cdc42d2b006f8badef04394>:0) ColorChange.Start () (at
  Assets/ColorChange.cs:21)

I have a fbx robot2 in my Unity program, it have been imported as a Asset. I want change the color when program start, but I get this message. How could I render my fbx in Unity?

public Color colorStart = Color.red;
public Color colorEnd = Color.green;
public Renderer rend;

// Start is called before the first frame update
void Start()
{
    rend = GetComponent<Renderer>();
    rend.material.color = colorStart;
}

Body:
Basically the error message says it all:

GetComponent only returns a component attached to the same GameObject as your script.

But your robo2 has no mesh and therefore also no Renderer.

What you rather want to do in your case would be using GetComponentsInChildren which rather returns all according components attached to the GameObject itself your script is attached to or any child object nested under it recursively

void Start()
{
    // pass true in order to also include disabled or inactive child Renderer
    foreach(var rend in GetComponentsInChildren<Renderer>(true))
    {
        rend.material.color = colorStart;
    }
}


问:
Can mutex implementations be interchanged (independently of the thread implementation)
Do all mutex implementations ultimately call the same basic system/hardware calls - meaning that they can be interchanged?

Specifically, if I'm using __gnu_parallel algorithms (that uses openmp) and I want to make the classes they call threadsafe may I use boost::mutex for the locking? or must I write my own mutex such as the one described here

```<code>//An openmp mutex.  Can this be replaced with boost::mutex?
class Mutex {
public:
    Mutex() { omp_init_lock(&_mutex); }
    ~Mutex() { omp_destroy_lock(&_mutex); }
    void lock() { omp_set_lock(&_mutex); }
    void unlock() { omp_unset_lock(&_mutex); }
private:
    omp_lock_t _mutex;
};
</code>```

Edit, the link above to the openmp mutex seems to be broken, for anyone interested, the lock that goes with this mutex is along these lines

```<code>class Lock
{
public:
    Lock(Mutex& mutex)
        : m_mutex(mutex),
    m_release(false)
    {
        m_mutex.lock();
    }

    ~Lock()
    {
        if (!m_release)
            m_mutex.unlock();
    }

    bool operator() const
    {
        return !m_release;
    }

    void release()
    {
        if (!m_release)
        {
            m_release = true;
            m_mutex.unlock();
        }
    }

private:
    Mutex& m_mutex;
    bool m_release;
};
</code>```

答:
This link provides a useful discussion:

http://groups.google.com/group/comp.programming.threads/browse_thread/thread/67e7b9b9d6a4b7df?pli=1

Paraphrasing, (at least on Linux) Boost::Thread and OpenMP both an interface to pthread and so in principle should be able to be mixed (as Anders says +1), but mixing threading technologies in this way is generally a bad idea (as Andy says, +1).

ContentLicense: CC BY-SA 3.0

Body:
Do all mutex implementations ultimately call the same basic system/hardware calls - meaning that they can be interchanged?

Specifically, if I'm using __gnu_parallel algorithms (that uses openmp) and I want to make the classes they call threadsafe may I use boost::mutex for the locking? or must I write my own mutex such as the one described here

//An openmp mutex.  Can this be replaced with boost::mutex?
class Mutex {
public:
    Mutex() { omp_init_lock(&_mutex); }
    ~Mutex() { omp_destroy_lock(&_mutex); }
    void lock() { omp_set_lock(&_mutex); }
    void unlock() { omp_unset_lock(&_mutex); }
private:
    omp_lock_t _mutex;
};

Edit, the link above to the openmp mutex seems to be broken, for anyone interested, the lock that goes with this mutex is along these lines

class Lock
{
public:
    Lock(Mutex& mutex)
        : m_mutex(mutex),
    m_release(false)
    {
        m_mutex.lock();
    }

    ~Lock()
    {
        if (!m_release)
            m_mutex.unlock();
    }

    bool operator() const
    {
        return !m_release;
    }

    void release()
    {
        if (!m_release)
        {
            m_release = true;
            m_mutex.unlock();
        }
    }

private:
    Mutex& m_mutex;
    bool m_release;
};


问:
How to position a image over the map
Im trying to position an image on the map, but can't figure out what the position values mean, this gives me a very hard time getting the right position of the image.

The following is the code I'm using.

```<code>const imageExtent: any = [10, 10, 10, 10];

        this.map = new Map({
            target: 'map',
            interactions: defaultInteractions().extend([new DragRotateAndZoom()]),
            layers: [
                new TileLayer({
                    source: new OSM()
                }),
                new ImageLayer({
                    source: new Static({
                        url: 'https://www.petmd.com/sites/default/files/small-kitten-walking-towards_127900829_0.jpg',
                        crossOrigin: '',
                        projection: 'EPSG:4326',
                        imageExtent
                    })
                })
            ],
            view: new View({
                center: fromLonLat([15, 50]),
                zoom: 16
            })
        });
</code>```

The image is currently showing, but in the wrong position.
We would like to use the same coordinate standard as Google Maps.

答:
Have a look at ol-ext GeoImage source to display images on the map.

This project lets you reference the image and calculate the params https://github.com/Viglino/Map-georeferencer

Title: How to position a image over the map

Body:
Im trying to position an image on the map, but can't figure out what the position values mean, this gives me a very hard time getting the right position of the image.

The following is the code I'm using.

const imageExtent: any = [10, 10, 10, 10];

        this.map = new Map({
            target: 'map',
            interactions: defaultInteractions().extend([new DragRotateAndZoom()]),
            layers: [
                new TileLayer({
                    source: new OSM()
                }),
                new ImageLayer({
                    source: new Static({
                        url: 'https://www.petmd.com/sites/default/files/small-kitten-walking-towards_127900829_0.jpg',
                        crossOrigin: '',
                        projection: 'EPSG:4326',
                        imageExtent
                    })
                })
            ],
            view: new View({
                center: fromLonLat([15, 50]),
                zoom: 16
            })
        });

The image is currently showing, but in the wrong position.
We would like to use the same coordinate standard as Google Maps.


问:
Dockeried setup for Node and Reactjs
I want to run two docker containers: one is node server(backend) and other has react js code(frontend).

My node contains an API as shown below:

```<code>app.get('/build', function (req, res) {
    ...
    ...
});

app.listen(3001);
console.log("Listening to PORT 3001");
</code>```

I am using this API in my react code as follows:

```<code>componentDidMount() {

axios.get('http://localhost:3001/build', { headers: {"x-access-token": this.state.token}
      })
           .then(response => {
              const builds = response.data.message;
              //console.log("builds",builds);
              this.setState({ builds: builds,done: true });
           });
}
</code>```

But when I run 2 different Docker containers, exposing 3001 for backend container and exposing 3000 for frontend container and access http://aws-ip:3000 (aws-ip is the public IP of my AWS instance where I am running the two docker containers), the request made is

http://localhost:3001/build due to which I am not able to hit the node api of docker container.

What changes should I make in the existing setup so that my react application can fetch the data from node server which is running on the same AWS instance?

答:
You can follow his tutorial.
I think you can achieve that with docker-compose: https://docs.docker.com/compose/

Example: https://dev.to/numtostr/running-react-and-node-js-in-one-shot-with-docker-3o09

and here how I am using

```<code>version: '3'
services:
    awsService:
        build:
            context: ./awsService
            dockerfile: Dockerfile.dev
        volumes:
            - ./awsService/src:/app/src
        ports:
            - "3000:3000"
    keymaster:
        build:
            context: ./keymaster
            dockerfile: Dockerfile.dev
        volumes:
            - /app/node_modules
            - ./keymaster:/app
        ports:
            - "8080:8080"
    postgres:
        image: postgres:12.1
        ports:
            - "5432:5432"
        environment:
            POSTGRES_PASSWORD: mypassword
        volumes:
            - ./postgresql/data:/var/lib/postgresql/data
    service:
        build:
            context: ./service
            dockerfile: Dockerfile.dev
        volumes:
            - /app/node_modules
            - ./service/config:/app/config
            - ./service/src:/app/src
        ports:
            - "3001:3000"
    ui:
        build:
            context: ./ui
            dockerfile: Dockerfile.dev
        volumes:
            - /app/node_modules
            - ./ui:/app
        ports:
            - "8081:8080"

</code>```

For future reference, if you have something running on the same port, just bind your local machine port to a different port.

Hope this helps.

Title: Dockeried setup for Node and Reactjs

Body:
I want to run two docker containers: one is node server(backend) and other has react js code(frontend).

My node contains an API as shown below:

app.get('/build', function (req, res) {
    ...
    ...
});

app.listen(3001);
console.log("Listening to PORT 3001");

I am using this API in my react code as follows:

componentDidMount() {

axios.get('http://localhost:3001/build', { headers: {"x-access-token": this.state.token}
      })
           .then(response => {
              const builds = response.data.message;
              //console.log("builds",builds);
              this.setState({ builds: builds,done: true });
           });
}

But when I run 2 different Docker containers, exposing 3001 for backend container and exposing 3000 for frontend container and access http://aws-ip:3000 (aws-ip is the public IP of my AWS instance where I am running the two docker containers), the request made is

http://localhost:3001/build due to which I am not able to hit the node api of docker container.

What changes should I make in the existing setup so that my react application can fetch the data from node server which is running on the same AWS instance?

Body:
You can follow his tutorial.
I think you can achieve that with docker-compose: https://docs.docker.com/compose/

Example: https://dev.to/numtostr/running-react-and-node-js-in-one-shot-with-docker-3o09

and here how I am using

version: '3'
services:
    awsService:
        build:
            context: ./awsService
            dockerfile: Dockerfile.dev
        volumes:
            - ./awsService/src:/app/src
        ports:
            - "3000:3000"
    keymaster:
        build:
            context: ./keymaster
            dockerfile: Dockerfile.dev
        volumes:
            - /app/node_modules
            - ./keymaster:/app
        ports:
            - "8080:8080"
    postgres:
        image: postgres:12.1
        ports:
            - "5432:5432"
        environment:
            POSTGRES_PASSWORD: mypassword
        volumes:
            - ./postgresql/data:/var/lib/postgresql/data
    service:
        build:
            context: ./service
            dockerfile: Dockerfile.dev
        volumes:
            - /app/node_modules
            - ./service/config:/app/config
            - ./service/src:/app/src
        ports:
            - "3001:3000"
    ui:
        build:
            context: ./ui
            dockerfile: Dockerfile.dev
        volumes:
            - /app/node_modules
            - ./ui:/app
        ports:
            - "8081:8080"

For future reference, if you have something running on the same port, just bind your local machine port to a different port.

Hope this helps.


问:
java.lang.Object cannot be converted to the class i created
im having a problem calling a method i created for a class when it is returned from a list. I get a "java.lang.Object cannot be converted to Thing"
error when running the following code

```<code>public class Test1
{
  public static void main(String args[])
  {
    Thing whipersnaper = new Thing(30, "whipersnaper");
    List storage = new List();

    storage.insert(whipersnaper);

    Thing x = storage.getItem(0);

    x.doubleWeight();

    System.out.println(x.getWeight());
  }
}
</code>```

here is the "Thing" class

```<code>public class Thing
{
  private int weight;
  private String name;

  public Thing(int weight,String name){
    this.weight = weight;
    this.name = name;
  }

  public void doubleWeight(){
    this.weight *= 2;
  }

  public int getWeight(){
    return this.weight;
  }
}
</code>```

finally here is the List class

```<code>public class List
{
  private Object[] itemList;
  private int size;

  public List()
  {
    this.itemList = new Object[10];
    this.size = 0;
  }

  public void insert(Object item){
    itemList[size] = item;
    size++;
  }

  public Object getItem(int index){
    return itemList[index];
  }
}
</code>```

i need the list to be able to hold objects of any type and not exclusively Thing objects.
i have tried to google a solution but I cant find a good way to phrase the question to get an answer. thanks in advance.

答: Change that line Thing x = storage.getItem(0); with Thing x = (Thing) storage.getItem(0);

Body:
im having a problem calling a method i created for a class when it is returned from a list. I get a "java.lang.Object cannot be converted to Thing"
error when running the following code

public class Test1
{
  public static void main(String args[])
  {
    Thing whipersnaper = new Thing(30, "whipersnaper");
    List storage = new List();

    storage.insert(whipersnaper);

    Thing x = storage.getItem(0);

    x.doubleWeight();

    System.out.println(x.getWeight());
  }
}

here is the "Thing" class

public class Thing
{
  private int weight;
  private String name;

  public Thing(int weight,String name){
    this.weight = weight;
    this.name = name;
  }

  public void doubleWeight(){
    this.weight *= 2;
  }

  public int getWeight(){
    return this.weight;
  }
}

finally here is the List class

public class List
{
  private Object[] itemList;
  private int size;

  public List()
  {
    this.itemList = new Object[10];
    this.size = 0;
  }

  public void insert(Object item){
    itemList[size] = item;
    size++;
  }

  public Object getItem(int index){
    return itemList[index];
  }
}

i need the list to be able to hold objects of any type and not exclusively Thing objects.
i have tried to google a solution but I cant find a good way to phrase the question to get an answer. thanks in advance.


问:
get(int index) method in java
I am trying to do a get(int index) method that returns the element at the specified index in a list but I can't see what to return. What shall I have after tempNode in the end?

```<code>public E get(int index) throws IndexOutOfBoundsException {
    Node tempNode = head;
    if (index < 0 || index >= size) {
        throw new IllegalArgumentException("index was out of bounds");
    }
    for (int i = 0; i < index; i++) {
        tempNode = tempNode.getmNextNode();
    }
    return tempNode.;
}
</code>```

I am using the Node class:

```<code>public class Node<E> {
    private E mElement;
    private Node<E> mNextNode;

    Node(E data) {
        this.setmElement(data);
    }
    public E getmElement() {
        return this.mElement;
    }
    public void setmElement(E element) {
        this.mElement = element;
    }
    public Node<E> getmNextNode() {
        return this.mNextNode;
    }
    public void setmNextNode(Node<E> node) {
        this.mNextNode = node;
    }
}
</code>```

答:
You've got a getmElement() method on Node that will return the data you want.

However, currently your get(int) method is using a raw Node variable, so there's no way to ask it for the appropriate return type.  Currently tempNode.getmElement() will just return an Object.

What you need to do is use a Node<E> like so:

```<code>public E get(int index) throws IndexOutOfBoundsException {
    Node<E> tempNode = head;
    if (index < 0 || index >= size) {
        throw new IllegalArgumentException("index was out of bounds");
    }
    for (int i = 0; i < index; i++) {
        tempNode = tempNode.getmNextNode();
    }
    return tempNode.getmElement();
}
</code>```

Title: get(int index) method in java

Body:
I am trying to do a get(int index) method that returns the element at the specified index in a list but I can't see what to return. What shall I have after tempNode in the end?

public E get(int index) throws IndexOutOfBoundsException {
    Node tempNode = head;
    if (index < 0 || index >= size) {
        throw new IllegalArgumentException("index was out of bounds");
    }
    for (int i = 0; i < index; i++) {
        tempNode = tempNode.getmNextNode();
    }
    return tempNode.;
}

I am using the Node class:

public class Node<E> {
    private E mElement;
    private Node<E> mNextNode;

    Node(E data) {
        this.setmElement(data);
    }
    public E getmElement() {
        return this.mElement;
    }
    public void setmElement(E element) {
        this.mElement = element;
    }
    public Node<E> getmNextNode() {
        return this.mNextNode;
    }
    public void setmNextNode(Node<E> node) {
        this.mNextNode = node;
    }
}

Body:
You've got a getmElement() method on Node that will return the data you want.

However, currently your get(int) method is using a raw Node variable, so there's no way to ask it for the appropriate return type.  Currently tempNode.getmElement() will just return an Object.

What you need to do is use a Node<E> like so:

public E get(int index) throws IndexOutOfBoundsException {
    Node<E> tempNode = head;
    if (index < 0 || index >= size) {
        throw new IllegalArgumentException("index was out of bounds");
    }
    for (int i = 0; i < index; i++) {
        tempNode = tempNode.getmNextNode();
    }
    return tempNode.getmElement();
}


问:
"Infinite loop" while using Navigator.push()
I tried to use Navigator.push() method to load another page, but when I do this, it throws me errors while navigating on page, and then it restarts page loading and shows me the errors, and loading again, and errors again...

Here is the code for navigation :

```<code>return Future.delayed(Duration.zero, (){
        Navigator.of(context).push(MaterialPageRoute(builder: (context) => UserProfilePage(id, cookies)));
});
</code>```

Where id is my user ID, and cookies is a string list.

The errors thrown are :

RangeError (index): Invalid value: Valid value range is empty: 0
  See also: https://flutter.dev/docs/testing/errors

Invalid argument(s)
  See also: https://flutter.dev/docs/testing/errors

Here are the methods called when arriving in UserProfilePage :

```<code>_getUserProfile(BuildContext context, String userId) async
{
await HibooksApiController.getUserInfo(userId).then((response) {
  setState(() {
    var resultApi = json.decode(response.body);
    User result = User.fromJson(resultApi);
    user = result;
  });
});

for (var friend in user.friends) {
  _getFriendProfile(context, friend.id, friends);
}
}

_getFriendProfile(BuildContext context, String friendId, List<User> friends) async
{
await HibooksApiController.getUserInfo(friendId).then((response) {
  setState(() {
    var resultApi = json.decode(response.body);
    User result = User.fromJson(resultApi);
    friends.add(result);
  });
});
}

_getLibraries(BuildContext context, String userId) async
{
await HibooksApiController.getLibraries(userId).then((response){
  setState(() {
    var resultApi = json.decode(response.body);
    for (var item in resultApi) {
      Library library = Library.fromJson(item);
      libraries.add(library);
    }
  });
});
}
</code>```

答:
@MarianoZorrilla I implemented a Fragment Manager using an example I found, and here's the interaction :

```<code>_getDrawerItemWidget(int pos){
switch (pos) {
  // SIDEBAR
  case 0:
    return new Text("Nous");
  case 1:
    return new Text("Paramètes");
  case 2:
    return new Text("Langue");
  case 3:
    return new Text("Dictionnaire");
  case 4:
    return new Text("FAQ");
  case 5:
    return new Text("Politique de confidentialité");
    // --- HERE IS MY NAVIGATION PROBLEM --- //
  case 6:
      return Future.delayed(Duration.zero, (){
        Navigator.of(context).push(MaterialPageRoute(builder: (context) => UserProfilePage(id, cookies)));
      });
    // --- //
  case 7:
    return new Text("Informations du compte");
  case 8:
    return new Text("Mes Favoris");
  case 9:
    return Future.delayed(Duration.zero, () => Navigator.push(context, MaterialPageRoute(builder: (context) => LoginPage())));

  //BOTTOM NAVIGATION BAR
  case 10:
    return new AccueilFragment(id);
  case 11:
    return new LibraryFragment(id, cookies);
  case 12:
    return new ChatFragment(id, cookies);
  case 13:
    return new MatchFragment(id, cookies);
  case 14:
    return new Text("Événements");

  default:
    return new Text("Error");
}
}
</code>```

The method :

```<code> _onSelectItem(int drawerIndex) {
  setState(() => _selectedDrawerIndex = drawerIndex);
  Navigator.of(context).pop(); // close the drawer
 }
</code>```

The implementation :

```<code>var drawerOptions = <Widget>[];
drawerOptions.add(
  new SizedBox(
    height: 80,
    width: 350,
    child: new DrawerHeader(
      child: Text("Outils", style: TextStyle(fontFamily: "SFProDisplay")),
      decoration: BoxDecoration(color: Color.fromRGBO(247, 247, 247, 1.0)),
    ),
  )
);
for (var i = 0; i <= 5; i++) {
  var d = widget.drawerItems[i];
  drawerOptions.add(
    new ListTile(
      leading: new SizedBox(child: d.icon,),
      title: new Text(d.title, style: TextStyle(fontFamily: "SFProDisplay")),
      selected: i == _selectedDrawerIndex,
      onTap: () => _onSelectItem(i),
    )
  );
}
drawerOptions.add(
  new SizedBox(
    height: 80,
    width: 350,
    child: new DrawerHeader(
      child: Text("Profil", style: TextStyle(fontFamily: "SFProDisplay")),
      decoration: BoxDecoration(color: Color.fromRGBO(247, 247, 247, 1.0)),
    ),
  )
);
for(var j = 6; j <= 9; j++)
{
  var d2 = widget.drawerItems[j];
  drawerOptions.add(
    new ListTile(
      leading: new SizedBox(child: d2.icon,),
      title: new Text(d2.title, style: TextStyle(fontFamily: "SFProDisplay")),
      selected: j == _selectedDrawerIndex,
      onTap: () => _onSelectItem(j),
    )
  );
}

for (var i = 10; i < widget.drawerItems.length; i++) {
  var d = widget.drawerItems[i];
  navbarOptions.add(
    new BottomNavigationBarItem(
      icon: new SizedBox(child: d.icon,),
      title: Text(d.title),
    )
  );
}

if(navbarOptions.length != 0)
{
  for(var z = navbarOptions.length; z > 5; z--)
  {
    navbarOptions.removeLast();
  }
}
</code>```

And the call, in my Widget build() :

```<code>return new Scaffold(
  appBar: new AppBar(
    leading: Builder(builder: (BuildContext context) {
      return new GestureDetector(
        onTap: (){
          Scaffold.of(context).openDrawer();
        },
        child: Material(
          shape: CircleBorder(),
          child: ClipOval(
            child: FadeInImage(
              placeholder: new ExactAssetImage("assets/Pictogramme-fond-blanc.png", scale: 4.5),
              image: NetworkImage(user.image.url),
              height: 50,
              width: 50,
              fit: BoxFit.cover,
            ),
          ),

        )
      );
    }),
    title: Text(
      user.name.first != "" || user.name.last != "" ? "${user.name.first} ${user.name.last[0]}." : "${user.username}",
      style: TextStyle(color: Colors.black),
    ),
    backgroundColor: Color(0xFFFFFFFF),
  ),
  drawer: new Drawer(
    child: new SingleChildScrollView(
      child: new Column(
        children: <Widget>[
          new Column(children: drawerOptions),
        ],
      ),
    ),
  ),
  body: _getDrawerItemWidget(_selectedDrawerIndex),

  bottomNavigationBar: BottomNavigationBar(
    items: navbarOptions,
    currentIndex: _selectedNavbarIndex,
    selectedItemColor: hibooks,
    onTap: _onItemTapped,
  ),
);
</code>```

Also, all of these methods worked when I developed them, but the bug started when I upgraded Flutter to version "1.12.13+hotfix.5" .

Body:
I tried to use Navigator.push() method to load another page, but when I do this, it throws me errors while navigating on page, and then it restarts page loading and shows me the errors, and loading again, and errors again...

Here is the code for navigation :

return Future.delayed(Duration.zero, (){
        Navigator.of(context).push(MaterialPageRoute(builder: (context) => UserProfilePage(id, cookies)));
});

Where id is my user ID, and cookies is a string list.

The errors thrown are :

RangeError (index): Invalid value: Valid value range is empty: 0
  See also: https://flutter.dev/docs/testing/errors

Invalid argument(s)
  See also: https://flutter.dev/docs/testing/errors

Here are the methods called when arriving in UserProfilePage :

_getUserProfile(BuildContext context, String userId) async
{
await HibooksApiController.getUserInfo(userId).then((response) {
  setState(() {
    var resultApi = json.decode(response.body);
    User result = User.fromJson(resultApi);
    user = result;
  });
});

for (var friend in user.friends) {
  _getFriendProfile(context, friend.id, friends);
}
}

_getFriendProfile(BuildContext context, String friendId, List<User> friends) async
{
await HibooksApiController.getUserInfo(friendId).then((response) {
  setState(() {
    var resultApi = json.decode(response.body);
    User result = User.fromJson(resultApi);
    friends.add(result);
  });
});
}

_getLibraries(BuildContext context, String userId) async
{
await HibooksApiController.getLibraries(userId).then((response){
  setState(() {
    var resultApi = json.decode(response.body);
    for (var item in resultApi) {
      Library library = Library.fromJson(item);
      libraries.add(library);
    }
  });
});
}

Body:
@MarianoZorrilla I implemented a Fragment Manager using an example I found, and here's the interaction :

_getDrawerItemWidget(int pos){
switch (pos) {
  // SIDEBAR
  case 0:
    return new Text("Nous");
  case 1:
    return new Text("Paramètes");
  case 2:
    return new Text("Langue");
  case 3:
    return new Text("Dictionnaire");
  case 4:
    return new Text("FAQ");
  case 5:
    return new Text("Politique de confidentialité");
    // --- HERE IS MY NAVIGATION PROBLEM --- //
  case 6:
      return Future.delayed(Duration.zero, (){
        Navigator.of(context).push(MaterialPageRoute(builder: (context) => UserProfilePage(id, cookies)));
      });
    // --- //
  case 7:
    return new Text("Informations du compte");
  case 8:
    return new Text("Mes Favoris");
  case 9:
    return Future.delayed(Duration.zero, () => Navigator.push(context, MaterialPageRoute(builder: (context) => LoginPage())));

  //BOTTOM NAVIGATION BAR
  case 10:
    return new AccueilFragment(id);
  case 11:
    return new LibraryFragment(id, cookies);
  case 12:
    return new ChatFragment(id, cookies);
  case 13:
    return new MatchFragment(id, cookies);
  case 14:
    return new Text("Événements");

  default:
    return new Text("Error");
}
}

The method :

 _onSelectItem(int drawerIndex) {
  setState(() => _selectedDrawerIndex = drawerIndex);
  Navigator.of(context).pop(); // close the drawer
 }

The implementation :

var drawerOptions = <Widget>[];
drawerOptions.add(
  new SizedBox(
    height: 80,
    width: 350,
    child: new DrawerHeader(
      child: Text("Outils", style: TextStyle(fontFamily: "SFProDisplay")),
      decoration: BoxDecoration(color: Color.fromRGBO(247, 247, 247, 1.0)),
    ),
  )
);
for (var i = 0; i <= 5; i++) {
  var d = widget.drawerItems[i];
  drawerOptions.add(
    new ListTile(
      leading: new SizedBox(child: d.icon,),
      title: new Text(d.title, style: TextStyle(fontFamily: "SFProDisplay")),
      selected: i == _selectedDrawerIndex,
      onTap: () => _onSelectItem(i),
    )
  );
}
drawerOptions.add(
  new SizedBox(
    height: 80,
    width: 350,
    child: new DrawerHeader(
      child: Text("Profil", style: TextStyle(fontFamily: "SFProDisplay")),
      decoration: BoxDecoration(color: Color.fromRGBO(247, 247, 247, 1.0)),
    ),
  )
);
for(var j = 6; j <= 9; j++)
{
  var d2 = widget.drawerItems[j];
  drawerOptions.add(
    new ListTile(
      leading: new SizedBox(child: d2.icon,),
      title: new Text(d2.title, style: TextStyle(fontFamily: "SFProDisplay")),
      selected: j == _selectedDrawerIndex,
      onTap: () => _onSelectItem(j),
    )
  );
}

for (var i = 10; i < widget.drawerItems.length; i++) {
  var d = widget.drawerItems[i];
  navbarOptions.add(
    new BottomNavigationBarItem(
      icon: new SizedBox(child: d.icon,),
      title: Text(d.title),
    )
  );
}

if(navbarOptions.length != 0)
{
  for(var z = navbarOptions.length; z > 5; z--)
  {
    navbarOptions.removeLast();
  }
}

And the call, in my Widget build() :

return new Scaffold(
  appBar: new AppBar(
    leading: Builder(builder: (BuildContext context) {
      return new GestureDetector(
        onTap: (){
          Scaffold.of(context).openDrawer();
        },
        child: Material(
          shape: CircleBorder(),
          child: ClipOval(
            child: FadeInImage(
              placeholder: new ExactAssetImage("assets/Pictogramme-fond-blanc.png", scale: 4.5),
              image: NetworkImage(user.image.url),
              height: 50,
              width: 50,
              fit: BoxFit.cover,
            ),
          ),

        )
      );
    }),
    title: Text(
      user.name.first != "" || user.name.last != "" ? "${user.name.first} ${user.name.last[0]}." : "${user.username}",
      style: TextStyle(color: Colors.black),
    ),
    backgroundColor: Color(0xFFFFFFFF),
  ),
  drawer: new Drawer(
    child: new SingleChildScrollView(
      child: new Column(
        children: <Widget>[
          new Column(children: drawerOptions),
        ],
      ),
    ),
  ),
  body: _getDrawerItemWidget(_selectedDrawerIndex),

  bottomNavigationBar: BottomNavigationBar(
    items: navbarOptions,
    currentIndex: _selectedNavbarIndex,
    selectedItemColor: hibooks,
    onTap: _onItemTapped,
  ),
);

Also, all of these methods worked when I developed them, but the bug started when I upgraded Flutter to version "1.12.13+hotfix.5" .


问:
php Curl clicked links
I need any link that has a "a href=" tag when clicked to be received via curl. I can't hard code these links as they are from a dynamic site so could be anything. How would I achieve this?

Thanks

Edit: Let me explain more. I have an app on my pc that uses a web front end. It catalogs files and gives yo options to rename delete etc. I want to add a public view however if I put it as is online then anyone can delete rename files. If I curl the pages I can remove the menu bars and editing options through the use of a different css. That part all works. The only part that isn't working is if I click on a link on the page it directs me back to the original link address and that defeats the point as the menu bars are back. I need it to curl the clicked links. Hope that makes more sense..

Here is my code that fetches the original link and curls that and changes the css to point to my own css. It points the java script to the original as I dont need to change that. I now need to make the "a href" links on the page when clicked be called by curl and not go to the original destination

```<code><?php

$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, 'http://192.168.0.14:8081/home/');
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
$curl_response = curl_exec($ch);
curl_close($ch);

//Change link url

$link = $curl_response;

$linkgo = '/sickbeard_public';
$linkfind = 'href="';
$linkreplace = 'href="' . $linkgo ;

$link = str_replace($linkfind, $linkreplace, $link);

//Change js url
$js = $link;

$jsgo = 'http://192.168.0.14:8081';
$jsfind = 'src="';
$jsreplace = 'src="' . $jsgo ;

$js = str_replace($jsfind, $jsreplace, $js);

//Fix on page link errors
$alink = $js;
$alinkgo = 'http://192.168.0.14:8081/';
$alinkfind = 'a href="/sickbeard_public/';
$alinkreplace = 'a href="' . $alinkgo ;

$alink = str_replace($alinkfind, $alinkreplace, $alink);

//Echo page back
echo $alink;

?>
</code>```

答:
As far as I can understand your question you need to get the contents of URL via CURL... so here is the solution

```<code><a href="<?php print $my_url; ?>" id="my_link">Click here to get via curl </a>
</code>```

Then attach an event with the above  tag, e.g. in JQuery

```<code>$("#my_link").click(function(){
   var target_url = $(this).attr("href");
   //Send an ajax call to some of your page like cURL_wrapper.php with target_url as parameter in get
});
</code>```

then in cURL_wrapper.php do follwoing

```<code><?php
//Get the $target_url here from $_GET[];
$ch = curl_init($your_domain");
$fp = fopen("$target_url", "r");

curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);

curl_exec($ch);
curl_close($ch);
fclose($fp);
?>
</code>```

Title: php Curl clicked links

Body:
I need any link that has a "a href=" tag when clicked to be received via curl. I can't hard code these links as they are from a dynamic site so could be anything. How would I achieve this?

Thanks

Edit: Let me explain more. I have an app on my pc that uses a web front end. It catalogs files and gives yo options to rename delete etc. I want to add a public view however if I put it as is online then anyone can delete rename files. If I curl the pages I can remove the menu bars and editing options through the use of a different css. That part all works. The only part that isn't working is if I click on a link on the page it directs me back to the original link address and that defeats the point as the menu bars are back. I need it to curl the clicked links. Hope that makes more sense..

Here is my code that fetches the original link and curls that and changes the css to point to my own css. It points the java script to the original as I dont need to change that. I now need to make the "a href" links on the page when clicked be called by curl and not go to the original destination

<?php

$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, 'http://192.168.0.14:8081/home/');
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
$curl_response = curl_exec($ch);
curl_close($ch);

//Change link url

$link = $curl_response;

$linkgo = '/sickbeard_public';
$linkfind = 'href="';
$linkreplace = 'href="' . $linkgo ;

$link = str_replace($linkfind, $linkreplace, $link);

//Change js url
$js = $link;

$jsgo = 'http://192.168.0.14:8081';
$jsfind = 'src="';
$jsreplace = 'src="' . $jsgo ;

$js = str_replace($jsfind, $jsreplace, $js);

//Fix on page link errors
$alink = $js;
$alinkgo = 'http://192.168.0.14:8081/';
$alinkfind = 'a href="/sickbeard_public/';
$alinkreplace = 'a href="' . $alinkgo ;

$alink = str_replace($alinkfind, $alinkreplace, $alink);

//Echo page back
echo $alink;

?>

Body:
As far as I can understand your question you need to get the contents of URL via CURL... so here is the solution

<a href="<?php print $my_url; ?>" id="my_link">Click here to get via curl </a>

Then attach an event with the above <a> tag, e.g. in JQuery

$("#my_link").click(function(){
   var target_url = $(this).attr("href");
   //Send an ajax call to some of your page like cURL_wrapper.php with target_url as parameter in get
});

then in cURL_wrapper.php do follwoing

<?php
//Get the $target_url here from $_GET[];
$ch = curl_init($your_domain");
$fp = fopen("$target_url", "r");

curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);

curl_exec($ch);
curl_close($ch);
fclose($fp);
?>


问:
Track cell changes in comments in named ranges
I have a code that looks if any cell in Sheet1 has been changed. All the cells are formulas, so that's why I am using Worksheet_Calculate. If it's changed, it makes sure the user wants to record the old value as a comment.

```<code>Dim cache As Variant

Private Sub Workbook_Open()
    cache = getSheetValues(Sheet1)
End Sub

Private Function getSheetValues(sheet As Worksheet) As Variant
    Dim arr As Variant
    Dim cell As Range

'    Get last cell in the used range
    Set cell = sheet.Cells.SpecialCells(xlCellTypeLastCell)
    ' Get all values in the range between A1 and that cell
    arr = sheet.Cells.Resize(cell.Row, cell.Column)
    If IsEmpty(arr) Then ReDim arr(0, 0) ' Default if no data at all
    getSheetValues = arr

End Function

Private Sub Workbook_SheetCalculate(ByVal Sh As Object)
    Dim current As Variant
    Dim previous As Variant
    Dim i As Long
    Dim j As Long
    Dim prevVal As Variant
    Dim currVal As Variant

    If Sh.CodeName <> Sheet1.CodeName Then Exit Sub
    ' Get the values of the sheet and from the cache
    previous = cache
    current = getSheetValues(Sh)
    For i = 1 To WorksheetFunction.Max(UBound(previous), UBound(current))
        For j = 1 To WorksheetFunction.Max(UBound(previous, 2), UBound(current, 2))
            prevVal = ""
            currVal = ""
            On Error Resume Next ' Ignore errors when out of array bounds
                prevVal = previous(i, j)
                currVal = current(i, j)
            On Error GoTo 0
            If prevVal <> currVal Then
                ' Change detected: call the function that will treat this
                CellChanged Sheet1.Cells(i, j), prevVal
            End If
        Next
    Next
    ' Update cache
    cache = current
ext:
End Sub

Private Sub CellChanged(cell As Range, oldValue As Variant)

Dim answer As Integer
    ' This is the place where you would put your logic

    Sheet1.Activate

    answer = MsgBox("Changement de casier!" & Chr(10) & "Garder l'historique de " & Chr(10) & """" & oldValue & """?", _
    vbQuestion + vbYesNo, "Attention")

    If answer = vbYes Then

    cell.ClearComments
    cell.AddComment.Text Text:=oldValue & Chr(10) & Format(Date, "dd-mm-yyyy")

    Else: Exit Sub

    End If

End Sub
</code>```

This works fine. However, I don't want it to be looking at the whole sheet. I want it to be looking at 3 named ranges. Tried changing getSheetValues = Range("Colonne8300") but it doesn't work.

答:
getSheetValues expects a worksheet object, if you want to send it a range (i.e. use getSheetValues = Range("Colonne8300")) then you need to change the function to accept a range:

```<code>Private Function getSheetValues(myRange As Range) As Variant
</code>```

Then modify the function to use myRange instead of all cells in the worksheet.

Body:
I have a code that looks if any cell in Sheet1 has been changed. All the cells are formulas, so that's why I am using Worksheet_Calculate. If it's changed, it makes sure the user wants to record the old value as a comment.

Dim cache As Variant

Private Sub Workbook_Open()
    cache = getSheetValues(Sheet1)
End Sub

Private Function getSheetValues(sheet As Worksheet) As Variant
    Dim arr As Variant
    Dim cell As Range

'    Get last cell in the used range
    Set cell = sheet.Cells.SpecialCells(xlCellTypeLastCell)
    ' Get all values in the range between A1 and that cell
    arr = sheet.Cells.Resize(cell.Row, cell.Column)
    If IsEmpty(arr) Then ReDim arr(0, 0) ' Default if no data at all
    getSheetValues = arr

End Function

Private Sub Workbook_SheetCalculate(ByVal Sh As Object)
    Dim current As Variant
    Dim previous As Variant
    Dim i As Long
    Dim j As Long
    Dim prevVal As Variant
    Dim currVal As Variant

    If Sh.CodeName <> Sheet1.CodeName Then Exit Sub
    ' Get the values of the sheet and from the cache
    previous = cache
    current = getSheetValues(Sh)
    For i = 1 To WorksheetFunction.Max(UBound(previous), UBound(current))
        For j = 1 To WorksheetFunction.Max(UBound(previous, 2), UBound(current, 2))
            prevVal = ""
            currVal = ""
            On Error Resume Next ' Ignore errors when out of array bounds
                prevVal = previous(i, j)
                currVal = current(i, j)
            On Error GoTo 0
            If prevVal <> currVal Then
                ' Change detected: call the function that will treat this
                CellChanged Sheet1.Cells(i, j), prevVal
            End If
        Next
    Next
    ' Update cache
    cache = current
ext:
End Sub

Private Sub CellChanged(cell As Range, oldValue As Variant)

Dim answer As Integer
    ' This is the place where you would put your logic

    Sheet1.Activate

    answer = MsgBox("Changement de casier!" & Chr(10) & "Garder l'historique de " & Chr(10) & """" & oldValue & """?", _
    vbQuestion + vbYesNo, "Attention")

    If answer = vbYes Then

    cell.ClearComments
    cell.AddComment.Text Text:=oldValue & Chr(10) & Format(Date, "dd-mm-yyyy")

    Else: Exit Sub

    End If

End Sub

This works fine. However, I don't want it to be looking at the whole sheet. I want it to be looking at 3 named ranges. Tried changing getSheetValues = Range("Colonne8300") but it doesn't work.

Body:
getSheetValues expects a worksheet object, if you want to send it a range (i.e. use getSheetValues = Range("Colonne8300")) then you need to change the function to accept a range:

Private Function getSheetValues(myRange As Range) As Variant

Then modify the function to use myRange instead of all cells in the worksheet.