问:
Can I use multiple H1 tags in bootstrap carousel
I am not able to decide how to structure my HTML document and how to place heading tags

Following is my page structure

```<code><html>
<head>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <header>
        <nav>
            //Logo and navigation using bootstrap code - site wide
        </nav>
    </header>
    <div>
        //bootstrap carouse
        <div>
            .....
            .....
            <!-- Wrapper for slides -->
            <div class="carousel-inner" role="listbox">
                <div class="item active" style="background-image: url('assets/ssp365.jpg')">
                    <div class="carousel-caption">
                        <h1>Heading for slide 1</h1>
                        <span>Brief description</span>
                    </div>
                </div>
                <div class="item" style="background-image: url('assets/ssp365.jpg')">
                    <div class="carousel-caption">
                        <h1>Heading for slide 2</h1>
                        <span>Brief description</span>
                    </div>
                </div>
                <div class="item" style="background-image: url('assets/ssp365.jpg')">
                    <div class="carousel-caption">
                        <h1>Heading for slide 3</h1>
                        <span>Brief description</span>
                    </div>
                </div>
            </div>
            ......
            ......

            //rest of the content
        </div>
    </div>
    <footer>
        //page footer - site wide
    </footer>
</body>
</html>
</code>```

I want to know if I can use H1's the way I have used within the bootstrap carousel caption.

I always find it difficult to decide where to place H1 tag when there is a carousel used at the top of the home page and there is no real heading to describe the page. Also, normally a home page tries to cover a lot of content about the entire website so it becomes difficult to structure the page.

Please help.

答:
I would recommend you to use css styling with font-size. Give page header a bigger size than the carousel hearders.

```<code>.page-header{
    font-size : 50px;
}

.carousel-header{
    font-size : 35px;
}
</code>```

Try these.

Body:
I am not able to decide how to structure my HTML document and how to place heading tags

Following is my page structure

    <link rel="stylesheet" href="style.css">

            //Logo and navigation using bootstrap code - site wide

        //bootstrap carouse

            .....
            .....

Heading for slide 1

                        Brief description

Heading for slide 2

                        Brief description

Heading for slide 3

                        Brief description

            ......
            ......

            //rest of the content

        //page footer - site wide

I want to know if I can use H1's the way I have used within the bootstrap carousel caption.

I always find it difficult to decide where to place H1 tag when there is a carousel used at the top of the home page and there is no real heading to describe the page. Also, normally a home page tries to cover a lot of content about the entire website so it becomes difficult to structure the page.

Please help.

Body:
I would recommend you to use css styling with font-size. Give page header a bigger size than the carousel hearders.

.page-header{
    font-size : 50px;
}

.carousel-header{
    font-size : 35px;
}

Try these.


来源: stackexchange

问:
Why head method is not working in swagger using docsstring in flask?
Docstring in triple quotes is not working in the head method. I am using the package flassger. I am not able to use docstring in head method for swagger ui. However, it is working in patch, post, put, and get methods.

```<code>from flasgger import Swagger

@app.route('/flight/<flight_no>', methods=['HEAD'])
    def get_flight_exist(flight_no):
        """
            show Flight Existence
            This resource returns flight exist response
            ---
            tags:
              - hello
            parameters:
            - name: flight_no
              in: path
              type: string
              description: Flight_no
              required: true

            responses:
                '200':
                  description: Flight data  response
                  schema:
                     description: Flight object
                     properties:
                       flight_name:
                         type: string
                         description: name of the flight
                       flight_no:
                         type: string
                         description: flight number
                       total_seat:
                         type: integer
                     required:
                       - flight_name
                       - flight_no
                       - total_seat

                '404':
                  description: Flight not found

            """
</code>```

答:
HEAD and OPTION are ignored by default.

You can use

```<code>app.config['SWAGGER'] = {'ignore_verbs': []}
</code>```

to pass an empty list to ignore

ContentLicense: CC BY-SA 3.0

Body:
Docstring in triple quotes is not working in the head method. I am using the package flassger. I am not able to use docstring in head method for swagger ui. However, it is working in patch, post, put, and get methods.

from flasgger import Swagger

@app.route('/flight/<flight_no>', methods=['HEAD'])
    def get_flight_exist(flight_no):
        """
            show Flight Existence
            This resource returns flight exist response
            ---
            tags:
              - hello
            parameters:
            - name: flight_no
              in: path
              type: string
              description: Flight_no
              required: true

            responses:
                '200':
                  description: Flight data  response
                  schema:
                     description: Flight object
                     properties:
                       flight_name:
                         type: string
                         description: name of the flight
                       flight_no:
                         type: string
                         description: flight number
                       total_seat:
                         type: integer
                     required:
                       - flight_name
                       - flight_no
                       - total_seat

                '404':
                  description: Flight not found

            """

Body:
HEAD and OPTION are ignored by default.

You can use

app.config['SWAGGER'] = {'ignore_verbs': []}

to pass an empty list to ignore


问:
How to show a UITableView in MKAnnotationView?
I would like to show several information in MKAnnotationView but the number of items is not always the same so I would like to make a non-scrollable UITableView in this MKAnnotationView.
I didn't managed to do that properly. When the annotation is placed, there is no annotation view by clicking on it.

Edit with Joakim comment:
The tableView is showed outside the AnnotationView and it doesn't disappear when click outside.

```<code>extension MapViewController: MKMapViewDelegate {
    func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
        let reuseIdentifier = "pin"

        var pinView = self.mapView.dequeueReusableAnnotationView(withIdentifier: reuseIdentifier) as? MKPinAnnotationView
        if pinView == nil {
            pinView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: reuseIdentifier)
            let placesTableView = UITableView(frame: CGRect(x: 0, y: 0, width: 150, height: 200))
            placesTableView.delegate = self
            placesTableView.dataSource = self
            placeData = ["France", "Ile de france", "Paris"]
            pinView?.addSubview(placesTableView)
        } else {
            pinView?.annotation = annotation
        }

        return pinView
    }

    func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {
        GlobalVariables.sharedInstance.selectedCountry = mapView.selectedAnnotations[0].title!!
        self.tabBarController?.selectedIndex = 0

        FIRAnalytics.logEvent(withName: "location_from_map", parameters: [
            "location": GlobalVariables.sharedInstance.selectedCountry as NSObject
            ])
    }
}

extension MapViewController: UITableViewDelegate {

}

extension MapViewController: UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return placeData.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell(style: .default, reuseIdentifier: nil)
        cell.textLabel?.text = placeData[indexPath.item]
        return cell
    }
}
</code>```

PS: The annotation view is visible with the other code I put so I know the problem comes from the tableview implementation.

答:
Problem solved. Thanks for the UIStackView advice.

My problem was in fact that I was setting the view in

mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView?

while I had to do it in

mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView).

DogCoffee's answer helped me on this post: MapKit iOS 9 detailCalloutAccessoryView usage

Body:
I would like to show several information in MKAnnotationView but the number of items is not always the same so I would like to make a non-scrollable UITableView in this MKAnnotationView.
I didn't managed to do that properly. When the annotation is placed, there is no annotation view by clicking on it.

Edit with Joakim comment:
The tableView is showed outside the AnnotationView and it doesn't disappear when click outside.

extension MapViewController: MKMapViewDelegate {
    func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
        let reuseIdentifier = "pin"

        var pinView = self.mapView.dequeueReusableAnnotationView(withIdentifier: reuseIdentifier) as? MKPinAnnotationView
        if pinView == nil {
            pinView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: reuseIdentifier)
            let placesTableView = UITableView(frame: CGRect(x: 0, y: 0, width: 150, height: 200))
            placesTableView.delegate = self
            placesTableView.dataSource = self
            placeData = ["France", "Ile de france", "Paris"]
            pinView?.addSubview(placesTableView)
        } else {
            pinView?.annotation = annotation
        }

        return pinView
    }

    func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {
        GlobalVariables.sharedInstance.selectedCountry = mapView.selectedAnnotations[0].title!!
        self.tabBarController?.selectedIndex = 0

        FIRAnalytics.logEvent(withName: "location_from_map", parameters: [
            "location": GlobalVariables.sharedInstance.selectedCountry as NSObject
            ])
    }
}

extension MapViewController: UITableViewDelegate {

}

extension MapViewController: UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return placeData.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell(style: .default, reuseIdentifier: nil)
        cell.textLabel?.text = placeData[indexPath.item]
        return cell
    }
}

PS: The annotation view is visible with the other code I put so I know the problem comes from the tableview implementation.


问:
Manage pages displayed in Progressive Web Apps ( PWA )
I am new to PWA and was just going through some readups. We have public website and in the website we provide login for users to manage their account. By going with PWA, I understand that users can save the website on the mobile homepage  as an icon. My question is that , when user click on my PWA icon , can we load the login page for the users so that they can only manage account with PWA instead of loading entire website.</p>

答:
Yes you can, within your web app manifest file you can set a JSON property called "start_url".

There's further information here https://developers.google.com/web/fundamentals/engage-and-retain/web-app-manifest/#set_a_start_url


问:
Second argument to std::vector
Looking at vector, I realized that I have never used the second argument when creating vectors.

```<code>std::vector<int> myInts; // this is what I usually do
std::vector<int, ???> myOtherInts; // but is there a second argument there?
</code>```

Looking at the link above it says that it is for:

Allocator object to be used instead of constructing a new one.

or, as for this one:

Allocator: Type of the allocator object used to define the storage allocation model. By default, the allocator class template for type T is used, which defines the simplest memory allocation model and is value-independent.

I guess it has to do with something with memory management. However, I am not sure how to use that.

Any pointers regarding this?

答:
Maybe this will help: http://www.codeguru.com/cpp/cpp/cpp_mfc/stl/article.php/c4079

You may try google for: stl allocator.

ContentLicense: CC BY-SA 2.5

Title: Second argument to std::vector

Body:
Looking at vector, I realized that I have never used the second argument when creating vectors.

std::vector<int> myInts; // this is what I usually do
std::vector<int, ???> myOtherInts; // but is there a second argument there?

Looking at the link above it says that it is for:

Allocator object to be used instead of constructing a new one.

or, as for this one:

Allocator: Type of the allocator object used to define the storage allocation model. By default, the allocator class template for type T is used, which defines the simplest memory allocation model and is value-independent.

I guess it has to do with something with memory management. However, I am not sure how to use that.

Any pointers regarding this?


问:
List validation(data annotation) not working on the client side
I have a Groups list which has a custom attribute method associated with it. It does not seem to catch the validation error on the screen. However on the controller, it gives ModelState.Valid as false. Is there a way to catch it in the view instead of it having to go to the server side and I then catch and display it?
Other validations are working, so its not the case of missing jquery files.

Model:

```<code>   [RequiredList(ErrorMessage = "The {0} field is required.")]
    [Display(Name = "Selected Organization(s)")]
    public List<OrganizationDTO> Organizations { get; set; }
</code>```

Custom Attribute:

```<code>public class RequiredListAttribute : ValidationAttribute
{
    public override bool IsValid(object value)
    {
        var list = value as IList;
        if (list != null)
        {
            return list.Count > 0;
        }
        return false;
    }
}
</code>```

View:

```<code><div class="form-group">
     <div class="controls">
          <label class="control-label" for="Selected Groups">Selected Group(s)</label>
               <div class="panel panel-default">
                     <div class="panel-body"  style="overflow-y: auto; max-height: 100px; min-height:50px" id="divSelGroups">
                          @for (int i = 0; Model.Groups!= null && i < Model.Groups.Count(); i++)
                          {
                             var group= Model.Groups[i];
                             var checkedAttr = (group.Id != Guid.Empty) ? "checked='checked'" : "";
                              <div class="row">
                                        <input type="hidden" name="Groups.Index" value="@i" />
                                        <input type="hidden"name="Groups[@i].Name" value="@group.Name" />
                                        <input type="hidden" name="Groups[@i].Data" value="@group.Data" />
                                        <div class="col-xs-1">
                                            <input type="checkbox" name="Groups[@i].Id" value="@group.Id" @checkedAttr data-org-selected="true" />
                                        </div>
                                        <div class="col-xs-11" data-toggle="tooltip" data-placement="top" title="@group.Data">@group.Name</div>
                                </div>
                           }
                     </div>
                  </div>
                  @Html.ValidationMessageFor(m => m.Groups)
          </div>
   </div>
</code>```

答:
I had to include a workaround to get it working, though does not answer my original question still gets the requirement of the question resolved. I had to introduce a hidden textbox which contains the number of list items and put a range validator on it.

Model:

```<code>[Range(1, double.MaxValue, ErrorMessage = "Atleast one organization needs to be selected.")]
public int OrgCount { get; set; }
</code>```

View:

```<code>@Html.TextBoxFor(m => m.OrgCount, new { style="visibility:hidden;height:0"})
@Html.ValidationMessageFor(m => m.OrgCount)
</code>```

JS script:

```<code>var orgCount = $(".panel-body  input[name='Organizations.Index']").last().val();
if (isNaN(orgCount))
    orgCount = -1;
$("#OrgCount").val(parseInt(orgCount) + 1);
</code>```

So basically if there are no elements I make it 0 and hence they fail the validation and so the range validator error message is displayed.

Body:
I have a Groups list which has a custom attribute method associated with it. It does not seem to catch the validation error on the screen. However on the controller, it gives ModelState.Valid as false. Is there a way to catch it in the view instead of it having to go to the server side and I then catch and display it?
Other validations are working, so its not the case of missing jquery files.

Model:

   [RequiredList(ErrorMessage = "The {0} field is required.")]
    [Display(Name = "Selected Organization(s)")]
    public List<OrganizationDTO> Organizations { get; set; }

Custom Attribute:

public class RequiredListAttribute : ValidationAttribute
{
    public override bool IsValid(object value)
    {
        var list = value as IList;
        if (list != null)
        {
            return list.Count > 0;
        }
        return false;
    }
}

View:

          Selected Group(s)

                          @for (int i = 0; Model.Groups!= null && i < Model.Groups.Count(); i++)
                          {
                             var group= Model.Groups[i];
                             var checkedAttr = (group.Id != Guid.Empty) ? "checked='checked'" : "";

                                        <input type="hidden" name="Groups.Index" value="@i" />
                                        <input type="hidden"name="Groups[@i].Name" value="@group.Name" />
                                        <input type="hidden" name="Groups[@i].Data" value="@group.Data" />

                                            <input type="checkbox" name="Groups[@i].Id" value="@group.Id" @checkedAttr data-org-selected="true" />

@group.Name

                           }

                  @Html.ValidationMessageFor(m => m.Groups)

Body:
I had to include a workaround to get it working, though does not answer my original question still gets the requirement of the question resolved. I had to introduce a hidden textbox which contains the number of list items and put a range validator on it.

Model:

[Range(1, double.MaxValue, ErrorMessage = "Atleast one organization needs to be selected.")]
public int OrgCount { get; set; }

View:

@Html.TextBoxFor(m => m.OrgCount, new { style="visibility:hidden;height:0"})
@Html.ValidationMessageFor(m => m.OrgCount)

JS script:

var orgCount = $(".panel-body  input[name='Organizations.Index']").last().val();
if (isNaN(orgCount))
    orgCount = -1;
$("#OrgCount").val(parseInt(orgCount) + 1);

So basically if there are no elements I make it 0 and hence they fail the validation and so the range validator error message is displayed.

ContentLicense: CC BY-SA 4.0


问:
Editable cells in dynamic table
I'm trying to make a dynamic table with variable no. of rows and columns. Table is created but when i click on the cells, they are not editable as i assumed they will be.

$(document).ready(function() {
            $("#createit").click(function() {
                var num_rows = document.getElementById('rows').value;
                var num_cols = document.getElementById('cols').value;
                var tbody = '';
                for (var i = 0; i < num_rows; i++) {
                    tbody += '
';
                    for (var j = 0; j < num_cols; j++) {
                        tbody += '';
                        tbody += 'Cell' + i + j;
                        tbody += '	'
                    }
                    tbody += '
';
                }
                //document.getElementById('wrapper').innerHTML = theader + tbody + tfooter;
                $('.editableTable').append(tbody);
            });
        });
        $(".editableTable td").dblclick(function() {
            console.log('clicked');
            var OriginalContent = $(this).text();
            $(this).addClass("cellEditing");
            $(this).html("<select><option>1</option><option>2</option><option >3</option></select>");
            $(this).children().first().focus();
            $(this).bgColor = 'red';

            $(this).children().first().keypress(function(e) {
                if (e.which == 13) {
                    var newContent = OriginalContent;
                    $(this).parent().text(OriginalContent);
                    $(this).parent().removeClass("cellEditing");
                }
            });
            $(this).children().first().blur(function() {
                $(this).parent().text(OriginalContent);
                $(this).parent().removeClass("cellEditing");
            });
        });
        $(".editableTable td").bind('keydown', function(event) {
            if (event.keyCode === 9 || event.keyCode === 13) {
                var tabindex = $(this).attr('tabindex');
                tabindex++; //increment tabindex
                $('[tabindex=' + tabindex + ']').focus().dblclick();
                return false;
            }
        });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.editableTable {
            border: solid 0px;
            width: 100%;
            text-align: center
        }

        .editableTable td {
            border: solid 0.5px;
            border-color: lightblue;
            min-width: 100px;
        }

        .editableTable .cellEditing {
            padding: 0;
        }

        select {
            border: 0px;
            width: 100%;
        }</code>```

Rows: <input type="text" name="rows" id="rows"/>

    Cols: <input type="text" name="cols" id="cols"/>

    <input name="generate" type="button" value="Create Table!" id='createit' />

```

Same thing i have done before but with a static table. JSFIDDLE https://jsfiddle.net/rbrohitbisht/691rx62k/

Now i want to do the same thing with the dynamic table. What i'm doing wrong here?

答:
You should add contenteditable="true" to your code

https://codepen.io/anon/pen/XgJaxE

```<code>$(document).ready(function() {
        $("#createit").click(function() {
            var num_rows = document.getElementById('rows').value;
            var num_cols = document.getElementById('cols').value;
            var tbody = '';
            for (var i = 0; i < num_rows; i++) {
                tbody += '<tr>';
                for (var j = 0; j < num_cols; j++) {
                    tbody += '<td contenteditable="true" tabindex=' + j + '>';
                    tbody += 'Cell' + i + j;
                    tbody += '</td>'
                }
                tbody += '</tr>';
            }
            //document.getElementById('wrapper').innerHTML = theader + tbody + tfooter;
            $('.editableTable').append(tbody);
        });
    });
    $(".editableTable td").dblclick(function() {
        console.log('clicked');
        var OriginalContent = $(this).text();
        $(this).addClass("cellEditing");
        $(this).html("<select><option>1</option><option>2</option><option >3</option></select>");
        $(this).children().first().focus();
        $(this).bgColor = 'red';

        $(this).children().first().keypress(function(e) {
            if (e.which == 13) {
                var newContent = OriginalContent;
                $(this).parent().text(OriginalContent);
                $(this).parent().removeClass("cellEditing");
            }
        });
        $(this).children().first().blur(function() {
            $(this).parent().text(OriginalContent);
            $(this).parent().removeClass("cellEditing");
        });
    });
    $(".editableTable td").bind('keydown', function(event) {
        if (event.keyCode === 9 || event.keyCode === 13) {
            var tabindex = $(this).attr('tabindex');
            tabindex++; //increment tabindex
            $('[tabindex=' + tabindex + ']').focus().dblclick();
            return false;
        }
    });
</code>```

Title: Editable cells in dynamic table

Body:
I'm trying to make a dynamic table with variable no. of rows and columns. Table is created but when i click on the cells, they are not editable as i assumed they will be.

$(document).ready(function() {
            $("#createit").click(function() {
                var num_rows = document.getElementById('rows').value;
                var num_cols = document.getElementById('cols').value;
                var tbody = '';
                for (var i = 0; i < num_rows; i++) {
                    tbody += '
';
                    for (var j = 0; j < num_cols; j++) {
                        tbody += '';
                        tbody += 'Cell' + i + j;
                        tbody += '	'
                    }
                    tbody += '
';
                }
                //document.getElementById('wrapper').innerHTML = theader + tbody + tfooter;
                $('.editableTable').append(tbody);
            });
        });
        $(".editableTable td").dblclick(function() {
            console.log('clicked');
            var OriginalContent = $(this).text();
            $(this).addClass("cellEditing");
            $(this).html("<select><option>1</option><option>2</option><option >3</option></select>");
            $(this).children().first().focus();
            $(this).bgColor = 'red';

            $(this).children().first().keypress(function(e) {
                if (e.which == 13) {
                    var newContent = OriginalContent;
                    $(this).parent().text(OriginalContent);
                    $(this).parent().removeClass("cellEditing");
                }
            });
            $(this).children().first().blur(function() {
                $(this).parent().text(OriginalContent);
                $(this).parent().removeClass("cellEditing");
            });
        });
        $(".editableTable td").bind('keydown', function(event) {
            if (event.keyCode === 9 || event.keyCode === 13) {
                var tabindex = $(this).attr('tabindex');
                tabindex++; //increment tabindex
                $('[tabindex=' + tabindex + ']').focus().dblclick();
                return false;
            }
        });

.editableTable {
            border: solid 0px;
            width: 100%;
            text-align: center
        }

        .editableTable td {
            border: solid 0.5px;
            border-color: lightblue;
            min-width: 100px;
        }

        .editableTable .cellEditing {
            padding: 0;
        }

        select {
            border: 0px;
            width: 100%;
        }

Rows: <input type="text" name="rows" id="rows"/>

    Cols: <input type="text" name="cols" id="cols"/>

    <input name="generate" type="button" value="Create Table!" id='createit' />

Same thing i have done before but with a static table. JSFIDDLE https://jsfiddle.net/rbrohitbisht/691rx62k/

Now i want to do the same thing with the dynamic table. What i'm doing wrong here?

Body:
You should add contenteditable="true" to your code

https://codepen.io/anon/pen/XgJaxE

$(document).ready(function() {
        $("#createit").click(function() {
            var num_rows = document.getElementById('rows').value;
            var num_cols = document.getElementById('cols').value;
            var tbody = '';
            for (var i = 0; i < num_rows; i++) {
                tbody += '<tr>';
                for (var j = 0; j < num_cols; j++) {
                    tbody += '<td contenteditable="true" tabindex=' + j + '>';
                    tbody += 'Cell' + i + j;
                    tbody += '</td>'
                }
                tbody += '</tr>';
            }
            //document.getElementById('wrapper').innerHTML = theader + tbody + tfooter;
            $('.editableTable').append(tbody);
        });
    });
    $(".editableTable td").dblclick(function() {
        console.log('clicked');
        var OriginalContent = $(this).text();
        $(this).addClass("cellEditing");
        $(this).html("<select><option>1</option><option>2</option><option >3</option></select>");
        $(this).children().first().focus();
        $(this).bgColor = 'red';

        $(this).children().first().keypress(function(e) {
            if (e.which == 13) {
                var newContent = OriginalContent;
                $(this).parent().text(OriginalContent);
                $(this).parent().removeClass("cellEditing");
            }
        });
        $(this).children().first().blur(function() {
            $(this).parent().text(OriginalContent);
            $(this).parent().removeClass("cellEditing");
        });
    });
    $(".editableTable td").bind('keydown', function(event) {
        if (event.keyCode === 9 || event.keyCode === 13) {
            var tabindex = $(this).attr('tabindex');
            tabindex++; //increment tabindex
            $('[tabindex=' + tabindex + ']').focus().dblclick();
            return false;
        }
    });


问:
Bootstrap accordions on the same page not working if rendered from partial
In my rails app, I have a page where up to 3 different partials are rendered depending on a dropdown selection. Every partial contains the same bootstrap accordion, with the ids and data-parent changed to differenciate them. The problem is that if I put them both on the same page, they work as they should see the code here, but if they are in separate partials, rendered on the same page, the second doesn't work and I have no idea why?

here is the index.html.erb where the partials are rendered:

```<code><div class="container-fluid" style="height: 90rem;" >
  <div class="row"><h1 class="page-header" style="color: #777777">Privacy settings<small> <br>Here is a list of the available privacy settings on different social networks. Click on a setting to see its details </small></h1><br>

  </div>

  <div class="row" style="padding-bottom: 3rem;text-align: center"> <!-- selection row -->

    <div class="col-md-3 col-md-offset-1 dropsel"> <!-- first column -->

      <select id="selectMe2" class="selectpicker" data-width="fit" title="Choose social network" >
        <option>None</option>
        <option value="facebook2">Facebook</option>
        <option value="twitter2">Twitter</option>
        <option value="linkedin2">LinkedIn</option>
        <option value="google2">Google +</option>
        <option value="pinterest2">Pinterest</option>
      </select>
    </div>

      <div class="col-md-3 dropsel" > <!-- second column -->

        <select id="selectMe3" class="selectpicker" data-width="fit" title="Choose social network">
          <option>None</option>
          <option value="facebook3">Facebook</option>
          <option value="twitter3">Twitter</option>
          <option value="linkedin3">LinkedIn</option>
          <option value="google3">Google +</option>
          <option value="pinterest3">Pinterest</option>
        </select>

      </div>

        <div class="col-md-3 dropsel" > <!-- third column -->

          <select id="selectMe4" class="selectpicker" data-width="fit" title="Choose social network">
            <option>None</option>
            <option value="facebook4">Facebook</option>
            <option value="twitter4">Twitter</option>
            <option value="linkedin4">LinkedIn</option>
            <option value="google4">Google +</option>
            <option value="pinterest4">Pinterest</option>
          </select>

        </div>
  </div>

<div class="row"> <!-- content row  -->
  <div class="col-md-3 col-md-offset-1 dropcont"> <!-- first content column -->

      <div id="facebook2" class="group2" >
        <%= render partial:"fbpartial2" %>
      </div>

      <div id="twitter2" class="group2" >
        <%= render partial:"twpartial2" %>
      </div>

      <div id="linkedin2" class="group2" >
        <%= render partial:"lkpartial" %>
      </div>

      <div id="google2" class="group2" >
        <%= render partial:"googlepartial" %>
      </div>

      <div id="pinterest2" class="group2" >
        <%= render partial:"pinpartial" %>
      </div>
    </div><!-- /first column -->

  <div class="col-md-3 dropcont"> <!-- second content column -->

      <div id="facebook3" class="group3" >
        <%= render partial:"fbpartial2" %>
      </div>

      <div id="twitter3" class="group3" >
        <%= render partial:"twpartial2" %>
      </div>

      <div id="linkedin3" class="group3" >
        <%= render partial:"lkpartial" %>
      </div>

      <div id="google3" class="group3" >
        <%= render partial:"googlepartial" %>
      </div>

      <div id="pinterest3" class="group3" >
        <%= render partial:"pinpartial" %>
      </div>
    </div><!-- /second column -->

  <div class="col-md-3 dropcont"> <!-- third content column -->

      <div id="facebook4" class="group4" >
        <%= render partial:"fbpartial" %>
      </div>

      <div id="twitter4" class="group4" >
        <%= render partial:"twpartial" %>
      </div>

      <div id="linkedin4" class="group4" >
        <%= render partial:"lkpartial" %>
      </div>

      <div id="google4" class="group4" >
        <%= render partial:"googlepartial" %>
      </div>

      <div id="pinterest4" class="group4" >
        <%= render partial:"pinpartial" %>
      </div>
    </div><!-- /third column -->

  </div>
</div>

<!-- scripts -->

<script>
    $(document).ready(function () {
        $('.group2').hide();//hide
        $('#none').show();//set default class to be shown here, or remove to hide all
                $('#selectMe2').change(function () {//on change do stuff
            $('.group2').hide();//hide all with .group2 class
            $('#'+$(this).val()).show(); //show selected option's respective element
        })
    });</script>

<script>
    $(document).ready(function () {
        $('.group3').hide();//hide
        $('#none').show();//set default class to be shown here, or remove to hide all
        $('#selectMe3').change(function () {//on change do stuff
            $('.group3').hide();//hide all with .group2 class
            $('#'+$(this).val()).show(); //show selected option's respective element
        })
    });</script>

<script>
    $(document).ready(function () {
        $('.group4').hide();//hide
        $('#none').show();//set default class to be shown here, or remove to hide all
        $('#selectMe4').change(function () {//on change do stuff
            $('.group4').hide();//hide all with .group2 class
            $('#'+$(this).val()).show(); //show selected option's respective element
        })
    });</script>
</code>```

the first partial (_fbpartial2):

```<code><div class="container-fluid">
  <div class="row">
    <div class="col-md-12" style="text-align: center; overflow-x: hidden;">

      <div class="row" style="padding-bottom: 4rem;">
        <i class="fa fa-exclamation-circle fa-4x" aria-hidden="true"></i> <br>
        <p> Warning, your profile is only 20% private!</p>
      </div>

      <div class="panel-group" id="accordion">
        <div class="panel panel-default">
          <div class="panel-heading">
            <h4 class="panel-title">
              <a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion" href="#collapseOne">
                <i class="fa fa-plus-square-o pull-right" aria-hidden="true"></i>
                Public Information
              </a>
            </h4>
          </div>

          <div id="collapseOne" class="panel-collapse collapse in">
            <div class="panel-body" style="text-align: center;">
              panel content

            </div>
          </div>
        </div>

        <div class="panel panel-default">
          <div class="panel-heading">
            <h4 class="panel-title">
              <a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion" href="#collapseTwo">
                <i class="fa fa-plus-square-o pull-right" aria-hidden="true"></i>
                Public Photos
              </a>
            </h4>
          </div>
          <div id="collapseTwo" class="panel-collapse collapse">
            <div class="panel-body">
              panel content

            </div>
          </div>
        </div>
        <div class="panel panel-default">
          <div class="panel-heading">
            <h4 class="panel-title">
              <a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion" href="#collapseThree">
                <i class="fa fa-plus-square-o pull-right" aria-hidden="true"></i>
                Public Posts
              </a>
            </h4>
          </div>
          <div id="collapseThree" class="panel-collapse collapse">
            <div class="panel-body">
              Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>
</code>```

and the second (_twpartial2, identical to the first, outside of the changed parameters I said before):

```<code><div class="container-fluid">
  <div class="row">
    <div class="col-md-12" style="text-align: center; overflow-x: hidden;">

      <div class="row" style="padding-bottom: 4rem;">
        <i class="fa fa-exclamation-circle fa-4x" aria-hidden="true"></i> <br>
        <p> Warning, your profile is only 20% private!</p>
      </div>

      <div class="panel-group" id="accordion2">
        <div class="panel panel-default">
          <div class="panel-heading">
            <h4 class="panel-title">
              <a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion2" href="#collapseOne2">
                <i class="fa fa-plus-square-o pull-right" aria-hidden="true"></i>
                Public Information
              </a>
            </h4>
          </div>

          <div id="collapseOne2" class="panel-collapse collapse in">
            <div class="panel-body" style="text-align: center;">

             panel content

            </div>
          </div>
        </div>

        <div class="panel panel-default">
          <div class="panel-heading">
            <h4 class="panel-title">
              <a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion2" href="#collapseTwo2">
                <i class="fa fa-plus-square-o pull-right" aria-hidden="true"></i>
                Public Photos
              </a>
            </h4>
          </div>
          <div id="collapseTwo2" class="panel-collapse collapse">
            <div class="panel-body">

panel content

            </div>
          </div>
        </div>
        <div class="panel panel-default">
          <div class="panel-heading">
            <h4 class="panel-title">
              <a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion2" href="#collapseThree2">
                <i class="fa fa-plus-square-o pull-right" aria-hidden="true"></i>
                Public Posts
              </a>
            </h4>
          </div>
          <div id="collapseThree2" class="panel-collapse collapse">
            <div class="panel-body">
              Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>
</code>```

you can see the javascript for accordion on the bootply example

答:
OK I think I found the problem. It has something to do with the fact that the same partials are rendered 3 times and hidden when the page is loaded. So when I try to open/close the accordion on the second column, it probably reacts on the first.

I solved it by creating 2 duplicates of every partial and naming them differently, so that every column loads a different partial. I'm sure there is a more elegant solution, but being a beginner I'm happy it works :)

Body:
In my rails app, I have a page where up to 3 different partials are rendered depending on a dropdown selection. Every partial contains the same bootstrap accordion, with the ids and data-parent changed to differenciate them. The problem is that if I put them both on the same page, they work as they should see the code here, but if they are in separate partials, rendered on the same page, the second doesn't work and I have no idea why?

here is the index.html.erb where the partials are rendered:

Privacy settings
Here is a list of the available privacy settings on different social networks. Click on a setting to see its details

      <select id="selectMe2" class="selectpicker" data-width="fit" title="Choose social network" >
        <option>None</option>
        <option value="facebook2">Facebook</option>
        <option value="twitter2">Twitter</option>
        <option value="linkedin2">LinkedIn</option>
        <option value="google2">Google +</option>
        <option value="pinterest2">Pinterest</option>
      </select>

        <select id="selectMe3" class="selectpicker" data-width="fit" title="Choose social network">
          <option>None</option>
          <option value="facebook3">Facebook</option>
          <option value="twitter3">Twitter</option>
          <option value="linkedin3">LinkedIn</option>
          <option value="google3">Google +</option>
          <option value="pinterest3">Pinterest</option>
        </select>

          <select id="selectMe4" class="selectpicker" data-width="fit" title="Choose social network">
            <option>None</option>
            <option value="facebook4">Facebook</option>
            <option value="twitter4">Twitter</option>
            <option value="linkedin4">LinkedIn</option>
            <option value="google4">Google +</option>
            <option value="pinterest4">Pinterest</option>
          </select>

        <%= render partial:"fbpartial2" %>

        <%= render partial:"twpartial2" %>

        <%= render partial:"lkpartial" %>

        <%= render partial:"googlepartial" %>

        <%= render partial:"pinpartial" %>

        <%= render partial:"fbpartial2" %>

        <%= render partial:"twpartial2" %>

        <%= render partial:"lkpartial" %>

        <%= render partial:"googlepartial" %>

        <%= render partial:"pinpartial" %>

        <%= render partial:"fbpartial" %>

        <%= render partial:"twpartial" %>

        <%= render partial:"lkpartial" %>

        <%= render partial:"googlepartial" %>

        <%= render partial:"pinpartial" %>

the first partial (_fbpartial2):

 Warning, your profile is only 20% private!

                Public Information

              panel content

                Public Photos

              panel content

                Public Posts

              Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.

and the second (_twpartial2, identical to the first, outside of the changed parameters I said before):

 Warning, your profile is only 20% private!

                Public Information

             panel content

                Public Photos

panel content

                Public Posts

              Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.

you can see the javascript for accordion on the bootply example


问:
Using Nexus as feature repository
Is there a way to add a secured Nexus repository as feature repository to Apache Karaf?

I tried to run the command:

```<code>karaf@root()> feature:repo-add http://<user>:<password>@<my-repository>
</code>```

But I get the following error:

```<code>Adding feature url http://<user>:<password>@<my-repository> Error executing command: Server returned HTTP response code: 401 for URL: http://<user>:<password>@<my-repository>
</code>```

I'm using Apache Karaf 3.0.0.

Thanks,
Mickael

答:
You can add your own Maven repository to org.ops4j.pax.url.mvn.repositories.

config:edit org.ops4j.pax.url.mvn

config:property-set org.ops4j.pax.url.mvn.repositories http://your.nexus.repo/here

config:update

Title: Using Nexus as feature repository

Body:
Is there a way to add a secured Nexus repository as feature repository to Apache Karaf?

I tried to run the command:

karaf@root()> feature:repo-add http://<user>:<password>@<my-repository>

But I get the following error:

Adding feature url http://<user>:<password>@<my-repository> Error executing command: Server returned HTTP response code: 401 for URL: http://<user>:<password>@<my-repository>

I'm using Apache Karaf 3.0.0.

Thanks,
Mickael


问:
How to change the "Inherited Values" in Property Page in Visual Studio 2012 Express
I downloaded the source for a library I want to include in a project I am working on.  In the Properties Page > Config Properties > C/C++ > Preprocessor.  Click Edit from the Preprocessor Definitions drop down menu.

The bottom half of the dialog shows "Inherited values", these are read only.  I would like to know where these values are set, so that I can edit them.

答: I think the best way to modify "Inherited values" is to go with View->Property Manager and then navigate to YourProject->|, double-click Microsoft.Cpp..user and search for settings you want to change.</p>


问:
Extract value from multidimensional array and place in comma separated string
I have an array that looks like this

```<code>Array
(
    [1] => Array
        (
            [name] => Zeze
            [city] => Denver,
            [state] => Colorado,
            [country] => United States
            [user_id] => 1
            [cars] => Array
                (
                    [140] => Array
                        (
                            [cars_name] => BMW
                        )

                    [162] => Array
                        (
                            [cars_name] => Mazda
                        )
                )
        )

    [8] => Array
        (
            [name] => Lex
            [city] => Schwelm,
            [state] => North Rhine-Westphalia,
            [country] => Germany
            [user_id] => 5
            [cars] => Array
                (
                    [140] => Array
                        (
                            [cars_name] => Mercedes
                        )

                    [162] => Array
                        (
                            [cars_name] => Audi
                        )
                )
        )
)
</code>```

I need to extract the value from user_id and put it in a comma separated string.

For the above array, I would like to get:

1,5

I'm a bit confused how to loop this array with foreach and then how would I create the string? Or is there a better way?

答:
This will be the most easier method:

echo implode(",", array_column($myArray, "user_id"));

Body:
I have an array that looks like this

Array
(
    [1] => Array
        (
            [name] => Zeze
            [city] => Denver,
            [state] => Colorado,
            [country] => United States
            [user_id] => 1
            [cars] => Array
                (
                    [140] => Array
                        (
                            [cars_name] => BMW
                        )

                    [162] => Array
                        (
                            [cars_name] => Mazda
                        )
                )
        )

    [8] => Array
        (
            [name] => Lex
            [city] => Schwelm,
            [state] => North Rhine-Westphalia,
            [country] => Germany
            [user_id] => 5
            [cars] => Array
                (
                    [140] => Array
                        (
                            [cars_name] => Mercedes
                        )

                    [162] => Array
                        (
                            [cars_name] => Audi
                        )
                )
        )
)

I need to extract the value from user_id and put it in a comma separated string.

For the above array, I would like to get:

1,5

I'm a bit confused how to loop this array with foreach and then how would I create the string? Or is there a better way?


问:
Read primitive datatype values in Kotlin
Note: Please do not downvote question as I tried searching but did not find anything. The question has already been marked duplicate.

How to read primitive datatype values in Kotlin?

We can use Scanner object of java but I want to implement using readLine function of kotlin.

How do I scan numbers e.g num1 and num2 and perform some operation like sum ?

How do it convert following code to koltin without using scanner?

```<code>val sc = Scanner(System.in)
val num1 = sc.nextInt()
val num2 = sc.nextInt()
val sum = sum(num1, num2)
</code>```

答:
Just do something like:</p>

```<code>fun main(vararg args: String) {
  val (a, b) = readLine()!!.split(' ')
  println(a.toInt() + b.toInt())
}
</code>```

Body:
Note: Please do not downvote question as I tried searching but did not find anything. The question has already been marked duplicate.

How to read primitive datatype values in Kotlin?

We can use Scanner object of java but I want to implement using readLine function of kotlin.

How do I scan numbers e.g num1 and num2 and perform some operation like sum ?

How do it convert following code to koltin without using scanner?

val sc = Scanner(System.in)
val num1 = sc.nextInt()
val num2 = sc.nextInt()
val sum = sum(num1, num2)

Body:
Just do something like:

fun main(vararg args: String) {
  val (a, b) = readLine()!!.split(' ')
  println(a.toInt() + b.toInt())
}


问:
Not reaching .then() after post
I am having troubles with my MEAN stack app, I don't know why after doing the post (used a factory for this) the .then() code is no being executed. Here is the controller:

```<code>angular.module('AcontecimientoCtrl', ['AcontecimientoService'])
  .controller('AcontecimientoController', function($scope, Acontecimiento) {
    var pls = this;
    $scope.agregarAcontecimiento = function() {
        pls.errorMsg = false;
        Acontecimiento
          .create($scope.acontecimiento)
          .then(function(data) {
            $scope.acontecimiento = {};
            console.log(data.data.success);
            console.log(data.data.message);
            if (data.data.success) {
              pls.successMsg = data.data.message;
            } else {
                pls.errorMsg = data.data.message;
            }
        })
    };
});
</code>```

this is the service:

```<code>angular.module('AcontecimientoService', [])
  .factory('Acontecimiento', function($http) {
    return {
        get : function() {
            return $http.get('/api/acontecimiento');
        },
        create : function(acontecimiento) {
            return $http.post('/api/acontecimiento', acontecimiento);
        },
        delete : function(id) {
            return $http.delete('/api/acontecimiento/' + id);
        }
    }
});
</code>```

here it is the post method:

```<code>app.post('/api/acontecimiento', function(req, res) {
         // create a todo, information comes from AJAX request from Angular
         if (req.body.campo == '' || req.body.titular == '' || req.body.fecha == '' || req.body.tipo == '') {
           res.json({success: false, message: 'Campo, titular, fecha y tipo de operacion deben especificarse'});
         } else {
           Acontecimiento.create({
             campo : req.body.campo,
             titular : req.body.titular,
             fecha : req.body.fecha,
             tipo : req.body.tipo,
             brucelosis : req.body.brucelosis,
             vacas : req.body.vacas,
             toros : req.body.toros,
             novillitos : req.body.novillitos,
             vaquillonas : req.body.vaquillonas,
             terneras : req.body.terneras,
             terneros : req.body.terneros,
           }, function(err, acontecimiento) {
           if (err)
              res.sendfile('./public/views/index.html');
           });
         }
       });
</code>```

And in case you need, this is my view:

```<code><div class="row show-hide-message" ng-show="successMsg">
  <div class="alert alert-success">Nueva operacion guardada</div>
</div>
<div class="row show-hide-message" ng-show="errorMsg">
  <div class="alert alert-danger">Campo, titular, fecha y tipo de operacion deben especificarse</div>
</div>
<div class="jumbotron text-center">
    <form ng-submit="agregarAcontecimiento()" class="form-horizontal">
      <div class="form-group">
        <label class="control-label col-sm-2" for="campo">Campo</label>
        <div class="col-sm-9">
          <select class="form-control" id="campo" ng-model="acontecimiento.campo" required />
            <option>GUARANIMINI</option>
            <option>TRES MARIAS</option>
            <option>ESPADAÑAL</option>
          </select>
        </div>
      </div>
      <div class="form-group">
        <label class="control-label col-sm-2" for="titular">Titular</label>
        <div class="col-sm-9">
          <select class="form-control" id="titular" ng-model="acontecimiento.titular" required />
            <option>RUBEN CARLOS P.</option>
            <option>VICTOR HUGO P.</option>
          </select>
        </div>
      </div>
      <div class="form-group">
        <label class="control-label col-sm-2" for="fecha">Fecha</label>
        <div class="col-sm-9">
          <input type="date" id="fecha" class="form-control" ng-model="acontecimiento.fecha" required />
        </div>
      </div>
      <div class="form-group">
        <label class="control-label col-sm-2" for="tipo">Tipo</label>
        <div class="col-sm-9">
          <select class="form-control" id="tipo" ng-model="acontecimiento.tipo" required />
            <option>VACUNA</option>
            <option>VENTA</option>
            <option>MUERTE</option>
            <option>TRANSLADO</option>
            <option>CONTAR STOCK ACTUAL</option>
          </select>
        </div>
      </div>
      <div class="form-group">
        <label class="control-label col-sm-2" for="brucelosis">Brucelosis</label>
        <div class="col-sm-9">
          <input type="number" id="brucelosis" class="form-control" ng-model="acontecimiento.brucelosis"  />
        </div>
      </div>
      <div class="form-group">
        <label class="control-label col-sm-2" for="vacas">Vacas</label>
        <div class="col-sm-9">
          <input type="number" id="vacas" class="form-control" ng-model="acontecimiento.vacas"  />
        </div>
      </div>
      <div class="form-group">
        <label class="control-label col-sm-2" for="toros">Toros</label>
        <div class="col-sm-9">
          <input type="number" id="toros" class="form-control" ng-model="acontecimiento.toros"  />
        </div>
      </div>
      <div class="form-group">
        <label class="control-label col-sm-2" for="novillitos">Novillitos</label>
        <div class="col-sm-9">
          <input type="number" id="novillitos" class="form-control" ng-model="acontecimiento.novillitos"  />
        </div>
      </div>
      <div class="form-group">
        <label class="control-label col-sm-2" for="vaquillonas">Vaquillonas</label>
        <div class="col-sm-9">
          <input type="number" id="vaquillonas" class="form-control" ng-model="acontecimiento.vaquillonas"  />
        </div>
      </div>
      <div class="form-group">
        <label class="control-label col-sm-2" for="terneras">Terneras</label>
        <div class="col-sm-9">
          <input type="number" id="terneras" class="form-control" ng-model="acontecimiento.terneras"  />
        </div>
      </div>
      <div class="form-group">
        <label class="control-label col-sm-2" for="terneros">Terneros</label>
        <div class="col-sm-9">
          <input type="number" id="terneros" class="form-control" ng-model="acontecimiento.terneros"  />
        </div>
      </div>
      <div class="pull-right">
        <button type="submit" class="btn btn-default">Aceptar</button>
      </div>
    </form>
</div>
</code>```

答:
The issue in your code is:

In client side you are not handling error and In server side you are not handling success

So, change angular controller code and add an error callback:

```<code>$scope.agregarAcontecimiento = function() {
    pls.errorMsg = false;
    Acontecimiento
        .create($scope.acontecimiento)
        .then(function(data) {
        $scope.acontecimiento = {};
        console.log(data.data.success);
        console.log(data.data.message);
        if (data.data.success) {
            pls.successMsg = data.data.message;
        } else {
            pls.errorMsg = data.data.message;
        }
    },
    function(err){
        console.log('eror')
    })
};
</code>```

In server side as @George mentioned, add successs response

```<code>app.post('/api/acontecimiento', function (req, res) {
    // create a todo, information comes from AJAX request from Angular
    if (req.body.campo == '' || req.body.titular == '' || req.body.fecha == '' || req.body.tipo == '') {
        res.json({
            success: false,
            message: 'Campo, titular, fecha y tipo de operacion deben especificarse'
        });
    } else {
        Acontecimiento.create({
            campo: req.body.campo,
            titular: req.body.titular,
            fecha: req.body.fecha,
            tipo: req.body.tipo,
            brucelosis: req.body.brucelosis,
            vacas: req.body.vacas,
            toros: req.body.toros,
            novillitos: req.body.novillitos,
            vaquillonas: req.body.vaquillonas,
            terneras: req.body.terneras,
            terneros: req.body.terneros,
        }, function (err, acontecimiento) {
            if (err) {
                res.sendfile('./public/views/index.html');
            } else {
                res.json({
                    success: true,
                    message: 'Success'
                });
            }
        });
    }
});
</code>```

Title: Not reaching .then() after post

Body:
I am having troubles with my MEAN stack app, I don't know why after doing the post (used a factory for this) the .then() code is no being executed. Here is the controller:

angular.module('AcontecimientoCtrl', ['AcontecimientoService'])
  .controller('AcontecimientoController', function($scope, Acontecimiento) {
    var pls = this;
    $scope.agregarAcontecimiento = function() {
        pls.errorMsg = false;
        Acontecimiento
          .create($scope.acontecimiento)
          .then(function(data) {
            $scope.acontecimiento = {};
            console.log(data.data.success);
            console.log(data.data.message);
            if (data.data.success) {
              pls.successMsg = data.data.message;
            } else {
                pls.errorMsg = data.data.message;
            }
        })
    };
});

this is the service:

angular.module('AcontecimientoService', [])
  .factory('Acontecimiento', function($http) {
    return {
        get : function() {
            return $http.get('/api/acontecimiento');
        },
        create : function(acontecimiento) {
            return $http.post('/api/acontecimiento', acontecimiento);
        },
        delete : function(id) {
            return $http.delete('/api/acontecimiento/' + id);
        }
    }
});

here it is the post method:

app.post('/api/acontecimiento', function(req, res) {
         // create a todo, information comes from AJAX request from Angular
         if (req.body.campo == '' || req.body.titular == '' || req.body.fecha == '' || req.body.tipo == '') {
           res.json({success: false, message: 'Campo, titular, fecha y tipo de operacion deben especificarse'});
         } else {
           Acontecimiento.create({
             campo : req.body.campo,
             titular : req.body.titular,
             fecha : req.body.fecha,
             tipo : req.body.tipo,
             brucelosis : req.body.brucelosis,
             vacas : req.body.vacas,
             toros : req.body.toros,
             novillitos : req.body.novillitos,
             vaquillonas : req.body.vaquillonas,
             terneras : req.body.terneras,
             terneros : req.body.terneros,
           }, function(err, acontecimiento) {
           if (err)
              res.sendfile('./public/views/index.html');
           });
         }
       });

And in case you need, this is my view:

Nueva operacion guardada

Campo, titular, fecha y tipo de operacion deben especificarse

    <form ng-submit="agregarAcontecimiento()" class="form-horizontal">

        Campo

          <select class="form-control" id="campo" ng-model="acontecimiento.campo" required />
            <option>GUARANIMINI</option>
            <option>TRES MARIAS</option>
            <option>ESPADAÑAL</option>
          </select>

        Titular

          <select class="form-control" id="titular" ng-model="acontecimiento.titular" required />
            <option>RUBEN CARLOS P.</option>
            <option>VICTOR HUGO P.</option>
          </select>

        Fecha

          <input type="date" id="fecha" class="form-control" ng-model="acontecimiento.fecha" required />

        Tipo

          <select class="form-control" id="tipo" ng-model="acontecimiento.tipo" required />
            <option>VACUNA</option>
            <option>VENTA</option>
            <option>MUERTE</option>
            <option>TRANSLADO</option>
            <option>CONTAR STOCK ACTUAL</option>
          </select>

        Brucelosis

          <input type="number" id="brucelosis" class="form-control" ng-model="acontecimiento.brucelosis"  />

        Vacas

          <input type="number" id="vacas" class="form-control" ng-model="acontecimiento.vacas"  />

        Toros

          <input type="number" id="toros" class="form-control" ng-model="acontecimiento.toros"  />

        Novillitos

          <input type="number" id="novillitos" class="form-control" ng-model="acontecimiento.novillitos"  />

        Vaquillonas

          <input type="number" id="vaquillonas" class="form-control" ng-model="acontecimiento.vaquillonas"  />

        Terneras

          <input type="number" id="terneras" class="form-control" ng-model="acontecimiento.terneras"  />

        Terneros

          <input type="number" id="terneros" class="form-control" ng-model="acontecimiento.terneros"  />

        <button type="submit" class="btn btn-default">Aceptar</button>

    </form>

Body:
The issue in your code is:

In client side you are not handling error and In server side you are not handling success

So, change angular controller code and add an error callback:

$scope.agregarAcontecimiento = function() {
    pls.errorMsg = false;
    Acontecimiento
        .create($scope.acontecimiento)
        .then(function(data) {
        $scope.acontecimiento = {};
        console.log(data.data.success);
        console.log(data.data.message);
        if (data.data.success) {
            pls.successMsg = data.data.message;
        } else {
            pls.errorMsg = data.data.message;
        }
    },
    function(err){
        console.log('eror')
    })
};

In server side as @George mentioned, add successs response

app.post('/api/acontecimiento', function (req, res) {
    // create a todo, information comes from AJAX request from Angular
    if (req.body.campo == '' || req.body.titular == '' || req.body.fecha == '' || req.body.tipo == '') {
        res.json({
            success: false,
            message: 'Campo, titular, fecha y tipo de operacion deben especificarse'
        });
    } else {
        Acontecimiento.create({
            campo: req.body.campo,
            titular: req.body.titular,
            fecha: req.body.fecha,
            tipo: req.body.tipo,
            brucelosis: req.body.brucelosis,
            vacas: req.body.vacas,
            toros: req.body.toros,
            novillitos: req.body.novillitos,
            vaquillonas: req.body.vaquillonas,
            terneras: req.body.terneras,
            terneros: req.body.terneros,
        }, function (err, acontecimiento) {
            if (err) {
                res.sendfile('./public/views/index.html');
            } else {
                res.json({
                    success: true,
                    message: 'Success'
                });
            }
        });
    }
});


问:
Sniff ICMP packets (e.g. ping echo requests) using Python TAP device
I'm implementing a simple userspace networking stack for self-learning purposes. I'm writing it in Python, running it in Linux (Ubuntu 16.04.2 LTS). I'm using a Python TAP device to receive Layer 2 frames (e.g. Ethernet). From there, I extract the headers and process frames according to header fields.

Problem: The TAP device receives several types of frames, however not ICMP packets (e.g. ICMP echo requests). I would like it to receive ICMP echo requests too.

Details: To test the behavior of the stack I'm running ping 10.0.0.4 on the same machine. My Ubuntu environment is running on a VM, and so I've also tried running ping 10.0.0.4 from the host machine (after adding the appropriate entry to the routing table). I always get ICMP echo replies, even though the TAP device sees none of the echo requests:

```<code>PING 10.0.0.4 (10.0.0.4): 56 data bytes
64 bytes from 10.0.0.4: icmp_seq=0 ttl=64 time=0.451 ms
64 bytes from 10.0.0.4: icmp_seq=1 ttl=64 time=0.530 ms
</code>```

Here's the packet handling code (simplified for the purposes of this question):

```<code>from pytun import TunTapDevice, IFF_TAP, IFF_NO_PI

tap_dev = TunTapDevice(flags = (IFF_TAP | IFF_NO_PI))
tap_dev.persist(True)
tap_dev.addr = '10.0.0.4'
tap_dev.netmask = '255.255.255.0'
tap_dev.up()

while (1):
    frame = tap_dev.read(1500)
    # extract the Ethernet header from the raw frame
    # (assume this is working correctly)
    eth_frame_hdr = unpack_eth_hdr(frame)

    # check if it is an IPv4 packet
    if eth_frame_hdr.type == 0x0800:
        ipv4_hdr = unpack_ipv4_hdr(frame)

        # check if an icmp packet
        if ipv4_hdr.proto == 0x01:
            process_icmp(frame)
</code>```

My diagnosis: I think what's happening is that the Linux kernel is handling the ICMP echo requests directly, and either (1) doesn't even put a packet 'on the wire' or (2) doesn't pass the ICMP packets to userspace.

(Failed) resolution attempts: I've tried several things to get ICMP packets on the TAP device, none of them resulted in the TAP device receiving the ICMP echo requests:

Ignoring ICMP echo handling:

echo 1 | sudo tee /proc/sys/net/ipv4/icmp_echo_ignore_all

Add an iptables rule to drop ICMP echo requests:

sudo iptables -I INPUT -p icmp --icmp-type echo-request -j DROP

Add an iptables rule which 'jumps' to the QUEUE target (idea was to pass ICMP packets to userspace):

sudo iptables -I INPUT -p icmp --icmp-type echo-request -j QUEUE

Use a raw socket as a special case to handle ICMP packets:

from socket import *
icmp_listener_sock = socket(AF_PACKET, SOCK_RAW, IPPROTO_ICMP)
icmp_listener_sock.bind((tap_dev.name, IPPROTO_ICMP))
(icmp_ipv4_dgram, snd_addr) = icmp_listener_sock.recvfrom(2048)
process_icmp(icmp_ipv4_dgram)

Can you point me to the right way to have the Python TAP device receive the ICMP echo requests?

答:
I reviewed solution attempt 4, and made it work by changing AF_PACKET to AF_INET when creating the raw socket and binding the socket to the address (<ip-address>, 0).

```<code>from socket import *
icmp_listener_sock = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP)
icmp_listener_sock.bind((tap_dev.ip_addr, 0))
(icmp_ipv4_dgram, snd_addr) = icmp_listener_sock.recvfrom(2048)
process_icmp(icmp_ipv4_dgram)
</code>```

Note that this is a workaround, it doesn't answer the question on how to get ICMP packets with a Python TAP device.

EDIT (and definitive answer):

I've tried a different approach, which is not listed in the original post. Instead of using the python-pytun package, I've directly opened Linux's TUN/TAP device, using Python-like open() and ioctl() system calls.

It works very well, and it doesn't require the raw socket workaround to handle ICMP packets.

In hindsight, this is the approach I should have followed to begin with...

Here's a minimal example of how to do it:

```<code>import os
import struct
from fcntl import ioctl

# ioctl constants
TUNSETIFF = 0x400454ca
TUNSETPERSIST = 0x400454cb
IFF_TUN = 0x0001
IFF_TAP = 0x0002
IFF_NO_PI = 0x1000
SIOCGIFHWADDR = 0x00008927

try:
    # tap device name
    tap_devname = 'tap0'

    # open tap device
    tap_fd = os.open('/dev/net/tun', os.O_RDWR)

    # set tap device flags via ioctl():
    #
    # IFF_TUN   : tun device (no Ethernet headers)
    # IFF_TAP   : tap device
    # IFF_NO_PI : do not provide packet information, otherwise we end
    #             up with unnecessary packet information prepended to
    #             the Ethernet frame
    ifr = struct.pack("16sH", ("%s" % (tap_devname)), IFF_TAP | IFF_NO_PI)
    ioctl(tap_fd, TUNSETIFF, ifr)

    # set device to persistent (if needed be, if not, comment the next line)
    ioctl(tap_fd, TUNSETPERSIST, 1)

    print("[INFO] tap device w/ name %s allocated" % (ifr[:16].strip("\x00")))

except Exception as e:
    print("[ERROR] cannot setup tap device (%s)" % (e.message))
</code>```

Note: after the above, you should do 2 things to make the TAP device operational:

Bring the TAP device up. E.g. in Linux, this could be accomplished with the ip command, as shown below (assumes TAP device name is tap0):

$ ip link set dev tap0 up

Probably you'll want to associate an IP address with your TAP device. You should add a route table entry so that packets directed to that address are forwarded over the tap0 interface (assumes IP address to associate is 10.0.0.4, and a 255.255.255.0 netmask:

$ ip route add dev tap0 10.0.0.4/24

You can do the above in Python too, using Python's subprocess package (see example in my Github).

Body:
I'm implementing a simple userspace networking stack for self-learning purposes. I'm writing it in Python, running it in Linux (Ubuntu 16.04.2 LTS). I'm using a Python TAP device to receive Layer 2 frames (e.g. Ethernet). From there, I extract the headers and process frames according to header fields.

Problem: The TAP device receives several types of frames, however not ICMP packets (e.g. ICMP echo requests). I would like it to receive ICMP echo requests too.

Details: To test the behavior of the stack I'm running ping 10.0.0.4 on the same machine. My Ubuntu environment is running on a VM, and so I've also tried running ping 10.0.0.4 from the host machine (after adding the appropriate entry to the routing table). I always get ICMP echo replies, even though the TAP device sees none of the echo requests:

PING 10.0.0.4 (10.0.0.4): 56 data bytes
64 bytes from 10.0.0.4: icmp_seq=0 ttl=64 time=0.451 ms
64 bytes from 10.0.0.4: icmp_seq=1 ttl=64 time=0.530 ms

Here's the packet handling code (simplified for the purposes of this question):

from pytun import TunTapDevice, IFF_TAP, IFF_NO_PI

tap_dev = TunTapDevice(flags = (IFF_TAP | IFF_NO_PI))
tap_dev.persist(True)
tap_dev.addr = '10.0.0.4'
tap_dev.netmask = '255.255.255.0'
tap_dev.up()

while (1):
    frame = tap_dev.read(1500)
    # extract the Ethernet header from the raw frame
    # (assume this is working correctly)
    eth_frame_hdr = unpack_eth_hdr(frame)

    # check if it is an IPv4 packet
    if eth_frame_hdr.type == 0x0800:
        ipv4_hdr = unpack_ipv4_hdr(frame)

        # check if an icmp packet
        if ipv4_hdr.proto == 0x01:
            process_icmp(frame)

My diagnosis: I think what's happening is that the Linux kernel is handling the ICMP echo requests directly, and either (1) doesn't even put a packet 'on the wire' or (2) doesn't pass the ICMP packets to userspace.

(Failed) resolution attempts: I've tried several things to get ICMP packets on the TAP device, none of them resulted in the TAP device receiving the ICMP echo requests:

Ignoring ICMP echo handling:

echo 1 | sudo tee /proc/sys/net/ipv4/icmp_echo_ignore_all

Add an iptables rule to drop ICMP echo requests:

sudo iptables -I INPUT -p icmp --icmp-type echo-request -j DROP

Add an iptables rule which 'jumps' to the QUEUE target (idea was to pass ICMP packets to userspace):

sudo iptables -I INPUT -p icmp --icmp-type echo-request -j QUEUE

Use a raw socket as a special case to handle ICMP packets:

from socket import *
icmp_listener_sock = socket(AF_PACKET, SOCK_RAW, IPPROTO_ICMP)
icmp_listener_sock.bind((tap_dev.name, IPPROTO_ICMP))
(icmp_ipv4_dgram, snd_addr) = icmp_listener_sock.recvfrom(2048)
process_icmp(icmp_ipv4_dgram)

Can you point me to the right way to have the Python TAP device receive the ICMP echo requests?

Body:
I reviewed solution attempt 4, and made it work by changing AF_PACKET to AF_INET when creating the raw socket and binding the socket to the address (<ip-address>, 0).

from socket import *
icmp_listener_sock = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP)
icmp_listener_sock.bind((tap_dev.ip_addr, 0))
(icmp_ipv4_dgram, snd_addr) = icmp_listener_sock.recvfrom(2048)
process_icmp(icmp_ipv4_dgram)

Note that this is a workaround, it doesn't answer the question on how to get ICMP packets with a Python TAP device.

EDIT (and definitive answer):

I've tried a different approach, which is not listed in the original post. Instead of using the python-pytun package, I've directly opened Linux's TUN/TAP device, using Python-like open() and ioctl() system calls.

It works very well, and it doesn't require the raw socket workaround to handle ICMP packets.

In hindsight, this is the approach I should have followed to begin with...

Here's a minimal example of how to do it:

import os
import struct
from fcntl import ioctl

# ioctl constants
TUNSETIFF = 0x400454ca
TUNSETPERSIST = 0x400454cb
IFF_TUN = 0x0001
IFF_TAP = 0x0002
IFF_NO_PI = 0x1000
SIOCGIFHWADDR = 0x00008927

try:
    # tap device name
    tap_devname = 'tap0'

    # open tap device
    tap_fd = os.open('/dev/net/tun', os.O_RDWR)

    # set tap device flags via ioctl():
    #
    # IFF_TUN   : tun device (no Ethernet headers)
    # IFF_TAP   : tap device
    # IFF_NO_PI : do not provide packet information, otherwise we end
    #             up with unnecessary packet information prepended to
    #             the Ethernet frame
    ifr = struct.pack("16sH", ("%s" % (tap_devname)), IFF_TAP | IFF_NO_PI)
    ioctl(tap_fd, TUNSETIFF, ifr)

    # set device to persistent (if needed be, if not, comment the next line)
    ioctl(tap_fd, TUNSETPERSIST, 1)

    print("[INFO] tap device w/ name %s allocated" % (ifr[:16].strip("\x00")))

except Exception as e:
    print("[ERROR] cannot setup tap device (%s)" % (e.message))

Note: after the above, you should do 2 things to make the TAP device operational:

Bring the TAP device up. E.g. in Linux, this could be accomplished with the ip command, as shown below (assumes TAP device name is tap0):

$ ip link set dev tap0 up

Probably you'll want to associate an IP address with your TAP device. You should add a route table entry so that packets directed to that address are forwarded over the tap0 interface (assumes IP address to associate is 10.0.0.4, and a 255.255.255.0 netmask:

$ ip route add dev tap0 10.0.0.4/24

You can do the above in Python too, using Python's subprocess package (see example in my Github).


问:
How to build library with WPF forms
Is it possible to build a Class Library dll which also includes WPF forms?
When I try to build one I get following errors:

Error 1 Library project file cannot specify ApplicationDefinition element.

  Error 2 The project file contains a property value that is not valid.

If I set my project as Windows Application it compiles & runs tho. Is there a way to get arround this? I'm using VS2010 & C# .NET 4.0 if that might be of any interest to you guys.

Thanks

答: Choose WPF Custom Control Library or WPF User Control Library when creating/adding new project to your solution.

Title: How to build library with WPF forms


问:
Number of Columns a DataRowView has?
I have a method SelectedRow() that grabs the content of a selected DataGrid row

```<code>private System.Data.DataRowView SelectedRow()
{
    System.Data.DataRowView row = (System.Data.DataRowView)dgBrokerages.SelectedItems[0];
    return row;
}
</code>```

and would like to know how I can obtain an int containing the number of Columns that row contains.

```<code>private int NumColumns()
{
    System.Data.DataRowView row = SelectedRow();
    return row.Length; // <- Something like that
}
</code>```

I'm basically looking for if there is a row.Length or row.Size?

Thanks,
iato

答:
Try this:</p>

```<code>private int NumColumns()
{
    System.Data.DataRowView row = SelectedRow();
    return row.Row.Table.Columns.Count;
}
</code>```

Title: Number of Columns a DataRowView has?

Body:
I have a method SelectedRow() that grabs the content of a selected DataGrid row

private System.Data.DataRowView SelectedRow()
{
    System.Data.DataRowView row = (System.Data.DataRowView)dgBrokerages.SelectedItems[0];
    return row;
}

and would like to know how I can obtain an int containing the number of Columns that row contains.

private int NumColumns()
{
    System.Data.DataRowView row = SelectedRow();
    return row.Length; // <- Something like that
}

I'm basically looking for if there is a row.Length or row.Size?

Thanks,
iato

Body:
Try this:

private int NumColumns()
{
    System.Data.DataRowView row = SelectedRow();
    return row.Row.Table.Columns.Count;
}


问:
Excel VBA - Unable to change year in date format in TextBox in Userform
I have a userform with two TextBox fields for dates. When I fill in the textboxes and press "tab" or click on the other box, the field will first fill in a cell on a worksheet and then format the date in the textbox (This allows for date entry in different formats such as 1/1/17, no matter what it should return as mmm dd, yyyy).

Here's my issue. Everything works absolutely perfectly, but the year is always stuck on 2017. I tried entering the date in all formats, the month and date change accordingly, but the year remains on 2017.

Here is the code below:

```<code>Private Sub Button_OK_Click()

Sheets("Inputs").Range("C18").Value = Format(TextBox_StartDate.Value, "mmm dd, yyyy")
TextBox_StartDate.Value = Format(Sheets("Inputs").Range("C18").Text, "mmm dd, yyyy")
Sheets("Inputs").Range("C19").Value = Format(TextBox_EndDate.Value, "mmm dd, yyyy")
TextBox_EndDate.Value = Format(Sheets("Inputs").Range("C19").Text, "mmm dd, yyyy")
If TextBox_StartDate.Value = "" Or TextBox_EndDate.Value = "" Then
    MsgBox ("Start and End Dates must be filled in to continue.")
ElseIf Sheets("Inputs").Range("C18").Value > Sheets("Inputs").Range("C19").Value Then
    MsgBox ("End Date must be after Start Date.")
ElseIf Not (IsNumeric(Sheets("Inputs").Range("C18").Value) And IsNumeric(Sheets("Inputs").Range("C18").Value)) Then
    MsgBox ("Date fields must be filled in properly.")
Else
    Continue = True
    Unload Me
End If
End Sub

Private Sub TextBox_StartDate_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
If KeyCode = 9 Then
    Sheets("Inputs").Range("C18").Value = Format(TextBox_StartDate.Value, "mmm dd, yyyy")
     TextBox_StartDate.Value = Format(Sheets("Inputs").Range("C18").Text, "mmm dd, yyyy")
    Sheets("Inputs").Range("C19").Value = Format(TextBox_EndDate.Value, "mmm dd, yyyy")
     TextBox_EndDate.Value = Format(Sheets("Inputs").Range("C19").Text, "mmm dd, yyyy")
End If
End Sub
</code>```

Any help would be much appreciated!

答:
I figured out the problem. Cells C18 and C19 were formatted as dd-mmm. In order for the code to work properly, the year value must be included in the format. Changing to format to dd-mmm-yy or mmm dd, yyyy in cells C18 and C19 fixed the problem for me.

Thanks for the help!

Body:
I have a userform with two TextBox fields for dates. When I fill in the textboxes and press "tab" or click on the other box, the field will first fill in a cell on a worksheet and then format the date in the textbox (This allows for date entry in different formats such as 1/1/17, no matter what it should return as mmm dd, yyyy).

Here's my issue. Everything works absolutely perfectly, but the year is always stuck on 2017. I tried entering the date in all formats, the month and date change accordingly, but the year remains on 2017.

Here is the code below:

Private Sub Button_OK_Click()

Sheets("Inputs").Range("C18").Value = Format(TextBox_StartDate.Value, "mmm dd, yyyy")
TextBox_StartDate.Value = Format(Sheets("Inputs").Range("C18").Text, "mmm dd, yyyy")
Sheets("Inputs").Range("C19").Value = Format(TextBox_EndDate.Value, "mmm dd, yyyy")
TextBox_EndDate.Value = Format(Sheets("Inputs").Range("C19").Text, "mmm dd, yyyy")
If TextBox_StartDate.Value = "" Or TextBox_EndDate.Value = "" Then
    MsgBox ("Start and End Dates must be filled in to continue.")
ElseIf Sheets("Inputs").Range("C18").Value > Sheets("Inputs").Range("C19").Value Then
    MsgBox ("End Date must be after Start Date.")
ElseIf Not (IsNumeric(Sheets("Inputs").Range("C18").Value) And IsNumeric(Sheets("Inputs").Range("C18").Value)) Then
    MsgBox ("Date fields must be filled in properly.")
Else
    Continue = True
    Unload Me
End If
End Sub

Private Sub TextBox_StartDate_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
If KeyCode = 9 Then
    Sheets("Inputs").Range("C18").Value = Format(TextBox_StartDate.Value, "mmm dd, yyyy")
     TextBox_StartDate.Value = Format(Sheets("Inputs").Range("C18").Text, "mmm dd, yyyy")
    Sheets("Inputs").Range("C19").Value = Format(TextBox_EndDate.Value, "mmm dd, yyyy")
     TextBox_EndDate.Value = Format(Sheets("Inputs").Range("C19").Text, "mmm dd, yyyy")
End If
End Sub

Any help would be much appreciated!


问:
When using JSQMessagesViewController as detailView in UISplitviewCOntroller, KeyBoardToolBar needs to appear in DetailViewController only
When using JSQMessagesViewController as detailView in UISplitViewController, KeyBoardToolBar needs to appear in DetailViewController only

答:
late answer...

if u want to reduce the inputToolbar you need to create a subclass of JSQMessagesToolbarContentView and provide your own view for the tool bar's content view.

below i am giving the sample example, create a subcalss of JSQMessagesToolbarContentView name it as JSQMessagesToolbarContentView_custom in the subcalss add below code,

```<code>#import "JSQMessagesToolbarContentView.h"

@interface JSQMessagesToolbarContentView_custom : JSQMessagesToolbarContentView
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *holderViewLeadingConstraint;
@end
</code>```

and in JSQMessagesToolbarContentView_custom.m file,

```<code>#import "UIView+JSQMessages.h"
#import "JSQMessagesToolbarContentView_custom.h"

@implementation JSQMessagesToolbarContentView_custom

+ (UINib *)nib
{
      return [UINib nibWithNibName:NSStringFromClass([JSQMessagesToolbarContentView_custom class])
                      bundle:[NSBundle bundleForClass:[JSQMessagesToolbarContentView_custom class]]];
}

#pragma mark - Initialization

- (void)awakeFromNib
{
   [super awakeFromNib];
   [self setTranslatesAutoresizingMaskIntoConstraints:NO];
   self.backgroundColor = [UIColor clearColor];
}

//below method will place the contentview to desired position
- (void)layoutSubviews
{
   [super layoutSubviews];
   self.holderViewLeadingConstraint.constant = 320;
}

#pragma mark - Setters

- (void)setBackgroundColor:(UIColor *)backgroundColor
{
   [super setBackgroundColor:backgroundColor];
   self.leftBarButtonContainerView.backgroundColor = backgroundColor;
   self.rightBarButtonContainerView.backgroundColor = backgroundColor;
}

- (void)setLeftBarButtonItem:(UIButton *)leftBarButtonItem
{
   [super setLeftBarButtonItem:leftBarButtonItem];
}

- (void)setLeftBarButtonItemWidth:(CGFloat)leftBarButtonItemWidth
{
   // self.leftBarButtonContainerViewWidthConstraint.constant = leftBarButtonItemWidth;
   [self setNeedsUpdateConstraints];
}

- (void)setRightBarButtonItem:(UIButton *)rightBarButtonItem
{
   [super setRightBarButtonItem:rightBarButtonItem];
}

- (void)setRightBarButtonItemWidth:(CGFloat)rightBarButtonItemWidth
{
   //  self.rightBarButtonContainerViewWidthConstraint.constant = rightBarButtonItemWidth;
   [self setNeedsUpdateConstraints];
}

- (void)setRightContentPadding:(CGFloat)rightContentPadding
{
   // self.rightHorizontalSpacingConstraint.constant = rightContentPadding;
  [self setNeedsUpdateConstraints];
}

- (void)setLeftContentPadding:(CGFloat)leftContentPadding
{
   //  self.leftHorizontalSpacingConstraint.constant = leftContentPadding;
   [self setNeedsUpdateConstraints];
}

#pragma mark - UIView overrides

- (void)setNeedsDisplay
{
    [super setNeedsDisplay];
    [self.textView setNeedsDisplay];
}

//return the custom view that we are going to create next
- (JSQMessagesToolbarContentView_custom *)loadToolbarContentView
{
   NSArray *nibViews = [[NSBundle bundleForClass:[JSQMessagesToolbarContentView_custom class]] loadNibNamed:NSStringFromClass([JSQMessagesToolbarContentView_custom class])  owner:nil  options:nil];
  return nibViews.firstObject;
}
</code>```

after this you need to create add new .xib file name it as JSQMessagesToolbarContentView_custom.xib this file contains our small content view for the inputToolbar and more importantly set the out let connections as doing the demo example and aslo set the view class name to JSQMessagesToolbarContentView_custom. hear i can only add image of the custom view.

now create a outlet for leading constraint to reduce the size of the content view as give below,

and add the constraints  outlet's as given in the demo. so if u add some constrians without modifying the base class it will give error or runtime error so edit the base class also

now go to JSQMessagesToolbarContentView.h and add the blow properties form JSQMessagesToolbarContentView.m just cut and past and make it public.

```<code>@interface JSQMessagesToolbarContentView : UIView

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *leftBarButtonContainerViewWidthConstraint;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *rightBarButtonContainerViewWidthConstraint;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *leftHorizontalSpacingConstraint;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *rightHorizontalSpacingConstraint;

//...rest of the code
</code>```

now in the JSQMessagesInputToolbar.m file, in order to make the tool bar transperent for half of the splitview,

```<code>- (void)awakeFromNib
{
    [super awakeFromNib];
     //...rest of the code
    [self setBackgroundImage:[UIImage new]//imageNamed:@"topbar"]
              forToolbarPosition:UIToolbarPositionAny
                      barMetrics:UIBarMetricsDefault];
    [self setShadowImage:[UIImage new] forToolbarPosition:UIBarPositionAny];
    [self setBackgroundColor:[UIColor clearColor]];

}
</code>```

thats it now run the project, and change the leading constraints constant you see below output,

Body:
late answer...

if u want to reduce the inputToolbar you need to create a subclass of JSQMessagesToolbarContentView and provide your own view for the tool bar's content view.

below i am giving the sample example, create a subcalss of JSQMessagesToolbarContentView name it as JSQMessagesToolbarContentView_custom in the subcalss add below code,

#import "JSQMessagesToolbarContentView.h"

@interface JSQMessagesToolbarContentView_custom : JSQMessagesToolbarContentView
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *holderViewLeadingConstraint;
@end

and in JSQMessagesToolbarContentView_custom.m file,

#import "UIView+JSQMessages.h"
#import "JSQMessagesToolbarContentView_custom.h"

@implementation JSQMessagesToolbarContentView_custom

+ (UINib *)nib
{
      return [UINib nibWithNibName:NSStringFromClass([JSQMessagesToolbarContentView_custom class])
                      bundle:[NSBundle bundleForClass:[JSQMessagesToolbarContentView_custom class]]];
}

#pragma mark - Initialization

- (void)awakeFromNib
{
   [super awakeFromNib];
   [self setTranslatesAutoresizingMaskIntoConstraints:NO];
   self.backgroundColor = [UIColor clearColor];
}

//below method will place the contentview to desired position
- (void)layoutSubviews
{
   [super layoutSubviews];
   self.holderViewLeadingConstraint.constant = 320;
}

#pragma mark - Setters

- (void)setBackgroundColor:(UIColor *)backgroundColor
{
   [super setBackgroundColor:backgroundColor];
   self.leftBarButtonContainerView.backgroundColor = backgroundColor;
   self.rightBarButtonContainerView.backgroundColor = backgroundColor;
}

- (void)setLeftBarButtonItem:(UIButton *)leftBarButtonItem
{
   [super setLeftBarButtonItem:leftBarButtonItem];
}

- (void)setLeftBarButtonItemWidth:(CGFloat)leftBarButtonItemWidth
{
   // self.leftBarButtonContainerViewWidthConstraint.constant = leftBarButtonItemWidth;
   [self setNeedsUpdateConstraints];
}

- (void)setRightBarButtonItem:(UIButton *)rightBarButtonItem
{
   [super setRightBarButtonItem:rightBarButtonItem];
}

- (void)setRightBarButtonItemWidth:(CGFloat)rightBarButtonItemWidth
{
   //  self.rightBarButtonContainerViewWidthConstraint.constant = rightBarButtonItemWidth;
   [self setNeedsUpdateConstraints];
}

- (void)setRightContentPadding:(CGFloat)rightContentPadding
{
   // self.rightHorizontalSpacingConstraint.constant = rightContentPadding;
  [self setNeedsUpdateConstraints];
}

- (void)setLeftContentPadding:(CGFloat)leftContentPadding
{
   //  self.leftHorizontalSpacingConstraint.constant = leftContentPadding;
   [self setNeedsUpdateConstraints];
}

#pragma mark - UIView overrides

- (void)setNeedsDisplay
{
    [super setNeedsDisplay];
    [self.textView setNeedsDisplay];
}

//return the custom view that we are going to create next
- (JSQMessagesToolbarContentView_custom *)loadToolbarContentView
{
   NSArray *nibViews = [[NSBundle bundleForClass:[JSQMessagesToolbarContentView_custom class]] loadNibNamed:NSStringFromClass([JSQMessagesToolbarContentView_custom class])  owner:nil  options:nil];
  return nibViews.firstObject;
}

after this you need to create add new .xib file name it as JSQMessagesToolbarContentView_custom.xib this file contains our small content view for the inputToolbar and more importantly set the out let connections as doing the demo example and aslo set the view class name to JSQMessagesToolbarContentView_custom. hear i can only add image of the custom view.

now create a outlet for leading constraint to reduce the size of the content view as give below,

and add the constraints  outlet's as given in the demo. so if u add some constrians without modifying the base class it will give error or runtime error so edit the base class also

now go to JSQMessagesToolbarContentView.h and add the blow properties form JSQMessagesToolbarContentView.m just cut and past and make it public.

@interface JSQMessagesToolbarContentView : UIView

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *leftBarButtonContainerViewWidthConstraint;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *rightBarButtonContainerViewWidthConstraint;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *leftHorizontalSpacingConstraint;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *rightHorizontalSpacingConstraint;

//...rest of the code

now in the JSQMessagesInputToolbar.m file, in order to make the tool bar transperent for half of the splitview,

- (void)awakeFromNib
{
    [super awakeFromNib];
     //...rest of the code
    [self setBackgroundImage:[UIImage new]//imageNamed:@"topbar"]
              forToolbarPosition:UIToolbarPositionAny
                      barMetrics:UIBarMetricsDefault];
    [self setShadowImage:[UIImage new] forToolbarPosition:UIBarPositionAny];
    [self setBackgroundColor:[UIColor clearColor]];

}

thats it now run the project, and change the leading constraints constant you see below output,