问:
How to tell what type of Java error you're getting in Eclipse
So As previously stated in another post, I'm currently in school for a Java class.  I am using eclipse, but I am trying to learn the difference between the errors I get in the console.  I don't believe it is telling me what error I am getting.  So, what is the best way to tell the difference?

Here is my code that I know is failing and I know why it is failing, "theres no data in the Array"  I just don't know what type of error I am getting.

```<code>int[][] a = {{5,2,8,4},{}};
System.out.println(a[1][2]);
</code>```

error that I am getting

```<code>Exception in thread "main" 123
java.lang.ArrayIndexOutOfBoundsException: 2
at test.main(test.java:82)
</code>```

I apologize for not being clear before.  I need to understand the difference between a Compile error, Run-time error, Logical Error and Syntax error.  And which category would this fall under?

答:
In Java, array index starts from 0. The 2D array does not have a row at a[1]. So, you are going out of bounds since the length of the array at a[1] is 0. At runtime, when you try to access a[1][2], it is out of bounds and thus the JVM throws the ArrayIndexOutOfBoundsException

You could try adding elements to the initial array to:

```<code>int[][] a = {{5,2,8,4},{1, 2, 3, 4}};
</code>```

Body:
So As previously stated in another post, I'm currently in school for a Java class.  I am using eclipse, but I am trying to learn the difference between the errors I get in the console.  I don't believe it is telling me what error I am getting.  So, what is the best way to tell the difference?

Here is my code that I know is failing and I know why it is failing, "theres no data in the Array"  I just don't know what type of error I am getting.

int[][] a = {{5,2,8,4},{}};
System.out.println(a[1][2]);

error that I am getting

Exception in thread "main" 123
java.lang.ArrayIndexOutOfBoundsException: 2
at test.main(test.java:82)

I apologize for not being clear before.  I need to understand the difference between a Compile error, Run-time error, Logical Error and Syntax error.  And which category would this fall under?

Body:
In Java, array index starts from 0. The 2D array does not have a row at a[1]. So, you are going out of bounds since the length of the array at a[1] is 0. At runtime, when you try to access a[1][2], it is out of bounds and thus the JVM throws the ArrayIndexOutOfBoundsException

You could try adding elements to the initial array to:

int[][] a = {{5,2,8,4},{1, 2, 3, 4}};


来源: stackexchange

问:
Changing Label in toolbar using wxPython
I currently have a toolbar in wxpython with an start icon. I want it so when this icon is clicked the icon and method that it uses changes to stop.

This is the code that I have so far:

```<code>#!/usr/bin/env python
# encoding: utf-8
"""
logClient2.py
Created by Allister on 2010-11-30.
"""

import wx
import sqlite3

WINDOW_SIZE = (900,400)

class logClient(wx.Frame):
    def __init__(self, parent, id, title):

        wx.Frame.__init__(self, parent, id, title, size=WINDOW_SIZE)

        self.toolbar = self.CreateToolBar()
        self.toolbar.AddLabelTool(1, 'Refresh', wx.Bitmap('icons/refresh_icon.png'))
        self.toolbar.Realize()

        self.Bind(wx.EVT_TOOL, self.startLiveUpdate, id=1)

        self.Show(True)

    def startLiveUpdate(self, event):
      pass

if __name__ == '__main__':
    app = wx.App(False)
    logClient(None, -1, "Log Event Viewer")
    app.MainLoop()
</code>```

Not really sure what to put in the startLiveUpdate method ?

Thanks for any help!

答:
Here's a quickly hacked together one. Tested on Ubuntu 9.10, Python 2.6, wx 2.8.10.1</p>

```<code>#!/usr/bin/env python
# encoding: utf-8
"""
logClient2.py
Created by Allister on 2010-11-30.
"""

import wx
import sqlite3

WINDOW_SIZE = (900,400)

class logClient(wx.Frame):
    def __init__(self, parent, id, title):

        wx.Frame.__init__(self, parent, id, title, size=WINDOW_SIZE)

        self.toolbar = self.CreateToolBar()
        self.startLiveUpdate(None)

        self.Show(True)

    def startLiveUpdate(self, event):
        self.createToolbarItem("Refresh", "refresh.jpg", self.stopLiveUpdate)

    def stopLiveUpdate(self, event):
        self.createToolbarItem("Stop", "refresh2.jpg", self.startLiveUpdate)

    def createToolbarItem(self, label, imageName, method):
        self.toolbar.RemoveTool(1)
        self.toolbar.AddLabelTool(1, label, wx.Bitmap(imageName))
        self.toolbar.Realize()
        self.Bind(wx.EVT_TOOL, method, id=1)

if __name__ == '__main__':
    app = wx.App(False)
    logClient(None, -1, "Log Event Viewer")
    app.MainLoop()
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I currently have a toolbar in wxpython with an start icon. I want it so when this icon is clicked the icon and method that it uses changes to stop.

This is the code that I have so far:

#!/usr/bin/env python
# encoding: utf-8
"""
logClient2.py
Created by Allister on 2010-11-30.
"""

import wx
import sqlite3

WINDOW_SIZE = (900,400)

class logClient(wx.Frame):
    def __init__(self, parent, id, title):

        wx.Frame.__init__(self, parent, id, title, size=WINDOW_SIZE)

        self.toolbar = self.CreateToolBar()
        self.toolbar.AddLabelTool(1, 'Refresh', wx.Bitmap('icons/refresh_icon.png'))
        self.toolbar.Realize()

        self.Bind(wx.EVT_TOOL, self.startLiveUpdate, id=1)

        self.Show(True)

    def startLiveUpdate(self, event):
      pass

if __name__ == '__main__':
    app = wx.App(False)
    logClient(None, -1, "Log Event Viewer")
    app.MainLoop()

Not really sure what to put in the startLiveUpdate method ?

Thanks for any help!

Body:
Here's a quickly hacked together one. Tested on Ubuntu 9.10, Python 2.6, wx 2.8.10.1

#!/usr/bin/env python
# encoding: utf-8
"""
logClient2.py
Created by Allister on 2010-11-30.
"""

import wx
import sqlite3

WINDOW_SIZE = (900,400)

class logClient(wx.Frame):
    def __init__(self, parent, id, title):

        wx.Frame.__init__(self, parent, id, title, size=WINDOW_SIZE)

        self.toolbar = self.CreateToolBar()
        self.startLiveUpdate(None)

        self.Show(True)

    def startLiveUpdate(self, event):
        self.createToolbarItem("Refresh", "refresh.jpg", self.stopLiveUpdate)

    def stopLiveUpdate(self, event):
        self.createToolbarItem("Stop", "refresh2.jpg", self.startLiveUpdate)

    def createToolbarItem(self, label, imageName, method):
        self.toolbar.RemoveTool(1)
        self.toolbar.AddLabelTool(1, label, wx.Bitmap(imageName))
        self.toolbar.Realize()
        self.Bind(wx.EVT_TOOL, method, id=1)

if __name__ == '__main__':
    app = wx.App(False)
    logClient(None, -1, "Log Event Viewer")
    app.MainLoop()


答:
You are getting an ArrayOutOfBoundsException. The array a[1] is empty, and so when you try to read from position 2 Java is going to complain because the referenced memory location is outside the bounds of the array a[1].

This is a language safety feature of Java that is supposed to keep you from doing dangerous things. In a language like C where there is no default ArrayOutOfBoundsException, accessing memory locations outside of the bounds of an array can sometimes result in segmentation violations that crash your program, and even if that doesn't happen, it will often return random data and should be considered a bug.

ContentLicense: CC BY-SA 3.0

Title: How to tell what type of Java error you're getting in Eclipse


问:
Custom NSButton drawing messes up text rendering
I'm subclassing NSButton / NSButtonCell and everything works fine, but at least in Retina drawing as soon as I implement any of the drawing functions in either NSButton or NSButtonCell, the text rendering changes no matter whether I do some custom text drawing or delegate straight to the super implementation.

As you can see the text goes much thinner with just the anti-aliasing changing.

When I examine this in Xcode's Reveal-rip off, I see that the text is embedded in a NSButtonTextField when none of the drawing methods are overridden. As soon as any of the drawing methods are overridden, the NSButtonTextField disappears.

None of this happens when I insert a background layer behind the button text and set

```<code>button.isBorderd = false
</code>```

but I don't much like that solution.

Is there any way of getting the same "fat" text rendering without messing with layers? Perhaps an attributed string attribute, a special text drawing command, anything?

Any help would be appreciated/

答:
I wasn't able to reproduce your work-around with a background layer, though I might've been doing it wrong.

I ended up adding an NSTextField as a subview to the button, with the following attributes:

```<code>_titleTextField = [[NSTextField alloc] initWithFrame:NSZeroRect];
[_titleTextField setBordered:NO];
[_titleTextField setDrawsBackground:NO];
[_titleTextField setFont:[NSFont systemFontOfSize:13]];
[_titleTextField setTextColor:[FantasticalColors color:@"dimLabelTextColor"]];
[_titleTextField setStringValue:[self title]];
[_titleTextField setEditable:NO];
[_titleTextField setFocusRingType:NSFocusRingTypeNone];
[self addSubview:_titleTextField];
</code>```

Then I was able to render all non-text in my cell's drawRect, and then let the text field render the text. Also not ideal, but was the only way I was able to match font rendering.

Body:
I'm subclassing NSButton / NSButtonCell and everything works fine, but at least in Retina drawing as soon as I implement any of the drawing functions in either NSButton or NSButtonCell, the text rendering changes no matter whether I do some custom text drawing or delegate straight to the super implementation.

As you can see the text goes much thinner with just the anti-aliasing changing.

When I examine this in Xcode's Reveal-rip off, I see that the text is embedded in a NSButtonTextField when none of the drawing methods are overridden. As soon as any of the drawing methods are overridden, the NSButtonTextField disappears.

None of this happens when I insert a background layer behind the button text and set

button.isBorderd = false

but I don't much like that solution.

Is there any way of getting the same "fat" text rendering without messing with layers? Perhaps an attributed string attribute, a special text drawing command, anything?

Any help would be appreciated/

Body:
I wasn't able to reproduce your work-around with a background layer, though I might've been doing it wrong.

I ended up adding an NSTextField as a subview to the button, with the following attributes:

_titleTextField = [[NSTextField alloc] initWithFrame:NSZeroRect];
[_titleTextField setBordered:NO];
[_titleTextField setDrawsBackground:NO];
[_titleTextField setFont:[NSFont systemFontOfSize:13]];
[_titleTextField setTextColor:[FantasticalColors color:@"dimLabelTextColor"]];
[_titleTextField setStringValue:[self title]];
[_titleTextField setEditable:NO];
[_titleTextField setFocusRingType:NSFocusRingTypeNone];
[self addSubview:_titleTextField];

Then I was able to render all non-text in my cell's drawRect, and then let the text field render the text. Also not ideal, but was the only way I was able to match font rendering.


问:
Python base64.b64encode. How to obtain the 6 bit value for each encoded character?
For example, say I perform

```<code>base64.b64encode('Monday')
</code>```

to obtain 'TW9uZGF5'.  But when I want to access the 6 bits for each of the characters, I get something like this (the ASCII values for each of these characters):

```<code>[84 87 57 117 90 71 70 53]
</code>```

when I want to obtain the 6 bit (values between 0 and 63] equivalents:

```<code>[19 22 61  46 25  6  5 57]
</code>```

Is there a way to do so without looping through the list and manually changing them accordingly?

Thanks!

Body:
For example, say I perform

base64.b64encode('Monday')

to obtain 'TW9uZGF5'.  But when I want to access the 6 bits for each of the characters, I get something like this (the ASCII values for each of these characters):

[84 87 57 117 90 71 70 53]

when I want to obtain the 6 bit (values between 0 and 63] equivalents:

[19 22 61  46 25  6  5 57]

Is there a way to do so without looping through the list and manually changing them accordingly?

Thanks!

Body:
Just use mask like in c:

a & 63

You can also shift the number to get 6 higher bits:

a >> 2 & 63

Simple way:

translate_dict = {
    'A': 0, 'Q': 16, 'g': 32, 'w': 48,
    'B': 1, 'R': 17, 'h': 33, 'x': 49,
    'C': 2, 'S': 18, 'i': 34, 'y': 50,
    'D': 3, 'T': 19, 'j': 35, 'z': 51,
    'E': 4, 'U': 20, 'k': 36, '0': 52,
    'F': 5, 'V': 21, 'l': 37, '1': 53,
    'G': 6, 'W': 22, 'm': 38, '2': 54,
    'H': 7, 'X': 23, 'n': 39, '3': 55,
    'I': 8, 'Y': 24, 'o': 40, '4': 56,
    'J': 9, 'Z': 25, 'p': 41, '5': 57,
    'K': 10, 'a': 26, 'q': 42, '6': 58,
    'L': 11, 'b': 27, 'r': 43, '7': 59,
    'M': 12, 'c': 28, 's': 44, '8': 60,
    'N': 13, 'd': 29, 't': 45, '9': 61,
    'O': 14, 'e': 30, 'u': 46, '+': 62,
    'P': 15, 'f': 31, 'v': 47, '/': 63
}

print([translate_dict[sym] for sym in 'TW9uZGF5'])


问:
Valgrind errors
I have written a code for an rpn calculator which takes input from a file.

The code seems to work with my test cases but Valgrind tells me there are 28 errors. I am new to C and I haven't used Valgrind much. I can't understand what these errors are. Can someone please help me understand what they are and how to fix them?

There is no memory leakage.

This is my code, sorry for the very messy code.

```<code>#include <stdio.h>
#include <stdlib.h>
#include<string.h>

float rpn (char * filename)
{

 float result;

   FILE *in = fopen(filename, "r");
if (in == NULL)
  {
    fprintf(stderr," input file fopen fail\n");
    return EXIT_FAILURE;  // if fopen fails, return false
  }

int count=0;
char c;

 for (c = getc(in); c != EOF && c!='\n'; c = getc(in))
  {
    if(c==' ')
     {
       count = count + 1;
     }
 }
 fclose(in);

 if (count==0)
 {
  fprintf(stderr,"EMPTY FILE\n");
  fclose(in);
  return EXIT_SUCCESS;
}

 fprintf(stderr,"count=%d\n",count);

 FILE *in2 = fopen(filename, "r");
 if (in == NULL)
   {
     fprintf(stderr," input file fopen fail\n");
     return EXIT_FAILURE;  // if fopen fails, return false
   }
   int num = 0;
   int num_op = 0;
   int index =0;
   int len = count+1;

    fprintf(stderr,"len = %d\n",len);

    char**input = malloc(sizeof(char*)*(len+1));

    for(int i =0;i<len; i++)
     {

        input[i] = malloc(sizeof(char));

        fscanf(in2,"%s",input[i]);

          if((strcmp(input[i],"+")==0)||(strcmp(input[i],"-")==0)||(strcmp(input[i],"*")==0)||(strcmp(input[i],"/")==0))
     {
       num_op = num_op + 1;
     }
  else if(atof(input[i])||(strcmp(input[i],"0")==0)||(strcmp(input[i],"-0")==0))
     {
       index = index+1;
       num = num+1;
     }
   }
  fclose(in2);

fprintf(stderr,"numbers= %d\n",num);
fprintf(stderr,"num_op= %d\n",num_op);
fprintf(stderr,"index= %d\n",index);

if((num != (num_op+1)))
{
 fprintf(stderr,"Bad Input\n");
  return EXIT_FAILURE;
}

for (int f=index;f<len;f++)
 {
    if(!((strcmp(input[f],"+")==0)||(strcmp(input[f],"-")==0)||(strcmp(input[f],"*")==0)||(strcmp(input[f],"/")==0)))
      {
        fprintf(stderr,"Bad Input\n");
        return EXIT_FAILURE;
      }
 }

float *stack = malloc(sizeof(float)*(index+1));

for(int h=0; h<index; h++)
  {
     stack[h] = atof(input[h]);
  }

   /*   for(int l =0;(l<index); l++)
  {
    printf("stack[%d] = %lf\n",l,stack[l]);
 }

for(int j =0;(j<len); j++)
   {
   printf("input[%d] = %s\n",j,input[j]);
   }
 */

   int u = index-1;
   for(int k=index;k<len;k++)
     {
       if ((strcmp(input[k],"+"))==0)
         {

               stack[u-1] = (stack[u-1] + stack[u]);
               printf("Result + = %lf\n",stack[u-1]);
         }

    else if ((strcmp(input[k],"-"))==0)
      {
               stack[u-1] = (stack[u-1] - stack[u]);
               printf("Result -  = %lf\n",stack[u-1]);
      }
  else if ((strcmp(input[k],"*"))==0)
      {
               stack[u-1] = (stack[u-1] * stack[u]);
                printf("Result *  = %lf\n",stack[u-1]);
      }

    else if ((strcmp(input[k],"/"))==0)
    {
               stack[u-1] = (stack[u-1] / stack[u]);
                printf("Result /  = %lf\n",stack[u-1]);
     }

      else{
                printf("Invalid Operator\n");

                return EXIT_FAILURE;
           }

                  if ((u) == 1)
                  {
                     printf("stack_last= %lf\n",stack[u-1]);
                     result = stack[u-1];
                     for(int d =0;d<len; d++)
                        {

                          free(input[d]);
                        }

                    free(input);
                    free(stack);
                    return result;

                  }
               u = u-1;
     }

  return EXIT_FAILURE;

   }
   int main (int argc, char ** argv) {
     if (argc != 2) {
    fprintf(stderr, "Incorrect number of arguments.\n");
    fprintf(stderr, "Usage: ./pa11 <input file>\n");
    return EXIT_FAILURE;

                   }

   float result; //store the result of your calculation here.

  result=(rpn(argv[1]));

fprintf(stdout,"Result = %f\n", result);

return EXIT_SUCCESS;
  }
</code>```

and these are the errors from valgrind

```<code>==7692== Invalid write of size 1
==7692==    at 0x391C858C76: _IO_vfscanf (vfscanf.c:1110)
==7692==    by 0x391C8645EA: __isoc99_fscanf (isoc99_fscanf.c:35)
==7692==    by 0x401320: rpn (pa11.c:70)
==7692==    by 0x401CAD: main (pa11.c:199)
==7692==  Address 0x4c3e5b1 is 0 bytes after a block of size 1 alloc'd
==7692==    at 0x4A06A2E: malloc (vg_replace_malloc.c:270)
==7692==    by 0x4012F4: rpn (pa11.c:68)
==7692==    by 0x401CAD: main (pa11.c:199)
==7692==
==7692== Invalid read of size 1
==7692==    at 0x391C83AC70: ____strtod_l_internal (strtod_l.c:732)
==7692==    by 0x401411: rpn (pa11.c:79)
==7692==    by 0x401CAD: main (pa11.c:199)
==7692==  Address 0x4c3e5b1 is 0 bytes after a block of size 1 alloc'd
==7692==    at 0x4A06A2E: malloc (vg_replace_malloc.c:270)
==7692==    by 0x4012F4: rpn (pa11.c:68)
==7692==    by 0x401CAD: main (pa11.c:199)
==7692==
==7692== Invalid read of size 1
==7692==    at 0x391C83A478: ____strtod_l_internal (strtod_l.c:787)
==7692==    by 0x401411: rpn (pa11.c:79)
==7692==    by 0x401CAD: main (pa11.c:199)
==7692==  Address 0x4c3e5b1 is 0 bytes after a block of size 1 alloc'd
==7692==    at 0x4A06A2E: malloc (vg_replace_malloc.c:270)
==7692==    by 0x4012F4: rpn (pa11.c:68)
==7692==    by 0x401CAD: main (pa11.c:199)
==7692==
==7692== Invalid write of size 1
==7692==    at 0x391C858257: _IO_vfscanf (vfscanf.c:1031)
==7692==    by 0x391C8645EA: __isoc99_fscanf (isoc99_fscanf.c:35)
==7692==    by 0x401320: rpn (pa11.c:70)
==7692==    by 0x401CAD: main (pa11.c:199)
==7692==  Address 0x4c3e601 is 0 bytes after a block of size 1 alloc'd
==7692==    at 0x4A06A2E: malloc (vg_replace_malloc.c:270)
==7692==    by 0x4012F4: rpn (pa11.c:68)
==7692==    by 0x401CAD: main (pa11.c:199)
==7692==
==7692== Invalid read of size 1
==7692==    at 0x391C839E30: str_to_mpn (strtod_l.c:327)
==7692==    by 0x391C83B3D2: ____strtod_l_internal (strtod_l.c:1115)
==7692==    by 0x401411: rpn (pa11.c:79)
==7692==    by 0x401CAD: main (pa11.c:199)
==7692==  Address 0x4c3e601 is 0 bytes after a block of size 1 alloc'd
==7692==    at 0x4A06A2E: malloc (vg_replace_malloc.c:270)
==7692==    by 0x4012F4: rpn (pa11.c:68)
==7692==    by 0x401CAD: main (pa11.c:199)
==7692==
==7692== Invalid read of size 1
==7692==    at 0x4A084E8: strcmp (mc_replace_strmem.c:729)
==7692==    by 0x40133D: rpn (pa11.c:75)
==7692==    by 0x401CAD: main (pa11.c:199)
==7692==  Address 0x4c3e6a1 is 0 bytes after a block of size 1 alloc'd
==7692==    at 0x4A06A2E: malloc (vg_replace_malloc.c:270)
==7692==    by 0x4012F4: rpn (pa11.c:68)
==7692==    by 0x401CAD: main (pa11.c:199)
==7692==
==7692== Invalid read of size 1
==7692==    at 0x4A084E8: strcmp (mc_replace_strmem.c:729)
==7692==    by 0x401374: rpn (pa11.c:75)
==7692==    by 0x401CAD: main (pa11.c:199)
==7692==  Address 0x4c3e6f1 is 0 bytes after a block of size 1 alloc'd
==7692==    at 0x4A06A2E: malloc (vg_replace_malloc.c:270)
==7692==    by 0x4012F4: rpn (pa11.c:68)
==7692==    by 0x401CAD: main (pa11.c:199)
==7692==
numbers= 3
num_op= 2
index= 3
==7692== Invalid read of size 1
==7692==    at 0x4A084E8: strcmp (mc_replace_strmem.c:729)
==7692==    by 0x401619: rpn (pa11.c:99)
==7692==    by 0x401CAD: main (pa11.c:199)
==7692==  Address 0x4c3e6a1 is 0 bytes after a block of size 1 alloc'd
==7692==    at 0x4A06A2E: malloc (vg_replace_malloc.c:270)
==7692==    by 0x4012F4: rpn (pa11.c:68)
==7692==    by 0x401CAD: main (pa11.c:199)
==7692==
==7692== Invalid read of size 1
==7692==    at 0x4A084E8: strcmp (mc_replace_strmem.c:729)
==7692==    by 0x401650: rpn (pa11.c:99)
==7692==    by 0x401CAD: main (pa11.c:199)
==7692==  Address 0x4c3e6f1 is 0 bytes after a block of size 1 alloc'd
==7692==    at 0x4A06A2E: malloc (vg_replace_malloc.c:270)
==7692==    by 0x4012F4: rpn (pa11.c:68)
==7692==    by 0x401CAD: main (pa11.c:199)
==7692==
==7692== Invalid read of size 1
==7692==    at 0x391C83AC70: ____strtod_l_internal (strtod_l.c:732)
==7692==    by 0x40177B: rpn (pa11.c:112)
==7692==    by 0x401CAD: main (pa11.c:199)
==7692==  Address 0x4c3e5b1 is 0 bytes after a block of size 1 alloc'd
==7692==    at 0x4A06A2E: malloc (vg_replace_malloc.c:270)
==7692==    by 0x4012F4: rpn (pa11.c:68)
==7692==    by 0x401CAD: main (pa11.c:199)
==7692==
==7692== Invalid read of size 1
==7692==    at 0x391C83A478: ____strtod_l_internal (strtod_l.c:787)
==7692==    by 0x40177B: rpn (pa11.c:112)
==7692==    by 0x401CAD: main (pa11.c:199)
==7692==  Address 0x4c3e5b1 is 0 bytes after a block of size 1 alloc'd
==7692==    at 0x4A06A2E: malloc (vg_replace_malloc.c:270)
==7692==    by 0x4012F4: rpn (pa11.c:68)
==7692==    by 0x401CAD: main (pa11.c:199)
==7692==
==7692== Invalid read of size 1
==7692==    at 0x391C839E30: str_to_mpn (strtod_l.c:327)
==7692==    by 0x391C83B3D2: ____strtod_l_internal (strtod_l.c:1115)
==7692==    by 0x40177B: rpn (pa11.c:112)
==7692==    by 0x401CAD: main (pa11.c:199)
==7692==  Address 0x4c3e601 is 0 bytes after a block of size 1 alloc'd
==7692==    at 0x4A06A2E: malloc (vg_replace_malloc.c:270)
==7692==    by 0x4012F4: rpn (pa11.c:68)
==7692==    by 0x401CAD: main (pa11.c:199)
==7692==
==7692== Invalid read of size 1
==7692==    at 0x4A084E8: strcmp (mc_replace_strmem.c:729)
==7692==    by 0x4017E8: rpn (pa11.c:134)
==7692==    by 0x401CAD: main (pa11.c:199)
==7692==  Address 0x4c3e6a1 is 0 bytes after a block of size 1 alloc'd
==7692==    at 0x4A06A2E: malloc (vg_replace_malloc.c:270)
==7692==    by 0x4012F4: rpn (pa11.c:68)
==7692==    by 0x401CAD: main (pa11.c:199)
==7692==
Result + = 12.000000
==7692== Invalid read of size 1
==7692==    at 0x4A084E8: strcmp (mc_replace_strmem.c:729)
==7692==    by 0x40187C: rpn (pa11.c:141)
==7692==    by 0x401CAD: main (pa11.c:199)
==7692==  Address 0x4c3e6f1 is 0 bytes after a block of size 1 alloc'd
==7692==    at 0x4A06A2E: malloc (vg_replace_malloc.c:270)
==7692==    by 0x4012F4: rpn (pa11.c:68)
==7692==    by 0x401CAD: main (pa11.c:199)
==7692==
Result -  = -5.000000
stack_last= -5.000000
Result = -5.000000
==7692==
==7692== HEAP SUMMARY:
==7692==     in use at exit: 0 bytes in 0 blocks
==7692==   total heap usage: 10 allocs, 10 frees, 1,773 bytes allocated
==7692==
==7692== All heap blocks were freed -- no leaks are possible
==7692==
==7692== For counts of detected and suppressed errors, rerun with: -v
==7692== ERROR SUMMARY: 28 errors from 14 contexts (suppressed: 6 from 6)
</code>```

答:
Clearly you have error here:

```<code>    input[i] = malloc(sizeof(char));

    fscanf(in2,"%s",input[i]);
</code>```

if you want input one char you need use %c instead of %s,
for %s you need allocate at least two char, one for symbol,
another for trailing '\0'

Title: Valgrind errors

Body:
I have written a code for an rpn calculator which takes input from a file.

The code seems to work with my test cases but Valgrind tells me there are 28 errors. I am new to C and I haven't used Valgrind much. I can't understand what these errors are. Can someone please help me understand what they are and how to fix them?

There is no memory leakage.

This is my code, sorry for the very messy code.

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

float rpn (char * filename)
{

 float result;

   FILE *in = fopen(filename, "r");
if (in == NULL)
  {
    fprintf(stderr," input file fopen fail\n");
    return EXIT_FAILURE;  // if fopen fails, return false
  }

int count=0;
char c;

 for (c = getc(in); c != EOF && c!='\n'; c = getc(in))
  {
    if(c==' ')
     {
       count = count + 1;
     }
 }
 fclose(in);

 if (count==0)
 {
  fprintf(stderr,"EMPTY FILE\n");
  fclose(in);
  return EXIT_SUCCESS;
}

 fprintf(stderr,"count=%d\n",count);

 FILE *in2 = fopen(filename, "r");
 if (in == NULL)
   {
     fprintf(stderr," input file fopen fail\n");
     return EXIT_FAILURE;  // if fopen fails, return false
   }
   int num = 0;
   int num_op = 0;
   int index =0;
   int len = count+1;

    fprintf(stderr,"len = %d\n",len);

    char**input = malloc(sizeof(char*)*(len+1));

    for(int i =0;i<len; i++)
     {

        input[i] = malloc(sizeof(char));

        fscanf(in2,"%s",input[i]);

          if((strcmp(input[i],"+")==0)||(strcmp(input[i],"-")==0)||(strcmp(input[i],"*")==0)||(strcmp(input[i],"/")==0))
     {
       num_op = num_op + 1;
     }
  else if(atof(input[i])||(strcmp(input[i],"0")==0)||(strcmp(input[i],"-0")==0))
     {
       index = index+1;
       num = num+1;
     }
   }
  fclose(in2);

fprintf(stderr,"numbers= %d\n",num);
fprintf(stderr,"num_op= %d\n",num_op);
fprintf(stderr,"index= %d\n",index);

if((num != (num_op+1)))
{
 fprintf(stderr,"Bad Input\n");
  return EXIT_FAILURE;
}

for (int f=index;f<len;f++)
 {
    if(!((strcmp(input[f],"+")==0)||(strcmp(input[f],"-")==0)||(strcmp(input[f],"*")==0)||(strcmp(input[f],"/")==0)))
      {
        fprintf(stderr,"Bad Input\n");
        return EXIT_FAILURE;
      }
 }

float *stack = malloc(sizeof(float)*(index+1));

for(int h=0; h<index; h++)
  {
     stack[h] = atof(input[h]);
  }

   /*   for(int l =0;(l<index); l++)
  {
    printf("stack[%d] = %lf\n",l,stack[l]);
 }

for(int j =0;(j<len); j++)
   {
   printf("input[%d] = %s\n",j,input[j]);
   }
 */

   int u = index-1;
   for(int k=index;k<len;k++)
     {
       if ((strcmp(input[k],"+"))==0)
         {

               stack[u-1] = (stack[u-1] + stack[u]);
               printf("Result + = %lf\n",stack[u-1]);
         }

    else if ((strcmp(input[k],"-"))==0)
      {
               stack[u-1] = (stack[u-1] - stack[u]);
               printf("Result -  = %lf\n",stack[u-1]);
      }
  else if ((strcmp(input[k],"*"))==0)
      {
               stack[u-1] = (stack[u-1] * stack[u]);
                printf("Result *  = %lf\n",stack[u-1]);
      }

    else if ((strcmp(input[k],"/"))==0)
    {
               stack[u-1] = (stack[u-1] / stack[u]);
                printf("Result /  = %lf\n",stack[u-1]);
     }

      else{
                printf("Invalid Operator\n");

                return EXIT_FAILURE;
           }

                  if ((u) == 1)
                  {
                     printf("stack_last= %lf\n",stack[u-1]);
                     result = stack[u-1];
                     for(int d =0;d<len; d++)
                        {

                          free(input[d]);
                        }

                    free(input);
                    free(stack);
                    return result;

                  }
               u = u-1;
     }

  return EXIT_FAILURE;

   }
   int main (int argc, char ** argv) {
     if (argc != 2) {
    fprintf(stderr, "Incorrect number of arguments.\n");
    fprintf(stderr, "Usage: ./pa11 <input file>\n");
    return EXIT_FAILURE;

                   }

   float result; //store the result of your calculation here.

  result=(rpn(argv[1]));

fprintf(stdout,"Result = %f\n", result);

return EXIT_SUCCESS;
  }

and these are the errors from valgrind

==7692== Invalid write of size 1
==7692==    at 0x391C858C76: _IO_vfscanf (vfscanf.c:1110)
==7692==    by 0x391C8645EA: __isoc99_fscanf (isoc99_fscanf.c:35)
==7692==    by 0x401320: rpn (pa11.c:70)
==7692==    by 0x401CAD: main (pa11.c:199)
==7692==  Address 0x4c3e5b1 is 0 bytes after a block of size 1 alloc'd
==7692==    at 0x4A06A2E: malloc (vg_replace_malloc.c:270)
==7692==    by 0x4012F4: rpn (pa11.c:68)
==7692==    by 0x401CAD: main (pa11.c:199)
==7692==
==7692== Invalid read of size 1
==7692==    at 0x391C83AC70: ____strtod_l_internal (strtod_l.c:732)
==7692==    by 0x401411: rpn (pa11.c:79)
==7692==    by 0x401CAD: main (pa11.c:199)
==7692==  Address 0x4c3e5b1 is 0 bytes after a block of size 1 alloc'd
==7692==    at 0x4A06A2E: malloc (vg_replace_malloc.c:270)
==7692==    by 0x4012F4: rpn (pa11.c:68)
==7692==    by 0x401CAD: main (pa11.c:199)
==7692==
==7692== Invalid read of size 1
==7692==    at 0x391C83A478: ____strtod_l_internal (strtod_l.c:787)
==7692==    by 0x401411: rpn (pa11.c:79)
==7692==    by 0x401CAD: main (pa11.c:199)
==7692==  Address 0x4c3e5b1 is 0 bytes after a block of size 1 alloc'd
==7692==    at 0x4A06A2E: malloc (vg_replace_malloc.c:270)
==7692==    by 0x4012F4: rpn (pa11.c:68)
==7692==    by 0x401CAD: main (pa11.c:199)
==7692==
==7692== Invalid write of size 1
==7692==    at 0x391C858257: _IO_vfscanf (vfscanf.c:1031)
==7692==    by 0x391C8645EA: __isoc99_fscanf (isoc99_fscanf.c:35)
==7692==    by 0x401320: rpn (pa11.c:70)
==7692==    by 0x401CAD: main (pa11.c:199)
==7692==  Address 0x4c3e601 is 0 bytes after a block of size 1 alloc'd
==7692==    at 0x4A06A2E: malloc (vg_replace_malloc.c:270)
==7692==    by 0x4012F4: rpn (pa11.c:68)
==7692==    by 0x401CAD: main (pa11.c:199)
==7692==
==7692== Invalid read of size 1
==7692==    at 0x391C839E30: str_to_mpn (strtod_l.c:327)
==7692==    by 0x391C83B3D2: ____strtod_l_internal (strtod_l.c:1115)
==7692==    by 0x401411: rpn (pa11.c:79)
==7692==    by 0x401CAD: main (pa11.c:199)
==7692==  Address 0x4c3e601 is 0 bytes after a block of size 1 alloc'd
==7692==    at 0x4A06A2E: malloc (vg_replace_malloc.c:270)
==7692==    by 0x4012F4: rpn (pa11.c:68)
==7692==    by 0x401CAD: main (pa11.c:199)
==7692==
==7692== Invalid read of size 1
==7692==    at 0x4A084E8: strcmp (mc_replace_strmem.c:729)
==7692==    by 0x40133D: rpn (pa11.c:75)
==7692==    by 0x401CAD: main (pa11.c:199)
==7692==  Address 0x4c3e6a1 is 0 bytes after a block of size 1 alloc'd
==7692==    at 0x4A06A2E: malloc (vg_replace_malloc.c:270)
==7692==    by 0x4012F4: rpn (pa11.c:68)
==7692==    by 0x401CAD: main (pa11.c:199)
==7692==
==7692== Invalid read of size 1
==7692==    at 0x4A084E8: strcmp (mc_replace_strmem.c:729)
==7692==    by 0x401374: rpn (pa11.c:75)
==7692==    by 0x401CAD: main (pa11.c:199)
==7692==  Address 0x4c3e6f1 is 0 bytes after a block of size 1 alloc'd
==7692==    at 0x4A06A2E: malloc (vg_replace_malloc.c:270)
==7692==    by 0x4012F4: rpn (pa11.c:68)
==7692==    by 0x401CAD: main (pa11.c:199)
==7692==
numbers= 3
num_op= 2
index= 3
==7692== Invalid read of size 1
==7692==    at 0x4A084E8: strcmp (mc_replace_strmem.c:729)
==7692==    by 0x401619: rpn (pa11.c:99)
==7692==    by 0x401CAD: main (pa11.c:199)
==7692==  Address 0x4c3e6a1 is 0 bytes after a block of size 1 alloc'd
==7692==    at 0x4A06A2E: malloc (vg_replace_malloc.c:270)
==7692==    by 0x4012F4: rpn (pa11.c:68)
==7692==    by 0x401CAD: main (pa11.c:199)
==7692==
==7692== Invalid read of size 1
==7692==    at 0x4A084E8: strcmp (mc_replace_strmem.c:729)
==7692==    by 0x401650: rpn (pa11.c:99)
==7692==    by 0x401CAD: main (pa11.c:199)
==7692==  Address 0x4c3e6f1 is 0 bytes after a block of size 1 alloc'd
==7692==    at 0x4A06A2E: malloc (vg_replace_malloc.c:270)
==7692==    by 0x4012F4: rpn (pa11.c:68)
==7692==    by 0x401CAD: main (pa11.c:199)
==7692==
==7692== Invalid read of size 1
==7692==    at 0x391C83AC70: ____strtod_l_internal (strtod_l.c:732)
==7692==    by 0x40177B: rpn (pa11.c:112)
==7692==    by 0x401CAD: main (pa11.c:199)
==7692==  Address 0x4c3e5b1 is 0 bytes after a block of size 1 alloc'd
==7692==    at 0x4A06A2E: malloc (vg_replace_malloc.c:270)
==7692==    by 0x4012F4: rpn (pa11.c:68)
==7692==    by 0x401CAD: main (pa11.c:199)
==7692==
==7692== Invalid read of size 1
==7692==    at 0x391C83A478: ____strtod_l_internal (strtod_l.c:787)
==7692==    by 0x40177B: rpn (pa11.c:112)
==7692==    by 0x401CAD: main (pa11.c:199)
==7692==  Address 0x4c3e5b1 is 0 bytes after a block of size 1 alloc'd
==7692==    at 0x4A06A2E: malloc (vg_replace_malloc.c:270)
==7692==    by 0x4012F4: rpn (pa11.c:68)
==7692==    by 0x401CAD: main (pa11.c:199)
==7692==
==7692== Invalid read of size 1
==7692==    at 0x391C839E30: str_to_mpn (strtod_l.c:327)
==7692==    by 0x391C83B3D2: ____strtod_l_internal (strtod_l.c:1115)
==7692==    by 0x40177B: rpn (pa11.c:112)
==7692==    by 0x401CAD: main (pa11.c:199)
==7692==  Address 0x4c3e601 is 0 bytes after a block of size 1 alloc'd
==7692==    at 0x4A06A2E: malloc (vg_replace_malloc.c:270)
==7692==    by 0x4012F4: rpn (pa11.c:68)
==7692==    by 0x401CAD: main (pa11.c:199)
==7692==
==7692== Invalid read of size 1
==7692==    at 0x4A084E8: strcmp (mc_replace_strmem.c:729)
==7692==    by 0x4017E8: rpn (pa11.c:134)
==7692==    by 0x401CAD: main (pa11.c:199)
==7692==  Address 0x4c3e6a1 is 0 bytes after a block of size 1 alloc'd
==7692==    at 0x4A06A2E: malloc (vg_replace_malloc.c:270)
==7692==    by 0x4012F4: rpn (pa11.c:68)
==7692==    by 0x401CAD: main (pa11.c:199)
==7692==
Result + = 12.000000
==7692== Invalid read of size 1
==7692==    at 0x4A084E8: strcmp (mc_replace_strmem.c:729)
==7692==    by 0x40187C: rpn (pa11.c:141)
==7692==    by 0x401CAD: main (pa11.c:199)
==7692==  Address 0x4c3e6f1 is 0 bytes after a block of size 1 alloc'd
==7692==    at 0x4A06A2E: malloc (vg_replace_malloc.c:270)
==7692==    by 0x4012F4: rpn (pa11.c:68)
==7692==    by 0x401CAD: main (pa11.c:199)
==7692==
Result -  = -5.000000
stack_last= -5.000000
Result = -5.000000
==7692==
==7692== HEAP SUMMARY:
==7692==     in use at exit: 0 bytes in 0 blocks
==7692==   total heap usage: 10 allocs, 10 frees, 1,773 bytes allocated
==7692==
==7692== All heap blocks were freed -- no leaks are possible
==7692==
==7692== For counts of detected and suppressed errors, rerun with: -v
==7692== ERROR SUMMARY: 28 errors from 14 contexts (suppressed: 6 from 6)

Body:
Clearly you have error here:

    input[i] = malloc(sizeof(char));

    fscanf(in2,"%s",input[i]);

if you want input one char you need use %c instead of %s,
for %s you need allocate at least two char, one for symbol,
another for trailing '\0'


问:
Lazy let? Unswifty workaround in structs
I have an immutable struct that I'm working with, and I'm trying to create a property that is not a computed value, however it's assignation requires the values of previously assigned properties.

(Wow mouthful).

The property I'm struggling with is perimeter: Int

```<code>// Floor made out of square tiles.
struct Floor {

  let
  size:           (x: Int, y: Int), // How many tiles in the floor
  tilePerimeter:  Int,

  // Calculate entire floor's perimeter based on tile quantity and perimeter:
  lazy let perimeter: Int = {

    let
    t4th  = self.tilePerimeter / 4,  // Tile width / length
    sx    = self.size.x * t4th,      // All X tiles' length
    sy    = self.size.y * t4th       // All Y tiles' width

    return (sx * 2) + (sy * 2)       // Perimeter calc
  }()
};
</code>```

Unfortunately, Swift will not let me use a lazy let.. So my workaround here was to just make a computed var with only a getter... but if this calculation took a long time (loading an image or complex math) then it would be called many times, when really it is only needed to call once

So my actual workaround was to just to create an initializer and assign the perimeter there... only some of my structs have MANY properties, and not creating an initializer for structs is part of the Swiftiness that I love.

I know that I could just make this a lazy var and instantiate the struct as let, but that seems confusing and error-prone.

Is there a way to do this where I can retain immutability, performance, and Swiftiness? And also, what is the reason for there not being allowed to use lazy let?

答:
You can force this to be computed only once while still using a read-only computed var by using an optional private var with a default of nil, much in the same way as singleton objects are implemented.

```<code>// Floor made out of square tiles.
struct Floor {
  private var computedPerimeter: Int? = nil

  let
  size:           (x: Int, y: Int), // How many tiles in the floor
  tilePerimeter:  Int

  // Calculate entire floor's perimeter based on tile quantity and perimeter:
  var perimeter: Int {
    mutating get {
        if computedPerimeter == nil {
            let
            t4th  = self.tilePerimeter / 4,  // Tile width / length
            sx    = self.size.x * t4th,      // All X tiles' length
            sy    = self.size.y * t4th       // All Y tiles' width

            computedPerimeter = ((sx * 2) + (sy * 2))       // Perimeter calc
         }
         return computedPerimeter!
     }
  }
};
</code>```

Body:
I have an immutable struct that I'm working with, and I'm trying to create a property that is not a computed value, however it's assignation requires the values of previously assigned properties.

(Wow mouthful).

The property I'm struggling with is perimeter: Int

// Floor made out of square tiles.
struct Floor {

  let
  size:           (x: Int, y: Int), // How many tiles in the floor
  tilePerimeter:  Int,

  // Calculate entire floor's perimeter based on tile quantity and perimeter:
  lazy let perimeter: Int = {

    let
    t4th  = self.tilePerimeter / 4,  // Tile width / length
    sx    = self.size.x * t4th,      // All X tiles' length
    sy    = self.size.y * t4th       // All Y tiles' width

    return (sx * 2) + (sy * 2)       // Perimeter calc
  }()
};

Unfortunately, Swift will not let me use a lazy let.. So my workaround here was to just make a computed var with only a getter... but if this calculation took a long time (loading an image or complex math) then it would be called many times, when really it is only needed to call once

So my actual workaround was to just to create an initializer and assign the perimeter there... only some of my structs have MANY properties, and not creating an initializer for structs is part of the Swiftiness that I love.

I know that I could just make this a lazy var and instantiate the struct as let, but that seems confusing and error-prone.

Is there a way to do this where I can retain immutability, performance, and Swiftiness? And also, what is the reason for there not being allowed to use lazy let?

Body:
You can force this to be computed only once while still using a read-only computed var by using an optional private var with a default of nil, much in the same way as singleton objects are implemented.

// Floor made out of square tiles.
struct Floor {
  private var computedPerimeter: Int? = nil

  let
  size:           (x: Int, y: Int), // How many tiles in the floor
  tilePerimeter:  Int

  // Calculate entire floor's perimeter based on tile quantity and perimeter:
  var perimeter: Int {
    mutating get {
        if computedPerimeter == nil {
            let
            t4th  = self.tilePerimeter / 4,  // Tile width / length
            sx    = self.size.x * t4th,      // All X tiles' length
            sy    = self.size.y * t4th       // All Y tiles' width

            computedPerimeter = ((sx * 2) + (sy * 2))       // Perimeter calc
         }
         return computedPerimeter!
     }
  }
};


问:
ASP.net: Display PDF in a asp.net web page
User click on a link button and it will direct them to a url that is dynmaically generated which a pdf file. The browser will prompt the user to either save or open it.

I want to know if it is possible to downlaod the pdf file to the server then show the pdf file in the asp.net web page. When i google on this question, 99% of top link are some third party component. Is it a way to do this without purchase any 3rd party component?

thank

答:
I think what you want to do is by going to: http://my_site.com/generate-pdf.aspx?=someId
this should in fact just show the PDF file?
What you need to do is change the Response type.

See here for how to do this with images.

OwnerDisplayName: Jack

OwnerDisplayName: Filip Ekberg


问:
Creating a table in Crystal Reports Basic (one built in vs2008)?
Is it possible to create a table with this crystal reports, because I need to layout or format my data into a table(not cross tab), is there a way to do this cause I think my tool box is only limited to lines and boxes and basic shapes. </p>

答: Sorry, but Crystal reports can not create tables.  It can execute a stored procedure that creates tables, but that's really the procedure creating the tables.</p>


问:
In C++ is really a "reference" just an alias, instead of a "pointer"?
This code:

```<code>int main()
{
    int v[] = {0,10,45};

    for (auto& x : v) {
        cout << x << endl;
        x++;
    }
}
</code>```

Is giving this output:

0
10
45

So, why when "x" is being read is reading the value, but when "x" is modified is modifying the reference target?.

答:
Consider the following:

```<code>int main() {
    int v[] = {0,10,45};

    for (auto x : v) { // Since it's not an alias it doesn't alter `v` array's contents.
        std::cout << ++x << ' '; // Output: 1, 11, 46
    }

    for (auto x : v) {
        std::cout << x << ' ';   // Output: 0, 10, 45 DOES NOT MODIFY v
    }

}
</code>```

However, if you do this:

```<code>int main() {
    int v[] = {0,10,45};

    for (auto& x : v) { // Since it IS an alias it will alter `v` array's contents.
        std::cout << ++x << ' '; // Output: 1, 11, 46
    }

    for (auto x : v) {
        std::cout << x << ' ';   // Output: 1, 11, 46 MODIFIES v
    }
}
</code>```

See it for yourself.

Body:
This code:

int main()
{
    int v[] = {0,10,45};

    for (auto& x : v) {
        cout << x << endl;
        x++;
    }
}

Is giving this output:

0
10
45

So, why when "x" is being read is reading the value, but when "x" is modified is modifying the reference target?.

Body:
Consider the following:

int main() {
    int v[] = {0,10,45};

    for (auto x : v) { // Since it's not an alias it doesn't alter `v` array's contents.
        std::cout << ++x << ' '; // Output: 1, 11, 46
    }

    for (auto x : v) {
        std::cout << x << ' ';   // Output: 0, 10, 45 DOES NOT MODIFY v
    }

}

However, if you do this:

int main() {
    int v[] = {0,10,45};

    for (auto& x : v) { // Since it IS an alias it will alter `v` array's contents.
        std::cout << ++x << ' '; // Output: 1, 11, 46
    }

    for (auto x : v) {
        std::cout << x << ' ';   // Output: 1, 11, 46 MODIFIES v
    }
}

See it for yourself.


问:
Checking Clojure function equality by name
As an exercise in manipulating code as data I wanted to take a piece of Clojure code and change all the bar calls for foo calls. But I came across a struggle in checking for function equality. My problem is:

```<code>(= foo foo) ;returns true
(= foo (first `(foo))) ;returns false
</code>```

What is the proper way of checking for the second equality?

答:
The reason is that you quote the list:</p>

```<code>> (= 'foo (first '(foo)))
true
> (= 'foo (first (list foo)))
false
> (= foo (first (list foo)))
true
</code>```

Body:
As an exercise in manipulating code as data I wanted to take a piece of Clojure code and change all the bar calls for foo calls. But I came across a struggle in checking for function equality. My problem is:

(= foo foo) ;returns true
(= foo (first `(foo))) ;returns false

What is the proper way of checking for the second equality?

Body:
The reason is that you quote the list:

> (= 'foo (first '(foo)))
true
> (= 'foo (first (list foo)))
false
> (= foo (first (list foo)))
true


问:
Right click without Actions in Selenium 3.x in Firefox browser
How to right click an element without using Actions object. I get exception while using Actions in Selenium3 in FireFox  with GeckoDriver.
I have used the following code to set the GeckoDriver property.</p>

```<code>System.setProperty("webdriver.gecko.driver", new File("lib/geckodriver").getAbsolutePath());
</code>```

答:
Post the exception and detail which versions you are using (driver and FF).

Meanwhile, take a look at this post. At it, the problem was related with a driver problem.

Body:
How to right click an element without using Actions object. I get exception while using Actions in Selenium3 in FireFox  with GeckoDriver.
I have used the following code to set the GeckoDriver property.

System.setProperty("webdriver.gecko.driver", new File("lib/geckodriver").getAbsolutePath());


问:
How to display images from a website on ImageView on Android?
I could pull only 1 image from a website using AsyncTask when clicking a button; however, I want to display more images at the same time and they can display by themselves without click anything.
Here is my code"</p>

```<code>import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.ExecutionException;

import javax.net.ssl.HttpsURLConnection;

public class MainActivity extends AppCompatActivity {

ImageView downloadedImg;

   public void downLoad(View view) {

        ImageDownloader task = new ImageDownloader();
        Bitmap myImage;
        try {
            myImage = task.execute("https://i.ytimg.com/vi/tntOCGkgt98/maxresdefault.jpg").get();
            downloadedImg.setImageBitmap(myImage);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public class ImageDownloader extends AsyncTask <String, Void, Bitmap>{

        @Override
        protected Bitmap doInBackground(String... urls) {

            try {
                URL url = new URL(urls[0]);

                HttpURLConnection connection = (HttpURLConnection) url.openConnection();

                connection.connect();

                InputStream inputStream = connection.getInputStream();

                Bitmap myBitmap = BitmapFactory.decodeStream(inputStream);

                return myBitmap;

            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        downloadedImg = (ImageView) findViewById(R.id.imageView);

    }
}
</code>```

答:
I believe you know the urls of the images you want to download

I recommend you to use Picasso or Glide

Picasso:

```<code>compile 'com.squareup.picasso:picasso:2.5.2'

Picasso.with(context).load(url).into(imageView);
</code>```

Glide:

```<code>compile 'com.github.bumptech.glide:glide:3.7.0'

Glide.with(context).load(url).into(imageView);
</code>```

Body:
I could pull only 1 image from a website using AsyncTask when clicking a button; however, I want to display more images at the same time and they can display by themselves without click anything.
Here is my code"

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.ExecutionException;

import javax.net.ssl.HttpsURLConnection;

public class MainActivity extends AppCompatActivity {

ImageView downloadedImg;

   public void downLoad(View view) {

        ImageDownloader task = new ImageDownloader();
        Bitmap myImage;
        try {
            myImage = task.execute("https://i.ytimg.com/vi/tntOCGkgt98/maxresdefault.jpg").get();
            downloadedImg.setImageBitmap(myImage);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public class ImageDownloader extends AsyncTask <String, Void, Bitmap>{

        @Override
        protected Bitmap doInBackground(String... urls) {

            try {
                URL url = new URL(urls[0]);

                HttpURLConnection connection = (HttpURLConnection) url.openConnection();

                connection.connect();

                InputStream inputStream = connection.getInputStream();

                Bitmap myBitmap = BitmapFactory.decodeStream(inputStream);

                return myBitmap;

            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        downloadedImg = (ImageView) findViewById(R.id.imageView);

    }
}

Body:
I believe you know the urls of the images you want to download

I recommend you to use Picasso or Glide

Picasso:

compile 'com.squareup.picasso:picasso:2.5.2'

Picasso.with(context).load(url).into(imageView);

Glide:

compile 'com.github.bumptech.glide:glide:3.7.0'

Glide.with(context).load(url).into(imageView);


问:
What's the NHibernate session.Load equivalent in Entity Framework?
What's the following NHibernate lazy loading equivalent to Entity Framework?

```<code>product.Categories.Add(s.Load<Category>(cat));
</code>```

I tried this, but it read the Category table from the database:

```<code>product.Categories.Add(db.Categories.Find(cat));
</code>```

答:
While Entity Framework doesn't have an exact equivalent to the Load() method, it does provide the ability to persist a new association without first retrieving an entity or exposing foreign key properties (i.e. arguably the most common use of NHibernate's Load method).

The following extension methods either return an entity already tracked or returns a newly attached entity which can then be used to save new associations:

```<code>public static class EntityFrameworkExtensions
{
    // Loads when the Id property is always "Id" based on derived types of EntityBase<TId>
    public static TEntity LoadEntity<TEntity,TId>(this DbContext context, TId id) where TEntity : EntityBase<TId>, new()
    {
        var entity = context.ChangeTracker.Entries<TEntity>().SingleOrDefault(e => e.Entity.Id.Equals(id))?.Entity;

        if (entity == null)
        {
            entity = new TEntity { Id = id };
            context.Set<TEntity>().Attach(entity);
        }

        return entity;
    }

    // Loads when you're dealing with a composite key and need to specify both how to identify the key and how to assign if attaching a newly created entity.
    public static TEntity LoadEntity<TEntity>(this DbContext context, Func<TEntity, bool> predicate, Action<TEntity> idAssignmentAction) where TEntity : class, new()
    {
        var entity = context.ChangeTracker.Entries<TEntity>().SingleOrDefault(e => predicate(e.Entity))?.Entity;

        if (entity == null)
        {
            entity = new TEntity();
            idAssignmentAction(entity);
            context.Set<TEntity>().Attach(entity);
        }

        return entity;
    }
}

    // Loads by allowing you to specify an expression identifying the primary key property
    public static TEntity LoadEntity<TEntity, TIdProperty>(this DbContext context,
        Expression<Func<TEntity, TIdProperty>> idExpression, TIdProperty id) where TEntity : class, new()
    {
        var parameterExpression = Expression.Parameter(typeof(DbEntityEntry<TEntity>), "ent");
        Expression entityProperty = Expression.Property(parameterExpression, "Entity");
        var keyValue = Expression.Invoke(idExpression, entityProperty);
        var pkValue = Expression.Constant(id, typeof(TIdProperty));
        Expression equalsExpression = Expression.Equal(keyValue, pkValue);
        var lambda = Expression.Lambda<Func<DbEntityEntry<TEntity>, bool>>(equalsExpression, parameterExpression);
        var lambdaC = lambda.Compile();

        var entity = context.ChangeTracker.Entries<TEntity>().SingleOrDefault(lambdaC)?.Entity;

        if (entity == null)
        {
            entity = new TEntity();

            var valueParameterExpression = Expression.Parameter(typeof(object));
            var targetExpression = idExpression.Body is UnaryExpression
                ? ((UnaryExpression) idExpression.Body).Operand
                : idExpression.Body;

            var assign = Expression.Lambda<Action<TEntity, object>>
            (
                Expression.Assign(targetExpression,
                    Expression.Convert(valueParameterExpression, targetExpression.Type)),
                idExpression.Parameters.Single(),
                valueParameterExpression
            );

            assign.Compile().Invoke(entity, id);
            context.Set<TEntity>().Attach(entity);
        }

        return entity;
    }
</code>```

Example usage:

```<code>var account1 = _dbContext.LoadEntity<Account, int>(request.AccountId);

var account2 = _dbContext.LoadEntity<AccountWithComposite>(a => a.X == 1 && a.Y == 2, a => { a.X = 1; a.Y = 2; });

var account3 = _dbContext.LoadEntity<Account, int>(a => a.AccountId, request.AccountId);
</code>```

Body:
What's the following NHibernate lazy loading equivalent to Entity Framework?

product.Categories.Add(s.Load<Category>(cat));

I tried this, but it read the Category table from the database:

product.Categories.Add(db.Categories.Find(cat));

Body:
While Entity Framework doesn't have an exact equivalent to the Load() method, it does provide the ability to persist a new association without first retrieving an entity or exposing foreign key properties (i.e. arguably the most common use of NHibernate's Load method).

The following extension methods either return an entity already tracked or returns a newly attached entity which can then be used to save new associations:

public static class EntityFrameworkExtensions
{
    // Loads when the Id property is always "Id" based on derived types of EntityBase<TId>
    public static TEntity LoadEntity<TEntity,TId>(this DbContext context, TId id) where TEntity : EntityBase<TId>, new()
    {
        var entity = context.ChangeTracker.Entries<TEntity>().SingleOrDefault(e => e.Entity.Id.Equals(id))?.Entity;

        if (entity == null)
        {
            entity = new TEntity { Id = id };
            context.Set<TEntity>().Attach(entity);
        }

        return entity;
    }

    // Loads when you're dealing with a composite key and need to specify both how to identify the key and how to assign if attaching a newly created entity.
    public static TEntity LoadEntity<TEntity>(this DbContext context, Func<TEntity, bool> predicate, Action<TEntity> idAssignmentAction) where TEntity : class, new()
    {
        var entity = context.ChangeTracker.Entries<TEntity>().SingleOrDefault(e => predicate(e.Entity))?.Entity;

        if (entity == null)
        {
            entity = new TEntity();
            idAssignmentAction(entity);
            context.Set<TEntity>().Attach(entity);
        }

        return entity;
    }
}

    // Loads by allowing you to specify an expression identifying the primary key property
    public static TEntity LoadEntity<TEntity, TIdProperty>(this DbContext context,
        Expression<Func<TEntity, TIdProperty>> idExpression, TIdProperty id) where TEntity : class, new()
    {
        var parameterExpression = Expression.Parameter(typeof(DbEntityEntry<TEntity>), "ent");
        Expression entityProperty = Expression.Property(parameterExpression, "Entity");
        var keyValue = Expression.Invoke(idExpression, entityProperty);
        var pkValue = Expression.Constant(id, typeof(TIdProperty));
        Expression equalsExpression = Expression.Equal(keyValue, pkValue);
        var lambda = Expression.Lambda<Func<DbEntityEntry<TEntity>, bool>>(equalsExpression, parameterExpression);
        var lambdaC = lambda.Compile();

        var entity = context.ChangeTracker.Entries<TEntity>().SingleOrDefault(lambdaC)?.Entity;

        if (entity == null)
        {
            entity = new TEntity();

            var valueParameterExpression = Expression.Parameter(typeof(object));
            var targetExpression = idExpression.Body is UnaryExpression
                ? ((UnaryExpression) idExpression.Body).Operand
                : idExpression.Body;

            var assign = Expression.Lambda<Action<TEntity, object>>
            (
                Expression.Assign(targetExpression,
                    Expression.Convert(valueParameterExpression, targetExpression.Type)),
                idExpression.Parameters.Single(),
                valueParameterExpression
            );

            assign.Compile().Invoke(entity, id);
            context.Set<TEntity>().Attach(entity);
        }

        return entity;
    }

Example usage:

var account1 = _dbContext.LoadEntity<Account, int>(request.AccountId);

var account2 = _dbContext.LoadEntity<AccountWithComposite>(a => a.X == 1 && a.Y == 2, a => { a.X = 1; a.Y = 2; });

var account3 = _dbContext.LoadEntity<Account, int>(a => a.AccountId, request.AccountId);

ContentLicense: CC BY-SA 4.0


问:
selenium firefox Profile has been set on both the capabilities and these options but they're different. Unable to determine which one you want to use
```<code>$host = 'http://localhost:4444/wd/hub';
</code>```

$profile = new FirefoxProfile();
$profile->setPreference('log', "{level: info}");

$caps = DesiredCapabilities::firefox();
$caps->setCapability(FirefoxDriver::PROFILE, $profile);

$driver = RemoteWebDriver::create($host, $caps, 500000, 500000);

PHP version: 5.5
Selenium server version: 3.3
Operating system: win7
Browser used + version: firefox 52
geckodriver version:0.15

答:
This should be fixed in Selenium Server 3.3.1.

See https://github.com/SeleniumHQ/selenium/issues/3632 .

Body:
$host = 'http://localhost:4444/wd/hub';

$profile = new FirefoxProfile();
$profile->setPreference('log', "{level: info}");

$caps = DesiredCapabilities::firefox();
$caps->setCapability(FirefoxDriver::PROFILE, $profile);

$driver = RemoteWebDriver::create($host, $caps, 500000, 500000);

PHP version: 5.5
Selenium server version: 3.3
Operating system: win7
Browser used + version: firefox 52
geckodriver version:0.15


问:
Searching for numbers, doing arithmetic on results, then replacing
I need to search and replace numbers in a string. However there are two caveats.

First, I need to do arithmetic before replacing. So if I was adding 5 to them, a search for 6 would replace it with 11, 7 with 12, etc.

Second, I'm only doing numbers that are followed by a colon. So '7:' would become '12:', '8:' would become '13:', but just '9' with no colon would remain unchanged.

Here is something I've tried

```<code>var string = "89 12 13: 42:";
var regex = new RegExp('[0-9]+','g');
string = string.replace(regex + ':',(regex + 5) + ':');
</code>```

It should look like "89 12 18: 47:" when finished. The plus 5 means I'm trying to add 5 to the number that comes out before replacing.

Thanks,

答:
You're close; but you're not scanning for : and you're missing .replace with a function.

test = "I like 55: 12: 9: yay";

test = test.replace(/[0-9]+:/g, function (a) {
  return Number(a.slice(0,-1)) + 5 + ":";
});
console.log(test);```

Body:
I need to search and replace numbers in a string. However there are two caveats.

First, I need to do arithmetic before replacing. So if I was adding 5 to them, a search for 6 would replace it with 11, 7 with 12, etc.

Second, I'm only doing numbers that are followed by a colon. So '7:' would become '12:', '8:' would become '13:', but just '9' with no colon would remain unchanged.

Here is something I've tried

var string = "89 12 13: 42:";
var regex = new RegExp('[0-9]+','g');
string = string.replace(regex + ':',(regex + 5) + ':');

It should look like "89 12 18: 47:" when finished. The plus 5 means I'm trying to add 5 to the number that comes out before replacing.

Thanks,


问:
Are there no built in C# GUI Layouts?
I'm used to the GUI frameworks in Java as well as the QT GUI framework, and I'm used to the various layout managers. It doesn't seem that C# has any layout managers built in, or am I missing something?

2 Year Later Edit

I just want to point out to any readers of this question that in hind-sight, my question was misplaced. With proper anchoring and docking of child controls, having a need for the layout managers of Java and QT4 is nearly non-existent.

答: WPF and Silverlight have different "Panels" that work similar to the layout managers in other languages.</p>

Title: Are there no built in C# GUI Layouts?


问:
remove extraneous characters from a filename
I have been tasked a little above my head with taking a repository of files and removing excess garbage characters from the filename and saving the renamed file in a different directory folder.

An example of the filenames are:

```
100-expresstoll.pdf
1000-2012-09-29.jpg
10000-2014-01-15_14.03.22.jpg
10001-2014-01-15_19.05.24.jpg
10002-2014-01-15_21.30.23.jpg
10003-2014-01-16_07.33.54.jpg
10004-2014-01-16_13.33.21.jpg
10005-Feb 4, 2014.jpeg
10006-O'Reilly_Media,_Inc..pdf
```

First group of numbers at the beginning are record IDs and are to be retained along with the file's extension. Everything else between the record IDs and the file extension needs to be dropped.

For example, the final name for first three files would be:

```
100.pdf
1000.jpg
10000.jpg
```

I have read Removing characters and Rearranging filenames in addition to other postings, but the complexity of having a variable character length at the front, a variable number of intermediary characters to be removed and variable file extension types have really tossed this beyond my limited PowerShell reach.

答:
I know this is not a PowerShell thing. If you just want something to work, this is a cmd batch file thing.</p>

```<code>SETLOCAL ENABLEDELAYEDEXPANSION

SET "OLDDIR=C:\Users\lit\files"
SET "NEWDIR=C:\Users\lit\newdir"

FOR /F "usebackq tokens=*" %%a IN (`DIR /A:-D /B "%OLDDIR%\*"`) DO (
    FOR /F "usebackq delims=- tokens=1" %%b IN (`ECHO %%a`) DO (SET "BN=%%b")
    SET "EXT=%%~xa"
    ECHO COPY /Y "%OLDDIR%\%%~a" "%NEWDIR%\!BN!!EXT!"
)
</code>```

Body:
I have been tasked a little above my head with taking a repository of files and removing excess garbage characters from the filename and saving the renamed file in a different directory folder.

An example of the filenames are:

100-expresstoll.pdf
1000-2012-09-29.jpg
10000-2014-01-15_14.03.22.jpg
10001-2014-01-15_19.05.24.jpg
10002-2014-01-15_21.30.23.jpg
10003-2014-01-16_07.33.54.jpg
10004-2014-01-16_13.33.21.jpg
10005-Feb 4, 2014.jpeg
10006-O'Reilly_Media,_Inc..pdf

First group of numbers at the beginning are record IDs and are to be retained along with the file's extension. Everything else between the record IDs and the file extension needs to be dropped.

For example, the final name for first three files would be:

100.pdf
1000.jpg
10000.jpg

I have read Removing characters and Rearranging filenames in addition to other postings, but the complexity of having a variable character length at the front, a variable number of intermediary characters to be removed and variable file extension types have really tossed this beyond my limited PowerShell reach.

Body:
I know this is not a PowerShell thing. If you just want something to work, this is a cmd batch file thing.

SETLOCAL ENABLEDELAYEDEXPANSION

SET "OLDDIR=C:\Users\lit\files"
SET "NEWDIR=C:\Users\lit\newdir"

FOR /F "usebackq tokens=*" %%a IN (`DIR /A:-D /B "%OLDDIR%\*"`) DO (
    FOR /F "usebackq delims=- tokens=1" %%b IN (`ECHO %%a`) DO (SET "BN=%%b")
    SET "EXT=%%~xa"
    ECHO COPY /Y "%OLDDIR%\%%~a" "%NEWDIR%\!BN!!EXT!"
)


问:
When I use Deployment in Kubernetes, what's the differences between apps/v1beta1 and extensions/v1beta1?
I use the yaml file, which is in the Kubernetes official document,  to create a Deployment in Kubernetes, and it uses apiVersion: apps/v1beta1 at the top. Then I typed kubectl create -f deployment.yaml to create this Deployment, but it occured an error as following:

```
error: error validating "deployment.yaml": error validating data: couldn't find type: v1beta1.Deployment; if you choose to ignore these errors, turn validation off with --validate=false`
```

After some search, I changed apiVersion: apps/v1beta1 to extensions/v1beta1, and then recreate the Deployment with the yaml file, and it worked fine.

So, I wanna know what's the differences between apps/v1beta1 and extensions/v1beta1. Is it pertinent to the Kubernetes version?

```
# kubectl version
Client Version: version.Info{Major:"1", Minor:"5", GitVersion:"v1.5.4", GitCommit:"7243c69eb523aa4377bce883e7c0dd76b84709a1", GitTreeState:"clean", BuildDate:"2017-03-07T23:53:09Z", GoVersion:"go1.7.4", Compiler:"gc", Platform:"linux/amd64"}
Server Version: version.Info{Major:"1", Minor:"5", GitVersion:"v1.5.4", GitCommit:"7243c69eb523aa4377bce883e7c0dd76b84709a1", GitTreeState:"clean", BuildDate:"2017-03-07T23:34:32Z", GoVersion:"go1.7.4", Compiler:"gc", Platform:"linux/amd64"}
```

答:
The apps API group will be where the v1 Deployment type lives. The apps/v1beta1 version was added in 1.6.0, so if you have a 1.5.x client or server, you should still use the extensions/v1beta1 version.

The apps/v1beta1 and extensions/v1beta1 Deployment types are identical, but when creating via the apps API, some improved defaults are used

Body:
I use the yaml file, which is in the Kubernetes official document,  to create a Deployment in Kubernetes, and it uses apiVersion: apps/v1beta1 at the top. Then I typed kubectl create -f deployment.yaml to create this Deployment, but it occured an error as following:

error: error validating "deployment.yaml": error validating data: couldn't find type: v1beta1.Deployment; if you choose to ignore these errors, turn validation off with --validate=false`

After some search, I changed apiVersion: apps/v1beta1 to extensions/v1beta1, and then recreate the Deployment with the yaml file, and it worked fine.

So, I wanna know what's the differences between apps/v1beta1 and extensions/v1beta1. Is it pertinent to the Kubernetes version?

# kubectl version
Client Version: version.Info{Major:"1", Minor:"5", GitVersion:"v1.5.4", GitCommit:"7243c69eb523aa4377bce883e7c0dd76b84709a1", GitTreeState:"clean", BuildDate:"2017-03-07T23:53:09Z", GoVersion:"go1.7.4", Compiler:"gc", Platform:"linux/amd64"}
Server Version: version.Info{Major:"1", Minor:"5", GitVersion:"v1.5.4", GitCommit:"7243c69eb523aa4377bce883e7c0dd76b84709a1", GitTreeState:"clean", BuildDate:"2017-03-07T23:34:32Z", GoVersion:"go1.7.4", Compiler:"gc", Platform:"linux/amd64"}


问:
How to update value in a List using LINQ
I have a list which I want to update using LINQ.

```<code>class Student
{
    private string name;
    private int marks;
    public string Name { get; set;}
    public int Marks { get; set; }
    public Student(string name, int marks)
    {
        Name = name;
        Marks = marks;
    }
}

List<Student> myList = new List<Student>();
myList.Add(new Student("John", 10));
myList.Add(new Student("Tom", 20));
</code>```

Now I want to update the list using LINQ such that only marks of John gets updated. I am using the following syntax:

```<code>myList.Where(w => w.Name == "Tom").Select(w=> { w.Marks = 35; return w});
</code>```

But this doesnt update data in myList. Can someone tell me where am I going wrong.

答:
Objects are stored by reference in the list so you can recover object via linq and then edit, it will be reflect the changes on the list.

Example

```<code>    static void Main(string[] args)
        {
            List<Entity> testList = new List<Entity>()
            {
                new Entity() {Id = 1, Text = "Text"},
                new Entity() {Id = 2, Text = "Text2"}
            };

            Console.WriteLine($"First text value:{testList[1].Text}");

            Entity entityToEdit = testList.FirstOrDefault(e => e.Id == 2);
            if (entityToEdit != null)
                entityToEdit.Text = "Hello You!!";

            Console.WriteLine($"Edited text value:{testList[1].Text}");

            Console.ReadLine();
        }

 internal class Entity
    {
        public int Id { get; set; }
        public String Text { get; set; }
    }
</code>```

Testing the app you will get the follow result:

First text value:Text2

Edited text value:Hello You!!

Body:
I have a list which I want to update using LINQ.

class Student
{
    private string name;
    private int marks;
    public string Name { get; set;}
    public int Marks { get; set; }
    public Student(string name, int marks)
    {
        Name = name;
        Marks = marks;
    }
}

List<Student> myList = new List<Student>();
myList.Add(new Student("John", 10));
myList.Add(new Student("Tom", 20));

Now I want to update the list using LINQ such that only marks of John gets updated. I am using the following syntax:

myList.Where(w => w.Name == "Tom").Select(w=> { w.Marks = 35; return w});

But this doesnt update data in myList. Can someone tell me where am I going wrong.

Body:
Objects are stored by reference in the list so you can recover object via linq and then edit, it will be reflect the changes on the list.

Example

    static void Main(string[] args)
        {
            List<Entity> testList = new List<Entity>()
            {
                new Entity() {Id = 1, Text = "Text"},
                new Entity() {Id = 2, Text = "Text2"}
            };

            Console.WriteLine($"First text value:{testList[1].Text}");

            Entity entityToEdit = testList.FirstOrDefault(e => e.Id == 2);
            if (entityToEdit != null)
                entityToEdit.Text = "Hello You!!";

            Console.WriteLine($"Edited text value:{testList[1].Text}");

            Console.ReadLine();
        }

 internal class Entity
    {
        public int Id { get; set; }
        public String Text { get; set; }
    }

Testing the app you will get the follow result:

First text value:Text2

Edited text value:Hello You!!


问:
Escape ContainsTable Keywords
How can I escape ContainsTable control keywords (such as NEAR or ISABOUT) so that Full Text Search will actually look for those words, and not treat them as control keywords?</p>

答:
Just create your own StopWords in a StopList and put in your full-text index

Regards,

DavLeMag

Title: Escape ContainsTable Keywords


问:
Why does for_each return function by move
I was reading the documentation for std::for_each here http://en.cppreference.com/w/cpp/algorithm/for_each and saw that the return value is std::move(f)

Why does the standard enforce moving the input parameter in the return value?  Won't it be moved by default anyway, since the input parameter is passed by value?

This leads me to a couple of followups, when you compile the following code

```<code>Something function(Something something) {
    return something;
}
</code>```

The return statement is a move on my system with the highest optimization level (-O3),  why don't most compilers elide this return value?  Local values are elided but function arguments are not..

Does C++17 enforce elision in this case?  I read the proposal (http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/p0135r0.html) but I do not fully understand which cases qualify for mandatory elision.

I have tried this on Apple LLVM version 8.0.0 (clang-800.0.42.1) on my Mac and on g++ 5.4 on Ubuntu 16.04.

答:
This is due to a late-breaking change in the move-semantics rules for C++11.  The original move proposal did not automatically move when by-value function arguments appeared on the return clause.  However by late in the C++11 process, that language feature was added.

Prior to the language feature being added, for_each "was moved".  At that time the move on the return statement was necessary.  But it became unnecessary, though harmless by the time C++11 shipped.

LWG issue 2747 corrected this for C++17.

As to your first followup question, I am not a compiler writer, but my best guess is:  It is not currently legal to elide the return from a function parameter (that much I know), and I'm guessing as to why it isn't legal is that no one has figured out how to implement it, and thus no one has had the motivation to change the standard to make it legal.

Second follow up:  No, C++17 does not enforce elision in this case.  The rules remain the same as for C++11 in this case, save for the fact that the redundant move from for_each is no longer specified.

From the comments below:

Why do you say it's not legal to elide the return from a function parameter?

I'm referencing N4660, which is C++17, but there is similar wording in C++98/03/11/14 ... backup, it has recently been protected.  See N4659 instead (just as good):

15.8.3 Copy/move elision [class.copy.elision]

When certain criteria are met, an implementation is allowed to omit the copy/move construction of a class object, ...

in a return statement in a function with a class return type, when the expression is the name of a non-volatile automatic object (other than a function parameter or a variable introduced by the exception-declaration of a handler (18.3)) with the same type (ignoring cv-qualification) as the function return type, the copy/move operation can be omitted by constructing the automatic object directly into the function call’s return object

This language specifically disallows elision from function parameters.

Body:
I was reading the documentation for std::for_each here http://en.cppreference.com/w/cpp/algorithm/for_each and saw that the return value is std::move(f)

Why does the standard enforce moving the input parameter in the return value?  Won't it be moved by default anyway, since the input parameter is passed by value?

This leads me to a couple of followups, when you compile the following code

Something function(Something something) {
    return something;
}

The return statement is a move on my system with the highest optimization level (-O3),  why don't most compilers elide this return value?  Local values are elided but function arguments are not..

Does C++17 enforce elision in this case?  I read the proposal (http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/p0135r0.html) but I do not fully understand which cases qualify for mandatory elision.

I have tried this on Apple LLVM version 8.0.0 (clang-800.0.42.1) on my Mac and on g++ 5.4 on Ubuntu 16.04.


问:
IQueryable for 1 to N tables to select all the data (c#)
I am beginner of C#, and I am writing the code for "search" function now. I have linked table which is 1 to N like example below. And, I like to find out the data for table A which matches e.g. table B, "KeyB002". (Answer is KeyA001 & KeyA003).

I have been using IQueryable, and is this okay with this syntax? Or, this won't work? I am wondering SingleOrDefault or FirstOrDefault will pick up only the first key which is attached with tableA, and don't go through (search) from all the attached keys and find out the data in tableA....

Thank you very much.

(Current Syntax) FYI - searchtableB_ID from screen...

```<code>var IqueryableData = from m in db.tableA.Include(p => p.tableB) select m;
IqueryableData = IqueryableData.Where(s => s.tableB.SingleOrDefault().tableB_Key == searchtableB_ID);
</code>```

table A & table B:

KeyA001 - KeyB001

KeyA001 - KeyB002

KeyA001 - KeyB005

KeyA001 - KeyB007

KeyA002 - KeyB003

KeyA002 - KeyB005

KeyA002 - KeyB008

KeyA003 - KeyB001

KeyA003 - KeyB002

KeyA003 - KeyB006

KeyA003 - KeyB009

答:
You could just:

```<code>var queryableData = db.tableB.Include(p => p.tableA).Where(q=> q.tableB_key == searchtableB_ID).First(m => m.tableA);
</code>```

Notice the reversed Include (p => p.tableB) instead of (p => p.tableA)

Body:
I am beginner of C#, and I am writing the code for "search" function now. I have linked table which is 1 to N like example below. And, I like to find out the data for table A which matches e.g. table B, "KeyB002". (Answer is KeyA001 & KeyA003).

I have been using IQueryable, and is this okay with this syntax? Or, this won't work? I am wondering SingleOrDefault or FirstOrDefault will pick up only the first key which is attached with tableA, and don't go through (search) from all the attached keys and find out the data in tableA....

Thank you very much.

(Current Syntax) FYI - searchtableB_ID from screen...

var IqueryableData = from m in db.tableA.Include(p => p.tableB) select m;
IqueryableData = IqueryableData.Where(s => s.tableB.SingleOrDefault().tableB_Key == searchtableB_ID);

table A & table B:

KeyA001 - KeyB001

KeyA001 - KeyB002

KeyA001 - KeyB005

KeyA001 - KeyB007

KeyA002 - KeyB003

KeyA002 - KeyB005

KeyA002 - KeyB008

KeyA003 - KeyB001

KeyA003 - KeyB002

KeyA003 - KeyB006

KeyA003 - KeyB009

Body:
You could just:

var queryableData = db.tableB.Include(p => p.tableA).Where(q=> q.tableB_key == searchtableB_ID).First(m => m.tableA);

Notice the reversed Include (p => p.tableB) instead of (p => p.tableA)


问:
Displaying and hiding content when div with a certain class or id is clicked
I have a 4 divs that are stacked on top of each other. When I click on a given div, I want it to show a content section below it and above the other three divs. When I click the div again, it should hide the content section associated with it. My current code is able to display the content on click but I can't find anything on how to hide that content when I click on the div again.

Here is my code for example

HTML

```<code>                <div class="dropItem wow fadeInLeft">Nature <b class="caret"></b></div>
                <div id="show">
                    <p>Some text here</p>
                </div>

                <div class="dropItem2 wow fadeInLeft">Discovery <b class="caret"></b></div>
                <div id="show2">
                    <p>Some text here</p>
                </div>

                <div class="dropItem3 wow fadeInLeft">Perspective <b class="caret"></b></div>
                <div id="show3">
                    <p>Some text here</p>
                </div>

                <div class="dropItem4 wow fadeInLeft">Mindfullness <b class="caret"></b></div>
                <div id="show4">
                    <p>Some text here</p>
                </div>

            </div>
        </div><!--end about column-->
</code>```

Javascript

```<code>$(document).ready(function(){
    //hide content sections at first
    $("#show").hide();
    $("#show2").hide();
    $("#show3").hide();
   $("#show4").hide();

 //display each content section when corresponding div is clicked
    $(".dropItem").click(function(){
        $("#show").show();
    });

    $(".dropItem2").click(function(){
       $("#show2").show();
    });

    $(".dropItem3").click(function(){
        $("#show3").show();
     });

     $(".dropItem4").click(function(){
         $("#show4").show();
      });

});
</code>```

CSS

```<code>.dropItem, .dropItem2, .dropItem3, .dropItem4 {
 width: 100%;
 height: 25%;
 padding-top: 4%;
 text-align: center;
 border-top: 1px solid #000;
 font-weight: bold;
}

.caret {
 color: teal;
}

#show, #show2, #show3, #show4 {
 width: 100%;
 height: 250px;
 background-color: teal;
 color: #FFFFFF;
 border: 1px solid teal;
}
</code>```

Link to site for example
http://jackloudphoto.com/

答:
You can do this with this three solutions.

First of all, good idea is wrap it into one div as box, because you need define item borders.

Solution one

I like this because no matter how much deep is content div inside in box. If you change box structure eg.  you don't need to change your js code because everything will work.

HTML

```<code><!-- solution one -->
<div class="box">
  <div class="box-header dropItem wow fadeInLeft">Nature <b class="caret"></b>
  <div class="box-content">
    <p>Some text here</p>
  </div>
</div>
</code>```

JS

```<code>// solution one
$('.box .box-header').click(function(e) {
    $(this).closest('.box').find('.box-content').toggle();
});
</code>```

Solution two

It is similar to your code. You need get ID what you want to show. For this is perfect use HTML5 Data attribute like in example. But if you need to change your structure, you probably will need change js code too.

HTML

```<code><!-- solution two -->
<div class="box2">
  <div class="box-header2 dropItem wow fadeInLeft" data-box-id="2">Nature <b class="caret"></b>
  <div class="box-content2 item-2">
    <p>Some text here 222</p>
  </div>
</div>
</code>```

JS

```<code>// solution two
$('.box2 .box-header2').click(function(e) {
    var id = $(this).data('box-id');
  $('.item-'+id).toggle();
});
</code>```

Solution three

Is solution one without short toggle function.

HTML

```<code><!-- solution three -->
<div class="box3">
  <div class="box-header3 dropItem wow fadeInLeft">Nature <b class="caret"></b>
  <div class="box-content3 item-3">
    <p>Some text here 3333</p>
  </div>
</div>
</code>```

JS

```<code>$('.box3 .box-header3').click(function(e) {
    var $content = $(this).closest('.box3').find('.box-content3');
  if($content.is(':hidden')) {
    $content.show();
  }
  else {
    $content.hide();
  }
});
</code>```

I prefer the solution one but sometimes use solution two. Depend what is frendly for you.

JS DEMO

Body:
I have a 4 divs that are stacked on top of each other. When I click on a given div, I want it to show a content section below it and above the other three divs. When I click the div again, it should hide the content section associated with it. My current code is able to display the content on click but I can't find anything on how to hide that content when I click on the div again.

Here is my code for example

HTML

Nature

Some text here

Discovery

Some text here

Perspective

Some text here

Mindfullness

Some text here

Javascript

$(document).ready(function(){
    //hide content sections at first
    $("#show").hide();
    $("#show2").hide();
    $("#show3").hide();
   $("#show4").hide();

 //display each content section when corresponding div is clicked
    $(".dropItem").click(function(){
        $("#show").show();
    });

    $(".dropItem2").click(function(){
       $("#show2").show();
    });

    $(".dropItem3").click(function(){
        $("#show3").show();
     });

     $(".dropItem4").click(function(){
         $("#show4").show();
      });

});

CSS

.dropItem, .dropItem2, .dropItem3, .dropItem4 {
 width: 100%;
 height: 25%;
 padding-top: 4%;
 text-align: center;
 border-top: 1px solid #000;
 font-weight: bold;
}

.caret {
 color: teal;
}

#show, #show2, #show3, #show4 {
 width: 100%;
 height: 250px;
 background-color: teal;
 color: #FFFFFF;
 border: 1px solid teal;
}

Link to site for example
http://jackloudphoto.com/

Body:
You can do this with this three solutions.

First of all, good idea is wrap it into one div as box, because you need define item borders.

Solution one

I like this because no matter how much deep is content div inside in box. If you change box structure eg.  you don't need to change your js code because everything will work.

HTML

<!-- solution one -->
<div class="box">
  <div class="box-header dropItem wow fadeInLeft">Nature <b class="caret"></b>
  <div class="box-content">
    <p>Some text here</p>
  </div>
</div>

JS

// solution one
$('.box .box-header').click(function(e) {
    $(this).closest('.box').find('.box-content').toggle();
});

Solution two

It is similar to your code. You need get ID what you want to show. For this is perfect use HTML5 Data attribute like in example. But if you need to change your structure, you probably will need change js code too.

HTML

<!-- solution two -->
<div class="box2">
  <div class="box-header2 dropItem wow fadeInLeft" data-box-id="2">Nature <b class="caret"></b>
  <div class="box-content2 item-2">
    <p>Some text here 222</p>
  </div>
</div>

JS

// solution two
$('.box2 .box-header2').click(function(e) {
    var id = $(this).data('box-id');
  $('.item-'+id).toggle();
});

Solution three

Is solution one without short toggle function.

HTML

<!-- solution three -->
<div class="box3">
  <div class="box-header3 dropItem wow fadeInLeft">Nature <b class="caret"></b>
  <div class="box-content3 item-3">
    <p>Some text here 3333</p>
  </div>
</div>

JS

$('.box3 .box-header3').click(function(e) {
    var $content = $(this).closest('.box3').find('.box-content3');
  if($content.is(':hidden')) {
    $content.show();
  }
  else {
    $content.hide();
  }
});

I prefer the solution one but sometimes use solution two. Depend what is frendly for you.

JS DEMO


问:
How to extract certain portion of String using RegEx expression?
I would like to extract certain values from the given String

String --> 1ABCDE23

I need only ABCDE from the above string value. Always skip the first value(1) and get next 5 characters(ABCDE) and skip the rest(23)

Appreciate your help

答:
Always skip the first value(1) and get next 5 characters(ABCDE) and skip the rest(23)

This is just extracting a substring from a string! You don't need a regex for this - there has to be a faster function for that in the language you're using, assuming you're using a sane language.

Here are some examples:

Java: String abcde = "1ABCDE23".substring(1, 6);

JavaScript: var abcde = "1ABCDE23".substring(1, 6);

C++: std::string abcde = std::string("1ABCDE23").substr(1, 5);

Python: abcde = "1ABCDE23"[1:6]

PHP: $abcde = substr("1ABCDE23", 1, 5);

C#: string abcde = "1ABCDE23".Substring(1, 5);

Perl: $abcde = substr "1ABCDE23", 1, 5;

Ruby: abcde = "1ABCDE23"[1...6]

If you're using an insane language that has a regex engine with support for capturing groups but not a facility for extracting substrings from strings, you can run this regex (which is suggested by sln) and take the first capturing group:

^.(.{5}).*

^          the match must be at the beginning of the string
 .         match any character
  (    )   put what's matched by the parenthesized expression into the 1st capturing group
   .{5}    match 5 characters; any character goes
        .* match 0 or more characters; any character goes
```


问:
How to run the same test-case for different classes?
I have several classes that share some invariants and have a common interface, and I would like to run automatically the same test for each of them.

As an example, suppose I have several classes that implement different approaches for partitioning a data-set. The common invariant here would be, that for all of these classes the union over all partitions should equal the original data-set.

What I currently have looks something like this:

```<code>class PartitionerInvariantsTests(unittest.TestCase):
    def setUp(self):
        self.testDataSet = range(100) # create test-data-set

    def impl(self, partitioner):
        self.assertEqual(self.testDataSet,
                         chain.from_iterable(partitioner(self.testDataSet))
</code>```

Then I add a different function that calls impl for each of the classes I want to test with an instance of that class. The problem with this becomes apparent when doing this for more than one test-function. Suppose I have 5 test-functions and 5 classes I want to test. This would make 25 functions that look almost identical for invoking all the tests.

Another approach I was thinking about was to implement the template as a super-class, and then create a sub-class for each of the classes I want to test. The sub-classes could provide a function for instantiating the class. The problem with that is that the default test-loader would consider the (unusable) base-class a valid test-case and try to run it, which would fail.

So, what are your suggestions?

P.S.: I am using Python 2.6

答:
Subclass PartitionerInvariantsTests:

```<code>class PartitionerInvariantsTests(unittest.TestCase):
    def test_impl(self):
        self.assertEqual(self.testDataSet,
                         chain.from_iterable(self.partitioner(self.testDataSet))

class PartitionerATests(PartitionerInvariantsTests):
</code>```

for each Partitioner class you wish to test. Then test_impl would be run for each Partitioner class, by virtue of inheritance.

Following up on Nathon's comment, you can prevent the base class from being tested by having it inherit only from object:

```<code>import unittest

class Test(object):
    def test_impl(self):
        print('Hi')

class TestA(Test,unittest.TestCase):
    pass

class TestB(Test,unittest.TestCase):
    pass

if __name__ == '__main__':
    unittest.sys.argv.insert(1,'--verbose')
    unittest.main(argv = unittest.sys.argv)
</code>```

Running test.py yields

```<code>test_impl (__main__.TestA) ... Hi
ok
test_impl (__main__.TestB) ... Hi
ok

----------------------------------------------------------------------
Ran 2 tests in 0.000s

OK
</code>```

Body:
I have several classes that share some invariants and have a common interface, and I would like to run automatically the same test for each of them.

As an example, suppose I have several classes that implement different approaches for partitioning a data-set. The common invariant here would be, that for all of these classes the union over all partitions should equal the original data-set.

What I currently have looks something like this:

class PartitionerInvariantsTests(unittest.TestCase):
    def setUp(self):
        self.testDataSet = range(100) # create test-data-set

    def impl(self, partitioner):
        self.assertEqual(self.testDataSet,
                         chain.from_iterable(partitioner(self.testDataSet))

Then I add a different function that calls impl for each of the classes I want to test with an instance of that class. The problem with this becomes apparent when doing this for more than one test-function. Suppose I have 5 test-functions and 5 classes I want to test. This would make 25 functions that look almost identical for invoking all the tests.

Another approach I was thinking about was to implement the template as a super-class, and then create a sub-class for each of the classes I want to test. The sub-classes could provide a function for instantiating the class. The problem with that is that the default test-loader would consider the (unusable) base-class a valid test-case and try to run it, which would fail.

So, what are your suggestions?

P.S.: I am using Python 2.6

Body:
Subclass PartitionerInvariantsTests:

class PartitionerInvariantsTests(unittest.TestCase):
    def test_impl(self):
        self.assertEqual(self.testDataSet,
                         chain.from_iterable(self.partitioner(self.testDataSet))

class PartitionerATests(PartitionerInvariantsTests):

for each Partitioner class you wish to test. Then test_impl would be run for each Partitioner class, by virtue of inheritance.

Following up on Nathon's comment, you can prevent the base class from being tested by having it inherit only from object:

import unittest

class Test(object):
    def test_impl(self):
        print('Hi')

class TestA(Test,unittest.TestCase):
    pass

class TestB(Test,unittest.TestCase):
    pass

if __name__ == '__main__':
    unittest.sys.argv.insert(1,'--verbose')
    unittest.main(argv = unittest.sys.argv)

Running test.py yields

test_impl (__main__.TestA) ... Hi
ok
test_impl (__main__.TestB) ... Hi
ok

----------------------------------------------------------------------
Ran 2 tests in 0.000s

OK


问:
Lazy let? Unswifty workaround in structs
I have an immutable struct that I'm working with, and I'm trying to create a property that is not a computed value, however it's assignation requires the values of previously assigned properties.

(Wow mouthful).

The property I'm struggling with is perimeter: Int

```<code>// Floor made out of square tiles.
struct Floor {

  let
  size:           (x: Int, y: Int), // How many tiles in the floor
  tilePerimeter:  Int,

  // Calculate entire floor's perimeter based on tile quantity and perimeter:
  lazy let perimeter: Int = {

    let
    t4th  = self.tilePerimeter / 4,  // Tile width / length
    sx    = self.size.x * t4th,      // All X tiles' length
    sy    = self.size.y * t4th       // All Y tiles' width

    return (sx * 2) + (sy * 2)       // Perimeter calc
  }()
};
</code>```

Unfortunately, Swift will not let me use a lazy let.. So my workaround here was to just make a computed var with only a getter... but if this calculation took a long time (loading an image or complex math) then it would be called many times, when really it is only needed to call once

So my actual workaround was to just to create an initializer and assign the perimeter there... only some of my structs have MANY properties, and not creating an initializer for structs is part of the Swiftiness that I love.

I know that I could just make this a lazy var and instantiate the struct as let, but that seems confusing and error-prone.

Is there a way to do this where I can retain immutability, performance, and Swiftiness? And also, what is the reason for there not being allowed to use lazy let?

答:
Maybe you could use lazy var after all:

```<code>lazy private(set) var perimeter: Int = {
    ...
}()
</code>```

A read-only var gets you closer to the desired let semantics.

Body:
I have an immutable struct that I'm working with, and I'm trying to create a property that is not a computed value, however it's assignation requires the values of previously assigned properties.

(Wow mouthful).

The property I'm struggling with is perimeter: Int

// Floor made out of square tiles.
struct Floor {

  let
  size:           (x: Int, y: Int), // How many tiles in the floor
  tilePerimeter:  Int,

  // Calculate entire floor's perimeter based on tile quantity and perimeter:
  lazy let perimeter: Int = {

    let
    t4th  = self.tilePerimeter / 4,  // Tile width / length
    sx    = self.size.x * t4th,      // All X tiles' length
    sy    = self.size.y * t4th       // All Y tiles' width

    return (sx * 2) + (sy * 2)       // Perimeter calc
  }()
};

Unfortunately, Swift will not let me use a lazy let.. So my workaround here was to just make a computed var with only a getter... but if this calculation took a long time (loading an image or complex math) then it would be called many times, when really it is only needed to call once

So my actual workaround was to just to create an initializer and assign the perimeter there... only some of my structs have MANY properties, and not creating an initializer for structs is part of the Swiftiness that I love.

I know that I could just make this a lazy var and instantiate the struct as let, but that seems confusing and error-prone.

Is there a way to do this where I can retain immutability, performance, and Swiftiness? And also, what is the reason for there not being allowed to use lazy let?

Body:
Maybe you could use lazy var after all:

lazy private(set) var perimeter: Int = {
    ...
}()

A read-only var gets you closer to the desired let semantics.


问:
How to make a JButton unclickable after clicking on it?
Here's my code :

```<code>for(int row = 0; row < 10; row++)
{
    for(int col = 0; col < 10; col++)
    {
            button = new JButton();

            panel_1.add(button);
     }
 }

    button.addActionListener(new ActionListener()
    {
        public void actionPerformed(ActionEvent e)
        {
            //If Button is clicked, make the button unclickable
            if(button == (JButton)e.getSource())
            {
                button.setEnabled(false);

            }
        }

    });
</code>```

I want to make any JButton I click from this 10 x 10 grid button layout unclickable; however, this method only makes no other that the right button unclickable, What's wrong? I have put the ActionListener outside the for-Loop that is responsible for making the buttons. I don't know what's going on.

Here's what it looks like :

Edit: bsd code works. Add ActionListener before adding the buttons or something along those lines.

答:
You only add the ActionListener to the last button created.

You need to add the ActionListener to every button created inside the loop.

So the code should be something like:

```<code>ActionListener al = new ActionListener()
{
    public void actionPerformed(ActionEvent e)
    {
         JButton button = (JButton)e.getSource();
         button.setEnabled( false );
    }
};

for(int row = 0; row < 10; row++)
{
    for(int col = 0; col < 10; col++)
    {
            button = new JButton();
            button.addActionListener( al );
            panel_1.add(button);
     }
 }
</code>```

Body:
Here's my code :

for(int row = 0; row < 10; row++)
{
    for(int col = 0; col < 10; col++)
    {
            button = new JButton();

            panel_1.add(button);
     }
 }

    button.addActionListener(new ActionListener()
    {
        public void actionPerformed(ActionEvent e)
        {
            //If Button is clicked, make the button unclickable
            if(button == (JButton)e.getSource())
            {
                button.setEnabled(false);

            }
        }

    });

I want to make any JButton I click from this 10 x 10 grid button layout unclickable; however, this method only makes no other that the right button unclickable, What's wrong? I have put the ActionListener outside the for-Loop that is responsible for making the buttons. I don't know what's going on.

Here's what it looks like :

Edit: bsd code works. Add ActionListener before adding the buttons or something along those lines.

Body:
You only add the ActionListener to the last button created.

You need to add the ActionListener to every button created inside the loop.

So the code should be something like:

ActionListener al = new ActionListener()
{
    public void actionPerformed(ActionEvent e)
    {
         JButton button = (JButton)e.getSource();
         button.setEnabled( false );
    }
};

for(int row = 0; row < 10; row++)
{
    for(int col = 0; col < 10; col++)
    {
            button = new JButton();
            button.addActionListener( al );
            panel_1.add(button);
     }
 }