答:
You can write query like this

```<code>SELECT a.name,
GROUP_CONCAT(LNr1.LID SEPARATOR '-') AS LNr1,
GROUP_CONCAT(LNr2.LID SEPARATOR '-') AS LNr2,
GROUP_CONCAT(LNr3.LID SEPARATOR '-') AS LNr3,
GROUP_CONCAT(LNr4.LID SEPARATOR '-') AS LNr4,
GROUP_CONCAT(LNr5.LID SEPARATOR '-') AS LNr5,
GROUP_CONCAT(LNr6.LID SEPARATOR '-') AS LNr6,
GROUP_CONCAT(LNr7.LID SEPARATOR '-') AS LNr7,
GROUP_CONCAT(LNr8.LID SEPARATOR '-') AS LNr8,
GROUP_CONCAT(LNr9.LID SEPARATOR '-') AS LNr9,
GROUP_CONCAT(LNr10.LID SEPARATOR '-') AS LNr10
FROM klz AS a
LEFT JOIN klz AS LNr1 ON LNr1.LNr = 1 AND a.id = LNr1.id
LEFT JOIN klz AS LNr2 ON LNr2.LNr = 2 AND a.id = LNr2.id
LEFT JOIN klz AS LNr3 ON LNr3.LNr = 3 AND a.id = LNr3.id
LEFT JOIN klz AS LNr4 ON LNr4.LNr = 4 AND a.id = LNr4.id
LEFT JOIN klz AS LNr5 ON LNr5.LNr = 5 AND a.id = LNr5.id
LEFT JOIN klz AS LNr6 ON LNr6.LNr = 6 AND a.id = LNr6.id
LEFT JOIN klz AS LNr7 ON LNr7.LNr = 7 AND a.id = LNr7.id
LEFT JOIN klz AS LNr8 ON LNr8.LNr = 8 AND a.id = LNr8.id
LEFT JOIN klz AS LNr9 ON LNr9.LNr = 9 AND a.id = LNr9.id
LEFT JOIN klz AS LNr10 ON LNr10.LNr = 10 AND a.id = LNr10.id
GROUP BY a.name;
</code>```

Hope this helps.

Body:
You can write query like this

SELECT a.name,
GROUP_CONCAT(LNr1.LID SEPARATOR '-') AS LNr1,
GROUP_CONCAT(LNr2.LID SEPARATOR '-') AS LNr2,
GROUP_CONCAT(LNr3.LID SEPARATOR '-') AS LNr3,
GROUP_CONCAT(LNr4.LID SEPARATOR '-') AS LNr4,
GROUP_CONCAT(LNr5.LID SEPARATOR '-') AS LNr5,
GROUP_CONCAT(LNr6.LID SEPARATOR '-') AS LNr6,
GROUP_CONCAT(LNr7.LID SEPARATOR '-') AS LNr7,
GROUP_CONCAT(LNr8.LID SEPARATOR '-') AS LNr8,
GROUP_CONCAT(LNr9.LID SEPARATOR '-') AS LNr9,
GROUP_CONCAT(LNr10.LID SEPARATOR '-') AS LNr10
FROM klz AS a
LEFT JOIN klz AS LNr1 ON LNr1.LNr = 1 AND a.id = LNr1.id
LEFT JOIN klz AS LNr2 ON LNr2.LNr = 2 AND a.id = LNr2.id
LEFT JOIN klz AS LNr3 ON LNr3.LNr = 3 AND a.id = LNr3.id
LEFT JOIN klz AS LNr4 ON LNr4.LNr = 4 AND a.id = LNr4.id
LEFT JOIN klz AS LNr5 ON LNr5.LNr = 5 AND a.id = LNr5.id
LEFT JOIN klz AS LNr6 ON LNr6.LNr = 6 AND a.id = LNr6.id
LEFT JOIN klz AS LNr7 ON LNr7.LNr = 7 AND a.id = LNr7.id
LEFT JOIN klz AS LNr8 ON LNr8.LNr = 8 AND a.id = LNr8.id
LEFT JOIN klz AS LNr9 ON LNr9.LNr = 9 AND a.id = LNr9.id
LEFT JOIN klz AS LNr10 ON LNr10.LNr = 10 AND a.id = LNr10.id
GROUP BY a.name;

Hope this helps.


来源: stackexchange

问:
Send Smiley/Emoticons in email using javax.mail
I am trying to send smiley with text in email sent using javax.mail API.

When I sysout the unicode after unescaping, it gives correct smiley on console but in mail it displays "?" (question mark).

Here's how I am trying to do it:

Unicode String : \u0048\u0069\u0020\uD83D\uDE0A\uD83D\uDE00\uD83D\uDE01\uD83D\uDE02

```<code>String uniMessage = "\u0048\u0069\u0020\uD83D\uDE0A\uD83D\uDE00\uD83D\uDE01\uD83D\uDE02";
String message = StringEscapeUtils.unescapeJava(uniMessage);
</code>```

Sysout prints correct message on console as "Hi " whereas in email it is displayed as "Hi ????".

Properties props = new Properties();

```<code>        props.put("mail.smtp.auth", "true");
        props.setProperty("mail.transport.protocol", "smtp");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.host", SMTPHost);
        props.put("mail.smtp.port", SMTPPort);
        props.put("mail.smtp.user", username);
        props.put("mail.smtp.password", password);
        props.put("mail.smtp.socketFactory.port", SMTPPort);
        props.put("mail.smtp.socketFactory.fallback", "true");

        Session session = Session.getInstance(props,
                new javax.mail.Authenticator() {
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(username,
                                password);
                    }
                });
        session.setDebug(debug);
        Message msg = new MimeMessage(session);
        InternetAddress addressFrom = new InternetAddress(username);
        msg.setFrom(addressFrom);
        InternetAddress addressTo = new InternetAddress(to);
        addressTo = new InternetAddress(to);
        msg.setRecipient(Message.RecipientType.TO, addressTo);
        msg.addHeader("Demo", "Demo");
        msg.setSubject(subject);
        msg.setContent(message, "text/html");
        Transport.send(msg);
</code>```

Above is my mail service. How do I send smiley/emoticons correctly in email?
Please help.

答:
It was done as suggested by @RealSkeptic as follow:</p>

```<code>msg.setContent(StringEscapeUtils.unescapeJava(message), "text/html; charset=UTF-8");
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to send smiley with text in email sent using javax.mail API.

When I sysout the unicode after unescaping, it gives correct smiley on console but in mail it displays "?" (question mark).

Here's how I am trying to do it:

Unicode String : \u0048\u0069\u0020\uD83D\uDE0A\uD83D\uDE00\uD83D\uDE01\uD83D\uDE02

String uniMessage = "\u0048\u0069\u0020\uD83D\uDE0A\uD83D\uDE00\uD83D\uDE01\uD83D\uDE02";
String message = StringEscapeUtils.unescapeJava(uniMessage);

Sysout prints correct message on console as "Hi " whereas in email it is displayed as "Hi ????".

Properties props = new Properties();

        props.put("mail.smtp.auth", "true");
        props.setProperty("mail.transport.protocol", "smtp");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.host", SMTPHost);
        props.put("mail.smtp.port", SMTPPort);
        props.put("mail.smtp.user", username);
        props.put("mail.smtp.password", password);
        props.put("mail.smtp.socketFactory.port", SMTPPort);
        props.put("mail.smtp.socketFactory.fallback", "true");

        Session session = Session.getInstance(props,
                new javax.mail.Authenticator() {
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(username,
                                password);
                    }
                });
        session.setDebug(debug);
        Message msg = new MimeMessage(session);
        InternetAddress addressFrom = new InternetAddress(username);
        msg.setFrom(addressFrom);
        InternetAddress addressTo = new InternetAddress(to);
        addressTo = new InternetAddress(to);
        msg.setRecipient(Message.RecipientType.TO, addressTo);
        msg.addHeader("Demo", "Demo");
        msg.setSubject(subject);
        msg.setContent(message, "text/html");
        Transport.send(msg);

Above is my mail service. How do I send smiley/emoticons correctly in email?
Please help.

Body:
It was done as suggested by @RealSkeptic as follow:

msg.setContent(StringEscapeUtils.unescapeJava(message), "text/html; charset=UTF-8");


问:
Unable to get readable class labels for Inception-ResNet-v2 model
I am using Inception-ResNet-v2 pretrained version to classify the images. I need human-readable class labels for this. I found one in following site: https://gist.github.com/yrevar/942d3a0ac09ec9e5eb3a.

However, when I try to validate these labels with the images, I find it doesn't map to correct labels. One such instance is I tried to classify "Panda" image- the class label it matches is : "barracouta, snoek" with score - 0.927924 and "giant panda, panda, panda bear, coon bear, Ailuropoda melanoleuca" with score - 0.001053.

Please provide me a source where I can find correct mappings of class label to human-readable text for this model.

答: https://gist.github.com/yrevar/942d3a0ac09ec9e5eb3a this human readable label works, but initialize the class label list with an "unused background", before loading these labels, as inception resnet v2 model is trained for 1001 classes and this has 1000.</p>


问:
C++ error: expected ',' or ';' before '{' token when their is
I am trying to create a function that will return the alphabet position of a letter that is passed into the function
for example

```<code>cout<<getPosition('l')
</code>```

would return the integer 12. I am fairly certain I have got the logic correct however I am having some trouble with the syntax. I found many similar questions however I still was not able to solve the problem.
Any help appreciated

```<code>#include <iostream>
using namespace std;

int getPosition(letter)
{
    int pos = 0;
    const char alphabet[26]={'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
    for (int counter=0; counter!=26; counter++)
    {
        if (alphabet[counter] == letter)
        {
            pos = counter;
            break;
        }
    }
    return pos;
}

int main()
{
    string letter = 'r';
    cout << posInAlpha(letter);
    return 0;
}
</code>```

答:
it all begins here

```<code>int getPosition(letter)
{
</code>```

this function is not right declared/defined, letter must be a type and you just gave none...

assuming this

```<code>char letter = 'r';
cout << posInAlpha(letter);
</code>```

that letter must be a char and the function posInAlpha should be renamed to getPosition

it all looks like you are mixing std::strings and chars,

your final fixed code should look like:

```<code>#include <iostream>
using namespace std;

int getPosition(char& letter)
{
    int pos = 0;
    const char alphabet[26] = { 'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z' };
    for (int counter = 0; counter != 26; counter++)
    {
        if (alphabet[counter] == letter)
        {
            pos = counter;
            break;
        }
    }
    return pos;
}

int main()
{
    char letter = 'r';
    cout << getPosition(letter);
    cin.get();
    return 0;
}
</code>```

which prints 17 for the given char 'r'

Body:
I am trying to create a function that will return the alphabet position of a letter that is passed into the function
for example

cout<<getPosition('l')

would return the integer 12. I am fairly certain I have got the logic correct however I am having some trouble with the syntax. I found many similar questions however I still was not able to solve the problem.
Any help appreciated

#include <iostream>
using namespace std;

int getPosition(letter)
{
    int pos = 0;
    const char alphabet[26]={'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
    for (int counter=0; counter!=26; counter++)
    {
        if (alphabet[counter] == letter)
        {
            pos = counter;
            break;
        }
    }
    return pos;
}

int main()
{
    string letter = 'r';
    cout << posInAlpha(letter);
    return 0;
}

Body:
it all begins here

int getPosition(letter)
{

this function is not right declared/defined, letter must be a type and you just gave none...

assuming this

char letter = 'r';
cout << posInAlpha(letter);

that letter must be a char and the function posInAlpha should be renamed to getPosition

it all looks like you are mixing std::strings and chars,

your final fixed code should look like:

#include <iostream>
using namespace std;

int getPosition(char& letter)
{
    int pos = 0;
    const char alphabet[26] = { 'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z' };
    for (int counter = 0; counter != 26; counter++)
    {
        if (alphabet[counter] == letter)
        {
            pos = counter;
            break;
        }
    }
    return pos;
}

int main()
{
    char letter = 'r';
    cout << getPosition(letter);
    cin.get();
    return 0;
}

which prints 17 for the given char 'r'


问:
$scope variable in function
I  have to take a few pictures in an app, I'm making it with Ionic and Angular.

I have 3 buttons and each has to take a picture.
This is the HTML side:

```<code><img ng-src="{{srcImage1 || 'img/foto_defecto.png'}}" id="takeImage1"
 height="40" width="40" style="margin-right: 7px;" ng-click="Take">

<img ng-src="{{srcImage2 || 'img/foto_defecto.png'}}" id="srcImage2"
height="40" width="40" style="margin-right: 7px;" ng-click="takeImage2">

<img ng-src="{{srcImage3 || 'img/foto_defecto.png'}}" id="srcImage3"
height="40" width="40" style="margin-right: 7px;" ng-click="takeImage3">
</code>```

Doesn't matter I have inline css, it's a test.

And these are the functions: 3 of them, one for each button.

```<code>    $scope.takeImage1 = function() {
      var options = {
        quality: 100,
        destinationType: Camera.DestinationType.DATA_URL,
        sourceType: Camera.PictureSourceType.CAMERA,
        allowEdit: false,
        encodingType: Camera.EncodingType.PNG,
        targetWidth: 250,
        targetHeight: 250,
        popoverOptions: CameraPopoverOptions,
        saveToPhotoAlbum: true
      };

      $cordovaCamera.getPicture(options).then(function(imageData) {
        $scope.srcImage1 = "data:image/PNG;base64," + imageData;

      }, function(err) {
        // error
      });
    }
</code>```

What the function does is: takes the picture, saves it and it'll show a thumbnail under the srcImage1/2/3/etc.

However I want to have just ONE function and call it from each button.

For that I changed the code to this:

the call:

```<code><img ng-src="{{srcImage1 || 'img/foto_defecto.png'}}" id="srcImage1"
height="40" width="40" style="margin-right: 7px;" ng-click="hacerFoto(1)">
</code>```

the function:

```<code> $scope.hacerFoto = function(numero) {
    var options = {
        quality: 100,
        destinationType: Camera.DestinationType.DATA_URL,
        sourceType: Camera.PictureSourceType.CAMERA,
        allowEdit: false,
        encodingType: Camera.EncodingType.PNG,
        targetWidth: 250,
        targetHeight: 250,
        popoverOptions: CameraPopoverOptions,
        saveToPhotoAlbum: true
    };
  var buscar = "srcImage".concat(numero);
  alert(buscar);
  $cordovaCamera.getPicture(options).then(function(imageData) {
        $scope.buscar = "data:image/PNG;base64," + imageData;
  }, function() {
        alert("error al hacer la foto");
  });
}
</code>```

However the $scope.buscar in my intent to make a general function won't update the thumbnail.

The alert(buscar); shows exactly what I'm expecting, however $scope.buscar won't update the image. I don't know why it wouldn't work.

I found a solution to this, which is the next one:

```<code>  $cordovaCamera.getPicture(options).then(function(imageData) {
        var image = document.getElementById('srcImage'+numero);
        image.src = "data:image/PNG;base64," + imageData;
  }, function() {
        alert("error al hacer la foto");
  });
</code>```

Just take the ID with JS and replace the src.
However, the answer from @Vladimir Zdenek is much more elegant and in Angular - so I changed my code to that. I accepted his answear as the correct one.

答:
Try to clear the value of 'imageData' on each time of the function call.

var imageData="";

Title: $scope variable in function

Body:
I  have to take a few pictures in an app, I'm making it with Ionic and Angular.

I have 3 buttons and each has to take a picture.
This is the HTML side:

Doesn't matter I have inline css, it's a test.

And these are the functions: 3 of them, one for each button.

    $scope.takeImage1 = function() {
      var options = {
        quality: 100,
        destinationType: Camera.DestinationType.DATA_URL,
        sourceType: Camera.PictureSourceType.CAMERA,
        allowEdit: false,
        encodingType: Camera.EncodingType.PNG,
        targetWidth: 250,
        targetHeight: 250,
        popoverOptions: CameraPopoverOptions,
        saveToPhotoAlbum: true
      };

      $cordovaCamera.getPicture(options).then(function(imageData) {
        $scope.srcImage1 = "data:image/PNG;base64," + imageData;

      }, function(err) {
        // error
      });
    }

What the function does is: takes the picture, saves it and it'll show a thumbnail under the srcImage1/2/3/etc.

However I want to have just ONE function and call it from each button.

For that I changed the code to this:

the call:

the function:

 $scope.hacerFoto = function(numero) {
    var options = {
        quality: 100,
        destinationType: Camera.DestinationType.DATA_URL,
        sourceType: Camera.PictureSourceType.CAMERA,
        allowEdit: false,
        encodingType: Camera.EncodingType.PNG,
        targetWidth: 250,
        targetHeight: 250,
        popoverOptions: CameraPopoverOptions,
        saveToPhotoAlbum: true
    };
  var buscar = "srcImage".concat(numero);
  alert(buscar);
  $cordovaCamera.getPicture(options).then(function(imageData) {
        $scope.buscar = "data:image/PNG;base64," + imageData;
  }, function() {
        alert("error al hacer la foto");
  });
}

However the $scope.buscar in my intent to make a general function won't update the thumbnail.

The alert(buscar); shows exactly what I'm expecting, however $scope.buscar won't update the image. I don't know why it wouldn't work.

I found a solution to this, which is the next one:

  $cordovaCamera.getPicture(options).then(function(imageData) {
        var image = document.getElementById('srcImage'+numero);
        image.src = "data:image/PNG;base64," + imageData;
  }, function() {
        alert("error al hacer la foto");
  });

Just take the ID with JS and replace the src.
However, the answer from @Vladimir Zdenek is much more elegant and in Angular - so I changed my code to that. I accepted his answear as the correct one.


问:
Adobe AIR. Open app from tray with double click
I've used example from here

App doesn't open with double click.

Works

```<code>SystemTrayIcon(NativeApplication.nativeApplication.icon).addEventListener(MouseEvent.CLICK, unDock);
</code>```

Doesn't work

```<code>SystemTrayIcon(NativeApplication.nativeApplication.icon).addEventListener(MouseEvent.DOUBLE_CLICK, unDock);
</code>```

答:
Thanks J_A_X. :)</p>

```<code>        SystemTrayIcon(NativeApplication.nativeApplication.icon).addEventListener(MouseEvent.CLICK, openWindow);

        private var previousTimeStamp:int;

        private function openWindow(event:Event):void
        {
            var currentTimeStamp:int = getTimer();

            if(currentTimeStamp)
            {
                if(currentTimeStamp - previousTimeStamp < 400)
                {
                    // double click
                    trace("double click");
                }
            }
            previousTimeStamp = getTimer();
        }
</code>```

Body:
I've used example from here

App doesn't open with double click.

Works

SystemTrayIcon(NativeApplication.nativeApplication.icon).addEventListener(MouseEvent.CLICK, unDock);

Doesn't work

SystemTrayIcon(NativeApplication.nativeApplication.icon).addEventListener(MouseEvent.DOUBLE_CLICK, unDock);

Body:
Thanks J_A_X. :)

        SystemTrayIcon(NativeApplication.nativeApplication.icon).addEventListener(MouseEvent.CLICK, openWindow);

        private var previousTimeStamp:int;

        private function openWindow(event:Event):void
        {
            var currentTimeStamp:int = getTimer();

            if(currentTimeStamp)
            {
                if(currentTimeStamp - previousTimeStamp < 400)
                {
                    // double click
                    trace("double click");
                }
            }
            previousTimeStamp = getTimer();
        }


答:
You are mixing std::string and char, while you don't need the first. Moreover, your main() uses a function not declared. Furthermore, your function's parameter lacks it's type. Your compiler should be pretty explanatory for these. I modified your code to get the desired behavior; please take a moment or two understanding what had to be modified here:

```<code>#include <iostream>
using namespace std;

// Returns the index of 'letter' in alphabet, or -1 if not found.
int getPosition(char letter)
{
    int pos = -1;
    const char alphabet[26]={'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
    for (int counter=0;counter!=26;counter++)
    {
        if (alphabet[counter]==letter)
        {
            pos=counter;
            break;
        }
    }
    return pos;
}

int main()
{
    char letter='r';
    cout<<getPosition(letter);
    return 0;
}
</code>```

Output:

17

I initialized pos to -1, in case letter does not belong in the alphabet. Otherwise the function would return 0, meaning that a was the answer.

PS: If letter was an std::string, then your comparison with every letter of the alphabet would produce a compilation error, since the types do not match.

Title: C++ error: expected ',' or ';' before '{' token when their is

Body:
You are mixing std::string and char, while you don't need the first. Moreover, your main() uses a function not declared. Furthermore, your function's parameter lacks it's type. Your compiler should be pretty explanatory for these. I modified your code to get the desired behavior; please take a moment or two understanding what had to be modified here:

#include <iostream>
using namespace std;

// Returns the index of 'letter' in alphabet, or -1 if not found.
int getPosition(char letter)
{
    int pos = -1;
    const char alphabet[26]={'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
    for (int counter=0;counter!=26;counter++)
    {
        if (alphabet[counter]==letter)
        {
            pos=counter;
            break;
        }
    }
    return pos;
}

int main()
{
    char letter='r';
    cout<<getPosition(letter);
    return 0;
}

Output:

17

I initialized pos to -1, in case letter does not belong in the alphabet. Otherwise the function would return 0, meaning that a was the answer.

PS: If letter was an std::string, then your comparison with every letter of the alphabet would produce a compilation error, since the types do not match.


问:
Disable F5 key in Safari 4
I have written the following Javascript code to catch F5 key press and prevent the user from refreshing:

(I understand this is not a good idea but I am stuck with this whether any one likes it or not. Also the question I ask pertains to why the script below does not work with Safari 4 but works for other browsers.)

```<code>var fn = function (e)
{

    if (!e)
        var e = window.event;

    var keycode = e.keyCode;
    if (e.which)
        keycode = e.which;

    var src = e.srcElement;
    if (e.target)
        src = e.target;

    // 116 = F5
    if (116 == keycode)
    {
        // Firefox and other non IE browsers
        if (e.preventDefault)
        {
            e.preventDefault();
            e.stopPropagation();
        }
        // Internet Explorer
        else if (e.keyCode)
        {
            e.keyCode = 0;
            e.returnValue = false;
            e.cancelBubble = true;
        }

        return false;
    }
}

// Assign function to onkeydown event
document.onkeydown = fn;
</code>```

The above code works perfectly for IE 6,7 and 8, from Firefox 2.0 onwards and also in Chrome.

However it does not work for Safari 4 for windows. Pressing the F5 key refreshes the document. The funny thing is that in Safari the code gets inside the if (e.preventDefault) part above but for some reason its not preventing the default action i.e. refreshing the page.

Is this a bug with Safari 4 or is there some Safari specific code I need to write?

答: I had a logic to handle the F5 similar to the question.I am displaying a confirm box which asks "Data you have entered may not be saved?".If the the user click Ok, page should reload and if click Cancel, page need to retain as it is. But only in safari "Cancel" click also reload the page. I have tested in Safari 5.1.7.

OwnerDisplayName: Scripter

ContentLicense: CC BY-SA 4.0

Title: Disable F5 key in Safari 4

Body:
I have written the following Javascript code to catch F5 key press and prevent the user from refreshing:

(I understand this is not a good idea but I am stuck with this whether any one likes it or not. Also the question I ask pertains to why the script below does not work with Safari 4 but works for other browsers.)

var fn = function (e)
{

    if (!e)
        var e = window.event;

    var keycode = e.keyCode;
    if (e.which)
        keycode = e.which;

    var src = e.srcElement;
    if (e.target)
        src = e.target;

    // 116 = F5
    if (116 == keycode)
    {
        // Firefox and other non IE browsers
        if (e.preventDefault)
        {
            e.preventDefault();
            e.stopPropagation();
        }
        // Internet Explorer
        else if (e.keyCode)
        {
            e.keyCode = 0;
            e.returnValue = false;
            e.cancelBubble = true;
        }

        return false;
    }
}

// Assign function to onkeydown event
document.onkeydown = fn;

The above code works perfectly for IE 6,7 and 8, from Firefox 2.0 onwards and also in Chrome.

However it does not work for Safari 4 for windows. Pressing the F5 key refreshes the document. The funny thing is that in Safari the code gets inside the if (e.preventDefault) part above but for some reason its not preventing the default action i.e. refreshing the page.

Is this a bug with Safari 4 or is there some Safari specific code I need to write?


答:
Start with this query

```<code>SELECT
    Name AS tableRows,
    LNr AS tableCols,
    GROUP_CONCAT(LID ORDER BY LID SEPARATOR ' - ') AS cellValue
FROM klz
GROUP BY 1,2
ORDER BY 1,2;
</code>```

Now put the results in an array.
Also, get every distinct column (LNr) and row (Name) in other arrays.

```<code>$ar = array();
$tableRows = array();
$tableCols = array();

while($row = mysqli_fetch_array($klz, MYSQL_ASSOC)){
    $ar[$row['tableRows']][$row['tableCols']] = $row['cellValue'];
    $tableRows[] = $row['tableRows'];
    $tableCols[] = $row['tableCols'];
}

$tableRows = array_unique($tableRows);
$tableCols = array_unique($tableCols);
</code>```

sort the 2 arrays with rows and columns

```<code>sort($tableRows);
sort($tableCols);
</code>```

foreach row, foreach column, echo value of the multi array

```<code>echo "<table>";
echo "<tr><th>Name</th>";

foreach($tableCols as $x){
    echo "<th>LNr$x</th>";
}

echo "</tr>";

foreach($tableRows as $y){
    echo "<tr><td>$y</td>";
    foreach($tableCols as $x){
        echo "<td>" . $ar[$y][$x] . "</td>";
    }
    echo "</tr>";
}
echo "</table>";
</code>```

Title: Putting more than one MySQL Row in a column

Body:
the problem that i've is, that I have a Table in my Database and want to fetch some of the rows of this table in one column.

For example I've this table names klz:

|-------+-----------+-----+-----|
| ID    | Name      | LNr | LID |
|-------+-----------+-----+-----|
| 1     | 0000_01   | 1   | 16  |
| 2     | 0000_01   | 2   | 35  |
| 3     | 0000_02   | 1   | 16  |
| 4     | 0000_02   | 2   | 35  |
| 5     | 0000_10   | 1   | 18  |
| ..    | ..        | ..  | ..  |
| 297   | 0214_01   | 1   | 23  |
| 298   | 0214_01   | 1   | 66  |
| 299   | 0214_01   | 2   | 24  |
| 300   | 0214_01   | 2   | 67  |
| 301   | 0214_01   | 3   | 26  |
| 302   | 0214_01   | 4   | 28  |
| 303   | 0214_01   | 4   | 69  |
| 304   | 0214_01   | 5   | 30  |
| 305   | 0214_01   | 5   | 70  |
| 306   | 0214_01   | 6   | 31  |
| 307   | 0214_01   | 6   | 71  |
|-------+-----------+-----+-----|

If I fetch this table with a while-loop in PHP I would get the same table.

So what I want to have is a table like this:

|-----------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------|
| Name      | LNr1    | LNr2    | LNr3    | LNr4    | LNr5    | LNr6    | LNr7    | LNr8    | LNr9    | LNr10   |
|-----------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------|
| 0000_01   | 16      | 35      |         |         |         |         |         |         |         |         |
| 0000_02   | 16      | 35      |         |         |         |         |         |         |         |         |
| 0000_10   | 18      |         |         |         |         |         |         |         |         |         |
| 0214_01   | 23 - 66 | 24      | 26 - 68 | 28 - 69 | 30 - 70 | 31 - 71 |         |         |         |         |
|-----------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------|

This table have the column Name and an enumeration of the possible LNr from 1 to 10 as columns. The data inside the LNr columns arethe LIDs from the table above.

My Question is, how can I put in dependency of the Name and the LNr, the LIDs in the right columns?
In this table you have listed all Names once and set for all LNr the right LID.

Here is the Code I'm trying to do this with... Until now it works only for the first LNr column, to write the LID in:

<?php
  include "dbconnect.php";

  $klz = mysqli_query($db, "SELECT      *
                            FROM        klz;");

?>

           Name
           Leitungsnr 1
           Leitungsnr 2
           Leitungsnr 3
           Leitungsnr 4
           Leitungsnr 5
           Leitungsnr 6
           Leitungsnr 7
           Leitungsnr 8
           Leitungsnr 9
           Leitungsnr 10

<?php
  $name_old = "";
  $lnr_old  = "";
  $name     = [];
  $lnr      = [];
  $lid      = [];

  while($row = mysqli_fetch_array($klz, MYSQL_ASSOC)){
    $name[] = $row['Name'];
    $lnr[] = $row['LNr'];
    $lid[] = $row['LID'];
  }

  for($i=0; $i <= sizeof($name)-1; $i++){

    if($name[$i] != $name_old){

      echo "
";
        echo "". $name[$i] . "	 \n";

        if($lnr[$i] != $lnr_old){
          echo "". $lid[$i] . "	 \n";

          $lnr_old != $lnr[$i];
        }

      echo "
";

      $name_old = $name[$i];
    }
  }
?>

<?php
  mysqli_close($db);
?>

I hope you know what I mean and trying to do. If not feel free to ask please.
Thank you

Body:
Start with this query

SELECT
    Name AS tableRows,
    LNr AS tableCols,
    GROUP_CONCAT(LID ORDER BY LID SEPARATOR ' - ') AS cellValue
FROM klz
GROUP BY 1,2
ORDER BY 1,2;

Now put the results in an array.
Also, get every distinct column (LNr) and row (Name) in other arrays.

$ar = array();
$tableRows = array();
$tableCols = array();

while($row = mysqli_fetch_array($klz, MYSQL_ASSOC)){
    $ar[$row['tableRows']][$row['tableCols']] = $row['cellValue'];
    $tableRows[] = $row['tableRows'];
    $tableCols[] = $row['tableCols'];
}

$tableRows = array_unique($tableRows);
$tableCols = array_unique($tableCols);

sort the 2 arrays with rows and columns

sort($tableRows);
sort($tableCols);

foreach row, foreach column, echo value of the multi array

echo "<table>";
echo "<tr><th>Name</th>";

foreach($tableCols as $x){
    echo "<th>LNr$x</th>";
}

echo "</tr>";

foreach($tableRows as $y){
    echo "<tr><td>$y</td>";
    foreach($tableCols as $x){
        echo "<td>" . $ar[$y][$x] . "</td>";
    }
    echo "</tr>";
}
echo "</table>";


问:
Retrofit 2.2.0 Android API 24 javax.net.ssl.SSLHandshakeException: Handshake failed
I'm using Retrofit 2.2.0 for uploading image to server (using Java). With an Android device (Samsung galaxy S6) API 24 (Build : NRD90M.G920FXXU5EQAC) when I try to post a request, this request failed with this error

```<code>javax.net.ssl.SSLHandshakeException: Handshake failed
</code>```

ps: I try to downgrade the Retrofit 2.1.0 and it works perfectly.

答:
The solution for me was adding more ciphers as acceptable for OkHttpClient. Since API 21, some TLS certificates are deprecated for Android. This might help:

```<code>ConnectionSpec spec = new
ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS)
                .tlsVersions(TlsVersion.TLS_1_2)
                .cipherSuites(
CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
CipherSuite.TLS_DHE_RSA_WITH_AES_128_GCM_SHA256)
                .build();

OkHttpClient client = new OkHttpClient.Builder()
            .connectionSpecs(Collections.singletonList(spec))
            .build();
</code>```

For more info please visit: https://github.com/square/okhttp/wiki/HTTPS

Body:
I'm using Retrofit 2.2.0 for uploading image to server (using Java). With an Android device (Samsung galaxy S6) API 24 (Build : NRD90M.G920FXXU5EQAC) when I try to post a request, this request failed with this error

javax.net.ssl.SSLHandshakeException: Handshake failed

ps: I try to downgrade the Retrofit 2.1.0 and it works perfectly.

Body:
The solution for me was adding more ciphers as acceptable for OkHttpClient. Since API 21, some TLS certificates are deprecated for Android. This might help:

ConnectionSpec spec = new
ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS)
                .tlsVersions(TlsVersion.TLS_1_2)
                .cipherSuites(
CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
CipherSuite.TLS_DHE_RSA_WITH_AES_128_GCM_SHA256)
                .build();

OkHttpClient client = new OkHttpClient.Builder()
            .connectionSpecs(Collections.singletonList(spec))
            .build();

For more info please visit: https://github.com/square/okhttp/wiki/HTTPS


问:
Excel Macro Help - Stacking Macros
I am using the following subroutine to combine multiple Excel files from a single folder into a single workbook with multiple worksheets.

```<code>Sub Merge2MultiSheets()

Dim wbDst As Workbook
Dim wbSrc As Workbook
Dim wsSrc As Worksheet
Dim MyPath As String
Dim strFilename As String

Application.DisplayAlerts = False
Application.EnableEvents = False
Application.ScreenUpdating = False
MyPath = "C:\MyPath" ' <-- Insert Absolute Folder Location
Set wbDst = Workbooks.Add(xlWBATWorksheet)
strFilename = Dir(MyPath & "\*.xls", vbNormal)

If Len(strFilename) = 0 Then Exit Sub

Do Until strFilename = ""
    Set wbSrc = Workbooks.Open(Filename:=MyPath & "\" & strFilename)
    Set wsSrc = wbSrc.Worksheets(1)
    wsSrc.Copy After:=wbDst.Worksheets(wbDst.Worksheets.Count)
    wbSrc.Close False
    strFilename = Dir()
Loop
wbDst.Worksheets(1).Delete

Application.DisplayAlerts = True
Application.EnableEvents = True
Application.ScreenUpdating = True

End Sub
</code>```

The end product is an excel file with multiple worksheets (as well as one blank Sheet 1). I was wondering how I can then apply another macro to this newly created Workbook. As an example, I wish for all the worksheets within this new workbook to have their Headers bold and coloured a certain way, and to have the empty Worksheet deleted.

eg:

```<code>Sub Headers()

Rows("1:1").Select
Selection.Font.Bold = True
With Selection.Interior
    .ColorIndex = 37
    .Pattern = xlSolid
End With
Selection.Borders(xlDiagonalDown).LineStyle = xlNone
Selection.Borders(xlDiagonalUp).LineStyle = xlNone
With Selection.Borders(xlEdgeLeft)
    .LineStyle = xlContinuous
    .Weight = xlThin
    .ColorIndex = xlAutomatic
End With
With Selection.Borders(xlEdgeTop)
    .LineStyle = xlContinuous
    .Weight = xlThin
    .ColorIndex = xlAutomatic
End With
With Selection.Borders(xlEdgeBottom)
    .LineStyle = xlContinuous
    .Weight = xlThin
    .ColorIndex = xlAutomatic
End With
With Selection.Borders(xlEdgeRight)
    .LineStyle = xlContinuous
    .Weight = xlThin
    .ColorIndex = xlAutomatic
End With
With Selection.Borders(xlInsideVertical)
    .LineStyle = xlContinuous
    .Weight = xlThin
    .ColorIndex = xlAutomatic
End With

End Sub
</code>```

答:
```<code>Sheets.Select       'selects all sheets'
Rows("1:1").Select
Selection.Interior.ColorIndex = 37
</code>```

ContentLicense: CC BY-SA 2.5

Title: Excel Macro Help - Stacking Macros

Body:
I am using the following subroutine to combine multiple Excel files from a single folder into a single workbook with multiple worksheets.

Sub Merge2MultiSheets()

Dim wbDst As Workbook
Dim wbSrc As Workbook
Dim wsSrc As Worksheet
Dim MyPath As String
Dim strFilename As String

Application.DisplayAlerts = False
Application.EnableEvents = False
Application.ScreenUpdating = False
MyPath = "C:\MyPath" ' <-- Insert Absolute Folder Location
Set wbDst = Workbooks.Add(xlWBATWorksheet)
strFilename = Dir(MyPath & "\*.xls", vbNormal)

If Len(strFilename) = 0 Then Exit Sub

Do Until strFilename = ""
    Set wbSrc = Workbooks.Open(Filename:=MyPath & "\" & strFilename)
    Set wsSrc = wbSrc.Worksheets(1)
    wsSrc.Copy After:=wbDst.Worksheets(wbDst.Worksheets.Count)
    wbSrc.Close False
    strFilename = Dir()
Loop
wbDst.Worksheets(1).Delete

Application.DisplayAlerts = True
Application.EnableEvents = True
Application.ScreenUpdating = True

End Sub

The end product is an excel file with multiple worksheets (as well as one blank Sheet 1). I was wondering how I can then apply another macro to this newly created Workbook. As an example, I wish for all the worksheets within this new workbook to have their Headers bold and coloured a certain way, and to have the empty Worksheet deleted.

eg:

Sub Headers()

Rows("1:1").Select
Selection.Font.Bold = True
With Selection.Interior
    .ColorIndex = 37
    .Pattern = xlSolid
End With
Selection.Borders(xlDiagonalDown).LineStyle = xlNone
Selection.Borders(xlDiagonalUp).LineStyle = xlNone
With Selection.Borders(xlEdgeLeft)
    .LineStyle = xlContinuous
    .Weight = xlThin
    .ColorIndex = xlAutomatic
End With
With Selection.Borders(xlEdgeTop)
    .LineStyle = xlContinuous
    .Weight = xlThin
    .ColorIndex = xlAutomatic
End With
With Selection.Borders(xlEdgeBottom)
    .LineStyle = xlContinuous
    .Weight = xlThin
    .ColorIndex = xlAutomatic
End With
With Selection.Borders(xlEdgeRight)
    .LineStyle = xlContinuous
    .Weight = xlThin
    .ColorIndex = xlAutomatic
End With
With Selection.Borders(xlInsideVertical)
    .LineStyle = xlContinuous
    .Weight = xlThin
    .ColorIndex = xlAutomatic
End With

End Sub


问:
How to launch the activity for user to key in information once only in android?
This is my login activity code. I just want to launch my user information for user to key in their information once only after that next time when user login will straight open to main activity. Can anyone help me or teach me?

```<code>public class LoginActivity extends AppCompatActivity implements View.OnClickListener{

private Button buttonSignIn;
private EditText editTextEmail;
private EditText editTextPassword;
private TextView textViewSignup;
private ProgressDialog progressDialog;
private FirebaseAuth firebaseAuth;

private SharedPreferences prefs;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);

    Boolean session_tag = prefs.getBoolean("session", false);
    if(session_tag)
    {
        startActivity(new Intent(getApplicationContext(),MainActivity.class));

    }

    firebaseAuth = FirebaseAuth.getInstance();

    if(firebaseAuth.getCurrentUser() !=null){
        //profile activity here
    }

    editTextEmail = (EditText) findViewById(R.id.editTextEmail);
    editTextPassword = (EditText) findViewById(R.id.editTextPassword);
    textViewSignup = (TextView) findViewById(R.id.textViewSignUp);
    buttonSignIn = (Button) findViewById(R.id.buttonSignin);

    progressDialog = new ProgressDialog(this);
    buttonSignIn.setOnClickListener(this);
    textViewSignup.setOnClickListener(this);

    prefs = PreferenceManager.getDefaultSharedPreferences(this);
}

private void userLogin(){
    String email = editTextEmail.getText().toString().trim();
    String password = editTextPassword.getText().toString().trim();

    if(TextUtils.isEmpty(email)){
        //email is empty
        Toast.makeText(this,"Please enter email", Toast.LENGTH_SHORT).show();
        //stopping the function execction further
        return;
    }

    if(TextUtils.isEmpty(password)){
        //password is empty
        Toast.makeText(this,"Please enter password",Toast.LENGTH_SHORT).show();
        //stopping the function execution further
        return;
    }
    //if validations are ok

    progressDialog.setMessage("Logging In...");
    progressDialog.show();

    firebaseAuth.signInWithEmailAndPassword(email,password)
            .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    progressDialog.dismiss();

                    if(task.isSuccessful()){

                        //start the profle activity
                        finish();
                        startActivity(new Intent(getApplicationContext(),MainActivity.class));
                    }else{
                        Toast.makeText(getApplicationContext(),"Wrong email or password",Toast.LENGTH_SHORT).show();
                    }
                }

            });
}

@Override
public void onClick(View view) {
    if(view == buttonSignIn){
        userLogin();

    }
    if (view == textViewSignup){
        finish();
        startActivity(new Intent(this,RegisterActivity.class));

    }
}
</code>```

}

答:
Use a boolean in Shared Preferences.

In the onComplete method, add boolean loggedIn = true and add this to SharedPreferences, then start MainActivity.

At the start of LoginActivity, access SharedPreferences and check if boolean true.
If its true start MainActivity.

SharedPreferences guide : SharedPrefs

Body:
This is my login activity code. I just want to launch my user information for user to key in their information once only after that next time when user login will straight open to main activity. Can anyone help me or teach me?

public class LoginActivity extends AppCompatActivity implements View.OnClickListener{

private Button buttonSignIn;
private EditText editTextEmail;
private EditText editTextPassword;
private TextView textViewSignup;
private ProgressDialog progressDialog;
private FirebaseAuth firebaseAuth;

private SharedPreferences prefs;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);

    Boolean session_tag = prefs.getBoolean("session", false);
    if(session_tag)
    {
        startActivity(new Intent(getApplicationContext(),MainActivity.class));

    }

    firebaseAuth = FirebaseAuth.getInstance();

    if(firebaseAuth.getCurrentUser() !=null){
        //profile activity here
    }

    editTextEmail = (EditText) findViewById(R.id.editTextEmail);
    editTextPassword = (EditText) findViewById(R.id.editTextPassword);
    textViewSignup = (TextView) findViewById(R.id.textViewSignUp);
    buttonSignIn = (Button) findViewById(R.id.buttonSignin);

    progressDialog = new ProgressDialog(this);
    buttonSignIn.setOnClickListener(this);
    textViewSignup.setOnClickListener(this);

    prefs = PreferenceManager.getDefaultSharedPreferences(this);
}

private void userLogin(){
    String email = editTextEmail.getText().toString().trim();
    String password = editTextPassword.getText().toString().trim();

    if(TextUtils.isEmpty(email)){
        //email is empty
        Toast.makeText(this,"Please enter email", Toast.LENGTH_SHORT).show();
        //stopping the function execction further
        return;
    }

    if(TextUtils.isEmpty(password)){
        //password is empty
        Toast.makeText(this,"Please enter password",Toast.LENGTH_SHORT).show();
        //stopping the function execution further
        return;
    }
    //if validations are ok

    progressDialog.setMessage("Logging In...");
    progressDialog.show();

    firebaseAuth.signInWithEmailAndPassword(email,password)
            .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    progressDialog.dismiss();

                    if(task.isSuccessful()){

                        //start the profle activity
                        finish();
                        startActivity(new Intent(getApplicationContext(),MainActivity.class));
                    }else{
                        Toast.makeText(getApplicationContext(),"Wrong email or password",Toast.LENGTH_SHORT).show();
                    }
                }

            });
}

@Override
public void onClick(View view) {
    if(view == buttonSignIn){
        userLogin();

    }
    if (view == textViewSignup){
        finish();
        startActivity(new Intent(this,RegisterActivity.class));

    }
}

}


问:
How to set sth. on infinity in Java?
I want to implement the dijkstra algorithm and have to set each note at the beginning  to infinity.

I would like to know, if there is any function in Java which makes it easy.

答:
Double.POSITIVE_INFINITY if you are using Double to store your data.
Also note that this is not a number, which is nice depending on what you want to do. Double supports this concept.

Title: How to set sth. on infinity in Java?


问:
Open third party extension with TYPO3 extension builder
There is a custom TYPO3 extension in our installation which was obviously bootstrapped using the TYPO3 extension builder. But I cant access it using the "load" button.

Where do I tell the extension builder that he is in charge of this extension?

The original developer of the extension is no longer available.

答:
This answer is wrong! Accepted answer is right!

Whether an extension shows up in the load dropdown in Extension Builder depends on the presence of the file Configuration/ExtensionBuilder/settings.yml in your extension.

If it‘s not there (which seems to be the case) you could look for a dedicated branch - some people create such branch at the beginning and delete Extension Builder stuff in their main branch.


问:
Express JS node framework did not respond to post() request
I'm following a blog to build my first node API with express framework. But the POST request did not return a response.

```<code>const app = express();

require('./app/routes')(app, {});
app.listen(port, () => {
  console.log('We are live on ' + port);
});

module.exports = function(app, db) {
  console.log('reached2');
  app.post('/notes', (req, res) => {
    // You'll create your note here.
    console.log('reached3');
    res.send('Hello');
    //res.end();;
  });
};
</code>```

Here are my console logs,

```<code>reached1
reached2
We are live on 8000
</code>```

Here are my dependencies,

```<code>"dependencies": {
    "body-parser": "^1.17.2",
    "express": "^4.15.3",
    "mongodb": "^2.2.28"
  },
  "devDependencies": {
    "nodemon": "^1.11.0"
  }
</code>```

Im using the postman client to POST.

I tried replacing the fat arrow operator with an anonymous function but still doesnt work.

Please point the problem in this code.

答:
Instead of writing route in a function you can use it directly. Below is the code snippet for the same:</p>

```<code>const app = express();
app.listen(port, () => {
    console.log('We are live on ' + port);
});

app.post('/notes', (req, res) => {
    // You'll create your note here.
    res.send('Hello');
});
</code>```

Body:
I'm following a blog to build my first node API with express framework. But the POST request did not return a response.

const app = express();

require('./app/routes')(app, {});
app.listen(port, () => {
  console.log('We are live on ' + port);
});

module.exports = function(app, db) {
  console.log('reached2');
  app.post('/notes', (req, res) => {
    // You'll create your note here.
    console.log('reached3');
    res.send('Hello');
    //res.end();;
  });
};

Here are my console logs,

reached1
reached2
We are live on 8000

Here are my dependencies,

"dependencies": {
    "body-parser": "^1.17.2",
    "express": "^4.15.3",
    "mongodb": "^2.2.28"
  },
  "devDependencies": {
    "nodemon": "^1.11.0"
  }

Im using the postman client to POST.

I tried replacing the fat arrow operator with an anonymous function but still doesnt work.

Please point the problem in this code.

Body:
Instead of writing route in a function you can use it directly. Below is the code snippet for the same:

const app = express();
app.listen(port, () => {
    console.log('We are live on ' + port);
});

app.post('/notes', (req, res) => {
    // You'll create your note here.
    res.send('Hello');
});


问:
Is my WCF using the correct Binding?
My wcf service's web.config looks like this:

How can I confirm that it is using the settings correctly?

I still get this timeout error sometimes even though I have configured the binding to use:
 SendTimeout = 10 minutes etc. ?

```<code><system.serviceModel>
    <services>
      <service behaviorConfiguration="MyService.MyServiceBehavior"
        name="MyService.MyService">
        <endpoint address="" binding="basicHttpBinding" bindingConfiguration="longTimeoutBinding"
          bindingName="" contract="MyService.IMyService">
          <identity>
            <dns value="localhost" />
          </identity>
        </endpoint>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
      </service>
    </services>
    <bindings>
      <basicHttpBinding>
        <binding name="longTimeoutBinding" closeTimeout="00:05:00" openTimeout="00:05:00"
          receiveTimeout="00:10:00" sendTimeout="00:10:00" maxBufferPoolSize="1048576" maxReceivedMessageSize="67108864">
          <security mode="None" />
        </binding>
      </basicHttpBinding>
    </bindings>

    <behaviors>
      <serviceBehaviors>
        <behavior name="MyService.MyServiceBehavior">
          <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
          <serviceMetadata httpGetEnabled="true"/>
          <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
          <serviceDebug includeExceptionDetailInFaults="true"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>
</code>```

My client (windows service) app.config looks like:

```<code><system.serviceModel>
    <bindings>
      <basicHttpBinding>
        <binding name="BasicHttpBinding_IMyService" closeTimeout="00:01:00"
          openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
          allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
          maxBufferSize="65536" maxBufferPoolSize="1048576" maxReceivedMessageSize="67108864"
          messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered"
          useDefaultWebProxy="true">
          <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
            maxBytesPerRead="4096" maxNameTableCharCount="16384" />
          <security mode="None">
            <transport clientCredentialType="None" proxyCredentialType="None"
              realm="" />
            <message clientCredentialType="UserName" algorithmSuite="Default" />
          </security>
        </binding>
      </basicHttpBinding>
    </bindings>
    <client>
      <endpoint address="http://local/MyService/MyService.svc"
        binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IMyService"
        contract="MyService.IMyService" name="BasicHttpBinding_IMyService" />
    </client>
  </system.serviceModel>
</code>```

答: Try setting the timeout values in the client side config.</p>

OwnerDisplayName: Blankman

Title: Is my WCF using the correct Binding?

Body:
My wcf service's web.config looks like this:

How can I confirm that it is using the settings correctly?

I still get this timeout error sometimes even though I have configured the binding to use:
 SendTimeout = 10 minutes etc. ?

<system.serviceModel>
    <services>
      <service behaviorConfiguration="MyService.MyServiceBehavior"
        name="MyService.MyService">
        <endpoint address="" binding="basicHttpBinding" bindingConfiguration="longTimeoutBinding"
          bindingName="" contract="MyService.IMyService">
          <identity>
            <dns value="localhost" />
          </identity>
        </endpoint>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
      </service>
    </services>
    <bindings>
      <basicHttpBinding>
        <binding name="longTimeoutBinding" closeTimeout="00:05:00" openTimeout="00:05:00"
          receiveTimeout="00:10:00" sendTimeout="00:10:00" maxBufferPoolSize="1048576" maxReceivedMessageSize="67108864">
          <security mode="None" />
        </binding>
      </basicHttpBinding>
    </bindings>

    <behaviors>
      <serviceBehaviors>
        <behavior name="MyService.MyServiceBehavior">

          <serviceMetadata httpGetEnabled="true"/>

          <serviceDebug includeExceptionDetailInFaults="true"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>

My client (windows service) app.config looks like:

<system.serviceModel>
    <bindings>
      <basicHttpBinding>
        <binding name="BasicHttpBinding_IMyService" closeTimeout="00:01:00"
          openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
          allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
          maxBufferSize="65536" maxBufferPoolSize="1048576" maxReceivedMessageSize="67108864"
          messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered"
          useDefaultWebProxy="true">
          <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
            maxBytesPerRead="4096" maxNameTableCharCount="16384" />
          <security mode="None">
            <transport clientCredentialType="None" proxyCredentialType="None"
              realm="" />
            <message clientCredentialType="UserName" algorithmSuite="Default" />
          </security>
        </binding>
      </basicHttpBinding>
    </bindings>
    <client>
      <endpoint address="http://local/MyService/MyService.svc"
        binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IMyService"
        contract="MyService.IMyService" name="BasicHttpBinding_IMyService" />
    </client>
  </system.serviceModel>

LastEditorDisplayName: Blankman

OwnerDisplayName: Terry Donaghe


问:
SSRS Formatting a string to a comma number
I have the following value in one of my fileds in SSRS:

```<code>=CStr(Fields!Shipment_Weight.Value) + "#"
</code>```

I do this becuase I need the #(pounds) sign at the end. This now does not allow me to format the number into something like 1,000 it gives me 1000 currently. Is there a way to add commas in the code rather than the format box since this is a string now? Values are all different from 1-1000000000

Thanks!

答:
I believe the above will work, I've always used the following from MSDN

```<code>=CSTR(FORMAT(Fields!Shipment_Weight.Value,"#,#")) & "#"
</code>```

The article on MSDN about string formatting

Body:
I have the following value in one of my fileds in SSRS:

=CStr(Fields!Shipment_Weight.Value) + "#"

I do this becuase I need the #(pounds) sign at the end. This now does not allow me to format the number into something like 1,000 it gives me 1000 currently. Is there a way to add commas in the code rather than the format box since this is a string now? Values are all different from 1-1000000000

Thanks!

Body:
I believe the above will work, I've always used the following from MSDN

=CSTR(FORMAT(Fields!Shipment_Weight.Value,"#,#")) & "#"

The article on MSDN about string formatting


问:
Build armeabi instead of armeabi-v7a target using arm clang toolchain
I followed the article "Standalone Toolchains" to create seven customized toolchains (armeabi, armeabi-v7a, arm64-v8a, misp, mips64, x86, and x86_64). Then I want to build PROJ.4 library. I know ARM clang toolchain by default targets armeabi-v7a, so in order to target armeabi, I use the following commands:

```<code>export CFLAGS="-march=arm -O2"
export CC=~/Android/toolchain/arm/bin/clang
export CXX==~/Android/toolchain/arm/bin/clang++
./configure --host=arm-linux-androideabi
</code>```

Then I get the errors:
clang38: error: the clang compiler does not support '-march=arm'

If I change CFLAGS to "-march=arm-v7a -O2", there would be no errors. But it targets armeabi-v7a, not armeabi. So what is the value for -march flag targeting armeabi?

答:
Try armv5 instead, as described here:

https://developer.android.com/ndk/guides/abis.html

Body:
I followed the article "Standalone Toolchains" to create seven customized toolchains (armeabi, armeabi-v7a, arm64-v8a, misp, mips64, x86, and x86_64). Then I want to build PROJ.4 library. I know ARM clang toolchain by default targets armeabi-v7a, so in order to target armeabi, I use the following commands:

export CFLAGS="-march=arm -O2"
export CC=~/Android/toolchain/arm/bin/clang
export CXX==~/Android/toolchain/arm/bin/clang++
./configure --host=arm-linux-androideabi

Then I get the errors:
clang38: error: the clang compiler does not support '-march=arm'

If I change CFLAGS to "-march=arm-v7a -O2", there would be no errors. But it targets armeabi-v7a, not armeabi. So what is the value for -march flag targeting armeabi?


问:
sql server complex query

1st one is the source table and 2nd one is the destination table, so in 2nd table by using unpivot the the 12 month columns converted into single column and YTD field should be update automatically. If the month name is Jan means the YTD field will Jan data only, if it is Feb means it will add the Jan data with Feb data. same if it is Dec means it will add from Jan to Dec of the same row.

答:
Just select all your Month indivitually and then UNION them:

```<code>select [ORU code], [BG Name], YEAR, 'Jan' as [Month], [Jan] as [KPI #], [Jan]
as [YTD/ITM] from  source_table
union all
select [ORU code], [BG Name], YEAR, 'Feb' as [Month], [Feb] as [KPI #], [Jan]+
[Feb]  as [YTD/ITM] from  source_table
union all
select ....
</code>```

you get the Idea

Title: sql server complex query

Body:
Just select all your Month indivitually and then UNION them:

select [ORU code], [BG Name], YEAR, 'Jan' as [Month], [Jan] as [KPI #], [Jan]
as [YTD/ITM] from  source_table
union all
select [ORU code], [BG Name], YEAR, 'Feb' as [Month], [Feb] as [KPI #], [Jan]+
[Feb]  as [YTD/ITM] from  source_table
union all
select ....

you get the Idea


问:
System V - LIFO way
I'm using System V to manage a message queue.
I successfully made a working prototype, everything works as expected, however I would like to have a LIFO queue instead of FIFO (expected last msgsnd message sent is first read msgget).

Is this possible ?

答:
I think it is impossible.

The term "queue" means FIFO. See wikipedia:

Queue (abstract data type)

In computer science, a queue (/ˈkjuː/ KYEW) is a particular kind of abstract data type or collection in which the entities in the collection are kept in order and the principal (or only) operations on the collection are the addition of entities to the rear terminal position, known as enqueue, and removal of entities from the front terminal position, known as dequeue. This makes the queue a First-In-First-Out (FIFO) data structure.

Title: System V - LIFO way


问:
Azure blob storage
I am just wondering whether there is a possibility to access privately the blob storage within an azure service (let's say from a worker role) instead of accessing files through the public address (which basically send your files over the internet, leaving the cluster). The same question i have for storage queues or for Storage Tables ... are they accessible using a private endpoint (LAN HTTP address by IP or sort of)?</p>

答:
Today it is not possible to access Azure Storage privately. The traffic must route through public Internet.

There's a feedback item on the same on Azure's feedback site - https://feedback.azure.com/forums/217298-storage/suggestions/6954656-storage-accounts-on-vnet-or-disable-key-options. From the status, it seems Azure Storage team is currently reviewing this though no time line has been specified for that. Feel free to upvote this request.

Title: Azure blob storage


问:
Does a finally block always get executed in Java?
Considering this code, can I be absolutely sure that the finally block always executes, no matter what something() is?

```<code>try {
    something();
    return success;
}
catch (Exception e) {
    return failure;
}
finally {
    System.out.println("I don't know if this will get printed out");
}
</code>```

答:
If you don't handle exception, before terminating the program, JVM executes finally block. It will not executed only if normal execution of program will fail mean's termination of program due to these following reasons..

By causing a fatal error that causes the process to abort.

Termination of program due to memory corrupt.

By calling System.exit()

If program goes into infinity loop.

OwnerDisplayName: jonny five

Body:
Considering this code, can I be absolutely sure that the finally block always executes, no matter what something() is?

try {
    something();
    return success;
}
catch (Exception e) {
    return failure;
}
finally {
    System.out.println("I don't know if this will get printed out");
}


问:
Error 500 while Uploading CSV file to S3 bucket using boto3 and python flask
kind of looked at all possible options.
I am using boto3 and python3.6 to upload file to s3 bucket, Funny thing is while json and even .py file is getting uploaded, it is throwing Error 500 while uploading CSV. On successful uplaod i am returning an json to check all the values.

```<code>    import boto3
    from botocore.client import Config

    @app.route("/upload",methods = ['POST','GET'])
    def upload():
    if request.method == 'POST':
        file = request.files['file']
        filename = secure_filename(file.filename)
        s3 = boto3.resource('s3', aws_access_key_id= os.environ.get('AWS_ACCESS_KEY_ID'), aws_secret_access_key=os.environ.get('AWS_SECRET_ACCESS_KEY'),config=Config(signature_version='s3v4'))
        s3.Bucket(os.environ.get('S3_BUCKET')).put_object(Key=filename, Body=open(filename, 'rb'), ContentEncoding='text/csv')
        return jsonify({'successful upload':filename, 'S3_BUCKET':os.environ.get('S3_BUCKET'), 'ke':os.environ.get('AWS_ACCESS_KEY_ID'), 'sec':os.environ.get('AWS_SECRET_ACCESS_KEY'),'filepath': "https://s3.us-east-2.amazonaws.com/"+os.environ.get('S3_BUCKET')+"/" +filename})
</code>```

Please help!!

答:
You are getting a FileNotFoundError for file xyz.csv because the file does not exist.

This could be because the code in upload() does not actually save the uploaded file, it merely obtains a safe name for it and immediately tries to open it - which fails.

That it works for other files is probably due to the fact that those files already exist, perhaps left over from testing, so there is no problem.

Try saving the file to the file system using save() after obtaining the safe filename:

```<code>upload_file = request.files['file']
filename = secure_filename(upload_file.filename)
upload_file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
</code>```

and then uploading it (assuming that you've configured an UPLOAD_FOLDER):

```<code>with open(os.path.join(app.config['UPLOAD_FOLDER'], filename), 'rb') as f:
    s3.Bucket(os.environ.get('S3_BUCKET')).put_object(Key=filename, Body=f, ContentEncoding='text/csv')
    return jsonify({...})
</code>```

There is no need to actually save the file to the file system; it can be streamed directly to your S3 bucket using the stream attribute of the upload_file object:

```<code>upload_file = request.files['file']
filename = secure_filename(upload_file.filename)

s3 = boto3.resource('s3', aws_access_key_id='key', aws_secret_access_key='secret')
s3.Bucket('bucket').put_object(Key=filename, Body=upload_file.stream, ContentType=upload_file.content_type)
</code>```

To make this more generic you should use the content_type attribute of the uploaded file as shown above.

Body:
kind of looked at all possible options.
I am using boto3 and python3.6 to upload file to s3 bucket, Funny thing is while json and even .py file is getting uploaded, it is throwing Error 500 while uploading CSV. On successful uplaod i am returning an json to check all the values.

    import boto3
    from botocore.client import Config

    @app.route("/upload",methods = ['POST','GET'])
    def upload():
    if request.method == 'POST':
        file = request.files['file']
        filename = secure_filename(file.filename)
        s3 = boto3.resource('s3', aws_access_key_id= os.environ.get('AWS_ACCESS_KEY_ID'), aws_secret_access_key=os.environ.get('AWS_SECRET_ACCESS_KEY'),config=Config(signature_version='s3v4'))
        s3.Bucket(os.environ.get('S3_BUCKET')).put_object(Key=filename, Body=open(filename, 'rb'), ContentEncoding='text/csv')
        return jsonify({'successful upload':filename, 'S3_BUCKET':os.environ.get('S3_BUCKET'), 'ke':os.environ.get('AWS_ACCESS_KEY_ID'), 'sec':os.environ.get('AWS_SECRET_ACCESS_KEY'),'filepath': "https://s3.us-east-2.amazonaws.com/"+os.environ.get('S3_BUCKET')+"/" +filename})

Please help!!

Body:
You are getting a FileNotFoundError for file xyz.csv because the file does not exist.

This could be because the code in upload() does not actually save the uploaded file, it merely obtains a safe name for it and immediately tries to open it - which fails.

That it works for other files is probably due to the fact that those files already exist, perhaps left over from testing, so there is no problem.

Try saving the file to the file system using save() after obtaining the safe filename:

upload_file = request.files['file']
filename = secure_filename(upload_file.filename)
upload_file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))

and then uploading it (assuming that you've configured an UPLOAD_FOLDER):

with open(os.path.join(app.config['UPLOAD_FOLDER'], filename), 'rb') as f:
    s3.Bucket(os.environ.get('S3_BUCKET')).put_object(Key=filename, Body=f, ContentEncoding='text/csv')
    return jsonify({...})

There is no need to actually save the file to the file system; it can be streamed directly to your S3 bucket using the stream attribute of the upload_file object:

upload_file = request.files['file']
filename = secure_filename(upload_file.filename)

s3 = boto3.resource('s3', aws_access_key_id='key', aws_secret_access_key='secret')
s3.Bucket('bucket').put_object(Key=filename, Body=upload_file.stream, ContentType=upload_file.content_type)

To make this more generic you should use the content_type attribute of the uploaded file as shown above.


问:
Discover if a variable is a number
Is there a Way To compare nan with a variable?I need this To understand if a variable is a number or Not without using javascript's functions.</p>

答:
Ignoring your weird restriction on "no Javascript functions"…:

```<code>typeof num == 'number' && !isNaN(num)
</code>```

This is the correct way to figure out if a value is a Number and not NaN. If you also want to figure out whether the number is finite (not Infinity), use an isFinite() instead.

Title: Discover if a variable is a number

Body:
Ignoring your weird restriction on "no Javascript functions"…:

typeof num == 'number' && !isNaN(num)

This is the correct way to figure out if a value is a Number and not NaN. If you also want to figure out whether the number is finite (not Infinity), use an isFinite() instead.


问:
WPF ListView select added item when moving between list views
I have a view with 2 listviews bound to CollectionViewSources created from ObservableCollections on my view model.

Each listview item is templated to a textblock and a button - with unitsInMeasureListView.ItemTemplate button binding to a command to remove the item from its bound collection and add it to the collection on availableUnitsListView.

The reverse is true for availableUnitsListView.ItemTemplate button - it removes it from availableUnitsListView and adds it to unitsInMeasureListView.

This all works fine, items are removed and added from each listview as required.

Is there a way that I can automatically select the item added to availableUnitsListView when unitsInMeasureListView still has focus?

XAML:

```<code> <CollectionViewSource x:Key="unitsInMeasureViewSource" Source="{Binding Path=MeasureUnits}">
                <CollectionViewSource.SortDescriptions>
                    <componentModel:SortDescription PropertyName="UnitInMeasure.IsPredefined" Direction="Descending" />
                    <componentModel:SortDescription PropertyName="UnitInMeasure.Name"  />
                </CollectionViewSource.SortDescriptions>
            </CollectionViewSource>
            <CollectionViewSource x:Key="availableUnitsViewSource" Source="{Binding Path=AvailableUnits}">
                <CollectionViewSource.SortDescriptions>
                    <componentModel:SortDescription PropertyName="UnitInMeasure.IsPredefined" Direction="Descending" />
                    <componentModel:SortDescription PropertyName="UnitInMeasure.Name"  />
                </CollectionViewSource.SortDescriptions>
            </CollectionViewSource>

<ListView Grid.Row="1" x:Name="unitsInMeasureListView" BorderThickness="1" BorderBrush="Gray" VerticalAlignment="Stretch" ScrollViewer.VerticalScrollBarVisibility="Auto" HorizontalContentAlignment="Stretch" ItemsSource="{Binding Source={StaticResource unitsInMeasureViewSource}}">
                        <ListView.ItemTemplate>
                            <DataTemplate>
                                <Border Margin="0 3" >
                                    <DockPanel>
                                        <TextBlock x:Name="unitItem" DockPanel.Dock="Left" Height="20" VerticalAlignment="Center" >
                                            <TextBlock.Text>
                                                <MultiBinding StringFormat=" {0} ({1})" >
                                                    <Binding Path="UnitInMeasure.Name" />
                                                    <Binding Path="UnitInMeasure.Symbol" />
                                                </MultiBinding>
                                            </TextBlock.Text>
                                            <TextBlock.Style>
                                                <Style>
                                                    <Style.Triggers>
                                                        <DataTrigger Binding="{Binding Path=UnitInMeasure.IsPredefined}" Value="false">
                                                            <Setter Property="TextBlock.FontStyle" Value="Italic"/>
                                                        </DataTrigger>
                                                    </Style.Triggers>
                                                </Style>
                                            </TextBlock.Style>
                                                <TextBlock.InputBindings>
                                                    <MouseBinding MouseAction="LeftDoubleClick" Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=ListView}, Path=DataContext.EditUnitCommand}" CommandParameter="{Binding Path=UnitInMeasure}" />
                                                </TextBlock.InputBindings>
                                        </TextBlock>
                                        <Button Command="{Binding Path=RemoveUnitFromMeasureCommand}" DockPanel.Dock="Right" HorizontalAlignment="Right" Style="{StaticResource TransparentStyle}" >
                                            <Button.Visibility>
                                                <MultiBinding Converter="{StaticResource multiBindingToVisibilityConverter}">
                                                    <Binding Path="IsSelected" RelativeSource="{RelativeSource AncestorType={x:Type ListViewItem}}"/>
                                                    <Binding Path="IsMeasureEditable"/>
                                                    <Binding Path="CanRemoveUnit" />
                                                </MultiBinding>
                                            </Button.Visibility>
                                            <Image Source="../../Images/Small/navigate_minus.png" ToolTip="Remove unit from measure" >
                                                <Image.Visibility>
                                                    <MultiBinding Converter="{StaticResource multiBindingToVisibilityConverter}">
                                                        <Binding Path="IsFocused" RelativeSource="{RelativeSource AncestorType={x:Type ListViewItem}}"/>
                                                    </MultiBinding>
                                                </Image.Visibility>
                                            </Image>
                                        </Button>
                                    </DockPanel>
                                </Border>
                            </DataTemplate>
                        </ListView.ItemTemplate>
                    </ListView>
<ListView Grid.Row="3" x:Name="availableUnitsListView" BorderThickness="1" BorderBrush="Gray" VerticalAlignment="Stretch" ScrollViewer.VerticalScrollBarVisibility="Auto" HorizontalContentAlignment="Stretch" ItemsSource="{Binding Source={StaticResource availableUnitsViewSource}}">
                        <ListView.ItemTemplate>
                            <DataTemplate>
                                <Border Margin="3" >
                                    <DockPanel>
                                        <TextBlock  x:Name="measure" Height="20" VerticalAlignment="Center">
                                                <TextBlock.Text>
                                                    <MultiBinding StringFormat=" {0} ({1})" >
                                                        <Binding Path="UnitInMeasure.Name" />
                                                        <Binding Path="UnitInMeasure.Symbol" />
                                                    </MultiBinding>
                                                </TextBlock.Text>
                                                <TextBlock.Style>
                                                    <Style>
                                                        <Style.Triggers>
                                                            <DataTrigger Binding="{Binding Path=UnitInMeasure.IsPredefined}" Value="false">
                                                                <Setter Property="TextBlock.FontStyle" Value="Italic"/>
                                                            </DataTrigger>
                                                        </Style.Triggers>
                                                    </Style>
                                                </TextBlock.Style>
                                        </TextBlock>
                                        <Button Command="{Binding Path=AddUnitToMeasureCommand}" DockPanel.Dock="Right" HorizontalAlignment="Right" Style="{StaticResource TransparentStyle}" >
                                            <Button.Visibility>
                                                <MultiBinding Converter="{StaticResource multiBindingToVisibilityConverter}">
                                                    <Binding Path="IsSelected" RelativeSource="{RelativeSource AncestorType={x:Type ListViewItem}}"/>
                                                    <Binding Path="IsMeasureEditable"/>
                                                </MultiBinding>
                                            </Button.Visibility>
                                            <Image Source="../../Images/Small/navigate_plus.png" ToolTip="Add unit to measure"  >
                                                <Image.Visibility>
                                                    <MultiBinding Converter="{StaticResource multiBindingToVisibilityConverter}">
                                                        <Binding Path="IsFocused" RelativeSource="{RelativeSource AncestorType={x:Type ListViewItem}}"/>
                                                    </MultiBinding>
                                                </Image.Visibility>
                                            </Image>
                                        </Button>
                                    </DockPanel>
                                </Border>
                            </DataTemplate>
                        </ListView.ItemTemplate>
                    </ListView>
</code>```

The bound collections on the View Model are:

```<code>    /// <summary>
    /// Gets a list of all unit view models currently within this measure.
    /// </summary>
    public ReadOnlyObservableCollection<UnitInMeasureViewModel> MeasureUnits
    {
        get
        {
            return this._measureUnits;
        }
    }
    private readonly ReadOnlyObservableCollection<UnitInMeasureViewModel> _measureUnits;
    private readonly ObservableCollection<UnitInMeasureViewModel> measureUnits;

    /// <summary>
    /// Gets a list of all unit view models currently available to this measure.
    /// </summary>
    public ReadOnlyObservableCollection<UnitInMeasureViewModel> AvailableUnits
    {
        get
        {
            return this._availableUnits;
        }
    }
    private readonly ReadOnlyObservableCollection<UnitInMeasureViewModel> _availableUnits;
    private readonly ObservableCollection<UnitInMeasureViewModel> availableUnits;
</code>```

And the view model code executed by the button command bindings:

```<code>    /// <summary>
    /// Adds a unit to this measure.
    /// </summary>
    /// <param name="vm">The view model for the unit to be added.</param>
    internal void AddUnitToMeasure(UnitInMeasureViewModel vm)
    {
        this.availableUnits.Remove(vm);
        this.measureUnits.Add(vm);
    }

    /// <summary>
    /// Removes a unit from this measure.
    /// </summary>
    /// <param name="vm">The view model for the unit to be removed.</param>
    internal void RemoveUnitFromMeasure(UnitInMeasureViewModel vm)
    {
        this.measureUnits.Remove(vm);
        this.availableUnits.Add(vm);
    }
</code>```

答:
Bind SelectedItem in ListBox to some property(say X) in View Model.
Whenever you add or remove item from the ListBox(AddUnitToMeasure method and RemoveUnitFromMeasure method), you need to update this X property as well to update the selected item in ListBox.</p>

Body:
I have a view with 2 listviews bound to CollectionViewSources created from ObservableCollections on my view model.

Each listview item is templated to a textblock and a button - with unitsInMeasureListView.ItemTemplate button binding to a command to remove the item from its bound collection and add it to the collection on availableUnitsListView.

The reverse is true for availableUnitsListView.ItemTemplate button - it removes it from availableUnitsListView and adds it to unitsInMeasureListView.

This all works fine, items are removed and added from each listview as required.

Is there a way that I can automatically select the item added to availableUnitsListView when unitsInMeasureListView still has focus?

XAML:

 <CollectionViewSource x:Key="unitsInMeasureViewSource" Source="{Binding Path=MeasureUnits}">
                <CollectionViewSource.SortDescriptions>
                    <componentModel:SortDescription PropertyName="UnitInMeasure.IsPredefined" Direction="Descending" />
                    <componentModel:SortDescription PropertyName="UnitInMeasure.Name"  />
                </CollectionViewSource.SortDescriptions>
            </CollectionViewSource>
            <CollectionViewSource x:Key="availableUnitsViewSource" Source="{Binding Path=AvailableUnits}">
                <CollectionViewSource.SortDescriptions>
                    <componentModel:SortDescription PropertyName="UnitInMeasure.IsPredefined" Direction="Descending" />
                    <componentModel:SortDescription PropertyName="UnitInMeasure.Name"  />
                </CollectionViewSource.SortDescriptions>
            </CollectionViewSource>

<ListView Grid.Row="1" x:Name="unitsInMeasureListView" BorderThickness="1" BorderBrush="Gray" VerticalAlignment="Stretch" ScrollViewer.VerticalScrollBarVisibility="Auto" HorizontalContentAlignment="Stretch" ItemsSource="{Binding Source={StaticResource unitsInMeasureViewSource}}">
                        <ListView.ItemTemplate>
                            <DataTemplate>
                                <Border Margin="0 3" >
                                    <DockPanel>
                                        <TextBlock x:Name="unitItem" DockPanel.Dock="Left" Height="20" VerticalAlignment="Center" >
                                            <TextBlock.Text>
                                                <MultiBinding StringFormat=" {0} ({1})" >
                                                    <Binding Path="UnitInMeasure.Name" />
                                                    <Binding Path="UnitInMeasure.Symbol" />
                                                </MultiBinding>
                                            </TextBlock.Text>
                                            <TextBlock.Style>

                                                </Style>
                                            </TextBlock.Style>
                                                <TextBlock.InputBindings>
                                                    <MouseBinding MouseAction="LeftDoubleClick" Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=ListView}, Path=DataContext.EditUnitCommand}" CommandParameter="{Binding Path=UnitInMeasure}" />
                                                </TextBlock.InputBindings>
                                        </TextBlock>
                                        <Button Command="{Binding Path=RemoveUnitFromMeasureCommand}" DockPanel.Dock="Right" HorizontalAlignment="Right" Style="{StaticResource TransparentStyle}" >
                                            <Button.Visibility>
                                                <MultiBinding Converter="{StaticResource multiBindingToVisibilityConverter}">
                                                    <Binding Path="IsSelected" RelativeSource="{RelativeSource AncestorType={x:Type ListViewItem}}"/>
                                                    <Binding Path="IsMeasureEditable"/>
                                                    <Binding Path="CanRemoveUnit" />
                                                </MultiBinding>
                                            </Button.Visibility>
                                            <Image Source="../../Images/Small/navigate_minus.png" ToolTip="Remove unit from measure" >
                                                <Image.Visibility>
                                                    <MultiBinding Converter="{StaticResource multiBindingToVisibilityConverter}">
                                                        <Binding Path="IsFocused" RelativeSource="{RelativeSource AncestorType={x:Type ListViewItem}}"/>
                                                    </MultiBinding>
                                                </Image.Visibility>
                                            </Image>
                                        </Button>
                                    </DockPanel>
                                </Border>
                            </DataTemplate>
                        </ListView.ItemTemplate>
                    </ListView>
<ListView Grid.Row="3" x:Name="availableUnitsListView" BorderThickness="1" BorderBrush="Gray" VerticalAlignment="Stretch" ScrollViewer.VerticalScrollBarVisibility="Auto" HorizontalContentAlignment="Stretch" ItemsSource="{Binding Source={StaticResource availableUnitsViewSource}}">
                        <ListView.ItemTemplate>
                            <DataTemplate>
                                <Border Margin="3" >
                                    <DockPanel>
                                        <TextBlock  x:Name="measure" Height="20" VerticalAlignment="Center">
                                                <TextBlock.Text>
                                                    <MultiBinding StringFormat=" {0} ({1})" >
                                                        <Binding Path="UnitInMeasure.Name" />
                                                        <Binding Path="UnitInMeasure.Symbol" />
                                                    </MultiBinding>
                                                </TextBlock.Text>
                                                <TextBlock.Style>

                                                    </Style>
                                                </TextBlock.Style>
                                        </TextBlock>
                                        <Button Command="{Binding Path=AddUnitToMeasureCommand}" DockPanel.Dock="Right" HorizontalAlignment="Right" Style="{StaticResource TransparentStyle}" >
                                            <Button.Visibility>
                                                <MultiBinding Converter="{StaticResource multiBindingToVisibilityConverter}">
                                                    <Binding Path="IsSelected" RelativeSource="{RelativeSource AncestorType={x:Type ListViewItem}}"/>
                                                    <Binding Path="IsMeasureEditable"/>
                                                </MultiBinding>
                                            </Button.Visibility>
                                            <Image Source="../../Images/Small/navigate_plus.png" ToolTip="Add unit to measure"  >
                                                <Image.Visibility>
                                                    <MultiBinding Converter="{StaticResource multiBindingToVisibilityConverter}">
                                                        <Binding Path="IsFocused" RelativeSource="{RelativeSource AncestorType={x:Type ListViewItem}}"/>
                                                    </MultiBinding>
                                                </Image.Visibility>
                                            </Image>
                                        </Button>
                                    </DockPanel>
                                </Border>
                            </DataTemplate>
                        </ListView.ItemTemplate>
                    </ListView>

The bound collections on the View Model are:

    ///
    /// Gets a list of all unit view models currently within this measure.
    ///
    public ReadOnlyObservableCollection<UnitInMeasureViewModel> MeasureUnits
    {
        get
        {
            return this._measureUnits;
        }
    }
    private readonly ReadOnlyObservableCollection<UnitInMeasureViewModel> _measureUnits;
    private readonly ObservableCollection<UnitInMeasureViewModel> measureUnits;

    ///
    /// Gets a list of all unit view models currently available to this measure.
    ///
    public ReadOnlyObservableCollection<UnitInMeasureViewModel> AvailableUnits
    {
        get
        {
            return this._availableUnits;
        }
    }
    private readonly ReadOnlyObservableCollection<UnitInMeasureViewModel> _availableUnits;
    private readonly ObservableCollection<UnitInMeasureViewModel> availableUnits;

And the view model code executed by the button command bindings:

    ///
    /// Adds a unit to this measure.
    ///
    /// <param name="vm">The view model for the unit to be added.</param>
    internal void AddUnitToMeasure(UnitInMeasureViewModel vm)
    {
        this.availableUnits.Remove(vm);
        this.measureUnits.Add(vm);
    }

    ///
    /// Removes a unit from this measure.
    ///
    /// <param name="vm">The view model for the unit to be removed.</param>
    internal void RemoveUnitFromMeasure(UnitInMeasureViewModel vm)
    {
        this.measureUnits.Remove(vm);
        this.availableUnits.Add(vm);
    }


问:
Java List MVC Pattern
I'm having some trouble implementing a JList in Java using the MVC Pattern because I can't figure out how am I suppose to write the controller and the view(each one in a separte class) so that I can call the methods from the model.Example : In the model I have a method called ( getBooks() ) and in the GUI a frame with a JList so that when I click an item in the list some textboxes will get filled with the appropriate information(title, author etc). The problem is I'm not sure how to write the listeners in the controller and/or in the view.By the way the items from the list should also be loaded from the model.

Thank you.

答: There are several approaches to creating a list model, discussed here. Swing uses a separable model architecture, described further in A Swing Architecture Overview.

Title: Java List MVC Pattern


问:
finding the first and last entry with a certain value in a row
I have a excel sheet containing multiple cells with a string foo in the first row. I want to find the first and last column in which the string is written. I have tried the following

```<code>Dim first_col As Integer
Dim last_col As Integer
Dim col As Integer
Dim found As Range
Dim ws_MLB as Worksheet
Dim foo as String

set ws_MLB = ThisWorkbook.Sheet(1)

Set found = ws_MLB.Rows(1).Find(foo)
If Not found Is Nothing Then
    col = found.Column
    first_col = col
    last_col = col
    Do
        found = ws_MLB.Rows(1).FindNext(found)
        col = found.Column

        If col < first_col Then
            first_col = col
            MsgBox ("This should not happen")
        ElseIf col > last_col Then
            last_col = col
        End If
    Loop While Not found Is Nothing And col <> first_col
Else
    MsgBox ("not found")
End If
</code>```

But this way I only get the the first value for both first_col and last_col. When I search for the string with the integrated excel search I find multiple instances. So the string is there. Have I done a mistake or is there a better way to do this?

edit forgot to mention that I also tried to change the search direction, but I still got the first entry.

答:
I would do that like this:</p>

```<code>Public Sub foo()
  Dim nCol As Integer
  Dim nFirst As Integer
  Dim nLast As Integer

  With ActiveSheet
    nCol = 1
    Do Until .Cells(1, nCol) = ""
      If .Cells(1, nCol) = "foo" Then
        If nFirst = 0 Then
          nFirst = nCol
        Else
          nLast = nCol
        End If
      End If
      nCol = nCol + 1
    Loop
  End With

  MsgBox "First: " & nFirst & vbCr & "Last: " & nLast
End Sub
</code>```

Body:
I have a excel sheet containing multiple cells with a string foo in the first row. I want to find the first and last column in which the string is written. I have tried the following

Dim first_col As Integer
Dim last_col As Integer
Dim col As Integer
Dim found As Range
Dim ws_MLB as Worksheet
Dim foo as String

set ws_MLB = ThisWorkbook.Sheet(1)

Set found = ws_MLB.Rows(1).Find(foo)
If Not found Is Nothing Then
    col = found.Column
    first_col = col
    last_col = col
    Do
        found = ws_MLB.Rows(1).FindNext(found)
        col = found.Column

        If col < first_col Then
            first_col = col
            MsgBox ("This should not happen")
        ElseIf col > last_col Then
            last_col = col
        End If
    Loop While Not found Is Nothing And col <> first_col
Else
    MsgBox ("not found")
End If

But this way I only get the the first value for both first_col and last_col. When I search for the string with the integrated excel search I find multiple instances. So the string is there. Have I done a mistake or is there a better way to do this?

edit forgot to mention that I also tried to change the search direction, but I still got the first entry.

Body:
I would do that like this:

Public Sub foo()
  Dim nCol As Integer
  Dim nFirst As Integer
  Dim nLast As Integer

  With ActiveSheet
    nCol = 1
    Do Until .Cells(1, nCol) = ""
      If .Cells(1, nCol) = "foo" Then
        If nFirst = 0 Then
          nFirst = nCol
        Else
          nLast = nCol
        End If
      End If
      nCol = nCol + 1
    Loop
  End With

  MsgBox "First: " & nFirst & vbCr & "Last: " & nLast
End Sub