问:
How to easily diagnose problems due to access to unmapped mmap regions?
I've recently found a segfault that neither Valgrind, nor Address Sanitizer could give any useful info about. It happened because the faulty program munmapped a file and then tried to access the formerly mmapped region.

The following example demonstrates the problem:

#include <stdio.h>
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/mman.h>

int main()
{
    const int fd=open("/tmp/test.txt", O_RDWR);
    if(fd<0) abort();
    const char buf[]="Hello";
    if(write(fd, buf, sizeof buf) != sizeof buf) abort();

    char*const volatile ptr=mmap(NULL,sizeof buf,PROT_READ,MAP_SHARED,fd,0);
    if(!ptr) abort();
    printf("1%c\n", ptr[0]);

    if(close(fd)<0) abort();
    printf("2%c\n", ptr[0]);

    if(munmap(ptr, sizeof buf)<0) abort();
    printf("3%c\n", ptr[0]); // Cause a segfault
}
```

<p>With Address Sanitizer I get the following output:</p>

<pre class="lang-none prettyprint-override"><code>1H
2H
AddressSanitizer:DEADLYSIGNAL
=================================================================
==8503==ERROR: AddressSanitizer: SEGV on unknown address 0x7fe7d0836000 (pc 0x55bda425c055 bp 0x7ffda5887210 sp 0x7ffda5887140 T0)
==8503==The signal is caused by a READ memory access.
    #0 0x55bda425c054 in main /tmp/test/test1.c:22
    #1 0x7fe7cf64fb96 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x21b96)
    #2 0x55bda425bcd9 in _start (/tmp/test/test1+0xcd9)

AddressSanitizer can not provide additional info.
SUMMARY: AddressSanitizer: SEGV /tmp/test/test1.c:22 in main
</code>```

And here's the relevant part of output with Valgrind:

1H
2H
==8863== Invalid read of size 1
==8863==    at 0x108940: main (test1.c:22)
==8863==  Address 0x4029000 is not stack'd, malloc'd or (recently) free'd
==8863==
==8863==
==8863== Process terminating with default action of signal 11 (SIGSEGV)
==8863==  Access not within mapped region at address 0x4029000
==8863==    at 0x108940: main (test1.c:22)
```

<p>Compare this with the case when a <code>malloc</code>ed region is accessed after <code>free</code>. Test program:</p>

<pre class="lang-c prettyprint-override"><code>#include <stdio.h>
#include <string.h>
#include <malloc.h>

int main()
{
    const char buf[]="Hello";
    char*const volatile ptr=malloc(sizeof buf);
    if(!ptr)
    {
        fprintf(stderr, "malloc failed");
        return 1;
    }
    memcpy(ptr,buf,sizeof buf);
    printf("1%c\n", ptr[0]);
    free(ptr);
    printf("2%c\n", ptr[0]); // Cause a segfault
}
</code>```

Output with Address Sanitizer:

1H
=================================================================
==7057==ERROR: AddressSanitizer: heap-use-after-free on address 0x602000000010 at pc 0x55b8f96b5003 bp 0x7ffff5179b70 sp 0x7ffff5179b60
READ of size 1 at 0x602000000010 thread T0
    #0 0x55b8f96b5002 in main /tmp/test/test1.c:17
    #1 0x7f4298fd8b96 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x21b96)
    #2 0x55b8f96b4c49 in _start (/tmp/test/test1+0xc49)

0x602000000010 is located 0 bytes inside of 6-byte region [0x602000000010,0x602000000016)
freed by thread T0 here:
    #0 0x7f42994b3b4f in free (/usr/lib/x86_64-linux-gnu/libasan.so.5+0x10bb4f)
    #1 0x55b8f96b4fca in main /tmp/test/test1.c:16
    #2 0x7f4298fd8b96 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x21b96)

previously allocated by thread T0 here:
    #0 0x7f42994b3f48 in __interceptor_malloc (/usr/lib/x86_64-linux-gnu/libasan.so.5+0x10bf48)
    #1 0x55b8f96b4e25 in main /tmp/test/test1.c:8
    #2 0x7f4298fd8b96 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x21b96)
```

<p>Output with Valgrind:</p>

<pre class="lang-none prettyprint-override"><code>1H
==6888== Invalid read of size 1
==6888==    at 0x108845: main (test1.c:17)
==6888==  Address 0x522d040 is 0 bytes inside a block of size 6 free'd
==6888==    at 0x4C30D3B: free (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==6888==    by 0x108840: main (test1.c:16)
==6888==  Block was alloc'd at
==6888==    at 0x4C2FB0F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==6888==    by 0x1087D2: main (test1.c:8)
</code>```

My question: is there any way to make Valgrind or a Sanitizer, or some other Linux-compatible tool output useful diagnostic about the context of access to munmapped region (like where it had been mmapped and munmapped), similar to the above given output for the access-after-free?

答:
is there any way to make Valgrind or a Sanitizer, or some other Linux-compatible tool output useful diagnostic

I know of no such tool, although it would be relatively easy to make one.

Your problem is sufficiently different from heap corruption problems which require specialized tools, and probably doesn't need such a tool.

The major difference is the "action at a distance" aspect: with heap corruption, the code in which the problem manifests is often very far removed from the code in which the problem originates. Hence the need to track memory state, to have red zones, etc.

In your case, the access to munmapped memory results in immediate crash. So if you just log every mmap and munmap that your program performs, you'll only have to look back for the last munmap that "covered" the address on which you crashed.

In addition, most programs perform relatively few mmap and munmap operations. If your program performs so many that you can't log them all, it's likely that it shouldn't actually do that (mmap and munmap are relatively very expensive system calls).

Body:
I've recently found a segfault that neither Valgrind, nor Address Sanitizer could give any useful info about. It happened because the faulty program munmapped a file and then tried to access the formerly mmapped region.

The following example demonstrates the problem:

#include <stdio.h>
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/mman.h>

int main()
{
    const int fd=open("/tmp/test.txt", O_RDWR);
    if(fd<0) abort();
    const char buf[]="Hello";
    if(write(fd, buf, sizeof buf) != sizeof buf) abort();

    char*const volatile ptr=mmap(NULL,sizeof buf,PROT_READ,MAP_SHARED,fd,0);
    if(!ptr) abort();
    printf("1%c\n", ptr[0]);

    if(close(fd)<0) abort();
    printf("2%c\n", ptr[0]);

    if(munmap(ptr, sizeof buf)<0) abort();
    printf("3%c\n", ptr[0]); // Cause a segfault
}

With Address Sanitizer I get the following output:

1H
2H
AddressSanitizer:DEADLYSIGNAL
=================================================================
==8503==ERROR: AddressSanitizer: SEGV on unknown address 0x7fe7d0836000 (pc 0x55bda425c055 bp 0x7ffda5887210 sp 0x7ffda5887140 T0)
==8503==The signal is caused by a READ memory access.
    #0 0x55bda425c054 in main /tmp/test/test1.c:22
    #1 0x7fe7cf64fb96 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x21b96)
    #2 0x55bda425bcd9 in _start (/tmp/test/test1+0xcd9)

AddressSanitizer can not provide additional info.
SUMMARY: AddressSanitizer: SEGV /tmp/test/test1.c:22 in main

And here's the relevant part of output with Valgrind:

1H
2H
==8863== Invalid read of size 1
==8863==    at 0x108940: main (test1.c:22)
==8863==  Address 0x4029000 is not stack'd, malloc'd or (recently) free'd
==8863==
==8863==
==8863== Process terminating with default action of signal 11 (SIGSEGV)
==8863==  Access not within mapped region at address 0x4029000
==8863==    at 0x108940: main (test1.c:22)

Compare this with the case when a malloced region is accessed after free. Test program:

#include <stdio.h>
#include <string.h>
#include <malloc.h>

int main()
{
    const char buf[]="Hello";
    char*const volatile ptr=malloc(sizeof buf);
    if(!ptr)
    {
        fprintf(stderr, "malloc failed");
        return 1;
    }
    memcpy(ptr,buf,sizeof buf);
    printf("1%c\n", ptr[0]);
    free(ptr);
    printf("2%c\n", ptr[0]); // Cause a segfault
}

Output with Address Sanitizer:

1H
=================================================================
==7057==ERROR: AddressSanitizer: heap-use-after-free on address 0x602000000010 at pc 0x55b8f96b5003 bp 0x7ffff5179b70 sp 0x7ffff5179b60
READ of size 1 at 0x602000000010 thread T0
    #0 0x55b8f96b5002 in main /tmp/test/test1.c:17
    #1 0x7f4298fd8b96 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x21b96)
    #2 0x55b8f96b4c49 in _start (/tmp/test/test1+0xc49)

0x602000000010 is located 0 bytes inside of 6-byte region [0x602000000010,0x602000000016)
freed by thread T0 here:
    #0 0x7f42994b3b4f in free (/usr/lib/x86_64-linux-gnu/libasan.so.5+0x10bb4f)
    #1 0x55b8f96b4fca in main /tmp/test/test1.c:16
    #2 0x7f4298fd8b96 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x21b96)

previously allocated by thread T0 here:
    #0 0x7f42994b3f48 in __interceptor_malloc (/usr/lib/x86_64-linux-gnu/libasan.so.5+0x10bf48)
    #1 0x55b8f96b4e25 in main /tmp/test/test1.c:8
    #2 0x7f4298fd8b96 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x21b96)

Output with Valgrind:

1H
==6888== Invalid read of size 1
==6888==    at 0x108845: main (test1.c:17)
==6888==  Address 0x522d040 is 0 bytes inside a block of size 6 free'd
==6888==    at 0x4C30D3B: free (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==6888==    by 0x108840: main (test1.c:16)
==6888==  Block was alloc'd at
==6888==    at 0x4C2FB0F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==6888==    by 0x1087D2: main (test1.c:8)

My question: is there any way to make Valgrind or a Sanitizer, or some other Linux-compatible tool output useful diagnostic about the context of access to munmapped region (like where it had been mmapped and munmapped), similar to the above given output for the access-after-free?


来源: stackexchange

问:
chart.js load totally new data
The API for chart.js allows one to edit points of the datasets loaded into it, for example:

.update( )

Calling update() on your Chart instance will re-render the chart with
  any updated values, allowing you to edit the value of multiple
  existing points, then render those in one animated render loop.

.addData( valuesArray, label )

Calling addData(valuesArray, label) on your Chart instance passing an
  array of values for each dataset, along with a label for those points.

.removeData( )

Calling removeData() on your Chart instance will remove the first
  value for all datasets on the chart.

All of these are great, but I cannot figure out how to load an entirely new dataset in, wiping out the old. The documentation does not seem to cover this.

答:
Not is necesary destroy the chart. Try with this</p>

```<code>function removeData(chart) {

        let total = chart.data.labels.length;

        while (total >= 0) {
            chart.data.labels.pop();
            chart.data.datasets[0].data.pop();
            total--;
        }

        chart.update();
    }
</code>```

ContentLicense: CC BY-SA 3.0

Title: chart.js load totally new data

Body:
Not is necesary destroy the chart. Try with this

function removeData(chart) {

        let total = chart.data.labels.length;

        while (total >= 0) {
            chart.data.labels.pop();
            chart.data.datasets[0].data.pop();
            total--;
        }

        chart.update();
    }

ContentLicense: CC BY-SA 4.0


问:
why cant I view a struct value on the previous view controller
I'm pretty new to Objective-C (and C itself) so this is probably really easy, but I'm a bit stuck.

I've got a view controller that requires some input from the user, I have a table view that has a row for a latitude and longitude value. When the user taps that row, it takes them to a new view controller with a map view on it.

I've got a marker for them to drag and pick out their location:

```<code>- (void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)annotationView
didChangeDragState:(MKAnnotationViewDragState)newState fromOldState:(MKAnnotationViewDragState)oldState
</code>```

In this method I want to update the previous view controller with the new coordinates.

It has a property:

```<code>CLLocationCoordinate2D destinationCoordinates;
</code>```

which I've set as nonatomic, assign and synthesized

My code does this:

```<code>NSArray *allControllers = self.navigationController.viewControllers;

EnterDetailsViewController *parent = [allControllers objectAtIndex:([allControllers count] -2)];

if ([parent isKindOfClass:[EnterDetailsViewController class]])
{
    CLLocationCoordinate2D theCoordinate;
    theCoordinate.latitude = annotation.coordinate.latitude;
    theCoordinate.longitude =  annotation.coordinate.longitude;

    parent.destinationCoordinates = theCoordinate;

    NSLog(@"Set coord to %@ - %@",
          parent.destinationCoordinates.latitude,
          parent.destinationCoordinates.latitude);
</code>```

But the NSLog always crashes with an EXC_BAD_ACCESS - why is this? What core concept am I misunderstanding here?

答:
The definition of CLLocationCoordinate2D is:

```<code>typedef struct {
  CLLocationDegrees latitude;
  CLLocationDegrees longitude;
} CLLocationCoordinate2D;
</code>```

Your using %@ to print an object, try instead:

```<code>NSLog(@"Set coord to %f - %f",
      parent.destinationCoordinates.latitude,
      parent.destinationCoordinates.longitude);
</code>```

Note that CLLocationDegrees is of type double:

```<code>typedef double CLLocationDegrees;
</code>```

Body:
I'm pretty new to Objective-C (and C itself) so this is probably really easy, but I'm a bit stuck.

I've got a view controller that requires some input from the user, I have a table view that has a row for a latitude and longitude value. When the user taps that row, it takes them to a new view controller with a map view on it.

I've got a marker for them to drag and pick out their location:

- (void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)annotationView
didChangeDragState:(MKAnnotationViewDragState)newState fromOldState:(MKAnnotationViewDragState)oldState

In this method I want to update the previous view controller with the new coordinates.

It has a property:

CLLocationCoordinate2D destinationCoordinates;

which I've set as nonatomic, assign and synthesized

My code does this:

NSArray *allControllers = self.navigationController.viewControllers;

EnterDetailsViewController *parent = [allControllers objectAtIndex:([allControllers count] -2)];

if ([parent isKindOfClass:[EnterDetailsViewController class]])
{
    CLLocationCoordinate2D theCoordinate;
    theCoordinate.latitude = annotation.coordinate.latitude;
    theCoordinate.longitude =  annotation.coordinate.longitude;

    parent.destinationCoordinates = theCoordinate;

    NSLog(@"Set coord to %@ - %@",
          parent.destinationCoordinates.latitude,
          parent.destinationCoordinates.latitude);

But the NSLog always crashes with an EXC_BAD_ACCESS - why is this? What core concept am I misunderstanding here?

Body:
The definition of CLLocationCoordinate2D is:

typedef struct {
  CLLocationDegrees latitude;
  CLLocationDegrees longitude;
} CLLocationCoordinate2D;

Your using %@ to print an object, try instead:

NSLog(@"Set coord to %f - %f",
      parent.destinationCoordinates.latitude,
      parent.destinationCoordinates.longitude);

Note that CLLocationDegrees is of type double:

typedef double CLLocationDegrees;


问:
Setting state along with AsyncStorage in useEffect hook causes infinite loop?
I'm new to hooks and recently started using hooks in my React Native projects.

I'm building a simple todo app using the AsyncStorage. First I initialize initial data and setData state using useState hook:

```<code>const [data, setData] = useState([]);
</code>```

There are two textInput and submit button that I use to save data to AsyncStorage. Here is the saveData function:

```<code>const saveData = async () => {
  const arrData = [{ name: 'vikrant', phone: 123456 }]; // [{ name, phone}] from the textInput

  const storedData = await AsyncStorage.getItem('user');
  const storedDataParsed = JSON.parse(storedData);

  let newData = [];

  if (storedData === null) {
    // save
    await AsyncStorage.setItem('user', JSON.stringify(arrData));
  } else {
    newData = [...storedDataParsed, user];
    await AsyncStorage.setItem('user', JSON.stringify(newData));
  }
  setName('');
  setPhone('');
  Keyboard.dismiss();
};
</code>```

Now, I'm using useEffect to get data from the AsyncStorage and setting it to the data state. I'm using data to render the text in the screen.

```<code>useEffect(() => {
  retrieveData();
}, [data]);

const retrieveData = async () => {
  try {
    const valueString = await AsyncStorage.getItem('user');
    const value = JSON.parse(valueString);
    setData(value);
  } catch (error) {
    console.log(error);
  }
};
</code>```

I'm using [data] in useEffect since I want to re-render my component each time  data changes i.e. each time I save data in AsyncStorage. But this is causing infinite loop as setData causes useEffect to run infinitely.

If I remove data from the [] it doesn't loop but my data in render is one step behind. So whenever I save data it doesn't show the current data but the previous one.

Any explanation of what I am doing wrong here and how can i fix this?

Thanks.

答:
As already mentioned by you, the infinite loop is due to thefact that you pass data as a dependency to useEffect and also set in inside the function called in useEffect.

The solution here is to not use useEffect and instead setData whenever you are setting value in AsyncStorage

```<code>const saveData = async () => {
  const arrData = [{ name: 'vikrant', phone: 123456 }]; // [{ name, phone}] from the textInput

  const storedData = await AsyncStorage.getItem('user');
  const storedDataParsed = JSON.parse(storedData);

  let newData = [];

  if (storedData === null) {
    // save
    await AsyncStorage.setItem('user', JSON.stringify(arrData));
  } else {
    newData = [...storedDataParsed, user];
    await AsyncStorage.setItem('user', JSON.stringify(newData));
  }
  setName('');
  setPhone('');
  setData(newData);
  Keyboard.dismiss();
};
</code>```

Body:
I'm new to hooks and recently started using hooks in my React Native projects.

I'm building a simple todo app using the AsyncStorage. First I initialize initial data and setData state using useState hook:

const [data, setData] = useState([]);

There are two textInput and submit button that I use to save data to AsyncStorage. Here is the saveData function:

const saveData = async () => {
  const arrData = [{ name: 'vikrant', phone: 123456 }]; // [{ name, phone}] from the textInput

  const storedData = await AsyncStorage.getItem('user');
  const storedDataParsed = JSON.parse(storedData);

  let newData = [];

  if (storedData === null) {
    // save
    await AsyncStorage.setItem('user', JSON.stringify(arrData));
  } else {
    newData = [...storedDataParsed, user];
    await AsyncStorage.setItem('user', JSON.stringify(newData));
  }
  setName('');
  setPhone('');
  Keyboard.dismiss();
};

Now, I'm using useEffect to get data from the AsyncStorage and setting it to the data state. I'm using data to render the text in the screen.

useEffect(() => {
  retrieveData();
}, [data]);

const retrieveData = async () => {
  try {
    const valueString = await AsyncStorage.getItem('user');
    const value = JSON.parse(valueString);
    setData(value);
  } catch (error) {
    console.log(error);
  }
};

I'm using [data] in useEffect since I want to re-render my component each time  data changes i.e. each time I save data in AsyncStorage. But this is causing infinite loop as setData causes useEffect to run infinitely.

If I remove data from the [] it doesn't loop but my data in render is one step behind. So whenever I save data it doesn't show the current data but the previous one.

Any explanation of what I am doing wrong here and how can i fix this?

Thanks.

Body:
As already mentioned by you, the infinite loop is due to thefact that you pass data as a dependency to useEffect and also set in inside the function called in useEffect.

The solution here is to not use useEffect and instead setData whenever you are setting value in AsyncStorage

const saveData = async () => {
  const arrData = [{ name: 'vikrant', phone: 123456 }]; // [{ name, phone}] from the textInput

  const storedData = await AsyncStorage.getItem('user');
  const storedDataParsed = JSON.parse(storedData);

  let newData = [];

  if (storedData === null) {
    // save
    await AsyncStorage.setItem('user', JSON.stringify(arrData));
  } else {
    newData = [...storedDataParsed, user];
    await AsyncStorage.setItem('user', JSON.stringify(newData));
  }
  setName('');
  setPhone('');
  setData(newData);
  Keyboard.dismiss();
};


问:
Resetting array index when reaching the last index
I'm trying to build a code in which the 12 months of the calendar are in an array, the code then asks for a month, and then it outputs the 10 months ahead of the inputted month.

```<code>e.g.
input: January
output: February, March,...November
</code>```

I'm having trouble reverting the index back to the start once the index exceeds 12, for example, if I input August, it's supposed to output September to June, but instead it stops at December and says out of bounds. Thank you

```<code>   String months[];
   String choice;
   months = new String[13];
   months[0] = null ;
   months[1] = "January";
   months[2] = "February";
   months[3] = "March";
   months[4] = "April";
   months[5] = "May";
   months[6] = "June";
   months[7] = "July";
   months[8] = "August";
   months[9] = "September";
   months[10] = "October";
   months[11] = "November";
   months[12] = "December";
   System.out.print("Enter Month : ");
   choice = a.nextLine();

   if (choice.equals("August")) {
       for(int i=8; i<i+10; i++) {
           String result= months[i];
           System.out.println(result);
       }
   }
</code>```

答:
Try this,</p>

```<code>     public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        String months[];
        String choice;
        months = new String[13];
        months[0] = null;
        months[1] = "January";
        months[2] = "February";
        months[3] = "March";
        months[4] = "April";
        months[5] = "May";
        months[6] = "June";
        months[7] = "July";
        months[8] = "August";
        months[9] = "September";
        months[10] = "October";
        months[11] = "November";
        months[12] = "December";
        System.out.print("Enter Month : ");
        choice = scanner.nextLine();

        int startIndex = 0;
        for (int i = 0; i < months.length; i++) {
            if (choice.equalsIgnoreCase(months[i])) {
                startIndex = i + 1;
            }
        }

        for (int j = startIndex; j < months.length; j++) {
            String result = months[j];
            System.out.println(result);
        }
    }
</code>```

Body:
I'm trying to build a code in which the 12 months of the calendar are in an array, the code then asks for a month, and then it outputs the 10 months ahead of the inputted month.

e.g.
input: January
output: February, March,...November

I'm having trouble reverting the index back to the start once the index exceeds 12, for example, if I input August, it's supposed to output September to June, but instead it stops at December and says out of bounds. Thank you

   String months[];
   String choice;
   months = new String[13];
   months[0] = null ;
   months[1] = "January";
   months[2] = "February";
   months[3] = "March";
   months[4] = "April";
   months[5] = "May";
   months[6] = "June";
   months[7] = "July";
   months[8] = "August";
   months[9] = "September";
   months[10] = "October";
   months[11] = "November";
   months[12] = "December";
   System.out.print("Enter Month : ");
   choice = a.nextLine();

   if (choice.equals("August")) {
       for(int i=8; i<i+10; i++) {
           String result= months[i];
           System.out.println(result);
       }
   }

Body:
Try this,

     public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        String months[];
        String choice;
        months = new String[13];
        months[0] = null;
        months[1] = "January";
        months[2] = "February";
        months[3] = "March";
        months[4] = "April";
        months[5] = "May";
        months[6] = "June";
        months[7] = "July";
        months[8] = "August";
        months[9] = "September";
        months[10] = "October";
        months[11] = "November";
        months[12] = "December";
        System.out.print("Enter Month : ");
        choice = scanner.nextLine();

        int startIndex = 0;
        for (int i = 0; i < months.length; i++) {
            if (choice.equalsIgnoreCase(months[i])) {
                startIndex = i + 1;
            }
        }

        for (int j = startIndex; j < months.length; j++) {
            String result = months[j];
            System.out.println(result);
        }
    }


问:
Code=17000 "The custom token format is incorrect. Please check the documentation."
I followed the steps described here : https://firebase.google.com/docs/auth/admin/create-custom-tokens

I am able to create custom tokens using the Firebase Admin SDK.

I send them back to the client iOS app to use like this :

```<code>Auth.auth().signIn(withCustomToken: customToken ?? "") { (user, error) in
  // ...
}
</code>```

But I get this error :

```<code>Code=17000 "The custom token format is incorrect. Please check the documentation." UserInfo={NSLocalizedDescription=The custom token format is incorrect. Please check the documentation., error_name=ERROR_INVALID_CUSTOM_TOKEN}
</code>```

I'm using Firebase Admin 5.2.0 and the Firebase iOS client 4.0.0

Any idea?

答:
After checking the token and its lifetime, it turned out that a mismatch in system-time was the problem in our case.

After setting the timezone and the time to 'automatic', the problem was solved.

Body:
I followed the steps described here : https://firebase.google.com/docs/auth/admin/create-custom-tokens

I am able to create custom tokens using the Firebase Admin SDK.

I send them back to the client iOS app to use like this :

Auth.auth().signIn(withCustomToken: customToken ?? "") { (user, error) in
  // ...
}

But I get this error :

Code=17000 "The custom token format is incorrect. Please check the documentation." UserInfo={NSLocalizedDescription=The custom token format is incorrect. Please check the documentation., error_name=ERROR_INVALID_CUSTOM_TOKEN}

I'm using Firebase Admin 5.2.0 and the Firebase iOS client 4.0.0

Any idea?


问:
How to resolve the error in launching git
I have installed the latest git(version 2.25.0) in Windows. However, I got an error while I am executing any of the git commands either in Powershell or in Command Prompt.

After executing the git command, the terminal produces :

Error launching git: The paging file is too small for this operation to complete

I have already uninstalled and reinstalled the software and restarted the system after installation. Can anyone help me to resolve this? Thanks in advance

答:
AS per my understanding error here seems to be with the Windows page file and not Git.

Try the following steps below to resize the page file.

Start, Control Panel, System

The system properties applet will appear, select the advanced tab

In the performance tab, click settings

The performance dialog will appear, click the advanced tab click the change button.

You will now (assuming that you are a local admin) be able to increase the size of you virtual memory.

Change the paging size and click set.

Click OK

Click OK

Click OK

At this point, the machine may need to re-start.

Reference: Paging file is too small for this operation to complete


问:
What are the steps necessary to render my scene to a Framebuffer Object(FBO) and then render that FBO to the screen?
I've got a fairly complicated scene with many GL_POINTS that I need to render.  The scene will be largely static, so I'd like to render it to a Framebuffer Object and then only update that FBO when my scene actually changes.  I'd then like to render the FBO to the screen each frame.

I've found examples that render an FBO into a texture.  I've found examples that render an FBO into a RenderBuffer (still not quite sure what that is).  I'm not sure what the steps are to achieve this.  Do I need to render to a texture and the draw the texture to the screen?

Can you please enumerate the steps (ideally even in pseudocode or actual code) to render my scene to an FBO and then draw that FBO to the screen.

draw() is sufficient for a placeholder for my own drawing functions.

答:
Here is alternative example which does not require textures:

```<code>// copy framebuffer
if(fboUsed)
{
    glBindFramebuffer(GL_READ_FRAMEBUFFER, fboId);
    glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
    glBlitFramebuffer(0, 0, TEXTURE_WIDTH, TEXTURE_HEIGHT,
                      0, 0, screenWidth, screenHeight,
                      GL_COLOR_BUFFER_BIT,
                      GL_LINEAR);
    glBindFramebuffer(GL_READ_FRAMEBUFFER, 0);
 }
</code>```

Replace variables in blit with your own.

Apperently frame buffer 0 is front buffer.
fboId is your frame buffer number.

Body:
Here is alternative example which does not require textures:

// copy framebuffer
if(fboUsed)
{
    glBindFramebuffer(GL_READ_FRAMEBUFFER, fboId);
    glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
    glBlitFramebuffer(0, 0, TEXTURE_WIDTH, TEXTURE_HEIGHT,
                      0, 0, screenWidth, screenHeight,
                      GL_COLOR_BUFFER_BIT,
                      GL_LINEAR);
    glBindFramebuffer(GL_READ_FRAMEBUFFER, 0);
 }

Replace variables in blit with your own.

Apperently frame buffer 0 is front buffer.
fboId is your frame buffer number.


问:
How to Sort Values on the Graph
I'm using python to analyze 911 Call for Service dataset. I'm showing data monthwise. Data is not sorted Date Wise.

```<code>import pandas as pd
import matplotlib.pyplot as plt

df = pd.read_csv('911_calls_for_service.csv')
r, c = df.shape

df['callDateTime'] = pd.to_datetime(df['callDateTime'])
df['MonthYear'] = df['callDateTime'].apply(lambda time: str(time.year) + '-' + str(time.month))
df['MonthYear'].value_counts().plot()
print(df['MonthYear'].value_counts())
plt.tight_layout()
plt.show()
</code>```

答:
```<code>import pandas as pd
import matplotlib.pyplot as plt

df = pd.read_csv('911_calls_for_service.csv')
df['callDateTime'] = pd.to_datetime(df['callDateTime'])

ax = df['callDateTime'].groupby([df["callDateTime"].dt.year, df["callDateTime"].dt.month]).count().plot()
ax.set_xlabel("Date")
ax.set_ylabel("Frequency")

plt.tight_layout()
plt.show()
</code>```

Title: How to Sort Values on the Graph

Body:
I'm using python to analyze 911 Call for Service dataset. I'm showing data monthwise. Data is not sorted Date Wise.

import pandas as pd
import matplotlib.pyplot as plt

df = pd.read_csv('911_calls_for_service.csv')
r, c = df.shape

df['callDateTime'] = pd.to_datetime(df['callDateTime'])
df['MonthYear'] = df['callDateTime'].apply(lambda time: str(time.year) + '-' + str(time.month))
df['MonthYear'].value_counts().plot()
print(df['MonthYear'].value_counts())
plt.tight_layout()
plt.show()


问:
Google Cloud AI Platform: I can't create a model version using the "--accelerator" parameter
In order to get online predictions, I'm creating a model version on the ai-platform. It works fine unless I want to use the --accelerator parameter.

Here is the command that works:

```<code>    gcloud alpha ai-platform versions create [...] --model [...] --origin=[...] --python-version=3.5 --runtime-version=1.14 --package-uris=[...] --machine-type=mls1-c4-m4 --prediction-class=[...]
</code>```

Here is the parameter that makes it not work:

```<code>    --accelerator=^:^count=1:type=nvidia-tesla-k80
</code>```

This is the error message I get:

```<code>    ERROR: (gcloud.alpha.ai-platform.versions.create) INVALID_ARGUMENT: Request contains an invalid argument.
</code>```

I expect it to work, since 1) the parameter exists and uses these two keys (count and type), 2) I use the correct syntax for the parameter, any other syntaxes would return a syntax error, and 3) the "nvidia-tesla-k80" value exists (it is described in --help) and is available in the region in which the model is deployed.

答:
Make sure you are using a recent version of the Google Cloud SDK.

Then you can use the following command:

```<code>gcloud beta ai-platform versions create $VERSION_NAME \
  --model $MODEL_NAME \
  --origin gs://$MODEL_DIRECTORY_URI \
  --runtime-version 1.15 \
  --python-version 3.7 \
  --framework tensorflow \
  --machine-type n1-standard-4 \
  --accelerator count=1,type=nvidia-tesla-t4
</code>```

For reference you can enable logging during model creation:

```<code>gcloud beta ai-platform models create {MODEL_NAME} \
 --regions {REGION}
 --enable-logging \
 --enable-console-logging
</code>```

Body:
In order to get online predictions, I'm creating a model version on the ai-platform. It works fine unless I want to use the --accelerator parameter.

Here is the command that works:

    gcloud alpha ai-platform versions create [...] --model [...] --origin=[...] --python-version=3.5 --runtime-version=1.14 --package-uris=[...] --machine-type=mls1-c4-m4 --prediction-class=[...]

Here is the parameter that makes it not work:

    --accelerator=^:^count=1:type=nvidia-tesla-k80

This is the error message I get:

    ERROR: (gcloud.alpha.ai-platform.versions.create) INVALID_ARGUMENT: Request contains an invalid argument.

I expect it to work, since 1) the parameter exists and uses these two keys (count and type), 2) I use the correct syntax for the parameter, any other syntaxes would return a syntax error, and 3) the "nvidia-tesla-k80" value exists (it is described in --help) and is available in the region in which the model is deployed.

Body:
Make sure you are using a recent version of the <a href="https://cloud.google.com/sdk/?utm_source=google&utm_medium=cpc&utm_campaign=na-US-all-en-dr-skws-all-all-trial-b-dr-1008076&utm_content=text-ad-none-any-DEV_c-CRE_79747450687-ADGP_Hybrid%20%7C%20AW%20SEM%20%7C%20SKWS%20%7C%20US%20%7C%20en%20%7C%20BMM%20~%20Cloud%20SDK-KWID_43700007037793881-kwd-26018927532&utm_term=KW_%2Bcloud%20%2Bsdk-ST_%2Bcloud%20%2Bsdk&gclid=Cj0KCQjwu6fzBRC6ARIsAJUwa2QfDqqWGmpBf2dQMbLkGEAWGDSunVfDzWx6H8jASSgpVSBAn1aIdZQaAlW6EALw_wcB" rel="nofollow noreferrer">Google Cloud SDK.

Then you can use the following command:

gcloud beta ai-platform versions create $VERSION_NAME \
  --model $MODEL_NAME \
  --origin gs://$MODEL_DIRECTORY_URI \
  --runtime-version 1.15 \
  --python-version 3.7 \
  --framework tensorflow \
  --machine-type n1-standard-4 \
  --accelerator count=1,type=nvidia-tesla-t4

For reference you can enable logging during model creation:

gcloud beta ai-platform models create {MODEL_NAME} \
 --regions {REGION}
 --enable-logging \
 --enable-console-logging


问:
Getting user input as a argument for a script
I am trying to make a bash script that gives the user options 1-5,with 5 being to exit. For option 2 I want the to be able to pass the file name as a argument for the file_size script but even when I catch the user input it still says the error message please enter a single file name as an argument. I am not sure why is doesn't pass it as a argument, Any help would be appreciated.</p>

```<code>    #!/bin/bash

# usage: ./menu_script

exitvar=false

while [ $exitvar = "false" ]  # keep looping until exit equal true
  do

echo -n "Enter a number 1 through 5, 5 to exit"
read number

case $number in
1) echo "Move empty files"
/home/student/move_empty;;

2) echo "Check file size"
echo -n "Enter a file name to check: "
read sourcefile

/home/student/file_size;;

3) echo "Option3";;

4) echo "File check rwx"
echo -n "Enter a file name to check: "
read  sourcefile

if [ -e $sourcefile ]  # does the source file exist?
 then
   echo $sourcefile "exists!"
  fi

# find out if file has write permission or not
[ -w $sourcefile ] && W="Write = yes" || W="Write = No"

# find out if file has excute permission or not
[ -x $sourcefile ] && X="Execute = yes" || X="Execute = No"

# find out if file has read permission or not
[ -r $sourcefile ] && R="Read = yes" || R="Read = No"

echo "$sourcefile permissions"
echo "$W"
echo "$R"
echo "$X"

;;

5) echo "exit"
   exitvar="true"
   ;;
 *) echo "Invalid number try again"
   ;;
 esac
done
</code>```

答:
At the option 2)

```<code>2) echo "Check file size"
  echo -n "Enter a file name to check: "
  read -r  sourcefile
  echo /home/student/file_size "$sourcefile";;
</code>```

To see if the argument is being pass to /home/student/filesize

It would be nice and informative to show a menu with numbers alongside the option.

Body:
I am trying to make a bash script that gives the user options 1-5,with 5 being to exit. For option 2 I want the to be able to pass the file name as a argument for the file_size script but even when I catch the user input it still says the error message please enter a single file name as an argument. I am not sure why is doesn't pass it as a argument, Any help would be appreciated.

    #!/bin/bash

# usage: ./menu_script

exitvar=false

while [ $exitvar = "false" ]  # keep looping until exit equal true
  do

echo -n "Enter a number 1 through 5, 5 to exit"
read number

case $number in
1) echo "Move empty files"
/home/student/move_empty;;

2) echo "Check file size"
echo -n "Enter a file name to check: "
read sourcefile

/home/student/file_size;;

3) echo "Option3";;

4) echo "File check rwx"
echo -n "Enter a file name to check: "
read  sourcefile

if [ -e $sourcefile ]  # does the source file exist?
 then
   echo $sourcefile "exists!"
  fi

# find out if file has write permission or not
[ -w $sourcefile ] && W="Write = yes" || W="Write = No"

# find out if file has excute permission or not
[ -x $sourcefile ] && X="Execute = yes" || X="Execute = No"

# find out if file has read permission or not
[ -r $sourcefile ] && R="Read = yes" || R="Read = No"

echo "$sourcefile permissions"
echo "$W"
echo "$R"
echo "$X"

;;

5) echo "exit"
   exitvar="true"
   ;;
 *) echo "Invalid number try again"
   ;;
 esac
done

Body:
At the option 2)

2) echo "Check file size"
  echo -n "Enter a file name to check: "
  read -r  sourcefile
  echo /home/student/file_size "$sourcefile";;

To see if the argument is being pass to /home/student/filesize

It would be nice and informative to show a menu with numbers alongside the option.


问:
Input redirection problems in C++ when writing
Hello I can read a file perfectly using dup2 but am having trouble when writing to a file and adding to it with these commands:

```<code>shell: ls >+ lsout
shell: cat lsout
</code>```

Here is the C++ code that is handling the dup2 for write:

```<code>else if(write == true)
            {
                int fd = open(rCommand[1],O_WRONLY | O_APPEND);
                dup2(fd, 1);
                close(fd);
                execvp(substrings[0], substrings);
            }
</code>```

Substrings array holds the arguments made in the command line and rCommand[1] is the file name of what is trying to be opened or written to.

My understanding is that ls >+ lsout is suppose to create an empty file called lsout but instead when executing only lists items in the current directory. Any help would be appreciated

答:
well one thing I found out after running ls >+ lsout is that it creates a file called + and not lsout:

$ ls >+ lsout
ls: cannot access 'lsout': No such file or directory

Therefore, cat lsout inevitably throws an error:

$ cat lsout cat: lsout: No such file or directory

So I guess this needs to be solved first before moving on.
Also, on further research, I found that the execvp(substrings[0], substrings); statement might be wrong as execvp() takes generally the first argument as the pointer to the file we are dealing with, but my inference is that substrings[0] might hold the command we executed instead of the file name.

And, also just like @aschepler said, please try posting a more descriptive question accompanied by error messages and side-effects as it is helpful for someone trying to solve your problem :)

Best.

Body:
Hello I can read a file perfectly using dup2 but am having trouble when writing to a file and adding to it with these commands:

shell: ls >+ lsout
shell: cat lsout

Here is the C++ code that is handling the dup2 for write:

else if(write == true)
            {
                int fd = open(rCommand[1],O_WRONLY | O_APPEND);
                dup2(fd, 1);
                close(fd);
                execvp(substrings[0], substrings);
            }

Substrings array holds the arguments made in the command line and rCommand[1] is the file name of what is trying to be opened or written to.

My understanding is that ls >+ lsout is suppose to create an empty file called lsout but instead when executing only lists items in the current directory. Any help would be appreciated


问:
Tkinter, python 3.8.1, win10Pro, How can I change a label image?
This is my VERY first post so forgive my newness.  I'm trying to make a GUI of a dice rolling game (2 x six-sided).  Logic of the random rolls is working fine to console.  Also in console I see that die number is mapping to correct image file, but I'm having trouble changing tkinter label images to the new corresponding images on every roll beyond the initial startup roll.

On startup, it displays both die images correctly, but when I click "roll" button, both images from first roll just disappear and new roll images are not displayed.  It just blanks the space previously occupied by first roll images.

Looking closely, I can see the correct die images "flash" on screen in their correct positions only to immediately disappear each time I press "roll".

I'm unable to attach the six images I'm using for the possible die rolls (lack of creds), but point is to demonstrate ability to change from any image to any other so feel free to try with any 6 gifs.

I saw similar questions on this site but when I tried code suggested, or combos of code suggested, I had same problem I am having now.

I'm using python 3.8.1 on win10pro.  Any help would be appreciated!  Here's my code:

```<code>from tkinter import *
import random

window = Tk()
window.title( 'Roller' )
window.resizable( 0, 0 )

def get_roll():
    min=1
    max=6

    die1 = random.randint(min,max)
    die2 = random.randint(min,max)

    if die1 == die2:
        print(die1,'+',die2,'=',die1+die2, '*** You rolled doubles ***')
    else:
        print(die1,'+',die2,'=',die1+die2)
    return die1,die2

def get_image(index):
    images = []
    images.append('die_01_42158_sm.gif')
    images.append('die_02_42159_sm.gif')
    images.append('die_03_42160_sm.gif')
    images.append('die_04_42161_sm.gif')
    images.append('die_05_42162_sm.gif')
    images.append('die_06_42164_sm.gif')
    return images[index-1]

def do_roll():
    global window

    die1, die2 = get_roll()

    imgfile1 = get_image(die1)
    imgfile2 = get_image(die2)

    print(imgfile1)
    img1 = PhotoImage( file = imgfile1 )
    #img1 = img1.subsample(20)
    imgLbl1.configure( image = img1 )
    #imgLbl1 = Label( window, image = img1 )
    #imgLbl1.grid(row = 0, column = 0)
    window.update_idletasks()

    print(imgfile2)
    img2 = PhotoImage( file = imgfile2 )
    #img2 = img2.subsample(20)
    imgLbl2.configure( image = img2 )
    #imgLbl2 = Label( window, image = img2 )
    #imgLbl2.grid(row = 0, column = 1)
    window.update_idletasks()

die1, die2 = get_roll()
imgfile1 = get_image(die1)
imgfile2 = get_image(die2)

img1 = PhotoImage( file = imgfile1 )
#img1 = img1.subsample(20)
imgLbl1 = Label( window, image = img1 )
imgLbl1.grid( row = 0, column = 0 )

img2 = PhotoImage( file = imgfile2 )
#img2 = img2.subsample(20)
imgLbl2 = Label( window, image = img2 )
imgLbl2.grid( row = 0, column = 1 )

rollBtn = Button( window )
rollBtn.grid( row = 0, column = 2 )
rollBtn.configure( text = 'Roll' )
rollBtn.configure( command = do_roll )

quitBtn = Button( window )
quitBtn.grid( row = 0, column = 3 )
quitBtn.configure( text = 'Quit' )
quitBtn.configure( command = window.destroy )

#do_roll()

window.mainloop()

</code>```

答:
Since you used local variables to hold the images, they will be garbage collected after the function.

You have to keep the references of the images:

```<code>def do_roll():
    die1, die2 = get_roll()

    imgfile1 = get_image(die1)
    imgfile2 = get_image(die2)

    print(imgfile1)
    imgLbl1.image = PhotoImage(file=imgfile1)
    imgLbl1.configure(image=imgLbl1.image)

    print(imgfile2)
    imgLbl2.image = PhotoImage(file=imgfile2)
    imgLbl2.configure(image=imgLbl2.image)
</code>```

Or declare img1 and img2 as global:

```<code>def do_roll():
    global img1, img2

    die1, die2 = get_roll()

    imgfile1 = get_image(die1)
    imgfile2 = get_image(die2)

    print(imgfile1)
    img1 = PhotoImage(file=imgfile1)
    imgLbl1.configure(image=img1)

    print(imgfile2)
    img2 = PhotoImage(file=imgfile2)
    imgLbl2.configure(image=img2)
</code>```

Body:
This is my VERY first post so forgive my newness.  I'm trying to make a GUI of a dice rolling game (2 x six-sided).  Logic of the random rolls is working fine to console.  Also in console I see that die number is mapping to correct image file, but I'm having trouble changing tkinter label images to the new corresponding images on every roll beyond the initial startup roll.

On startup, it displays both die images correctly, but when I click "roll" button, both images from first roll just disappear and new roll images are not displayed.  It just blanks the space previously occupied by first roll images.

Looking closely, I can see the correct die images "flash" on screen in their correct positions only to immediately disappear each time I press "roll".

I'm unable to attach the six images I'm using for the possible die rolls (lack of creds), but point is to demonstrate ability to change from any image to any other so feel free to try with any 6 gifs.

I saw similar questions on this site but when I tried code suggested, or combos of code suggested, I had same problem I am having now.

I'm using python 3.8.1 on win10pro.  Any help would be appreciated!  Here's my code:

from tkinter import *
import random

window = Tk()
window.title( 'Roller' )
window.resizable( 0, 0 )

def get_roll():
    min=1
    max=6

    die1 = random.randint(min,max)
    die2 = random.randint(min,max)

    if die1 == die2:
        print(die1,'+',die2,'=',die1+die2, '*** You rolled doubles ***')
    else:
        print(die1,'+',die2,'=',die1+die2)
    return die1,die2

def get_image(index):
    images = []
    images.append('die_01_42158_sm.gif')
    images.append('die_02_42159_sm.gif')
    images.append('die_03_42160_sm.gif')
    images.append('die_04_42161_sm.gif')
    images.append('die_05_42162_sm.gif')
    images.append('die_06_42164_sm.gif')
    return images[index-1]

def do_roll():
    global window

    die1, die2 = get_roll()

    imgfile1 = get_image(die1)
    imgfile2 = get_image(die2)

    print(imgfile1)
    img1 = PhotoImage( file = imgfile1 )
    #img1 = img1.subsample(20)
    imgLbl1.configure( image = img1 )
    #imgLbl1 = Label( window, image = img1 )
    #imgLbl1.grid(row = 0, column = 0)
    window.update_idletasks()

    print(imgfile2)
    img2 = PhotoImage( file = imgfile2 )
    #img2 = img2.subsample(20)
    imgLbl2.configure( image = img2 )
    #imgLbl2 = Label( window, image = img2 )
    #imgLbl2.grid(row = 0, column = 1)
    window.update_idletasks()

die1, die2 = get_roll()
imgfile1 = get_image(die1)
imgfile2 = get_image(die2)

img1 = PhotoImage( file = imgfile1 )
#img1 = img1.subsample(20)
imgLbl1 = Label( window, image = img1 )
imgLbl1.grid( row = 0, column = 0 )

img2 = PhotoImage( file = imgfile2 )
#img2 = img2.subsample(20)
imgLbl2 = Label( window, image = img2 )
imgLbl2.grid( row = 0, column = 1 )

rollBtn = Button( window )
rollBtn.grid( row = 0, column = 2 )
rollBtn.configure( text = 'Roll' )
rollBtn.configure( command = do_roll )

quitBtn = Button( window )
quitBtn.grid( row = 0, column = 3 )
quitBtn.configure( text = 'Quit' )
quitBtn.configure( command = window.destroy )

#do_roll()

window.mainloop()

Body:
Since you used local variables to hold the images, they will be garbage collected after the function.

You have to keep the references of the images:

def do_roll():
    die1, die2 = get_roll()

    imgfile1 = get_image(die1)
    imgfile2 = get_image(die2)

    print(imgfile1)
    imgLbl1.image = PhotoImage(file=imgfile1)
    imgLbl1.configure(image=imgLbl1.image)

    print(imgfile2)
    imgLbl2.image = PhotoImage(file=imgfile2)
    imgLbl2.configure(image=imgLbl2.image)

Or declare img1 and img2 as global:

def do_roll():
    global img1, img2

    die1, die2 = get_roll()

    imgfile1 = get_image(die1)
    imgfile2 = get_image(die2)

    print(imgfile1)
    img1 = PhotoImage(file=imgfile1)
    imgLbl1.configure(image=img1)

    print(imgfile2)
    img2 = PhotoImage(file=imgfile2)
    imgLbl2.configure(image=img2)


问:
Python print/display only if the sum is not zero
I have a dataframe below:

```<code>df = pd.DataFrame({'Product': ['A', 'A', 'C', 'D'], 'Volume': ['-3', '3', '1', '5']})
</code>```

I am using groupby and sum.

```<code>final = df.groupby(['Product'])['Volume'].sum().reset_index()
print(final)
</code>```

This is ok.
But I only want the print to be carry only those where sum != 0. Like Product C and D

Any idea how can I do that?
I try to use:

```<code>if final != 0:
    print (final)
</code>```

But this is throwing error and usually when I get this error, the syntax is definitely wrong...

```<code>ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
</code>```

答:
Given,

```<code>import pandas as pd
df = pd.DataFrame({'Product': ['A', 'A', 'C', 'D'], 'Volume': [-3, 3, 1, 5]})
final = df.groupby(['Product'])['Volume'].sum().reset_index()
</code>```

Use selection to only select rows that match your criteria. df[some_series_of_booleans_based_on_condition]

```<code>print(final[final['Volume'] != 0])
#output:
  Product  Volume
1       C       1
2       D       5
</code>```

The idea being that if [some series of booleans]: doesn't make sense for python to interpret, and thus it complains about the syntax with the message that you saw.

Body:
I have a dataframe below:

df = pd.DataFrame({'Product': ['A', 'A', 'C', 'D'], 'Volume': ['-3', '3', '1', '5']})

I am using groupby and sum.

final = df.groupby(['Product'])['Volume'].sum().reset_index()
print(final)

This is ok.
But I only want the print to be carry only those where sum != 0. Like Product C and D

Any idea how can I do that?
I try to use:

if final != 0:
    print (final)

But this is throwing error and usually when I get this error, the syntax is definitely wrong...

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

Body:
Given,

import pandas as pd
df = pd.DataFrame({'Product': ['A', 'A', 'C', 'D'], 'Volume': [-3, 3, 1, 5]})
final = df.groupby(['Product'])['Volume'].sum().reset_index()

Use selection to only select rows that match your criteria. df[some_series_of_booleans_based_on_condition]

print(final[final['Volume'] != 0])
#output:
  Product  Volume
1       C       1
2       D       5

The idea being that if [some series of booleans]: doesn't make sense for python to interpret, and thus it complains about the syntax with the message that you saw.


问:
Ksoap Blackberry PropertyInfo.setValue
so i im using the PropertyInfo to pass complex objects in my soap request, and its working fine on android, sample :

```<code>        PropertyInfo pi = new PropertyInfo();
        pi.name = "envelope";
        pi.setName("envelope");
        pi.setValue(envelope);
        pi.setType(envelope.getClass().toString());
</code>```

//envelope is a KvmSerializable class with namespace mappings.

now im trying to do the same for blackberry, but its not liking the "setName" or "setValue" parameters.

Any ideas?

答:
Try:

```<code>soapObject.addProperty("envelope", envelope);
</code>```

from SoapObject#addProperty

Title: Ksoap Blackberry PropertyInfo.setValue

Body:
so i im using the PropertyInfo to pass complex objects in my soap request, and its working fine on android, sample :

        PropertyInfo pi = new PropertyInfo();
        pi.name = "envelope";
        pi.setName("envelope");
        pi.setValue(envelope);
        pi.setType(envelope.getClass().toString());

//envelope is a KvmSerializable class with namespace mappings.

now im trying to do the same for blackberry, but its not liking the "setName" or "setValue" parameters.

Any ideas?

Body:
Try:

soapObject.addProperty("envelope", envelope);

from SoapObject#addProperty


问:
How do I fix unhandled exception 0xDDDDDDDD for linked list class implementation?
My goal is to implement overloaded operators -= and - in my linked list class. The code and question are from a book called "DATA STRUCTURES & OTHER OBJECTS Using C++ 4th by MICHAEL MAIN, WALTER SAVITCH" pg.149 question 2.

So far I had some success with the code running, but not with the right results. Right now I am at a halt with a read access violation. To me, it seems like a pointer is pointing to a null variable but I don't know where. It could do with my -= overloaded operator as it is the only function I know that affecting the error(I commented it out the function body and it's running with wrong results). You'll see main_savitch_5:: for each function in my "toolkit.cpp" because of their non-member functions.

This is the error message from my code:

This is the toolkit header.

```<code>#ifndef TOOLKIT_H
#define TOOLKIT_H

#include <cstdlib>

namespace main_savitch_5
{
    class node {
    public:
        // TYPEDEF
        typedef double value_type;

        // CONSTRUCTOR
        node(
            const value_type& init_data = value_type(),
            node* init_link = NULL
        ) {
            data_field = init_data;
            link_field = init_link;
        }

        // Member functions to set the data and link fields:
        void set_data(const value_type& new_data) { data_field = new_data; }

        void set_link(node* new_link) { link_field = new_link; }

        // Constant member function to retrieve the current data:
        value_type data() const { return data_field; }

        // Two slightly different member functions to retreive
        // the current link:
        const node* link() const { return link_field; }

        node* link() { return link_field; }

    private:
        value_type data_field;
        node* link_field;
    };

    // FUNCTIONS for the linked list toolkit
    std::size_t list_length(const node* head_ptr);

    void list_head_insert(node*& head_ptr, const node::value_type& entry);

    void list_insert(node* previous_ptr, const node::value_type& entry);

    node* list_search(node* head_ptr, const node::value_type& target);

    const node* list_search
    (const node* head_ptr, const node::value_type& target);

    node* list_locate(node* head_ptr, std::size_t position);

    const node* list_locate(const node* head_ptr, std::size_t position);

    void list_head_remove(node*& head_ptr);

    void list_remove(node* previous_ptr);

    void list_clear(node*& head_ptr);

    void list_copy(const node* source_ptr, node*& head_ptr, node*& tail_ptr);
}

#endif // TOOLKIT_H
</code>```

this is the toolkit source file

```<code>#include <cstdlib>
#include <assert.h>
#include "toolkit.h"
using namespace main_savitch_5;

using namespace std;

std::size_t main_savitch_5::list_length(const node* head_ptr) {
    int length = 0;

    const node* trav = head_ptr;
    while (trav != NULL) {
        length++;
        trav = trav->link();
    }
    return length;
}

void main_savitch_5::list_head_insert(node*& head_ptr, const node::value_type& entry) {
    node* new_node = new node();
    new_node->set_data(entry);
    new_node->set_link(head_ptr);
    head_ptr = new_node;
}

void main_savitch_5::list_insert(node* previous_ptr, const node::value_type& entry) {
    node* new_node = new node(entry);
    new_node->set_link(previous_ptr->link());
    previous_ptr->set_link(new_node);
}

node* main_savitch_5::list_search(node* head_ptr, const node::value_type& target) {
    node* trav = head_ptr;
    // the first part of the condition guards the second part
    while ((trav != NULL) && (trav->data() != target)) {
        trav = trav->link();
    }
    // examine the results
    // if trav is NULL, we didn't find it, so return NULL
    // if trav is not NULL then trav->data() == target,  so return trav
    return trav;

}

const node* main_savitch_5::list_search
(const node* head_ptr, const node::value_type& target) {
    const node* trav = head_ptr;
    // the first part of the condition guards the second part
    while ((trav != NULL) && (trav->data() != target)) {
        trav = trav->link();
    }
    // examine the results
    // if trav is NULL, we didn't find it, so return NULL
    // if trav is not NULL then trav->data() == target,  so return trav
    return trav;
}

node* main_savitch_5::list_locate(node* head_ptr, std::size_t position) {

    if (position == 1) {
        return head_ptr;
    }
    else if (head_ptr == NULL) {
        return NULL;
    }
    else {
        return list_locate(head_ptr->link(), position - 1);
    }
}

const node* main_savitch_5::list_locate(const node* head_ptr, std::size_t position) {
    const node* trav = head_ptr;
    int count = position;
    while ((trav != NULL) && (count > 1)) {
        trav = trav->link();
        count--;
    }
    return trav;
}

void main_savitch_5::list_head_remove(node*& head_ptr) {
    assert(head_ptr != NULL);
    node* tmp = head_ptr;  /// first node, soon to be removed
    head_ptr = head_ptr->link();  // head_ptr now points at the second node
    delete tmp;
}

void main_savitch_5::list_remove(node* previous_ptr)
{
    node* remove_ptr;

    remove_ptr = previous_ptr->link();
    previous_ptr->set_link(remove_ptr->link());
    delete remove_ptr;
}

void main_savitch_5::list_copy(const node* source_ptr, node*& head_ptr, node*& tail_ptr)
// Library facilities used: cstdlib
{
    head_ptr = NULL;
    tail_ptr = NULL;

    // Handle the case of the empty list.
    if (source_ptr == NULL)
        return;

    // Make the head node for the newly created list, and put data in it.
    list_head_insert(head_ptr, source_ptr->data());
    tail_ptr = head_ptr;

    // Copy the rest of the nodes one at a time, adding at the tail of new list.
    source_ptr = source_ptr->link();
    while (source_ptr != NULL)
    {
        list_insert(tail_ptr, source_ptr->data());
        tail_ptr = tail_ptr->link();
        source_ptr = source_ptr->link();
    }
}

void main_savitch_5::list_clear(node*& head_ptr) {
    while (head_ptr != NULL) {
        // we know that head_ptr is not NULL
        // so head_ptr points at the first node of the rest of the list
        node* rest = head_ptr->link();
        delete  head_ptr;  // get rid of first node
        head_ptr = rest;
    }
}

</code>```

This is my bag header.

```<code>// FILE: bag3.h
// CLASS PROVIDED: bag (part of the namespace main_savitch_5)
//
// TYPEDEFS for the bag class:
//   bag::value_type
//     is the data type of the items in the bag. It may be any
//     of the C++ built-in types (int, char, etc.), or a class with a default
//     constructor, a copy constructor, an assignment
//     operator, and a test for equality (x == y).
//
//   bag::size_type
//     is the data type of any variable that keeps track of how many items are
//     in a bag
//
// CONSTRUCTOR for the bag class:
//   bag( )
//     Postcondition: The bag is empty.
//
// MODIFICATION MEMBER FUNCTIONS for the bag class:
//   size_type erase(const value_type& target)
//     Postcondition: All copies of target have been removed from the bag.
//     The return value is the number of copies removed (which could be zero).
//
//   bool erase_one(const value_type& target)
//     Postcondition: If target was in the bag, then one copy of target has
//     been removed from the bag; otherwise the bag is unchanged. A true
//     return value indicates that one copy was removed; false indicates that
//     nothing was removed.
//
//   void insert(const value_type& entry)
//     Postcondition: A new copy of entry has been inserted into the bag.
//
//   void operator +=(const bag& addend)
//     Postcondition: Each item in addend has been added to this bag.
//
// CONSTANT MEMBER FUNCTIONS for the bag class:
//   size_type size( ) const
//     Postcondition: Return value is the total number of items in the bag.
//
//   size_type count(const value_type& target) const
//     Postcondition: Return value is number of times target is in the bag.
//
//   value_type grab( ) const
//     Precondition: size( ) > 0.
//     Postcondition: The return value is a randomly selected item from the bag.
//
// NONMEMBER FUNCTIONS for the bag class:
//   bag operator +(const bag& b1, const bag& b2)
//     Postcondition: The bag returned is the union of b1 and b2.
//
// VALUE SEMANTICS for the bag class:
//    Assignments and the copy constructor may be used with bag objects.
//
// DYNAMIC MEMORY USAGE by the bag:
//   If there is insufficient dynamic memory, then the following functions throw
//   bad_alloc: The constructors, insert, operator +=, operator +, and the
//   assignment operator.

#ifndef BAG3_H
#define BAG3_H
#include <cstdlib>   // Provides size_t and NULL
#include "toolkit.h"   // Provides node class

namespace main_savitch_5
{
    class bag
    {
    public:
        // TYPEDEFS
        typedef std::size_t size_type;
        typedef node::value_type value_type;
        // CONSTRUCTORS and DESTRUCTOR
        bag();
        bag(const bag& source);
        ~bag();
        // MODIFICATION MEMBER FUNCTIONS
        size_type erase(const value_type& target);
        bool erase_one(const value_type& target);
        void insert(const value_type& entry);
        void operator +=(const bag& addend);
        void operator -=(const bag& subtrahend);
        void operator =(const bag& source);
        // CONSTANT MEMBER FUNCTIONS
        size_type size() const { return many_nodes; }
        size_type count(const value_type& target) const;
        value_type grab() const;
    private:
        node* head_ptr;       // List head pointer
        size_type many_nodes; // Number of nodes on the list
    };

    // NONMEMBER FUNCTIONS for the bag class:
    bag operator +(const bag& b1, const bag& b2);
    bag operator -(const bag& b1, const bag& b2);
}

#endif
</code>```

This is my bag source

```<code>// FILE: bag3.cxx
// CLASS implemented: bag (see bag3.h for documentation)
// INVARIANT for the bag ADT:
//   1. The items in the bag are stored on a linked list;
//   2. The head pointer of the list is stored in the member variable head_ptr;
//   3. The total number of items in the list is stored in the member variable
//      many_nodes.

#include <cassert>  // Provides assert
#include <cstdlib>  // Provides NULL, rand, size_t
#include "toolkit.h"  // Provides node and the linked list functions
#include "bag3.h"

using namespace std;
using namespace main_savitch_5;

bag::bag()
// Library facilities used: cstdlib
{
    head_ptr = NULL;
    many_nodes = 0;
}

bag::bag(const bag& source)
// Library facilities used: node1.h
{
    node* tail_ptr;  // Needed for argument of list_copy

    list_copy(source.head_ptr, head_ptr, tail_ptr);
    many_nodes = source.many_nodes;
}

bag::~bag()
// Library facilities used: node1.h
{
    list_clear(head_ptr);
    many_nodes = 0;
}

bag::size_type bag::count(const value_type& target) const
// Library facilities used: cstdlib, node1.h
{
    size_type answer;
    const node* cursor; // Use const node* since we don't change the nodes.

    answer = 0;
    cursor = list_search(head_ptr, target);
    while (cursor != NULL)
    {
        // Each time that cursor is not NULL, we have another occurrence of
        // target, so we add one to answer, and move cursor to the next
        // occurrence of the target.
        ++answer;
        cursor = cursor->link();
        cursor = list_search(cursor, target);
    }
    return answer;
}

bag::size_type bag::erase(const value_type& target)
// Library facilities used: cstdlib, node1.h
{
    size_type answer = 0;
    node* target_ptr;

    target_ptr = list_search(head_ptr, target);
    while (target_ptr != NULL)
    {
        // Each time that target_ptr is not NULL, we have another occurrence
    // of target. We remove this target using the same technique that
    // was used in erase_one.
        target_ptr->set_data(head_ptr->data());
        target_ptr = target_ptr->link();
        target_ptr = list_search(target_ptr, target);
        list_head_remove(head_ptr);
        --many_nodes;
        ++answer;
    }
    return answer;
}

bool bag::erase_one(const value_type& target)
// Library facilities used: cstdlib, node1.h
{
    node* target_ptr;

    target_ptr = list_search(head_ptr, target);
    if (target_ptr == NULL)
        return false; // target isn't in the bag, so no work to do
    target_ptr->set_data(head_ptr->data());
    list_head_remove(head_ptr);
    --many_nodes;
    return true;
}

bag::value_type bag::grab() const
// Library facilities used: cassert, cstdlib, node1.h
{
    size_type i;
    const node* cursor; // Use const node* since we don't change the nodes.

    assert(size() > 0);
    i = (rand() % size()) + 1;
    cursor = list_locate(head_ptr, i);
    return cursor->data();
}

void bag::insert(const value_type& entry)
// Library facilities used: node1.h
{
    list_head_insert(head_ptr, entry);
    ++many_nodes;
}

void bag::operator +=(const bag& addend)
// Library facilities used: cstdlib, node1.h
{
    node* copy_head_ptr;
    node* copy_tail_ptr;

    if (addend.many_nodes > 0)
    {
        list_copy(addend.head_ptr, copy_head_ptr, copy_tail_ptr);
        copy_tail_ptr->set_link(head_ptr);
        head_ptr = copy_head_ptr;
        many_nodes += addend.many_nodes;
    }
}

void bag::operator -=(const bag& subtrahend) //Code giving me exception.
{
    node* temp_head_ptr = head_ptr;
    node* tail_ptr = NULL;
    int n = many_nodes;

    while (temp_head_ptr != NULL)
    {
        node* prev_ptr = NULL;
        node* temp_head_ptr2 = subtrahend.head_ptr;
        while (temp_head_ptr2 != NULL)
        {
            if (temp_head_ptr->data() == temp_head_ptr2->data()) {
                n--;
                if (prev_ptr == NULL) {
                    list_head_remove(temp_head_ptr2);
                }
                else
                {
                    list_remove(prev_ptr);
                }
            }
            else
            {
                prev_ptr = temp_head_ptr2;
                temp_head_ptr2 = temp_head_ptr2->link();
            }
        }
        tail_ptr = temp_head_ptr;
        temp_head_ptr = temp_head_ptr->link();
    }
    many_nodes = n;
}

void bag::operator =(const bag& source)
// Library facilities used: node1.h
{
    node* tail_ptr; // Needed for argument to list_copy

    if (this == &source)
        return;

    list_clear(head_ptr);
    many_nodes = 0;
    list_copy(source.head_ptr, head_ptr, tail_ptr);
    many_nodes = source.many_nodes;
}

bag main_savitch_5::operator +(const bag& b1, const bag& b2)
{
    bag answer;

    answer += b1;
    answer += b2;
    return answer;
}

bag main_savitch_5::operator-(const bag& b1, const bag& b2)
{
    bag answer;

    answer += b1;
    answer -= b2;
    return answer;
}

</code>```

Test file

```<code>//
//
//  test -= and - on bag
/*
    This program will print informative messages if something goes wrong
    in either creating and filling bags or in getting the diffference
    between bags.

    If all goes well, only the final message prints.

*/

#include <iostream>
#include "bag3.h"

using namespace std;
using namespace main_savitch_5;

int main() {
    int size = 5;
    // how many of each value to put in each bag
    // one 0 will be put in b1
    // two 1's will be put in b1
    // five 0's will be in b2 ...
    int num1[] = { 1, 2, 3, 4, 5 };
    int num2[] = { 5, 4, 3, 2, 1 };
    bag b1;
    bag b2;
    // insert data into bags
    for (int i = 0; i < size; i++) {
        for (int j = 0; j < num1[i]; j++) {
            b1.insert(i);
        }
        for (int j = 0; j < num2[i]; j++) {
            b2.insert(i);
        }
    }
    for (int i = 0; i < size; i++) {
        if (num1[i] != b1.count(i)) {
            cout << "value  " << i << " has bad count in b1: "
                << b1.count(i) << " rather than " << num1[i] << endl;
        }
        if (num2[i] != b2.count(i)) {
            cout << "value  " << i << " has bad count in b2: "
                << b2.count(i) << " rather than " << num2[i] << endl;
        }
    }
    bag b3 = b1 - b2;
    for (int i = 0; i < size; i++) {
        int d = num1[i] - num2[i];
        d = (d >= 0) ? d : 0;
        if (b3.count(i) != d) {
            cout << "value  " << i << " has bad count in b3: "
                << b3.count(i) << " rather than " << d << endl;
        }
    }

    b1 -= b1;
    for (int i = 0; i < size; i++) {
        if (0 != b1.count(i)) {
            cout << "value  " << i << " has bad count in b1: "
                << b1.count(i) << " rather than " << 0 << endl;
        }
    }

    cout << "no news is good news!" << endl;
}
</code>```

答:
Your test includes the operation b1 -= b1;.  This will call your operator-= with both this and subtrahend pointing at the same object.

Eventually the call to list_head_remove(temp_head_ptr2);, to remove a node from subtrahend will remove the node that temp_head_ptr points to (i.e., the head node).  When this happens the later call to temp_head_ptr = temp_head_ptr->link() will access this dangling pointer resulting in Undefined Behavior.  In your case, your compiler has filled freed memory with a signal value (0xDDDDDDDD) that generates an access violation on access, and is easily spotted in the debugger.

Body:
My goal is to implement overloaded operators -= and - in my linked list class. The code and question are from a book called "DATA STRUCTURES & OTHER OBJECTS Using C++ 4th by MICHAEL MAIN, WALTER SAVITCH" pg.149 question 2.

So far I had some success with the code running, but not with the right results. Right now I am at a halt with a read access violation. To me, it seems like a pointer is pointing to a null variable but I don't know where. It could do with my -= overloaded operator as it is the only function I know that affecting the error(I commented it out the function body and it's running with wrong results). You'll see main_savitch_5:: for each function in my "toolkit.cpp" because of their non-member functions.

This is the error message from my code:

This is the toolkit header.

#ifndef TOOLKIT_H
#define TOOLKIT_H

#include <cstdlib>

namespace main_savitch_5
{
    class node {
    public:
        // TYPEDEF
        typedef double value_type;

        // CONSTRUCTOR
        node(
            const value_type& init_data = value_type(),
            node* init_link = NULL
        ) {
            data_field = init_data;
            link_field = init_link;
        }

        // Member functions to set the data and link fields:
        void set_data(const value_type& new_data) { data_field = new_data; }

        void set_link(node* new_link) { link_field = new_link; }

        // Constant member function to retrieve the current data:
        value_type data() const { return data_field; }

        // Two slightly different member functions to retreive
        // the current link:
        const node* link() const { return link_field; }

        node* link() { return link_field; }

    private:
        value_type data_field;
        node* link_field;
    };

    // FUNCTIONS for the linked list toolkit
    std::size_t list_length(const node* head_ptr);

    void list_head_insert(node*& head_ptr, const node::value_type& entry);

    void list_insert(node* previous_ptr, const node::value_type& entry);

    node* list_search(node* head_ptr, const node::value_type& target);

    const node* list_search
    (const node* head_ptr, const node::value_type& target);

    node* list_locate(node* head_ptr, std::size_t position);

    const node* list_locate(const node* head_ptr, std::size_t position);

    void list_head_remove(node*& head_ptr);

    void list_remove(node* previous_ptr);

    void list_clear(node*& head_ptr);

    void list_copy(const node* source_ptr, node*& head_ptr, node*& tail_ptr);
}

#endif // TOOLKIT_H

this is the toolkit source file

#include <cstdlib>
#include <assert.h>
#include "toolkit.h"
using namespace main_savitch_5;

using namespace std;

std::size_t main_savitch_5::list_length(const node* head_ptr) {
    int length = 0;

    const node* trav = head_ptr;
    while (trav != NULL) {
        length++;
        trav = trav->link();
    }
    return length;
}

void main_savitch_5::list_head_insert(node*& head_ptr, const node::value_type& entry) {
    node* new_node = new node();
    new_node->set_data(entry);
    new_node->set_link(head_ptr);
    head_ptr = new_node;
}

void main_savitch_5::list_insert(node* previous_ptr, const node::value_type& entry) {
    node* new_node = new node(entry);
    new_node->set_link(previous_ptr->link());
    previous_ptr->set_link(new_node);
}

node* main_savitch_5::list_search(node* head_ptr, const node::value_type& target) {
    node* trav = head_ptr;
    // the first part of the condition guards the second part
    while ((trav != NULL) && (trav->data() != target)) {
        trav = trav->link();
    }
    // examine the results
    // if trav is NULL, we didn't find it, so return NULL
    // if trav is not NULL then trav->data() == target,  so return trav
    return trav;

}

const node* main_savitch_5::list_search
(const node* head_ptr, const node::value_type& target) {
    const node* trav = head_ptr;
    // the first part of the condition guards the second part
    while ((trav != NULL) && (trav->data() != target)) {
        trav = trav->link();
    }
    // examine the results
    // if trav is NULL, we didn't find it, so return NULL
    // if trav is not NULL then trav->data() == target,  so return trav
    return trav;
}

node* main_savitch_5::list_locate(node* head_ptr, std::size_t position) {

    if (position == 1) {
        return head_ptr;
    }
    else if (head_ptr == NULL) {
        return NULL;
    }
    else {
        return list_locate(head_ptr->link(), position - 1);
    }
}

const node* main_savitch_5::list_locate(const node* head_ptr, std::size_t position) {
    const node* trav = head_ptr;
    int count = position;
    while ((trav != NULL) && (count > 1)) {
        trav = trav->link();
        count--;
    }
    return trav;
}

void main_savitch_5::list_head_remove(node*& head_ptr) {
    assert(head_ptr != NULL);
    node* tmp = head_ptr;  /// first node, soon to be removed
    head_ptr = head_ptr->link();  // head_ptr now points at the second node
    delete tmp;
}

void main_savitch_5::list_remove(node* previous_ptr)
{
    node* remove_ptr;

    remove_ptr = previous_ptr->link();
    previous_ptr->set_link(remove_ptr->link());
    delete remove_ptr;
}

void main_savitch_5::list_copy(const node* source_ptr, node*& head_ptr, node*& tail_ptr)
// Library facilities used: cstdlib
{
    head_ptr = NULL;
    tail_ptr = NULL;

    // Handle the case of the empty list.
    if (source_ptr == NULL)
        return;

    // Make the head node for the newly created list, and put data in it.
    list_head_insert(head_ptr, source_ptr->data());
    tail_ptr = head_ptr;

    // Copy the rest of the nodes one at a time, adding at the tail of new list.
    source_ptr = source_ptr->link();
    while (source_ptr != NULL)
    {
        list_insert(tail_ptr, source_ptr->data());
        tail_ptr = tail_ptr->link();
        source_ptr = source_ptr->link();
    }
}

void main_savitch_5::list_clear(node*& head_ptr) {
    while (head_ptr != NULL) {
        // we know that head_ptr is not NULL
        // so head_ptr points at the first node of the rest of the list
        node* rest = head_ptr->link();
        delete  head_ptr;  // get rid of first node
        head_ptr = rest;
    }
}

This is my bag header.

// FILE: bag3.h
// CLASS PROVIDED: bag (part of the namespace main_savitch_5)
//
// TYPEDEFS for the bag class:
//   bag::value_type
//     is the data type of the items in the bag. It may be any
//     of the C++ built-in types (int, char, etc.), or a class with a default
//     constructor, a copy constructor, an assignment
//     operator, and a test for equality (x == y).
//
//   bag::size_type
//     is the data type of any variable that keeps track of how many items are
//     in a bag
//
// CONSTRUCTOR for the bag class:
//   bag( )
//     Postcondition: The bag is empty.
//
// MODIFICATION MEMBER FUNCTIONS for the bag class:
//   size_type erase(const value_type& target)
//     Postcondition: All copies of target have been removed from the bag.
//     The return value is the number of copies removed (which could be zero).
//
//   bool erase_one(const value_type& target)
//     Postcondition: If target was in the bag, then one copy of target has
//     been removed from the bag; otherwise the bag is unchanged. A true
//     return value indicates that one copy was removed; false indicates that
//     nothing was removed.
//
//   void insert(const value_type& entry)
//     Postcondition: A new copy of entry has been inserted into the bag.
//
//   void operator +=(const bag& addend)
//     Postcondition: Each item in addend has been added to this bag.
//
// CONSTANT MEMBER FUNCTIONS for the bag class:
//   size_type size( ) const
//     Postcondition: Return value is the total number of items in the bag.
//
//   size_type count(const value_type& target) const
//     Postcondition: Return value is number of times target is in the bag.
//
//   value_type grab( ) const
//     Precondition: size( ) > 0.
//     Postcondition: The return value is a randomly selected item from the bag.
//
// NONMEMBER FUNCTIONS for the bag class:
//   bag operator +(const bag& b1, const bag& b2)
//     Postcondition: The bag returned is the union of b1 and b2.
//
// VALUE SEMANTICS for the bag class:
//    Assignments and the copy constructor may be used with bag objects.
//
// DYNAMIC MEMORY USAGE by the bag:
//   If there is insufficient dynamic memory, then the following functions throw
//   bad_alloc: The constructors, insert, operator +=, operator +, and the
//   assignment operator.

#ifndef BAG3_H
#define BAG3_H
#include <cstdlib>   // Provides size_t and NULL
#include "toolkit.h"   // Provides node class

namespace main_savitch_5
{
    class bag
    {
    public:
        // TYPEDEFS
        typedef std::size_t size_type;
        typedef node::value_type value_type;
        // CONSTRUCTORS and DESTRUCTOR
        bag();
        bag(const bag& source);
        ~bag();
        // MODIFICATION MEMBER FUNCTIONS
        size_type erase(const value_type& target);
        bool erase_one(const value_type& target);
        void insert(const value_type& entry);
        void operator +=(const bag& addend);
        void operator -=(const bag& subtrahend);
        void operator =(const bag& source);
        // CONSTANT MEMBER FUNCTIONS
        size_type size() const { return many_nodes; }
        size_type count(const value_type& target) const;
        value_type grab() const;
    private:
        node* head_ptr;       // List head pointer
        size_type many_nodes; // Number of nodes on the list
    };

    // NONMEMBER FUNCTIONS for the bag class:
    bag operator +(const bag& b1, const bag& b2);
    bag operator -(const bag& b1, const bag& b2);
}

#endif

This is my bag source

// FILE: bag3.cxx
// CLASS implemented: bag (see bag3.h for documentation)
// INVARIANT for the bag ADT:
//   1. The items in the bag are stored on a linked list;
//   2. The head pointer of the list is stored in the member variable head_ptr;
//   3. The total number of items in the list is stored in the member variable
//      many_nodes.

#include <cassert>  // Provides assert
#include <cstdlib>  // Provides NULL, rand, size_t
#include "toolkit.h"  // Provides node and the linked list functions
#include "bag3.h"

using namespace std;
using namespace main_savitch_5;

bag::bag()
// Library facilities used: cstdlib
{
    head_ptr = NULL;
    many_nodes = 0;
}

bag::bag(const bag& source)
// Library facilities used: node1.h
{
    node* tail_ptr;  // Needed for argument of list_copy

    list_copy(source.head_ptr, head_ptr, tail_ptr);
    many_nodes = source.many_nodes;
}

bag::~bag()
// Library facilities used: node1.h
{
    list_clear(head_ptr);
    many_nodes = 0;
}

bag::size_type bag::count(const value_type& target) const
// Library facilities used: cstdlib, node1.h
{
    size_type answer;
    const node* cursor; // Use const node* since we don't change the nodes.

    answer = 0;
    cursor = list_search(head_ptr, target);
    while (cursor != NULL)
    {
        // Each time that cursor is not NULL, we have another occurrence of
        // target, so we add one to answer, and move cursor to the next
        // occurrence of the target.
        ++answer;
        cursor = cursor->link();
        cursor = list_search(cursor, target);
    }
    return answer;
}

bag::size_type bag::erase(const value_type& target)
// Library facilities used: cstdlib, node1.h
{
    size_type answer = 0;
    node* target_ptr;

    target_ptr = list_search(head_ptr, target);
    while (target_ptr != NULL)
    {
        // Each time that target_ptr is not NULL, we have another occurrence
    // of target. We remove this target using the same technique that
    // was used in erase_one.
        target_ptr->set_data(head_ptr->data());
        target_ptr = target_ptr->link();
        target_ptr = list_search(target_ptr, target);
        list_head_remove(head_ptr);
        --many_nodes;
        ++answer;
    }
    return answer;
}

bool bag::erase_one(const value_type& target)
// Library facilities used: cstdlib, node1.h
{
    node* target_ptr;

    target_ptr = list_search(head_ptr, target);
    if (target_ptr == NULL)
        return false; // target isn't in the bag, so no work to do
    target_ptr->set_data(head_ptr->data());
    list_head_remove(head_ptr);
    --many_nodes;
    return true;
}

bag::value_type bag::grab() const
// Library facilities used: cassert, cstdlib, node1.h
{
    size_type i;
    const node* cursor; // Use const node* since we don't change the nodes.

    assert(size() > 0);
    i = (rand() % size()) + 1;
    cursor = list_locate(head_ptr, i);
    return cursor->data();
}

void bag::insert(const value_type& entry)
// Library facilities used: node1.h
{
    list_head_insert(head_ptr, entry);
    ++many_nodes;
}

void bag::operator +=(const bag& addend)
// Library facilities used: cstdlib, node1.h
{
    node* copy_head_ptr;
    node* copy_tail_ptr;

    if (addend.many_nodes > 0)
    {
        list_copy(addend.head_ptr, copy_head_ptr, copy_tail_ptr);
        copy_tail_ptr->set_link(head_ptr);
        head_ptr = copy_head_ptr;
        many_nodes += addend.many_nodes;
    }
}

void bag::operator -=(const bag& subtrahend) //Code giving me exception.
{
    node* temp_head_ptr = head_ptr;
    node* tail_ptr = NULL;
    int n = many_nodes;

    while (temp_head_ptr != NULL)
    {
        node* prev_ptr = NULL;
        node* temp_head_ptr2 = subtrahend.head_ptr;
        while (temp_head_ptr2 != NULL)
        {
            if (temp_head_ptr->data() == temp_head_ptr2->data()) {
                n--;
                if (prev_ptr == NULL) {
                    list_head_remove(temp_head_ptr2);
                }
                else
                {
                    list_remove(prev_ptr);
                }
            }
            else
            {
                prev_ptr = temp_head_ptr2;
                temp_head_ptr2 = temp_head_ptr2->link();
            }
        }
        tail_ptr = temp_head_ptr;
        temp_head_ptr = temp_head_ptr->link();
    }
    many_nodes = n;
}

void bag::operator =(const bag& source)
// Library facilities used: node1.h
{
    node* tail_ptr; // Needed for argument to list_copy

    if (this == &source)
        return;

    list_clear(head_ptr);
    many_nodes = 0;
    list_copy(source.head_ptr, head_ptr, tail_ptr);
    many_nodes = source.many_nodes;
}

bag main_savitch_5::operator +(const bag& b1, const bag& b2)
{
    bag answer;

    answer += b1;
    answer += b2;
    return answer;
}

bag main_savitch_5::operator-(const bag& b1, const bag& b2)
{
    bag answer;

    answer += b1;
    answer -= b2;
    return answer;
}

Test file

//
//
//  test -= and - on bag
/*
    This program will print informative messages if something goes wrong
    in either creating and filling bags or in getting the diffference
    between bags.

    If all goes well, only the final message prints.

*/

#include <iostream>
#include "bag3.h"

using namespace std;
using namespace main_savitch_5;

int main() {
    int size = 5;
    // how many of each value to put in each bag
    // one 0 will be put in b1
    // two 1's will be put in b1
    // five 0's will be in b2 ...
    int num1[] = { 1, 2, 3, 4, 5 };
    int num2[] = { 5, 4, 3, 2, 1 };
    bag b1;
    bag b2;
    // insert data into bags
    for (int i = 0; i < size; i++) {
        for (int j = 0; j < num1[i]; j++) {
            b1.insert(i);
        }
        for (int j = 0; j < num2[i]; j++) {
            b2.insert(i);
        }
    }
    for (int i = 0; i < size; i++) {
        if (num1[i] != b1.count(i)) {
            cout << "value  " << i << " has bad count in b1: "
                << b1.count(i) << " rather than " << num1[i] << endl;
        }
        if (num2[i] != b2.count(i)) {
            cout << "value  " << i << " has bad count in b2: "
                << b2.count(i) << " rather than " << num2[i] << endl;
        }
    }
    bag b3 = b1 - b2;
    for (int i = 0; i < size; i++) {
        int d = num1[i] - num2[i];
        d = (d >= 0) ? d : 0;
        if (b3.count(i) != d) {
            cout << "value  " << i << " has bad count in b3: "
                << b3.count(i) << " rather than " << d << endl;
        }
    }

    b1 -= b1;
    for (int i = 0; i < size; i++) {
        if (0 != b1.count(i)) {
            cout << "value  " << i << " has bad count in b1: "
                << b1.count(i) << " rather than " << 0 << endl;
        }
    }

    cout << "no news is good news!" << endl;
}


问:
How to map JSON data to model using Model Adapter Pattern in Ionic/Angular
I have a Json data that looks like:

```<code>{
    "restaurant": null,
    "details": [
        {
            "text": {
                "text": "Tea",
                "coordinateX": 311
            },
            "price": {
                "unitPrice": 5.0,
                "coordinateX": 389
            }
        },
        {
            "text": {
                "text": "Americano",
                "coordinateX": 311
            },
            "price": {
                "unitPrice": 41.24,
                "coordinateX": 205,
            }
        },
        {
            "text": {
                "text": "Latte",
                "coordinateX": 130
            },
            "price": {
                "unitPrice": 43.24,
                "coordinateX": 205,
            }
        }
    ]
}
</code>```

I'm using the model adapter pattern to map the json result from an API to the models I've created. My issue is that the nested objects are not being mapped. Only the the outermost object is.

ImageResult Object - this is the only one that is properly mapped

```<code>export class ImageResult {
    constructor(
        public Restaurant: string,
        public CapturedDetails: Array<Details>
    ) {}

    static adapt(item: any): ImageResult {
        return new ImageResult(
            item.restaurant,
            item.details
        );
      }
  }
</code>```

Details Object - no longer mapped. Shown as generic Object

```<code>export class Details {
    constructor(
        public Text: Word,
        public UnitPrice: Price
    ) {}

    static adapt(item: any): Details {
        return new Details(
            item.text,
            item.price
        );
      }
  }
</code>```

Word Object - no longer mapped. Shown as generic Object

```<code>export class Word {
    constructor(
        public Text: string = '',
        public CoordinateX: number  = 0
    ) {}

    static adapt(item: any): Word {
        return new Word(
            item.text,
            item.coordinateX
        );
      }
  }
</code>```

Mapping when the API is called:

```<code>GetText(formData: FormData): Observable<ImageResult> {
    return this.httpClient.post(this.getServiceUrl('TextCapture'), formData)
    .pipe(map(ImageResult.adapt));
  }
</code>```

答:
```<code>GetText(formData: FormData): Observable<any> {
    return this.httpClient.post(this.getServiceUrl('TextCapture'), formData)
        .map(Response => Response.json())
        .catch((error: any) => Observable.throw(error.json().error || 'Server error'));
}
</code>```

Body:
I have a Json data that looks like:

{
    "restaurant": null,
    "details": [
        {
            "text": {
                "text": "Tea",
                "coordinateX": 311
            },
            "price": {
                "unitPrice": 5.0,
                "coordinateX": 389
            }
        },
        {
            "text": {
                "text": "Americano",
                "coordinateX": 311
            },
            "price": {
                "unitPrice": 41.24,
                "coordinateX": 205,
            }
        },
        {
            "text": {
                "text": "Latte",
                "coordinateX": 130
            },
            "price": {
                "unitPrice": 43.24,
                "coordinateX": 205,
            }
        }
    ]
}

I'm using the model adapter pattern to map the json result from an API to the models I've created. My issue is that the nested objects are not being mapped. Only the the outermost object is.

ImageResult Object - this is the only one that is properly mapped

export class ImageResult {
    constructor(
        public Restaurant: string,
        public CapturedDetails: Array
    ) {}

    static adapt(item: any): ImageResult {
        return new ImageResult(
            item.restaurant,
            item.details
        );
      }
  }

Details Object - no longer mapped. Shown as generic Object

export class Details {
    constructor(
        public Text: Word,
        public UnitPrice: Price
    ) {}

    static adapt(item: any): Details {
        return new Details(
            item.text,
            item.price
        );
      }
  }

Word Object - no longer mapped. Shown as generic Object

export class Word {
    constructor(
        public Text: string = '',
        public CoordinateX: number  = 0
    ) {}

    static adapt(item: any): Word {
        return new Word(
            item.text,
            item.coordinateX
        );
      }
  }

Mapping when the API is called:

GetText(formData: FormData): Observable<ImageResult> {
    return this.httpClient.post(this.getServiceUrl('TextCapture'), formData)
    .pipe(map(ImageResult.adapt));
  }


问:
Pythonic way of not printing a error message up
I am trying to suppress a error/warning in my log while calling a library. Assume i have this code

```<code>        try:
            kazoo_client.start()
        except:
            pass
</code>```

This is calling a zookeeper client which throws some exception which bubble up, now i don't want the warn/error in my logs when i call kazoo_client.start() is there a way to get this suppressed when you call the client

答:
Assuming python 2.7.17

Try this approach:

```<code>import sys, StringIO

def funky() :
 "1" + 1 # This should raise an error

sys.stderr = StringIO.StringIO()
funky() # this should call the funky function
</code>```

And your code should look something like this:

```<code>import sys, StringIO

# import kazoo somehere around here

sys.stderr = StringIO.StringIO()
kazoo_client.start()
</code>```

And lastly the Python 3 example:

```<code>import sys
from io import StringIO
# import kazoo somehere around here

sys.stderr = StringIO()
kazoo_client.start()
</code>```

Body:
I am trying to suppress a error/warning in my log while calling a library. Assume i have this code

        try:
            kazoo_client.start()
        except:
            pass

This is calling a zookeeper client which throws some exception which bubble up, now i don't want the warn/error in my logs when i call kazoo_client.start() is there a way to get this suppressed when you call the client

Body:
Assuming python 2.7.17

Try this approach:

import sys, StringIO

def funky() :
 "1" + 1 # This should raise an error

sys.stderr = StringIO.StringIO()
funky() # this should call the funky function

And your code should look something like this:

import sys, StringIO

# import kazoo somehere around here

sys.stderr = StringIO.StringIO()
kazoo_client.start()

And lastly the Python 3 example:

import sys
from io import StringIO
# import kazoo somehere around here

sys.stderr = StringIO()
kazoo_client.start()


问:
Connect Operation timed out while running mvn test
I have created a new quarkus project using online tool with kotlin extenstion. I am able to execute ./mvnw compile quarkus:dev and curl on http://localhost:8080. However I am getting following exception while executing ./mvnw test.

```<code>[INFO] -------------------------------------------------------
[INFO]  T E S T S
[INFO] -------------------------------------------------------
[INFO] Running dev.sanket.ExampleResourceTest
2020-02-20 14:06:27,010 INFO  [io.quarkus] (main) Quarkus 1.2.1.Final started in 0.411s. Listening on: http://0.0.0.0:8081
2020-02-20 14:06:27,013 INFO  [io.quarkus] (main) Profile test activated.
2020-02-20 14:06:27,013 INFO  [io.quarkus] (main) Installed features: [cdi, kotlin, resteasy]
[ERROR] Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 78.626 s <<< FAILURE! - in dev.sanket.ExampleResourceTest
[ERROR] testHelloEndpoint  Time elapsed: 76.099 s  <<< ERROR!
java.net.ConnectException: Operation timed out (Connection timed out)
</code>```

Any idea what is causing this?

答:
Default configuration for quarkus.http.host is 0.0.0.0, if you want to run it as localhost while you are only in test phase, then you can add this to your properties file :

%test.quarkus.http.host=localhost

It is like specifying a set of properties for certain profile. It can be applied to other properties as well.

Further links : profiling and configuration in Quarkus.

Body:
I have created a new quarkus project using online tool with kotlin extenstion. I am able to execute ./mvnw compile quarkus:dev and curl on http://localhost:8080. However I am getting following exception while executing ./mvnw test.

[INFO] -------------------------------------------------------
[INFO]  T E S T S
[INFO] -------------------------------------------------------
[INFO] Running dev.sanket.ExampleResourceTest
2020-02-20 14:06:27,010 INFO  [io.quarkus] (main) Quarkus 1.2.1.Final started in 0.411s. Listening on: http://0.0.0.0:8081
2020-02-20 14:06:27,013 INFO  [io.quarkus] (main) Profile test activated.
2020-02-20 14:06:27,013 INFO  [io.quarkus] (main) Installed features: [cdi, kotlin, resteasy]
[ERROR] Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 78.626 s <<< FAILURE! - in dev.sanket.ExampleResourceTest
[ERROR] testHelloEndpoint  Time elapsed: 76.099 s  <<< ERROR!
java.net.ConnectException: Operation timed out (Connection timed out)

Any idea what is causing this?


问:
Google Maps info Bubble With Font Awesome Icons and bootstrap?
I am attempting to customize links int a Google Maps info-bubble with Bootstrap and font awesome Icons.

I was able to use a list-group from bootstrap for my links in the info bubble successfully, but when I tried to add a font awesome Icon to the link it just does not show up.

```<code><a href="https://www.youtube.com/watch?v=u8iaZF-iFNk" target="_blank" class="list-group-item list-group-item-action"> <i class="fab fa-youtube"></i> Hiking 42 Miles along Michigan's Lake Superior (Adventure Archive)</a>
</code>```

I followed the code on this link here: https://fontawesome.com/v4.7.0/examples/

But when I test on my site the font awesome icon doesn't show up like in the example I followed.

Not sure what I am doing wrong....

答:
Have you gotten the Font Awesome CDN in the  tags of your file as <link rel="stylesheet" href="path/to/font-awesome/css/font-awesome.min.css">? I don't know if you have issues with other icons in your website, but without that CDN, you may not be able to get your icons to show up! See Font Awesome's Troubleshooting Page.

What's your code so far? Do you have a parent
 above your anchor tag to match the class attributes of your list-group-item list-group-item-action anchor tag (but this may just be hierarchy issue, not the cause of your Font Awesome icons not showing up)? Still, check out this article by Bootstrap, under "Links and Buttons" header. Play around with it!

Body:
I am attempting to customize links int a Google Maps info-bubble with Bootstrap and font awesome Icons.

I was able to use a list-group from bootstrap for my links in the info bubble successfully, but when I tried to add a font awesome Icon to the link it just does not show up.

  Hiking 42 Miles along Michigan's Lake Superior (Adventure Archive)

I followed the code on this link here: https://fontawesome.com/v4.7.0/examples/

But when I test on my site the font awesome icon doesn't show up like in the example I followed.

Not sure what I am doing wrong....

Body:
Have you gotten the Font Awesome CDN in the <head> tags of your file as <link rel="stylesheet" href="path/to/font-awesome/css/font-awesome.min.css">? I don't know if you have issues with other icons in your website, but without that CDN, you may not be able to get your icons to show up! See Font Awesome's Troubleshooting Page.

What's your code so far? Do you have a parent <div class="list-group"> above your anchor tag to match the class attributes of your list-group-item list-group-item-action anchor tag (but this may just be hierarchy issue, not the cause of your Font Awesome icons not showing up)? Still, check out this article by Bootstrap, under "Links and Buttons" header. Play around with it!


问:
RPC Server is unavailable when trying to deploy pocket pc application
I'm currently developing an application for pocket pc in vb.net (.net compact framework 3.5) using Visual Studio 2008. The first time I deploy the application after starting VS it goes smooth but after the first deployment I keep getting the error "RPC Server is Unavailable". The only way to deploy again afterwards is to restart visual studio which can get annoying since I have to make dozens of deployments everyday.

I check Windows services manager and the RPC Server is running fine.

Any ideas of what might be causing this issue? I upgraded recently to Windows 10, never had this problem before on Windows 7.

答: clean solution from the parent project and rebuild worked for me.</p>