问:
Is it actually possible to store and process individual UTF-8 characters on C ? If so, how?
I've written a program in C that breaks words down into syllables, segments and letters. It's working well with ASCII characters but I want to make versions that work for the IPA and Arabic too.

I'm having massive problems saving and performing functions on individual characters. My editor and console are both set up to UTF-8 and can display Arabic text fine if I save it as a char*, but when I try to print wchars they display random punctuation marks.

My program needs to be able to recognise an individual UTF-8 character in order to work. For example, for the word 'though' it stores 't' as syllable[1]segment[1]letter[1], h as syllable[1]segment[1]letter[2] etc. I want to be able to do the same for non-ASCII characters.

I've spent basically the whole day researching unicode and trying out different methods and I can't get any of them to let me store an Arabic character as a character.

I'm not sure if I've just made some stupid syntax errors along the way, if I've completely misunderstood the whole concept, or if it actually just isn't possible to do what I want in C and I should just give up and try another language...

I would massively, massively, massively appreciate any help you can offer! I'm pretty new to programming, but unicode is completely instrumental to my work so I want to work out how to do it from the beginning.

My understanding of how unicode works (in case that's where I'm going wrong):

I type some text into my editor. My editor encodes it according to the encoding I have set. So if I set it to UFT-8 it will encode the Arabic letter ب with the 2 byte sequence 0xd8 0xab which indicates the code point U+0628.

I compile it, breaking down 0xd8 0xab into the binary 11011000 10101000.

I run it on the command prompt. The command prompt interprets the text according to the encoding I have set, so if I set it to UFT-8 it should interpret 11011000 10101000 as the code point U+0628. Unicode algorithms also tell it which version of U+0628 to display to me, as the character has different shapes depending on where it is in the word. As the character is alone it will show me the standalone version ب

My understanding of the ways I can process unicode in C:

Option A - Use single bytes encoded as UTF-8 (http://www.nubaria.com/en/blog/?p=289)

Use single bytes encoded as UTF-8. Leave all my datatypes as chars and char arrays and only type ASCII characters in my code. If I absolutely have to hard code a unicode character enter it as an array in the format:

```<code>    const char kChineseSampleText[] = "\xe4\xb8\xad\xe6\x96\x87";
</code>```

My problems with this:

I need to manipulate individual characters

Having to type Arabic characters as code points is going to render my code completely unreadable and slow me down immensely.

Option B - Use wchar and friends (http://icu-project.org/docs/papers/unicode_wchar_t.html)

Swap using chars for wchars, which hold 2 to 4 bytes depending on the compiler. String functions like strlen will not work as they are expecting characters to be one byte, but there are w functions like  wprintf I can use instead.

My problem with this:

I can’t get wchars to print Arabic characters at all! I can get them to print English letters fine, but Arabic characters just pull through as random punctuation marks.

I've tried inputing the unicode code point as well as the actual Arabic character and I've tried printing them both to the console and to a UTF-8 encoded text file and I get the same result, even though both the console and the text file display Arabic text if entered as a char*. I've included my code at the end.

(It’s worth saying here that I am aware that a lot of people think wchars are bad because they aren’t very portable and because they take up extra space for ASCII characters. But at this stage, neither of those things are really a worry for me - I’m just writing the program to run on my own computer and the program will only be processing short strings.)

Option C - Use external libraries

I've read in various comments that external libraries are the way to go so I've tried:

C programming library

http://www.cprogramming.com/tutorial/unicode.html suggests replacing all chars with unsigned long integers and using special functions for iterating through strings etc. The site even provides a sample library to download.

My problem:

While I can set the character to be an unsigned long integer I can’t print it out, because the printf and wprintf functions don’t work, and neither does the library provided on the website (I think maybe the library was designed for Linux? Some of the datatypes are invalid and amending them didn't work either)

ICU library

My problem:

I downloaded the ICU library, but when I was looking into how to use it I saw that functionality such as the characterIterator is not available for use in C (http://userguide.icu-project.org/strings). Being able to iterate through characters is completely fundamental to what I need to do, so I don't think the library will work for me.

My code

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

int main ()
{
wchar_t unicode = L'\xd8ac';
wchar_t arabic = L'ب';
wchar_t number = 0x062c;

FILE* f;
f = fopen("unitest.txt","w");
char* string = "ايه الاخبار";

//printf - works

printf("printf - literal arabic character is \"م\"\n");
fprintf(f,"printf - literal arabic character is \"م\"\n");

printf("printf - char* string is \"%s\"\n",string);
fprintf(f,"printf - char* string is \"%s\"\n",string);

//wprintf  - english - works

wprintf(L"wprintf - literal english char is \"%C\"\n\n", L't');
fwprintf(f,L"wprintf - literal english char is \"%C\"\n\n", L't');

//wprintf - arabic - doesnt work

wprintf(L"wprintf - unicode wchar_t is \"%C\"\n", unicode);
fwprintf(f,L"wprintf - unicode wchar_t is \"%C\"\n", unicode);

wprintf(L"wprintf - unicode number wchar_t is \"%C\"\n", number);
fwprintf(f,L"wprintf - unicode number wchar_t is \"%C\"\n", number);

wprintf(L"wprintf - arabic wchar_t is \"%C\"\n", arabic);
fwprintf(f,L"wprintf - arabic wchar_t is \"%C\"\n", arabic);

wprintf(L"wprintf - literal arabic character is \"%C\"\n",L'ت');
fwprintf(f,L"wprintf - literal arabic character is \"%C\"\n",L'ت');

wprintf(L"wprintf - literal arabic character in string is \"م\"\n\n");
fwprintf(f,L"wprintf - literal arabic character in string is \"م\"\n\n");

fclose(f);

return 0;
}
</code>```

Output file

```<code>printf - literal arabic character is "م"
printf - char* string is "ايه الاخبار"
wprintf - literal english char is "t"

wprintf - unicode wchar_t is "�"
wprintf - unicode number wchar_t is ","
wprintf - arabic wchar_t is "("
wprintf - literal arabic character is "*"
wprintf - literal arabic character in string is ""
</code>```

I'm using Windows 10, Notepad++ and  MinGW.

Edit
This got marked as a duplicate of Light C Unicode Library but I don't think it really answers my question. I've downloaded the library and had a look at and you can call me stupid if you like, but I'm really new to programming and I don't understand most of the code in the library, so it's hard for me to work out how I can use it achieve what I want. I searched the library for a print function and couldn't find one...

I just want to save a UTF-8 character and then print it out again! Do I really need to install an entire library to do that? I would just really appreciate someone taking pity on me and telling me in baby terms how I can do it... People keep saying I should use uint_32 or something instead of wchar - but how do I then print those datatypes? Can I do it with wprintf?!

答:
You need to very clearly understand the difference between a Unicode code point and UTF-8. UTF-8 is a variable byte encoding of Unicode code points. The lower end, values 0-127, is stored as a single byte. That's the main point of UTF-8, and makes it backwards compatible with Ascii.

When bit 7 is set, for values over 127, a variable length code of two bytes or more is used. The leading byte always has the bit pattern 11xxxxxx.

Here's code to get the skip (the number of character used), also to read a codepoint and to write one.

```<code>static const unsigned int offsetsFromUTF8[6] =
{
    0x00000000UL, 0x00003080UL, 0x000E2080UL,
    0x03C82080UL, 0xFA082080UL, 0x82082080UL
};

static const unsigned char trailingBytesForUTF8[256] = {
    0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
    0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
    0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
    0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
    0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
    0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
    1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
    2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 3,3,3,3,3,3,3,3,4,4,4,4,5,5,5,5
};

int bbx_utf8_skip(const char *utf8)
{
  return trailingBytesForUTF8[(unsigned char) *utf8] + 1;
}

int bbx_utf8_getch(const char *utf8)
{
    int ch;
    int nb;

    nb = trailingBytesForUTF8[(unsigned char)*utf8];
    ch = 0;
    switch (nb)
    {
            /* these fall through deliberately */
        case 3: ch += (unsigned char)*utf8++; ch <<= 6;
        case 2: ch += (unsigned char)*utf8++; ch <<= 6;
        case 1: ch += (unsigned char)*utf8++; ch <<= 6;
        case 0: ch += (unsigned char)*utf8++;
    }
    ch -= offsetsFromUTF8[nb];

    return ch;
}

int bbx_utf8_putch(char *out, int ch)
{
  char *dest = out;
  if (ch < 0x80)
  {
     *dest++ = (char)ch;
  }
  else if (ch < 0x800)
  {
    *dest++ = (ch>>6) | 0xC0;
    *dest++ = (ch & 0x3F) | 0x80;
  }
  else if (ch < 0x10000)
  {
     *dest++ = (ch>>12) | 0xE0;
     *dest++ = ((ch>>6) & 0x3F) | 0x80;
     *dest++ = (ch & 0x3F) | 0x80;
  }
  else if (ch < 0x110000)
  {
     *dest++ = (ch>>18) | 0xF0;
     *dest++ = ((ch>>12) & 0x3F) | 0x80;
     *dest++ = ((ch>>6) & 0x3F) | 0x80;
     *dest++ = (ch & 0x3F) | 0x80;
  }
  else
    return 0;
  return dest - out;
}
</code>```

Using these functions or similar, you convert between code points and UTF-8
and back.

Windows currently uses UTF-16 for its apis. To a first approximation, UTF-16 is the code points in 16 bit format. So when writing a UTF-8 based program, you need to convert the UTF-8 to UTF-16 (using wide chars) immediately before calling Windows output functions.

Support for UTF-8 via printf() is patchy. Passing a UTF-8 encoded string to printf() is unlikely to do what you want.

Body:
I've written a program in C that breaks words down into syllables, segments and letters. It's working well with ASCII characters but I want to make versions that work for the IPA and Arabic too.

I'm having massive problems saving and performing functions on individual characters. My editor and console are both set up to UTF-8 and can display Arabic text fine if I save it as a char*, but when I try to print wchars they display random punctuation marks.

My program needs to be able to recognise an individual UTF-8 character in order to work. For example, for the word 'though' it stores 't' as syllable[1]segment[1]letter[1], h as syllable[1]segment[1]letter[2] etc. I want to be able to do the same for non-ASCII characters.

I've spent basically the whole day researching unicode and trying out different methods and I can't get any of them to let me store an Arabic character as a character.

I'm not sure if I've just made some stupid syntax errors along the way, if I've completely misunderstood the whole concept, or if it actually just isn't possible to do what I want in C and I should just give up and try another language...

I would massively, massively, massively appreciate any help you can offer! I'm pretty new to programming, but unicode is completely instrumental to my work so I want to work out how to do it from the beginning.

My understanding of how unicode works (in case that's where I'm going wrong):

I type some text into my editor. My editor encodes it according to the encoding I have set. So if I set it to UFT-8 it will encode the Arabic letter ب with the 2 byte sequence 0xd8 0xab which indicates the code point U+0628.

I compile it, breaking down 0xd8 0xab into the binary 11011000 10101000.

I run it on the command prompt. The command prompt interprets the text according to the encoding I have set, so if I set it to UFT-8 it should interpret 11011000 10101000 as the code point U+0628. Unicode algorithms also tell it which version of U+0628 to display to me, as the character has different shapes depending on where it is in the word. As the character is alone it will show me the standalone version ب

My understanding of the ways I can process unicode in C:

Option A - Use single bytes encoded as UTF-8 (http://www.nubaria.com/en/blog/?p=289)

Use single bytes encoded as UTF-8. Leave all my datatypes as chars and char arrays and only type ASCII characters in my code. If I absolutely have to hard code a unicode character enter it as an array in the format:

    const char kChineseSampleText[] = "\xe4\xb8\xad\xe6\x96\x87";

My problems with this:

I need to manipulate individual characters

Having to type Arabic characters as code points is going to render my code completely unreadable and slow me down immensely.

Option B - Use wchar and friends (http://icu-project.org/docs/papers/unicode_wchar_t.html)

Swap using chars for wchars, which hold 2 to 4 bytes depending on the compiler. String functions like strlen will not work as they are expecting characters to be one byte, but there are w functions like  wprintf I can use instead.

My problem with this:

I can’t get wchars to print Arabic characters at all! I can get them to print English letters fine, but Arabic characters just pull through as random punctuation marks.

I've tried inputing the unicode code point as well as the actual Arabic character and I've tried printing them both to the console and to a UTF-8 encoded text file and I get the same result, even though both the console and the text file display Arabic text if entered as a char*. I've included my code at the end.

(It’s worth saying here that I am aware that a lot of people think wchars are bad because they aren’t very portable and because they take up extra space for ASCII characters. But at this stage, neither of those things are really a worry for me - I’m just writing the program to run on my own computer and the program will only be processing short strings.)

Option C - Use external libraries

I've read in various comments that external libraries are the way to go so I've tried:

C programming library

http://www.cprogramming.com/tutorial/unicode.html suggests replacing all chars with unsigned long integers and using special functions for iterating through strings etc. The site even provides a sample library to download.

My problem:

While I can set the character to be an unsigned long integer I can’t print it out, because the printf and wprintf functions don’t work, and neither does the library provided on the website (I think maybe the library was designed for Linux? Some of the datatypes are invalid and amending them didn't work either)

ICU library

My problem:

I downloaded the ICU library, but when I was looking into how to use it I saw that functionality such as the characterIterator is not available for use in C (http://userguide.icu-project.org/strings). Being able to iterate through characters is completely fundamental to what I need to do, so I don't think the library will work for me.

My code

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

int main ()
{
wchar_t unicode = L'\xd8ac';
wchar_t arabic = L'ب';
wchar_t number = 0x062c;

FILE* f;
f = fopen("unitest.txt","w");
char* string = "ايه الاخبار";

//printf - works

printf("printf - literal arabic character is \"م\"\n");
fprintf(f,"printf - literal arabic character is \"م\"\n");

printf("printf - char* string is \"%s\"\n",string);
fprintf(f,"printf - char* string is \"%s\"\n",string);

//wprintf  - english - works

wprintf(L"wprintf - literal english char is \"%C\"\n\n", L't');
fwprintf(f,L"wprintf - literal english char is \"%C\"\n\n", L't');

//wprintf - arabic - doesnt work

wprintf(L"wprintf - unicode wchar_t is \"%C\"\n", unicode);
fwprintf(f,L"wprintf - unicode wchar_t is \"%C\"\n", unicode);

wprintf(L"wprintf - unicode number wchar_t is \"%C\"\n", number);
fwprintf(f,L"wprintf - unicode number wchar_t is \"%C\"\n", number);

wprintf(L"wprintf - arabic wchar_t is \"%C\"\n", arabic);
fwprintf(f,L"wprintf - arabic wchar_t is \"%C\"\n", arabic);

wprintf(L"wprintf - literal arabic character is \"%C\"\n",L'ت');
fwprintf(f,L"wprintf - literal arabic character is \"%C\"\n",L'ت');

wprintf(L"wprintf - literal arabic character in string is \"م\"\n\n");
fwprintf(f,L"wprintf - literal arabic character in string is \"م\"\n\n");

fclose(f);

return 0;
}

Output file

printf - literal arabic character is "م"
printf - char* string is "ايه الاخبار"
wprintf - literal english char is "t"

wprintf - unicode wchar_t is "�"
wprintf - unicode number wchar_t is ","
wprintf - arabic wchar_t is "("
wprintf - literal arabic character is "*"
wprintf - literal arabic character in string is ""

I'm using Windows 10, Notepad++ and  MinGW.

Edit
This got marked as a duplicate of Light C Unicode Library but I don't think it really answers my question. I've downloaded the library and had a look at and you can call me stupid if you like, but I'm really new to programming and I don't understand most of the code in the library, so it's hard for me to work out how I can use it achieve what I want. I searched the library for a print function and couldn't find one...

I just want to save a UTF-8 character and then print it out again! Do I really need to install an entire library to do that? I would just really appreciate someone taking pity on me and telling me in baby terms how I can do it... People keep saying I should use uint_32 or something instead of wchar - but how do I then print those datatypes? Can I do it with wprintf?!

Body:
You need to very clearly understand the difference between a Unicode code point and UTF-8. UTF-8 is a variable byte encoding of Unicode code points. The lower end, values 0-127, is stored as a single byte. That's the main point of UTF-8, and makes it backwards compatible with Ascii.

When bit 7 is set, for values over 127, a variable length code of two bytes or more is used. The leading byte always has the bit pattern 11xxxxxx.

Here's code to get the skip (the number of character used), also to read a codepoint and to write one.

static const unsigned int offsetsFromUTF8[6] =
{
    0x00000000UL, 0x00003080UL, 0x000E2080UL,
    0x03C82080UL, 0xFA082080UL, 0x82082080UL
};

static const unsigned char trailingBytesForUTF8[256] = {
    0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
    0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
    0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
    0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
    0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
    0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
    1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
    2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 3,3,3,3,3,3,3,3,4,4,4,4,5,5,5,5
};

int bbx_utf8_skip(const char *utf8)
{
  return trailingBytesForUTF8[(unsigned char) *utf8] + 1;
}

int bbx_utf8_getch(const char *utf8)
{
    int ch;
    int nb;

    nb = trailingBytesForUTF8[(unsigned char)*utf8];
    ch = 0;
    switch (nb)
    {
            /* these fall through deliberately */
        case 3: ch += (unsigned char)*utf8++; ch <<= 6;
        case 2: ch += (unsigned char)*utf8++; ch <<= 6;
        case 1: ch += (unsigned char)*utf8++; ch <<= 6;
        case 0: ch += (unsigned char)*utf8++;
    }
    ch -= offsetsFromUTF8[nb];

    return ch;
}

int bbx_utf8_putch(char *out, int ch)
{
  char *dest = out;
  if (ch < 0x80)
  {
     *dest++ = (char)ch;
  }
  else if (ch < 0x800)
  {
    *dest++ = (ch>>6) | 0xC0;
    *dest++ = (ch & 0x3F) | 0x80;
  }
  else if (ch < 0x10000)
  {
     *dest++ = (ch>>12) | 0xE0;
     *dest++ = ((ch>>6) & 0x3F) | 0x80;
     *dest++ = (ch & 0x3F) | 0x80;
  }
  else if (ch < 0x110000)
  {
     *dest++ = (ch>>18) | 0xF0;
     *dest++ = ((ch>>12) & 0x3F) | 0x80;
     *dest++ = ((ch>>6) & 0x3F) | 0x80;
     *dest++ = (ch & 0x3F) | 0x80;
  }
  else
    return 0;
  return dest - out;
}

Using these functions or similar, you convert between code points and UTF-8
and back.

Windows currently uses UTF-16 for its apis. To a first approximation, UTF-16 is the code points in 16 bit format. So when writing a UTF-8 based program, you need to convert the UTF-8 to UTF-16 (using wide chars) immediately before calling Windows output functions.

Support for UTF-8 via printf() is patchy. Passing a UTF-8 encoded string to printf() is unlikely to do what you want.


来源: stackexchange

问:
Swift3 passing value into array that is property of class
I have a swift viewcontroller - BulkGridCell, in it I have a property set up for an array:

```<code>var arrGroup: Array = [AnyObject]()
</code>```

I am instantiating BulkGridCell in another viewcontroller, BulkProcessController:

```<code>for (index, value) in self.arrData.enumerated() {

//add each data cell
let gridCell = storyboard.instantiateViewController(withIdentifier: "bulkGridCell") as! BulkGridCell
  resizeGridCell(vGridCell: gridCell.view, frameY: frameY, frameH:50.0)
  gridCell.bIsHeader = false
  gridCell.bIsDeleteProcess = bIsDelete
  gridCell.buildCell()
  self.svData.addSubview(gridCell.view)

  //pass the data entity to data cell
  gridCell.arrGroup.addObject(value)
</code>```

when I try to add value to the array arrGroup I get this error message:

Value of [AnyObject] has no member addObject

I'm crossing over from Obj-C to Swift so this has me a bit confused, isn't addObject a method of the Array object, I'm not trying to run that method off of value.

Any help would be appreciated.

Edit: value is a Core Data entity if that helps. I was reading that I might have to cast these to AnyObject, though when I tried value as AnyObject I still got the same error.

答:
So I'm noticing a couple issues that could be fixed with the correct syntax.

First if you have a custom object, and you want to create an array of those objects, the type of that array should [be in square brackets like this].
Lets say I have an object called Friend that I want to add into an array. I would create the array like this.

```<code>var arrayOfFriends: [Friend] = []
</code>```

This creates an array of Friends objects and it's currently empty.

To add elements into an array, you want to use the .append instance method on your array.

```<code>let friend1 = Friend()
let friend2 = Friend()

arrayOfFriends.append(friend1)
arrayOfFriends.append(friend2)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a swift viewcontroller - BulkGridCell, in it I have a property set up for an array:

var arrGroup: Array = [AnyObject]()

I am instantiating BulkGridCell in another viewcontroller, BulkProcessController:

for (index, value) in self.arrData.enumerated() {

//add each data cell
let gridCell = storyboard.instantiateViewController(withIdentifier: "bulkGridCell") as! BulkGridCell
  resizeGridCell(vGridCell: gridCell.view, frameY: frameY, frameH:50.0)
  gridCell.bIsHeader = false
  gridCell.bIsDeleteProcess = bIsDelete
  gridCell.buildCell()
  self.svData.addSubview(gridCell.view)

  //pass the data entity to data cell
  gridCell.arrGroup.addObject(value)

when I try to add value to the array arrGroup I get this error message:

Value of [AnyObject] has no member addObject

I'm crossing over from Obj-C to Swift so this has me a bit confused, isn't addObject a method of the Array object, I'm not trying to run that method off of value.

Any help would be appreciated.

Edit: value is a Core Data entity if that helps. I was reading that I might have to cast these to AnyObject, though when I tried value as AnyObject I still got the same error.

Body:
So I'm noticing a couple issues that could be fixed with the correct syntax.

First if you have a custom object, and you want to create an array of those objects, the type of that array should [be in square brackets like this].
Lets say I have an object called Friend that I want to add into an array. I would create the array like this.

var arrayOfFriends: [Friend] = []

This creates an array of Friends objects and it's currently empty.

To add elements into an array, you want to use the .append instance method on your array.

let friend1 = Friend()
let friend2 = Friend()

arrayOfFriends.append(friend1)
arrayOfFriends.append(friend2)


问:
XSTREAM array converter
I want to convert below XML to objects. I

```<code><authentication>
    <name>Reese Rideout</name>
    <shows type="array">
        <show>stage</show>
        <show>youtube</show>
    </shows>
</authentication>
</code>```

I have Authentication class with List<Show> shows. I believe I will need to use the array converter. However, I do not understand how to use it and am not finding any documents.

Kindly suggest how could I parse this into my object graph.

答:
This is how I fixed this:

```<code>xstream.alias("shows", Shows.class);
xstream.alias("show", String.class);
</code>```

And also set the Shows.shows field as an implicit collection: xstream.addImplicitCollection(Shows.class, "shows");

Title: XSTREAM array converter

Body:
I want to convert below XML to objects. I

<authentication>
    <name>Reese Rideout</name>
    <shows type="array">
        <show>stage</show>
        <show>youtube</show>
    </shows>
</authentication>

I have Authentication class with List<Show> shows. I believe I will need to use the array converter. However, I do not understand how to use it and am not finding any documents.

Kindly suggest how could I parse this into my object graph.

Body:
This is how I fixed this:

xstream.alias("shows", Shows.class);
xstream.alias("show", String.class);

And also set the Shows.shows field as an implicit collection: xstream.addImplicitCollection(Shows.class, "shows");


问:
Joomla 3.7.2 can't send any emails with contact forms
I'm at the end of my rope here and I'm here to get some help. I'm going to try and explain it as best as I can.

I have a website running on Joomla 3.7.2 which you can visit here: https://www.meteordesign.nl

For some reason my contact form does not work anymore. Whenever I click 'send' the page reloads but no confirmation or an email being sent.

I have tried the following:

Switched from PHP mail to SMTP and send a test mail (came in fine).

Used several other contact form modules and components and even an HTML one which you can find here https://bootstrapious.com/p/bootstrap-recaptcha

They all don't work. I have tried disabling my .htaccess file to see if that solved it but to no avail.

You can find the contact form here:
https://www.meteordesign.nl/contact

I don't know if this is important but recently my hosting provider switched to https. Could that be causing it?

I hope I explained it well. If not feel free to ask me more questions, I really need your help fixing this!

答: You are likely running into a JavaScript issue. Just tested this and you seem that you have solved it. Please let us know what the issue was so that others can learn from your experience.</p>


问:
Determining if a squence is true
How would I determine if a sequence is true?
Lets say I have this code

```<code>int a = random.nextInt(10);
int b = random.nextInt(10);
int c = random.nextInt(10);
</code>```

How would I use an if statement or a loop to determine if/when a = 1, b = 2, and c = 3 (or any combination of a,b, and c being only one number apart. Like 4,5,6 or 7,8,9) is in a sequence such as stated?

答:
You can check if the distance between the two numbers is equal to one:</p>

```<code>if(b-a == 1 && c-b == 1)
</code>```

Title: Determining if a squence is true

Body:
How would I determine if a sequence is true?
Lets say I have this code

int a = random.nextInt(10);
int b = random.nextInt(10);
int c = random.nextInt(10);

How would I use an if statement or a loop to determine if/when a = 1, b = 2, and c = 3 (or any combination of a,b, and c being only one number apart. Like 4,5,6 or 7,8,9) is in a sequence such as stated?

Body:
You can check if the distance between the two numbers is equal to one:

if(b-a == 1 && c-b == 1)


问:
Geany: How to increase the font size of plugin MultiTerm in Geany text editor?
I have been using geany text editor quite a lot.

I have activated the plugin MultiTerm, however, the problem is the font is too small and I can't increase the font size.

Attempts:

1. select the text in MultiTerm and Cmd +

2. select the text in MultiTerm and go to View then choose Increase Font.

I searched the preference options and I was unable to find the solution.

The screenshot looks like this:

I need a magnifier to see what the letters are there in the Multi Terminal to read them, but I assume that was not the purpose of the plugin.

If anybody has any idea the suggestion will be truly appreciated.

答:
According to plugin documentation the fontsize can be changed in plugins config file:

~/.config/geany/plugins/multiterm/multiterm.conf

You can tweak also background and font color.

sample from file:

```<code>[shell=default]

# This will be the tabs default tab label and won't change unless
# track_title is set to true.
name=Default Shell

# This is the command to fork in the VTE, leave blank for default shell
command=sh

# Make the tab's label track the VTE title
track_title=true

# Background color, foreground color and font for the VTE
bg_color=#ffffff
fg_color=#000000
font=Monospace 44
</code>```

Body:
According to plugin documentation the fontsize can be changed in plugins config file:

~/.config/geany/plugins/multiterm/multiterm.conf

You can tweak also background and font color.

sample from file:

[shell=default]

# This will be the tabs default tab label and won't change unless
# track_title is set to true.
name=Default Shell

# This is the command to fork in the VTE, leave blank for default shell
command=sh

# Make the tab's label track the VTE title
track_title=true

# Background color, foreground color and font for the VTE
bg_color=#ffffff
fg_color=#000000
font=Monospace 44


问:
Is it unPythonic to ask the package's user to extend a class, but the user cannot instantiate it?
I'm writing the Python bindings of a C library which allows the user to create custom "classes" in C and instantiate them through another object, something like:

my_class = create_class(init_callback, finalize_callback, ...);
instance1 = manager_create_object(some_manager, my_class, ...);
instance2 = manager_create_object(some_manager, my_class, ...);
```

<p>Unfortunately, the C language is not object-oriented, so this library uses the concept within the limits of what the language offers.</p>

<p>In Python, for a user to define its own class, I'd like to use the concept of a Python class:</p>

<pre class="lang-py prettyprint-override"><code>class MyClass(package.BaseClass):
    def __init__(self, ...):
        ...

    def _finalize(self, ...):
        ...

instance1 = some_manager.create_object(MyClass, ...)
instance2 = some_manager.create_object(MyClass, ...)
</code>```

I cannot instantiate the object directly with MyClass() because it needs said manager (see manager_create_object() above).

Is it weird/unPythonic to ask the user to extend the package's class (package.BaseClass in this example) without being able to instantiate the derived class (MyClass) directly with MyClass()? This is mostly for a plugin interface, where we would need the user to define one or more classes in a Python module file.

答:
It's not unusual to insist that the user (client side) supply a local implementation of certain capabilities, especially if you can supply examples and/or templates for the needed support.  Many suppliers do this, as they cannot cover all of the implementations.

However, make sure that you give a wide variety of examples.  You want to make it easy for your users.  Better yet, deliver files that constitute working implementations for several popular environments.

Body:
I'm writing the Python bindings of a C library which allows the user to create custom "classes" in C and instantiate them through another object, something like:

my_class = create_class(init_callback, finalize_callback, ...);
instance1 = manager_create_object(some_manager, my_class, ...);
instance2 = manager_create_object(some_manager, my_class, ...);

Unfortunately, the C language is not object-oriented, so this library uses the concept within the limits of what the language offers.

In Python, for a user to define its own class, I'd like to use the concept of a Python class:

class MyClass(package.BaseClass):
    def __init__(self, ...):
        ...

    def _finalize(self, ...):
        ...

instance1 = some_manager.create_object(MyClass, ...)
instance2 = some_manager.create_object(MyClass, ...)

I cannot instantiate the object directly with MyClass() because it needs said manager (see manager_create_object() above).

Is it weird/unPythonic to ask the user to extend the package's class (package.BaseClass in this example) without being able to instantiate the derived class (MyClass) directly with MyClass()? This is mostly for a plugin interface, where we would need the user to define one or more classes in a Python module file.


问:
duplicate context menu items when clicked multiple times on same row in JFace table in mac
I am using Jface table and have a context menu which differs for each row depending on the selected row.

When I click once the context menu is getting displayed fine, but when I click multiple times the context menu is getting added to the previous context menu and getting displayed twice or thrice depending on number of clicks.

This is happening only on mac and not on windows.

Can someone help me in resolving this?

答:
You had a similar issue with Eclipse 4.x using JFace at the time in 2013-2014

Right click on the second line (you may have to bring the context menu up a few times)

The context menu now shows some (but not all) entries twice: "Remove from Context" and the entries in "Team", "Compare With" and "Replace With" menus

That was fixed in that commit.

Even though your project might not involve Eclipse, the general reason can give you some clue for your specific project.

The reason of the problem is that some action contributions computed for the editor and active selection are the same.


问:
ScalaJS facades with JS and application data
I'm attempting to write a facade for a jQuery plugin (https://github.com/devbridge/jQuery-Autocomplete).  In includes some callbacks that pass an object I've modelled as:

```<code>@js.native
trait AutocompleteSuggestion extends js.Object {
  val value: String = js.native
  val data : js.Any = js.native
}
</code>```

The library needs to access value;  data is for my use.  I create the object, feed it to the library, and it gives it back to me as the argument to a callback.

The best I've been able to do for creating these objects is

```<code>object AutocompleteSuggestion {
  def apply[T](value: String, data: T) = {
    literal(value = value, data = data.asInstanceOf[js.Any]).asInstanceOf[AutocompleteSuggestion]
  }
}
</code>```

Callbacks that are passed one of these objects often end up looking like

```<code>def onSelect(suggestion: AutocompleteSuggestion): Unit = {
  val cb = suggestion.data.asInstanceOf[CourseBasic]
  // do something with the data
}
</code>```

Any suggestions on how to improve this?  In particular it feels like I'm doing a lot of casting.  I don't see that in the examples at https://www.scala-js.org/doc/interoperability/facade-types.html -- but those examples also studiously avoid using anything but primitive types.

答:
I suggest the following. Basically it boils down to typing your AutocompleteSuggestion better by giving a type parameter for the type of data. In addition, we make it an @ScalaJSDefined trait instead of @js.native (as most JS traits should be anyway) so that we can instantiate it in a type-safe way:

import js.annotation._

@ScalaJSDefined
trait AutocompleteSuggestion[T] extends js.Object {
  val value: String
  val data: T
}

object AutocompleteSuggestion {
  def apply[T](value0: String, data0: T): AutocompleteSuggestion[T] = {
    new AutocompleteSuggestion[T] {
      val value: String = value0
      val data: T = data0
    }
  }
}

def onSelect(suggestion: AutocompleteSuggestion[CourseBasic]): Unit = {
  val cb = suggestion.data
  // do something with the data
}
```

Aaand, not a single cast :)

Body:
I'm attempting to write a facade for a jQuery plugin (https://github.com/devbridge/jQuery-Autocomplete).  In includes some callbacks that pass an object I've modelled as:

@js.native
trait AutocompleteSuggestion extends js.Object {
  val value: String = js.native
  val data : js.Any = js.native
}

The library needs to access value;  data is for my use.  I create the object, feed it to the library, and it gives it back to me as the argument to a callback.

The best I've been able to do for creating these objects is

object AutocompleteSuggestion {
  def apply[T](value: String, data: T) = {
    literal(value = value, data = data.asInstanceOf[js.Any]).asInstanceOf[AutocompleteSuggestion]
  }
}

Callbacks that are passed one of these objects often end up looking like

def onSelect(suggestion: AutocompleteSuggestion): Unit = {
  val cb = suggestion.data.asInstanceOf[CourseBasic]
  // do something with the data
}

Any suggestions on how to improve this?  In particular it feels like I'm doing a lot of casting.  I don't see that in the examples at https://www.scala-js.org/doc/interoperability/facade-types.html -- but those examples also studiously avoid using anything but primitive types.

Body:
I suggest the following. Basically it boils down to typing your AutocompleteSuggestion better by giving a type parameter for the type of data. In addition, we make it an @ScalaJSDefined trait instead of @js.native (as most JS traits should be anyway) so that we can instantiate it in a type-safe way:

import js.annotation._

@ScalaJSDefined
trait AutocompleteSuggestion[T] extends js.Object {
  val value: String
  val data: T
}

object AutocompleteSuggestion {
  def apply[T](value0: String, data0: T): AutocompleteSuggestion[T] = {
    new AutocompleteSuggestion[T] {
      val value: String = value0
      val data: T = data0
    }
  }
}

def onSelect(suggestion: AutocompleteSuggestion[CourseBasic]): Unit = {
  val cb = suggestion.data
  // do something with the data
}

Aaand, not a single cast :)


问:
How to access elements under `shadow-root` at 'chrome://downloads' using jquery and selenium?
I am trying to get the name of the last downloaded file in my selenium javascript application.

I have my selenium driver navigating to the chrome downloads page using: driver.get('chrome://downloads'); , but when I get there, selenium is not able to find ANY elements on the download page.

The chrome downloads page 'chrome://downloads' has a bunch of shadow-root elements that I don't know how to get underneath in order to access the id's that I want. How do I access identifiers beneath shadow-root items?

I want to get $("#file-link") as shown here:

But when I use jquery to find it, everything returns null (probably because it's behind shadow-root)

Here's a big picture of all the information I have including showing that "#file-link" totally exists:

The code I am using to wait for the element to exist is the same that I use for all elements in my application, so I think this is already working:

```<code>driver.wait(until.elementLocated(By.id('downloads-manager')), 120000).then(function(){
    console.log("#downloads-manager shows");
    driver.findElement(By.id('downloads-manager')).then(function(dwMan){
        //How do I "open" #shadow-root now? :(
    });
});
</code>```

Here is my version information:

Chromium v54.0.2840.71

Node v6.5.0

ChromeDriver v2.27.440175

selenium-webdriver v3.4.0

Similar Question

Selenium webdriver can't find elements at chrome://downloads (This is the same problem I am having but in python)

Links

Selenium Javascript API: https://seleniumhq.github.io/selenium/docs/api/javascript/

答:
Why not check the downloads folder directly? I do this for downloading Excel files. I first clear the downloads folder, click the button to download the file, wait ~5 sec (varies by file size, internet speed, etc.), and then looking in the folder for a "*.xlsx" file. This also has the benefit of working with any browser.

C# Examples:

```<code>/// <summary>
/// Deletes the contents of the current user's "Downloads" folder
/// </summary>
public static void DeleteDownloads()
{
    // Get the default downloads folder for the current user
    string downloadFolderPath = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) + "\\Downloads";
    // Delete all existing files
    DirectoryInfo di = new DirectoryInfo(directoryPath);
    foreach (FileInfo file in di.GetFiles())
    {
        file.Delete();
    }
    foreach (DirectoryInfo dir in di.GetDirectories())
    {
        dir.Delete(true);
    }
}

/// <summary>
/// Looks for a file with the given extension (Example: "*.xlsx") in the current user's "Download" folder.
/// </summary>
/// <returns>Empty string if files are found</returns>
public static string LocateDownloadedFile(string fileExtension)
{
    // Get the default downloads folder for the current user
    string downloadFolderPath = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) + "\\Downloads";
    DirectoryInfo di = new DirectoryInfo(downloadFolderPath);
    FileInfo[] filesFound = di.GetFiles(fileExtension);
    if (filesFound.Length == 0)
    {
        return "No files present";
    }
    else
    {
        return "";
    }
}
</code>```

And then in my Test I can Assert.IsEmpty(LocateDownloadedFile); This way if the assert fails, the error message if printed.

Expected: String.Empty.
  Actual: No files present.

Body:
I am trying to get the name of the last downloaded file in my selenium javascript application.

I have my selenium driver navigating to the chrome downloads page using: driver.get('chrome://downloads'); , but when I get there, selenium is not able to find ANY elements on the download page.

The chrome downloads page 'chrome://downloads' has a bunch of shadow-root elements that I don't know how to get underneath in order to access the id's that I want. How do I access identifiers beneath shadow-root items?

I want to get $("#file-link") as shown here:

But when I use jquery to find it, everything returns null (probably because it's behind shadow-root)

Here's a big picture of all the information I have including showing that "#file-link" totally exists:

The code I am using to wait for the element to exist is the same that I use for all elements in my application, so I think this is already working:

driver.wait(until.elementLocated(By.id('downloads-manager')), 120000).then(function(){
    console.log("#downloads-manager shows");
    driver.findElement(By.id('downloads-manager')).then(function(dwMan){
        //How do I "open" #shadow-root now? :(
    });
});

Here is my version information:

Chromium v54.0.2840.71

Node v6.5.0

ChromeDriver v2.27.440175

selenium-webdriver v3.4.0

Similar Question

Selenium webdriver can't find elements at chrome://downloads (This is the same problem I am having but in python)

Links

Selenium Javascript API: https://seleniumhq.github.io/selenium/docs/api/javascript/

Body:
Why not check the downloads folder directly? I do this for downloading Excel files. I first clear the downloads folder, click the button to download the file, wait ~5 sec (varies by file size, internet speed, etc.), and then looking in the folder for a "*.xlsx" file. This also has the benefit of working with any browser.

C# Examples:

/// <summary>
/// Deletes the contents of the current user's "Downloads" folder
/// </summary>
public static void DeleteDownloads()
{
    // Get the default downloads folder for the current user
    string downloadFolderPath = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) + "\\Downloads";
    // Delete all existing files
    DirectoryInfo di = new DirectoryInfo(directoryPath);
    foreach (FileInfo file in di.GetFiles())
    {
        file.Delete();
    }
    foreach (DirectoryInfo dir in di.GetDirectories())
    {
        dir.Delete(true);
    }
}

/// <summary>
/// Looks for a file with the given extension (Example: "*.xlsx") in the current user's "Download" folder.
/// </summary>
/// <returns>Empty string if files are found</returns>
public static string LocateDownloadedFile(string fileExtension)
{
    // Get the default downloads folder for the current user
    string downloadFolderPath = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) + "\\Downloads";
    DirectoryInfo di = new DirectoryInfo(downloadFolderPath);
    FileInfo[] filesFound = di.GetFiles(fileExtension);
    if (filesFound.Length == 0)
    {
        return "No files present";
    }
    else
    {
        return "";
    }
}

And then in my Test I can Assert.IsEmpty(LocateDownloadedFile); This way if the assert fails, the error message if printed.

Expected: String.Empty.
  Actual: No files present.


问:
Use main function in R
I've been using R for 4 months now, and I really hope there is a way to use main function as in other languages (C++, Python...)

The main reason I want to do this is that all the variables I use in a R script are global variables that can potentially pollute the namespace of the functions I defined in the same script:

```<code>f <- function(x) {
  x + a
}
a <- 50
f(5)
</code>```

For me, this is just a personal preference. I'm a sloppy programmer and I want to prevent myself from making silly mistakes.

I can surely define main <- function() {}, but I want to know if there is anything similar to this:

```<code>if __name__ == "__main__":
    main()
</code>```

(In this Python script, if the function name is main, then run main() to call the main function.)

答:
but is there anything similar to

```<code>if __name__ == "__main__":
    main()
</code>```

in python?

There is indeed!

But you need to use the package ‘box’ instead of source/packages. Then, inside your module, you can write

```<code>if (is.null(box::name())) …
</code>```

… which is equivalent to Python’s if __name__ == '__main__'.

Or you can even use the klmr/sys module. Then you can write the following:

```<code>box::use(klmr/sys)

f = function(x) {
    x + a
}

sys$run({
    a = 50
    sys$print(f(5))
})
</code>```

If you execute this script on the command line (via Rscript or R CMD BATCH), it will execute the main function specified by sys$run. Conversely, if you import this script as a module into another script, the main function won’t be executed, but f will still be defined and exported.

ContentLicense: CC BY-SA 4.0

Title: Use main function in R

Body:
I've been using R for 4 months now, and I really hope there is a way to use main function as in other languages (C++, Python...)

The main reason I want to do this is that all the variables I use in a R script are global variables that can potentially pollute the namespace of the functions I defined in the same script:

f <- function(x) {
  x + a
}
a <- 50
f(5)

For me, this is just a personal preference. I'm a sloppy programmer and I want to prevent myself from making silly mistakes.

I can surely define main <- function() {}, but I want to know if there is anything similar to this:

if __name__ == "__main__":
    main()

(In this Python script, if the function name is main, then run main() to call the main function.)

Body:
but is there anything similar to

if __name__ == "__main__":
    main()

in python?

There is indeed!

But you need to use the package ‘box’ instead of source/packages. Then, inside your module, you can write

if (is.null(box::name())) …

… which is equivalent to Python’s if __name__ == '__main__'.

Or you can even use the klmr/sys module. Then you can write the following:

box::use(klmr/sys)

f = function(x) {
    x + a
}

sys$run({
    a = 50
    sys$print(f(5))
})

If you execute this script on the command line (via Rscript or R CMD BATCH), it will execute the main function specified by sys$run. Conversely, if you import this script as a module into another script, the main function won’t be executed, but f will still be defined and exported.


问:
How to write to SRAM on STm32 nucleo board (mbed)
I want to store a simple integer in the SRAM on the chip. (Cortex M4)
The program I use is mbed online.
I know that the address for the SRAM starts at 0x2000 0000 and the chip has 4KB of said memory.

I have read the datasheet and the bitbanding part, but it just doesn't make sense to me.

Can someone please explain to me how I can store for example the number 5 in the SRAM and read it again?

Current code is like this(c is an integer that the user changes with a button):

    if(c==100){
    temp=c;
    MBX_B0 = 1;      // Word write
    temp = MBX_B7;   // Word read

    TIMER_B0 = temp; // Byte write
    return TIMER_B7; // Byte read
}
    pc.printf("%d",temp);

It just stops running once c==100
THE VALUE SHOULD BE SAVED EVEN AFTER POWER DOWN.

答:
While reading about bitbanding, I found this code in an Application Note

I copied it out and compiled it.  This should get you started.

```<code>#define BITBAND_SRAM_REF   0x20000000
#define BITBAND_SRAM_BASE  0x22000000
#define BITBAND_SRAM(a,b)  ((BITBAND_SRAM_BASE + (a-BITBAND_SRAM_REF)*32 + (b*4))) // Convert SRAM address
#define BITBAND_PERI_REF   0x40000000
#define BITBAND_PERI_BASE  0x42000000
#define BITBAND_PERI(a,b)  ((BITBAND_PERI_BASE + (a-BITBAND_PERI_REF)*32  + (b*4))) // Convert PERI address
#define MAILBOX            0x20004000
#define TIMER              0x40004000 // Mailbox bit 0
#define MBX_B0             *((volatile unsigned int*)(BITBAND_SRAM(MAILBOX,0))) // Mailbox bit 7
#define MBX_B7             *((volatile unsigned int*)(BITBAND_SRAM(MAILBOX,7))) // Timer bit 0
#define TIMER_B0           *((volatile unsigned char*)(BITBAND_PERI(TIMER,0)))  // Timer bit 7
#define TIMER_B7           *((volatile unsigned char*)(BITBAND_PERI(TIMER,7)))

int main(void)
{
    unsigned int temp = 0;

    MBX_B0 = 1;      // Word write
    temp = MBX_B7;   // Word read
    TIMER_B0 = temp; // Byte write
    return TIMER_B7; // Byte read
}
</code>```

Can someone please explain to me how I can store for example the number 5 in the SRAM and read it again?

In the sample code above, temp is in RAM.

If you dont care about using bitbanding right now, just declaring a variable int x = 5 stores the number 5 in RAM.

Body:
While reading about bitbanding, I found this code in an Application Note

I copied it out and compiled it.  This should get you started.

#define BITBAND_SRAM_REF   0x20000000
#define BITBAND_SRAM_BASE  0x22000000
#define BITBAND_SRAM(a,b)  ((BITBAND_SRAM_BASE + (a-BITBAND_SRAM_REF)*32 + (b*4))) // Convert SRAM address
#define BITBAND_PERI_REF   0x40000000
#define BITBAND_PERI_BASE  0x42000000
#define BITBAND_PERI(a,b)  ((BITBAND_PERI_BASE + (a-BITBAND_PERI_REF)*32  + (b*4))) // Convert PERI address
#define MAILBOX            0x20004000
#define TIMER              0x40004000 // Mailbox bit 0
#define MBX_B0             *((volatile unsigned int*)(BITBAND_SRAM(MAILBOX,0))) // Mailbox bit 7
#define MBX_B7             *((volatile unsigned int*)(BITBAND_SRAM(MAILBOX,7))) // Timer bit 0
#define TIMER_B0           *((volatile unsigned char*)(BITBAND_PERI(TIMER,0)))  // Timer bit 7
#define TIMER_B7           *((volatile unsigned char*)(BITBAND_PERI(TIMER,7)))

int main(void)
{
    unsigned int temp = 0;

    MBX_B0 = 1;      // Word write
    temp = MBX_B7;   // Word read
    TIMER_B0 = temp; // Byte write
    return TIMER_B7; // Byte read
}

Can someone please explain to me how I can store for example the number 5 in the SRAM and read it again?

In the sample code above, temp is in RAM.

If you dont care about using bitbanding right now, just declaring a variable int x = 5 stores the number 5 in RAM.


问:
How to git reset an old commit for the purposes of branching off another commit
So, midway through a PR I realized this would be a lot easier if I had branched off another commit (let's call this commit A) on a separate branch. In short, my current PR (call this commit B) is dependent on that commit (commit A).

Unfortunately, while working on commit B, I made one commit. Let's call this commit B0. How do I checkout to prior to me commiting commit B0 so that I have non-committed files that I can stash? IN short, I want to stash my changes from commit B0, branch off commit A, and stash pop my changes onto commit A1. How do I do this?

Can I also cherry pick?

答: git reset HEAD~ returns the branch pointer to the last but one commit preserving work tree so your files will appear modified in git status. From that point you can stash them and continue.


问:
DROP TABLE behaviour in Postgres transactions
Say I'm working on an ETL that periodically reads source data from a CSV and replaces a table in Postgres (9.6).

Here is one approach:

```<code>BEGIN
DROP TABLE IF EXISTS table
CREATE TABLE table (...)
COPY table FROM STDIN (FORMAT csv, HEADER true)
CREATE INDEX ON table (...)
COMMIT
</code>```

Here is another:

```<code>BEGIN
CREATE TABLE table_temp (...)
COPY table_temp FROM STDIN (FORMAT csv, HEADER true)
CREATE INDEX ON table_temp (...)
DROP TABLE IF EXISTS table
ALTER TABLE table_temp RENAME TO table
COMMIT
</code>```

Am I correct about the following?

The first transaction will lock the table at the DROP command, so concurrent SELECT queries will block until the transaction is complete.

The second transaction will not block SELECT queries until after the COPY and CREATE INDEX finish.

Both transactions are atomic: in either case, if I issue a ROLLBACK instead of COMMIT, the table will be restored with all original data and indexes.

Also, aside from the name of the index, are there any other functional differences?

答:
Yes, all 3 of your assumptions are correct.

The end result would be the same in case of both transactions but the blocking caused by the first transaction would be longer and depend on the amount of data and the time it takes to create the index. The 2nd transaction would require a very brief lock to rename the objects.

Body:
Say I'm working on an ETL that periodically reads source data from a CSV and replaces a table in Postgres (9.6).

Here is one approach:

BEGIN
DROP TABLE IF EXISTS table
CREATE TABLE table (...)
COPY table FROM STDIN (FORMAT csv, HEADER true)
CREATE INDEX ON table (...)
COMMIT

Here is another:

BEGIN
CREATE TABLE table_temp (...)
COPY table_temp FROM STDIN (FORMAT csv, HEADER true)
CREATE INDEX ON table_temp (...)
DROP TABLE IF EXISTS table
ALTER TABLE table_temp RENAME TO table
COMMIT

Am I correct about the following?

The first transaction will lock the table at the DROP command, so concurrent SELECT queries will block until the transaction is complete.

The second transaction will not block SELECT queries until after the COPY and CREATE INDEX finish.

Both transactions are atomic: in either case, if I issue a ROLLBACK instead of COMMIT, the table will be restored with all original data and indexes.

Also, aside from the name of the index, are there any other functional differences?


问:
Checking if a string of numbers is sorted C# in an if statement
I'm trying to figure out how to write an if statement in C# that basically does this</p>

```<code>string myString = "1234";
if( myString is sorted)
    {
        //Do some stuff
    }
else
    {
       // Do some other stuff
    }
</code>```

答:
You can avoid parsing, sorting and creating new string - zip string with itself shifted by one character, and then just check that characters placed in ascending order:</p>

```<code>var ordered = myString.Zip(myString.Skip(1), (a, b) => a <= b).All(x => x);
</code>```

Body:
I'm trying to figure out how to write an if statement in C# that basically does this

string myString = "1234";
if( myString is sorted)
    {
        //Do some stuff
    }
else
    {
       // Do some other stuff
    }

Body:
You can avoid parsing, sorting and creating new string - zip string with itself shifted by one character, and then just check that characters placed in ascending order:

var ordered = myString.Zip(myString.Skip(1), (a, b) => a <= b).All(x => x);


问:
how to switch broadleaf thymeleaf to angularjs ui
I want to change broadleaf thymeleaf ui to angularjs.

edited

```<code>    <!-- Commented bean -->
<!-- <bean class="org.broadleafcommerce.common.web.BroadleafThymeleafViewResolver">
        <property name="templateEngine" ref="blWebTemplateEngine" />
        <property name="order" value="1" />
        <property name="cache" value="${thymeleaf.view.resolver.cache}" />
        <property name="characterEncoding" value="UTF-8" />
    </bean> -->

Added new viewresolver
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix">
            <value>/WEB-INF/templates/</value>
        </property>
        <property name="order" value="1" />
    </bean>
</code>```

Excluded thymeleaf jar and added all beans
as per http://www.broadleafcommerce.com/docs/core/current/appendix/removing-thymeleaf

getting error while loading the page

No mapping found for HTTP request with URI [/WEB-INF/templates/index.html] in DispatcherServlet with name 'mycompany'

答:
I recommend to build a new angular project instead modifiying existing broadleaf ui. Broadleaf Community Starter project has api module which has rest services already.

I am building an angular site project. I would like to share my way. I checkout broadleaf community starter project. Refactored package names. Configured to work with mysql. After able to run community starter admin,site,api projects with mysql. I created a separate "angular" project(by jhipster) for ui. I added modified broadleaf project as dependency. I extend existing broadleaf api controllers in my ng-site project. Found an html theme. Parse it to angular components. Created angular services and bind to backend restservices. It is working partly.

Here is my ng-site project sources. It is not finished but it can give you an idea.

Body:
I want to change broadleaf thymeleaf ui to angularjs.

edited

Added new viewresolver
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix">
            <value>/WEB-INF/templates/</value>
        </property>
        <property name="order" value="1" />
    </bean>

Excluded thymeleaf jar and added all beans
as per http://www.broadleafcommerce.com/docs/core/current/appendix/removing-thymeleaf

getting error while loading the page

No mapping found for HTTP request with URI [/WEB-INF/templates/index.html] in DispatcherServlet with name 'mycompany'


问:
Set environment variable for current process in spring boot application
I'm working on a spring(with maven) project. I want to customize my spring boot banner. In my banner.txt file, I can access some specified banner variable ref as well as system environment variable like JAVA_HOME.

My banner.txt file

```<code>:: Spring Version :: ${spring-boot.formatted-version}
:: Java Home :: ${JAVA_HOME}
</code>```

I want to show some more info from my current process in my spring boot banner. So I'm trying to find out a way to set some variable to the environment for the current process. So that I can access them from my banner.txt like ${JAVA_HOME}. Any help will be appreciated.

答:
You can implement Banner interface to customize the banner, for example:

```<code>public class CustomBanner implements Banner {
    @Override
    public void printBanner(Environment environment, Class<?> aClass, PrintStream printStream) {
        printStream.println("|==================================|");
        printStream.println("|----------My Demo Module----------|");
        printStream.println("|==================================|");
        printStream.println("|>>> Java Home  : " + environment.getProperty("JAVA_HOME"));
        printStream.println("|>>> Process Id : " + ManagementFactory.getRuntimeMXBean().getName());
    }
}
</code>```

With environment variable you can retrieve any system environment variable as JAVA_HOME. With printStream variable you can customize the output.

And finally you must modify your class boot, for example:

```<code>@SpringBootApplication
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(DemoApplication.class);
        app.setBanner(new CustomBanner());
        app.run(args);
    }
}
</code>```

Output:

```<code>|==================================|
|----------My Demo Module----------|
|==================================|
|>>> Java Home  : /usr/bin/java
|>>> Process Id : 14548@Juans-MacBook-Pro.local
</code>```

Body:
I'm working on a spring(with maven) project. I want to customize my spring boot banner. In my banner.txt file, I can access some specified banner variable ref as well as system environment variable like JAVA_HOME.

My banner.txt file

:: Spring Version :: ${spring-boot.formatted-version}
:: Java Home :: ${JAVA_HOME}

I want to show some more info from my current process in my spring boot banner. So I'm trying to find out a way to set some variable to the environment for the current process. So that I can access them from my banner.txt like ${JAVA_HOME}. Any help will be appreciated.

Body:
You can implement Banner interface to customize the banner, for example:

public class CustomBanner implements Banner {
    @Override
    public void printBanner(Environment environment, Class<?> aClass, PrintStream printStream) {
        printStream.println("|==================================|");
        printStream.println("|----------My Demo Module----------|");
        printStream.println("|==================================|");
        printStream.println("|>>> Java Home  : " + environment.getProperty("JAVA_HOME"));
        printStream.println("|>>> Process Id : " + ManagementFactory.getRuntimeMXBean().getName());
    }
}

With environment variable you can retrieve any system environment variable as JAVA_HOME. With printStream variable you can customize the output.

And finally you must modify your class boot, for example:

@SpringBootApplication
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(DemoApplication.class);
        app.setBanner(new CustomBanner());
        app.run(args);
    }
}

Output:

|==================================|
|----------My Demo Module----------|
|==================================|
|>>> Java Home  : /usr/bin/java
|>>> Process Id : 14548@Juans-MacBook-Pro.local


问:
Why is selfregistration bad?
Assuming self-registration is used to install components as part of a larger installer program, why is self-registration bad? E.g. self-registering vb custom controls or capicom or whatever.  I acknowledge that self-registration is probably not as safe in the case of a dll you wrote yourself, but I'm not discussing those.

The MSDN lists several reasons why self-registration is bad, reproduced here:

 Rollback won't work properly.

OK, this reason makes sense.

 Advertisement will not work as well.

Ignoring the fact that advertisement is only important for certain types of software clients, I don't understand why this is an issue.  Only the main application needs to be advertised, not its components.

Self-registration does not support per-user keys properly.

So what? Giving every user access to "common" components is not a bad thing unless you have a lot of users on the machine, in which case it's still not world-ending.

 Self-registration is more susceptible to coding errors.

I can definitely believe this, except in the case of dlls which were written by Microsoft (they may have errors, but I don't think trusting them is unreasonable).  And in the case of tlbs and ocxs which were generated by software, coding errors seem pretty unlikely.

 Self-registering dlls may link to other dlls.

In the case of dlls generated by programs, it doesn't seem likely that self-registration will fail due to this but adding the registration keys manually would have worked.  I'd rather have my self-registration return an error that I'm missing the dlls.

I'm sure this will draw flames :/

Edit: Crossed out arguments that I think actually matter (based on user responses and my own).

答:
I would add one potential "gotcha" which I have run into (with auto-generated self-registration code for MS COM objects):

Self-registration runs the executable, with all that entails/requires. So, for example, if your component directly or indirectly logs the fact that it was activated (perhaps for security logging if the component is only supposed to be running at very specific points or in very specific contexts, or in coordination with other applications), registration will appear to be an activation (unless you're careful about logging). This can also be interesting if your logs record, say, the context in which the component was utilized, in which case you will have whatever inherited context triggered the self-registration.

Not a big deal in most cases, but it can cause some subtle confusion sometimes. I'd add it to the list of reasons why it's probably not preferable.

OwnerDisplayName: Brian

ContentLicense: CC BY-SA 2.5

Title: Why is selfregistration bad?

LastEditorDisplayName: Brian

OwnerDisplayName: Nick


问:
Significance of parameter names in oracle trace files
I am comparing results of two different JDBC drivers of oracle with the help of oracle's SQL tracing capabilities. I am using TKProf to format the results.

When I look at the output of TKProf sometimes I see parameters named prefixed with 'v':

```<code>WHERE start_time BETWEEN  :v0  AND  :v1
</code>```

At other instances the parameters are not prefixed:

```<code>WHERE start_time BETWEEN :1 AND :2
</code>```

I suspect that in second case, query optimizer is not picking some indices.

Is there a hint in the naming convention of parameters?

答:
I'm certainly not an expert in how the JDBC drivers talk to the database. With luck, someone else will provide that detail.

I believe, though, that the parameter names shouldn't mean anything. That should just be what the particular driver decides to call them when it's sending the query to the database. But if you can peek at the actual values of the bind variables, that might tell you something. My concern would be that one driver is setting it up so the values have to go through a cast on the way to running the query, which could affect index use.

Body:
I am comparing results of two different JDBC drivers of oracle with the help of oracle's SQL tracing capabilities. I am using TKProf to format the results.

When I look at the output of TKProf sometimes I see parameters named prefixed with 'v':

WHERE start_time BETWEEN  :v0  AND  :v1

At other instances the parameters are not prefixed:

WHERE start_time BETWEEN :1 AND :2

I suspect that in second case, query optimizer is not picking some indices.

Is there a hint in the naming convention of parameters?


问:
Count the number of likert scale results from multiple column questions in pandas
I have the following dataframe:

```<code>       Question1        Question2         Question3          Question4
User1  Agree            Agree          Disagree         Strongly Disagree
User2  Disagree         Agree          Agree            Disagree
User3  Agree            Agree          Agree            Agree
</code>```

Is there a way to convert the dataframe listed above to the following?

```<code>              Agree         Disagree         Strongly Disagree
 Question1    2               1                  0

 Question2    2               1                  0

 Question3    2               1                  0
 Question4    1               1                  1
</code>```

This is similar to my previous question: Make a dataframe with grouped questions from three columns

I tried looking at previous questions with stack/pivot but could not figure it out.  The actual dataframe has 20+ questions and a likert scale from strongly agree, agree, neutral, disagree, strongly disagree.

答:
You can iterate over columns with pd.Series.value_counts. If you do this with apply, indices will be aligned automatically:

```<code>df.apply(pd.Series.value_counts)
Out:
                   Question1  Question2  Question3  Question4
Agree                    2.0        3.0        2.0          1
Disagree                 1.0        NaN        1.0          1
Strongly Disagree        NaN        NaN        NaN          1
</code>```

A little postprocessing:

```<code>df.apply(pd.Series.value_counts).fillna(0).astype('int')
Out:
                   Question1  Question2  Question3  Question4
Agree                      2          3          2          1
Disagree                   1          0          1          1
Strongly Disagree          0          0          0          1
</code>```

Body:
I have the following dataframe:

       Question1        Question2         Question3          Question4
User1  Agree            Agree          Disagree         Strongly Disagree
User2  Disagree         Agree          Agree            Disagree
User3  Agree            Agree          Agree            Agree

Is there a way to convert the dataframe listed above to the following?

              Agree         Disagree         Strongly Disagree
 Question1    2               1                  0

 Question2    2               1                  0

 Question3    2               1                  0
 Question4    1               1                  1

This is similar to my previous question: Make a dataframe with grouped questions from three columns

I tried looking at previous questions with stack/pivot but could not figure it out.  The actual dataframe has 20+ questions and a likert scale from strongly agree, agree, neutral, disagree, strongly disagree.

Body:
You can iterate over columns with pd.Series.value_counts. If you do this with apply, indices will be aligned automatically:

df.apply(pd.Series.value_counts)
Out:
                   Question1  Question2  Question3  Question4
Agree                    2.0        3.0        2.0          1
Disagree                 1.0        NaN        1.0          1
Strongly Disagree        NaN        NaN        NaN          1

A little postprocessing:

df.apply(pd.Series.value_counts).fillna(0).astype('int')
Out:
                   Question1  Question2  Question3  Question4
Agree                      2          3          2          1
Disagree                   1          0          1          1
Strongly Disagree          0          0          0          1


问:
bootstrap sidebar no bg color
Hey i have tried a lot to give the background color of my sidebar from my bootstrap a color but it doesnt work.

here is my code from the page

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <title>ToolsForEver</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1""> <!-- een viewport is de userscreen  dus we gebruiken 100% normale zoom -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
    <link rel="stylesheet" type="text/css" href="../style.css">
</head>

<body>
<nav class="navbar navbar-inverse navbar-fixed-top">
  <div class="container-fluid">
    <!-- Dit is voor de logo en dat de je een kleine soort dropdown ziet waarmee je op kleinere toestellen ook beter kan besturen -->
    <div class="navbar-header">
      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
      <a class="navbar-brand" href="../afbeeldingen/tools.png">ToolsForEver</a>
    </div>

    <!-- Collect the nav links, forms, and other content for toggling -->
    <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
      <ul class="nav navbar-nav">
        <li class="active"><a href="#">contact <span class="sr-only">(current)</span></a></li>
        <li><a href="#">Link</a></li>
      </ul>
      <ul class="nav navbar-nav navbar-right">
        <li>    <a href="uitloggen.php" class="btn btn-info" role="button">Uitloggen</a></li>
      </ul>
    </div><!-- /.navbar-collapse -->
  </div><!-- /.container-fluid -->

</nav>
            <!-- Sidebar -->
        <div id="sidebar">
            <ul class="sidebar-nav">
                <li>
                    <a href="#">Beheer Voorraad</a>
                </li>
                <li>
                    <a href="#">Beheer Medewerkers</a>
                </li>
                <li>
                    <a href="#">Beheer Locaties</a>
                </li>
                <li>
                    <a href="#">Beheer Voorraad</a>
                </li>
                <li>
                    <a href="#">Beheer Voorraad</a>
                </li>
            </ul>
        </div>

<div class = "container">
    <div class = "jumbotron">
        <img src="../afbeeldingen/toolsforever.jpg" alt="ToolsForever" class="img-responsive">
    </div>
</body>
</html>

<?php session_start();
//als session leeg is dan doe je dit
if(empty($_SESSION['email']))
{
    header("location:../index.php");
}

    include 'footer.php';
?>
</code>```

Here is my code of my css file

```<code>body {
    padding-top: 65px;
    padding-left: 135px;
}

.container{
    padding-top: 65px;
    padding-left: 135px;
}

#sidebar{
    position: fixed;
    left: 250px;
    width: 0;
    height: 100%;
    margin-left: -250px;
    color: blue;
}

.sidebar-nav {
    position: absolute;
    top: 0;
    width: 250px;
    margin: 0;
    padding: 0;
    list-style: none;
}

.sidebar-nav li {
    text-indent: 20px;
    line-height: 40px
}

.sidebar-nav li a {
    display: block;
    text-decoration: none;
    color: black;
}
</code>```

Can you guys please help me ;)

thank you!

答:
You could use this code, but since the element is fixed you must give it a constant width property and so the responsiveness would probably be destroyed. Although you could use media queries to set when this element is visible. Underneath you have a fiddle.

```<code>#sidebar{
    position: fixed;
    left: 250px;
    width: 200px;
    min-height: 100vh;
    background-color:red;
    margin-left: -250px;
    color: blue;
}
</code>```

To eliminate the blank white space between navbar and top navbar remove top body padding

```<code>body {
    padding-left: 135px;
}
</code>```

Updated the fiddle too :)

https://jsfiddle.net/wje3t8f0/3/

Title: bootstrap sidebar no bg color

Body:
Hey i have tried a lot to give the background color of my sidebar from my bootstrap a color but it doesnt work.

here is my code from the page

<!DOCTYPE html>

    <title>ToolsForEver</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1"">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

    <link rel="stylesheet" type="text/css" href="../style.css">

      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
        Toggle navigation

      </button>
      ToolsForEver

contact (current)

Link

    Uitloggen

                    Beheer Voorraad

                    Beheer Medewerkers

                    Beheer Locaties

                    Beheer Voorraad

                    Beheer Voorraad

<?php session_start();
//als session leeg is dan doe je dit
if(empty($_SESSION['email']))
{
    header("location:../index.php");
}

    include 'footer.php';
?>

Here is my code of my css file

body {
    padding-top: 65px;
    padding-left: 135px;
}

.container{
    padding-top: 65px;
    padding-left: 135px;
}

#sidebar{
    position: fixed;
    left: 250px;
    width: 0;
    height: 100%;
    margin-left: -250px;
    color: blue;
}

.sidebar-nav {
    position: absolute;
    top: 0;
    width: 250px;
    margin: 0;
    padding: 0;
    list-style: none;
}

.sidebar-nav li {
    text-indent: 20px;
    line-height: 40px
}

.sidebar-nav li a {
    display: block;
    text-decoration: none;
    color: black;
}

Can you guys please help me ;)

thank you!

Body:
You could use this code, but since the element is fixed you must give it a constant width property and so the responsiveness would probably be destroyed. Although you could use media queries to set when this element is visible. Underneath you have a fiddle.

#sidebar{
    position: fixed;
    left: 250px;
    width: 200px;
    min-height: 100vh;
    background-color:red;
    margin-left: -250px;
    color: blue;
}

To eliminate the blank white space between navbar and top navbar remove top body padding

body {
    padding-left: 135px;
}

Updated the fiddle too :)

https://jsfiddle.net/wje3t8f0/3/


问:
How to find the type of an object in a set?
How do I find the type of an object that is in a set with using one line code?</p>

```<code>setup = {(1,2),(3,4),(5,6)}

>>> type(setup.____)

<class 'int'>
</code>```

答:
If you want to get the type of each element in the tuple you can use list comprehension like:

```<code>[type(x) for elem in setup for x in elem]
</code>```

output:

```<code>[<type 'int'>, <type 'int'>, <type 'int'>, <type 'int'>, <type 'int'>, <type 'int'>]
</code>```

or if you want to group them you can use:

```<code>[[type(x) for x in elem] for elem in setup]
</code>```

to get the following output:

```<code>[[<type 'int'>, <type 'int'>], [<type 'int'>, <type 'int'>], [<type 'int'>, <type 'int'>]]
</code>```

Body:
How do I find the type of an object that is in a set with using one line code?

setup = {(1,2),(3,4),(5,6)}

>>> type(setup.____)

<class 'int'>

Body:
If you want to get the type of each element in the tuple you can use list comprehension like:

[type(x) for elem in setup for x in elem]

output:

[<type 'int'>, <type 'int'>, <type 'int'>, <type 'int'>, <type 'int'>, <type 'int'>]

or if you want to group them you can use:

[[type(x) for x in elem] for elem in setup]

to get the following output:

[[<type 'int'>, <type 'int'>], [<type 'int'>, <type 'int'>], [<type 'int'>, <type 'int'>]]


问:
Boolean flag to show or ignore PowerShell GUI
I have a PowerShell script with a WPF GUI that allows the users to enter values and choose from drop-down lists. It works great, but some users want to bypass it and run the script manually (enter their own values directly into the script).

Right now the structure is:

```<code>#A bunch of XML and PowerShell that generates the GUI

$WPFbutton.Add_Click({

#Variables that get populated by the GUI

#The rest of the script

})
</code>```

I want to add something like:

$UseGUI = $true

at the top of the script that they can change to false, which will cause the script to ignore the XML and button click line.

I was thinking I could surround the XML stuff in an if statement based on $UseGUI but that doesn't help with the button click part.

One thing I know would work is copy and pasting the entire script to another if statement based on $UseGUI. The issue there is it would double the script size, and it's already 2000 lines.

答:
One idea would be to use a function and parameters to identify if the person using the script wants to use the GUI or has supplied the correct information by themselves:

```<code>param
(
    [Parameter(ParameterSetName = 'Interface',
               Mandatory = $true,
               Position = 0)]
    [switch]
    $UseGUI,

    [Parameter(ParameterSetName = 'CommandLine',
               Mandatory = $true,
               Position = 0)]
    [ValidateNotNullOrEmpty()]
    [string]
    $Person
)

function SayHelloTo ($User)
{
    Write-Output "Hello $User"
}

if ($UseGUI)
{
    #A bunch of XML and PowerShell that generates the GUI

    $WPFbutton.Add_Click({

        #Variables that get populated by the GUI

        #The rest of the script

        $variable = "jdope"

        SayHello -User $variable

    })
}
else
{
    SayHello -User $Person
}
</code>```

The parameter sets will prevent the script from being called with both options so when you check if UseGUI is $True you will know to show the GUI (and get the input to call the function) or call the function with the input.

To use the GUI call the script with -UseGUI

```<code>.\MyPowerShellWpfScript -UseGUI
</code>```

To supply the Person information and bypass the GUI use

```<code>.\MyPowerShellWpfScript -Person "jdope"
</code>```

Body:
I have a PowerShell script with a WPF GUI that allows the users to enter values and choose from drop-down lists. It works great, but some users want to bypass it and run the script manually (enter their own values directly into the script).

Right now the structure is:

#A bunch of XML and PowerShell that generates the GUI

$WPFbutton.Add_Click({

#Variables that get populated by the GUI

#The rest of the script

})

I want to add something like:

$UseGUI = $true

at the top of the script that they can change to false, which will cause the script to ignore the XML and button click line.

I was thinking I could surround the XML stuff in an if statement based on $UseGUI but that doesn't help with the button click part.

One thing I know would work is copy and pasting the entire script to another if statement based on $UseGUI. The issue there is it would double the script size, and it's already 2000 lines.

Body:
One idea would be to use a function and parameters to identify if the person using the script wants to use the GUI or has supplied the correct information by themselves:

param
(
    [Parameter(ParameterSetName = 'Interface',
               Mandatory = $true,
               Position = 0)]
    [switch]
    $UseGUI,

    [Parameter(ParameterSetName = 'CommandLine',
               Mandatory = $true,
               Position = 0)]
    [ValidateNotNullOrEmpty()]
    [string]
    $Person
)

function SayHelloTo ($User)
{
    Write-Output "Hello $User"
}

if ($UseGUI)
{
    #A bunch of XML and PowerShell that generates the GUI

    $WPFbutton.Add_Click({

        #Variables that get populated by the GUI

        #The rest of the script

        $variable = "jdope"

        SayHello -User $variable

    })
}
else
{
    SayHello -User $Person
}

The parameter sets will prevent the script from being called with both options so when you check if UseGUI is $True you will know to show the GUI (and get the input to call the function) or call the function with the input.

To use the GUI call the script with -UseGUI

.\MyPowerShellWpfScript -UseGUI

To supply the Person information and bypass the GUI use

.\MyPowerShellWpfScript -Person "jdope"


问:
Is there an out of the box way to parse a list of 2-tuples with json4s?
Given:

```<code>implicit val formats = DefaultFormats

val json =
  """[
      {"myType":"type1","things":["1","2","3","4","5","6"]},
      {"myType":"type1","things":["1","2","3","4","5","6"]}
    ]"""

case class Stuff(myType: String, things: List[String])
parse(json).extract[List[Stuff]]
</code>```

Scala produces this error at runtime:

```<code>An exception or error caused a run to abort: Temp and Temp$$anonfun$1$Stuff$3 disagree on InnerClasses attribute
java.lang.IncompatibleClassChangeError: Temp and Temp$$anonfun$1$Stuff$3 disagree on InnerClasses attribute
</code>```

Is there an out-of-the-box way to parse this with json4s, or is this a case for a custom serializer?

json4s version is 3.5.2

scala version is older due to a system limitation, 2.10.4

答:
Do you have an implicit Formats object in scope?

The extract method needs an implicit format parameter. Json4s provides default formatting for things like Lists.

The following code works for me

```<code>import org.json4s.DefaultFormats
import org.json4s.native.JsonMethods.parse

implicit val formats = DefaultFormats

val json =
  """[
      {"myType":"type1","things":["1","2","3","4","5","6"]},
      {"myType":"type1","things":["1","2","3","4","5","6"]}
  ]"""

case class Stuff(myType: String, things: List[String])
parse(json).extract[List[Stuff]]

res0: List[Stuff] = List(Stuff(type1,List(1, 2, 3, 4, 5, 6)), Stuff(type1,List(1, 2, 3, 4, 5, 6)))
</code>```

json4s version 3.2.11

scala version 2.11

If you do have a implicit formatter in scope it may be a bug in json4s Reflector. Declaring your Stuff case class in a different place may fix the issue. See this github issue for details  https://github.com/json4s/json4s/issues/84

Body:
Given:

implicit val formats = DefaultFormats

val json =
  """[
      {"myType":"type1","things":["1","2","3","4","5","6"]},
      {"myType":"type1","things":["1","2","3","4","5","6"]}
    ]"""

case class Stuff(myType: String, things: List[String])
parse(json).extract[List[Stuff]]

Scala produces this error at runtime:

An exception or error caused a run to abort: Temp and Temp$$anonfun$1$Stuff$3 disagree on InnerClasses attribute
java.lang.IncompatibleClassChangeError: Temp and Temp$$anonfun$1$Stuff$3 disagree on InnerClasses attribute

Is there an out-of-the-box way to parse this with json4s, or is this a case for a custom serializer?

json4s version is 3.5.2

scala version is older due to a system limitation, 2.10.4

Body:
Do you have an implicit Formats object in scope?

The extract method needs an implicit format parameter. Json4s provides default formatting for things like Lists.

The following code works for me

import org.json4s.DefaultFormats
import org.json4s.native.JsonMethods.parse

implicit val formats = DefaultFormats

val json =
  """[
      {"myType":"type1","things":["1","2","3","4","5","6"]},
      {"myType":"type1","things":["1","2","3","4","5","6"]}
  ]"""

case class Stuff(myType: String, things: List[String])
parse(json).extract[List[Stuff]]

res0: List[Stuff] = List(Stuff(type1,List(1, 2, 3, 4, 5, 6)), Stuff(type1,List(1, 2, 3, 4, 5, 6)))

json4s version 3.2.11

scala version 2.11

If you do have a implicit formatter in scope it may be a bug in json4s Reflector. Declaring your Stuff case class in a different place may fix the issue. See this github issue for details  https://github.com/json4s/json4s/issues/84


问:
sql parse full name field into first, middle, last, and suffix
I'm trying to split full names into last, first, middle, and suffix.  I searched but couldn't find the exact the same format as mine.  I have the following code, but I'm getting this error when running the full select.

```<code>Msg 537, Level 16, State 3, Line 1
Invalid length parameter passed to the LEFT or SUBSTRING function.
</code>```

SpaceComma table gets the correct indexes.
This is the format of the names I have:

```<code>    CREATE TABLE #myfullnames (fullName VARCHAR(50))
    GO

    INSERT #myfullnames VALUES ('BROOK SR, JAMES P.')
    INSERT #myfullnames VALUES ('BLOCK JR., BILL V.')
    INSERT #myfullnames VALUES ('MOOR, CLODE M.')
    INSERT #myfullnames VALUES ('SOUDER III, Laurence R.')
    INSERT #myfullnames VALUES ('SOUDER, WILL' )
    INSERT #myfullnames VALUES ('KOLIV, Kevin E.')
    INSERT #myfullnames VALUES ('Simk, JR. Thomas Todd')
    INSERT #myfullnames VALUES ('Polio, Gary R.')
</code>```

I would appreciate your help. Thanks.

```<code> select SplitNames.LastName, SplitNames.FirstName,
        SplitNames.MiddleName, SplitNames.Title
 from (
    select [fullName]
, substring([fullName], 1, SpceTitle-1) as LastName
, substring([fullName], SpceMid,(SpceMid - SpceFirstName - 1)) as FirstName
, substring([fullName], SpaceComma.SpceTitle, (SpaceComma.SpceFirstName -
    SpaceComma.SpceTitle)) as Title
, nullif(substring([fullName],SpaceComma.SpceMid+1,100),'') as
    MiddleName
from (
    select [fullName],
    charindex(',',[fullName]) as Comma,
    charindex(' ',[fullName]+space(1),charindex(',',[fullName])) as
            SpceFirstName,
    (len([fullName]) + 1 - charindex(' ',reverse([fullName]), 0)) as
            SpceMid,
    charindex(' ',[fullName], charindex (' ',reverse([fullName]))) as SpceTitle
    from #myfullnames
     ) SpaceComma
 ) SplitNames

 DROP TABLE #myfullnames
</code>```

答:
The data in your example does not follow any fixed set of rules so there will not be a perfect solution for parsing the names.  An example of the rule violation is  between "Simk" and "BLOCK" in that the "JR" is inside the comma on one and not the other.  The only solution to the rule violation is to manually correct the violators.

We can parse the name using the "PARSENAME" function in SQL Server.  SQL Server uses PARSENAME to seperate the SERVERNAME.DATABASE.SCHEMA.TABLE and is limited to four parts.

Here is a query which parses the names

```<code>select fullname
 , REPLACE(fullname,'.','') AS [1]
 , REPLACE(REPLACE(fullname,'.',''),', ','.') AS [2]
 , ParseName(REPLACE(REPLACE(fullname,'.',''),', ','.'),2) AS [3]
 , REPLACE(ParseName(REPLACE(REPLACE(fullname,'.',''),', ','.'),1),' ','.') AS [4]
 , PARSENAME(REPLACE(ParseName(REPLACE(REPLACE(fullname,'.',''),', ','.'),1),' ','.'),1) AS [5]
 , PARSENAME(REPLACE(ParseName(REPLACE(REPLACE(fullname,'.',''),', ','.'),1),' ','.'),2) AS [6]
 from #myfullnames
</code>```

The six output columns demonstrate the use of replacing characters with the "." then using PARSENAME to extract a portion of the string.

Body:
I'm trying to split full names into last, first, middle, and suffix.  I searched but couldn't find the exact the same format as mine.  I have the following code, but I'm getting this error when running the full select.

Msg 537, Level 16, State 3, Line 1
Invalid length parameter passed to the LEFT or SUBSTRING function.

SpaceComma table gets the correct indexes.
This is the format of the names I have:

    CREATE TABLE #myfullnames (fullName VARCHAR(50))
    GO

    INSERT #myfullnames VALUES ('BROOK SR, JAMES P.')
    INSERT #myfullnames VALUES ('BLOCK JR., BILL V.')
    INSERT #myfullnames VALUES ('MOOR, CLODE M.')
    INSERT #myfullnames VALUES ('SOUDER III, Laurence R.')
    INSERT #myfullnames VALUES ('SOUDER, WILL' )
    INSERT #myfullnames VALUES ('KOLIV, Kevin E.')
    INSERT #myfullnames VALUES ('Simk, JR. Thomas Todd')
    INSERT #myfullnames VALUES ('Polio, Gary R.')

I would appreciate your help. Thanks.

 select SplitNames.LastName, SplitNames.FirstName,
        SplitNames.MiddleName, SplitNames.Title
 from (
    select [fullName]
, substring([fullName], 1, SpceTitle-1) as LastName
, substring([fullName], SpceMid,(SpceMid - SpceFirstName - 1)) as FirstName
, substring([fullName], SpaceComma.SpceTitle, (SpaceComma.SpceFirstName -
    SpaceComma.SpceTitle)) as Title
, nullif(substring([fullName],SpaceComma.SpceMid+1,100),'') as
    MiddleName
from (
    select [fullName],
    charindex(',',[fullName]) as Comma,
    charindex(' ',[fullName]+space(1),charindex(',',[fullName])) as
            SpceFirstName,
    (len([fullName]) + 1 - charindex(' ',reverse([fullName]), 0)) as
            SpceMid,
    charindex(' ',[fullName], charindex (' ',reverse([fullName]))) as SpceTitle
    from #myfullnames
     ) SpaceComma
 ) SplitNames

 DROP TABLE #myfullnames

Body:
The data in your example does not follow any fixed set of rules so there will not be a perfect solution for parsing the names.  An example of the rule violation is  between "Simk" and "BLOCK" in that the "JR" is inside the comma on one and not the other.  The only solution to the rule violation is to manually correct the violators.

We can parse the name using the "PARSENAME" function in SQL Server.  SQL Server uses PARSENAME to seperate the SERVERNAME.DATABASE.SCHEMA.TABLE and is limited to four parts.

Here is a query which parses the names

select fullname
 , REPLACE(fullname,'.','') AS [1]
 , REPLACE(REPLACE(fullname,'.',''),', ','.') AS [2]
 , ParseName(REPLACE(REPLACE(fullname,'.',''),', ','.'),2) AS [3]
 , REPLACE(ParseName(REPLACE(REPLACE(fullname,'.',''),', ','.'),1),' ','.') AS [4]
 , PARSENAME(REPLACE(ParseName(REPLACE(REPLACE(fullname,'.',''),', ','.'),1),' ','.'),1) AS [5]
 , PARSENAME(REPLACE(ParseName(REPLACE(REPLACE(fullname,'.',''),', ','.'),1),' ','.'),2) AS [6]
 from #myfullnames

The six output columns demonstrate the use of replacing characters with the "." then using PARSENAME to extract a portion of the string.


问:
ImportError: No module named 'Cython'
I'm trying do from Cython.Build import cythonize and I get the message ImportError: No module named 'Cython', but I installed the Cython with the comand pip install Cython. What's wrong?

Python 3.5
Cython 0.25.2
Windows 8

答: I reinstalled the Cython with conda and install the Microsoft Visual C++ Build Tools and it works fine.</p>

Title: ImportError: No module named 'Cython'


问:
Share image resources between app and today widget
Can I share resources (images that are compiled into the application) between my main iOS app and my today extension widget?  Say I create a new application.  Then add a today extension project to the solution.  And then I create a UIImageView.  I want to reference an image from a shared pool of images rather than having 2 of every image, one added to main app and another added to widget app.  </p>

```<code>imageView.Image = UIImage.FromBundle("IMG_3799.JPG");
</code>```

<p>The IMG_3799.JPG is inside the main application in the References folder of that project.  I'd prefer the same image asset to be referenced by the widget.  Is that possible?  Currently, i'm making a 2nd copy of IMG_3799.JPG and putting it into the widget. </p>

答:
Out of box, you can't.

The closest thing to that would be to create an app group that contains the main app and the extension and that has access to the common folder. However you can't place any file there during deployment, just during runtime, so it may or may not be a workaround for what you require, but that is the only way.

Body:
Can I share resources (images that are compiled into the application) between my main iOS app and my today extension widget?  Say I create a new application.  Then add a today extension project to the solution.  And then I create a UIImageView.  I want to reference an image from a shared pool of images rather than having 2 of every image, one added to main app and another added to widget app.

imageView.Image = UIImage.FromBundle("IMG_3799.JPG");

The IMG_3799.JPG is inside the main application in the References folder of that project.  I'd prefer the same image asset to be referenced by the widget.  Is that possible?  Currently, i'm making a 2nd copy of IMG_3799.JPG and putting it into the widget.