问:
How to parse checkbox multidimensional array in JSON format?
I'm not really sure if the Title was correct. The actual application is a quiz. Ok let me illustrate this and here's my sample snippet.

   <form method="POST">

    Softdrinks:

       <input type="checkbox" name="question[1]answer[]" value="Coke">Coke

       <input type="checkbox" name="question[1]answer[]" value="Royal">Royal

    Coffee :

       <input type="checkbox" name="question[2]answer[]" value="Cappuccino">Cappuccino

       <input type="checkbox" name="question[2]answer[]" value="Latte">Latte

    <button type="submit">Submit</button>

    </form>```
</div>
</div>
</p>

<p>Let's assume that all of the options are checked. But when the form submitted, The output was something like this:</p>

```"question":{
    "1":"Coke",
    "2":"Cappuccino"
}
```

<p>So the "Royal" and "Latte" are skipped and i don't know why. I want the output should be like this :</p>

```"question":[
    "1": {
        "Coke",
        "Royal"
    }
    "2": {
        "Latte",
        "Cappuccino"
    }
]
```

答:
The name attributes on the element are incorrect. Try this

```<code><form method="POST">

Softdrinks:
<div class="checkbox">
   <label><input type="checkbox" name="question[1][]" value="Coke">Coke</label>
</div>
<div class="checkbox">
   <label><input type="checkbox" name="question[1][]" value="Royal">Royal</label>
</div>

Coffee :

<div class="checkbox">
   <label><input type="checkbox" name="question[2][]" value="Cappuccino">Cappuccino</label>
</div>
<div class="checkbox">
   <label><input type="checkbox" name="question[2][]" value="Latte">Latte</label>
</div>

<button type="submit">Submit</button>

</form>
</code>```

it should result in the following output

```<code>"question":[
    "1": {
        "Coke",
        "Royal"
    }
    "2": {
        "Latte",
        "Cappuccino"
    }
]
</code>```

Body:
I'm not really sure if the Title was correct. The actual application is a quiz. Ok let me illustrate this and here's my sample snippet.

   <form method="POST">

    Softdrinks:

       <input type="checkbox" name="question[1]answer[]" value="Coke">Coke

       <input type="checkbox" name="question[1]answer[]" value="Royal">Royal

    Coffee :

       <input type="checkbox" name="question[2]answer[]" value="Cappuccino">Cappuccino

       <input type="checkbox" name="question[2]answer[]" value="Latte">Latte

    <button type="submit">Submit</button>

    </form>

Let's assume that all of the options are checked. But when the form submitted, The output was something like this:

"question":{
    "1":"Coke",
    "2":"Cappuccino"
}

So the "Royal" and "Latte" are skipped and i don't know why. I want the output should be like this :

"question":[
    "1": {
        "Coke",
        "Royal"
    }
    "2": {
        "Latte",
        "Cappuccino"
    }
]

Body:
The name attributes on the element are incorrect. Try this

<form method="POST">

Softdrinks:
<div class="checkbox">
   <label><input type="checkbox" name="question[1][]" value="Coke">Coke</label>
</div>
<div class="checkbox">
   <label><input type="checkbox" name="question[1][]" value="Royal">Royal</label>
</div>

Coffee :

<div class="checkbox">
   <label><input type="checkbox" name="question[2][]" value="Cappuccino">Cappuccino</label>
</div>
<div class="checkbox">
   <label><input type="checkbox" name="question[2][]" value="Latte">Latte</label>
</div>

<button type="submit">Submit</button>

</form>

it should result in the following output

"question":[
    "1": {
        "Coke",
        "Royal"
    }
    "2": {
        "Latte",
        "Cappuccino"
    }
]


来源: stackexchange

问:
Can't open an image in WPF app
In my application I want to display some pictures (I need to have them stored in a list). I have problem with opening them. Firstly, I made a directory Images (using VS). Next I loaded pictures to this folder (also in VS).
I wanted to open one of them like here:
http://msdn.microsoft.com/en-us/library/aa970062.aspx

```<code>Stream imageStreamSource = new FileStream("Images\bulbOff.png", FileMode.Open, FileAccess.Read, FileShare.Read);
PngBitmapDecoder decoder = new PngBitmapDecoder(imageStreamSource, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
BitmapSource bitmapSource = decoder.Frames[0];
</code>```

And then while trying to run the program, I got:

```<code>XamlParseException
</code>```

with hardly any information.
For sure the first line is causing the problem, because the problem disappears only when I delete it.

I tried to do it also like:

```<code>Uri myUri = new Uri("Images\bulbOff.png", UriKind.RelativeOrAbsolute);
PngBitmapDecoder decoder2 = new PngBitmapDecoder(myUri, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
BitmapSource bitmapSource2 = decoder2.Frames[0];
</code>```

with the same result.
I also tried to copy the image to main folder of app (in SolutionView). When I tried to get "\bulbOff.png" the result was the same.
When I tried to get "bulbOff.png" I got

```<code>XamlParseException
</code>```

again, but with some info - there were hints that path could be wrong.

答:
If you want to provide a BitmapImage...

```<code>BitmapImage image = new BitmapImage();
image.BeginInit();
image.UriSource = new Uri(@"..\Images\DocumentAccess_16x16.png", UriKind.Relative);
image.EndInit();
</code>```

...where Images is a folder within your project.

ContentLicense: CC BY-SA 2.5

Title: Can't open an image in WPF app

Body:
In my application I want to display some pictures (I need to have them stored in a list). I have problem with opening them. Firstly, I made a directory Images (using VS). Next I loaded pictures to this folder (also in VS).
I wanted to open one of them like here:
http://msdn.microsoft.com/en-us/library/aa970062.aspx

Stream imageStreamSource = new FileStream("Images\bulbOff.png", FileMode.Open, FileAccess.Read, FileShare.Read);
PngBitmapDecoder decoder = new PngBitmapDecoder(imageStreamSource, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
BitmapSource bitmapSource = decoder.Frames[0];

And then while trying to run the program, I got:

XamlParseException

with hardly any information.
For sure the first line is causing the problem, because the problem disappears only when I delete it.

I tried to do it also like:

Uri myUri = new Uri("Images\bulbOff.png", UriKind.RelativeOrAbsolute);
PngBitmapDecoder decoder2 = new PngBitmapDecoder(myUri, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
BitmapSource bitmapSource2 = decoder2.Frames[0];

with the same result.
I also tried to copy the image to main folder of app (in SolutionView). When I tried to get "\bulbOff.png" the result was the same.
When I tried to get "bulbOff.png" I got

XamlParseException

again, but with some info - there were hints that path could be wrong.

Body:
If you want to provide a BitmapImage...

BitmapImage image = new BitmapImage();
image.BeginInit();
image.UriSource = new Uri(@"..\Images\DocumentAccess_16x16.png", UriKind.Relative);
image.EndInit();

...where Images is a folder within your project.


问:
Tkinter Label image without border
this is my first post. I visit frequently stack overflow and I previously have always found answers for all my questions, but not today.

I try to display images as labels in window, but it is not how I thought Tkinter would display them. In other words. I have several small images, which should be place each next to another without any gap. But in besides all my efforts Tkinter always place small border or gap (probably 1-2 pixel), between two neighbor elements.

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

class MainWindow():

def __init__(self, mainWidget):

    self.status_bar_text = StringVar()
    self.status_bar_text.set('')

    self.image_to_place = PhotoImage(file='my_image.png')

    self.main_frame = ttk.Frame(mainWidget, width=768, height=480, padding=(0, 0, 0, 0))
    self.main_frame.place(x=0, y=0)

    self.status_bar = ttk.Label(mainWidget, width=768, border=1, anchor=W, relief=SUNKEN, textvariable=self.status_bar_text)
    self.status_bar.place(x=0, y=480)

    self.main_gui()

def main_gui(self):
    i = 0
    plate_cords = [[0, 0], [24, 0], [48, 0], [72, 0], [96, 0], [120, 0]]

    for plate in plate_cords:
        self.wall_label = ttk.Label(self.main_frame, image=self.image_to_place)
        self.wall_label.place(x=plate_cords[i][0], y=plate_cords[i][1])
        i += 1
    del i

def main():
    global root
    root = Tk()
    root.title('Title')
    root.geometry('768x500+250+100')
    root.rowconfigure(0, weight=1)
    root.columnconfigure(0, weight=1)

    window = MainWindow(root)
    window

    root.mainloop()

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

I tried options such us 'borderwidth', 'padding', 'bordermode' and few other tricks, and nothing seems to work as I intend it to do. Thanks for any help and ideas.

答:
For me this worked better:</p>

```<code>Label(..., state='normal')
</code>```

ContentLicense: CC BY-SA 3.0

Title: Tkinter Label image without border

Body:
this is my first post. I visit frequently stack overflow and I previously have always found answers for all my questions, but not today.

I try to display images as labels in window, but it is not how I thought Tkinter would display them. In other words. I have several small images, which should be place each next to another without any gap. But in besides all my efforts Tkinter always place small border or gap (probably 1-2 pixel), between two neighbor elements.

from tkinter import *
from tkinter import ttk

class MainWindow():

def __init__(self, mainWidget):

    self.status_bar_text = StringVar()
    self.status_bar_text.set('')

    self.image_to_place = PhotoImage(file='my_image.png')

    self.main_frame = ttk.Frame(mainWidget, width=768, height=480, padding=(0, 0, 0, 0))
    self.main_frame.place(x=0, y=0)

    self.status_bar = ttk.Label(mainWidget, width=768, border=1, anchor=W, relief=SUNKEN, textvariable=self.status_bar_text)
    self.status_bar.place(x=0, y=480)

    self.main_gui()

def main_gui(self):
    i = 0
    plate_cords = [[0, 0], [24, 0], [48, 0], [72, 0], [96, 0], [120, 0]]

    for plate in plate_cords:
        self.wall_label = ttk.Label(self.main_frame, image=self.image_to_place)
        self.wall_label.place(x=plate_cords[i][0], y=plate_cords[i][1])
        i += 1
    del i

def main():
    global root
    root = Tk()
    root.title('Title')
    root.geometry('768x500+250+100')
    root.rowconfigure(0, weight=1)
    root.columnconfigure(0, weight=1)

    window = MainWindow(root)
    window

    root.mainloop()

if __name__ == '__main__':
    main()

I tried options such us 'borderwidth', 'padding', 'bordermode' and few other tricks, and nothing seems to work as I intend it to do. Thanks for any help and ideas.

Body:
For me this worked better:

Label(..., state='normal')


问:
How to build a swipable intro screen?
A lot of apps have swipable intro screens - You know - those with the dots below which indicate the page one is currently viewing.

What would be the best way to create one in Codename One - a Container with snapToGrid?

答:
OK - so that is my first attempt and I am pretty content with that:

```<code>private void showIntro() {
    Display display = Display.getInstance();
    int percentage = 60;
    int snapWidth = display.getDisplayWidth() * percentage / 100;
    int snapHeight = display.getDisplayHeight() * percentage / 100;
    Dialog dialog = new Dialog(new LayeredLayout()) {
        @Override
        protected Dimension calcPreferredSize() {
            return new Dimension(snapWidth, snapHeight);
        }
    };
    Tabs tabs = new Tabs();
    tabs.setTensileLength(0);
    tabs.hideTabs();
    int[] colors = {
            0xc00000,
            0x00c000,
            0x0000c0,
            0x909000,
            0x009090,
    };
    for (int colorIndex = 0; colorIndex < colors.length; colorIndex++) {
        Container containerElement = new Container() {
            @Override
            protected Dimension calcPreferredSize() {
                return new Dimension(snapWidth, snapHeight);
            }
        };
        Style style = containerElement.getAllStyles();
        style.setBgTransparency(0xff);
        style.setBgColor(colors[colorIndex]);
        tabs.addTab("tab" + tabs.getTabCount(),  containerElement);
    }
    int tabCount = tabs.getTabCount();
    Button[] buttons = new Button[tabCount];
    Style styleButton = UIManager.getInstance().getComponentStyle("Button");
    styleButton.setFgColor(0xffffff);
    Image imageDot = FontImage.createMaterial(FontImage.MATERIAL_LENS, styleButton);
    for (int tabIndex = 0; tabIndex < tabCount; tabIndex++) {
        buttons[tabIndex] = new Button(imageDot);
        buttons[tabIndex].setUIID("Container");
        final int tabIndexFinal = tabIndex;
        buttons[tabIndex].addActionListener(aActionEvent -> tabs.setSelectedIndex(tabIndexFinal, true));
    }
    Container containerButtons = FlowLayout.encloseCenter(buttons);
    dialog.add(tabs);
    Button buttonWest = new Button("Skip");
    buttonWest.setUIID("Container");
    buttonWest.getAllStyles().setFgColor(0xffffff);
    buttonWest.addActionListener(aActionEvent -> dialog.dispose());
    Button buttonEast = new Button(">");
    buttonEast.setUIID("Container");
    buttonEast.getAllStyles().setFgColor(0xffffff);
    buttonEast.addActionListener(aActionEvent -> {
        int selectedIndex = tabs.getSelectedIndex();
        if (selectedIndex < (tabs.getTabCount() - 1)) {
            tabs.setSelectedIndex(selectedIndex + 1, true);
        } else {
            dialog.dispose();
        }
    });
    Container containerSouth = BorderLayout.south(BorderLayout.centerAbsoluteEastWest(containerButtons, buttonEast, buttonWest));
    Style styleContainerSouth = containerSouth.getAllStyles();
    styleContainerSouth.setMarginUnit(
            Style.UNIT_TYPE_DIPS,
            Style.UNIT_TYPE_DIPS,
            Style.UNIT_TYPE_DIPS,
            Style.UNIT_TYPE_DIPS);
    styleContainerSouth.setMargin(2, 2, 2, 2);
    dialog.add(containerSouth);
    SelectionListener selectionListener = (aOldSelectionIndex, aNewSelectionIndex) -> {
        for (int buttonIndex = 0; buttonIndex < buttons.length; buttonIndex++) {
            if (buttonIndex == aNewSelectionIndex) {
                buttons[buttonIndex].getAllStyles().setOpacity(0xff);
            } else {
                buttons[buttonIndex].getAllStyles().setOpacity(0xc0);
            }
        }
        buttonEast.setText((aNewSelectionIndex < (tabs.getTabCount() - 1)) ? ">" : "Finish");
        buttonEast.getParent().animateLayout(400);
    };
    tabs.addSelectionListener(selectionListener);
    dialog.addShowListener(evt -> {
        buttonEast.getParent().layoutContainer();
        selectionListener.selectionChanged(-1, 0);
    });
    Command command = dialog.showPacked(BorderLayout.CENTER, true);
}
</code>```

Title: How to build a swipable intro screen?

Body:
OK - so that is my first attempt and I am pretty content with that:

private void showIntro() {
    Display display = Display.getInstance();
    int percentage = 60;
    int snapWidth = display.getDisplayWidth() * percentage / 100;
    int snapHeight = display.getDisplayHeight() * percentage / 100;
    Dialog dialog = new Dialog(new LayeredLayout()) {
        @Override
        protected Dimension calcPreferredSize() {
            return new Dimension(snapWidth, snapHeight);
        }
    };
    Tabs tabs = new Tabs();
    tabs.setTensileLength(0);
    tabs.hideTabs();
    int[] colors = {
            0xc00000,
            0x00c000,
            0x0000c0,
            0x909000,
            0x009090,
    };
    for (int colorIndex = 0; colorIndex < colors.length; colorIndex++) {
        Container containerElement = new Container() {
            @Override
            protected Dimension calcPreferredSize() {
                return new Dimension(snapWidth, snapHeight);
            }
        };
        Style style = containerElement.getAllStyles();
        style.setBgTransparency(0xff);
        style.setBgColor(colors[colorIndex]);
        tabs.addTab("tab" + tabs.getTabCount(),  containerElement);
    }
    int tabCount = tabs.getTabCount();
    Button[] buttons = new Button[tabCount];
    Style styleButton = UIManager.getInstance().getComponentStyle("Button");
    styleButton.setFgColor(0xffffff);
    Image imageDot = FontImage.createMaterial(FontImage.MATERIAL_LENS, styleButton);
    for (int tabIndex = 0; tabIndex < tabCount; tabIndex++) {
        buttons[tabIndex] = new Button(imageDot);
        buttons[tabIndex].setUIID("Container");
        final int tabIndexFinal = tabIndex;
        buttons[tabIndex].addActionListener(aActionEvent -> tabs.setSelectedIndex(tabIndexFinal, true));
    }
    Container containerButtons = FlowLayout.encloseCenter(buttons);
    dialog.add(tabs);
    Button buttonWest = new Button("Skip");
    buttonWest.setUIID("Container");
    buttonWest.getAllStyles().setFgColor(0xffffff);
    buttonWest.addActionListener(aActionEvent -> dialog.dispose());
    Button buttonEast = new Button(">");
    buttonEast.setUIID("Container");
    buttonEast.getAllStyles().setFgColor(0xffffff);
    buttonEast.addActionListener(aActionEvent -> {
        int selectedIndex = tabs.getSelectedIndex();
        if (selectedIndex < (tabs.getTabCount() - 1)) {
            tabs.setSelectedIndex(selectedIndex + 1, true);
        } else {
            dialog.dispose();
        }
    });
    Container containerSouth = BorderLayout.south(BorderLayout.centerAbsoluteEastWest(containerButtons, buttonEast, buttonWest));
    Style styleContainerSouth = containerSouth.getAllStyles();
    styleContainerSouth.setMarginUnit(
            Style.UNIT_TYPE_DIPS,
            Style.UNIT_TYPE_DIPS,
            Style.UNIT_TYPE_DIPS,
            Style.UNIT_TYPE_DIPS);
    styleContainerSouth.setMargin(2, 2, 2, 2);
    dialog.add(containerSouth);
    SelectionListener selectionListener = (aOldSelectionIndex, aNewSelectionIndex) -> {
        for (int buttonIndex = 0; buttonIndex < buttons.length; buttonIndex++) {
            if (buttonIndex == aNewSelectionIndex) {
                buttons[buttonIndex].getAllStyles().setOpacity(0xff);
            } else {
                buttons[buttonIndex].getAllStyles().setOpacity(0xc0);
            }
        }
        buttonEast.setText((aNewSelectionIndex < (tabs.getTabCount() - 1)) ? ">" : "Finish");
        buttonEast.getParent().animateLayout(400);
    };
    tabs.addSelectionListener(selectionListener);
    dialog.addShowListener(evt -> {
        buttonEast.getParent().layoutContainer();
        selectionListener.selectionChanged(-1, 0);
    });
    Command command = dialog.showPacked(BorderLayout.CENTER, true);
}


问:
MySQL Date For Monthly Reporting
I need some help with running a query at month end. Each 1st working day of a month may differ, and therefore I may only be at work on the 3rd of a given month.

I am trying to figure out what my WHERE statement would look like to select data for the current month, unless it is:
1st of a month, then it will need to select everything from the previous month
1st working day of a month, which could be the 3rd. It will then also need to select the previous month's data.

These are two scenarios I am currently playing with, and don't have data to test it with as yet.

I have thought about doing

```<code>WHERE
MONTH(action_date) = MONTH(DATE_SUB(CURDATE(),INTERVAL 1 DAY))
</code>```

But this then also returns data from 2016.

I have also thought of doing

```<code>WHERE
action_date = DATE_SUB(CURDATE(),INTERVAL 1 DAY)
</code>```

But this would not work if today was say Monday the 3rd.

I would appreciate any answers that would give me the best way of doing this

答:
You could simply subtract a few more days or even a month from the date, as all you will actually get from the subtraction is a month anyway

```<code>MONTH(DATE_SUB(CURDATE(),INTERVAL 5 DAY))
</code>```

OR

```<code>MONTH(DATE_SUB(CURDATE(),INTERVAL 1 MONTH))
</code>```

Title: MySQL Date For Monthly Reporting

Body:
I need some help with running a query at month end. Each 1st working day of a month may differ, and therefore I may only be at work on the 3rd of a given month.

I am trying to figure out what my WHERE statement would look like to select data for the current month, unless it is:
1st of a month, then it will need to select everything from the previous month
1st working day of a month, which could be the 3rd. It will then also need to select the previous month's data.

These are two scenarios I am currently playing with, and don't have data to test it with as yet.

I have thought about doing

WHERE
MONTH(action_date) = MONTH(DATE_SUB(CURDATE(),INTERVAL 1 DAY))

But this then also returns data from 2016.

I have also thought of doing

WHERE
action_date = DATE_SUB(CURDATE(),INTERVAL 1 DAY)

But this would not work if today was say Monday the 3rd.

I would appreciate any answers that would give me the best way of doing this

Body:
You could simply subtract a few more days or even a month from the date, as all you will actually get from the subtraction is a month anyway

MONTH(DATE_SUB(CURDATE(),INTERVAL 5 DAY))

OR

MONTH(DATE_SUB(CURDATE(),INTERVAL 1 MONTH))


问:
replace part of href between 2 words jquery
This is simple and I have done it before but can't make it work right now.

I need to change the name of the image in below href

var href="https://www.facebook.com/sharer/sharer.php?u=http://myurl.com/&description='tets'&picture=http://myurl.com/img/name-1654-45654.jpg"

$('.share, .share-2').prop('href', function () {
    $(this).replace(/(picture=).*?(&)/,'$1' + imgNew + '$2');
});
```

答:
You should change your code to the following one.

```<code>  href="https://www.facebook.com/sharer/sharer.php?u=http://myurl.com/&description='tets'&picture=http://myurl.com/img/name-1654-45654.jpg"

    $('.share, .share-2').prop('href', function () {
        $(this).replace(/\/(?=[^\/]*$)/, '/newpicturename'));
       });
</code>```

The last slash and following words will be replaced by the new picture name.

An example

var str = "http://one/two/three/four";
console.log(str.replace(/\/(?=[^\/]*$)/, '/newpicturename'));```

Body:
You should change your code to the following one.

  href="https://www.facebook.com/sharer/sharer.php?u=http://myurl.com/&description='tets'&picture=http://myurl.com/img/name-1654-45654.jpg"

    $('.share, .share-2').prop('href', function () {
        $(this).replace(/\/(?=[^\/]*$)/, '/newpicturename'));
       });

The last slash and following words will be replaced by the new picture name.

An example

var str = "http://one/two/three/four";
console.log(str.replace(/\/(?=[^\/]*$)/, '/newpicturename'));


问:
reducing list based on fuzzy values in python
I have a list that contains groups of nearly identical numeric values. i.e. (1004.523, 1004.575, 1004.475, 791.385, 791.298, 791.301, 791.305, 791.299)

What I am trying to do is read through the list and find all the 1004.5 +- values aggregate them and find the average value. then continue on and find all the 791.0 +- values and do the same to them.

I do not know how many individual values there will be in each "group" nor do I know how many groups there will be.

The result I am looking for is another list which would contain the average values of each of the groups. So in the example my result would be (1004.524, 791.3176)

The code I'm currently using is very Kludgey and it seems there should be a much better way to do it.

As you can see I have to repeat code twice once in the else and once at the end of the if since the last set of numbers does not trigger the else. Plus at the completion of the if I need to add the last value.

If I use the len(tones) rather that len(tones)-i I get an out of range error.

Any thoughts or suggestions would be appreciated. Thanks for your help.

Ed

```<code>    toneLen = len(tones) -1
    for i in range(0, toneLen):
        if abs(tones[i]-tones[i+1]) <= 2.0:
            tmpTones.append(tones[i])
        else:
            freq = mean(tmpTones)
            newTones.append(freq)
            tmpTones = []
    tmpTones.append(tones[i+1])
    freq = mean(tmpTones)
    newTones.append(freq)
    tones = newTones
</code>```

UPDATE:
First I wanted to thank everyone who submitted suggestions. The response was very quick and helpful. I should have probably included some more info which I am doing below. Thanks so much for your help.

Second , a quick explanation of what I am trying to do. Our local Fire Department is looking for a way to track dispatches for departments close to them. For the most part they use two tone sequential paging i.e. 1000Hz followed by 500Hz.

So I am using numpy fft to find the tone frequency. Since the accuracy of the tone appears to be about +- 2 Hz, I compare the calculated frequency to a list of known paging tones and pick the closest match. After all the tones have been matched to the paging tones I look for matches to departments of interest.

One thing I did not know when I started this that in any given dispatch the same tone can be repeated several times, so the order of the tones is important. An example:
707.3, 339.6, 707.3, 569.1, 447.2, 569.1 would be a typical dispatch. I then look to see if any of the tone pairs are ones I'm interested in if so I display a message

Thanks again for all your help.

Ed

答:
Perhaps you are looking for kmeans clustering.

In the code below, I use scipy.cluster.vq.kmeans to cluster the data into k groups.
If the distortion is greater than some set threshold amount, then we increase k by one, and redo the kmeans clustering. We repeat until we find groups whose total distortion is less than the threshold amount.

```<code>import scipy.cluster.vq as scv
import numpy as np
import collections
def auto_cluster(data,threshold=0.1):
    # There are more sophisticated ways of determining k
    # See http://en.wikipedia.org/wiki/Determining_the_number_of_clusters_in_a_data_set
    k=1
    distortion=1e20
    while distortion>threshold:
        codebook,distortion=scv.kmeans(data,k)
        k+=1
    code,dist=scv.vq(data,codebook)
    groups=collections.defaultdict(list)
    for index,datum in zip(code,data):
        groups[index].append(datum)
    return groups

data=np.array((1004.523, 1004.575, 1004.475, 791.385, 791.298, 791.301, 791.305, 791.299))
groups=auto_cluster(data)
for index in groups:
    print('{index}: ave({d}) = {ave}'.format(
        index=index,
        d=','.join(map('{0:g}'.format,groups[index])),
        ave=np.mean(groups[index]))
        )
</code>```

yields

```<code>0: ave(791.385,791.298,791.301,791.305,791.299) = 791.3176
1: ave(1004.52,1004.58,1004.48) = 1004.52433333
</code>```

Body:
I have a list that contains groups of nearly identical numeric values. i.e. (1004.523, 1004.575, 1004.475, 791.385, 791.298, 791.301, 791.305, 791.299)

What I am trying to do is read through the list and find all the 1004.5 +- values aggregate them and find the average value. then continue on and find all the 791.0 +- values and do the same to them.

I do not know how many individual values there will be in each "group" nor do I know how many groups there will be.

The result I am looking for is another list which would contain the average values of each of the groups. So in the example my result would be (1004.524, 791.3176)

The code I'm currently using is very Kludgey and it seems there should be a much better way to do it.

As you can see I have to repeat code twice once in the else and once at the end of the if since the last set of numbers does not trigger the else. Plus at the completion of the if I need to add the last value.

If I use the len(tones) rather that len(tones)-i I get an out of range error.

Any thoughts or suggestions would be appreciated. Thanks for your help.

Ed

    toneLen = len(tones) -1
    for i in range(0, toneLen):
        if abs(tones[i]-tones[i+1]) <= 2.0:
            tmpTones.append(tones[i])
        else:
            freq = mean(tmpTones)
            newTones.append(freq)
            tmpTones = []
    tmpTones.append(tones[i+1])
    freq = mean(tmpTones)
    newTones.append(freq)
    tones = newTones

UPDATE:
First I wanted to thank everyone who submitted suggestions. The response was very quick and helpful. I should have probably included some more info which I am doing below. Thanks so much for your help.

Second , a quick explanation of what I am trying to do. Our local Fire Department is looking for a way to track dispatches for departments close to them. For the most part they use two tone sequential paging i.e. 1000Hz followed by 500Hz.

So I am using numpy fft to find the tone frequency. Since the accuracy of the tone appears to be about +- 2 Hz, I compare the calculated frequency to a list of known paging tones and pick the closest match. After all the tones have been matched to the paging tones I look for matches to departments of interest.

One thing I did not know when I started this that in any given dispatch the same tone can be repeated several times, so the order of the tones is important. An example:
707.3, 339.6, 707.3, 569.1, 447.2, 569.1 would be a typical dispatch. I then look to see if any of the tone pairs are ones I'm interested in if so I display a message

Thanks again for all your help.

Ed

Body:
Perhaps you are looking for kmeans clustering.

In the code below, I use scipy.cluster.vq.kmeans to cluster the data into k groups.
If the distortion is greater than some set threshold amount, then we increase k by one, and redo the kmeans clustering. We repeat until we find groups whose total distortion is less than the threshold amount.

import scipy.cluster.vq as scv
import numpy as np
import collections
def auto_cluster(data,threshold=0.1):
    # There are more sophisticated ways of determining k
    # See http://en.wikipedia.org/wiki/Determining_the_number_of_clusters_in_a_data_set
    k=1
    distortion=1e20
    while distortion>threshold:
        codebook,distortion=scv.kmeans(data,k)
        k+=1
    code,dist=scv.vq(data,codebook)
    groups=collections.defaultdict(list)
    for index,datum in zip(code,data):
        groups[index].append(datum)
    return groups

data=np.array((1004.523, 1004.575, 1004.475, 791.385, 791.298, 791.301, 791.305, 791.299))
groups=auto_cluster(data)
for index in groups:
    print('{index}: ave({d}) = {ave}'.format(
        index=index,
        d=','.join(map('{0:g}'.format,groups[index])),
        ave=np.mean(groups[index]))
        )

yields

0: ave(791.385,791.298,791.301,791.305,791.299) = 791.3176
1: ave(1004.52,1004.58,1004.48) = 1004.52433333


问:
Vagrant up : bad interpreter: No such file or directory
Facing the following error while running vagrant up via cygwin.

```<code> stderr: /bin/bash: /home/vagrant/.ansible/tmp/ansible-tmp-1487226010.33-231113224080537/configure.sh: /bin/bash^M: bad interpreter: No such file or directory
</code>```

When checked, I cant find the configure.sh anywhere.

Cant figure out cause of this issue. Is this due to any missing configuration.

Full error:

```<code>$ vagrant up
Running on Ruby 2.0.0
Resolved settings:
---
vm:
  memory: '8192'
paths:
  ptc: C:/MYCERT
  mvnrepo: C:/Users/Cmpy/.m2/repository
  workspace: C:/code/vagrant/myCode
  install: C:/code/vagrant/install
  licenses: C:/code/vagrant/licenses
jive:
  jrebel: false
gsa:
  fgs:
    version: '1.0'
Bringing machine 'mySDK' up with 'virtualbox' provider...
==> mySDK: Importing base box 'centos-6.5-x86_64'...
==> mySDK: Matching MAC address for NAT networking...
==> mySDK: Setting the name of the VM: name_1487225947556_22185
==> mySDK: Clearing any previously set network interfaces...
==> mySDK: Preparing network interfaces based on configuration...
    mySDK: Adapter 1: nat
    mySDK: Adapter 2: hostonly
==> mySDK: Forwarding ports...
    mySDK: 10389 => 10389 (adapter 1)
    mySDK: 8080 => 8080 (adapter 1)
    mySDK: 8443 => 8443 (adapter 1)
    mySDK: 5432 => 5432 (adapter 1)
    mySDK: 7020 => 7020 (adapter 1)
    mySDK: 30000 => 30000 (adapter 1)
    mySDK: 19900 => 19900 (adapter 1)
    mySDK: 9020 => 9020 (adapter 1)
    mySDK: 9030 => 9030 (adapter 1)
    mySDK: 22 => 2222 (adapter 1)
==> mySDK: Running 'pre-boot' VM customizations...
==> mySDK: Booting VM...
==> mySDK: Waiting for machine to boot. This may take a few minutes...
    mySDK: SSH address: 127.0.0.1:2222
    mySDK: SSH username: vagrant
    mySDK: SSH auth method: private key
    mySDK: Warning: Connection timeout. Retrying...
==> mySDK: Machine booted and ready!
==> mySDK: Checking for guest additions in VM...
==> mySDK: Setting hostname...
==> mySDK: Configuring and enabling network interfaces...
==> mySDK: Mounting shared folders...
    mySDK: /PTC => C:/MYCERT
    mySDK: /workspace => C:/code/vagrant/myCode
    mySDK: /vagrant/ds => C:/code/vagrant/myCode/src/apacheds
    mySDK: /vagrant/db => C:/code/vagrant/myCode/src/provisioning/db
    mySDK: /vagrant/ssl => C:/code/vagrant/myCode/src/provisioning/ssl
    mySDK: /vagrant/vars => C:/code/vagrant/myCode
    mySDK: /vagrant/conf => C:/code/vagrant/myCode/src/provisioning/conf
    mySDK: /local_repository => C:/Users/Cmpy/.m2/repository
    mySDK: /vagrant/.install => C:/code/vagrant/install
    mySDK: /vagrant/.licenses => C:/code/vagrant/licenses
    mySDK: /vagrant/provisioning => C:/code/vagrant/myCode/src/provisioning
    mySDK: /vagrant/jboss_deployment => C:/code/vagrant/myCode/deploy
==> mySDK: Running provisioner: shell...
    mySDK: Running: C:/cygwin64/tmp/vagrant-shell20170216-3164-fiz5m3.sh
==> mySDK:
==> mySDK: PLAY [127.0.0.1] **************************************************************
==> mySDK:
==> mySDK: GATHERING FACTS ***************************************************************
==> mySDK: ok: [127.0.0.1]
==> mySDK:
==> mySDK: TASK: [common | Configure Java and ApacheDS] **********************************
==> mySDK: failed: [127.0.0.1] => {"changed": true, "rc": 126}
==> mySDK: stderr: /bin/bash: /home/vagrant/.ansible/tmp/ansible-tmp-1487226010.33-231113224080537/configure.sh: /bin/bash^M: bad interpreter: No such file or directory
==> mySDK:
==> mySDK:
==> mySDK: FATAL: all hosts have already failed -- aborting
==> mySDK:
==> mySDK: PLAY RECAP ********************************************************************
==> mySDK:            to retry, use: --limit @/home/vagrant/site.retry
==> mySDK:
==> mySDK: 127.0.0.1                  : ok=1    changed=0    unreachable=0    failed=1
The following SSH command responded with a non-zero exit status.
Vagrant assumes that this means the command failed!

chmod +x /tmp/vagrant-shell && /tmp/vagrant-shell

Stdout from the command:

PLAY [127.0.0.1] **************************************************************

GATHERING FACTS ***************************************************************
ok: [127.0.0.1]

TASK: [common | Configure Java and ApacheDS] **********************************
failed: [127.0.0.1] => {"changed": true, "rc": 126}
stderr: /bin/bash: /home/vagrant/.ansible/tmp/ansible-tmp-1487226010.33-231113224080537/configure.sh: /bin/bash^M: bad interpreter: No such file or directory

FATAL: all hosts have already failed -- aborting

PLAY RECAP ********************************************************************
           to retry, use: --limit @/home/vagrant/site.retry

127.0.0.1                  : ok=1    changed=0    unreachable=0    failed=1

Stderr from the command:
</code>```

答: Instead of using Cygwin, which doesn't handle UNIX/LINUX style line endings, I recommend installing ansible on Windows 10 Ubuntu subsystem to automagically handle things. You'll find this biting you more and more working with OSS users not to mention this issue will come up when you start using ansible vaults.</p>

Body:
Facing the following error while running vagrant up via cygwin.

 stderr: /bin/bash: /home/vagrant/.ansible/tmp/ansible-tmp-1487226010.33-231113224080537/configure.sh: /bin/bash^M: bad interpreter: No such file or directory

When checked, I cant find the configure.sh anywhere.

Cant figure out cause of this issue. Is this due to any missing configuration.

Full error:

$ vagrant up
Running on Ruby 2.0.0
Resolved settings:
---
vm:
  memory: '8192'
paths:
  ptc: C:/MYCERT
  mvnrepo: C:/Users/Cmpy/.m2/repository
  workspace: C:/code/vagrant/myCode
  install: C:/code/vagrant/install
  licenses: C:/code/vagrant/licenses
jive:
  jrebel: false
gsa:
  fgs:
    version: '1.0'
Bringing machine 'mySDK' up with 'virtualbox' provider...
==> mySDK: Importing base box 'centos-6.5-x86_64'...
==> mySDK: Matching MAC address for NAT networking...
==> mySDK: Setting the name of the VM: name_1487225947556_22185
==> mySDK: Clearing any previously set network interfaces...
==> mySDK: Preparing network interfaces based on configuration...
    mySDK: Adapter 1: nat
    mySDK: Adapter 2: hostonly
==> mySDK: Forwarding ports...
    mySDK: 10389 => 10389 (adapter 1)
    mySDK: 8080 => 8080 (adapter 1)
    mySDK: 8443 => 8443 (adapter 1)
    mySDK: 5432 => 5432 (adapter 1)
    mySDK: 7020 => 7020 (adapter 1)
    mySDK: 30000 => 30000 (adapter 1)
    mySDK: 19900 => 19900 (adapter 1)
    mySDK: 9020 => 9020 (adapter 1)
    mySDK: 9030 => 9030 (adapter 1)
    mySDK: 22 => 2222 (adapter 1)
==> mySDK: Running 'pre-boot' VM customizations...
==> mySDK: Booting VM...
==> mySDK: Waiting for machine to boot. This may take a few minutes...
    mySDK: SSH address: 127.0.0.1:2222
    mySDK: SSH username: vagrant
    mySDK: SSH auth method: private key
    mySDK: Warning: Connection timeout. Retrying...
==> mySDK: Machine booted and ready!
==> mySDK: Checking for guest additions in VM...
==> mySDK: Setting hostname...
==> mySDK: Configuring and enabling network interfaces...
==> mySDK: Mounting shared folders...
    mySDK: /PTC => C:/MYCERT
    mySDK: /workspace => C:/code/vagrant/myCode
    mySDK: /vagrant/ds => C:/code/vagrant/myCode/src/apacheds
    mySDK: /vagrant/db => C:/code/vagrant/myCode/src/provisioning/db
    mySDK: /vagrant/ssl => C:/code/vagrant/myCode/src/provisioning/ssl
    mySDK: /vagrant/vars => C:/code/vagrant/myCode
    mySDK: /vagrant/conf => C:/code/vagrant/myCode/src/provisioning/conf
    mySDK: /local_repository => C:/Users/Cmpy/.m2/repository
    mySDK: /vagrant/.install => C:/code/vagrant/install
    mySDK: /vagrant/.licenses => C:/code/vagrant/licenses
    mySDK: /vagrant/provisioning => C:/code/vagrant/myCode/src/provisioning
    mySDK: /vagrant/jboss_deployment => C:/code/vagrant/myCode/deploy
==> mySDK: Running provisioner: shell...
    mySDK: Running: C:/cygwin64/tmp/vagrant-shell20170216-3164-fiz5m3.sh
==> mySDK:
==> mySDK: PLAY [127.0.0.1] **************************************************************
==> mySDK:
==> mySDK: GATHERING FACTS ***************************************************************
==> mySDK: ok: [127.0.0.1]
==> mySDK:
==> mySDK: TASK: [common | Configure Java and ApacheDS] **********************************
==> mySDK: failed: [127.0.0.1] => {"changed": true, "rc": 126}
==> mySDK: stderr: /bin/bash: /home/vagrant/.ansible/tmp/ansible-tmp-1487226010.33-231113224080537/configure.sh: /bin/bash^M: bad interpreter: No such file or directory
==> mySDK:
==> mySDK:
==> mySDK: FATAL: all hosts have already failed -- aborting
==> mySDK:
==> mySDK: PLAY RECAP ********************************************************************
==> mySDK:            to retry, use: --limit @/home/vagrant/site.retry
==> mySDK:
==> mySDK: 127.0.0.1                  : ok=1    changed=0    unreachable=0    failed=1
The following SSH command responded with a non-zero exit status.
Vagrant assumes that this means the command failed!

chmod +x /tmp/vagrant-shell && /tmp/vagrant-shell

Stdout from the command:

PLAY [127.0.0.1] **************************************************************

GATHERING FACTS ***************************************************************
ok: [127.0.0.1]

TASK: [common | Configure Java and ApacheDS] **********************************
failed: [127.0.0.1] => {"changed": true, "rc": 126}
stderr: /bin/bash: /home/vagrant/.ansible/tmp/ansible-tmp-1487226010.33-231113224080537/configure.sh: /bin/bash^M: bad interpreter: No such file or directory

FATAL: all hosts have already failed -- aborting

PLAY RECAP ********************************************************************
           to retry, use: --limit @/home/vagrant/site.retry

127.0.0.1                  : ok=1    changed=0    unreachable=0    failed=1

Stderr from the command:


问:
Environment on Jitterbit Harmony does not show up in Jitterbit Studio
I am new to Jitterbit. I was given the access to an environment which shows up in Jitterbit Harmony website - Environments. However after logging into Jitterbit Studio on my desktop (with internet connection, refreshed), I cannot find that particular environment in the upper left corner's drop-down. Do I need to do anything in particular for integration?</p>

答: Stupid question, but have you tried the refresh button in the environment list?


问:
Cannot Connect to Oracle Thin Database in SoapUI but can in dbVisualizer
I've tried about every different method using the built in jdbc connections and groovy scripts.
I've tried with oracle thin drivers 14, 6, 7, and 8.

My connection string is in the format (changes where user/pass goes depending on where I use it):

```<code>jdbc:oracle:thin:@(DESCRIPTION=(LOAD_BALANCE=yes)(ADDRESS=(PROTOCOL=TCP)(HOST=host1)(PORT=1521))(ADDRESS=(PROTOCOL=TCP)(HOST=host2)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=serviceName)))
</code>```

Getting below errors:

the network adapter could not establish the connection

invalid username/password

The user and pass are correct, I've retyped them many times and the same user/pass work in dbVisualizer.

Looking for any suggestions on other things to try.

答:
It turns out we were actually used the Service Name and not the SID (We only had the service name and assumed it was the correct thing to be used.

So Service Name != SID

But we could not just plug in the Service Name and get it to work because to use the Service Name instead the connection string has to be changed and therefore the jbdc driver template had to be changed (or you could create a new one).

We changed it to:

```<code>jdbc:oracle:thin:<USER>/<PASSWORD>@//<HOST:127.0.0.1>:<PORT:1521>/<SID>
</code>```

The reason we have  on the end and not  (or something similar) is because SoapUI only seemed to recognize  as a field it would make a UI element from when creating a new connection.

After change it to this and entering in the correct information everything worked.

Body:
I've tried about every different method using the built in jdbc connections and groovy scripts.
I've tried with oracle thin drivers 14, 6, 7, and 8.

My connection string is in the format (changes where user/pass goes depending on where I use it):

jdbc:oracle:thin:@(DESCRIPTION=(LOAD_BALANCE=yes)(ADDRESS=(PROTOCOL=TCP)(HOST=host1)(PORT=1521))(ADDRESS=(PROTOCOL=TCP)(HOST=host2)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=serviceName)))

Getting below errors:

the network adapter could not establish the connection

invalid username/password

The user and pass are correct, I've retyped them many times and the same user/pass work in dbVisualizer.

Looking for any suggestions on other things to try.

Body:
It turns out we were actually used the Service Name and not the SID (We only had the service name and assumed it was the correct thing to be used.

So Service Name != SID

But we could not just plug in the Service Name and get it to work because to use the Service Name instead the connection string has to be changed and therefore the jbdc driver template had to be changed (or you could create a new one).

We changed it to:

jdbc:oracle:thin:<USER>/<PASSWORD>@//<HOST:127.0.0.1>:<PORT:1521>/<SID>

The reason we have  on the end and not  (or something similar) is because SoapUI only seemed to recognize  as a field it would make a UI element from when creating a new connection.

After change it to this and entering in the correct information everything worked.


问:
Update Android calendar events
I'm trying to update calendar events programmatically but I have some issues.

I'm using updating code from Google Android Documentation: https://developer.android.com/guide/topics/providers/calendar-provider.html#update-event

So here's my code :

```<code>ContentValues values = new ContentValues();
        Uri updateUri = null;
        // New end for event
        values.put(CalendarContract.Events.DTEND, endMillis);
        updateUri = ContentUris.withAppendedId(CalendarContract.Events.CONTENT_URI, eventID);
        int rows = c.getContentResolver().update(updateUri, values, null, null);
        Log.i("DEBUG_TAG", "Rows updated: " + rows);
</code>```

But rows variable always returns 0 except when I go into apps settings, remove calendar storage, add a new calendar and a new event and then when I try to update it, it works only once. If I try to add another event and update it afterward, rows return 0 again.

Any idea?

Thanks

Please note that my app is min API level 17 (on which it doesn't work) but I tried on API level 25 and it works, so do you have any idea how to add support to my code for previous Android versions? I've also found that after some tests, it works from API level 21. Under, it doesn't.

EDIT :
I've found a solution, check my answer below.

答:
Here's the solution that worked for me :

The eventID that I used was the result of the query with column CalendarContract.Events._ID but I had to used the ID provided by CalendarContract.Instances.EVENT_ID.
Indeed if I create a new event (the first one) it has _id = 1 and event_id = 1, and if I delete it from Android Calendar App and I create a new one with my app, it has also _id = 1 but event_id = 2.
So the update query failed if I use _id instead of event_id with withAppendedID().

Here's the code that worked for me. startMillis and endMillis are respectively your meeting start time and end time in milliseconds.

```<code>        Uri.Builder eventsUriBuilder = CalendarContract.Instances.CONTENT_URI
                .buildUpon();
        ContentUris.appendId(eventsUriBuilder, startMillis);
        ContentUris.appendId(eventsUriBuilder, endMillis);
        Uri eventsUri = eventsUriBuilder.build();

        String[] column = {CalendarContract.Instances.EVENT_ID, CalendarContract.Events.DTSTART, CalendarContract.Events.DTEND, CalendarContract.Events.TITLE};
        Cursor cursor;
        cursor = c.getContentResolver().query(eventsUri, column, CalendarContract.Events.CALENDAR_ID+"="+Constant.ID_CALENDAR, null, CalendarContract.Instances.DTSTART + " ASC");

        if (cursor.moveToFirst()) {
            do {
                uri = ContentUris.withAppendedId(CalendarContract.Events.CONTENT_URI,cursor.getLong(0));
            } while (cursor.moveToNext());
        }

        cursor.close();
        c.getContentResolver().delete(uri, null, null);
</code>```

Title: Update Android calendar events

Body:
I'm trying to update calendar events programmatically but I have some issues.

I'm using updating code from Google Android Documentation: https://developer.android.com/guide/topics/providers/calendar-provider.html#update-event

So here's my code :

ContentValues values = new ContentValues();
        Uri updateUri = null;
        // New end for event
        values.put(CalendarContract.Events.DTEND, endMillis);
        updateUri = ContentUris.withAppendedId(CalendarContract.Events.CONTENT_URI, eventID);
        int rows = c.getContentResolver().update(updateUri, values, null, null);
        Log.i("DEBUG_TAG", "Rows updated: " + rows);

But rows variable always returns 0 except when I go into apps settings, remove calendar storage, add a new calendar and a new event and then when I try to update it, it works only once. If I try to add another event and update it afterward, rows return 0 again.

Any idea?

Thanks

Please note that my app is min API level 17 (on which it doesn't work) but I tried on API level 25 and it works, so do you have any idea how to add support to my code for previous Android versions? I've also found that after some tests, it works from API level 21. Under, it doesn't.

EDIT :
I've found a solution, check my answer below.

Body:
Here's the solution that worked for me :

The eventID that I used was the result of the query with column CalendarContract.Events._ID but I had to used the ID provided by CalendarContract.Instances.EVENT_ID.
Indeed if I create a new event (the first one) it has _id = 1 and event_id = 1, and if I delete it from Android Calendar App and I create a new one with my app, it has also _id = 1 but event_id = 2.
So the update query failed if I use _id instead of event_id with withAppendedID().

Here's the code that worked for me. startMillis and endMillis are respectively your meeting start time and end time in milliseconds.

        Uri.Builder eventsUriBuilder = CalendarContract.Instances.CONTENT_URI
                .buildUpon();
        ContentUris.appendId(eventsUriBuilder, startMillis);
        ContentUris.appendId(eventsUriBuilder, endMillis);
        Uri eventsUri = eventsUriBuilder.build();

        String[] column = {CalendarContract.Instances.EVENT_ID, CalendarContract.Events.DTSTART, CalendarContract.Events.DTEND, CalendarContract.Events.TITLE};
        Cursor cursor;
        cursor = c.getContentResolver().query(eventsUri, column, CalendarContract.Events.CALENDAR_ID+"="+Constant.ID_CALENDAR, null, CalendarContract.Instances.DTSTART + " ASC");

        if (cursor.moveToFirst()) {
            do {
                uri = ContentUris.withAppendedId(CalendarContract.Events.CONTENT_URI,cursor.getLong(0));
            } while (cursor.moveToNext());
        }

        cursor.close();
        c.getContentResolver().delete(uri, null, null);

ContentLicense: CC BY-SA 4.0


问:
SAXParseException error in XML Parsing
Using web service call ,I got the following response from server. Now i need to parse this response, Extract all field values and store it in String values

```<code><?xml version="1.0" encoding="utf-8"?>
<ecomexpress-objects version="1.0"><object pk="1" model="awb">
    <field type="BigIntegerField" name="awb_number">102019265</field>
    <field type="CharField" name="orderid">8008444</field>
    <field type="FloatField" name="actual_weight">2</field>
    <field type="CharField" name="origin">DELHI-DSW</field>
    <field type="CharField" name="destination">Mumbai - BOW</field>
    <field type="CharField" name="current_location_name">Mumbai - BOW</field>
    <field type="CharField" name="current_location_code">BOW</field>
    <field type="CharField" name="customer">Ecom Express Private Limited - 32012</field>
    <field type="CharField" name="consignee">BEECHAND VERMA</field>
    <field type="CharField" name="pickupdate">22-Jan-2014</field>
    <field type="CharField" name="status">Undelivered</field>
    <field type="CharField" name="tracking_status">Undelivered</field>
    <field type="CharField" name="reason_code">221 - Consignee Refused To Accept</field>
    <field type="CharField" name="reason_code_description">Consignee Refused To Accept</field>
    <field type="CharField" name="reason_code_number">221 </field>
    <field type="CharField" name="receiver"></field>
    <field type="CharField" name="expected_date" >15-Feb-2014</field>
    <field type="CharField" name="last_update_date" ></field>
    <field type="CharField" name="delivery_date" ></field>
    <field type="CharField" name="ref_awb" >703063993</field>
    <field type="CharField" name="rts_shipment" >0</field>
    <field type="CharField" name="system_delivery_update" ></field>
    <field type="CharField" name="rts_system_delivery_status" Undelivered</field>
    <field type="CharField" name="rts_reason_code_number">777</field>
    <field type="CharField" name="rts_last_update">22 Jan, 2014, 12:44 </field>
    <field type="CharField" name="pincode" >400037</field>
    <field type="CharField" name="city" >MUMBAI</field>
    <field type="CharField" name="state" >Maharashtra</field>
    <field name="scans">
</ecomexpress-objects>
</code>```

If i try the following code to parse

```<code>    String xml=result.toString();
    try{
       DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        InputSource is;
        is = new InputSource(new StringReader(xml));
        Document doc = db.parse(is);
        NodeList nodelist = doc.getChildNodes();
       }
      catch (SAXException e) {
        e.printStackTrace();
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
</code>```

I get the following error.

```<code>    org.xml.sax.SAXParseException: expected: /field read: ecomexpress-objects (position:END_TAG </ecomexpress-objects>@1:1917 in java.io.StringReader@39978dff)
</code>```

I need to store all field values in respective string variables

答:
Your XML is not valid.

The tag <field name="scans"> is not closed.

Title: SAXParseException error in XML Parsing

Body:
Using web service call ,I got the following response from server. Now i need to parse this response, Extract all field values and store it in String values

<?xml version="1.0" encoding="utf-8"?>
<ecomexpress-objects version="1.0"><object pk="1" model="awb">
    <field type="BigIntegerField" name="awb_number">102019265</field>
    <field type="CharField" name="orderid">8008444</field>
    <field type="FloatField" name="actual_weight">2</field>
    <field type="CharField" name="origin">DELHI-DSW</field>
    <field type="CharField" name="destination">Mumbai - BOW</field>
    <field type="CharField" name="current_location_name">Mumbai - BOW</field>
    <field type="CharField" name="current_location_code">BOW</field>
    <field type="CharField" name="customer">Ecom Express Private Limited - 32012</field>
    <field type="CharField" name="consignee">BEECHAND VERMA</field>
    <field type="CharField" name="pickupdate">22-Jan-2014</field>
    <field type="CharField" name="status">Undelivered</field>
    <field type="CharField" name="tracking_status">Undelivered</field>
    <field type="CharField" name="reason_code">221 - Consignee Refused To Accept</field>
    <field type="CharField" name="reason_code_description">Consignee Refused To Accept</field>
    <field type="CharField" name="reason_code_number">221 </field>
    <field type="CharField" name="receiver"></field>
    <field type="CharField" name="expected_date" >15-Feb-2014</field>
    <field type="CharField" name="last_update_date" ></field>
    <field type="CharField" name="delivery_date" ></field>
    <field type="CharField" name="ref_awb" >703063993</field>
    <field type="CharField" name="rts_shipment" >0</field>
    <field type="CharField" name="system_delivery_update" ></field>
    <field type="CharField" name="rts_system_delivery_status" Undelivered</field>
    <field type="CharField" name="rts_reason_code_number">777</field>
    <field type="CharField" name="rts_last_update">22 Jan, 2014, 12:44 </field>
    <field type="CharField" name="pincode" >400037</field>
    <field type="CharField" name="city" >MUMBAI</field>
    <field type="CharField" name="state" >Maharashtra</field>
    <field name="scans">
</ecomexpress-objects>

If i try the following code to parse

    String xml=result.toString();
    try{
       DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        InputSource is;
        is = new InputSource(new StringReader(xml));
        Document doc = db.parse(is);
        NodeList nodelist = doc.getChildNodes();
       }
      catch (SAXException e) {
        e.printStackTrace();
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

I get the following error.

    org.xml.sax.SAXParseException: expected: /field read: ecomexpress-objects (position:END_TAG </ecomexpress-objects>@1:1917 in java.io.StringReader@39978dff)

I need to store all field values in respective string variables


问:
Cygwin executable not found even if existing
I have recently been trying to install Blackbox on Cygwin, and as the docs say I did cp ./blackbox/bin/* /usr/bin.

Then I tried accessing it using blackbox_edit, and I get:

/bin/bash: /usr/bin/blackbox_edit: No file or directory

Same when I run /usr/bin/blackbox_edit. Running stat /usr/bin/blackbox_edit gives:

```<code>  File: /usr/bin/blackbox_edit
  Size: 958             Blocks: 4          IO Block: 65536  regular file
Device: 671faeah/108133098d     Inode: 2251799814041428  Links: 1
Access: (0755/-rwxr-xr-x)  Uid: (197609/   adrie)   Gid: (197609/   adrie)
Access: 2017-06-07 15:34:50.353508600 +0200
Modify: 2017-06-07 15:54:58.823472200 +0200
Change: 2017-06-07 15:59:00.592320500 +0200
 Birth: 2017-06-07 15:34:50.353508600 +0200
</code>```

What am I missing?

Thanks in advance.

答:
Do not use GIT to get it.  Just go to GitHub, click on the big green button on the right that says, Clone or download.  Then click on Download ZIP.

That will download blackbox_master.zip.  Unzip it, then copy all the files in blackbox_master/bin to /usr/bin or /usr/local/bin.

Body:
I have recently been trying to install Blackbox on Cygwin, and as the docs say I did cp ./blackbox/bin/* /usr/bin.

Then I tried accessing it using blackbox_edit, and I get:

/bin/bash: /usr/bin/blackbox_edit: No file or directory

Same when I run /usr/bin/blackbox_edit. Running stat /usr/bin/blackbox_edit gives:

  File: /usr/bin/blackbox_edit
  Size: 958             Blocks: 4          IO Block: 65536  regular file
Device: 671faeah/108133098d     Inode: 2251799814041428  Links: 1
Access: (0755/-rwxr-xr-x)  Uid: (197609/   adrie)   Gid: (197609/   adrie)
Access: 2017-06-07 15:34:50.353508600 +0200
Modify: 2017-06-07 15:54:58.823472200 +0200
Change: 2017-06-07 15:59:00.592320500 +0200
 Birth: 2017-06-07 15:34:50.353508600 +0200

What am I missing?

Thanks in advance.


问:
Get access to the context element of a dynamically bound event inside the event handler in jQuery
I have piece of html that is injected into the page and dynamically bound to a click event handler. As shown in the code below

```<code> var matchMore = $(".match-more-btn");

 matchList.on("click", matchMore, function() {
   var self = $(this); //<--- Problem here
   matchFunc(self);
 });
</code>```

My problem is that I want to get the object passed in as the context (ie: dynamically bound element, the matchMore element shown above) but 'this' returns matchList object. How do I get access to the element that initiated the event

答:
The jQuery documentation at http://api.jquery.com/on/ states:

event.target indicates the deepest (innermost) element where the event
  occurred.

```<code>var matchMore = $(".match-more-btn");

matchList.on("click", matchMore, function(event) {
    var self = event.target;
    matchFunc(self);
});
</code>```

Body:
I have piece of html that is injected into the page and dynamically bound to a click event handler. As shown in the code below

 var matchMore = $(".match-more-btn");

 matchList.on("click", matchMore, function() {
   var self = $(this); //<--- Problem here
   matchFunc(self);
 });

My problem is that I want to get the object passed in as the context (ie: dynamically bound element, the matchMore element shown above) but 'this' returns matchList object. How do I get access to the element that initiated the event

Body:
The jQuery documentation at http://api.jquery.com/on/ states:

event.target indicates the deepest (innermost) element where the event
  occurred.

var matchMore = $(".match-more-btn");

matchList.on("click", matchMore, function(event) {
    var self = event.target;
    matchFunc(self);
});


问:
How do I save a UIImage to a file?
If I have a UIImage from an imagePicker, how can I save it to a subfolder in the documents directory?

答:
```<code>extension UIImage {
    /// Save PNG in the Documents directory
    func save(_ name: String) {
        let path: String = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
        let url = URL(fileURLWithPath: path).appendingPathComponent(name)
        try! UIImagePNGRepresentation(self)?.write(to: url)
        print("saved image at \(url)")
    }
}

// Usage: Saves file in the Documents directory
image.save("climate_model_2017.png")
</code>```

Title: How do I save a UIImage to a file?


问:
iOS | server returns 415 status code (Swift 3)
I am sending login information to the server that I built using ASP.NET Core. I tested my server via PostMan and Fiddler and it returns a valid response.

Here is my post request:

```<code>   var request = URLRequest(url: URL(string:     "http://adincebic.com/auth/login")!)
    request.httpMethod = "POST"
    let postString = "email=cebic.ad@gmail.com&password=a"
    request.httpBody = postString.data(using: .utf8)
    let task = URLSession.shared.dataTask(with: request) { data,      response, error in
        guard let data = data, error == nil else {                                                 // check for fundamental networking error
            print("error=\(String(describing: error))")
            return
        }

        if let httpStatus = response as? HTTPURLResponse,    httpStatus.statusCode != 200 {           // check for http errors
            print("statusCode should be 200, but is \. (httpStatus.statusCode)")
            print("response = \(String(describing: response))")
        }

        let responseString = String(data: data, encoding: .utf8)
        print("responseString = \(String(describing: responseString))")
    }
    task.resume()
</code>```

I tried using dictionary like ["email":"myEmail","password":"myPass"] but it did not let me do it that way.
I also tried using Alamofire but again with no luck, the server always returns 415 error in the console.

To verify that my server works I created a UWP application to test it and it worked as expected.

Here is my server response in XCode:

```<code>   statusCode should be 200, but is 415
   response = Optional(<NSHTTPURLResponse: 0x6080002275a0> { URL:        http://adincebic.com/auth/login } { status code: 415, headers {
Connection = "keep-alive";
"Content-Length" = 0;
Date = "Thu, 08 Jun 2017 12:16:12 GMT";
Server = "nginx/1.10.1 (Ubuntu)";
} })
responseString = Optional("")
</code>```

I am assuming that it may be a problem with encoding or a problem with reading data.

I wrote this post requests as described in this answer: HTTP Request in Swift with POST method

答:
Maybe you are missing the Content-Type header, like this:</p>

```<code>request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
</code>```

Body:
I am sending login information to the server that I built using ASP.NET Core. I tested my server via PostMan and Fiddler and it returns a valid response.

Here is my post request:

   var request = URLRequest(url: URL(string:     "http://adincebic.com/auth/login")!)
    request.httpMethod = "POST"
    let postString = "email=cebic.ad@gmail.com&password=a"
    request.httpBody = postString.data(using: .utf8)
    let task = URLSession.shared.dataTask(with: request) { data,      response, error in
        guard let data = data, error == nil else {                                                 // check for fundamental networking error
            print("error=\(String(describing: error))")
            return
        }

        if let httpStatus = response as? HTTPURLResponse,    httpStatus.statusCode != 200 {           // check for http errors
            print("statusCode should be 200, but is \. (httpStatus.statusCode)")
            print("response = \(String(describing: response))")
        }

        let responseString = String(data: data, encoding: .utf8)
        print("responseString = \(String(describing: responseString))")
    }
    task.resume()

I tried using dictionary like ["email":"myEmail","password":"myPass"] but it did not let me do it that way.
I also tried using Alamofire but again with no luck, the server always returns 415 error in the console.

To verify that my server works I created a UWP application to test it and it worked as expected.

Here is my server response in XCode:

   statusCode should be 200, but is 415
   response = Optional(<NSHTTPURLResponse: 0x6080002275a0> { URL:        http://adincebic.com/auth/login } { status code: 415, headers {
Connection = "keep-alive";
"Content-Length" = 0;
Date = "Thu, 08 Jun 2017 12:16:12 GMT";
Server = "nginx/1.10.1 (Ubuntu)";
} })
responseString = Optional("")

I am assuming that it may be a problem with encoding or a problem with reading data.

I wrote this post requests as described in this answer: HTTP Request in Swift with POST method

Body:
Maybe you are missing the Content-Type header, like this:

request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")


问:
How to get data from AsyncTask in android?
Iv tried some on the solutions in stack overflow, but was not able to work it out for my case.

I want to get the Bitmap data from onPostExecute or bmp from doInBackground and set it to ImageView imageurl using imageurl.setImageBitmap() in the getView() method

```<code>public class BooksAdapter extends ArrayAdapter<Books> {

    public BooksAdapter(Activity context, ArrayList<Books> word) {
        super(context, 0, word);
    }

    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        // Check if the existing view is being reused, otherwise inflate the view
        View listItemView = convertView;
        if (listItemView == null) {
            listItemView = LayoutInflater.from(getContext()).inflate(
                    R.layout.list_item, parent, false);
        }

        // Get the {@link AndroidFlavor} object located at this position in the list
        Books currentbook = getItem(position);

        TextView bookView = (TextView) listItemView.findViewById(R.id.bookTittle);
        String booktitle = currentbook.getBookName();
        bookView.setText(booktitle);

        TextView authorView = (TextView) listItemView.findViewById(R.id.authorname);
        String authorname = currentbook.getAuthorName();
        authorView.setText(authorname);

        ImageView imageurl = (ImageView) listItemView.findViewById(R.id.imageView);
        String imagelink = currentbook.getImageLink();

        ImageAsyncTask task = new ImageAsyncTask();
        task.execute(imagelink);

    // imageurl.setImageBitmap();

        return listItemView;

    }

    private class ImageAsyncTask extends AsyncTask<String, Void, Bitmap> {

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

            URL url = null;
            Bitmap bmp = null;

            try {
                url = new URL(urls[0]);
            } catch (MalformedURLException e) {
                Log.e(LOG_TAG, "Error with creating URL ", e);
            }
            try {
                bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
            } catch (IOException e) {
                Log.e(LOG_TAG, "Problem retrieving the earthquake JSON results.", e);
            }

            return bmp;

        }

        @Override
        protected void onPostExecute(Bitmap data) {

        }

    }

}
</code>```

答:
Just pass your ImageView to AsyncTask via constructor and then set image in onPostExecute like this:

```<code>ImageAsyncTask task = new ImageAsyncTask(myImageView);

private class ImageAsyncTask extends AsyncTask<String, Void, Bitmap> {
    private ImageView img;

    ImageAsyncTask(Imageview img){
       this.img = img;
    }

  ...

    protected void onPostExecute(Bitmap data) {
        this.img.setImageBitmap(data);

    }
</code>```

Body:
Iv tried some on the solutions in stack overflow, but was not able to work it out for my case.

I want to get the Bitmap data from onPostExecute or bmp from doInBackground and set it to ImageView imageurl using imageurl.setImageBitmap() in the getView() method

public class BooksAdapter extends ArrayAdapter<Books> {

    public BooksAdapter(Activity context, ArrayList<Books> word) {
        super(context, 0, word);
    }

    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        // Check if the existing view is being reused, otherwise inflate the view
        View listItemView = convertView;
        if (listItemView == null) {
            listItemView = LayoutInflater.from(getContext()).inflate(
                    R.layout.list_item, parent, false);
        }

        // Get the {@link AndroidFlavor} object located at this position in the list
        Books currentbook = getItem(position);

        TextView bookView = (TextView) listItemView.findViewById(R.id.bookTittle);
        String booktitle = currentbook.getBookName();
        bookView.setText(booktitle);

        TextView authorView = (TextView) listItemView.findViewById(R.id.authorname);
        String authorname = currentbook.getAuthorName();
        authorView.setText(authorname);

        ImageView imageurl = (ImageView) listItemView.findViewById(R.id.imageView);
        String imagelink = currentbook.getImageLink();

        ImageAsyncTask task = new ImageAsyncTask();
        task.execute(imagelink);

    // imageurl.setImageBitmap();

        return listItemView;

    }

    private class ImageAsyncTask extends AsyncTask<String, Void, Bitmap> {

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

            URL url = null;
            Bitmap bmp = null;

            try {
                url = new URL(urls[0]);
            } catch (MalformedURLException e) {
                Log.e(LOG_TAG, "Error with creating URL ", e);
            }
            try {
                bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
            } catch (IOException e) {
                Log.e(LOG_TAG, "Problem retrieving the earthquake JSON results.", e);
            }

            return bmp;

        }

        @Override
        protected void onPostExecute(Bitmap data) {

        }

    }

}

Body:
Just pass your ImageView to AsyncTask via constructor and then set image in onPostExecute like this:

ImageAsyncTask task = new ImageAsyncTask(myImageView);

private class ImageAsyncTask extends AsyncTask<String, Void, Bitmap> {
    private ImageView img;

    ImageAsyncTask(Imageview img){
       this.img = img;
    }

  ...

    protected void onPostExecute(Bitmap data) {
        this.img.setImageBitmap(data);

    }


问:
Split string by first white space
I want to split string in array based just on first white space in string.

Like this:

```<code>var name = "Jone Doe Doone";
var res = ["Jone", "Doe Doone"];
</code>```

答:
Here is an example where I have used indexOf() to find the first space and then return with a splitted array with substring()

function splitAtFirstSpace(str) {
  if (! str) return [];
  var i = str.indexOf(' ');
  if (i > 0) {
    return [str.substring(0, i), str.substring(i + 1)];
  }
  else return [str];
}

console.log(splitAtFirstSpace("Jone Doe Doone"));
console.log(splitAtFirstSpace("BooDoone"));
console.log(splitAtFirstSpace("Doe Doone"));```

Title: Split string by first white space

Body:
I want to split string in array based just on first white space in string.

Like this:

var name = "Jone Doe Doone";
var res = ["Jone", "Doe Doone"];


问:
How to install keras on Win10?
I know there are a lot of tutorials of installing keras on win. But I am faced with a weird problem and I cannot find a solution on Google.

The version of python I used is 2.7(anaconda 64bit).

When I typed 'pip install keras' in cmd, an error occurred.

It is said that no matching distribution found for tensorflow(from keras).
I googled it and one saying goes that this problem occurred when python is 32bit on windows. However, my python is 64-bit, so this saying does not hold.
I want to know how to handle this, given that I want to use theano as keras backend instead of tensorflow.

答:
I think the problem is that TensorFlow on Windows only support Python 3.5.X.

You should try installing anaconda3.

Source: https://www.tensorflow.org/install/install_windows

Title: How to install keras on Win10?


问:
Processing alternate element in for loop without using index value
I have list of elements with dictionary, for simplicity I have written them as strings:

```<code>ls = ['element1', 'element2', 'element3', 'element4', 'element5', 'element6', 'element7', 'element8', 'element9', 'element10']
</code>```

I am trying to process pair of element from list as follow:

```<code>#m1. Step for loop by size two with if condition
for x in ls:
    if ls.index(x)%2 == 0:
        # my code to be process
        print(x) # for simplicity I just printed element

#m2. tried another way like below:
for x in range(0, len(ls), 2):
    # this way give me output of alternate element from list
    print(ls[x])
</code>```

Is there any way to get only alternate elements while iterating the list items in m1 just like m2?

答:
You can slice the list in steps of two; exploiting memory:</p>

```<code>for x in ls[::2]:
    print(x)
</code>```

Body:
I have list of elements with dictionary, for simplicity I have written them as strings:

ls = ['element1', 'element2', 'element3', 'element4', 'element5', 'element6', 'element7', 'element8', 'element9', 'element10']

I am trying to process pair of element from list as follow:

#m1. Step for loop by size two with if condition
for x in ls:
    if ls.index(x)%2 == 0:
        # my code to be process
        print(x) # for simplicity I just printed element

#m2. tried another way like below:
for x in range(0, len(ls), 2):
    # this way give me output of alternate element from list
    print(ls[x])

Is there any way to get only alternate elements while iterating the list items in m1 just like m2?

Body:
You can slice the list in steps of two; exploiting memory:

for x in ls[::2]:
    print(x)


问:
Strange Checkbox behaviour using MVVM in ZK Framework
I've found strange behaviour of zk checkbox in MVVM. I made a MVVM form that shows list of items and detailed view of selected item. I placed checkbox on detailed view and bind it to boolean property of my POJO. And when I select an item with true value of this property checkbox is displayed checked, but next when I select an item with false value of property and then select an item with true value again checkbox is displayed unchecked.
I can illustrate this issue using ZK's MVVM tutorial http://books.zkoss.org/wiki/ZK_Getting_Started/Get_ZK_Up_and_Running_with_MVVM (source code http://sourceforge.net/projects/zkbook/files/GettingStarted/getzkup-20131127.zip/download )

Add to Car class boolean property:

```<code>private Boolean cool = false;

public Car(Integer id, String model, String make, String description,  String preview, Integer price, boolean cool){
    this.id = id;
    this.model = model;
    this.make = make;
    this.preview = preview;
    this.description = description;
    this.price = price;
    this.cool = cool;
}

public Boolean getCool() {
    return cool;
}

public void setCool(Boolean cool) {
    this.cool = cool;
}
</code>```

Change CarServiceImpl.java to initialize boolean property for our demo:

```<code>carList.add(
            new Car(id++,
                    "Camry",
                    "Toyota",
                    "The Toyota Camry is a midsize car ... ",
                    "/img/car3.png",
                    24170, true));
carList.add(
            new Car(id++,
                    "Century",
                    "Toyota",
                    "The Toyota Century is ... " ,
                    "/img/car4.png",
                    28730, true));
</code>```

Change searchMvvm.zul (add lines labeled as INSERTED):

```<code><window title="Search" width="600px" border="normal" apply="org.zkoss.bind.BindComposer"
viewModel="@id('vm') @init('tutorial.SearchViewModel')">
<hbox align="center">
    Keyword:
    <textbox value="@bind(vm.keyword)" />
    <button label="Search" image="/img/search.png" onClick="@command('search')" />
</hbox>
<listbox height="160px" model="@bind(vm.carList)" emptyMessage="No car found in the result"
selectedItem="@bind(vm.selectedCar)">
    <listhead>
        <listheader label="Model" />
        <listheader label="Make" />
        <listheader label="Price" width="20%"/>
        <listheader label="Cool" /> <!-- INSERTED -->
    </listhead>
    <template name="model">
        <listitem>
            <listcell label="@bind(each.model)"></listcell>
            <listcell label="@bind(each.make)"></listcell>
            <listcell>$<label value="@bind(each.price)" /></listcell>
            <listcell><checkbox checked="@bind(each.cool)" /></listcell> <!-- INSERTED -->
        </listitem>
    </template>
</listbox>
<hbox style="margin-top:20px">
     <image width="250px" src="@bind(vm.selectedCar.preview)" />
    <vbox>
        <label value="@bind(vm.selectedCar.model)" />
        <label value="@bind(vm.selectedCar.make)" />
        <label value="@bind(vm.selectedCar.price)" />
        <label value="@bind(vm.selectedCar.description)" />
        <checkbox checked="@bind(vm.selectedCar.cool)" label="Cool" /> <!-- INSERTED -->
    </vbox>
</hbox>
</code>```

After that start Tomcat and enter localhost:8080/tutorial/searchMvvm.zul in your browser. When you click on Toyota Camry item everything is ok, but when you click on Nissan Cifiro and then on Toyota Camry again checkbox in detaled view will be displayed unchecked. But checkbox in listbox works fine.

Do you know any workaround to solve this problem?

答:
You should use</p>

```<code>checkbox.setCheck(Boolean.valueOf(true));
</code>```

Body:
I've found strange behaviour of zk checkbox in MVVM. I made a MVVM form that shows list of items and detailed view of selected item. I placed checkbox on detailed view and bind it to boolean property of my POJO. And when I select an item with true value of this property checkbox is displayed checked, but next when I select an item with false value of property and then select an item with true value again checkbox is displayed unchecked.
I can illustrate this issue using ZK's MVVM tutorial http://books.zkoss.org/wiki/ZK_Getting_Started/Get_ZK_Up_and_Running_with_MVVM (source code http://sourceforge.net/projects/zkbook/files/GettingStarted/getzkup-20131127.zip/download )

Add to Car class boolean property:

private Boolean cool = false;

public Car(Integer id, String model, String make, String description,  String preview, Integer price, boolean cool){
    this.id = id;
    this.model = model;
    this.make = make;
    this.preview = preview;
    this.description = description;
    this.price = price;
    this.cool = cool;
}

public Boolean getCool() {
    return cool;
}

public void setCool(Boolean cool) {
    this.cool = cool;
}

Change CarServiceImpl.java to initialize boolean property for our demo:

carList.add(
            new Car(id++,
                    "Camry",
                    "Toyota",
                    "The Toyota Camry is a midsize car ... ",
                    "/img/car3.png",
                    24170, true));
carList.add(
            new Car(id++,
                    "Century",
                    "Toyota",
                    "The Toyota Century is ... " ,
                    "/img/car4.png",
                    28730, true));

Change searchMvvm.zul (add lines labeled as INSERTED):

<window title="Search" width="600px" border="normal" apply="org.zkoss.bind.BindComposer"
viewModel="@id('vm') @init('tutorial.SearchViewModel')">
<hbox align="center">
    Keyword:
    <textbox value="@bind(vm.keyword)" />
    <button label="Search" image="/img/search.png" onClick="@command('search')" />
</hbox>
<listbox height="160px" model="@bind(vm.carList)" emptyMessage="No car found in the result"
selectedItem="@bind(vm.selectedCar)">
    <listhead>
        <listheader label="Model" />
        <listheader label="Make" />
        <listheader label="Price" width="20%"/>
        <listheader label="Cool" />
    </listhead>
    <template name="model">
        <listitem>
            <listcell label="@bind(each.model)"></listcell>
            <listcell label="@bind(each.make)"></listcell>
            <listcell>$</listcell>
            <listcell><checkbox checked="@bind(each.cool)" /></listcell>
        </listitem>
    </template>
</listbox>
<hbox style="margin-top:20px">
     <image width="250px" src="@bind(vm.selectedCar.preview)" />
    <vbox>

        <checkbox checked="@bind(vm.selectedCar.cool)" label="Cool" />
    </vbox>
</hbox>

After that start Tomcat and enter localhost:8080/tutorial/searchMvvm.zul in your browser. When you click on Toyota Camry item everything is ok, but when you click on Nissan Cifiro and then on Toyota Camry again checkbox in detaled view will be displayed unchecked. But checkbox in listbox works fine.

Do you know any workaround to solve this problem?

Body:
You should use

checkbox.setCheck(Boolean.valueOf(true));


问:
Signing Certs - python-cryptography library behavior changes between versions
I'm using the Cryptography 1.0 library for python to sign SSL certificates with our company's CA. This snippet illustrates the code I'm using.

In version 1.0, the snippet produces a correctly signed certificate, but when I upgrade any newer version (including 1.0.1), the certificate hierarchy is flat, as you'd expect with a self-signed certificate. The issuer details on the Details tab, is the same, however. But of course the status of the cert signed by 1.7.1 is "The issuer of this certificate could not be found."

The only variation is the cryptography version. Same python, same system, same OpenSSL library.

I've reviewed the Cryptography docs, and I can't see what changed in the newer versions. Anyone have sharper eyes?

TIA!!

答: Ok, this is a bug in cryptography; filed at #3515.</p>


问:
Cargo creates empty ELF file
I'm trying to use this answer by writing a custom target .json file with "linker-flavor":"gcc". My full target .json file is:

```<code>{
  "llvm-target": "avr-atmel-none",
  "cpu": "atmega328p",
  "target-endian": "little",
  "target-pointer-width": "16",
  "os": "none",
  "target-env": "gnu",
  "target-vendor": "unknown",
  "arch": "avr",
  "data-layout": "e-p:16:16:16-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-n8",

  "executables": true,

  "linker": "avr-gcc",
  "linker-flavor": "gcc",
  "pre-link-args": {
    "gcc": ["-Os -mmcu=atmega328p"]
  },
  "exe-suffix": ".elf",
  "post-link-args": {
    "gcc": ["-Wl,--gc-sections"]
  },

  "no-default-libraries": false
}
</code>```

Running cargo build with this finishes without any error messages:

$ cargo build --release -v
   Compiling core v0.1.0 (https://github.com/gergoerdi/rust-avr-libcore-mini?rev=adda44aa91ac517aab6915447592ee4cad26564c#adda44aa)
     Running `rustc --crate-name core /home/cactus/.cargo/git/checkouts/rust-avr-libcore-mini-37e279d93a70b45a/adda44a/src/lib.rs --crate-type lib --emit=dep-info,link -C opt-level=3 -C metadata=655bb622dd229da9 -C extra-filename=-655bb622dd229da9 --out-dir /home/cactus/prog/rust/avr/chip8-avr/target/avr-atmega328p/release/deps --target avr-atmega328p -L dependency=/home/cactus/prog/rust/avr/chip8-avr/target/avr-atmega328p/release/deps -L dependency=/home/cactus/prog/rust/avr/chip8-avr/target/release/deps --cap-lints allow`
   Compiling chip8-engine v0.1.0 (https://github.com/gergoerdi/rust-avr-chip8-engine?rev=c6f88737bae4dae0bd6c5c2bbc73737e6dfadfcd#c6f88737)
     Running `rustc --crate-name chip8_engine /home/cactus/.cargo/git/checkouts/rust-avr-chip8-engine-4bce60f3f178d33a/c6f8873/src/lib.rs --crate-type lib --emit=dep-info,link -C opt-level=3 -C metadata=2197ff1f15f697c9 -C extra-filename=-2197ff1f15f697c9 --out-dir /home/cactus/prog/rust/avr/chip8-avr/target/avr-atmega328p/release/deps --target avr-atmega328p -L dependency=/home/cactus/prog/rust/avr/chip8-avr/target/avr-atmega328p/release/deps -L dependency=/home/cactus/prog/rust/avr/chip8-avr/target/release/deps --extern core=/home/cactus/prog/rust/avr/chip8-avr/target/avr-atmega328p/release/deps/libcore-655bb622dd229da9.rlib --cap-lints allow`
   Compiling chip8-avr v0.1.0 (file:///home/cactus/prog/rust/avr/chip8-avr)
     Running `rustc --crate-name chip8_avr src/main.rs --crate-type bin --emit=dep-info,link -C opt-level=3 -C metadata=014a8fed19cbc611 -C extra-filename=-014a8fed19cbc611 --out-dir /home/cactus/prog/rust/avr/chip8-avr/target/avr-atmega328p/release/deps --target avr-atmega328p -L dependency=/home/cactus/prog/rust/avr/chip8-avr/target/avr-atmega328p/release/deps -L dependency=/home/cactus/prog/rust/avr/chip8-avr/target/release/deps --extern chip8_engine=/home/cactus/prog/rust/avr/chip8-avr/target/avr-atmega328p/release/deps/libchip8_engine-2197ff1f15f697c9.rlib --extern core=/home/cactus/prog/rust/avr/chip8-avr/target/avr-atmega328p/release/deps/libcore-655bb622dd229da9.rlib`
    Finished release [optimized] target(s) in 15.99 secs
```

<p>However, the resulting ELF file's <code>.text</code> section is empty:</p>

<pre class="lang-none prettyprint-override"><code>$ avr-objdump -h target/avr-atmega328p/release/chip8-avr.elf

target/avr-atmega328p/release/chip8-avr.elf:     file format elf32-avr

Sections:
Idx Name          Size      VMA       LMA       File off  Algn
  0 .text         00000000  00000000  00000000  00000074  2**1
                  CONTENTS, ALLOC, LOAD, READONLY, CODE
  1 .data         00000000  00800060  00000000  00000074  2**0
                  CONTENTS, ALLOC, LOAD, DATA
  2 .stab         0000012c  00000000  00000000  00000074  2**2
                  CONTENTS, READONLY, DEBUGGING
  3 .stabstr      0000005d  00000000  00000000  000001a0  2**0
                  CONTENTS, READONLY, DEBUGGING
  4 .comment      00000011  00000000  00000000  000001fd  2**0
                  CONTENTS, READONLY
</code>```

So to figure out what's going on, I thought I'd replace my avr-gcc
with a small shellscript that logs its arguments before passing it to
the real avr-gcc executable.

This shows me that rustc/cargo is trying to run the following
command line to do the linking:

/usr/bin/avr-gcc -Os -mmcu=atmega328p \
  -L /home/cactus/prog/rust/rust-avr/build/build/x86_64-unknown-linux-gnu/stage1/lib/rustlib/avr-atmega328p/lib \
  /home/cactus/prog/rust/avr/chip8-avr/target/avr-atmega328p/release/deps/chip8_avr-014a8fed19cbc611.0.o \
  -o /home/cactus/prog/rust/avr/chip8-avr/target/avr-atmega328p/release/deps/chip8_avr-014a8fed19cbc611.elf \
  -Wl,--gc-sections \
  -L /home/cactus/prog/rust/avr/chip8-avr/target/avr-atmega328p/release/deps -L /home/cactus/prog/rust/avr/chip8-avr/target/release/deps -L /home/cactus/prog/rust/rust-avr/build/build/x86_64-unknown-linux-gnu/stage1/lib/rustlib/avr-atmega328p/lib \
  -Wl,-Bstatic /home/cactus/prog/rust/avr/chip8-avr/target/avr-atmega328p/release/deps/libchip8_engine-2197ff1f15f697c9.rlib \
  /home/cactus/prog/rust/avr/chip8-avr/target/avr-atmega328p/release/deps/libcore-655bb622dd229da9.rlib \
  -Wl,-Bdynamic -Wl,--gc-sections
```

<p>If I run the exact same command manually, with the exact same environment variables, I get a good ELF file with
the right contents (note that its <code>.text</code> section is not empty):</p>

<pre class="lang-none prettyprint-override"><code>$ /usr/bin/avr-gcc -Os -mmcu=atmega328p -L /home/cactus/prog/rust/rust-avr/build/build/x86_64-unknown-linux-gnu/stage1/lib/rustlib/avr-atmega328p/lib /home/cactus/prog/rust/avr/chip8-avr/target/avr-atmega328p/release/deps/chip8_avr-014a8fed19cbc611.0.o -o /home/cactus/prog/rust/avr/chip8-avr/target/avr-atmega328p/release/deps/chip8_avr-014a8fed19cbc611.elf -Wl,--gc-sections -L /home/cactus/prog/rust/avr/chip8-avr/target/avr-atmega328p/release/deps -L /home/cactus/prog/rust/avr/chip8-avr/target/release/deps -L /home/cactus/prog/rust/rust-avr/build/build/x86_64-unknown-linux-gnu/stage1/lib/rustlib/avr-atmega328p/lib -Wl,-Bstatic /home/cactus/prog/rust/avr/chip8-avr/target/avr-atmega328p/release/deps/libchip8_engine-2197ff1f15f697c9.rlib /home/cactus/prog/rust/avr/chip8-avr/target/avr-atmega328p/release/deps/libcore-655bb622dd229da9.rlib -Wl,-Bdynamic -Wl,--gc-sections
$ avr-objdump -h target/avr-atmega328p/release/deps/chip8_avr-014a8fed19cbc611.elf
target/avr-atmega328p/release/deps/chip8_avr-014a8fed19cbc611.elf:     file format elf32-avr

Sections:
Idx Name          Size      VMA       LMA       File off  Algn
  0 .data         0000020e  00800100  00001a56  00001af0  2**4
                  CONTENTS, ALLOC, LOAD, DATA
  1 .text         00001a56  00000000  00000000  00000094  2**1
                  CONTENTS, ALLOC, LOAD, READONLY, CODE
  2 .bss          000001fa  0080030e  0080030e  00001cfe  2**0
                  ALLOC
  3 .stab         000007ec  00000000  00000000  00001d00  2**2
                  CONTENTS, READONLY, DEBUGGING
  4 .stabstr      000000b0  00000000  00000000  000024ec  2**0
                  CONTENTS, READONLY, DEBUGGING
  5 .comment      00000011  00000000  00000000  0000259c  2**0
                  CONTENTS, READONLY
</code>```

So why does cargo silently produce a nonsensical empty ELF file, if
running the (supposedly) same command from the shell results in a valid ELF file?

答:
This is caused by a bug in the target .json file; specifically, this part:

```<code>"pre-link-args": {
  "gcc": ["-Os -mmcu=atmega328p"]
},
</code>```

The arguments are passed directly as argv to the linker, so multiple arguments need to be split into multiple elements of the array here:

```<code>"pre-link-args": {
  "gcc": ["-Os", "-mmcu=atmega328p"]
},
</code>```

The reason this problem didn't show up when using the special logging version of avr-gcc is that the log only contained all the arguments together, so there was no difference between the two representations.

As for avr-gcc '-Os -mmcu=atmega328p' creating an empty .elf file, it seems that is simply a side-effect of not specifying any (valid) -mmcu argument.

Title: Cargo creates empty ELF file

Body:
I'm trying to use this answer by writing a custom target .json file with "linker-flavor":"gcc". My full target .json file is:

{
  "llvm-target": "avr-atmel-none",
  "cpu": "atmega328p",
  "target-endian": "little",
  "target-pointer-width": "16",
  "os": "none",
  "target-env": "gnu",
  "target-vendor": "unknown",
  "arch": "avr",
  "data-layout": "e-p:16:16:16-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-n8",

  "executables": true,

  "linker": "avr-gcc",
  "linker-flavor": "gcc",
  "pre-link-args": {
    "gcc": ["-Os -mmcu=atmega328p"]
  },
  "exe-suffix": ".elf",
  "post-link-args": {
    "gcc": ["-Wl,--gc-sections"]
  },

  "no-default-libraries": false
}

Running cargo build with this finishes without any error messages:

$ cargo build --release -v
   Compiling core v0.1.0 (https://github.com/gergoerdi/rust-avr-libcore-mini?rev=adda44aa91ac517aab6915447592ee4cad26564c#adda44aa)
     Running `rustc --crate-name core /home/cactus/.cargo/git/checkouts/rust-avr-libcore-mini-37e279d93a70b45a/adda44a/src/lib.rs --crate-type lib --emit=dep-info,link -C opt-level=3 -C metadata=655bb622dd229da9 -C extra-filename=-655bb622dd229da9 --out-dir /home/cactus/prog/rust/avr/chip8-avr/target/avr-atmega328p/release/deps --target avr-atmega328p -L dependency=/home/cactus/prog/rust/avr/chip8-avr/target/avr-atmega328p/release/deps -L dependency=/home/cactus/prog/rust/avr/chip8-avr/target/release/deps --cap-lints allow`
   Compiling chip8-engine v0.1.0 (https://github.com/gergoerdi/rust-avr-chip8-engine?rev=c6f88737bae4dae0bd6c5c2bbc73737e6dfadfcd#c6f88737)
     Running `rustc --crate-name chip8_engine /home/cactus/.cargo/git/checkouts/rust-avr-chip8-engine-4bce60f3f178d33a/c6f8873/src/lib.rs --crate-type lib --emit=dep-info,link -C opt-level=3 -C metadata=2197ff1f15f697c9 -C extra-filename=-2197ff1f15f697c9 --out-dir /home/cactus/prog/rust/avr/chip8-avr/target/avr-atmega328p/release/deps --target avr-atmega328p -L dependency=/home/cactus/prog/rust/avr/chip8-avr/target/avr-atmega328p/release/deps -L dependency=/home/cactus/prog/rust/avr/chip8-avr/target/release/deps --extern core=/home/cactus/prog/rust/avr/chip8-avr/target/avr-atmega328p/release/deps/libcore-655bb622dd229da9.rlib --cap-lints allow`
   Compiling chip8-avr v0.1.0 (file:///home/cactus/prog/rust/avr/chip8-avr)
     Running `rustc --crate-name chip8_avr src/main.rs --crate-type bin --emit=dep-info,link -C opt-level=3 -C metadata=014a8fed19cbc611 -C extra-filename=-014a8fed19cbc611 --out-dir /home/cactus/prog/rust/avr/chip8-avr/target/avr-atmega328p/release/deps --target avr-atmega328p -L dependency=/home/cactus/prog/rust/avr/chip8-avr/target/avr-atmega328p/release/deps -L dependency=/home/cactus/prog/rust/avr/chip8-avr/target/release/deps --extern chip8_engine=/home/cactus/prog/rust/avr/chip8-avr/target/avr-atmega328p/release/deps/libchip8_engine-2197ff1f15f697c9.rlib --extern core=/home/cactus/prog/rust/avr/chip8-avr/target/avr-atmega328p/release/deps/libcore-655bb622dd229da9.rlib`
    Finished release [optimized] target(s) in 15.99 secs

However, the resulting ELF file's .text section is empty:

$ avr-objdump -h target/avr-atmega328p/release/chip8-avr.elf

target/avr-atmega328p/release/chip8-avr.elf:     file format elf32-avr

Sections:
Idx Name          Size      VMA       LMA       File off  Algn
  0 .text         00000000  00000000  00000000  00000074  2**1
                  CONTENTS, ALLOC, LOAD, READONLY, CODE
  1 .data         00000000  00800060  00000000  00000074  2**0
                  CONTENTS, ALLOC, LOAD, DATA
  2 .stab         0000012c  00000000  00000000  00000074  2**2
                  CONTENTS, READONLY, DEBUGGING
  3 .stabstr      0000005d  00000000  00000000  000001a0  2**0
                  CONTENTS, READONLY, DEBUGGING
  4 .comment      00000011  00000000  00000000  000001fd  2**0
                  CONTENTS, READONLY

So to figure out what's going on, I thought I'd replace my avr-gcc
with a small shellscript that logs its arguments before passing it to
the real avr-gcc executable.

This shows me that rustc/cargo is trying to run the following
command line to do the linking:

/usr/bin/avr-gcc -Os -mmcu=atmega328p \
  -L /home/cactus/prog/rust/rust-avr/build/build/x86_64-unknown-linux-gnu/stage1/lib/rustlib/avr-atmega328p/lib \
  /home/cactus/prog/rust/avr/chip8-avr/target/avr-atmega328p/release/deps/chip8_avr-014a8fed19cbc611.0.o \
  -o /home/cactus/prog/rust/avr/chip8-avr/target/avr-atmega328p/release/deps/chip8_avr-014a8fed19cbc611.elf \
  -Wl,--gc-sections \
  -L /home/cactus/prog/rust/avr/chip8-avr/target/avr-atmega328p/release/deps -L /home/cactus/prog/rust/avr/chip8-avr/target/release/deps -L /home/cactus/prog/rust/rust-avr/build/build/x86_64-unknown-linux-gnu/stage1/lib/rustlib/avr-atmega328p/lib \
  -Wl,-Bstatic /home/cactus/prog/rust/avr/chip8-avr/target/avr-atmega328p/release/deps/libchip8_engine-2197ff1f15f697c9.rlib \
  /home/cactus/prog/rust/avr/chip8-avr/target/avr-atmega328p/release/deps/libcore-655bb622dd229da9.rlib \
  -Wl,-Bdynamic -Wl,--gc-sections

If I run the exact same command manually, with the exact same environment variables, I get a good ELF file with
the right contents (note that its .text section is not empty):

$ /usr/bin/avr-gcc -Os -mmcu=atmega328p -L /home/cactus/prog/rust/rust-avr/build/build/x86_64-unknown-linux-gnu/stage1/lib/rustlib/avr-atmega328p/lib /home/cactus/prog/rust/avr/chip8-avr/target/avr-atmega328p/release/deps/chip8_avr-014a8fed19cbc611.0.o -o /home/cactus/prog/rust/avr/chip8-avr/target/avr-atmega328p/release/deps/chip8_avr-014a8fed19cbc611.elf -Wl,--gc-sections -L /home/cactus/prog/rust/avr/chip8-avr/target/avr-atmega328p/release/deps -L /home/cactus/prog/rust/avr/chip8-avr/target/release/deps -L /home/cactus/prog/rust/rust-avr/build/build/x86_64-unknown-linux-gnu/stage1/lib/rustlib/avr-atmega328p/lib -Wl,-Bstatic /home/cactus/prog/rust/avr/chip8-avr/target/avr-atmega328p/release/deps/libchip8_engine-2197ff1f15f697c9.rlib /home/cactus/prog/rust/avr/chip8-avr/target/avr-atmega328p/release/deps/libcore-655bb622dd229da9.rlib -Wl,-Bdynamic -Wl,--gc-sections
$ avr-objdump -h target/avr-atmega328p/release/deps/chip8_avr-014a8fed19cbc611.elf
target/avr-atmega328p/release/deps/chip8_avr-014a8fed19cbc611.elf:     file format elf32-avr

Sections:
Idx Name          Size      VMA       LMA       File off  Algn
  0 .data         0000020e  00800100  00001a56  00001af0  2**4
                  CONTENTS, ALLOC, LOAD, DATA
  1 .text         00001a56  00000000  00000000  00000094  2**1
                  CONTENTS, ALLOC, LOAD, READONLY, CODE
  2 .bss          000001fa  0080030e  0080030e  00001cfe  2**0
                  ALLOC
  3 .stab         000007ec  00000000  00000000  00001d00  2**2
                  CONTENTS, READONLY, DEBUGGING
  4 .stabstr      000000b0  00000000  00000000  000024ec  2**0
                  CONTENTS, READONLY, DEBUGGING
  5 .comment      00000011  00000000  00000000  0000259c  2**0
                  CONTENTS, READONLY

So why does cargo silently produce a nonsensical empty ELF file, if
running the (supposedly) same command from the shell results in a valid ELF file?

Body:
This is caused by a bug in the target .json file; specifically, this part:

"pre-link-args": {
  "gcc": ["-Os -mmcu=atmega328p"]
},

The arguments are passed directly as argv to the linker, so multiple arguments need to be split into multiple elements of the array here:

"pre-link-args": {
  "gcc": ["-Os", "-mmcu=atmega328p"]
},

The reason this problem didn't show up when using the special logging version of avr-gcc is that the log only contained all the arguments together, so there was no difference between the two representations.

As for avr-gcc '-Os -mmcu=atmega328p' creating an empty .elf file, it seems that is simply a side-effect of not specifying any (valid) -mmcu argument.


问:
JSP+Tomcat: Single Sign-On
How the best way to create a single sign-on for many JSP applications using Tomcat server?</p>

答:
One possibility is to use Tomcats build in SSO mechanism:
http://tomcat.apache.org/tomcat-5.5-doc/config/host.html#Single_Sign_On

A more generic, but still easy to use approach is CAS (Central Authentication Service):
http://www.jasig.org/cas
It's also open source.

Kerberos is the perfect fit if you want to do Integrated Windows SSO within a corporate environment. (Means, user authenticated to a Microsoft Windows system are automatically logged in to kerberized web applications). For a lot of other use cases it doesn't fit at all.

There is no general "best way" when it comes to SSO for web applications, but maybe one that fits best for your specific requirements. Maybe you can explaing them in a bit more detail?

btw why the heck are you still using Tomcat 5.5?

Title: JSP+Tomcat: Single Sign-On