问:
int vs IntPtr when you have a handle?
First a background question:

In general, what is the difference between int and IntPtr?  My guess is that it is an actual object rather than a value like an int or byte is.  Assuming that is true:

So they are not the same.  Yet I see handles represented as both.

IntPtr: Control.Handle

int (or uint):  A PInvoke can be setup to return an int and it works just fine:

```<code>[DllImport("coredll.dll", SetLastError = true)]
public static extern int GetForegroundWindow();
private string GetActiveWindow()
{
    const int nChars = 256;
    int handle = 0;
    StringBuilder Buff = new StringBuilder(nChars);

    handle = CoreDLL.GetForegroundWindow();

    if (CoreDLL.GetWindowText(handle, Buff, nChars) > 0)
    {
        return Buff.ToString();
    }

    return "";
}
</code>```

So, int vs IntPtr? Does it matter for handles?  Can you use either?

答:
int is 32 bits long. IntPtr is as long as a pointer for your architecture. Therefore, a pointer can be stored into an int only on 32 bit systems, while it can always be stored in an IntPtr.

Notice that your "int as a return value" example does not use an int to hold a pointer, but just to hold a numeric value. This does not mean that an int is automatically the correct size though: the author of that P/Invoke signature should have gone to the documentation for GetForegroundWindow and see that it returns a HWND.

Then, from windef.h in the Platform SDK (or this MSDN page) we can see that a HWND is a HANDLE which is a PVOID which is... a pointer!

Therefore, as far as I can tell, that signature is wrong, as the size of the return value of GetForegroundWindow depends on the architecture. Thus, it should also be an IntPtr.

Update:

While it can be inferred from the above, I think it's worthwhile to explicitly point out that:

Erroneously using int instead of IntPtr in 32-bit applications will never cause a problem, even if they run on 64-bit Windows; since most applications are 32-bit at this point in time, this will let you get away such mistakes very often.

Erroneously using int instead of IntPtr in 64-bit applications is not guaranteed to cause problems, since it is quite possible that in practice the values being encountered will fit in the 32 bits of the int. This further lessens the probability that a mistake will manifest as an application error.

Therefore, for an error to actually manifest there are three conditions that have to be satisfied at the same time:

An int is used where an IntPtr should be.

The executable image is 64-bit.

A value returned by some PInvoke call and stored as an int is actually larger than 32 bits.

Title: int vs IntPtr when you have a handle?

Body:
First a background question:

In general, what is the difference between int and IntPtr?  My guess is that it is an actual object rather than a value like an int or byte is.  Assuming that is true:

So they are not the same.  Yet I see handles represented as both.

IntPtr: Control.Handle

int (or uint):  A PInvoke can be setup to return an int and it works just fine:

[DllImport("coredll.dll", SetLastError = true)]
public static extern int GetForegroundWindow();
private string GetActiveWindow()
{
    const int nChars = 256;
    int handle = 0;
    StringBuilder Buff = new StringBuilder(nChars);

    handle = CoreDLL.GetForegroundWindow();

    if (CoreDLL.GetWindowText(handle, Buff, nChars) > 0)
    {
        return Buff.ToString();
    }

    return "";
}

So, int vs IntPtr? Does it matter for handles?  Can you use either?


来源: stackexchange

问:
Multiplying an option value by a fixed value
Using Excel 2010 I have a form that contains five option buttons in each of nine rows.  Each column, in which an option button can be selected, has a numeric value ranging from 5 -1.  Each row begins with a statement which also has a numeric value, which ranges from 10-1.  When an option button is selected, the value of that column is to be multiplied by the value of the row and the result entered in another column on the form.

Suggestions?

Thank you in advance.
JB

答:
Since you want to multiple Row number with a cell value, so for this I think no need to create Optionbutton,, simply you can multiple Row number with cell value,, like </p>

<p>C3=Row(A3) *B3, Drag it down. </p>

ContentLicense: CC BY-SA 3.0

Body:
Since you want to multiple Row number with a cell value, so for this I think no need to create Optionbutton,, simply you can multiple Row number with cell value,, like

C3=Row(A3) *B3, Drag it down.


问:
Google maps API error
I'm trying to generate and API javascript key for google maps to put in my project, i generated they key but it gives me the follwing error: InvalidKeyMapError
Here is my script code:</p>

```<code><script src="http://maps.googleapis.com/maps/api/js?key=AIzaSyBgeepqF19Lq0I2jhEWj88uafs55jmnFso;sensor=false"></script>
</code>```

答:
Try this

updated

```<code><script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBgeepqF19Lq0I2jhEWj88uafs55jmnFso&libraries=places&callback=initAutocomplete" async defer></script>
</code>```

where initAutocomplete would be your google map initialization method.

Title: Google maps API error

Body:
Try this

updated

<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBgeepqF19Lq0I2jhEWj88uafs55jmnFso&libraries=places&callback=initAutocomplete" async defer></script>

where initAutocomplete would be your google map initialization method.


问:
How can I install NumPy on Windows using 'pip install'?
I want to install NumPy using the pip install numpy command, but I get the following error:

RuntimeError: Broken toolchain: cannot link a simple C program
```

I'm using Windows 7 32 bit, Python 2.7.9, pip 6.1.1 and some MSVC compiler. I think it uses the compiler from Visual C++ 2010 Express, but actually I'm not sure which one, because I have several Visual Studio installations.

I know that there are prebuilt packages for Windows, but is there some way to do it just by typing pip install numpy?

I think that there could be other packages which must be compiled before usage, so it's not only about NumPy. I want to solve the problem with my compiler, so I could easily install any other similar package without necessity to search for prebuilt packages (and hope that there are some at all).

答:
First go through page Download Python to download Python 3.6.1 or 2.7.13 either of your choice. I preferred to use Python 2.7 or 3.4.4.

Now after installation, go to the folder name python27 or python34, and click on the script. Now here open the command prompt by left clicking and Run as administrator.

After the command prompt appears, write "pip install numpy" there. This will install the latest version of NumPy and installing it will show a success comment. That's all.

Similarly, Matplotlib can be installed by just typing "pip install matplotlip". And now if you want to download SciPy, then just write "pip install scipy" and if it doesn't work then you need to download Python SciPy from SciPy: Scientific Library for Python and install it.

ContentLicense: CC BY-SA 4.0

Body:
I want to install NumPy using the pip install numpy command, but I get the following error:

RuntimeError: Broken toolchain: cannot link a simple C program

I'm using Windows 7 32 bit, Python 2.7.9, pip 6.1.1 and some MSVC compiler. I think it uses the compiler from Visual C++ 2010 Express, but actually I'm not sure which one, because I have several Visual Studio installations.

I know that there are prebuilt packages for Windows, but is there some way to do it just by typing pip install numpy?

I think that there could be other packages which must be compiled before usage, so it's not only about NumPy. I want to solve the problem with my compiler, so I could easily install any other similar package without necessity to search for prebuilt packages (and hope that there are some at all).


问:
Programmatic Constraint issues in Swift Playgrounds Program
wondering how to update constraints for a custom UI View. Definitely are errors in my code. I apologize in advance, I'm just a beginner at Swift.

```<code>public class NoteCardView:UIView {
@IBInspectable var contentView = UIButton(frame: .zero)
@IBInspectable var delegate: MainViewController?
var leftAnchor: NSLayoutXAxisAnchor
var bottomAnchor: NSLayoutYAxisAnchor

override public func updateConstraints() {

    contentView.translatesAutoresizingMaskIntoConstraints = false

    contentView.layer.masksToBounds = true
    contentView.layer.cornerRadius = 6
    contentView.widthAnchor.constraint(equalToConstant: 75).isActive = true
    contentView.heightAnchor.constraint(equalToConstant: 100).isActive = true
    leftAnchor = contentView.leftAnchor.constraint(equalTo: contentView.leftAnchor, constant: positionX).isActive = true
    bottomAnchor = contentView.bottomAnchor.constraint(equalTo: (delegate?.view.bottomAnchor)!, constant: positionY).isActive = true
    titleLabel.textAlignment = .center
    titleLabel.text = note
    contentView.addSubview(titleLabel)

    super.updateConstraints()
}

class MainViewController: UIViewController {
override func viewDidLoad() {
// Trying to implement updated constraints to the NoteCardView here.
}
}
</code>```

Also having this other issue that is unrelated with the TapGestureRecognizer. I'm not very familiar with this concept either.

```<code>public class NoteCard:UIView {
internal var titleLabelTapGestureRecognizer: UITapGestureRecognizer?

internal func commonInit() {
self.titleLabelTapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(handleTitleLabelTap(UITapGestureRecognizer)))
}

internal func handleTitleLabelTap(_ recognizer:UITapGestureRecognizer) {
    self.delegate?.noteCardViewTitleLabelDidRecieveTap(self)
}
}
</code>```

Thank you in advance for your help!

答:
There are a couple of issues in your code :

What Rob mentioned in his comment :
contentView.leftAnchor.constraint(equalTo: contentView.leftAnchor,
constant: positionX) - this doesn't make sense, as constraints
should be between anchors of two different views. Also constraints should be configured after adding views to hierarchy.

Also with the same line : leftAnchor = contentView.leftAnchor.constraint(equalTo: contentView.leftAnchor,
constant: positionX).isActive = true. This line has actually two
problems :

2a. This compound assignment evaluates to this :

```<code>contentView.leftAnchor.constraint(equalTo: contentView.leftAnchor, constant: positionX).isActive = true
leftAnchor = true
</code>```

Which means, that you try to assign true to a variable of type NSLayoutXAxisAnchor. Same applies to bottomAnchor

2b. As to the type of leftAnchor - it should be NSLayoutConstraint, because calling constraint on an anchor creates a NSLayoutConstraint. If you wanted to grab a reference to an anchor, you would simply call leftAnchor = contentView.leftAnchor.

You setup not only your constraints, but your whole view in overridden updateConstraints method. While this isn't wrong, I would advise against it with such simple views. I'd rather make a public func setup() method and call it from view controllers viewDidLoad to setup the view and its constraints.

As to the gesture recognizer - you also need to add it to a view, it's not enough to initialize it. Simple self.addGestureRecognizer(self.titleLabelGestureRecognizer) should do the trick.

Body:
wondering how to update constraints for a custom UI View. Definitely are errors in my code. I apologize in advance, I'm just a beginner at Swift.

public class NoteCardView:UIView {
@IBInspectable var contentView = UIButton(frame: .zero)
@IBInspectable var delegate: MainViewController?
var leftAnchor: NSLayoutXAxisAnchor
var bottomAnchor: NSLayoutYAxisAnchor

override public func updateConstraints() {

    contentView.translatesAutoresizingMaskIntoConstraints = false

    contentView.layer.masksToBounds = true
    contentView.layer.cornerRadius = 6
    contentView.widthAnchor.constraint(equalToConstant: 75).isActive = true
    contentView.heightAnchor.constraint(equalToConstant: 100).isActive = true
    leftAnchor = contentView.leftAnchor.constraint(equalTo: contentView.leftAnchor, constant: positionX).isActive = true
    bottomAnchor = contentView.bottomAnchor.constraint(equalTo: (delegate?.view.bottomAnchor)!, constant: positionY).isActive = true
    titleLabel.textAlignment = .center
    titleLabel.text = note
    contentView.addSubview(titleLabel)

    super.updateConstraints()
}

class MainViewController: UIViewController {
override func viewDidLoad() {
// Trying to implement updated constraints to the NoteCardView here.
}
}

Also having this other issue that is unrelated with the TapGestureRecognizer. I'm not very familiar with this concept either.

public class NoteCard:UIView {
internal var titleLabelTapGestureRecognizer: UITapGestureRecognizer?

internal func commonInit() {
self.titleLabelTapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(handleTitleLabelTap(UITapGestureRecognizer)))
}

internal func handleTitleLabelTap(_ recognizer:UITapGestureRecognizer) {
    self.delegate?.noteCardViewTitleLabelDidRecieveTap(self)
}
}

Thank you in advance for your help!

Body:
There are a couple of issues in your code :

What Rob mentioned in his comment :
contentView.leftAnchor.constraint(equalTo: contentView.leftAnchor,
constant: positionX) - this doesn't make sense, as constraints
should be between anchors of two different views. Also constraints should be configured after adding views to hierarchy.

Also with the same line : leftAnchor = contentView.leftAnchor.constraint(equalTo: contentView.leftAnchor,
constant: positionX).isActive = true. This line has actually two
problems :

2a. This compound assignment evaluates to this :

contentView.leftAnchor.constraint(equalTo: contentView.leftAnchor, constant: positionX).isActive = true
leftAnchor = true

Which means, that you try to assign true to a variable of type NSLayoutXAxisAnchor. Same applies to bottomAnchor

2b. As to the type of leftAnchor - it should be NSLayoutConstraint, because calling constraint on an anchor creates a NSLayoutConstraint. If you wanted to grab a reference to an anchor, you would simply call leftAnchor = contentView.leftAnchor.

You setup not only your constraints, but your whole view in overridden updateConstraints method. While this isn't wrong, I would advise against it with such simple views. I'd rather make a public func setup() method and call it from view controllers viewDidLoad to setup the view and its constraints.

As to the gesture recognizer - you also need to add it to a view, it's not enough to initialize it. Simple self.addGestureRecognizer(self.titleLabelGestureRecognizer) should do the trick.


问:
Add value of playing cards - with pointers and structures
I'm going through some c programming questions and I'm currently stuck on a pointer related question

Q: Write a function that takes the values of a two-card blackjack HAND as input, and returns the point total of the hand. The value
 of the cards '2' through '9' is equal to their face value, the cards 'T', 'K', 'Q', 'J' are worth 10 points and the ace ('A') is worth 11 points
 unless it comes with another ace, then that second ace is worth 1 point. The program should be able to catch incorrect input.

Examples:
Enter cards: A Q
 The score is 21

Enter cards: A A
 The score is 12

I've tackled this question before, but this time I'd have to use pointers which I'm still fairly new towards. Getting card values and calculating cards must be done in one function. Here's what i have so far:

```<code>#include <stdio.h>
#define HAND 2
struct player_hand
{
     char card1;
     char card2;
};

void getHandValue(struct player_hand * hnd_ptr, char size, char size2)
{
    int first_card;
    int second_card;

    //get cards from user
    scanf("%c %c",&hnd_ptr->card1, &hnd_ptr->card2);
    printf("Enter Cards: %c %c", &hnd_ptr->card1, &hnd_ptr->card2);

    //check value of first card in hand
    if(hnd_ptr->card1<='9' && hnd_ptr->card1>='2')
    {
        first_card=(int)hnd_ptr->card1 -48;

    }
    //check for special cards: king, queen, jack, ten
    else if(hnd_ptr->card1=='T'||hnd_ptr->card1=='K'||hnd_ptr->card1=='Q'||hnd_ptr->card1=='J')
    {
        first_card=10;
    }
    //if first card is Ace
    else if(hnd_ptr->card1=='A')
    {
        first_card=11;
    }
    else
    {
        //card not valid
        printf("Not a valid card: %c",hnd_ptr->card1);
        return;
    }

    //check value of 2nd card
    if(hnd_ptr->card2<='9' && hnd_ptr->card2>='2')
    {
        second_card=(int)hnd_ptr->card2 -48;

    }
    //if 2nd card is a special kind
    else if(hnd_ptr->card2=='T'||hnd_ptr->card2=='K'||hnd_ptr->card2=='Q'||hnd_ptr->card2=='J')
    {
        second_card=10;
    }
    //if 2nd card is Ace
    else if(hnd_ptr->card2=='A')
    {
        if(hnd_ptr->card1=='A')
        second_card=1;
        else
        second_card=11;
    }
    else
    {
        //if 2nd card not valid
        printf("Not a valid card: %c",hnd_ptr->card2);
        return;
    }

    add cards
    printf("\nThe total card value is: %d",first_card+second_card);

}

//call function, test if works
//calling it wrong?
int main(void)
{
    struct player_hand hnd [HAND]  =  { {'A', 'A'}};
    getHandValue (hnd, HAND);
    return;
}
</code>```

答:
You have a few bugs.

Incorrect call in main.

The function doesn't need size arguments and if it did they should be int.

Bad return from main.

In the function, the printf is wrong.

Things are much more complicated than they need to be because the struct uses two scalars instead of an array.

I've created two versions of your program. One with bugs annotated. And another that cleans things up.

Here's the annotated version:

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

#define HAND 2

struct player_hand {
    char card1;
    char card2;
};

// NOTE/BUG: use 'int' for size and size2
void
getHandValue(struct player_hand *hnd_ptr, char size, char size2)
{
    int first_card;
    int second_card;

    // get cards from user
    scanf("%c %c", &hnd_ptr->card1, &hnd_ptr->card2);

// NOTE/BUG: this would print the _address_ of the values vs. the values
    printf("Enter Cards: %c %c", &hnd_ptr->card1, &hnd_ptr->card2);

// NOTE/BUG [sort of]: the code below is cut-n-paste replication because you
// have separate card1 and card2 in the struct -- this "cries out" for an
// array and a loop. Consider the general case where you have 5 cards in the
// hand (e.g. five card charlie). The code would be easier even with an array
// of only two

    // check value of first card in hand
    if (hnd_ptr->card1 <= '9' && hnd_ptr->card1 >= '2') {
        first_card = (int) hnd_ptr->card1 - 48;

    }
    // check for special cards: king, queen, jack, ten
    else if (hnd_ptr->card1 == 'T' || hnd_ptr->card1 == 'K' || hnd_ptr->card1 == 'Q' || hnd_ptr->card1 == 'J') {
        first_card = 10;
    }
    // if first card is Ace
    else if (hnd_ptr->card1 == 'A') {
        first_card = 11;
    }
    else {
        // card not valid
        printf("Not a valid card: %c", hnd_ptr->card1);
        return;
    }

    // check value of 2nd card
    if (hnd_ptr->card2 <= '9' && hnd_ptr->card2 >= '2') {
        second_card = (int) hnd_ptr->card2 - 48;

    }
    // if 2nd card is a special kind
    else if (hnd_ptr->card2 == 'T' || hnd_ptr->card2 == 'K' || hnd_ptr->card2 == 'Q' || hnd_ptr->card2 == 'J') {
        second_card = 10;
    }
    // if 2nd card is Ace
    else if (hnd_ptr->card2 == 'A') {
        if (hnd_ptr->card1 == 'A')
            second_card = 1;
        else
            second_card = 11;
    }
    else {
        // if 2nd card not valid
        printf("Not a valid card: %c", hnd_ptr->card2);
        return;
    }

    printf("\nThe total card value is: %d", first_card + second_card);
}

//call function, test if works
//calling it wrong?
int
main(void)
{

// NOTE: based on usage, this is only an array because you're not using &hnd
// below
    struct player_hand hnd[HAND] = {
        {'A', 'A'}
    };

// NOTE/BUG: too few arguments to function, but why pass count at all?
    getHandValue(hnd, HAND);

// NOTE/BUG: need to return value (e.g. return 0)
    return;
}
</code>```

Here's the cleaned up version:

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

#define CARDS_PER_HAND      2

struct player_hand {
    char card[CARDS_PER_HAND];
};

void
getHandValue(struct player_hand *hnd_ptr)
{
    int idx;
    int card;
    int sum;
    int count[CARDS_PER_HAND];

    // get cards from user
    printf("Enter Cards:");
    fflush(stdout);
    for (idx = 0;  idx < CARDS_PER_HAND;  ++idx)
        scanf(" %c", &hnd_ptr->card[idx]);

    // print cards
    printf("Cards entered:");
    for (idx = 0;  idx < CARDS_PER_HAND;  ++idx)
        printf(" %c", hnd_ptr->card[idx]);
    printf("\n");

    for (idx = 0;  idx < CARDS_PER_HAND;  ++idx) {
        card = hnd_ptr->card[idx];

        // simple cards
        if (card <= '9' && card >= '2') {
            count[idx] = (card - '2') + 2;
            continue;
        }

        switch (card) {
        case 'A':
            count[idx] = 11;
            if ((idx == 1) && (count[0] == 11))
                count[idx] = 1;
            break;

        case 'T':
        case 'K':
        case 'Q':
        case 'J':
            count[idx] = 10;
            break;

        default:
            printf("Not a valid card: %c", card);
            return;
            break;
        }
    }

    sum = 0;
    for (idx = 0;  idx < CARDS_PER_HAND;  ++idx)
        sum += count[idx];

    printf("The total card value is: %d\n", sum);
}

int
main(void)
{
    struct player_hand hnd;

    getHandValue(&hnd);

    return 0;
}
</code>```

Body:
I'm going through some c programming questions and I'm currently stuck on a pointer related question

Q: Write a function that takes the values of a two-card blackjack HAND as input, and returns the point total of the hand. The value
 of the cards '2' through '9' is equal to their face value, the cards 'T', 'K', 'Q', 'J' are worth 10 points and the ace ('A') is worth 11 points
 unless it comes with another ace, then that second ace is worth 1 point. The program should be able to catch incorrect input.

Examples:
Enter cards: A Q
 The score is 21

Enter cards: A A
 The score is 12

I've tackled this question before, but this time I'd have to use pointers which I'm still fairly new towards. Getting card values and calculating cards must be done in one function. Here's what i have so far:

#include <stdio.h>
#define HAND 2
struct player_hand
{
     char card1;
     char card2;
};

void getHandValue(struct player_hand * hnd_ptr, char size, char size2)
{
    int first_card;
    int second_card;

    //get cards from user
    scanf("%c %c",&hnd_ptr->card1, &hnd_ptr->card2);
    printf("Enter Cards: %c %c", &hnd_ptr->card1, &hnd_ptr->card2);

    //check value of first card in hand
    if(hnd_ptr->card1<='9' && hnd_ptr->card1>='2')
    {
        first_card=(int)hnd_ptr->card1 -48;

    }
    //check for special cards: king, queen, jack, ten
    else if(hnd_ptr->card1=='T'||hnd_ptr->card1=='K'||hnd_ptr->card1=='Q'||hnd_ptr->card1=='J')
    {
        first_card=10;
    }
    //if first card is Ace
    else if(hnd_ptr->card1=='A')
    {
        first_card=11;
    }
    else
    {
        //card not valid
        printf("Not a valid card: %c",hnd_ptr->card1);
        return;
    }

    //check value of 2nd card
    if(hnd_ptr->card2<='9' && hnd_ptr->card2>='2')
    {
        second_card=(int)hnd_ptr->card2 -48;

    }
    //if 2nd card is a special kind
    else if(hnd_ptr->card2=='T'||hnd_ptr->card2=='K'||hnd_ptr->card2=='Q'||hnd_ptr->card2=='J')
    {
        second_card=10;
    }
    //if 2nd card is Ace
    else if(hnd_ptr->card2=='A')
    {
        if(hnd_ptr->card1=='A')
        second_card=1;
        else
        second_card=11;
    }
    else
    {
        //if 2nd card not valid
        printf("Not a valid card: %c",hnd_ptr->card2);
        return;
    }

    add cards
    printf("\nThe total card value is: %d",first_card+second_card);

}

//call function, test if works
//calling it wrong?
int main(void)
{
    struct player_hand hnd [HAND]  =  { {'A', 'A'}};
    getHandValue (hnd, HAND);
    return;
}

Body:
You have a few bugs.

Incorrect call in main.

The function doesn't need size arguments and if it did they should be int.

Bad return from main.

In the function, the printf is wrong.

Things are much more complicated than they need to be because the struct uses two scalars instead of an array.

I've created two versions of your program. One with bugs annotated. And another that cleans things up.

Here's the annotated version:

#include <stdio.h>

#define HAND 2

struct player_hand {
    char card1;
    char card2;
};

// NOTE/BUG: use 'int' for size and size2
void
getHandValue(struct player_hand *hnd_ptr, char size, char size2)
{
    int first_card;
    int second_card;

    // get cards from user
    scanf("%c %c", &hnd_ptr->card1, &hnd_ptr->card2);

// NOTE/BUG: this would print the _address_ of the values vs. the values
    printf("Enter Cards: %c %c", &hnd_ptr->card1, &hnd_ptr->card2);

// NOTE/BUG [sort of]: the code below is cut-n-paste replication because you
// have separate card1 and card2 in the struct -- this "cries out" for an
// array and a loop. Consider the general case where you have 5 cards in the
// hand (e.g. five card charlie). The code would be easier even with an array
// of only two

    // check value of first card in hand
    if (hnd_ptr->card1 <= '9' && hnd_ptr->card1 >= '2') {
        first_card = (int) hnd_ptr->card1 - 48;

    }
    // check for special cards: king, queen, jack, ten
    else if (hnd_ptr->card1 == 'T' || hnd_ptr->card1 == 'K' || hnd_ptr->card1 == 'Q' || hnd_ptr->card1 == 'J') {
        first_card = 10;
    }
    // if first card is Ace
    else if (hnd_ptr->card1 == 'A') {
        first_card = 11;
    }
    else {
        // card not valid
        printf("Not a valid card: %c", hnd_ptr->card1);
        return;
    }

    // check value of 2nd card
    if (hnd_ptr->card2 <= '9' && hnd_ptr->card2 >= '2') {
        second_card = (int) hnd_ptr->card2 - 48;

    }
    // if 2nd card is a special kind
    else if (hnd_ptr->card2 == 'T' || hnd_ptr->card2 == 'K' || hnd_ptr->card2 == 'Q' || hnd_ptr->card2 == 'J') {
        second_card = 10;
    }
    // if 2nd card is Ace
    else if (hnd_ptr->card2 == 'A') {
        if (hnd_ptr->card1 == 'A')
            second_card = 1;
        else
            second_card = 11;
    }
    else {
        // if 2nd card not valid
        printf("Not a valid card: %c", hnd_ptr->card2);
        return;
    }

    printf("\nThe total card value is: %d", first_card + second_card);
}

//call function, test if works
//calling it wrong?
int
main(void)
{

// NOTE: based on usage, this is only an array because you're not using &hnd
// below
    struct player_hand hnd[HAND] = {
        {'A', 'A'}
    };

// NOTE/BUG: too few arguments to function, but why pass count at all?
    getHandValue(hnd, HAND);

// NOTE/BUG: need to return value (e.g. return 0)
    return;
}

Here's the cleaned up version:

#include <stdio.h>

#define CARDS_PER_HAND      2

struct player_hand {
    char card[CARDS_PER_HAND];
};

void
getHandValue(struct player_hand *hnd_ptr)
{
    int idx;
    int card;
    int sum;
    int count[CARDS_PER_HAND];

    // get cards from user
    printf("Enter Cards:");
    fflush(stdout);
    for (idx = 0;  idx < CARDS_PER_HAND;  ++idx)
        scanf(" %c", &hnd_ptr->card[idx]);

    // print cards
    printf("Cards entered:");
    for (idx = 0;  idx < CARDS_PER_HAND;  ++idx)
        printf(" %c", hnd_ptr->card[idx]);
    printf("\n");

    for (idx = 0;  idx < CARDS_PER_HAND;  ++idx) {
        card = hnd_ptr->card[idx];

        // simple cards
        if (card <= '9' && card >= '2') {
            count[idx] = (card - '2') + 2;
            continue;
        }

        switch (card) {
        case 'A':
            count[idx] = 11;
            if ((idx == 1) && (count[0] == 11))
                count[idx] = 1;
            break;

        case 'T':
        case 'K':
        case 'Q':
        case 'J':
            count[idx] = 10;
            break;

        default:
            printf("Not a valid card: %c", card);
            return;
            break;
        }
    }

    sum = 0;
    for (idx = 0;  idx < CARDS_PER_HAND;  ++idx)
        sum += count[idx];

    printf("The total card value is: %d\n", sum);
}

int
main(void)
{
    struct player_hand hnd;

    getHandValue(&hnd);

    return 0;
}


问:
Unsupported compiler 'com.apple.compilers.llvm.clang.1_0' selected for architecture 'x86_64' on Xcode 7 Beta 2
When I incorporated a popular OAuth2 library in iOS called OAuth2Client to my iOS app which is developed on Xcode 7 Beta 2 and then tried running the simulator, the following error occurred and the simulator didn't launch.

Unsupported compiler 'com.apple.compilers.llvm.clang.1_0' selected for architecture 'x86_64'

What does this error mean? A lot of warnings (yellow triangle) followed with the error above (red octagon), such as:

warning: no rule to process file '/Users/myUsername/myAppname/Pods/NXOAuth2Client/Sources/NSData+NXOAuth2.m' of type sourcecode.c.objc for architecture x86_64

How can I deal with the these errors and run the simulator properly? Or does CocoaPods only work on environments prior to Xcode 7 Beta?

UPDATE

Later I found that this occurs on any projects I create, not only on a project using CocoaPods. The only clue that occurs to me is that when I updated my iTunes to 12.2 today and then launched my Xcode, the dialog popped up, instructing to install new command-line tools.

UPDATE 2

I just upgrade to Xcode 7 Beta 3 but the error still got me annoyed...

答:
Solution 1

Close Xcode, open terminal, before anything else, type: “defaults delete com.apple.dt.Xcode” (this addresses your Xcode settings) open Xcode and your project should work normally.

Plan B

If that doesn't work try this to clear out your cache.  Save your files then put this in your terminal:

rm -rf Library/Caches/com.apple.dt.Xcode/

Potential causes

This bug can occur if you declared your pods with single quotes instead of double quotes or for some reason your pod files become corrupted (i.e.: working with p.lists, Google's p.list, firebase etc). I think what triggers the bug to break your code is during certain recompiling phases, for example: opening after unzipping the project, or opening the project after pulling it from GitHub.


问:
Uncaught Error: [$injector:unpr] for ngMaterial
I am having issue with ngMaterial while including it in project then its showing error Uncaught Error: [$injector:unpr]
My app.js file look like

```<code>angular
        .module('app', ['ui.router','ngMaterial','objectTable'])
        .config(config)
        .run(run);
</code>```

and in view, I have included files in this order

```<code><!-- external scripts -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular-animate.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular-aria.min.js"></script>

<script src="https://ajax.googleapis.com/ajax/libs/angular_material/0.11.2/angular-material.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.15/angular-ui-router.min.js"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<!-- bower plugins -->
<script type="text/javascript" src="app-content/scripts/object-table.js"></script>

<!-- application scripts -->
<script src="app.js"></script>
<script src="app-services/user.service.js"></script>
<script src="app-services/flash.service.js"></script>
<script src="home/index.controller.js"></script>
<script src="account/index.controller.js"></script>
</code>```

Can anyone help me to solve this? I tried to change the order of files but still, the issue is same.

答:
For posterity: I installed using Visual Studio and NuGET. I first installed my angularjs.core package (only the angular file). This was version 1.5.8. I then installed angular material afterwards. This was installed in version 1.1.3. What i didnt notice at first was that when iu installed angular material was that it included its own version of angular.

The point is - i was using my first installed "angularjs.core" in a way to high version (i think this was the problem). I then switched to using the angular version shipped with material NuGet package. Then then everything worked.

Body:
I am having issue with ngMaterial while including it in project then its showing error Uncaught Error: [$injector:unpr]
My app.js file look like

angular
        .module('app', ['ui.router','ngMaterial','objectTable'])
        .config(config)
        .run(run);

and in view, I have included files in this order

Can anyone help me to solve this? I tried to change the order of files but still, the issue is same.


问:
Show associated metric from CSV in tooltip when county is hovered
I have been working with bringing in multiple files using d3.queue(). The JSON is the map, the CSV are metrics tied to the IDs in the JSON file. I have successfully loaded the CSV and can print the list using d3.map().

From here I am unsure how to return actual_margin when a county is hovered. The goal is whenever a county is hovered to show the actual_margin in the tooltip. Here's the full code, the .html() is just printing hi as a placeholder.

```<code><!DOCTYPE html>
<style>

    .counties {
        fill: white;
        stroke: #7887AB;
        stroke-width: .5px;
    }

    .counties .hovered,
    .counties :hover {
        fill: #061539;
        stroke-width: .5px;
    }

    .county-borders {
        fill: none;
        stroke: #F0F8FF;
        stroke-width: .2px;
        stroke-linejoin: round;
        stroke-linecap: round;
        pointer-events: none;
    }

    .state-borders {
        fill: none;
        stroke: #162955;
        opacity: .8;
        stroke-linejoin: round;
        stroke-linecap: round;
        pointer-events: none;
    }

    .toolTip {
        position: absolute;
        display: none;
        min-width: 80px;
        height: auto;
        background: none repeat scroll 0 0 #ffffff;
        border: 1px solid #6F257F;
        padding: 14px;
        text-align: center;
    }
</style>

<svg width="960" height="600"></svg>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="https://d3js.org/topojson.v2.min.js"></script>
<script>
    var svg = d3.select("svg");
    var path = d3.geoPath();
    var tooltip = d3.select("body").append("div").attr("class", "toolTip");
    var metrics = d3.map();

    d3.queue()
        .defer(d3.json, "https://d3js.org/us-10m.v1.json")
        .defer(d3.csv, "https://raw.githubusercontent.com/MatthewSnellOKC/mapping/master/merge/countymetrics_json.csv", function(d) {metrics.set(d.county_fips, +d.actual_margin);})
        .await(ready);

    function ready(error, us) {
        if (error) throw error;

        svg.append("g")
            .attr("class", "counties")
            .selectAll("path")
            .data(topojson.feature(us, us.objects.counties).features)
            .enter()
            .append("path")
            .attr("d", path);

        svg.append("g")
            .attr("class", "state-borders")
            .selectAll("path")
            .data(topojson.feature(us, us.objects.nation).features)
            .enter()
            .append("path")
            .attr("d", path);
        svg.append("path")
            .attr("class", "state-borders")
            .attr("d", path(topojson.mesh(us, us.objects.nation, function(a, b) {
                return a !== b;
            })));
        svg.append("path")
            .attr("class", "state-borders")
            .attr("d", path(topojson.mesh(us, us.objects.states, function(a, b) {
                return a !== b;
            })));
        svg.append("path")
            .attr("class", "county-borders")
            .attr("d", path(topojson.mesh(us, us.objects.counties, function(a, b) {
                return a !== b;
            })));

        svg.selectAll('.counties path')
            .on('mouseover', function() {

                tooltip
                    .style("left", 500 + "px")
                    .style("top", 70 + "px")
                    .style("display", "inline-block")
                    .html("hi"); //Goal is to return the associated actual_margin to the ID of each county.
            })
            .on('mouseout', function(d) {
                tooltip.style("display", "none");
            });
    }
</script>
</code>```

答:
Since you're using a set...

```<code>metrics.set(d.county_fips, +d.actual_margin);
</code>```

... you have to retrieve the value with a get:

```<code>.html("The value is " + metrics.get(d.id));
</code>```

Also, notice that you have to pass the datum d to the mouseover event:

```<code>.on('mouseover', function(d) {
//datum here -------------^
</code>```

Here is your code with those changes:

<svg width="960" height="600"></svg>

```

Body:
I have been working with bringing in multiple files using d3.queue(). The JSON is the map, the CSV are metrics tied to the IDs in the JSON file. I have successfully loaded the CSV and can print the list using d3.map().

From here I am unsure how to return actual_margin when a county is hovered. The goal is whenever a county is hovered to show the actual_margin in the tooltip. Here's the full code, the .html() is just printing hi as a placeholder.

<!DOCTYPE html>

<svg width="960" height="600"></svg>

Body:
Since you're using a set...

metrics.set(d.county_fips, +d.actual_margin);

... you have to retrieve the value with a get:

.html("The value is " + metrics.get(d.id));

Also, notice that you have to pass the datum d to the mouseover event:

.on('mouseover', function(d) {
//datum here -------------^

Here is your code with those changes:

<style>
  .counties {
    fill: white;
    stroke: #7887AB;
    stroke-width: .5px;
  }

  .county-borders {
    fill: none;
    stroke: #F0F8FF;
    stroke-width: .2px;
    stroke-linejoin: round;
    stroke-linecap: round;
    pointer-events: none;
  }

  .state-borders {
    fill: none;
    stroke: #162955;
    opacity: .8;
    stroke-linejoin: round;
    stroke-linecap: round;
    pointer-events: none;
  }

  .toolTip {
    position: absolute;
    min-width: 80px;
    height: auto;
    background: none repeat scroll 0 0 #ffffff;
    border: 1px solid #6F257F;
    padding: 14px;
    text-align: center;
  }

</style>

<svg width="960" height="600"></svg>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="https://d3js.org/topojson.v2.min.js"></script>
<script>
  var svg = d3.select("svg");
  var path = d3.geoPath();
  var tooltip = d3.select("body").append("div").attr("class", "toolTip");
  var metrics = d3.map();

  d3.queue()
    .defer(d3.json, "https://d3js.org/us-10m.v1.json")
    .defer(d3.csv, "https://raw.githubusercontent.com/MatthewSnellOKC/mapping/master/merge/countymetrics_json.csv", function(d) {
      metrics.set(d.county_fips, +d.actual_margin);
    })
    .await(ready);

  function ready(error, us) {
    if (error) throw error;

    svg.append("g")
      .attr("class", "counties")
      .selectAll("path")
      .data(topojson.feature(us, us.objects.counties).features)
      .enter()
      .append("path")
      .attr("d", path);

    svg.append("g")
      .attr("class", "state-borders")
      .selectAll("path")
      .data(topojson.feature(us, us.objects.nation).features)
      .enter()
      .append("path")
      .attr("d", path);
    svg.append("path")
      .attr("class", "state-borders")
      .attr("d", path(topojson.mesh(us, us.objects.nation, function(a, b) {
        return a !== b;
      })));
    svg.append("path")
      .attr("class", "state-borders")
      .attr("d", path(topojson.mesh(us, us.objects.states, function(a, b) {
        return a !== b;
      })));
    svg.append("path")
      .attr("class", "county-borders")
      .attr("d", path(topojson.mesh(us, us.objects.counties, function(a, b) {
        return a !== b;
      })));

    svg.selectAll('path')
      .on('mouseover', function(d) {
        tooltip
          .style("left", d3.event.pageX + 20 + "px")
          .style("top", d3.event.pageY + "px")
          .style("display", "inline-block")
          .html("The value is " + metrics.get(d.id));
      })
      .on('mouseout', function(d) {
        tooltip.style("display", "none");
      });
  }

</script>


问:
ASP NET SQL - for each row create a new div
Looking for a solution to create a new div with its content for each row in SQL Server database table:

```<code>Dim com As SqlCommand = New SqlCommand("select Date,Title,Content from Log where Author = @Author", con)
com.Parameters.Add("@Author", SqlDbType.Char)
com.Parameters("@Author").Value = User.Identity.Name

Dim dt As DataTable = New DataTable()

For Each Datarow In dt.Rows
       //create New div with its content
Next
</code>```

This one is working, but can't get it to create a new div/table with its content yet.

Appreciate any help.

答:
```<code>DataSet ds = new DataSet();
SqlDataAdapter da1 = new SqlDataAdapter("select Date,Title,Content from Log where Author = @Author", ConfigurationManager.ConnectionStrings["sasa"].ConnectionString);
 da1.Fill(ds);
 string makehtml = string.Empty;
//however when you have DataSet then you can iterate easily and cerate whatever you want
    for(int i = 0; i < ds.Tables[0].Rows.Count; i++)
    {
        makehtml += "<div><span>Date:</span> " + ds.Tables[0].Rows[i]["Date"] + " <span>Title:</span> " + ds.Tables[0].Rows[i]["Title"] + "< span > Content:</ span > " + ds.Tables[0].Rows[i]["Content"] + " </div>";
    }
</code>```

Please check if it helps. i am not expert in VB but when you have DataSet then you can iterate over the DataSet Row by Row and create a div or have some other operations to perform.
Some Other options or good approach:

```<code> <asp:ListView ID="lstVDataBind" runat="server">
                                    <LayoutTemplate>
                                        <asp:PlaceHolder ID="itemPlaceholder" runat="server" />
                                    </LayoutTemplate>
                                    <ItemTemplate>
                                        <div class="col-md-12"><span>Date:</span><%#Eval("Date")%>
                                            <span>Title:</span><%#Eval("Title")%>< span > Content:</ span > <%#Eval("Content")%></div>
                                    </ItemTemplate>
                        </asp:ListView>
</code>```

And in code behind you can assign your dataset to Listview as datasource like:

```<code>lstVDataBind.DataSource = ds;
        lstVDataBind.DataBind();
</code>```

You can also use repeater instead of Listview.
Another way you can do samething:

```<code> <%-- statrt here --%>
            <% if (ds.Tables[0].Rows.Count > 0){
                    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                    {%>
            <div class="col-md-12">
                <div class="col-md-12"><span>Date:</span><%=ds.Tables[0].Rows[i]["Date"].ToString()%>
                <span>Title:</span><%=ds.Tables[0].Rows[i]["Title"].ToString()%><span> Content:</span><%=ds.Tables[0].Rows[i]["Content"].ToString()%></div>
            </div>
            <%}} %>
            <%-- Ends here --%>
</code>```

This code will be in aspx page but for this you have to make your dataset public so it be easilty accessible.

Body:
Looking for a solution to create a new div with its content for each row in SQL Server database table:

Dim com As SqlCommand = New SqlCommand("select Date,Title,Content from Log where Author = @Author", con)
com.Parameters.Add("@Author", SqlDbType.Char)
com.Parameters("@Author").Value = User.Identity.Name

Dim dt As DataTable = New DataTable()

For Each Datarow In dt.Rows
       //create New div with its content
Next

This one is working, but can't get it to create a new div/table with its content yet.

Appreciate any help.

Body:
DataSet ds = new DataSet();
SqlDataAdapter da1 = new SqlDataAdapter("select Date,Title,Content from Log where Author = @Author", ConfigurationManager.ConnectionStrings["sasa"].ConnectionString);
 da1.Fill(ds);
 string makehtml = string.Empty;
//however when you have DataSet then you can iterate easily and cerate whatever you want
    for(int i = 0; i < ds.Tables[0].Rows.Count; i++)
    {
        makehtml += "<div><span>Date:</span> " + ds.Tables[0].Rows[i]["Date"] + " <span>Title:</span> " + ds.Tables[0].Rows[i]["Title"] + "< span > Content:</ span > " + ds.Tables[0].Rows[i]["Content"] + " </div>";
    }

Please check if it helps. i am not expert in VB but when you have DataSet then you can iterate over the DataSet Row by Row and create a div or have some other operations to perform.
Some Other options or good approach:

 <asp:ListView ID="lstVDataBind" runat="server">
                                    <LayoutTemplate>
                                        <asp:PlaceHolder ID="itemPlaceholder" runat="server" />
                                    </LayoutTemplate>
                                    <ItemTemplate>
                                        <div class="col-md-12"><span>Date:</span><%#Eval("Date")%>
                                            <span>Title:</span><%#Eval("Title")%>< span > Content:</ span > <%#Eval("Content")%></div>
                                    </ItemTemplate>
                        </asp:ListView>

And in code behind you can assign your dataset to Listview as datasource like:

lstVDataBind.DataSource = ds;
        lstVDataBind.DataBind();

You can also use repeater instead of Listview.
Another way you can do samething:

 <%-- statrt here --%>
            <% if (ds.Tables[0].Rows.Count > 0){
                    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                    {%>
            <div class="col-md-12">
                <div class="col-md-12"><span>Date:</span><%=ds.Tables[0].Rows[i]["Date"].ToString()%>
                <span>Title:</span><%=ds.Tables[0].Rows[i]["Title"].ToString()%><span> Content:</span><%=ds.Tables[0].Rows[i]["Content"].ToString()%></div>
            </div>
            <%}} %>
            <%-- Ends here --%>

This code will be in aspx page but for this you have to make your dataset public so it be easilty accessible.


问:
automating replace and append words from text file
I have a line in bash file like ---

```<code>curl -L $domain/url1 options
</code>```

domain is already read from another text file and
domains like

```<code>abc.com
google.com
yahoo.com
</code>```

and i have another separate file which contains further URL (lot in number):

```<code>url1
url2
url3
....
url1000
</code>```

I want to replace that url and append that like:

```<code>curl -L abc.com/url1 options
curl -L abc.com/url2 options
curl -L abc.com/url3 options
....
curl -L $abc.com/url1000 options
</code>```

It is taking too much time manually, so I want to automate this process.

答:
Use a proper loop in bash with Process-substitution,

```<code>while IFS= read -r url; do
    curl -L abc.com/"$url" options
done <url_file
</code>```

would just be sufficient (or) in a single-line of the same-loop,

```<code>while IFS= read -r url; do curl -L abc.com/"$url" options; done <url_file
</code>```

For your updated requirement to loop on two files, you need to define multiple file descriptors and read from it,

```<code>while IFS= read -r domain <&3; do
    while IFS= read -r url <&4; do
        curl -L "$domain"/"$url" options
    done 4<url.txt
done 3<domain.txt
</code>```

The above should work fine on any POSIX shell not involving any bash-isms, you could just put the above in a script with a #!/bin/sh she-bang.

Body:
I have a line in bash file like ---

curl -L $domain/url1 options

domain is already read from another text file and
domains like

abc.com
google.com
yahoo.com

and i have another separate file which contains further URL (lot in number):

url1
url2
url3
....
url1000

I want to replace that url and append that like:

curl -L abc.com/url1 options
curl -L abc.com/url2 options
curl -L abc.com/url3 options
....
curl -L $abc.com/url1000 options

It is taking too much time manually, so I want to automate this process.

Body:
Use a proper loop in bash with Process-substitution,

while IFS= read -r url; do
    curl -L abc.com/"$url" options
done <url_file

would just be sufficient (or) in a single-line of the same-loop,

while IFS= read -r url; do curl -L abc.com/"$url" options; done <url_file

For your updated requirement to loop on two files, you need to define multiple file descriptors and read from it,

while IFS= read -r domain <&3; do
    while IFS= read -r url <&4; do
        curl -L "$domain"/"$url" options
    done 4<url.txt
done 3<domain.txt

The above should work fine on any POSIX shell not involving any bash-isms, you could just put the above in a script with a #!/bin/sh she-bang.


问:
How to return the Node class or type in the query results in Neo4j
I have a node type Author, which is linked to node types Book and Magazine by the relationship type WROTE.  I need to find all books and magazines a particular author wrote in a single query, and in the query results I want to be able to differentiate between the Book and the Magazine results.

One way I can achieve this is by defining separate relationships for Books and Magazines, and returning the TYPE(relationship) value in the results to match results for Books versus Magazines.

```<code>MATCH (a:Author)-[r]->(i) WHERE TYPE(r) = 'WROTE_BOOK' OR TYPE(r) = 'WROTE_MAGAZINE'
RETURN TYPE(r), i
</code>```

However, I would like to be able to do this without having separate relationships for WROTE.  Is there a way to query the node type or class in the query results?  In the example above, something like below:

```<code>MATCH (a:Author)-[:WROTE]->(i) WHERE TYPE(i) = 'Book' OR TYPE(i) = 'MAGAZINE'
RETURN TYPE(i), i
</code>```

It seems that the TYPE() function is only available for relationships, not for nodes.  Thanks for your help in advance!

答:
type is for relationships and labels is for nodes.

```<code>MATCH (a:Author)-[:WROTE]->(i) WHERE labels(i) in ['Book','MAGAZINE']
RETURN labels(i), i
</code>```

if your author wrote only magazines and books, you do not need the WHERE filter.

```<code>MATCH (a:Author)-[:WROTE]->(i)
RETURN labels(i), i
</code>```

Body:
I have a node type Author, which is linked to node types Book and Magazine by the relationship type WROTE.  I need to find all books and magazines a particular author wrote in a single query, and in the query results I want to be able to differentiate between the Book and the Magazine results.

One way I can achieve this is by defining separate relationships for Books and Magazines, and returning the TYPE(relationship) value in the results to match results for Books versus Magazines.

MATCH (a:Author)-[r]->(i) WHERE TYPE(r) = 'WROTE_BOOK' OR TYPE(r) = 'WROTE_MAGAZINE'
RETURN TYPE(r), i

However, I would like to be able to do this without having separate relationships for WROTE.  Is there a way to query the node type or class in the query results?  In the example above, something like below:

MATCH (a:Author)-[:WROTE]->(i) WHERE TYPE(i) = 'Book' OR TYPE(i) = 'MAGAZINE'
RETURN TYPE(i), i

It seems that the TYPE() function is only available for relationships, not for nodes.  Thanks for your help in advance!

Body:
type is for relationships and labels is for nodes.

MATCH (a:Author)-[:WROTE]->(i) WHERE labels(i) in ['Book','MAGAZINE']
RETURN labels(i), i

if your author wrote only magazines and books, you do not need the WHERE filter.

MATCH (a:Author)-[:WROTE]->(i)
RETURN labels(i), i


问:
Button click event binding in Electron js
I have started using electron js to develop desktop application.

I want to know that how to bind button click event with javascript function so that I can perform other operation.

I used below HTML code:

```<code><!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Manav Finance</title>
  </head>
  <body>
    <input type="button" onclick="getData()" value="Get Data" />
  </body>

  <script>
    // You can also require other files to run in this process
    require('./renderer.js')
  </script>
</html>
</code>```

My renderer.js code looks like this:

```<code>function getData(){
        console.log('Called!!!');
    }
</code>```

But I am getting error that:

Uncaught ReferenceError: getData is not defined
      at HTMLInputElement.onclick

Am I doing something wrong?

Update

Updated HTML document and removed require() method and its working now:

```<code><!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Manav Finance</title>
    <script src="renderer.js"></script>
  </head>
  <body>
    <input type="button" id="btnEd" value="Get Data" onclick="getData()" />
  </body>
</html>
</code>```

答: To explain this for future users.

Body:
I have started using electron js to develop desktop application.

I want to know that how to bind button click event with javascript function so that I can perform other operation.

I used below HTML code:

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Manav Finance</title>

    <input type="button" onclick="getData()" value="Get Data" />

My renderer.js code looks like this:

function getData(){
        console.log('Called!!!');
    }

But I am getting error that:

Uncaught ReferenceError: getData is not defined
      at HTMLInputElement.onclick

Am I doing something wrong?

Update

Updated HTML document and removed require() method and its working now:

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Manav Finance</title>

    <input type="button" id="btnEd" value="Get Data" onclick="getData()" />

Body:
To explain this for future users.  <script> tag's in an HTML document are executed in the global scope, this means that this === window, I.e. any function or variable declared in the script inherently becomes global.

When you require a script it becomes isolated in it's own context (it is wrapped in another function so this !== window, I.e. any function or variable declared in the script is not available globally.

The correct way to do this is to use require('./renderer.js') and to use this code

function getData() {
    ...
}

document.querySelector('#btnEd').addEventListener('click', () => {
    getData()
})


问:
Type checking and range checking
In one of the textbooks I'm reading is stated "While types are checked for compatibility at compile time, subranges require run-time range checking."
If I'm getting it right, a runtime check must be performed when new values are assigned to a variable that is defined in a certain subrange (subtype). Isn't it the same for types? Why this difference? Is this just a default of the compiler?</p>

答:
Simon Wright's answer addresses the question from the point of view of Ada and its subtype, which means a subset of values in a type, thus not what Ada or C++ call a derived type or derived class, respectively. (type Lower is new Upper … ; makes Lower be derived from Upper, the “…” defining further characteristics of the subtype then created.)

More generally, some languages allow any variable name to refer to any type of object at run-time. Thus, in JavaScript,

var a = 15, b = -1;
  ...
a = {"foo": "bar"}
  ...
return a + b;
```

<p>will return a result that might be surprising, but is fine if judged by the language. <code>a</code> is assigned a new value of a different type on the second line, and <code>+</code> will produce something from <code>a</code> and <code>b</code> on the third.</p>

<p>This flexibility is not wanted in languages like Ada, or C, or Swift for that matter: a program that is written in such a language, to run on any computer device, is meant to not be putting a dictionary-like object in a location <strong>declared</strong> to be of some integer type, say. Compile time type checking prevents this situation. Any “disrespect” when assigning (or passing) objects is required to be detected at compile time.</p>

<p>Ada, in addition to compile time type checking, uses name based equivalence of types. So, </p>

<pre class="lang-ada prettyprint-override"><code>type Apples is range 0 .. 20;
type Oranges is range 0 .. 20;

a : Apples := 5;
b : Oranges := 8;

return a + b;  -- Error!
</code>```

You get

```<code> 8.    return a + b;  -- Error!
                |
    >>> invalid operand types for operator "+"
    >>> left operand has type "Apples" defined at line 2
    >>> right operand has type "Oranges" defined at line 3
</code>```

This is pure type checking at compile-time.

Last, extending what Simon Wright's example is illustrating, sometimes Ada even requires subtypes to be checked at compile time. The phrase involved then is that subtypes statically match, where static means compile-time. For example, same bounds. But, this is advanced stuff occurring, e.g., when pointers should point to objects on the stack and these have a range (subtype) that is different from the pointer's.

Title: Type checking and range checking

Body:
Simon Wright's answer addresses the question from the point of view of Ada and its subtype, which means a subset of values in a type, thus not what Ada or C++ call a derived type or derived class, respectively. (type Lower is new Upper … ; makes Lower be derived from Upper, the “…” defining further characteristics of the subtype then created.)

More generally, some languages allow any variable name to refer to any type of object at run-time. Thus, in JavaScript,

var a = 15, b = -1;
  ...
a = {"foo": "bar"}
  ...
return a + b;

will return a result that might be surprising, but is fine if judged by the language. a is assigned a new value of a different type on the second line, and + will produce something from a and b on the third.

This flexibility is not wanted in languages like Ada, or C, or Swift for that matter: a program that is written in such a language, to run on any computer device, is meant to not be putting a dictionary-like object in a location declared to be of some integer type, say. Compile time type checking prevents this situation. Any “disrespect” when assigning (or passing) objects is required to be detected at compile time.

Ada, in addition to compile time type checking, uses name based equivalence of types. So,

type Apples is range 0 .. 20;
type Oranges is range 0 .. 20;

a : Apples := 5;
b : Oranges := 8;

return a + b;  -- Error!

You get

 8.    return a + b;  -- Error!
                |
    >>> invalid operand types for operator "+"
    >>> left operand has type "Apples" defined at line 2
    >>> right operand has type "Oranges" defined at line 3

This is pure type checking at compile-time.

Last, extending what Simon Wright's example is illustrating, sometimes Ada even requires subtypes to be checked at compile time. The phrase involved then is that subtypes statically match, where static means compile-time. For example, same bounds. But, this is advanced stuff occurring, e.g., when pointers should point to objects on the stack and these have a range (subtype) that is different from the pointer's.


问:
What is the difference between "lea eax, [ebx + eax]" and "add eax, ebx" in x86-32 assembly?
GCC made me some assembly code, and inside theres this statement:

```<code>lea eax, [ebx+eax]
</code>```

(Intel Syntax)
Just curious, what would the difference between that, and:

```<code>add eax, ebx
</code>```

Be?

eax, and ebx contains return values from functions :)

```<code>mov eax, DWORD PTR [ebp+8]
mov DWORD PTR [esp], eax
call CALC1
mov ebx, eax.
mov eax, DWORD PTR [ebp+8]
mov DWORD PTR [esp], eax
call CALC2
lea eax, [ebx+eax]
</code>```

答:
One difference that immediately springs to mind is that lea doesn't affect the flags, whereas add does.

It is impossible to say without seeing the rest of the assembly code whether this is of any relevance. It could simply be an artefact of the GCC's code generator (i.e. it could in fact be producing code for a more general case or just using lea as a more flexible add.)

Body:
GCC made me some assembly code, and inside theres this statement:

lea eax, [ebx+eax]

(Intel Syntax)
Just curious, what would the difference between that, and:

add eax, ebx

Be?

eax, and ebx contains return values from functions :)

mov eax, DWORD PTR [ebp+8]
mov DWORD PTR [esp], eax
call CALC1
mov ebx, eax.
mov eax, DWORD PTR [ebp+8]
mov DWORD PTR [esp], eax
call CALC2
lea eax, [ebx+eax]

ContentLicense: CC BY-SA 2.5


问:
Unable to pass a variable to a function
I want to pass the current index to a function reading images via FileApi and showing preview of them:

```<code>for(var i = 0, f; f = files[i]; i++) {
  if (!f.type.match("image.*")) {
    continue;
  }

  var reader = new FileReader();
  reader.onload = (function(theFile) {
    return function(e) {
      var dv = document.createElement("div");
      //.............

    };
  })(f);

  reader.readAsDataURL(f);
}
</code>```

I've tried this:

```<code>  //.......
  var reader = new FileReader();
  reader.onload = (function(theFile, i2) {

    //i2 is defined here

    return function(e) {
      var dv = document.createElement("div");

      //i2 isn't defined here

    };
  })(f, i);
</code>```

But as you can see, i2 isn't defined. How to fix that?

答:
If you organize the wrapper function(s) a bit, everything can be properly scoped. Here I wrap basically the whole loop body in a self-calling function. The onload handler is then just a plain old function assignment. In your production code you can remove the dummy onload.

var files = ['one', 'two', 'three'];
for (var i = 0, f; f = files[i]; i++) {
    (function(i, f) {
        var reader = new FileReader();
        reader.onload = function() {
            var dv = document.createElement("div");
            console.log(f + i);
        };
        // dummy onload
        (function(r) {
          setTimeout(r.onload, 1000 + (i + 1) * 333);
        })(reader);
    })(i, f)
}```

Title: Unable to pass a variable to a function

Body:
I want to pass the current index to a function reading images via FileApi and showing preview of them:

for(var i = 0, f; f = files[i]; i++) {
  if (!f.type.match("image.*")) {
    continue;
  }

  var reader = new FileReader();
  reader.onload = (function(theFile) {
    return function(e) {
      var dv = document.createElement("div");
      //.............

    };
  })(f);

  reader.readAsDataURL(f);
}

I've tried this:

  //.......
  var reader = new FileReader();
  reader.onload = (function(theFile, i2) {

    //i2 is defined here

    return function(e) {
      var dv = document.createElement("div");

      //i2 isn't defined here

    };
  })(f, i);

But as you can see, i2 isn't defined. How to fix that?


问:
How can I decode the following bytes?
```<code>>>> byte_code = b'\x01\x00^\x00H6\x00#'

>>> byte_code.decode("utf-8")
'\x01\x00^\x00H6\x00#'
</code>```

This doesn't seem to work in Python. Shouldn't the result be string?

答:
Python is higher level than C or C++ language and it is not the best language to work with bits and bytes. It has no any data type considering bytes and bits so the only way to work with them is to use packages implemented on C or C++ such as https://pypi.python.org/pypi/bitarray/. However Python is able to represent bits and bytes using strings so you basically right. I am not sure what you exactly mean by word "decode" but try this:

print('{}'.format('\x01\x00^\x00H6\x00#'))

Title: How can I decode the following bytes?

Body:
>>> byte_code = b'\x01\x00^\x00H6\x00#'

>>> byte_code.decode("utf-8")
'\x01\x00^\x00H6\x00#'

This doesn't seem to work in Python. Shouldn't the result be string?


问:
how to have a javascript flag reset after a time
I am using this code to have some speech occur when a user reaches section of the website:

```<code>var shutup_theform;
$(window).on('resize scroll', function() {
if (!shutup_theform){
    if ($('#theform').isInViewport())
        {
            speak_section("send us a message, we would love to hear from you!");
            shutup_theform = true;
        }
       } });
</code>```

(the isInViewport and speak_section functions not shown)

I'm using the shutup_theform variable to set a flag so that the speech occurs only once.

My question is what would be a suitable way to have this flag reset after a period of time? I'm aware of the setTimeout() function.

答:
Yes you can use setTimeout

```<code>function resetVar(){
   shutup_theform = false;
}

if ($('#theform').isInViewport()){
    speak_section("send us a message, we would love to hear from you!");
    shutup_theform = true;
    setTimeout(resetVar,time)
  }
</code>```

Body:
I am using this code to have some speech occur when a user reaches section of the website:

var shutup_theform;
$(window).on('resize scroll', function() {
if (!shutup_theform){
    if ($('#theform').isInViewport())
        {
            speak_section("send us a message, we would love to hear from you!");
            shutup_theform = true;
        }
       } });

(the isInViewport and speak_section functions not shown)

I'm using the shutup_theform variable to set a flag so that the speech occurs only once.

My question is what would be a suitable way to have this flag reset after a period of time? I'm aware of the setTimeout() function.

Body:
Yes you can use setTimeout

function resetVar(){
   shutup_theform = false;
}

if ($('#theform').isInViewport()){
    speak_section("send us a message, we would love to hear from you!");
    shutup_theform = true;
    setTimeout(resetVar,time)
  }


问:
C++ map customize comparator
I defined a map to count the number of strings while sorting the strings by their length:

```<code>struct cmp {
    bool operator()(const string& a, const string& b) {
        return a.size() > b.size();
    }
};

int main() {
    map<string, int, cmp> mp;
    mp["aaa"] = 1;
    mp["bbb"] = 2;
    cout << mp["aaa"];
}
</code>```

I'm confused as the output is 2. How should I achieve my goal?

答:
std::map not only sorts items by key, it stores them by (unique) key - 1 item per key.

This behavior is defined by the comparator: if for keys a & b neither of a<b and b<a is true, these keys are considered equal.

In your case mp["bbb"] = 2 just overwrites mp["aaa"].

If you want to fit all the strings in the map, you can use std::multimap, which allows more than 1 value per key.

The other way is to redefine the comparator, so that it would take the different strings into account:

```<code>struct cmp {
    bool operator()(const string& a, const string& b) {
        if(a.size() < b.size()) return true;
        if(b.size() < a.size()) return false;
        return a<b;
    }
};
</code>```

Thus your map will still prioritize sorting by string length, but it will also distinguish different strings of same size.

Depending on your use case, you can also check other containers like priority_queue or just plain vector with a proper insertion technique.

Title: C++ map customize comparator

Body:
I defined a map to count the number of strings while sorting the strings by their length:

struct cmp {
    bool operator()(const string& a, const string& b) {
        return a.size() > b.size();
    }
};

int main() {
    map<string, int, cmp> mp;
    mp["aaa"] = 1;
    mp["bbb"] = 2;
    cout << mp["aaa"];
}

I'm confused as the output is 2. How should I achieve my goal?

Body:
std::map not only sorts items by key, it stores them by (unique) key - 1 item per key.

This behavior is defined by the comparator: if for keys a & b neither of a<b and b<a is true, these keys are considered equal.

In your case mp["bbb"] = 2 just overwrites mp["aaa"].

If you want to fit all the strings in the map, you can use std::multimap, which allows more than 1 value per key.

The other way is to redefine the comparator, so that it would take the different strings into account:

struct cmp {
    bool operator()(const string& a, const string& b) {
        if(a.size() < b.size()) return true;
        if(b.size() < a.size()) return false;
        return a<b;
    }
};

Thus your map will still prioritize sorting by string length, but it will also distinguish different strings of same size.

Depending on your use case, you can also check other containers like priority_queue or just plain vector with a proper insertion technique.


问:
Using OpenJDK 9 EA with IntelliJ
Right now I'm trying to setup IntelliJ to play around with OpenJDK 9 which I downloaded and installed from here. I got the 64 bit Windows version. I added JDK 9 by going to Project Structure and adding the directory C:\Program Files\Java\jdk-9 as a new SDK. Everything looks great and normal until I try to actually run the program, then this happens.

```<code>Error:Internal error: (java.lang.NoClassDefFoundError) Could not initialize class java.lang.management.ManagementFactory$PlatformMBeanFinder
java.lang.NoClassDefFoundError: Could not initialize class java.lang.management.ManagementFactory$PlatformMBeanFinder
    at java.lang.management.ManagementFactory.getPlatformMXBeans(ManagementFactory.java:684)
    at java.lang.management.ManagementFactory.getMemoryPoolMXBeans(ManagementFactory.java:392)
    at com.intellij.openapi.util.LowMemoryWatcher.<clinit>(LowMemoryWatcher.java:84)
    at com.intellij.util.io.PersistentHashMap.<init>(PersistentHashMap.java:118)
    at com.intellij.util.io.PersistentHashMap.<init>(PersistentHashMap.java:126)
    at org.jetbrains.jps.incremental.storage.AbstractStateStorage.createMap(AbstractStateStorage.java:136)
    at org.jetbrains.jps.incremental.storage.AbstractStateStorage.<init>(AbstractStateStorage.java:41)
    at org.jetbrains.jps.incremental.storage.TimestampStorage.<init>(TimestampStorage.java:36)
    at org.jetbrains.jps.incremental.storage.ProjectTimestamps.<init>(ProjectTimestamps.java:36)
    at org.jetbrains.jps.cmdline.BuildRunner.load(BuildRunner.java:90)
    at org.jetbrains.jps.cmdline.BuildSession.runBuild(BuildSession.java:266)
    at org.jetbrains.jps.cmdline.BuildSession.run(BuildSession.java:125)
    at org.jetbrains.jps.cmdline.BuildMain$MyMessageHandler$1.run(BuildMain.java:232)
    at org.jetbrains.jps.service.impl.SharedThreadPoolImpl$1.run(SharedThreadPoolImpl.java:44)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:514)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1158)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:632)
    at java.lang.Thread.run(Thread.java:804)
</code>```

Has anyone else ran across this issue and found a way to use JDK 9 with IntelliJ?

答:
Maybe you have to try an older version of jdk. I have the same problem with you and I select an older version of jdk in IntelliJ.
But I still have problem installing Eclipse with java 9-ea. this is my post:With java 9 ea, Eclipse fails to install and show error "An error has occurred, see the log file null"

Title: Using OpenJDK 9 EA with IntelliJ

Body:
Right now I'm trying to setup IntelliJ to play around with OpenJDK 9 which I downloaded and installed from here. I got the 64 bit Windows version. I added JDK 9 by going to Project Structure and adding the directory C:\Program Files\Java\jdk-9 as a new SDK. Everything looks great and normal until I try to actually run the program, then this happens.

Error:Internal error: (java.lang.NoClassDefFoundError) Could not initialize class java.lang.management.ManagementFactory$PlatformMBeanFinder
java.lang.NoClassDefFoundError: Could not initialize class java.lang.management.ManagementFactory$PlatformMBeanFinder
    at java.lang.management.ManagementFactory.getPlatformMXBeans(ManagementFactory.java:684)
    at java.lang.management.ManagementFactory.getMemoryPoolMXBeans(ManagementFactory.java:392)
    at com.intellij.openapi.util.LowMemoryWatcher.<clinit>(LowMemoryWatcher.java:84)
    at com.intellij.util.io.PersistentHashMap.<init>(PersistentHashMap.java:118)
    at com.intellij.util.io.PersistentHashMap.<init>(PersistentHashMap.java:126)
    at org.jetbrains.jps.incremental.storage.AbstractStateStorage.createMap(AbstractStateStorage.java:136)
    at org.jetbrains.jps.incremental.storage.AbstractStateStorage.<init>(AbstractStateStorage.java:41)
    at org.jetbrains.jps.incremental.storage.TimestampStorage.<init>(TimestampStorage.java:36)
    at org.jetbrains.jps.incremental.storage.ProjectTimestamps.<init>(ProjectTimestamps.java:36)
    at org.jetbrains.jps.cmdline.BuildRunner.load(BuildRunner.java:90)
    at org.jetbrains.jps.cmdline.BuildSession.runBuild(BuildSession.java:266)
    at org.jetbrains.jps.cmdline.BuildSession.run(BuildSession.java:125)
    at org.jetbrains.jps.cmdline.BuildMain$MyMessageHandler$1.run(BuildMain.java:232)
    at org.jetbrains.jps.service.impl.SharedThreadPoolImpl$1.run(SharedThreadPoolImpl.java:44)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:514)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1158)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:632)
    at java.lang.Thread.run(Thread.java:804)

Has anyone else ran across this issue and found a way to use JDK 9 with IntelliJ?


问:
Redirect one page to another with parameters via htaccess
I want to redirect from a page to another with parameters with htaccess.

For example:

From: www.websitename.co.uk/mylink.php?u=*username*

To: www.websitename.co.uk/mylink/*username*

I tried this but it's not working.

```<code>RewriteEngine on
RewriteRule www.websitename.co.uk/mylink.php?u=*username* www.websitename.co.uk/mylink/*username* [R=301]
</code>```

Where am I doing wrong?

答:
Working fine for me , hope this will work fine.</p>

```<code>RewriteEngine on
RewriteCond %{REQUEST_URI} ^/mylink\.php$
RewriteCond %{QUERY_STRING} u=([a-zA-Z]+)
RewriteRule .* http://websitename.co.uk/mylink/%1? [R=301]
</code>```

Body:
I want to redirect from a page to another with parameters with htaccess.

For example:

From: www.websitename.co.uk/mylink.php?u=*username*

To: www.websitename.co.uk/mylink/*username*

I tried this but it's not working.

RewriteEngine on
RewriteRule www.websitename.co.uk/mylink.php?u=*username* www.websitename.co.uk/mylink/*username* [R=301]

Where am I doing wrong?

Body:
Working fine for me , hope this will work fine.

RewriteEngine on
RewriteCond %{REQUEST_URI} ^/mylink\.php$
RewriteCond %{QUERY_STRING} u=([a-zA-Z]+)
RewriteRule .* http://websitename.co.uk/mylink/%1? [R=301]


问:
Learn C# on mac?
Is mono the only route , any specific visual studio like editors that you recommend?</p>

答:
Mono is pretty much your only route right now, though there are incessant rumours (I wouldn't give much thought to them, though) that Microsoft is planning to port C# to Mac in the future.  I'd be very surprised if that happened, though.

As for IDEs, I can't help there... If I want C#, I stick to Visual Studio (run it through Parallels or BootCamp, if you really want to use VS).

Edit: As Graham points out, there is Cocoa#, but I'd caution that simply because the project has stalled, and there's unlikely to be much future for it. :(

Title: Learn C# on mac?

OwnerDisplayName: James Burgess


问:
Something wrong in c++ code
Please what wrong in this code:

```<code>#include <iostream>
#include <vector>

unsigned __int32 ConvertToChars(std::vector<int> container, char** pChars)
{
    *pChars = (char*)&container[0];

    return container.size() * sizeof(int);
}

void ConvertToIntegers(char* chars, short size, std::vector<int>& container)
{
    int count = size / sizeof(int);

    int* pIntegers = (int*)chars;

    for(int i=0; i < count; ++i)
    {
        container.push_back(*(pIntegers++));
    }
}

void Print(const std::vector<int>& container)
{
    for(int i=0; i < container.size(); ++i)
    {
        std::cout << container[i] << std::endl;
    }
}

void main()
{
    std::vector<int> vec1;

    vec1.push_back(1);
    vec1.push_back(2);
    vec1.push_back(3);

    char* buffer = 0;

    short bufferSize = ConvertToChars(vec1, &buffer);

    std::vector<int> vec2;

    ConvertToIntegers(buffer, bufferSize, vec2);

    Print(vec2);

    char c;

    std::cin >> c;
}
</code>```

function Print prints values:

-572662307

-842150451

-572662307

Thank you!!!

答:
I don't really understand the point of your program, but part of your problem is in your ConvertToIntegers function, where you make your program interpret a char * as int *.

```<code>int* pIntegers = (int*)chars;

for(int i=0; i < count; ++i)
{
    container.push_back(*(pIntegers++));
}
</code>```

You're interpreting the underlying bytes as int types, which could lead to the numbers you're seeing. I'm surprised you're not running into segmentation faults as this would cause you to overstep the block of the memory pointed to by the original char *.

Title: Something wrong in c++ code

Body:
Please what wrong in this code:

#include <iostream>
#include <vector>

unsigned __int32 ConvertToChars(std::vector<int> container, char** pChars)
{
    *pChars = (char*)&container[0];

    return container.size() * sizeof(int);
}

void ConvertToIntegers(char* chars, short size, std::vector<int>& container)
{
    int count = size / sizeof(int);

    int* pIntegers = (int*)chars;

    for(int i=0; i < count; ++i)
    {
        container.push_back(*(pIntegers++));
    }
}

void Print(const std::vector<int>& container)
{
    for(int i=0; i < container.size(); ++i)
    {
        std::cout << container[i] << std::endl;
    }
}

void main()
{
    std::vector<int> vec1;

    vec1.push_back(1);
    vec1.push_back(2);
    vec1.push_back(3);

    char* buffer = 0;

    short bufferSize = ConvertToChars(vec1, &buffer);

    std::vector<int> vec2;

    ConvertToIntegers(buffer, bufferSize, vec2);

    Print(vec2);

    char c;

    std::cin >> c;
}

function Print prints values:

-572662307

-842150451

-572662307

Thank you!!!

Body:
I don't really understand the point of your program, but part of your problem is in your ConvertToIntegers function, where you make your program interpret a char * as int *.

int* pIntegers = (int*)chars;

for(int i=0; i < count; ++i)
{
    container.push_back(*(pIntegers++));
}

You're interpreting the underlying bytes as int types, which could lead to the numbers you're seeing. I'm surprised you're not running into segmentation faults as this would cause you to overstep the block of the memory pointed to by the original char *.


问:
Incrementer not working inside string replace
I'm attempting to read a line from a file (csv header) and create a column list that prepends "c[num]_" in front of each column with this code:

```<code>int colCount=0;
string line = "col1,col2,col3,col4,col5";
string ColumnList = "([" + (++colCount).ToString() + "_" + line.Replace(",", "],[c" + (++colCount).ToString() + "_") + "]";
</code>```

I know it's not elegant, but I'm also not sure why my colCount variable doesn't increment inside the replace??  It results with a string like:

```<code>([c0_col1],[c1_col2],[c1_col3],[c1_col4],[c1_col5])
</code>```

The counter increments the first time and then not again inside the replace.  Any insights? I think it might be better written with a Regex ReplaceEvaluator but I haven't been able to piece that together yet either.

答:
The paramter of the Replace method is string, and the expression you've entered there is just a string. The count will always be 2. It's not a Func, it a string.

You can use the following Linq to easily achieve the conversion you'd like:

```<code>string ColumnList = string.Join(",", line.Split(',').Select((s, i) => $"[c{i + 1}_{s}]"));
</code>```

Body:
I'm attempting to read a line from a file (csv header) and create a column list that prepends "c[num]_" in front of each column with this code:

int colCount=0;
string line = "col1,col2,col3,col4,col5";
string ColumnList = "([" + (++colCount).ToString() + "_" + line.Replace(",", "],[c" + (++colCount).ToString() + "_") + "]";

I know it's not elegant, but I'm also not sure why my colCount variable doesn't increment inside the replace??  It results with a string like:

([c0_col1],[c1_col2],[c1_col3],[c1_col4],[c1_col5])

The counter increments the first time and then not again inside the replace.  Any insights? I think it might be better written with a Regex ReplaceEvaluator but I haven't been able to piece that together yet either.

Body:
The paramter of the Replace method is string, and the expression you've entered there is just a string. The count will always be 2. It's not a Func, it a string.

You can use the following Linq to easily achieve the conversion you'd like:

string ColumnList = string.Join(",", line.Split(',').Select((s, i) => $"[c{i + 1}_{s}]"));


问:
I need to split an array of data into cells in excel
I have a spreadsheet that queries a data source and returns an array of about 230 rows of comma separated results. The data looks like this:

I need to have all those comma separated values that are now in one cell (column B) split into separate cells. There are typically 21 results for each row. So the result should look like this:

The row the data starts on could vary, but typically starts around row 80. The top rows are used for displaying results from the data below it. The starting point could be fixed at say row 120 (if that makes scripting easier), which would leave plenty of room for future dev.

I've tried modifying a few different solutions I've found on here, but none worked. Any help is supremely appreciated!

答:
Thanks all for the help and pointing in the right direction. Here's what I've ended up using:

```<code>Sub Expand_Array_On_New_Sheet

'  First check that new sheet name doesn't already exist, and create sheet

   Sheet_name_to_create = Sheet10.Range("B1").Value
   If WorksheetExists2(Sheet10.Range("B1")) Then
      MsgBox "Sheet name already exists"
  Exit Sub
  Else
    Sheets.Add After:=Sheets(1)
    ActiveSheet.Name = Sheet_name_to_create
  End If

'  Copy array data to new sheet

    Worksheets("Lookup").Range("A11:B250").Copy
    Range("A101").Select
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _ :=False, Transpose:=False
    Application.CutCopyMode = False

'  Expand Array Data into Columns and do some formatting

   Range("B101:B350").Select
   Selection.TextToColumns Destination:=Range("C101"), DataType:=xlDelimited, _
       TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=False, _
       Semicolon:=False, Comma:=True, Space:=False, Other:=False, OtherChar _
       :=",", FieldInfo:=Array(Array(1, 1), Array(2, 1), Array(3, 1), Array(4, 1), Array(5, 1), Array(6, 1), Array(7, 1), Array(8, 1), Array(9, 1), Array(10, 1), Array(11, 1), Array(12, 1), Array(13, 1), Array(14, 1), Array(15, 1), Array(16, 1), Array(17, 1), Array(18, 1), Array(19, 1), Array(20, 1), Array(21, 1), Array(22, 1)), TrailingMinusNumbers:=True
   Range("C100").Select
   ActiveCell.FormulaR1C1 = "=R[-98]C[-1]-19"
   Range("D100").Select
   ActiveCell.FormulaR1C1 = "=RC[-1]+1"
   Range("D100").Select
   Selection.AutoFill Destination:=Range("D100:V100"), Type:=xlFillDefault
   Range("W100").Select
   ActiveCell.FormulaR1C1 = "Current"
   Range("C100:W100").Select
   With Selection.Interior
       .Pattern = xlSolid
       .PatternColorIndex = xlAutomatic
       .ThemeColor = xlThemeColorDark1
       .TintAndShade = -0.149998474074526
       .PatternTintAndShade = 0
   End With
   Selection.Font.Bold = True
   With Selection.Borders(xlEdgeBottom)
       .LineStyle = xlContinuous
       .ColorIndex = 0
       .TintAndShade = 0
       .Weight = xlMedium
   End With
   Selection.Borders(xlEdgeRight).LineStyle = xlNone
   Selection.Borders(xlInsideVertical).LineStyle = xlNone
   Selection.Borders(xlInsideHorizontal).LineStyle = xlNone
   Range("B1").Select
End Sub
</code>```

It seems to work well. The lingering issue I'm running into is that if the data set is less than 21 entries (most are 21, but not all), the last column of data ends up at column T or V or something. I need the last entry to always be in column W, and fill backwards. I probably need to search that as a separate question.

Thanks again for all the help!

Body:
Thanks all for the help and pointing in the right direction. Here's what I've ended up using:

Sub Expand_Array_On_New_Sheet

'  First check that new sheet name doesn't already exist, and create sheet

   Sheet_name_to_create = Sheet10.Range("B1").Value
   If WorksheetExists2(Sheet10.Range("B1")) Then
      MsgBox "Sheet name already exists"
  Exit Sub
  Else
    Sheets.Add After:=Sheets(1)
    ActiveSheet.Name = Sheet_name_to_create
  End If

'  Copy array data to new sheet

    Worksheets("Lookup").Range("A11:B250").Copy
    Range("A101").Select
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _ :=False, Transpose:=False
    Application.CutCopyMode = False

'  Expand Array Data into Columns and do some formatting

   Range("B101:B350").Select
   Selection.TextToColumns Destination:=Range("C101"), DataType:=xlDelimited, _
       TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=False, _
       Semicolon:=False, Comma:=True, Space:=False, Other:=False, OtherChar _
       :=",", FieldInfo:=Array(Array(1, 1), Array(2, 1), Array(3, 1), Array(4, 1), Array(5, 1), Array(6, 1), Array(7, 1), Array(8, 1), Array(9, 1), Array(10, 1), Array(11, 1), Array(12, 1), Array(13, 1), Array(14, 1), Array(15, 1), Array(16, 1), Array(17, 1), Array(18, 1), Array(19, 1), Array(20, 1), Array(21, 1), Array(22, 1)), TrailingMinusNumbers:=True
   Range("C100").Select
   ActiveCell.FormulaR1C1 = "=R[-98]C[-1]-19"
   Range("D100").Select
   ActiveCell.FormulaR1C1 = "=RC[-1]+1"
   Range("D100").Select
   Selection.AutoFill Destination:=Range("D100:V100"), Type:=xlFillDefault
   Range("W100").Select
   ActiveCell.FormulaR1C1 = "Current"
   Range("C100:W100").Select
   With Selection.Interior
       .Pattern = xlSolid
       .PatternColorIndex = xlAutomatic
       .ThemeColor = xlThemeColorDark1
       .TintAndShade = -0.149998474074526
       .PatternTintAndShade = 0
   End With
   Selection.Font.Bold = True
   With Selection.Borders(xlEdgeBottom)
       .LineStyle = xlContinuous
       .ColorIndex = 0
       .TintAndShade = 0
       .Weight = xlMedium
   End With
   Selection.Borders(xlEdgeRight).LineStyle = xlNone
   Selection.Borders(xlInsideVertical).LineStyle = xlNone
   Selection.Borders(xlInsideHorizontal).LineStyle = xlNone
   Range("B1").Select
End Sub

It seems to work well. The lingering issue I'm running into is that if the data set is less than 21 entries (most are 21, but not all), the last column of data ends up at column T or V or something. I need the last entry to always be in column W, and fill backwards. I probably need to search that as a separate question.

Thanks again for all the help!


问:
preventing juno-atom from recloning all julia packages
I am new to both julia and atom and trying to set them both up together. I installed juno for atom and am trying to run a julia script. I relocated my package directory for Julia from ~, because at my workplace there is a limit on space in said directory.

how do I make atom recognize the packages are in a different directory?

I am currently working on a CENTOS machine.

答:
Find your .juliarc.jl file, and insert the line

```<code>ENV["JULIA_PKGDIR"] = # your package directory
</code>```

BTW this issue is unrelated to Atom. It is the julia installation that keeps track of the package directory.

Body:
Find your .juliarc.jl file, and insert the line

ENV["JULIA_PKGDIR"] = # your package directory

BTW this issue is unrelated to Atom. It is the julia installation that keeps track of the package directory.


问:
Today button in jQuery Datepicker doesn't work
I'm using jQueryUI Datepicker and show "Today" button.
But it doesn't work. It also doesn't work in demo: http://www.jqueryui.com/demos/datepicker/#buttonbar

I'w want to fill input with today when press this button.

Is it possible to get it working?

答:
You should use the todayBtn option:

```<code>$("...").datepicker({
  todayBtn: "linked"
})
</code>```

(instead of todayBtn: true).

todayBtn

Boolean, “linked”. Default: false

If true or “linked”, displays a “Today” button at the bottom of the
  datepicker to select the current date. If true, the “Today” button
  will only move the current date into view; if “linked”, the current
  date will also be selected.

For more details look at the following link:
http://bootstrap-datepicker.readthedocs.io/en/latest/options.html#todaybtn

Body:
You should use the todayBtn option:

$("...").datepicker({
  todayBtn: "linked"
})

(instead of todayBtn: true).

todayBtn

Boolean, “linked”. Default: false

If true or “linked”, displays a “Today” button at the bottom of the
  datepicker to select the current date. If true, the “Today” button
  will only move the current date into view; if “linked”, the current
  date will also be selected.

For more details look at the following link:
http://bootstrap-datepicker.readthedocs.io/en/latest/options.html#todaybtn


问:
MYSQL - Joining Multiple tables with COUNT()
I was asked to create a database for both students' tardiness and school policy's violations.

Now, I have three separate tables:

tbl_ClassList:

```<code>  Student_ID    Student_Name
  1000          Lee, Jonder
  1001          Chow, Stephen
  1002          Kim, Martin
  1003          Johns, Kevin
  1004          Hearfield, Olivia
  1005          Jarrs, Marlon
</code>```

tbl_Tardy:

```<code>  Record_No Student_ID
          1 1001
          2 1001
          3 1000
          4 1003
          5 1002
          6 1003
          7 1001
          8 1001
          9 1002
         10 1004
</code>```

tbl_Violation:

```<code>  Record_No Student_ID
          1 1000
          2 1000
          3 1004
          4 1005
          5 1001
          6 1002
          7 1003
</code>```

What I was asked to do is to generate a list that combines that contains information about the students including his/her ID, name, number of tardiness and the number of violations. Something like this:

```<code>   Student_ID   Student_Name        No. of Tardy    No. of Violation
         1000   Lee, Jonder         1               2
         1001   Chow, Stephen       4               1
         1002   Kim, Martin         2               1
         1003   Johns, Kevin        2               1
         1004   Hearfield, Olivia   1               1
         1005   Jarrs, Marlon       0               1
</code>```

Is there any type of Joins I can use to achieve the output? Please help me.

答:
You can find separate aggregates for tardy and violations inside subqueries and left join them with classlist table. Use coalesce to get zero in case there is no row for tardy/violation.

```<code>select c.*,
    coalesce(t.count_tardy, 0) as no_of_tardy,
    coalesce(v.count_violations, 0) as no_of_violations,
from tbl_classlist c
left join (
    select student_id,
        count(*) as count_tardy
    from tbl_tardy
    group by student_id
    ) t on c.student_id = t.student_id
left join (
    select student_id,
        count(*) as count_violations
    from tbl_violation
    group by student_id
    ) v on c.student_id = v.student_id;
</code>```

Body:
I was asked to create a database for both students' tardiness and school policy's violations.

Now, I have three separate tables:

tbl_ClassList:

  Student_ID    Student_Name
  1000          Lee, Jonder
  1001          Chow, Stephen
  1002          Kim, Martin
  1003          Johns, Kevin
  1004          Hearfield, Olivia
  1005          Jarrs, Marlon

tbl_Tardy:

  Record_No Student_ID
          1 1001
          2 1001
          3 1000
          4 1003
          5 1002
          6 1003
          7 1001
          8 1001
          9 1002
         10 1004

tbl_Violation:

  Record_No Student_ID
          1 1000
          2 1000
          3 1004
          4 1005
          5 1001
          6 1002
          7 1003

What I was asked to do is to generate a list that combines that contains information about the students including his/her ID, name, number of tardiness and the number of violations. Something like this:

   Student_ID   Student_Name        No. of Tardy    No. of Violation
         1000   Lee, Jonder         1               2
         1001   Chow, Stephen       4               1
         1002   Kim, Martin         2               1
         1003   Johns, Kevin        2               1
         1004   Hearfield, Olivia   1               1
         1005   Jarrs, Marlon       0               1

Is there any type of Joins I can use to achieve the output? Please help me.

Body:
You can find separate aggregates for tardy and violations inside subqueries and left join them with classlist table. Use coalesce to get zero in case there is no row for tardy/violation.

select c.*,
    coalesce(t.count_tardy, 0) as no_of_tardy,
    coalesce(v.count_violations, 0) as no_of_violations,
from tbl_classlist c
left join (
    select student_id,
        count(*) as count_tardy
    from tbl_tardy
    group by student_id
    ) t on c.student_id = t.student_id
left join (
    select student_id,
        count(*) as count_violations
    from tbl_violation
    group by student_id
    ) v on c.student_id = v.student_id;


问:
How to add a property to favorites in Android Studio design preview?
I see a favorites section but no option to add a property there. Using Android Studio version 2.3.</p>

答:
Go to the All Properties section, and click on the Star icon that appears when you hoover the mouse over the left side of the property name.

You can find more information here


问:
Cannot get data from related models in Rails
I have 2 models in different namespace.

```<code>class Admin::Membership < ActiveRecord::Base
  has_many :authorization_roles
end

class AuthorizationRole < ActiveRecord::Base
  belongs_to :membership
end
</code>```

The Membership model is in different folder with AuthorizationRole model (I don't know what is called)

When run Admin::Membership.find(:all), the data from AuthorizationRole model is not included. I've create membership_id field on authorization_roles table, but I still can't get both models related. Is something wrong in this code? Sorry if I'm missing something basic here.

答:
Try this</p>

```<code>class Admin::Membership < ActiveRecord::Base
  has_many :authorization_roles, :class_name => '::AuthorizationRole'
end

class AuthorizationRole < ActiveRecord::Base
  belongs_to :membership, :class_name => 'Admin::Membership'
end
</code>```

Body:
I have 2 models in different namespace.

class Admin::Membership < ActiveRecord::Base
  has_many :authorization_roles
end

class AuthorizationRole < ActiveRecord::Base
  belongs_to :membership
end

The Membership model is in different folder with AuthorizationRole model (I don't know what is called)

When run Admin::Membership.find(:all), the data from AuthorizationRole model is not included. I've create membership_id field on authorization_roles table, but I still can't get both models related. Is something wrong in this code? Sorry if I'm missing something basic here.

Body:
Try this

class Admin::Membership < ActiveRecord::Base
  has_many :authorization_roles, :class_name => '::AuthorizationRole'
end

class AuthorizationRole < ActiveRecord::Base
  belongs_to :membership, :class_name => 'Admin::Membership'
end