问:
How to display multiple returned values in suggestion in twitter typeahead/bloodhound?
Im trying to use bloodhound and typeahead to create an autocomplete. The data is being returned correctly but displayed in the options as undefined
My code is:

Html:

```<code><form class="typeahead" role="search">
       <div class="form-group">
            <input type="search" name="q" class="form-control search-input" placeholder="Search" autocomplete="off">
       </div>
</form>
</code>```

Javascript:

```<code>var engine = new Bloodhound({
                remote: {
                    url: '{{ route('search') }}?query=%QUERY',
                    wildcard: '%QUERY'
                },
                datumTokenizer: Bloodhound.tokenizers.whitespace('name'),
                queryTokenizer: Bloodhound.tokenizers.whitespace
            });

            $(".search-input").typeahead({
                hint: true,
                highlight: true,
                minLength: 1
            }, {
                source: engine.ttAdapter(),

                // This will be appended to "tt-dataset-" to form the class name of the suggestion menu.
                name: 'profileList',

                // the key from the array we want to display (name,slug...)
                templates: {
                    empty: [
                        '<div class="list-group search-results-dropdown"><div class="list-group-item">Nothing found.</div></div>'
                    ],
                    header: [
                        '<div class="list-group search-results-dropdown">'
                    ],
                    suggestion: function (data) {
                        var profile = [];
                        profile.push(data);
                        console.log(profile);

                        return '<a href="' + data.slug + '" class="list-group-item">' + data.name + '</a>'
                    }
                }
            });
</code>```

When I console.log(data) I get 2 results which look like this:

```<code>Hello Molly
hello-molly-436057803095647
</code>```

but the values are displayed as undefined. The data returned from the backend looks like:

```<code>{"name":"Hello Molly","slug":"hello-molly-436057803095647"}
</code>```

I want to display name and slug like this: return '' + data.name + '' as a suggestion. How can I do that?

答:
For anyone else that gets stuck I had to create a transform function:

```<code>transform: function(response) {
                    return $.map(response, function (profile) {
                        return {
                            name: profile.name,
                            slug: profile.slug
                        }
                    });
                },
</code>```

to map out the json response. Also if your using a lot of browser caching clear your cache as this can stop the javascript from updating.

Full code:

```<code>var engine = new Bloodhound({
                remote: {
                    url: '{{ route('search') }}?query=%QUERY',
                    wildcard: '%QUERY',
                    transform: function(response) {
                        return $.map(response, function (profile) {
                            return {
                                name: profile.name,
                                slug: profile.slug
                            }
                        });
                    },
                },
                datumTokenizer: Bloodhound.tokenizers.whitespace('name', 'slug'),
                queryTokenizer: Bloodhound.tokenizers.whitespace

            });

            engine.initialize();

            $(".search-input").typeahead({
                hint: true,
                highlight: true,
                minLength: 1,
                displayKey: 'name',
            }, {
                source: engine.ttAdapter(),

                // This will be appended to "tt-dataset-" to form the class name of the suggestion menu.
                name: 'profileList',

                // the key from the array we want to display (name,id,email,etc...)
                templates: {
                    empty: [
                        '<div class="list-group search-results-dropdown"><div class="list-group-item">Nothing found.</div></div>'
                    ],
                    header: [
                        '<div class="list-group search-results-dropdown">'
                    ],
                    suggestion: function (data) {
                        return '<a href="' + data.slug + '" class="list-group-item">' + data.name + '</a>'
                    }
                }
            });
</code>```

Body:
Im trying to use bloodhound and typeahead to create an autocomplete. The data is being returned correctly but displayed in the options as undefined
My code is:

Html:

<form class="typeahead" role="search">

            <input type="search" name="q" class="form-control search-input" placeholder="Search" autocomplete="off">

</form>

Javascript:

var engine = new Bloodhound({
                remote: {
                    url: '{{ route('search') }}?query=%QUERY',
                    wildcard: '%QUERY'
                },
                datumTokenizer: Bloodhound.tokenizers.whitespace('name'),
                queryTokenizer: Bloodhound.tokenizers.whitespace
            });

            $(".search-input").typeahead({
                hint: true,
                highlight: true,
                minLength: 1
            }, {
                source: engine.ttAdapter(),

                // This will be appended to "tt-dataset-" to form the class name of the suggestion menu.
                name: 'profileList',

                // the key from the array we want to display (name,slug...)
                templates: {
                    empty: [
                        '

Nothing found.

'
                    ],
                    header: [
                        '
'
                    ],
                    suggestion: function (data) {
                        var profile = [];
                        profile.push(data);
                        console.log(profile);

                        return '' + data.name + ''
                    }
                }
            });

When I console.log(data) I get 2 results which look like this:

Hello Molly
hello-molly-436057803095647

but the values are displayed as undefined. The data returned from the backend looks like:

{"name":"Hello Molly","slug":"hello-molly-436057803095647"}

I want to display name and slug like this: return '' + data.name + '' as a suggestion. How can I do that?

Body:
For anyone else that gets stuck I had to create a transform function:

transform: function(response) {
                    return $.map(response, function (profile) {
                        return {
                            name: profile.name,
                            slug: profile.slug
                        }
                    });
                },

to map out the json response. Also if your using a lot of browser caching clear your cache as this can stop the javascript from updating.

Full code:

var engine = new Bloodhound({
                remote: {
                    url: '{{ route('search') }}?query=%QUERY',
                    wildcard: '%QUERY',
                    transform: function(response) {
                        return $.map(response, function (profile) {
                            return {
                                name: profile.name,
                                slug: profile.slug
                            }
                        });
                    },
                },
                datumTokenizer: Bloodhound.tokenizers.whitespace('name', 'slug'),
                queryTokenizer: Bloodhound.tokenizers.whitespace

            });

            engine.initialize();

            $(".search-input").typeahead({
                hint: true,
                highlight: true,
                minLength: 1,
                displayKey: 'name',
            }, {
                source: engine.ttAdapter(),

                // This will be appended to "tt-dataset-" to form the class name of the suggestion menu.
                name: 'profileList',

                // the key from the array we want to display (name,id,email,etc...)
                templates: {
                    empty: [
                        '<div class="list-group search-results-dropdown"><div class="list-group-item">Nothing found.</div></div>'
                    ],
                    header: [
                        '<div class="list-group search-results-dropdown">'
                    ],
                    suggestion: function (data) {
                        return '<a href="' + data.slug + '" class="list-group-item">' + data.name + '</a>'
                    }
                }
            });


来源: stackexchange

问:
When to return vector iterator instead of vector?
Let's say we have a function 1 :

```<code>vector<T>::iterator GetSomething()
{
 vector<T> vec;

 // Update vec with something...

 return vec.begin();
}
</code>```

And another function 2:

```<code>vector<T> GetSomething()
{
 vector<T> vec;

 // Update vec with something...

 return vec;
}
</code>```

In what situations would we prefer function 1 ?
Also, what would be the lifetime of that vector object ?
How would we know if the iterator is pointing to empty vector ? Probably need to pass pair of iterators to determine begin / end.

答:
There is no circumstance in which your first function would be preferred.  The vector vec ceases to exist when the function returns.  Any iterators supplied by that vector will be invalid for the caller.   And most usages of those iterators (particularly dereferencing) will cause the caller to exhibit undefined behaviour.

The only time an iterator should be returned by a function will be if the vector which provides those iterators is guaranteed to exist after the function returns.   Practically, there are only three circumstances in which one MIGHT do that.  The first is if the vector is passed as an argument to the function, such as

```<code> std::vector<int>::iterator func(std::vector<int> &vec)
 {
     return vec.begin();
 }
</code>```

Since the caller passes the vector, the vector will exist when the function returns.

The second case is if the vector is a static, or otherwise continues to exist when the function returns.

```<code> std::vector<int>::iterator func(std::vector<int> &vec)
 {
     static std::vector<int> vec;
     return vec.begin();
 }
</code>```

Of course, using a function like this has all the complications associated with statics (e.g. problems with reentrancy, need to synchronise usage across threads, etc etc).

The third case in which an iterator may be returned is if an iterator is passed to the function.  Such as

```<code> std::vector<int>::iterator func(std::vector<int>::iterator it)
 {
     return it + 1;
 }
</code>```

In this case, it is up to the caller to pass a valid iterator (e.g. obtained from a container it controls) that can be incremented (or advanced by 1).

Also, if a function returns an iterator, the caller might need to check if the iterator is valid before using it.   If so, that should be docuumented.  For example, if the function might return an end iterator, the caller should check BEFORE trying to dereference it, not after.

ContentLicense: CC BY-SA 3.0

Body:
Let's say we have a function 1 :

vector<T>::iterator GetSomething()
{
 vector<T> vec;

 // Update vec with something...

 return vec.begin();
}

And another function 2:

vector<T> GetSomething()
{
 vector<T> vec;

 // Update vec with something...

 return vec;
}

In what situations would we prefer function 1 ?
Also, what would be the lifetime of that vector object ?
How would we know if the iterator is pointing to empty vector ? Probably need to pass pair of iterators to determine begin / end.

Body:
There is no circumstance in which your first function would be preferred.  The vector vec ceases to exist when the function returns.  Any iterators supplied by that vector will be invalid for the caller.   And most usages of those iterators (particularly dereferencing) will cause the caller to exhibit undefined behaviour.

The only time an iterator should be returned by a function will be if the vector which provides those iterators is guaranteed to exist after the function returns.   Practically, there are only three circumstances in which one MIGHT do that.  The first is if the vector is passed as an argument to the function, such as

 std::vector<int>::iterator func(std::vector<int> &vec)
 {
     return vec.begin();
 }

Since the caller passes the vector, the vector will exist when the function returns.

The second case is if the vector is a static, or otherwise continues to exist when the function returns.

 std::vector<int>::iterator func(std::vector<int> &vec)
 {
     static std::vector<int> vec;
     return vec.begin();
 }

Of course, using a function like this has all the complications associated with statics (e.g. problems with reentrancy, need to synchronise usage across threads, etc etc).

The third case in which an iterator may be returned is if an iterator is passed to the function.  Such as

 std::vector<int>::iterator func(std::vector<int>::iterator it)
 {
     return it + 1;
 }

In this case, it is up to the caller to pass a valid iterator (e.g. obtained from a container it controls) that can be incremented (or advanced by 1).

Also, if a function returns an iterator, the caller might need to check if the iterator is valid before using it.   If so, that should be docuumented.  For example, if the function might return an end iterator, the caller should check BEFORE trying to dereference it, not after.


问:
UIbutton misplaced in simulator
Here I have to implement the UIView for both the screens iPhone 5 and 6. So I used the screeHeight to integrate the UIView. But the button in the view is misplaced in iPhone 5s simulator and works fine in iPhone 6 simulator Here is the code for that. Whatever I changed the values in x and y remains the same top position.

```<code>if screenHeight == 568{

        self.viewFareEstimate.frame = CGRect(x:0, y:150, width:359, height:40)

    }
</code>```

答:
Hi @imac for good programming practices try to avoid to give constant values to frame.

For your refrence height for iPhone 5 is 568.0f & 6 is 667.0f are different,

&

Whenever you want size width full then try to give frame like this,

```<code>self.viewFareEstimate.frame = CGRect(x:0, y:150, width:self.view.frame.size.width, height:40);// Manage width by + or - constant value now.
</code>```

In your case check that if you are giving constraint from storyboard already then it should work with setting frame only.

Title: UIbutton misplaced in simulator

Body:
Here I have to implement the UIView for both the screens iPhone 5 and 6. So I used the screeHeight to integrate the UIView. But the button in the view is misplaced in iPhone 5s simulator and works fine in iPhone 6 simulator Here is the code for that. Whatever I changed the values in x and y remains the same top position.

if screenHeight == 568{

        self.viewFareEstimate.frame = CGRect(x:0, y:150, width:359, height:40)

    }

Body:
Hi @imac for good programming practices try to avoid to give constant values to frame.

For your refrence height for iPhone 5 is 568.0f & 6 is 667.0f are different,

&

Whenever you want size width full then try to give frame like this,

self.viewFareEstimate.frame = CGRect(x:0, y:150, width:self.view.frame.size.width, height:40);// Manage width by + or - constant value now.

In your case check that if you are giving constraint from storyboard already then it should work with setting frame only.


问:
Link displays on two lines when adding style
Thank you all for your time.

I am trying to do something simple but it turns out to be so complicated.
I need a link to send an email but there's some issue with the style. It shows the content fractured (see jsfiddle). But when I right click several times, everything is back to normal. Any idea?

.sendAll {
    float: right;
    margin-right: 10%;
    margin-bottom: 3%;
    margin-top: 2%;
    display: inline-block;
}

#sendAll {
    color: white;
    padding: 7% 25%;
    background-color: #0080FF;
    display: inline-block;
}

#sendAll:hover {
    background-color: #0164c6;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>HTML:

<div class="sendAll">

                <b id="sendAll">Send Email to All Selected</b>

</div></code>```

Here's the jsfiddle link

Thank you all !

答:
Just provide display: block to #sendAll

The  tag provides a font-weight: bold property to the element, but the element is not a block level element by itself. So, you have to manually specify the same.

Refer code:

.sendAll {
  float: right;
  margin-right: 10%;
  margin-bottom: 3%;
  margin-top: 2%;
  display: inline-block;
}

#sendAll {
  color: white;
  padding: 7% 25%;
  background-color: #0080FF;
  display: block;
}

#sendAll:hover {
  background-color: #0164c6;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="sendAll">

    <b id="sendAll">Send Email to All Selected</b>

</div></code>```

Body:
Thank you all for your time.

I am trying to do something simple but it turns out to be so complicated.
I need a link to send an email but there's some issue with the style. It shows the content fractured (see jsfiddle). But when I right click several times, everything is back to normal. Any idea?

.sendAll {
    float: right;
    margin-right: 10%;
    margin-bottom: 3%;
    margin-top: 2%;
    display: inline-block;
}

#sendAll {
    color: white;
    padding: 7% 25%;
    background-color: #0080FF;
    display: inline-block;
}

#sendAll:hover {
    background-color: #0164c6;
}

HTML:

                Send Email to All Selected

Here's the jsfiddle link

Thank you all !

Body:
Just provide display: block to #sendAll

The <b> tag provides a font-weight: bold property to the element, but the element is not a block level element by itself. So, you have to manually specify the same.

Refer code:

.sendAll {
  float: right;
  margin-right: 10%;
  margin-bottom: 3%;
  margin-top: 2%;
  display: inline-block;
}

#sendAll {
  color: white;
  padding: 7% 25%;
  background-color: #0080FF;
  display: block;
}

#sendAll:hover {
  background-color: #0164c6;
}

<div class="sendAll">
  <a href="#">
    <b id="sendAll">Send Email to All Selected</b>
  </a>
</div>


问:
How to convert a number where I replaced the dot with a comma from a string back to a decimal number
I have an input field where users can enter decimal numbers by using a Dot or a comma ( Example: 79,99 or 79.99 ) . When users enter the number with a comma I replace it with a dot ( this number is then sent to a remote server for verification) . Now I would like to display the number after the user enters it in the footer using toFixed(2) function to display only the first two decimal numbers. I cant get it to work , because after converting it back to a number using  ParseFloat the 2 decimals after the comma disappear.

Example:

User enter in the input field : 79,99 which is then set into the variable totalAmount:

```<code>$('#amount-1').keyup(function() {

getRefundAmount(1); // This function calls the calcTotalAmount function

})

function calcTotalAmount() {
console.log('calcTotalAmount');

var totalAmount = 0;
var totalRefund = 0;
var rowAmount = 0;
var rowRefund = 0;

for(var i = 1; i < 4; i++ ) {
    rowAmount = parseFloat($('#amount-' + i).val());
    rowRefund = parseFloat($('#result-' + i).text());
    if(!isNaN(rowAmount)) {
        totalAmount += rowAmount;
        totalRefund += rowRefund;
    }
}

var toPay = totalAmount-totalRefund;
totalAmount = totalAmount.toString().replace(/\,/g, '.');
totalAmount = parseFloat(totalAmount).toFixed(2);

$('#footer-refund').text(totalRefund)
$('#footer-total').text(totalAmount)
if (totalAmount == '') {
    $('#footer-total').text("0.00");
}
}
</code>```

The Result displayed in the footer is : 79.00 instead of 79.99

答:
Thanks for all the help :

solution is as follows : I have to check it in the for loop already and replace it there.

```<code>for(var i = 1; i < 4; i++ ) {
    if(!$('#amount-' + i).val()){continue;}else{
    rowAmount = parseFloat($('#amount-' + i).val().toString().replace(/\,/g,'.'));
    rowRefund = parseFloat($('#result-' + i).text());
    if(!isNaN(rowAmount)) {
        totalAmount += rowAmount;
        totalRefund += rowRefund;
    }
    }
}
</code>```

Body:
I have an input field where users can enter decimal numbers by using a Dot or a comma ( Example: 79,99 or 79.99 ) . When users enter the number with a comma I replace it with a dot ( this number is then sent to a remote server for verification) . Now I would like to display the number after the user enters it in the footer using toFixed(2) function to display only the first two decimal numbers. I cant get it to work , because after converting it back to a number using  ParseFloat the 2 decimals after the comma disappear.

Example:

User enter in the input field : 79,99 which is then set into the variable totalAmount:

$('#amount-1').keyup(function() {

getRefundAmount(1); // This function calls the calcTotalAmount function

})

function calcTotalAmount() {
console.log('calcTotalAmount');

var totalAmount = 0;
var totalRefund = 0;
var rowAmount = 0;
var rowRefund = 0;

for(var i = 1; i < 4; i++ ) {
    rowAmount = parseFloat($('#amount-' + i).val());
    rowRefund = parseFloat($('#result-' + i).text());
    if(!isNaN(rowAmount)) {
        totalAmount += rowAmount;
        totalRefund += rowRefund;
    }
}

var toPay = totalAmount-totalRefund;
totalAmount = totalAmount.toString().replace(/\,/g, '.');
totalAmount = parseFloat(totalAmount).toFixed(2);

$('#footer-refund').text(totalRefund)
$('#footer-total').text(totalAmount)
if (totalAmount == '') {
    $('#footer-total').text("0.00");
}
}

The Result displayed in the footer is : 79.00 instead of 79.99

Body:
Thanks for all the help :

solution is as follows : I have to check it in the for loop already and replace it there.

for(var i = 1; i < 4; i++ ) {
    if(!$('#amount-' + i).val()){continue;}else{
    rowAmount = parseFloat($('#amount-' + i).val().toString().replace(/\,/g,'.'));
    rowRefund = parseFloat($('#result-' + i).text());
    if(!isNaN(rowAmount)) {
        totalAmount += rowAmount;
        totalRefund += rowRefund;
    }
    }
}


问:
pause/start AVAudioPlayer without glitchy pops
I'm playing back a longish audio file (20 seconds or so) using AVAudioPlayer. I need to be able to pause and start in the middle of the file. When I pause or start while the audio is playing, there's a noticeable "pop" as the audio starts or finishes.

I've been able to improve the situation by doing a very fast fade-out (setting the volume multiple times using performSelector: withObject: afterDelay. But the sound is still a little glitchy with this technique.

Is there a standard way to start/pause AVAudioPlayer without these glitches?

答: Use one of the lower level APIs (Audio Queues or RemoteIO).  Smoothly ramp a multiplication factor from 1.0 to 0.0 over some number of PCM samples. Use that factor for the sample-by-sample gain factor in your own DSP audio mixer.  Ramp from 0.0 to 1.0 on restart.  Linear or an ease-in/ease-out half-cosine curve.</p>

ContentLicense: CC BY-SA 2.5


问:
WPF - How do I reuse data templates of singular object for collection?
As I was creating a data type - control mapping for my application, I found out that it is feasible by using ContentPresenter and Data Templates. I have successfully done that. For this snippet, I included the mapping for System.String data type. However, I noticed that if I bound a list of strings and mapped a generic collection control for it, the strings are represented as a TextBox rather as just plain string as shown in the figure below (See StringCollection)!

Now, I wish to use this leverage in order to re-use the control when the dynamic PropertyValue is assigned with a collection. How can I implement the multi-binding for the TextBox? If the PropertyValue is an array, then bind to its elements; else bind to the PropertyValue itself.

```<code><DataTemplate>
    <StackPanel x:Name="ItemStackPanel" Orientation="Horizontal" Margin="8">
        <TextBlock Text="{Binding PropertyName}" FontSize="14" MinWidth="120"
            Validation.ErrorTemplate="{x:Null}">
        </TextBlock>
        <ContentPresenter Margin="48, 0, 0, 0" Content="{Binding PropertyValue}">
            <ContentPresenter.Resources>
                <DataTemplate DataType="{x:Type System:String}">
                    <TextBox Text="{Binding ElementName=ItemStackPanel, Path=DataContext.PropertyValue}"
                        Width="100" Validation.ErrorTemplate="{StaticResource ErrorTemplate}">
                    </TextBox>
                </DataTemplate>
                <DataTemplate DataType="{x:Type dataTypes:StringCollection}">
                    <controls:GenericCollectionControl x:Name="GenericCollectionControl"
                        ItemsSource="{Binding ElementName=ItemStackPanel, Path=DataContext.PropertyValue}"
                        Validation.ErrorTemplate="{StaticResource ErrorTemplate}">
                    </controls:GenericCollectionControl>
                </DataTemplate>
            </ContentPresenter.Resources>
        </ContentPresenter>
    </StackPanel>
</DataTemplate>
</code>```

--- Revision 1 ---

I managed to make it work by utilizing a IMultiValueConverter and return the correct binding.

```<code><TextBox Width="100" Validation.ErrorTemplate="{StaticResource ErrorTemplate}">
    <TextBox.Text>
        <MultiBinding Converter="{StaticResource BindingSelector}">
            <Binding Mode="OneWay"></Binding>
            <Binding ElementName="ItemStackPanel" Path="DataContext.PropertyValue"></Binding>
        </MultiBinding>
    </TextBox.Text>
</TextBox>
</code>```

But I'm having an exception if the binding mode is not one way. How can I achieve two-way binding for this?

答:
But I'm having an exception if the binding mode is not one way. How can I achieve two-way binding for this?

Try to specify a path for the first binding:

```<code><TextBox Width="100" Validation.ErrorTemplate="{StaticResource ErrorTemplate}">
    <TextBox.Text>
        <MultiBinding Converter="{StaticResource BindingSelector}">
            <Binding Path="." />
            <Binding ElementName="ItemStackPanel" Path="DataContext.PropertyValue"></Binding>
        </MultiBinding>
    </TextBox.Text>
</TextBox>
</code>```

Body:
As I was creating a data type - control mapping for my application, I found out that it is feasible by using ContentPresenter and Data Templates. I have successfully done that. For this snippet, I included the mapping for System.String data type. However, I noticed that if I bound a list of strings and mapped a generic collection control for it, the strings are represented as a TextBox rather as just plain string as shown in the figure below (See StringCollection)!

Now, I wish to use this leverage in order to re-use the control when the dynamic PropertyValue is assigned with a collection. How can I implement the multi-binding for the TextBox? If the PropertyValue is an array, then bind to its elements; else bind to the PropertyValue itself.

<DataTemplate>
    <StackPanel x:Name="ItemStackPanel" Orientation="Horizontal" Margin="8">
        <TextBlock Text="{Binding PropertyName}" FontSize="14" MinWidth="120"
            Validation.ErrorTemplate="{x:Null}">
        </TextBlock>
        <ContentPresenter Margin="48, 0, 0, 0" Content="{Binding PropertyValue}">
            <ContentPresenter.Resources>
                <DataTemplate DataType="{x:Type System:String}">
                    <TextBox Text="{Binding ElementName=ItemStackPanel, Path=DataContext.PropertyValue}"
                        Width="100" Validation.ErrorTemplate="{StaticResource ErrorTemplate}">
                    </TextBox>
                </DataTemplate>
                <DataTemplate DataType="{x:Type dataTypes:StringCollection}">
                    <controls:GenericCollectionControl x:Name="GenericCollectionControl"
                        ItemsSource="{Binding ElementName=ItemStackPanel, Path=DataContext.PropertyValue}"
                        Validation.ErrorTemplate="{StaticResource ErrorTemplate}">
                    </controls:GenericCollectionControl>
                </DataTemplate>
            </ContentPresenter.Resources>
        </ContentPresenter>
    </StackPanel>
</DataTemplate>

--- Revision 1 ---

I managed to make it work by utilizing a IMultiValueConverter and return the correct binding.

<TextBox Width="100" Validation.ErrorTemplate="{StaticResource ErrorTemplate}">
    <TextBox.Text>
        <MultiBinding Converter="{StaticResource BindingSelector}">
            <Binding Mode="OneWay"></Binding>
            <Binding ElementName="ItemStackPanel" Path="DataContext.PropertyValue"></Binding>
        </MultiBinding>
    </TextBox.Text>
</TextBox>

But I'm having an exception if the binding mode is not one way. How can I achieve two-way binding for this?

Body:
But I'm having an exception if the binding mode is not one way. How can I achieve two-way binding for this?

Try to specify a path for the first binding:

<TextBox Width="100" Validation.ErrorTemplate="{StaticResource ErrorTemplate}">
    <TextBox.Text>
        <MultiBinding Converter="{StaticResource BindingSelector}">
            <Binding Path="." />
            <Binding ElementName="ItemStackPanel" Path="DataContext.PropertyValue"></Binding>
        </MultiBinding>
    </TextBox.Text>
</TextBox>


问:
Objects Unable to be read twice with ObjectInputStream
Whenever I write the the file the initial time everything is fine. When I read the data into the linked list everything is fine. Then finally when I save the file the files contents match with the initial file where I just wrote it.

The issue I have is when I try to read the objects from the saved file (after running the program for the second time) is that everything in the file is erased and I can't read any objects in.

```<code>public class MedicalInformation {
    public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException, EOFException {

        Scanner userInput = new Scanner(System.in);

        System.out.println("Enter the file path");
        String filePath = userInput.next(); //"C:\\Users\\ag\\Desktop\\medicalData\\patient.dat";
        System.out.println("The file's path is " + filePath);
        System.out.println("Enter the file name and its path you want to read in");

        // create objects that allow one to read and write to the file
        ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(filePath));
        ObjectInputStream in = new ObjectInputStream(new FileInputStream(filePath));

        //creates the objects to be written into the file

        Patient p1 = new Patient("Alex", "1123 metropolitan Queens NY 11385", new Date("11/20/1997"));
        p1.setFirstVisit(new Date("11/20/1997"));
        p1.setHeight(72);
        p1.setLastVisit(new Date("11/20/1997"));
        p1.setWeight(200);
        out.writeObject(p1);
        System.out.println(p1);

        Patient p2 = new Patient("John", "200 avenue of americas Manhttann 10111", new Date("12/20/1999"));
        p2.setFirstVisit(new Date("11/11/2005"));
        p2.setHeight(5);
        p2.setLastVisit(new Date("11/21/2010"));
        p2.setWeight(150);
        out.writeObject(p2);

        Patient p3 = new Patient("Sarah", "24 Park avenue Manhttann 10111", new Date("09/07/1960"));
        p3.setFirstVisit(new Date("05/11/1977"));
        p3.setHeight(75);
        p3.setLastVisit(new Date("01/21/2017"));
        p3.setWeight(110);
        out.writeObject(p3);

        Patient p4 = new Patient("Malcolm", "56street East NY 10444", new Date("05/28/1977"));
        p4.setFirstVisit(new Date("01/11/1990"));
        p4.setHeight(75);
        p4.setLastVisit(new Date("8/21/2016"));
        p4.setWeight(155);
        out.writeObject(p4);

        Patient p5 = new Patient("Johnny", "89 street Jamaica 12221", new Date("12/25/1944"));
        p5.setFirstVisit(new Date("03/16/1966"));
        p5.setHeight(55);
        p5.setLastVisit(new Date("5/21/2015"));
        p5.setWeight(355);
        out.writeObject(p5);

        Patient p6 = new Patient("Laura", "east 4th street Brooklyn 12214", new Date("08/08/1988"));
        p6.setFirstVisit(new Date("05/11/1999"));
        p6.setHeight(48);
        p6.setLastVisit(new Date("8/21/2012"));
        p6.setWeight(350);
        out.writeObject(p6);

        //put them into a list
        List < Patient > list = new List < Patient > ();

        boolean done = false;
        while (!done) {
            try {
                Patient patients = (Patient) in .readObject();
                list.add(patients);
                //an EOFException is thrown when the stream ends, which means the end of the file is reached
            } catch (EOFException e) {
                done = true;
                out.close(); in .close();
            }
        }

        if (option == 8) {
            System.out.println("Would you like to save the file y/n");
            saveFile = userInput.next();

            if (saveFile.equals("y")) {
                //save file
                System.out.println("Enter the file's name where it is to be saved");
                filePath = userInput.next();
                out = new ObjectOutputStream(new FileOutputStream(filePath));
                LLNode < Patient > p = list.getList();
                while (p != null) {
                    out.writeUnshared(p.getInfo());
                    p = p.getLink();
                }
            } else {
                System.out.println("You chose not to save the file");
            }
            out.close(); in .close();
            break;
        }
    }

}
}
</code>```

So What I do is I enter the file name C:\Users\ag\Desktop\medicalData\patient.dat
then the six objects get written to it.

I then read these into the linked list

I perform no operations

I save the linked list to a file C:\Users\ag\Desktop\medicalData\patient.dat

I comment out writing the 6 objects into the file now I just want to read them. This is where my problem is I end up left with a file with two characters and am unable get an EOFException.

答:
Serializing the same object will deserialize the same object, even if you changed it at the sending end. You need to use one of:

ObjectOutputStream.reset()

ObjectOutputStream.writeUnshared()

ObjectInputStream.readUnshared().

Body:
Whenever I write the the file the initial time everything is fine. When I read the data into the linked list everything is fine. Then finally when I save the file the files contents match with the initial file where I just wrote it.

The issue I have is when I try to read the objects from the saved file (after running the program for the second time) is that everything in the file is erased and I can't read any objects in.

public class MedicalInformation {
    public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException, EOFException {

        Scanner userInput = new Scanner(System.in);

        System.out.println("Enter the file path");
        String filePath = userInput.next(); //"C:\\Users\\ag\\Desktop\\medicalData\\patient.dat";
        System.out.println("The file's path is " + filePath);
        System.out.println("Enter the file name and its path you want to read in");

        // create objects that allow one to read and write to the file
        ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(filePath));
        ObjectInputStream in = new ObjectInputStream(new FileInputStream(filePath));

        //creates the objects to be written into the file

        Patient p1 = new Patient("Alex", "1123 metropolitan Queens NY 11385", new Date("11/20/1997"));
        p1.setFirstVisit(new Date("11/20/1997"));
        p1.setHeight(72);
        p1.setLastVisit(new Date("11/20/1997"));
        p1.setWeight(200);
        out.writeObject(p1);
        System.out.println(p1);

        Patient p2 = new Patient("John", "200 avenue of americas Manhttann 10111", new Date("12/20/1999"));
        p2.setFirstVisit(new Date("11/11/2005"));
        p2.setHeight(5);
        p2.setLastVisit(new Date("11/21/2010"));
        p2.setWeight(150);
        out.writeObject(p2);

        Patient p3 = new Patient("Sarah", "24 Park avenue Manhttann 10111", new Date("09/07/1960"));
        p3.setFirstVisit(new Date("05/11/1977"));
        p3.setHeight(75);
        p3.setLastVisit(new Date("01/21/2017"));
        p3.setWeight(110);
        out.writeObject(p3);

        Patient p4 = new Patient("Malcolm", "56street East NY 10444", new Date("05/28/1977"));
        p4.setFirstVisit(new Date("01/11/1990"));
        p4.setHeight(75);
        p4.setLastVisit(new Date("8/21/2016"));
        p4.setWeight(155);
        out.writeObject(p4);

        Patient p5 = new Patient("Johnny", "89 street Jamaica 12221", new Date("12/25/1944"));
        p5.setFirstVisit(new Date("03/16/1966"));
        p5.setHeight(55);
        p5.setLastVisit(new Date("5/21/2015"));
        p5.setWeight(355);
        out.writeObject(p5);

        Patient p6 = new Patient("Laura", "east 4th street Brooklyn 12214", new Date("08/08/1988"));
        p6.setFirstVisit(new Date("05/11/1999"));
        p6.setHeight(48);
        p6.setLastVisit(new Date("8/21/2012"));
        p6.setWeight(350);
        out.writeObject(p6);

        //put them into a list
        List < Patient > list = new List < Patient > ();

        boolean done = false;
        while (!done) {
            try {
                Patient patients = (Patient) in .readObject();
                list.add(patients);
                //an EOFException is thrown when the stream ends, which means the end of the file is reached
            } catch (EOFException e) {
                done = true;
                out.close(); in .close();
            }
        }

        if (option == 8) {
            System.out.println("Would you like to save the file y/n");
            saveFile = userInput.next();

            if (saveFile.equals("y")) {
                //save file
                System.out.println("Enter the file's name where it is to be saved");
                filePath = userInput.next();
                out = new ObjectOutputStream(new FileOutputStream(filePath));
                LLNode < Patient > p = list.getList();
                while (p != null) {
                    out.writeUnshared(p.getInfo());
                    p = p.getLink();
                }
            } else {
                System.out.println("You chose not to save the file");
            }
            out.close(); in .close();
            break;
        }
    }

}
}

So What I do is I enter the file name C:\Users\ag\Desktop\medicalData\patient.dat
then the six objects get written to it.

I then read these into the linked list

I perform no operations

I save the linked list to a file C:\Users\ag\Desktop\medicalData\patient.dat

I comment out writing the 6 objects into the file now I just want to read them. This is where my problem is I end up left with a file with two characters and am unable get an EOFException.


问:
Do something after method returns
This is my situation in pseudocode:

```<code>function onRequest() {
    receiveConnectionRequest();

    response = function onConnect() {
        playersConnected++;
        if (playersConnected == 4) {
            sendAllPlayersTheirCards()
        }
        return OK;
    }();

    sendResponse(response);

}
</code>```

When players 1-3 connect, they get added to the list of players and OK is returned to them, at which point they will set stuff up on their side. When player 4 connects, however, before the response to his request is sent, all players are sent their cards. Because player 4 has not received a response to his request yet, he hasn't initialised correctly yet and errors upon receiving his cards.

What I'd like to have is this:

```<code>function onRequest() {
    receiveConnectionRequest();

    response = function onConnect() {
        playersConnected++;
        if (playersConnected == 4) {
            plan(sendAllPlayersTheirCards())
        }
        return OK;
    }();

    sendResponse(response);

    executePlanned() // now cards are sent
}
</code>```

Is there a general pattern for that? The onConnect function is in a different class and should not be aware of the implementation details of onRequest.

I'm specifically trying to implement this in Java, but generic solutions are welcome.

答:
I could do it like this:</p>

```<code>function onRequest(request) {

 game.handleRequest(request, function(response) {
  sendResponse(response);
 }

}

class game
function handleRequest(request, sendResponse:Function) {
 players++;
 sendResponse(OK);
 if (players == 4) sendCards();
}
</code>```

Title: Do something after method returns

Body:
This is my situation in pseudocode:

function onRequest() {
    receiveConnectionRequest();

    response = function onConnect() {
        playersConnected++;
        if (playersConnected == 4) {
            sendAllPlayersTheirCards()
        }
        return OK;
    }();

    sendResponse(response);

}

When players 1-3 connect, they get added to the list of players and OK is returned to them, at which point they will set stuff up on their side. When player 4 connects, however, before the response to his request is sent, all players are sent their cards. Because player 4 has not received a response to his request yet, he hasn't initialised correctly yet and errors upon receiving his cards.

What I'd like to have is this:

function onRequest() {
    receiveConnectionRequest();

    response = function onConnect() {
        playersConnected++;
        if (playersConnected == 4) {
            plan(sendAllPlayersTheirCards())
        }
        return OK;
    }();

    sendResponse(response);

    executePlanned() // now cards are sent
}

Is there a general pattern for that? The onConnect function is in a different class and should not be aware of the implementation details of onRequest.

I'm specifically trying to implement this in Java, but generic solutions are welcome.

Body:
I could do it like this:

function onRequest(request) {

 game.handleRequest(request, function(response) {
  sendResponse(response);
 }

}

class game
function handleRequest(request, sendResponse:Function) {
 players++;
 sendResponse(OK);
 if (players == 4) sendCards();
}


问:
Interactive image map in Android
I want to implement an interactive image map in android. I have to show an image map, have to show the location where user click and have to connect two locations in the image map. How can I implement this in Android.</p>

答:
For that you have to Create map XMl file to define Coordiantes of the image where you wnat to find click.

This link will help you to understand more...
https://github.com/catchthecows/AndroidImageMap

Title: Interactive image map in Android


问:
mongodb backup role - mongodump
We have a development team that will periodically take a mongodump out of DEV and then restore it back to their local host for work.  We have recently implemented authentication in mongodb and i would like to be able to allow our development team do a mongodump on one DB only so they can restore it to their local host.

I have a role that inherits the backup role from Admin, but that is for our DBA to backup the whole system.

My question, how do I allow for this backup role to be used by a specific user (lets call them "webdev") for a specific DB (lets call it "products")?

答:
I am using MongoDB3.4 version, First of all you want one root access for admin database and connect mongo shell,

$ mongo -u username -p xxxxxx --authenticationDatabase admin

After connecting mongoshell, change the database,

```<code>use products
</code>```

After change the DB create the new user,

```<code>db.createUser(
  {
    user: "webdev",
    pwd: "xxxxx",
    roles: [
       { role: "read", db: "products" },
       { role: "backup", db: "products"}
    ]
  }
)
</code>```

Above I mentioned, webdev user can be able to read the all collections and take backup access also.

```<code>db.auth('webdev', 'xxxxx')
</code>```

after successfully authenticate, you can able to read and take backup from DEV server.

Below I mentioned mongodump query with new webdev user.

```<code>mongodump --host hostname --port 27017 --username webdev --password xxxxx --authenticationDatabase products --db products --collection collection_name --out mongodump_outpath
</code>```

Refer: https://docs.mongodb.com/manual/reference/built-in-roles/#backup

Note:

Don't take mongodump frequently in production. It will impacts the
performance issue.

Don't give backup and restore access to any other teams like developer,
tester,..etc

Admin or DBA only do every time Backup/Restore.

Thank You. Please revert for any concern.

Title: mongodb backup role - mongodump

Body:
I am using MongoDB3.4 version, First of all you want one root access for admin database and connect mongo shell,

$ mongo -u username -p xxxxxx --authenticationDatabase admin

After connecting mongoshell, change the database,

use products

After change the DB create the new user,

db.createUser(
  {
    user: "webdev",
    pwd: "xxxxx",
    roles: [
       { role: "read", db: "products" },
       { role: "backup", db: "products"}
    ]
  }
)

Above I mentioned, webdev user can be able to read the all collections and take backup access also.

db.auth('webdev', 'xxxxx')

after successfully authenticate, you can able to read and take backup from DEV server.

Below I mentioned mongodump query with new webdev user.

mongodump --host hostname --port 27017 --username webdev --password xxxxx --authenticationDatabase products --db products --collection collection_name --out mongodump_outpath

Refer: https://docs.mongodb.com/manual/reference/built-in-roles/#backup

Note:

Don't take mongodump frequently in production. It will impacts the
performance issue.

Don't give backup and restore access to any other teams like developer,
tester,..etc

Admin or DBA only do every time Backup/Restore.

Thank You. Please revert for any concern.

ContentLicense: CC BY-SA 4.0


问:
Dropbox core api: is rev unique?
I am using the dropbox core api currently.
For each object, I tried to use the rev value as the uri.
However, from the document of dropbox and result of google, I am not sure whether the rev is a unique number or not.

```<code>file.rev // and results is something like: 7e91b4dee3f
</code>```

Can anyone confirm this?
Great Thanks~

答:
Further info on this from Dropbox:

"The rev value uniquely identifies the file in the Dropbox, including path, so you don't need to add a path too."

Title: Dropbox core api: is rev unique?

Body:
I am using the dropbox core api currently.
For each object, I tried to use the rev value as the uri.
However, from the document of dropbox and result of google, I am not sure whether the rev is a unique number or not.

file.rev // and results is something like: 7e91b4dee3f

Can anyone confirm this?
Great Thanks~


问:
Response for preflight has invalid HTTP status code
I have some trouble with folowing structure. I have 2 domains: example.com and api.example.com. I wrote main site in example.com on Angular. I use this code in example.com/app.js to call function in api.example.com:

```<code>$http({
    method: 'POST',
    url: 'http://api.example.com/register',
    dataType: 'json',
    crossDomain: true,
    data: {
        email: register.data.email,
        password: register.data.password
    },
    headers: {
        'Content-Type': 'application/json; charset=UTF-8'
    }
}).then(function(data) {
    console.log(data);
    }, function(data) {
        console.log(data);
});
</code>```

And all ofthis gives me errors

```<code>OPTIONS http://api.example.com/register 400 (Bad Request)
</code>```

and

```<code>XMLHttpRequest cannot load http://api.example.com/register. Response for preflight has invalid HTTP status code 400
</code>```

My php code returns folowing

```<code>//some logic code here
if ( $json['status'] == 0 )
{
    header('Access-Control-Allow-Origin: *');
    header('Access-Control-Allow-Methods: POST, GET');
    header('Access-Control-Allow-Headers: Content-Type');
    header('Content-type: application/json; charset=utf-8');
    echo json_encode($json['data']);
}
else
{
    header('Access-Control-Allow-Origin: *');
    header('Access-Control-Allow-Methods: POST');
    header('Access-Control-Allow-Methods: GET');
    header('Access-Control-Allow-Headers: X-Requested-With');
    header('HTTP/1.1 400 Bad Request');
    header('Access-Control-Allow-Headers: Content-Type');
    header('Content-Type: application/json; charset=UTF-8');
    http_response_code(400);
}
</code>```

Where my $json['status']=0 everything is OK. It works, return status 200 OK. When I give wrong parameters, I have $json['status']=1 and I get an error which I described.

Full header which network returns

```<code>Request URL:http://api.example.com/user/register
Request Method:OPTIONS
Status Code:400 Bad Request
Remote Address:78.46.140.200:80
Response Headers
view source
Access-Control-Allow-Headers:X-Requested-With
Access-Control-Allow-Methods:GET
Access-Control-Allow-Origin:*
Connection:close
Content-Type:text/html; charset=UTF-8
Date:Thu, 09 Mar 2017 17:12:22 GMT
Server:Apache
Transfer-Encoding:chunked
Request Headers
view source
Accept:*/*
Accept-Encoding:gzip, deflate, sdch
Accept-Language:ru-RU,ru;q=0.8,en-US;q=0.6,en;q=0.4,az;q=0.2
Access-Control-Request-Headers:content-type
Access-Control-Request-Method:POST
Connection:keep-alive
Host:api.example.com
Origin:http://example.com
Referer:http://example.com/register
User-Agent:Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36
</code>```

答: As a fact, all problem was in Angular. At first Angular send OPTIONS request, only then if this request has 200 OK header send selected request (in my case POST). I just made 200 OK header for all OPTIONS methods.</p>

Body:
I have some trouble with folowing structure. I have 2 domains: example.com and api.example.com. I wrote main site in example.com on Angular. I use this code in example.com/app.js to call function in api.example.com:

$http({
    method: 'POST',
    url: 'http://api.example.com/register',
    dataType: 'json',
    crossDomain: true,
    data: {
        email: register.data.email,
        password: register.data.password
    },
    headers: {
        'Content-Type': 'application/json; charset=UTF-8'
    }
}).then(function(data) {
    console.log(data);
    }, function(data) {
        console.log(data);
});

And all ofthis gives me errors

OPTIONS http://api.example.com/register 400 (Bad Request)

and

XMLHttpRequest cannot load http://api.example.com/register. Response for preflight has invalid HTTP status code 400

My php code returns folowing

//some logic code here
if ( $json['status'] == 0 )
{
    header('Access-Control-Allow-Origin: *');
    header('Access-Control-Allow-Methods: POST, GET');
    header('Access-Control-Allow-Headers: Content-Type');
    header('Content-type: application/json; charset=utf-8');
    echo json_encode($json['data']);
}
else
{
    header('Access-Control-Allow-Origin: *');
    header('Access-Control-Allow-Methods: POST');
    header('Access-Control-Allow-Methods: GET');
    header('Access-Control-Allow-Headers: X-Requested-With');
    header('HTTP/1.1 400 Bad Request');
    header('Access-Control-Allow-Headers: Content-Type');
    header('Content-Type: application/json; charset=UTF-8');
    http_response_code(400);
}

Where my $json['status']=0 everything is OK. It works, return status 200 OK. When I give wrong parameters, I have $json['status']=1 and I get an error which I described.

Full header which network returns

Request URL:http://api.example.com/user/register
Request Method:OPTIONS
Status Code:400 Bad Request
Remote Address:78.46.140.200:80
Response Headers
view source
Access-Control-Allow-Headers:X-Requested-With
Access-Control-Allow-Methods:GET
Access-Control-Allow-Origin:*
Connection:close
Content-Type:text/html; charset=UTF-8
Date:Thu, 09 Mar 2017 17:12:22 GMT
Server:Apache
Transfer-Encoding:chunked
Request Headers
view source
Accept:*/*
Accept-Encoding:gzip, deflate, sdch
Accept-Language:ru-RU,ru;q=0.8,en-US;q=0.6,en;q=0.4,az;q=0.2
Access-Control-Request-Headers:content-type
Access-Control-Request-Method:POST
Connection:keep-alive
Host:api.example.com
Origin:http://example.com
Referer:http://example.com/register
User-Agent:Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36


问:
Facebook C# SDK Authorization Problem
I have an iFrame Facebook application.  I am using the Facebook C# SDK, Facebook and Facebook.Web libraries.

When a user first comes to my application I create a FacebookApp object on page_load().  If the app.Session is null I create a CavasAuthorizer(app) then call Authorize().

Two problems:

First, the redirect URL that is generated by calling Authorize causes Facebook to error with a bad "next" parameter.  Says the "next" parameter is not owned by the application. It looks like this:

```<code>next=http://localhost:4002/facebookredirect.axd/mygame_dev/mygame.aspx
</code>```

I can edit the code in CanvasURLBuilder to make the next look like this:

```<code>next=http://localhost:4002/mygame.aspx
</code>```

At this point the URL works if I cut and paste into a browser however it brings me to my second issue.

When the code runs the user is presented with a mostly empty page with a mid-sized Facebook image and a link "go to Facebook".  When the user clicks on the link it then takes the user to the correct authorization page for my application.

I have a feeling these are two possibly related issues but potentially separate.

Any help here would be greatly appreciated.

-Andy

答: To test locally make sure your Site URL and Canvas URL in facebook is something like http://localhost:8181/yourpage.  Then make sure in VS you set the setting under project properties\Web so that ports are not dynamically generated and you can use 8181 (or whatever port you like, as long as it is the same as in FB).</p>

Title: Facebook C# SDK Authorization Problem

Body:
I have an iFrame Facebook application.  I am using the Facebook C# SDK, Facebook and Facebook.Web libraries.

When a user first comes to my application I create a FacebookApp object on page_load().  If the app.Session is null I create a CavasAuthorizer(app) then call Authorize().

Two problems:

First, the redirect URL that is generated by calling Authorize causes Facebook to error with a bad "next" parameter.  Says the "next" parameter is not owned by the application. It looks like this:

next=http://localhost:4002/facebookredirect.axd/mygame_dev/mygame.aspx

I can edit the code in CanvasURLBuilder to make the next look like this:

next=http://localhost:4002/mygame.aspx

At this point the URL works if I cut and paste into a browser however it brings me to my second issue.

When the code runs the user is presented with a mostly empty page with a mid-sized Facebook image and a link "go to Facebook".  When the user clicks on the link it then takes the user to the correct authorization page for my application.

I have a feeling these are two possibly related issues but potentially separate.

Any help here would be greatly appreciated.

-Andy


问:
Where can I modify wordpress contact form?
I downloaded a theme on the internet and am trying to modify its "contact" page. I cannot find the place to modify it anywhere on wordpress admin panel

When I pressed on "edit page", there is no code of the contact form, I cannot edit the code

I doubt the contact form is a plugin and look for it in my Plugin list. But no plugin for contact form either

Where can I find the code/ settings so that I can customize this contact form?

答: Download the wordpress theme, put it in a zip file, open it in WinRAR then click find and search for the string that will help you find out where the contact form is being generated. You can search for "Human Verification".</p>


问:
Python parent process is not catching SIGTERM/SIGINT signals when launching subprocess using os.sytem()
I have two python scripts as below -

parent.py

```<code>import os
import signal

shutdown = False

def sigterm_handler(signum, frame):
    global shutdown
    shutdown = True

if __name__ == '__main__':
    signal.signal(signal.SIGTERM, sigterm_handler)
    signal.signal(signal.SIGINT, sigterm_handler)
    os.chdir(os.path.dirname(os.path.abspath(__file__)))
    cmd = 'python child.py'
    while True:
        if shutdown == True:
            break
        print 'executing %s' % cmd
        exit_code = os.system(cmd)
        print 'Exit Code from %s > %s' % (cmd, exit_code)
    print 'Exiting Parent'
</code>```

child.py

```<code>import signal
import time

shutdown = False

def sigterm_handler(signum, frame):
    global shutdown
    shutdown = True

if __name__ == '__main__':
    signal.signal(signal.SIGTERM, sigterm_handler)
    signal.signal(signal.SIGINT, sigterm_handler)
    while True:
        if shutdown == True:
            break
        print 'Child Process Running !!'
        time.sleep(1)
</code>```

If I run parent.py and press ctrl + c on the terminal the child process exits and gets restarted by the parent as the parent is not processing the SIGINT is not being processed by the parent. I want to terminate both parent and the child if ctrl + c is pressed on the terminal. But for cases where the child exits because of some error instead of ctrl + c event, I want the parent to continue executing. I could have handled SIGCHLD in the parent but that doesn't indicate if the child was exited because of a ctrl + c event or something else. How would I achieve this behavior ?

below is the output I get if I run the parent -

```<code>executing python child.py
Child Process Running !!
Child Process Running !!
Child Process Running !!
Child Process Running !!
^CExit Code from python child.py > 2
executing python child.py
Child Process Running !!
Child Process Running !!
Child Process Running !!
Child Process Running !!
Child Process Running !!
^CExit Code from python child.py > 2
executing python child.py
Child Process Running !!
Child Process Running !!
Child Process Running !!
Child Process Running !!
^CExit Code from python child.py > 2
............................
............................
</code>```

答:
I think you'll have better luck with subprocess than os.system. In particular, I think you'll want to use subprocess with shell=False so that your child command is executed without a subshell (which might interfere with your ability to handle these kinds of signal-handling scenarios).

The code below does what you want, if I understand you correctly: CTRL-C causes both child and parent to stop; but if child dies for some other reason, parent will run the child again.

Here's a parent program similar to yours:

```<code>import signal
import subprocess

shutdown = False

def sigterm_handler(signum, frame):
    print 'parent got shutdown'
    global shutdown
    shutdown = True

if __name__ == '__main__':
    signal.signal(signal.SIGTERM, sigterm_handler)
    signal.signal(signal.SIGINT, sigterm_handler)
    cmd_args = ['python', 'child.py']
    while not shutdown:
        print 'executing', cmd_args
        try:
            subprocess.check_call(cmd_args)
        except subprocess.CalledProcessError:
            print 'child died'
            pass
    print 'Exiting Parent'
</code>```

And here is a child program that runs for a while and then dies with a ZeroDivisionError.

```<code>import signal
import sys
import time

def sigterm_handler(signum, frame):
    print 'child got shutdown'
    sys.exit(0)

if __name__ == '__main__':
    signal.signal(signal.SIGTERM, sigterm_handler)
    signal.signal(signal.SIGINT, sigterm_handler)
    for i in range(3, -1, -1):
        print 'Child Process Running', i, i/i
        time.sleep(3)
</code>```

Body:
I have two python scripts as below -

parent.py

import os
import signal

shutdown = False

def sigterm_handler(signum, frame):
    global shutdown
    shutdown = True

if __name__ == '__main__':
    signal.signal(signal.SIGTERM, sigterm_handler)
    signal.signal(signal.SIGINT, sigterm_handler)
    os.chdir(os.path.dirname(os.path.abspath(__file__)))
    cmd = 'python child.py'
    while True:
        if shutdown == True:
            break
        print 'executing %s' % cmd
        exit_code = os.system(cmd)
        print 'Exit Code from %s > %s' % (cmd, exit_code)
    print 'Exiting Parent'

child.py

import signal
import time

shutdown = False

def sigterm_handler(signum, frame):
    global shutdown
    shutdown = True

if __name__ == '__main__':
    signal.signal(signal.SIGTERM, sigterm_handler)
    signal.signal(signal.SIGINT, sigterm_handler)
    while True:
        if shutdown == True:
            break
        print 'Child Process Running !!'
        time.sleep(1)

If I run parent.py and press ctrl + c on the terminal the child process exits and gets restarted by the parent as the parent is not processing the SIGINT is not being processed by the parent. I want to terminate both parent and the child if ctrl + c is pressed on the terminal. But for cases where the child exits because of some error instead of ctrl + c event, I want the parent to continue executing. I could have handled SIGCHLD in the parent but that doesn't indicate if the child was exited because of a ctrl + c event or something else. How would I achieve this behavior ?

below is the output I get if I run the parent -

executing python child.py
Child Process Running !!
Child Process Running !!
Child Process Running !!
Child Process Running !!
^CExit Code from python child.py > 2
executing python child.py
Child Process Running !!
Child Process Running !!
Child Process Running !!
Child Process Running !!
Child Process Running !!
^CExit Code from python child.py > 2
executing python child.py
Child Process Running !!
Child Process Running !!
Child Process Running !!
Child Process Running !!
^CExit Code from python child.py > 2
............................
............................

Body:
I think you'll have better luck with subprocess than os.system. In particular, I think you'll want to use subprocess with shell=False so that your child command is executed without a subshell (which might interfere with your ability to handle these kinds of signal-handling scenarios).

The code below does what you want, if I understand you correctly: CTRL-C causes both child and parent to stop; but if child dies for some other reason, parent will run the child again.

Here's a parent program similar to yours:

import signal
import subprocess

shutdown = False

def sigterm_handler(signum, frame):
    print 'parent got shutdown'
    global shutdown
    shutdown = True

if __name__ == '__main__':
    signal.signal(signal.SIGTERM, sigterm_handler)
    signal.signal(signal.SIGINT, sigterm_handler)
    cmd_args = ['python', 'child.py']
    while not shutdown:
        print 'executing', cmd_args
        try:
            subprocess.check_call(cmd_args)
        except subprocess.CalledProcessError:
            print 'child died'
            pass
    print 'Exiting Parent'

And here is a child program that runs for a while and then dies with a ZeroDivisionError.

import signal
import sys
import time

def sigterm_handler(signum, frame):
    print 'child got shutdown'
    sys.exit(0)

if __name__ == '__main__':
    signal.signal(signal.SIGTERM, sigterm_handler)
    signal.signal(signal.SIGINT, sigterm_handler)
    for i in range(3, -1, -1):
        print 'Child Process Running', i, i/i
        time.sleep(3)


问:
Sort php array based on current time
I am currently using the following json data. (The key is a time hh:mm)

```<code> "chart": {
    "23:20": 11,
    "23:30": 11,
    "23:40": 11,
    "23:50": 16,
    "00:00": 16,
    "00:10": 14,
    "00:20": 11,
    "00:30": 12,
    "00:40": 14,
    "00:50": 10,
    "01:00": 8,
    "01:10": 12,
    "01:20": 15,
    "01:30": 13,
    "01:40": 11,
    "01:50": 8,
    "02:00": 8
 }
</code>```

https://pastebin.com/cp16Rr9w

I am then moving the data to a php array. I would like to sort the array, so it starts at the current server time and goes on from there.

At the moment i am using the following php (unsorted)

```<code>  <?php
    foreach ($data['chart'] as $key => $value){
        echo 'Time: '.$key.'Data: '.$value;
    }
  ?>
</code>```

答:
```<code>function hsort($a, $b) // callback function for uksort function
{
    return (floatval(str_replace(":", ".", $a)) - floatval(str_replace(":", ".", $b))) // convert each time to float value, like '01:56'-> "01.56", then compare values as float
}

$chart = array_flip($chart); // flip indexes with values to get ability to operate with indexes as array values (which are time in your array)
uksort($chart, "hsort"); // sort time values
$chart = array_flip($chart); // flip again to make time values as index again
</code>```

Title: Sort php array based on current time

Body:
I am currently using the following json data. (The key is a time hh:mm)

 "chart": {
    "23:20": 11,
    "23:30": 11,
    "23:40": 11,
    "23:50": 16,
    "00:00": 16,
    "00:10": 14,
    "00:20": 11,
    "00:30": 12,
    "00:40": 14,
    "00:50": 10,
    "01:00": 8,
    "01:10": 12,
    "01:20": 15,
    "01:30": 13,
    "01:40": 11,
    "01:50": 8,
    "02:00": 8
 }

https://pastebin.com/cp16Rr9w

I am then moving the data to a php array. I would like to sort the array, so it starts at the current server time and goes on from there.

At the moment i am using the following php (unsorted)

  <?php
    foreach ($data['chart'] as $key => $value){
        echo 'Time: '.$key.'Data: '.$value;
    }
  ?>


问:
How to config the marathon-lb when the container run in HOST network?
My json for marathon is below

```<code>{
  "id": "/storage/mysql",
  "cmd": null,
  "cpus": 1,
  "mem": 512,
  "disk": 0,
  "instances": 1,
  "constraints": [
    [
      "hostname",
      "UNIQUE"
    ]
  ],
  "container": {
    "type": "DOCKER",
    "volumes": [],
    "docker": {
      "image": "reg.xxxxx.cn/library/mysql:5.7",
      "network": "HOST",
      "portMappings": [],
      "privileged": true,
      "parameters": [],
      "forcePullImage": false
    }
  },
  "env": {
    "MYSQL_ROOT_PASSWORD": "123456"
  },
  "labels": {
    "HAPROXY_GROUP": "internal"
  },
  "portDefinitions": [
    {
      "port": 3306,
      "protocol": "tcp",
      "labels": {}
    }
  ]
}
</code>```

I find the haproxy (run at 192.168.30.142 View the screenshot) config is :

```<code>frontend storage_mysql_3306
  bind *:3306
  mode tcp
  use_backend storage_mysql_3306

backend storage_mysql_3306
  balance roundrobin
  mode tcp
  server 192_168_30_144_31695 192.168.30.144:31695
</code>```

the mysql container is run at 192.168.30.144 View the screenshot, so what i want is :

```<code>server 192_168_30_144_3306 192.168.30.144:3306
</code>```

so what should i do to slove it?
thanks!

答:
I think I found the answer
http://mesosphere.github.io/marathon/docs/host-port.html

Mesos agents do NOT offer all ports

Am I right?

Body:
My json for marathon is below

{
  "id": "/storage/mysql",
  "cmd": null,
  "cpus": 1,
  "mem": 512,
  "disk": 0,
  "instances": 1,
  "constraints": [
    [
      "hostname",
      "UNIQUE"
    ]
  ],
  "container": {
    "type": "DOCKER",
    "volumes": [],
    "docker": {
      "image": "reg.xxxxx.cn/library/mysql:5.7",
      "network": "HOST",
      "portMappings": [],
      "privileged": true,
      "parameters": [],
      "forcePullImage": false
    }
  },
  "env": {
    "MYSQL_ROOT_PASSWORD": "123456"
  },
  "labels": {
    "HAPROXY_GROUP": "internal"
  },
  "portDefinitions": [
    {
      "port": 3306,
      "protocol": "tcp",
      "labels": {}
    }
  ]
}

I find the haproxy (run at 192.168.30.142 View the screenshot) config is :

frontend storage_mysql_3306
  bind *:3306
  mode tcp
  use_backend storage_mysql_3306

backend storage_mysql_3306
  balance roundrobin
  mode tcp
  server 192_168_30_144_31695 192.168.30.144:31695

the mysql container is run at 192.168.30.144 View the screenshot, so what i want is :

server 192_168_30_144_3306 192.168.30.144:3306

so what should i do to slove it?
thanks!


问:
Using Rails polymorphism for nested comments
I need to build a nested comments system in a Rails 3 application that allows for comments on many models (articles, posts, etc) and am debating rolling my own solution along the lines of this post.  There are gems available like acts_as_commentable_with_threading with awesome_nested_set, but they feel bloated for my needs.

I need to be able to add comments to multiple models

I need to be able to add comments to comments, infinitely deep

I need to be able to efficiently retrieve all descendants for a post, article, etc

I need to be able to efficiently present the comments in their appropriate nesting

My question is, were I to roll my own solution what potential hiccups I could face.  I want to avoid going down one path only to reach a dead end.  My initial concerns relate to efficiently querying for children.  Say, for instance, getting a list of an articles descendant comments (children and children of children).

Anyone have input on this?  Thanks.

答:
A tree structure, yes, is a good idea - however it is the query execution itself that is of the utmost concern and i don't think most tree implementations as a gem take this into account and whilst nested set is alright - i reckon if something really bad happened, its overcomplicated in terms of write operations.

I'd check out Recursive CTEs - whilst not database agnostic, it gives you a nice data structure to work with without having to have extra attributes to track.


问:
Accessing super class variables/methods in sub class
Since subclass can access super class's variables and methods defined as protected, why following code gives compile error?</p>

```<code>public class Animal {
    protected int var;

    public void eat() {
        System.out.println("Animal eating");
    }
}
class Dog extends Animal {
    Animal an = new Animal();
    an.var = 10;
}
</code>```

答:
You need to put it inside a Method. See below :

class Dog extends Animal {

```<code>public void testMe()
{
    Animal an = new Animal();
    an.var = 10;
}
</code>```

}

Body:
Since subclass can access super class's variables and methods defined as protected, why following code gives compile error?

public class Animal {
    protected int var;

    public void eat() {
        System.out.println("Animal eating");
    }
}
class Dog extends Animal {
    Animal an = new Animal();
    an.var = 10;
}

Body:
You need to put it inside a Method. See below :

class Dog extends Animal {

public void testMe()
{
    Animal an = new Animal();
    an.var = 10;
}

}


问:
html:options calls get before set -> null pointer
I have the following:

```<code>    <html:select property="myObject.value">
        <html:options property='myMap(someKey)'/>
    </html:select>
</code>```

Where map(someKey) is set in the action. I've also created these methods in the form:

```<code>public void setMyMap( final Map<String, Collection<String>> map )
{
    myMap = map;
}

public Map<String, Collection<String>> getMyMap()
{
    return myMap;
}
</code>```

This almost seems to work, but occasionally myMap(someKey) is accessed before the appropriate Action is even hit, leading to null pointers. What am I doing wrong, here?

Edit:

If I use a LazyMap to work around this issue, I avoid null pointers until the action sets the form up. I'd still like to know why this is happening, however.

答: Use a LazyMap or upgrade to Struts 2/3, so someone might actually be able to help you.</p>

Body:
I have the following:

Where map(someKey) is set in the action. I've also created these methods in the form:

public void setMyMap( final Map<String, Collection<String>> map )
{
    myMap = map;
}

public Map<String, Collection<String>> getMyMap()
{
    return myMap;
}

This almost seems to work, but occasionally myMap(someKey) is accessed before the appropriate Action is even hit, leading to null pointers. What am I doing wrong, here?

Edit:

If I use a LazyMap to work around this issue, I avoid null pointers until the action sets the form up. I'd still like to know why this is happening, however.


问:
SQL Join with data associated to dates
Currently I have a simple SQL request to get aall group departure date and the associated group size (teamLength) between 2 dates but it doesn't work properly.

SELECT `groups`.`departure`, COUNT(`group_users`.`group_id`) as 'teamLength'
FROM `groups`
    INNER JOIN `group_users`
ON `groups`.`id` = `group_users`.`group_id`
  WHERE departure BETWEEN '2017-03-01' AND '2017-03-31'
```

In fact, if I have more than 1 group between the 2 dates, only 1 date will be recovered in association with the total number of teamLength.

For exemple, if I have 2 groups in the same interval with, for group 1, 2 people and for group 2, 1 people, the result will be:

Here are 2 screenshots of the current state of my groups and group_users tables:

Is it even possible to do what I want in only 1 SQL request ? Thanks

答:
In addition to what jarlh commented (JOIN with ON). Don't ever group data without an explicit GROUP BY. I don't know why MYSQL still allows this...

Change your query to something like this and you should get the result you are looking for. Currently, the other departure dates get lost in the aggregation.

```<code>SELECT
    groups.departure,
    COUNT(1) as team_length
FROM
    groups
    INNER JOIN group_users
        ON groups.id = group_users.group_id
WHERE
    groups.departure BETWEEN '2017-03-01' AND '2017-03-31'
GROUP BY
    groups.departure
</code>```

Title: SQL Join with data associated to dates

Body:
Currently I have a simple SQL request to get aall group departure date and the associated group size (teamLength) between 2 dates but it doesn't work properly.

SELECT `groups`.`departure`, COUNT(`group_users`.`group_id`) as 'teamLength'
FROM `groups`
    INNER JOIN `group_users`
ON `groups`.`id` = `group_users`.`group_id`
  WHERE departure BETWEEN '2017-03-01' AND '2017-03-31'

In fact, if I have more than 1 group between the 2 dates, only 1 date will be recovered in association with the total number of teamLength.

For exemple, if I have 2 groups in the same interval with, for group 1, 2 people and for group 2, 1 people, the result will be:

Here are 2 screenshots of the current state of my groups and group_users tables:

Is it even possible to do what I want in only 1 SQL request ? Thanks

Body:
In addition to what jarlh commented (JOIN with ON). Don't ever group data without an explicit GROUP BY. I don't know why MYSQL still allows this...

Change your query to something like this and you should get the result you are looking for. Currently, the other departure dates get lost in the aggregation.

SELECT
    groups.departure,
    COUNT(1) as team_length
FROM
    groups
    INNER JOIN group_users
        ON groups.id = group_users.group_id
WHERE
    groups.departure BETWEEN '2017-03-01' AND '2017-03-31'
GROUP BY
    groups.departure


问:
Keras - stateful vs stateless LSTMs
I'm having a hard time conceptualizing the difference between stateful and stateless LSTMs in Keras. My understanding is that at the end of each batch, the "state of the network is reset" in the stateless case, whereas for the stateful case, the state of the network is preserved for each batch, and must then be manually reset at the end of each epoch.

My questions are as follows:
1. In the stateless case, how is the network learning if the state isn't preserved in-between batches?
2. When would one use the stateless vs stateful modes of an LSTM?

答:
I recommend you to firstly learn the concepts of BPTT (Back Propagation Through Time) and mini-batch SGD(Stochastic Gradient Descent), then you'll have further understandings of LSTM's training procedure.

For your questions,

Q1. In stateless cases, LSTM updates parameters on batch1 and then, initiate hidden states and cell states (usually all zeros) for batch2, while in stateful cases, it uses batch1's last output hidden states and cell sates as initial states for batch2.

Q2. As you can see above, when two sequences in two batches have connections (e.g. prices of one stock), you'd better use stateful mode, else (e.g. one sequence represents a complete sentence) you should use stateless mode.

BTW, @vu.pham said if we use stateful RNN, then in production, the network is forced to deal with infinite long sequences. This seems not correct, actually, as you can see in Q1, LSTM WON'T learn on the whole sequence, it first learns sequence in batch1, updates parameters, and then learn sequence on batch2.

Title: Keras - stateful vs stateless LSTMs


答:
I think that you have a syntax issue in your query. You are missing the ON statement so your database could be trying to get a cartesian product since there is no join clause.

```<code>SELECT `groups`.`departure`, COUNT(`group_users`.`id`) as 'teamLength'
FROM `groups`
    INNER JOIN `group_users` ON `groups`.`id` = `group_users`.`group_id`
WHERE departure BETWEEN '2017-03-01' AND '2017-03-31'
GROUP BY `groups`.`departure`
</code>```

You also are missing the GROUP BYclause which is not mandatory in all RDBS but it is a good practice to set it.

Title: SQL Join with data associated to dates

Body:
I think that you have a syntax issue in your query. You are missing the ON statement so your database could be trying to get a cartesian product since there is no join clause.

SELECT `groups`.`departure`, COUNT(`group_users`.`id`) as 'teamLength'
FROM `groups`
    INNER JOIN `group_users` ON `groups`.`id` = `group_users`.`group_id`
WHERE departure BETWEEN '2017-03-01' AND '2017-03-31'
GROUP BY `groups`.`departure`

You also are missing the GROUP BYclause which is not mandatory in all RDBS but it is a good practice to set it.


问:
Emacs cache save error with cedet
Installed GNU Emacs 23.2.1 (i686-pc-linux-gnu) and I'm getting constant save errors. The following line is repeated over and over again with maybe 30sec intervals.

```<code>byte-code: Beginning of buffer [6 times]
Error Writing Table: #<semanticdb-table ctype.h>
Save Error: "\"Error in macro \\\"name\\\"\"": /home/user/.emacs.d/semanticdb/!usr!include!semantic.cache
</code>```

Any useful tips as to why or maybe even a solution? Stripped my .emacs only to the following 2 lines but the problems still persists

```<code>(global-ede-mode 1)
(semantic-mode 1)
</code>```

Tried deleting the cached files under the /sematicsdb/ folder but still the error pops up.

答:
There is a macro somewhere in one of your header files that CEDET can't handle.  Newer versions of CEDET (the one from the bzr repository on cedet.sf.net) work around the problem first by fixing some macro parsing problems, and secondarily by ignoring those problems during a save.

The newer version of CEDET that doesn't come with Emacs has a different install than what is in Emacs, but it should still work if you follow the installation instructions (which excludes 'semantic-mode').

Title: Emacs cache save error with cedet

Body:
Installed GNU Emacs 23.2.1 (i686-pc-linux-gnu) and I'm getting constant save errors. The following line is repeated over and over again with maybe 30sec intervals.

byte-code: Beginning of buffer [6 times]
Error Writing Table: #<semanticdb-table ctype.h>
Save Error: "\"Error in macro \\\"name\\\"\"": /home/user/.emacs.d/semanticdb/!usr!include!semantic.cache

Any useful tips as to why or maybe even a solution? Stripped my .emacs only to the following 2 lines but the problems still persists

(global-ede-mode 1)
(semantic-mode 1)

Tried deleting the cached files under the /sematicsdb/ folder but still the error pops up.


问:
Required Property and JSON PropertyName
I want to create a class with an required attribute and a mapped JSON name like the following:

```<code>class MyClass {
  [Required]
  public string Foo {get; set;}
}
</code>```

This works all fine. But combining this with an JSON annotation like the following, breaks the validation

```<code>class MyClass {
  [Required]
  [JsonProperty(PropertyName = "bar")]
  public string Foo {get; set;}
}
</code>```

Why does the behavior change here and how can I fix that?

答:
Try this:</p>

```<code>class MyClass
{
    [JsonProperty(PropertyName = "bar", Required = Required.Always)]
    public string Foo { get; set; }
}
</code>```

Title: Required Property and JSON PropertyName

Body:
I want to create a class with an required attribute and a mapped JSON name like the following:

class MyClass {
  [Required]
  public string Foo {get; set;}
}

This works all fine. But combining this with an JSON annotation like the following, breaks the validation

class MyClass {
  [Required]
  [JsonProperty(PropertyName = "bar")]
  public string Foo {get; set;}
}

Why does the behavior change here and how can I fix that?

Body:
Try this:

class MyClass
{
    [JsonProperty(PropertyName = "bar", Required = Required.Always)]
    public string Foo { get; set; }
}


问:
Update Ajax Url calls when scroll
I need to update/change the AJAX call while scrolling the page. I tried this with the scroll handler, but it doesn't work.

```<code>var size = "8";
var from = "0";
var url = "mywebservice" + from + "&s=" + size;

$(document).scroll(function (e) {
  var url = "mywebservice" + from + "&s=" + size;
  if ($(window).scrollTop() >= $(document).height() - $(window).height() - 10) {
    ++size;
  }

  $.ajax({
    type: 'GET',
    url: url,
    data: { get_param: 'value' },
    dataType: 'json',
    success: function (data) {
      $.each(data, function (index, element) {
        var HTML ='<div>' + element.name + '</div>';
        $('#container').append(HTML);
      });
    }
  });
});
</code>```

答:
Try using alert(size) on scroll handler. If it works then your code should work too.
And i think you should assign the value of URL after the if condition. So that each time you scroll, condition will be checked and you might get incremented size if condition is true.</p>

Title: Update Ajax Url calls when scroll

Body:
I need to update/change the AJAX call while scrolling the page. I tried this with the scroll handler, but it doesn't work.

var size = "8";
var from = "0";
var url = "mywebservice" + from + "&s=" + size;

$(document).scroll(function (e) {
  var url = "mywebservice" + from + "&s=" + size;
  if ($(window).scrollTop() >= $(document).height() - $(window).height() - 10) {
    ++size;
  }

  $.ajax({
    type: 'GET',
    url: url,
    data: { get_param: 'value' },
    dataType: 'json',
    success: function (data) {
      $.each(data, function (index, element) {
        var HTML ='
' + element.name + '
';
        $('#container').append(HTML);
      });
    }
  });
});


问:
How can I set image in middle ( center allign ) during printing in html css?
Any one please tell me how can I set this image in center allign for print?

I am using paid plugin "Real 3d Flipbook".

Below is a image.

答:
Use media = print in style tag and define css to positioning margin and padding. e.g.    </p>

```<code><style media="print">
   img{
      align:center;
   }
</style>
</code>```

Body:
Use media = print in style tag and define css to positioning margin and padding. e.g.

<style media="print">
   img{
      align:center;
   }
</style>


问:
Replace a range of elements in a vector with a value
I want to replace any value from a position a to a position b inside my vector.

I read about replace function, but I have to specify the value that I want replaced. I need to replace any values.

For example if the vector is: 1 2 3 4 5 6 7 8 9 0 0 0 0 0 0, and I want to replace all the elements from position 0 to position 8 with another value, how can I use that replace function?

Now I'm using a for loop to do that, but my program is very slow.

答:
Probably std::fill does what you want.</p>

```<code>int newValue = 0;
std::fill(std::begin(v), std::begin(v) + 8, newValue);
</code>```

Body:
Probably std::fill does what you want.

int newValue = 0;
std::fill(std::begin(v), std::begin(v) + 8, newValue);


问:
windows grep regex not working
Windows 10.

grep installed as part of git installation.

```<code>>grep --version

grep (GNU grep) 2.27
Copyright (C) 2016 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>.
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.

Written by Mike Haertel and others, see <http://git.sv.gnu.org/cgit/grep.git/tree/AUTHORS>.

>git --version

git version 2.12.0.windows.1
</code>```

File sample.txt created with notepad contains the following 3 lines;

```<code>a
b
c
</code>```

Get grep to return lines starting with 'a' or 'c' ;

```<code>>grep ^[ac].*$ sample.txt
a
c
</code>```

(OK - as expected)

Get grep to return lines starting with any char except 'a' or 'c' i.e. the line starting with 'b' ;

```<code>>grep ^[^ac].*$ sample.txt
a
c
</code>```

why is this not working ?

答:
At the command line ^ is used to indicate an escape (i.e. ^| is treated as as literal | as opposed to a command pipe).

To escape the escape double it so: ^^[^^ac ...

Title: windows grep regex not working

Body:
Windows 10.

grep installed as part of git installation.

>grep --version

grep (GNU grep) 2.27
Copyright (C) 2016 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>.
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.

Written by Mike Haertel and others, see <http://git.sv.gnu.org/cgit/grep.git/tree/AUTHORS>.

>git --version

git version 2.12.0.windows.1

File sample.txt created with notepad contains the following 3 lines;

a
b
c

Get grep to return lines starting with 'a' or 'c' ;

>grep ^[ac].*$ sample.txt
a
c

(OK - as expected)

Get grep to return lines starting with any char except 'a' or 'c' i.e. the line starting with 'b' ;

>grep ^[^ac].*$ sample.txt
a
c

why is this not working ?


问:
Python using Selenium lost count of a In range
I'm trying to get the HTML of many pages on a website more than a thousand.
My script is working but for no reason after a random number of page recuperate the script go to the next page. He does not take in the count all the page I want to get.

```<code> from selenium import webdriver
 from selenium.webdriver.common.keys import Keys
 from bs4 import BeautifulSoup
 import time
 import os.path

   classes = ["sup","spé","b1","b2","b3","2C",
  "2A","2D","m1","m2","m3","2B","3C","3B",'3D',"3A"]

def CrawlingAll():

for  Classes in classes :

    dir = os.path.dirname(__file__)
    print(dir)
    filename = os.path.join(dir, 'Fiche', Classes)
    print(filename)
    if not os.path.exists(filename):
        os.makedirs(filename)

    driver = webdriver.Chrome()

    #Identification

    driver.get("https://username:pw@web.esme.fr/sas/common/archives.aspx")

    year = driver.find_element_by_id("sas_SelectionPlaceHolder__anneeSelect")
    year.send_keys("1998")

    classe = driver.find_element_by_id("sas_SelectionPlaceHolder_nomClasse")
    classe.send_keys(Classes)

    search = driver.find_element_by_id("sas_SelectionPlaceHolder__btnSubmit")
    search.click()

    #iteration du clicks des fiches eleves
    try:
        for i in range(1, 10000):
            fiche = driver.find_element_by_xpath('//*[@id="liste"]/tbody/tr[%s]/td[4]/a'%(i))
            fiche.click()

            driver.switch_to_window(driver.window_handles[1]) #switch vers la pop up
            source_code = driver.page_source #recuperation du code source de la pop up
            driver.close() #fermeture de la pop up
            driver.switch_to_window(driver.window_handles[0]) #retour a la fenetre principale

    #Ecriture des fiches html / eleves
            with open("%s/file-"%filename + str(i) + ".html", 'wb') as f:
                f.write(source_code.encode('utf-16'))
                f.close()

    except:
        print ("======DONE======")

    driver.close() #fermeture de la fenetre principale

def Crawlingclasses():

print("Select the class your want to crawl:  ")
print(classes)
Classe = input ()

print("Select when do you want to start crawling ex: 2015:  ")
Year = input()

dir = os.path.dirname(__file__)
print (dir)
filename = os.path.join(dir,'Fiche',Classe)
print (filename)

if not os.path.exists(filename):
    os.makedirs(filename)

driver = webdriver.Chrome()

# Identification

driver.get("https://username:pw@web.esme.fr/sas/common/archives.aspx")

# Remplissage des boxs

# ================================= CRAWLING SUP =================================

year = driver.find_element_by_id("sas_SelectionPlaceHolder__anneeSelect")
year.send_keys(Year)

classe = driver.find_element_by_id("sas_SelectionPlaceHolder_nomClasse")
classe.send_keys(Classe)

search = driver.find_element_by_id("sas_SelectionPlaceHolder__btnSubmit")
search.click()

# iteration du clicks des fiches eleves
try:
    for i in range(1, 10000):
        fiche = driver.find_element_by_xpath('//*[@id="liste"]/tbody/tr[%s]/td[4]/a' % (i))
        fiche.click()

        driver.switch_to_window(driver.window_handles[1])  # switch vers la pop up
        source_code = driver.page_source  # recuperation du code source de la pop up
        driver.close()  # fermeture de la pop up
        driver.switch_to_window(driver.window_handles[0])  # retour a la fenetre principale

        # Ecriture des fiches html / eleves
        with open("%s/file-"%filename + str(i) + ".html", 'wb') as f:
            f.write(source_code.encode('utf-16'))
            f.close()

except:
    print("======DONE======")

driver.close()  # fermeture de la fenetre principale
</code>```

The number of pages is trying to get is here try:

for i in range(1, 10000):

Any idea why selenium skipping many pages?

答:
I'm pretty sure that your code catches error but you didn't print the error message on your try except block, it's hard to tell what kind of error.

For now I suggest skipping an iteration if error encountered rather than skipping entire loop :

```<code>import sys

for i in range(1, 10000):
    try:
        fiche = driver.find_element_by_xpath('//*[@id="liste"]/tbody/tr[%s]/td[4]/a' % (i))
        fiche.click()

        driver.switch_to_window(driver.window_handles[1])  # switch vers la pop up
        source_code = driver.page_source  # recuperation du code source de la pop up
        driver.close()  # fermeture de la pop up
        driver.switch_to_window(driver.window_handles[0])  # retour a la fenetre principale

        # Ecriture des fiches html / eleves
        with open("%s/file-"%filename + str(i) + ".html", 'wb') as f:
            f.write(source_code.encode('utf-16'))
            f.close()
    except:
        print("Error at iteration %s:"%i, sys.exc_info()[0])
</code>```

Body:
I'm trying to get the HTML of many pages on a website more than a thousand.
My script is working but for no reason after a random number of page recuperate the script go to the next page. He does not take in the count all the page I want to get.

 from selenium import webdriver
 from selenium.webdriver.common.keys import Keys
 from bs4 import BeautifulSoup
 import time
 import os.path

   classes = ["sup","spé","b1","b2","b3","2C",
  "2A","2D","m1","m2","m3","2B","3C","3B",'3D',"3A"]

def CrawlingAll():

for  Classes in classes :

    dir = os.path.dirname(__file__)
    print(dir)
    filename = os.path.join(dir, 'Fiche', Classes)
    print(filename)
    if not os.path.exists(filename):
        os.makedirs(filename)

    driver = webdriver.Chrome()

    #Identification

    driver.get("https://username:pw@web.esme.fr/sas/common/archives.aspx")

    year = driver.find_element_by_id("sas_SelectionPlaceHolder__anneeSelect")
    year.send_keys("1998")

    classe = driver.find_element_by_id("sas_SelectionPlaceHolder_nomClasse")
    classe.send_keys(Classes)

    search = driver.find_element_by_id("sas_SelectionPlaceHolder__btnSubmit")
    search.click()

    #iteration du clicks des fiches eleves
    try:
        for i in range(1, 10000):
            fiche = driver.find_element_by_xpath('//*[@id="liste"]/tbody/tr[%s]/td[4]/a'%(i))
            fiche.click()

            driver.switch_to_window(driver.window_handles[1]) #switch vers la pop up
            source_code = driver.page_source #recuperation du code source de la pop up
            driver.close() #fermeture de la pop up
            driver.switch_to_window(driver.window_handles[0]) #retour a la fenetre principale

    #Ecriture des fiches html / eleves
            with open("%s/file-"%filename + str(i) + ".html", 'wb') as f:
                f.write(source_code.encode('utf-16'))
                f.close()

    except:
        print ("======DONE======")

    driver.close() #fermeture de la fenetre principale

def Crawlingclasses():

print("Select the class your want to crawl:  ")
print(classes)
Classe = input ()

print("Select when do you want to start crawling ex: 2015:  ")
Year = input()

dir = os.path.dirname(__file__)
print (dir)
filename = os.path.join(dir,'Fiche',Classe)
print (filename)

if not os.path.exists(filename):
    os.makedirs(filename)

driver = webdriver.Chrome()

# Identification

driver.get("https://username:pw@web.esme.fr/sas/common/archives.aspx")

# Remplissage des boxs

# ================================= CRAWLING SUP =================================

year = driver.find_element_by_id("sas_SelectionPlaceHolder__anneeSelect")
year.send_keys(Year)

classe = driver.find_element_by_id("sas_SelectionPlaceHolder_nomClasse")
classe.send_keys(Classe)

search = driver.find_element_by_id("sas_SelectionPlaceHolder__btnSubmit")
search.click()

# iteration du clicks des fiches eleves
try:
    for i in range(1, 10000):
        fiche = driver.find_element_by_xpath('//*[@id="liste"]/tbody/tr[%s]/td[4]/a' % (i))
        fiche.click()

        driver.switch_to_window(driver.window_handles[1])  # switch vers la pop up
        source_code = driver.page_source  # recuperation du code source de la pop up
        driver.close()  # fermeture de la pop up
        driver.switch_to_window(driver.window_handles[0])  # retour a la fenetre principale

        # Ecriture des fiches html / eleves
        with open("%s/file-"%filename + str(i) + ".html", 'wb') as f:
            f.write(source_code.encode('utf-16'))
            f.close()

except:
    print("======DONE======")

driver.close()  # fermeture de la fenetre principale

The number of pages is trying to get is here try:

for i in range(1, 10000):

Any idea why selenium skipping many pages?

Body:
I'm pretty sure that your code catches error but you didn't print the error message on your try except block, it's hard to tell what kind of error.

For now I suggest skipping an iteration if error encountered rather than skipping entire loop :

import sys

for i in range(1, 10000):
    try:
        fiche = driver.find_element_by_xpath('//*[@id="liste"]/tbody/tr[%s]/td[4]/a' % (i))
        fiche.click()

        driver.switch_to_window(driver.window_handles[1])  # switch vers la pop up
        source_code = driver.page_source  # recuperation du code source de la pop up
        driver.close()  # fermeture de la pop up
        driver.switch_to_window(driver.window_handles[0])  # retour a la fenetre principale

        # Ecriture des fiches html / eleves
        with open("%s/file-"%filename + str(i) + ".html", 'wb') as f:
            f.write(source_code.encode('utf-16'))
            f.close()
    except:
        print("Error at iteration %s:"%i, sys.exc_info()[0])


问:
Adding an ActionListener to a JList
I have a JList with an array of strings. Basically it displays a restaurant menu.
right next to the JList i have another JList which is empty. Whenever a user double clicks on a string in the first JList (where the menu is displayed)  I want it to show up on the next JList which is right next to it.

how do i do that?

答:
```<code>public void addActionListener(final ActionListener al) {

    jList.addKeyListener(new KeyAdapter() {
        public void keyPressed(KeyEvent e) {
            if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                al.actionPerformed(new ActionEvent(e.getSource(), e.getID(), "ENTER"));
            }
        }
    });

    jList().addMouseListener(new MouseAdapter() {
        public void mouseClicked(MouseEvent e) {
            if (e.getClickCount() == 2) {
                al.actionPerformed(new ActionEvent(e.getSource(), e.getID(), "ENTER"));
            }
        }
    });

}
</code>```

Title: Adding an ActionListener to a JList