问:
Why is the structuring element asymmetric in OpenCV?

Why is the structuring element asymmetric in OpenCV?

cv2.getStructuringElement(cv2.MORPH_ELLIPSE, ksize=(4,4))
```

<p>returns</p>

<pre class="lang-py prettyprint-override"><code>array([[0, 0, 1, 0],
       [1, 1, 1, 1],
       [1, 1, 1, 1],
       [1, 1, 1, 1]], dtype=uint8)
</code>```

Why isn't it

array([[0, 1, 1, 0],
       [1, 1, 1, 1],
       [1, 1, 1, 1],
       [0, 1, 1, 0]], dtype=uint8)
```

<p>instead?</p>

<p>Odd-sized structuring elements are also asymmetric with respect to 90-degree rotations:</p>

<pre class="lang-py prettyprint-override"><code>array([[0, 0, 1, 0, 0],
       [1, 1, 1, 1, 1],
       [1, 1, 1, 1, 1],
       [1, 1, 1, 1, 1],
       [0, 0, 1, 0, 0]], dtype=uint8)
</code>```

What's the purpose of that?

答:
There's no purpose for it other than it's one of many possible interpolations for such a shape. In the case of the ellipse with size 5, if it were full it would just be the same as the MORPH_RECT and if the same two were removed from the sides as from the top it would be a diamond. Either way, the way it's actually implemented in the source code is what you would expect---it creates a circle via the distance function and takes near integers to get the binary pixels. Search that file for cv::getStructuringElement and you'll find the implementation, it's nothing too fancy.

If you think an update to this function should be made, then open up a PR on GitHub with the implemented version, or an issue to discuss it first. I think a successful contribution would be easy here and I'd venture that the case for symmetry is strong. One would expect the result of a symmetric image being processed with an elliptical kernel wouldn't depend on orientation of the image.

Body:
Why is the structuring element asymmetric in OpenCV?

cv2.getStructuringElement(cv2.MORPH_ELLIPSE, ksize=(4,4))

returns

array([[0, 0, 1, 0],
       [1, 1, 1, 1],
       [1, 1, 1, 1],
       [1, 1, 1, 1]], dtype=uint8)

Why isn't it

array([[0, 1, 1, 0],
       [1, 1, 1, 1],
       [1, 1, 1, 1],
       [0, 1, 1, 0]], dtype=uint8)

instead?

Odd-sized structuring elements are also asymmetric with respect to 90-degree rotations:

array([[0, 0, 1, 0, 0],
       [1, 1, 1, 1, 1],
       [1, 1, 1, 1, 1],
       [1, 1, 1, 1, 1],
       [0, 0, 1, 0, 0]], dtype=uint8)

What's the purpose of that?


来源: stackexchange

问:
Adding google place API to a google sheet
I have a form designed with google sheets. Within that form there are fields for country and city. I need these fields to be validated somehow so that when the user types in these cells, autocomplete suggestions appear. This is important for this document as we will be using these fields for data analysis so it is vital that no city is spelt in two different ways (e.g. Paris and PAR)...

Is there any way of linking to google places API to get this working.

If, for example, country is listed in cell A3 and city in B3, ideally the user would enter the country and then the cities suggested in the autocomplete for cell B3 would be filtered to just those within that specified country.

Thanks

答:
Google Forms do not support auto-complete and cannot be made to even with Apps Script.

But you're not without options. Your easiest workaround is to use a Dropdown form item and populate it with your list of countries and cities.

Your other option is to use the Short Answer form item and couple it with a regex validation keyed only to valid string names for each country or city.

ContentLicense: CC BY-SA 3.0


问:
How to display text in JFrame using Netbeans? How to clear text in a JFrame?
How can I display text in JFrame using Netbeans? And how to clear text in JFrame?

答:
you can use this

```<code>@Override
public void paintComponents(Graphics g) {
    super.paintComponents(g);
    g.drawString("Hello", 0, 0);
}
</code>```

or use jTextField

```<code> jTextField1.setText("Hello");
</code>```

Body:
you can use this

@Override
public void paintComponents(Graphics g) {
    super.paintComponents(g);
    g.drawString("Hello", 0, 0);
}

or use jTextField

 jTextField1.setText("Hello");

ContentLicense: CC BY-SA 2.5


问:
Gem dependencies incompatibality during upgrade of rails 4.2.10 to rails 5.0.0
I am in a middle of a process of upgrading our rails 4 app.
Following the rails upgrade guide, I have updated current rails version in a gemfile replacing 4.2.10 with 5.0.0.

But after running bundle update rails, I am getting many incompatibility issues even after running 4.2.10 (with rails 4.2.10) which should update all gems to the latest version.

Following are the compatibility errors I am getting after running bundle update rails with rails 5.0.0 in a gemfile:

```<code>Bundler could not find compatible versions for gem "actionpack":
  In Gemfile:
    active_link_to was resolved to 1.0.3, which depends on
      actionpack

    active_model_serializers was resolved to 0.10.2, which depends on
      actionpack (< 6, >= 4.1)

    inherited_resources was resolved to 1.6.0, which depends on
      actionpack (< 5, >= 3.2)

    inherited_resources was resolved to 1.6.0, which depends on
      actionpack (< 5, >= 3.2)

    kaminari was resolved to 0.17.0, which depends on
      actionpack (>= 3.0.0)

    rails (= 5.0.0) was resolved to 5.0.0, which depends on
      actionpack (= 5.0.0)

    rails (= 5.0.0) was resolved to 5.0.0, which depends on
      actionpack (= 5.0.0)

    rspec-rails (= 3.6.0) was resolved to 3.6.0, which depends on
      actionpack (>= 3.0)
</code>```

答:
What is your question?

Before update a gem you have to check if your project code and dependencies are ready for this changes, not an easy process if this is a big app.

1. Come back to de rails version you had.

gem install <gem> -v=<version>

e.g.

gem install rails -v=4.2

This way your rails app should use the version you want.

2. Update the rest of the gems... (not recommend it if you are not sure about the new releases)

Check your Gemfile.lock:

bundle update

Or delete your Gemfile.lock (it will be rebuild automatically when you try to start your rails app).

Body:
I am in a middle of a process of upgrading our rails 4 app.
Following the rails upgrade guide, I have updated current rails version in a gemfile replacing 4.2.10 with 5.0.0.

But after running bundle update rails, I am getting many incompatibility issues even after running 4.2.10 (with rails 4.2.10) which should update all gems to the latest version.

Following are the compatibility errors I am getting after running bundle update rails with rails 5.0.0 in a gemfile:

Bundler could not find compatible versions for gem "actionpack":
  In Gemfile:
    active_link_to was resolved to 1.0.3, which depends on
      actionpack

    active_model_serializers was resolved to 0.10.2, which depends on
      actionpack (< 6, >= 4.1)

    inherited_resources was resolved to 1.6.0, which depends on
      actionpack (< 5, >= 3.2)

    inherited_resources was resolved to 1.6.0, which depends on
      actionpack (< 5, >= 3.2)

    kaminari was resolved to 0.17.0, which depends on
      actionpack (>= 3.0.0)

    rails (= 5.0.0) was resolved to 5.0.0, which depends on
      actionpack (= 5.0.0)

    rails (= 5.0.0) was resolved to 5.0.0, which depends on
      actionpack (= 5.0.0)

    rspec-rails (= 3.6.0) was resolved to 3.6.0, which depends on
      actionpack (>= 3.0)


问:
Designing java project for monoliths and microservices at same time
I would like to know how you divide project modules in java for monolith with possibility of transforming modules to micro-services later?

My personal naming looks like this:

```<code>com.company.shopapp.product
...product.domain (ddd, services, repositories, entities, aggregates, command handlers - everything with package scope)
...product.api (everything with public scope)
...product.controller (CQRS endpoints for commands in web perspective - (package scope))
...product.query(CQRS - package scope)

com.company.shopapp.sales
- domain
- api
- controller
- query
</code>```

What we have here is basically product management context and sales context as packages.

Modules communicate each other using public interfaces (api package) only. In my project I use "..api.ProductFacade" to centralize communication points.

When my "sales" module grow i will turn it into microservice by implementing "..api.ProductFacade" interface as a "rest" or "soap" client and on the other side I will create Endpoint/RestController based on ProductFacade interface.
Package "com.company.shopapp.product.api" will be transformed into extended library and added to both projects.

Edit:
I can achive this out of the box using @Feign library.
https://cloud.spring.io/spring-cloud-netflix/multi/multi_spring-cloud-feign.html#spring-cloud-feign-inheritance

The whole idea feels nice, but maybe you have better way to design project and ensure that breaking it into micro-services will not break whole application.

答:
Microservices compound by functionality and degree of connectivity.
I used this approach:

com.company.product:

possible big service:

config

services

domain

etc

possible second big service:

config

services

domain

etc

config

services // which likely never be separated

domain // common domain

etc

When split project you analyze new common depencies seeing by packages, exclude common library, copy project for each microservice, delete unneccessary code, perhaps change services implementations (for example, if "possible big service" uses "possible second big service"), configurations and build.
"Big" in that context means full-fledged functional implementation of something, what could be horizontally scaled, or need to be microservice for other reasons.

Body:
I would like to know how you divide project modules in java for monolith with possibility of transforming modules to micro-services later?

My personal naming looks like this:

com.company.shopapp.product
...product.domain (ddd, services, repositories, entities, aggregates, command handlers - everything with package scope)
...product.api (everything with public scope)
...product.controller (CQRS endpoints for commands in web perspective - (package scope))
...product.query(CQRS - package scope)

com.company.shopapp.sales
- domain
- api
- controller
- query

What we have here is basically product management context and sales context as packages.

Modules communicate each other using public interfaces (api package) only. In my project I use "..api.ProductFacade" to centralize communication points.

When my "sales" module grow i will turn it into microservice by implementing "..api.ProductFacade" interface as a "rest" or "soap" client and on the other side I will create Endpoint/RestController based on ProductFacade interface.
Package "com.company.shopapp.product.api" will be transformed into extended library and added to both projects.

Edit:
I can achive this out of the box using @Feign library.
https://cloud.spring.io/spring-cloud-netflix/multi/multi_spring-cloud-feign.html#spring-cloud-feign-inheritance

The whole idea feels nice, but maybe you have better way to design project and ensure that breaking it into micro-services will not break whole application.


问:
Shorthand for extracting a high-dimensional sub-array, i.e. array[beg[0]:end[0],beg[1]:end[1],...]
I am looking for a concise way of extracting a subarray from a high-dimensional array.

For example let's take an array a. I want to extract a subarray, for which I have the beginning and end coordinates stored in two arrays b and e.

Currently, to extract the desired subarray, I type

```<code>a[b[0]:e[0],b[1]:e[1],b[2]:e[2],b[3]:e[3],...]
</code>```

I was wondering if there is a built-in, concise way of slicing such an array. I would love calling something like a[b:e], but this does not work.

答:
If the subclassing np.s_ approach shown here is too heavy for your liking, you can use:

```<code>a[tuple(slice(*idx) for idx in np.broadcast(start, stop, step))]
</code>```

The beauty of using np.broadcast here is that you can for example mix scalars and lists as in start=None, stop=[1,2,3]. This would be equivalent to a[:1, :2, :3].

Body:
I am looking for a concise way of extracting a subarray from a high-dimensional array.

For example let's take an array a. I want to extract a subarray, for which I have the beginning and end coordinates stored in two arrays b and e.

Currently, to extract the desired subarray, I type

a[b[0]:e[0],b[1]:e[1],b[2]:e[2],b[3]:e[3],...]

I was wondering if there is a built-in, concise way of slicing such an array. I would love calling something like a[b:e], but this does not work.

Body:
If the subclassing np.s_ approach shown here is too heavy for your liking, you can use:

a[tuple(slice(*idx) for idx in np.broadcast(start, stop, step))]

The beauty of using np.broadcast here is that you can for example mix scalars and lists as in start=None, stop=[1,2,3]. This would be equivalent to a[:1, :2, :3].


问:
control nested mixin behavior based on parent mixin
Here are two mixins

```<code>@mixin parent {
  .parent & {
    @content;
  }
}

@mixin child($child) {
  .#{$child} & {
    @content;
  }
}
</code>```

Both mixin works fine independently.

Things which am looking for:

child can be independent

Also child mixin can be included in parent but opposite
should not be allowed.

In case someone tries to include parent into child there should
be some error message.

In css output .parent should come before .child(see example below for this point)

Point 4 example:

```<code>.test {
  //some css properties
  @include parent {
    @include child(childboy) {
      color: red;
    }
  }
}
</code>```

as you can see this will give following output

```<code>.childboy .parent .test {
  color: red;
}
</code>```

As you can see .parent class is coming after .childboy.

How can we make it .parent class to come before .childboy

```<code>.parent .childboy .test {
  color: red;
}
</code>```

Is it possible to do with scss??
Please answer only in scss.

Thank you.

答:
I don't think you can do it that way.

Check out this CSS-tricks post:

The & doesn't allow you to selectively traverse up your nested
  selector tree to a certain place and only use a small portion of the
  compiled parent selector that you want to use.

If I understand correctly, the reason why you're trying to do this with SCSS is because you want to group the .parent .childboy .test selector within .test root selector.

Here's a different way to do this with SASS:

```<code>.test {
  @at-root .parent .childboy & {
    color: red;
  }
}
</code>```

Codepen demo

Note: the trailing & appends the selectors from root downwards - here, just the .test class

From the SASS docs:

The @at-root directive causes one or more rules to be emitted at the
  root of the document, rather than being nested beneath their parent
  selectors.

Body:
Here are two mixins

@mixin parent {
  .parent & {
    @content;
  }
}

@mixin child($child) {
  .#{$child} & {
    @content;
  }
}

Both mixin works fine independently.

Things which am looking for:

child can be independent

Also child mixin can be included in parent but opposite
should not be allowed.

In case someone tries to include parent into child there should
be some error message.

In css output .parent should come before .child(see example below for this point)

Point 4 example:

.test {
  //some css properties
  @include parent {
    @include child(childboy) {
      color: red;
    }
  }
}

as you can see this will give following output

.childboy .parent .test {
  color: red;
}

As you can see .parent class is coming after .childboy.

How can we make it .parent class to come before .childboy

.parent .childboy .test {
  color: red;
}

Is it possible to do with scss??
Please answer only in scss.

Thank you.

Body:
I don't think you can do it that way.

Check out this CSS-tricks post:

The & doesn't allow you to selectively traverse up your nested
  selector tree to a certain place and only use a small portion of the
  compiled parent selector that you want to use.

If I understand correctly, the reason why you're trying to do this with SCSS is because you want to group the .parent .childboy .test selector within .test root selector.

Here's a different way to do this with SASS:

.test {
  @at-root .parent .childboy & {
    color: red;
  }
}

Codepen demo

Note: the trailing & appends the selectors from root downwards - here, just the .test class

From the SASS docs:

The @at-root directive causes one or more rules to be emitted at the
  root of the document, rather than being nested beneath their parent
  selectors.


问:
SetMap(null) not working with markers in google maps v3
I'm creating a web app where on page load multiple polylines are drawn from one point to many. Their corresponding markers are also drawn. On change in dropdown list the polylines & markers should dissapear.

Current code output..

On changing the dropdown list the markers and the corresponding polylines should dissapear but currently only markers are dissapearing, not polylines

HTML code...

```<code>   <div class="filter-set">
    <label for="ship-select">See most popular destinations from an area:</label>
    <select id="type" onchange="filterAirports(this.value);">
    <option value="-1">Any</option>
    <option value="0">20001, Northwest Washington, Washington</option>
    <option value="1">512, 2001 Pennsylvania Ave NW, Washington, DC</option>
</select><br/><br/>
</div>
<div id="map_wrapper">
    <div id="us_map" class="mapping"></div>
</div>
</code>```

JavaScript Code...

```<code>    var gmarkers1 = [];
    var airport_location = [];
    var marker_element = [];
    var polyline=null,polyline1=null;
    var infowindow = new google.maps.InfoWindow({
        content: ''
    });
    var activities = document.getElementById("type");

    // start coordinates
    var start = [['20001, Northwest Washington, Washington',38.912068, -77.019023,1],
                ['512, 2001 Pennsylvania Ave NW, Washington, DC',38.90167,-77.045169,2]
                //['2000 H St NW, Washington, DC',38.89856,-77.045791]
                ];

    //2d array having multiple points for each point above
    airport_location = [[
        ['800 Gregorio Drive, Montgomery Knolls, Silver Spring', 39.009814, -76.99548, 1,2331], //
        ['9200 Whitney Street, Silver Spring', 39.005551, -77.003279, 2,2320], //
        ['100 Melbourne Avenue, Silver Spring', 39.006549, -77.011154, 3,2265], //
        ['8600 Lancaster Drive, Bethesda', 38.996859 ,  -77.088684, 4,2186], //
        ['8600 Irvington Avenue, Bradmoor, Bethesda', 38.996353 , -77.118253, 5,2159], //
        ['2400 Lyttonsville Place, Silver Spring', 38.998812, -77.052447, 6,2144], //
        ['8500 Glenville Road, Takoma Park', 38.994632, -76.993937, 7,2111], //
        ['8600 Cunningham Drive, Berwyn Heights', 38.991265 , -76.913815, 8,2097], //
        ['4800 Del Ray Avenue, Woodmont Triangle, Bethesda', 38.991144 , -77.097584, 9,2089],//
        ['8600 22nd Avenue, Hyattsville',  38.997182 , -76.968822, 10,2071] //
    ],
                    [
        ['9500 Elvis Lane, Lanham-Seabrook, Goddard', 38.985575 , -76.844996, 1,2547], //
        ['2700 Phelps Avenue, District Heights', 38.851711, -76.868447, 2,2469], //
        ['1800 Metzerott Road, Adelphi', 39.004447 , -76.977798, 3,2459], //
        ['3800 Forestville Road, District Heights', 38.836892 , -76.875601, 4,2366], //
        ['600 Cappy Avenue, Capitol Heights', 38.879616, -76.887745, 5,2360], //
        ['1700 Ritchie Road, District Heights', 38.866842, -76.862023, 6,2359], //
        ['6800 Asset Drive, Landover, 13, Kent, Prince George County, Maryland, United States, 20785)', 38.907013 , -76.890744, 7,2341], //
        ['5900 Cherrywood Lane, Greenbelt', 39.004776, -76.907918, 8,2319], //
        ['8600 22nd Avenue, Hyattsville', 38.997182, -76.968822, 9,2279],//
        ['1100 Valley Drive, College Park', 39.175554, -78.17089, 10,2274] //
    ]];

     //gmarkers1 = airport_location.slice();

    //Function to plot map intially on page load

    function initialize() {
        var center = new google.maps.LatLng(38.8977, -77.0365);
        var mapOptions = {
            zoom: 8,
            center: center,
            //mapTypeId: google.maps.MapTypeId.TERRAIN
        };

        map = new google.maps.Map(document.getElementById('us_map'), mapOptions);
        for (i = 0; i < airport_location.length; i++) {
            //addMarker(start[i]);
            for(var j=0; j < airport_location[i].length; j++){
                //console.log("Marker array is:" +airport_location[i][j]);
                addMarker(airport_location[i][j],i,j);
            }

        }
        console.log("gmarker array is: "+gmarkers1.length)

        var bounds = new google.maps.LatLngBounds();
        var paths = [];

        for (var i=0; i < airport_location.length; i++){
            for(var j=0; j < airport_location[i].length; j++){
        //  var startCoords = start[i].split(",");
            var startPt = new google.maps.LatLng(start[i][1],start[i][2]);
            //var endCoords = end[i].split(",");
            var endPt = new google.maps.LatLng(airport_location[i][j][1],airport_location[i][j][2]);
            if(i ==0){
                calcRoute(startPt, endPt);
                //paths.push([startPt, endPt]);
            }else{
            calcRoute1(startPt, endPt);
            }
            bounds.extend(startPt);
            bounds.extend(endPt);

            }
        }
        map.fitBounds(bounds);

    }

    // Initialize Google Maps API
    initialize();

    //Function to plot airports on the map

    function calcRoute(source,destination){
    polyline = new google.maps.Polyline({
        path: [source, destination],
        strokeColor: 'red',
        strokeWeight: 2,
        strokeOpacity: 1
    });

    polyline.setMap(map);
    }

    activities.addEventListener("change", function() {
        console.log("change called")
        polyline.setMap(null);
        //polyline = null;
        console.log("polyline "+polyline);
        polyline1.setMap(null);
        //polyline.setPath([]);
    });

    function calcRoute1(source,destination){
    polyline1 = new google.maps.Polyline({
        path: [source, destination],
        strokeColor: 'red',
        strokeWeight: 2,
        strokeOpacity: 1
    });

    polyline1.setMap(map);

    }

    function addMarker(marker,i,j) {
    console.log("i value is :"+i)
        var elevation = marker[4];
        var title = marker[0];
        var pos = new google.maps.LatLng(marker[1], marker[2]);
        var content = marker[0];

        marker1 = new google.maps.Marker({
            title: title,
            position: pos,
            elevation: elevation,
            map: map
        });
        //console.log("marker is: "+marker1)
        gmarkers1.push(marker1);

        // Fuction to display text on click
        google.maps.event.addListener(marker1, 'click', (function (marker1, content) {
            return function () {
            // console.log('Gmarker 1 gets pushed');
                infowindow.setContent(content);
                infowindow.open(map, marker1);
                map.panTo(this.getPosition());
            }
        })(marker1, content));
    }

    // function to add/remove markers based on filter

    filterAirports = function (elevation) {
    console.log("Condition: "+elevation)
            for (i = 0; i < gmarkers1.length; i++) {
            marker = gmarkers1[i];
            if(elevation == 0){
                if (i >=0 && i<= 9) {
                    marker.setVisible(true);
                }
                else {
                    marker.setVisible(false);

                }
            }else if(elevation == 1){
                if (i >=10 && i<= 19) {
                    marker.setVisible(true);
                }
                else {
                    marker.setVisible(false);
                }
            }else if(elevation == 2){

            }else if(elevation == -1){
                marker.setVisible(true);
            }

        }
    }
</code>```

As you can see in the code above, even after calling the setMap(null) code in the dropdown's event listener the polylines are not dissapearing.

Can't understand where I'm going wrong.. Spent 3 hours on this issue...Please Help!!

Edit 1:
 Added complete code to resolve few errors. On dropdown event change only the last polyline of point "1100 Valley Drive," is dissapearing but not reappearing on selecting some other option.

Edit 2:
JS fiddle https://jsfiddle.net/Lucy1/8qb0w1t4/
Basically I want the polylines, markers to appear & dissapear based on dropdown value selected. Marker code is working, polylines code is not!

答:
You need to save the polylines in an array like you do the markers:

```<code>// global variables
var gmarkers1 = [];
var polylines = []; // add this

function calcRoute1(source, destination) {
  polyline1 = new google.maps.Polyline({
    path: [source, destination],
    strokeColor: 'red',
    strokeWeight: 2,
    strokeOpacity: 1
  });

  polyline1.setMap(map);
  polylines.push(polyline1);
}
</code>```

Then when you filter them:

```<code>filterAirports = function(elevation) {
  console.log("Condition: " + elevation)
  for (i = 0; i < gmarkers1.length; i++) {
    marker = gmarkers1[i];
    // assume same number of polylines as markers and are in the same order in the arrays
    polyline = polylines[i];
    if (elevation == 0) {
      if (i >= 0 && i <= 9) {
        marker.setVisible(true);
        polyline.setMap(map);
      } else {
        marker.setVisible(false);
        polyline.setMap(null);
      }
    } else if (elevation == 1) {
      if (i >= 10 && i <= 19) {
        marker.setVisible(true);
        polyline.setMap(map);
      } else {
        marker.setVisible(false);
        polyline.setMap(null);
      }
    } else if (elevation == 2) {

    } else if (elevation == -1) {
      marker.setVisible(true)
      polyline.setMap(map);
    }
  }
}
</code>```

proof of concept fiddle

code snippet:

var map;
var gmarkers1 = [];
var polylines = [];
var airport_location = [];
var marker_element = [];
var polyline = null,
  polyline1 = null;
var infowindow = new google.maps.InfoWindow({
  content: ''
});
var activities = document.getElementById("type");

// start coordinates
var start = [
  ['20001, Northwest Washington, Washington', 38.912068, -77.019023, 1],
  ['512, 2001 Pennsylvania Ave NW, Washington, DC', 38.90167, -77.045169, 2]
  //['2000 H St NW, Washington, DC',38.89856,-77.045791]
];

//2d array having multiple points for each point above
airport_location = [
  [
    ['800 Gregorio Drive, Montgomery Knolls, Silver Spring', 39.009814, -76.99548, 1, 2331], //
    ['9200 Whitney Street, Silver Spring', 39.005551, -77.003279, 2, 2320], //
    ['100 Melbourne Avenue, Silver Spring', 39.006549, -77.011154, 3, 2265], //
    ['8600 Lancaster Drive, Bethesda', 38.996859, -77.088684, 4, 2186], //
    ['8600 Irvington Avenue, Bradmoor, Bethesda', 38.996353, -77.118253, 5, 2159], //
    ['2400 Lyttonsville Place, Silver Spring', 38.998812, -77.052447, 6, 2144], //
    ['8500 Glenville Road, Takoma Park', 38.994632, -76.993937, 7, 2111], //
    ['8600 Cunningham Drive, Berwyn Heights', 38.991265, -76.913815, 8, 2097], //
    ['4800 Del Ray Avenue, Woodmont Triangle, Bethesda', 38.991144, -77.097584, 9, 2089], //
    ['8600 22nd Avenue, Hyattsville', 38.997182, -76.968822, 10, 2071] //
  ],
  [
    ['9500 Elvis Lane, Lanham-Seabrook, Goddard', 38.985575, -76.844996, 1, 2547], //
    ['2700 Phelps Avenue, District Heights', 38.851711, -76.868447, 2, 2469], //
    ['1800 Metzerott Road, Adelphi', 39.004447, -76.977798, 3, 2459], //
    ['3800 Forestville Road, District Heights', 38.836892, -76.875601, 4, 2366], //
    ['600 Cappy Avenue, Capitol Heights', 38.879616, -76.887745, 5, 2360], //
    ['1700 Ritchie Road, District Heights', 38.866842, -76.862023, 6, 2359], //
    ['6800 Asset Drive, Landover, 13, Kent, Prince George County, Maryland, United States, 20785)', 38.907013, -76.890744, 7, 2341], //
    ['5900 Cherrywood Lane, Greenbelt', 39.004776, -76.907918, 8, 2319], //
    ['8600 22nd Avenue, Hyattsville', 38.997182, -76.968822, 9, 2279], //
    ['1100 Valley Drive, College Park', 39.175554, -78.17089, 10, 2274] //
  ]
];

//gmarkers1 = airport_location.slice();

//Function to plot map intially on page load

function initialize() {
  var center = new google.maps.LatLng(38.8977, -77.0365);
  var mapOptions = {
    zoom: 8,
    center: center,
    //mapTypeId: google.maps.MapTypeId.TERRAIN
  };

  map = new google.maps.Map(document.getElementById('us_map'), mapOptions);
  for (i = 1; i < airport_location.length; i++) {
    //addMarker(start[i]);
    for (var j = 0; j < airport_location[i].length; j++) {
      //console.log("Marker array is:" +airport_location[i][j]);
      addMarker(airport_location[i][j], i, j);
    }

  }
  console.log("gmarker array is: " + gmarkers1.length)

  var bounds = new google.maps.LatLngBounds();
  var paths = [];

  for (var i = 1; i < airport_location.length; i++) {
    for (var j = 0; j < airport_location[i].length; j++) {
      //  var startCoords = start[i].split(",");
      var startPt = new google.maps.LatLng(start[i][1], start[i][2]);
      //var endCoords = end[i].split(",");
      var endPt = new google.maps.LatLng(airport_location[i][j][1], airport_location[i][j][2]);
      if (i == 0) {
        calcRoute(startPt, endPt);
        //paths.push([startPt, endPt]);
      } else {
        calcRoute1(startPt, endPt);
      }
      bounds.extend(startPt);
      bounds.extend(endPt);

    }
  }
  map.fitBounds(bounds);

}

// Initialize Google Maps API
initialize();

//Function to plot airports on the map

function calcRoute(source, destination) {
  polyline = new google.maps.Polyline({
    path: [source, destination],
    strokeColor: 'red',
    strokeWeight: 2,
    strokeOpacity: 1
  });

  polyline.setMap(map);
  polylines.push(polyline);
}

/* activities.addEventListener("change", function() {
  console.log("change called")
  polyline.setMap(null);
  polyline = null;
  console.log("polyline " + polyline);
  //
  //polyline.setPath([]);
}); */

function calcRoute1(source, destination) {
  polyline1 = new google.maps.Polyline({
    path: [source, destination],
    strokeColor: 'red',
    strokeWeight: 2,
    strokeOpacity: 1
  });

  polyline1.setMap(map);
  polylines.push(polyline1);
}

function addMarker(marker, i, j) {
  console.log("i value is :" + i)
  var elevation = marker[4];
  var title = marker[0];
  var pos = new google.maps.LatLng(marker[1], marker[2]);
  var content = marker[0];

  marker1 = new google.maps.Marker({
    title: title,
    position: pos,
    elevation: elevation,
    map: map
  });
  //console.log("marker is: "+marker1)
  gmarkers1.push(marker1);

  // Fuction to display text on click
  google.maps.event.addListener(marker1, 'click', (function(marker1, content) {
    return function() {
      // console.log('Gmarker 1 gets pushed');
      infowindow.setContent(content);
      infowindow.open(map, marker1);
      map.panTo(this.getPosition());
    }
  })(marker1, content));
}

// function to add/remove markers based on filter

filterAirports = function(elevation) {
  console.log("Condition: " + elevation)
  for (i = 0; i < gmarkers1.length; i++) {
    marker = gmarkers1[i];
    // assume same number of polylines as markers and are in the same order in the arrays
    polyline = polylines[i];
    if (elevation == 0) {
      // polyline.setMap(null);
      if (i >= 0 && i <= 9) {
        marker.setVisible(true);
        polyline.setMap(map);
      } else {
        marker.setVisible(false);
        polyline.setMap(null);
      }
    } else if (elevation == 1) {
      if (i >= 10 && i <= 19) {
        marker.setVisible(true);
        polyline.setMap(map);
      } else {
        marker.setVisible(false);
        polyline.setMap(null);
      }
    } else if (elevation == 2) {

    } else if (elevation == -1) {
      marker.setVisible(true)
      polyline.setMap(map);
    }
  }
}
// google.maps.event.addDomListener(window, "load", initialize);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>html,
body,
#map_wrapper,
#us_map {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}</code>```

  See most popular destinations from an area:
  <select id="type" onchange="filterAirports(this.value);">
    <option value="-1">Any</option>
    <option value="0">20001, Northwest Washington, Washington</option>
    <option value="1">512, 2001 Pennsylvania Ave NW, Washington, DC</option>
  </select>

```

Body:
I'm creating a web app where on page load multiple polylines are drawn from one point to many. Their corresponding markers are also drawn. On change in dropdown list the polylines & markers should dissapear.

Current code output..

On changing the dropdown list the markers and the corresponding polylines should dissapear but currently only markers are dissapearing, not polylines

HTML code...

    See most popular destinations from an area:
    <select id="type" onchange="filterAirports(this.value);">
    <option value="-1">Any</option>
    <option value="0">20001, Northwest Washington, Washington</option>
    <option value="1">512, 2001 Pennsylvania Ave NW, Washington, DC</option>
</select>

JavaScript Code...

    var gmarkers1 = [];
    var airport_location = [];
    var marker_element = [];
    var polyline=null,polyline1=null;
    var infowindow = new google.maps.InfoWindow({
        content: ''
    });
    var activities = document.getElementById("type");

    // start coordinates
    var start = [['20001, Northwest Washington, Washington',38.912068, -77.019023,1],
                ['512, 2001 Pennsylvania Ave NW, Washington, DC',38.90167,-77.045169,2]
                //['2000 H St NW, Washington, DC',38.89856,-77.045791]
                ];

    //2d array having multiple points for each point above
    airport_location = [[
        ['800 Gregorio Drive, Montgomery Knolls, Silver Spring', 39.009814, -76.99548, 1,2331], //
        ['9200 Whitney Street, Silver Spring', 39.005551, -77.003279, 2,2320], //
        ['100 Melbourne Avenue, Silver Spring', 39.006549, -77.011154, 3,2265], //
        ['8600 Lancaster Drive, Bethesda', 38.996859 ,  -77.088684, 4,2186], //
        ['8600 Irvington Avenue, Bradmoor, Bethesda', 38.996353 , -77.118253, 5,2159], //
        ['2400 Lyttonsville Place, Silver Spring', 38.998812, -77.052447, 6,2144], //
        ['8500 Glenville Road, Takoma Park', 38.994632, -76.993937, 7,2111], //
        ['8600 Cunningham Drive, Berwyn Heights', 38.991265 , -76.913815, 8,2097], //
        ['4800 Del Ray Avenue, Woodmont Triangle, Bethesda', 38.991144 , -77.097584, 9,2089],//
        ['8600 22nd Avenue, Hyattsville',  38.997182 , -76.968822, 10,2071] //
    ],
                    [
        ['9500 Elvis Lane, Lanham-Seabrook, Goddard', 38.985575 , -76.844996, 1,2547], //
        ['2700 Phelps Avenue, District Heights', 38.851711, -76.868447, 2,2469], //
        ['1800 Metzerott Road, Adelphi', 39.004447 , -76.977798, 3,2459], //
        ['3800 Forestville Road, District Heights', 38.836892 , -76.875601, 4,2366], //
        ['600 Cappy Avenue, Capitol Heights', 38.879616, -76.887745, 5,2360], //
        ['1700 Ritchie Road, District Heights', 38.866842, -76.862023, 6,2359], //
        ['6800 Asset Drive, Landover, 13, Kent, Prince George County, Maryland, United States, 20785)', 38.907013 , -76.890744, 7,2341], //
        ['5900 Cherrywood Lane, Greenbelt', 39.004776, -76.907918, 8,2319], //
        ['8600 22nd Avenue, Hyattsville', 38.997182, -76.968822, 9,2279],//
        ['1100 Valley Drive, College Park', 39.175554, -78.17089, 10,2274] //
    ]];

     //gmarkers1 = airport_location.slice();

    //Function to plot map intially on page load

    function initialize() {
        var center = new google.maps.LatLng(38.8977, -77.0365);
        var mapOptions = {
            zoom: 8,
            center: center,
            //mapTypeId: google.maps.MapTypeId.TERRAIN
        };

        map = new google.maps.Map(document.getElementById('us_map'), mapOptions);
        for (i = 0; i < airport_location.length; i++) {
            //addMarker(start[i]);
            for(var j=0; j < airport_location[i].length; j++){
                //console.log("Marker array is:" +airport_location[i][j]);
                addMarker(airport_location[i][j],i,j);
            }

        }
        console.log("gmarker array is: "+gmarkers1.length)

        var bounds = new google.maps.LatLngBounds();
        var paths = [];

        for (var i=0; i < airport_location.length; i++){
            for(var j=0; j < airport_location[i].length; j++){
        //  var startCoords = start[i].split(",");
            var startPt = new google.maps.LatLng(start[i][1],start[i][2]);
            //var endCoords = end[i].split(",");
            var endPt = new google.maps.LatLng(airport_location[i][j][1],airport_location[i][j][2]);
            if(i ==0){
                calcRoute(startPt, endPt);
                //paths.push([startPt, endPt]);
            }else{
            calcRoute1(startPt, endPt);
            }
            bounds.extend(startPt);
            bounds.extend(endPt);

            }
        }
        map.fitBounds(bounds);

    }

    // Initialize Google Maps API
    initialize();

    //Function to plot airports on the map

    function calcRoute(source,destination){
    polyline = new google.maps.Polyline({
        path: [source, destination],
        strokeColor: 'red',
        strokeWeight: 2,
        strokeOpacity: 1
    });

    polyline.setMap(map);
    }

    activities.addEventListener("change", function() {
        console.log("change called")
        polyline.setMap(null);
        //polyline = null;
        console.log("polyline "+polyline);
        polyline1.setMap(null);
        //polyline.setPath([]);
    });

    function calcRoute1(source,destination){
    polyline1 = new google.maps.Polyline({
        path: [source, destination],
        strokeColor: 'red',
        strokeWeight: 2,
        strokeOpacity: 1
    });

    polyline1.setMap(map);

    }

    function addMarker(marker,i,j) {
    console.log("i value is :"+i)
        var elevation = marker[4];
        var title = marker[0];
        var pos = new google.maps.LatLng(marker[1], marker[2]);
        var content = marker[0];

        marker1 = new google.maps.Marker({
            title: title,
            position: pos,
            elevation: elevation,
            map: map
        });
        //console.log("marker is: "+marker1)
        gmarkers1.push(marker1);

        // Fuction to display text on click
        google.maps.event.addListener(marker1, 'click', (function (marker1, content) {
            return function () {
            // console.log('Gmarker 1 gets pushed');
                infowindow.setContent(content);
                infowindow.open(map, marker1);
                map.panTo(this.getPosition());
            }
        })(marker1, content));
    }

    // function to add/remove markers based on filter

    filterAirports = function (elevation) {
    console.log("Condition: "+elevation)
            for (i = 0; i < gmarkers1.length; i++) {
            marker = gmarkers1[i];
            if(elevation == 0){
                if (i >=0 && i<= 9) {
                    marker.setVisible(true);
                }
                else {
                    marker.setVisible(false);

                }
            }else if(elevation == 1){
                if (i >=10 && i<= 19) {
                    marker.setVisible(true);
                }
                else {
                    marker.setVisible(false);
                }
            }else if(elevation == 2){

            }else if(elevation == -1){
                marker.setVisible(true);
            }

        }
    }

As you can see in the code above, even after calling the setMap(null) code in the dropdown's event listener the polylines are not dissapearing.

Can't understand where I'm going wrong.. Spent 3 hours on this issue...Please Help!!

Edit 1:
 Added complete code to resolve few errors. On dropdown event change only the last polyline of point "1100 Valley Drive," is dissapearing but not reappearing on selecting some other option.

Edit 2:
JS fiddle https://jsfiddle.net/Lucy1/8qb0w1t4/
Basically I want the polylines, markers to appear & dissapear based on dropdown value selected. Marker code is working, polylines code is not!

Body:
You need to save the polylines in an array like you do the markers:

// global variables
var gmarkers1 = [];
var polylines = []; // add this

function calcRoute1(source, destination) {
  polyline1 = new google.maps.Polyline({
    path: [source, destination],
    strokeColor: 'red',
    strokeWeight: 2,
    strokeOpacity: 1
  });

  polyline1.setMap(map);
  polylines.push(polyline1);
}

Then when you filter them:

filterAirports = function(elevation) {
  console.log("Condition: " + elevation)
  for (i = 0; i < gmarkers1.length; i++) {
    marker = gmarkers1[i];
    // assume same number of polylines as markers and are in the same order in the arrays
    polyline = polylines[i];
    if (elevation == 0) {
      if (i >= 0 && i <= 9) {
        marker.setVisible(true);
        polyline.setMap(map);
      } else {
        marker.setVisible(false);
        polyline.setMap(null);
      }
    } else if (elevation == 1) {
      if (i >= 10 && i <= 19) {
        marker.setVisible(true);
        polyline.setMap(map);
      } else {
        marker.setVisible(false);
        polyline.setMap(null);
      }
    } else if (elevation == 2) {

    } else if (elevation == -1) {
      marker.setVisible(true)
      polyline.setMap(map);
    }
  }
}

proof of concept fiddle

code snippet:

var map;
var gmarkers1 = [];
var polylines = [];
var airport_location = [];
var marker_element = [];
var polyline = null,
  polyline1 = null;
var infowindow = new google.maps.InfoWindow({
  content: ''
});
var activities = document.getElementById("type");

// start coordinates
var start = [
  ['20001, Northwest Washington, Washington', 38.912068, -77.019023, 1],
  ['512, 2001 Pennsylvania Ave NW, Washington, DC', 38.90167, -77.045169, 2]
  //['2000 H St NW, Washington, DC',38.89856,-77.045791]
];

//2d array having multiple points for each point above
airport_location = [
  [
    ['800 Gregorio Drive, Montgomery Knolls, Silver Spring', 39.009814, -76.99548, 1, 2331], //
    ['9200 Whitney Street, Silver Spring', 39.005551, -77.003279, 2, 2320], //
    ['100 Melbourne Avenue, Silver Spring', 39.006549, -77.011154, 3, 2265], //
    ['8600 Lancaster Drive, Bethesda', 38.996859, -77.088684, 4, 2186], //
    ['8600 Irvington Avenue, Bradmoor, Bethesda', 38.996353, -77.118253, 5, 2159], //
    ['2400 Lyttonsville Place, Silver Spring', 38.998812, -77.052447, 6, 2144], //
    ['8500 Glenville Road, Takoma Park', 38.994632, -76.993937, 7, 2111], //
    ['8600 Cunningham Drive, Berwyn Heights', 38.991265, -76.913815, 8, 2097], //
    ['4800 Del Ray Avenue, Woodmont Triangle, Bethesda', 38.991144, -77.097584, 9, 2089], //
    ['8600 22nd Avenue, Hyattsville', 38.997182, -76.968822, 10, 2071] //
  ],
  [
    ['9500 Elvis Lane, Lanham-Seabrook, Goddard', 38.985575, -76.844996, 1, 2547], //
    ['2700 Phelps Avenue, District Heights', 38.851711, -76.868447, 2, 2469], //
    ['1800 Metzerott Road, Adelphi', 39.004447, -76.977798, 3, 2459], //
    ['3800 Forestville Road, District Heights', 38.836892, -76.875601, 4, 2366], //
    ['600 Cappy Avenue, Capitol Heights', 38.879616, -76.887745, 5, 2360], //
    ['1700 Ritchie Road, District Heights', 38.866842, -76.862023, 6, 2359], //
    ['6800 Asset Drive, Landover, 13, Kent, Prince George County, Maryland, United States, 20785)', 38.907013, -76.890744, 7, 2341], //
    ['5900 Cherrywood Lane, Greenbelt', 39.004776, -76.907918, 8, 2319], //
    ['8600 22nd Avenue, Hyattsville', 38.997182, -76.968822, 9, 2279], //
    ['1100 Valley Drive, College Park', 39.175554, -78.17089, 10, 2274] //
  ]
];

//gmarkers1 = airport_location.slice();

//Function to plot map intially on page load

function initialize() {
  var center = new google.maps.LatLng(38.8977, -77.0365);
  var mapOptions = {
    zoom: 8,
    center: center,
    //mapTypeId: google.maps.MapTypeId.TERRAIN
  };

  map = new google.maps.Map(document.getElementById('us_map'), mapOptions);
  for (i = 1; i < airport_location.length; i++) {
    //addMarker(start[i]);
    for (var j = 0; j < airport_location[i].length; j++) {
      //console.log("Marker array is:" +airport_location[i][j]);
      addMarker(airport_location[i][j], i, j);
    }

  }
  console.log("gmarker array is: " + gmarkers1.length)

  var bounds = new google.maps.LatLngBounds();
  var paths = [];

  for (var i = 1; i < airport_location.length; i++) {
    for (var j = 0; j < airport_location[i].length; j++) {
      //  var startCoords = start[i].split(",");
      var startPt = new google.maps.LatLng(start[i][1], start[i][2]);
      //var endCoords = end[i].split(",");
      var endPt = new google.maps.LatLng(airport_location[i][j][1], airport_location[i][j][2]);
      if (i == 0) {
        calcRoute(startPt, endPt);
        //paths.push([startPt, endPt]);
      } else {
        calcRoute1(startPt, endPt);
      }
      bounds.extend(startPt);
      bounds.extend(endPt);

    }
  }
  map.fitBounds(bounds);

}

// Initialize Google Maps API
initialize();

//Function to plot airports on the map

function calcRoute(source, destination) {
  polyline = new google.maps.Polyline({
    path: [source, destination],
    strokeColor: 'red',
    strokeWeight: 2,
    strokeOpacity: 1
  });

  polyline.setMap(map);
  polylines.push(polyline);
}

/* activities.addEventListener("change", function() {
  console.log("change called")
  polyline.setMap(null);
  polyline = null;
  console.log("polyline " + polyline);
  //
  //polyline.setPath([]);
}); */

function calcRoute1(source, destination) {
  polyline1 = new google.maps.Polyline({
    path: [source, destination],
    strokeColor: 'red',
    strokeWeight: 2,
    strokeOpacity: 1
  });

  polyline1.setMap(map);
  polylines.push(polyline1);
}

function addMarker(marker, i, j) {
  console.log("i value is :" + i)
  var elevation = marker[4];
  var title = marker[0];
  var pos = new google.maps.LatLng(marker[1], marker[2]);
  var content = marker[0];

  marker1 = new google.maps.Marker({
    title: title,
    position: pos,
    elevation: elevation,
    map: map
  });
  //console.log("marker is: "+marker1)
  gmarkers1.push(marker1);

  // Fuction to display text on click
  google.maps.event.addListener(marker1, 'click', (function(marker1, content) {
    return function() {
      // console.log('Gmarker 1 gets pushed');
      infowindow.setContent(content);
      infowindow.open(map, marker1);
      map.panTo(this.getPosition());
    }
  })(marker1, content));
}

// function to add/remove markers based on filter

filterAirports = function(elevation) {
  console.log("Condition: " + elevation)
  for (i = 0; i < gmarkers1.length; i++) {
    marker = gmarkers1[i];
    // assume same number of polylines as markers and are in the same order in the arrays
    polyline = polylines[i];
    if (elevation == 0) {
      // polyline.setMap(null);
      if (i >= 0 && i <= 9) {
        marker.setVisible(true);
        polyline.setMap(map);
      } else {
        marker.setVisible(false);
        polyline.setMap(null);
      }
    } else if (elevation == 1) {
      if (i >= 10 && i <= 19) {
        marker.setVisible(true);
        polyline.setMap(map);
      } else {
        marker.setVisible(false);
        polyline.setMap(null);
      }
    } else if (elevation == 2) {

    } else if (elevation == -1) {
      marker.setVisible(true)
      polyline.setMap(map);
    }
  }
}
// google.maps.event.addDomListener(window, "load", initialize);

html,
body,
#map_wrapper,
#us_map {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}

<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div class="filter-set">
  <label for="ship-select">See most popular destinations from an area:</label>
  <select id="type" onchange="filterAirports(this.value);">
    <option value="-1">Any</option>
    <option value="0">20001, Northwest Washington, Washington</option>
    <option value="1">512, 2001 Pennsylvania Ave NW, Washington, DC</option>
  </select>
  <br/>
  <br/>
</div>
<div id="map_wrapper">
  <div id="us_map" class="mapping"></div>
</div>

ContentLicense: CC BY-SA 4.0


问:
Can not show list with ngIf
Here is the component.ts file code;

```<code>import { Component, OnInit, ViewEncapsulation } from '@angular/core';

    const DISH = {
      name: 'Uthappizza',
      image: '/assets/images/uthappizza.png',
      category: 'mains',
      label: 'Hot',
      price: '4.99',
      description: 'A unique combination of Indian Uthappam (pancake) and Italian pizza, topped with Cerignola olives, ripe vine cherry tomatoes, Vidalia onion, Guntur chillies and Buffalo Paneer.',
      comments: [
        {
          rating: 5,
          comment: "Imagine all the eatables, living in conFusion!",
          author: "John Lemon",
          date: "2012-10-16T17:57:28.556094Z"
        },
        {
          rating: 4,
          comment: "Sends anyone to heaven, I wish I could get my mother-in-law to eat it!",
          author: "Paul McVites",
          date: "2014-09-05T17:57:28.556094Z"
        },
        {
          rating: 3,
          comment: "Eat it, just eat it!",
          author: "Michael Jaikishan",
          date: "2015-02-13T17:57:28.556094Z"
        },
        {
          rating: 4,
          comment: "Ultimate, Reaching for the stars!",
          author: "Ringo Starry",
          date: "2013-12-02T17:57:28.556094Z"
        },
        {
          rating: 2,
          comment: "It's your birthday, we're gonna party!",
          author: "25 Cent",
          date: "2011-12-02T17:57:28.556094Z"
        }
      ]
    };

    @Component({
      selector: 'app-dishdetail',
      templateUrl: './dishdetail.component.html',
      styleUrls: ['./dishdetail.component.scss'],
      encapsulation: ViewEncapsulation.None
    })
    export class DishdetailComponent implements OnInit {

      dish = DISH;

      constructor() { }

      ngOnInit() {
      }

    }
</code>```

And here is the html code

```<code>    <div class="container"
     fxLayout="row"
     fxLayout.sm="column"
     fxLayout.xs="column"
     fxLayoutAlign.gt-md="space-around center"
     fxLayoutGap="10px"
     fxLayoutGap.xs="0">

  <div fxFlex="40">
    <md-card>
      <md-card-header>
        <md-card-title>
          <h3>{{dish.name | uppercase}}</h3>
        </md-card-title>
      </md-card-header>
      <img md-card-image src={{dish.image}} alt={{dish.name}}>
      <md-card-content>
        <p>{{dish.description}}
        </p>
      </md-card-content>
      <md-card-actions>
        <button md-button>LIKE</button>
        <button md-button>SHARE</button>
      </md-card-actions>
    </md-card>
  </div>

  <div fxFlex="40">
    <md-card>
      <md-card-header>
        <md-card-title>
          <h3>Comments</h3>
        </md-card-title>
      </md-card-header>
      <md-card-content>
        <md-list *ngIf="dish.comments">
          <p>{{dish.comments}}</p>
        </md-list>
      </md-card-content>
    </md-card>
  </div>

</div>
</code>```

I am trying to show each comment in the DISH object, but can not list the comments.

It shows me like this

Comments

[object Object],[object Object],[object Object],[object Object],[object Object]**

Can anyone help me what is the missing part? What am i doing wrong?

答:
try this:</p>

```<code><md-card-content *ngIf="dish.comments">
        <md-list *ngFor="let comment of dish.comments">
          <p>{{comment.comment}}</p>
        </md-list>
</md-card-content>
</code>```

Title: Can not show list with ngIf

Body:
Here is the component.ts file code;

import { Component, OnInit, ViewEncapsulation } from '@angular/core';

    const DISH = {
      name: 'Uthappizza',
      image: '/assets/images/uthappizza.png',
      category: 'mains',
      label: 'Hot',
      price: '4.99',
      description: 'A unique combination of Indian Uthappam (pancake) and Italian pizza, topped with Cerignola olives, ripe vine cherry tomatoes, Vidalia onion, Guntur chillies and Buffalo Paneer.',
      comments: [
        {
          rating: 5,
          comment: "Imagine all the eatables, living in conFusion!",
          author: "John Lemon",
          date: "2012-10-16T17:57:28.556094Z"
        },
        {
          rating: 4,
          comment: "Sends anyone to heaven, I wish I could get my mother-in-law to eat it!",
          author: "Paul McVites",
          date: "2014-09-05T17:57:28.556094Z"
        },
        {
          rating: 3,
          comment: "Eat it, just eat it!",
          author: "Michael Jaikishan",
          date: "2015-02-13T17:57:28.556094Z"
        },
        {
          rating: 4,
          comment: "Ultimate, Reaching for the stars!",
          author: "Ringo Starry",
          date: "2013-12-02T17:57:28.556094Z"
        },
        {
          rating: 2,
          comment: "It's your birthday, we're gonna party!",
          author: "25 Cent",
          date: "2011-12-02T17:57:28.556094Z"
        }
      ]
    };

    @Component({
      selector: 'app-dishdetail',
      templateUrl: './dishdetail.component.html',
      styleUrls: ['./dishdetail.component.scss'],
      encapsulation: ViewEncapsulation.None
    })
    export class DishdetailComponent implements OnInit {

      dish = DISH;

      constructor() { }

      ngOnInit() {
      }

    }

And here is the html code

    <md-card>
      <md-card-header>
        <md-card-title>

{{dish.name | uppercase}}

        </md-card-title>
      </md-card-header>

      <md-card-content>

{{dish.description}}

      </md-card-content>
      <md-card-actions>
        <button md-button>LIKE</button>
        <button md-button>SHARE</button>
      </md-card-actions>
    </md-card>

    <md-card>
      <md-card-header>
        <md-card-title>

Comments

        </md-card-title>
      </md-card-header>
      <md-card-content>
        <md-list *ngIf="dish.comments">

{{dish.comments}}

        </md-list>
      </md-card-content>
    </md-card>

I am trying to show each comment in the DISH object, but can not list the comments.

It shows me like this

Comments

[object Object],[object Object],[object Object],[object Object],[object Object]**

Can anyone help me what is the missing part? What am i doing wrong?

Body:
try this:

<md-card-content *ngIf="dish.comments">
        <md-list *ngFor="let comment of dish.comments">
          <p>{{comment.comment}}</p>
        </md-list>
</md-card-content>


问:
Multi-dimensional char array prints within function, but not when passed to another function
I am attempting to write data into a multi-dimensional array, and then pass the array as a const char** to another function.  When I print the char* locally in the function in which it is declared, everything works as expected.  But, when I try to print the array of char* in another function, they are all empty strings.

I am using the following code:

```<code>void my_print (const char** lines, unsigned int num)
{
    int i = 0;

    for (i = 0; i < num; i++) {
        fprintf(stderr, "lines[%d]:  %s", i, lines[i]);
    }
}

void my_func ()
{
    char cfg[2][200];
    unsigned int value = 5;

    snprintf(cfg[0], 200, "one two three\n");
    snprintf(cfg[1], 200, "my value = %u\n", value);

    fprintf(stderr, "lines[0] = %slines[1] = %s\n", cfg[0], cfg[1]);

    my_print((const char**) cfg, 2);
}
</code>```

This results in the following output:

```<code>lines[0] = one two three
lines[1] = my value = 5
lines[0]:
lines[1]:
</code>```

If instead, of the given my_func, I use the following:

```<code>void my_func ()
{
    char* cfg[2];
    unsigned int value = 5;

    cfg[0] = malloc(200);
    cfg[1] = malloc(200);
    snprintf(cfg[0], 200, "one two three\n");
    snprintf(cfg[1], 200, "my value = %u\n", value);

    fprintf(stderr, "lines[0] = %slines[1] = %s\n", cfg[0], cfg[1]);

    my_print((const char**) cfg, 2);
}
</code>```

Then, everything works, and I get:

```<code>lines[0] = one two three
lines[1] = my value = 5
lines[0]: one two three
lines[1]: my value = 5
</code>```

So, what is happening in the background here?  Why do I need to use malloc in order for my_print to be able to print my strings?

Thanks you

答:
The explanation given is good: pointer-to-pointer is not the same thing as a multi-dimensional array.

Plainly explained, a 2-dimensional array with the syntax

char cfg[2][200];

is guaranteed to be allocated in adjacent memory cells. A 2-dimensional pointer-to-pointer array allocated with malloc will not be alloced in adjacent memory cells, it will be all over the heap. Because each time you call malloc, you will allocate a new segment. Making generic functions for multi-dimensional arrays in C is quite tricky because of this.

Body:
I am attempting to write data into a multi-dimensional array, and then pass the array as a const char** to another function.  When I print the char* locally in the function in which it is declared, everything works as expected.  But, when I try to print the array of char* in another function, they are all empty strings.

I am using the following code:

void my_print (const char** lines, unsigned int num)
{
    int i = 0;

    for (i = 0; i < num; i++) {
        fprintf(stderr, "lines[%d]:  %s", i, lines[i]);
    }
}

void my_func ()
{
    char cfg[2][200];
    unsigned int value = 5;

    snprintf(cfg[0], 200, "one two three\n");
    snprintf(cfg[1], 200, "my value = %u\n", value);

    fprintf(stderr, "lines[0] = %slines[1] = %s\n", cfg[0], cfg[1]);

    my_print((const char**) cfg, 2);
}

This results in the following output:

lines[0] = one two three
lines[1] = my value = 5
lines[0]:
lines[1]:

If instead, of the given my_func, I use the following:

void my_func ()
{
    char* cfg[2];
    unsigned int value = 5;

    cfg[0] = malloc(200);
    cfg[1] = malloc(200);
    snprintf(cfg[0], 200, "one two three\n");
    snprintf(cfg[1], 200, "my value = %u\n", value);

    fprintf(stderr, "lines[0] = %slines[1] = %s\n", cfg[0], cfg[1]);

    my_print((const char**) cfg, 2);
}

Then, everything works, and I get:

lines[0] = one two three
lines[1] = my value = 5
lines[0]: one two three
lines[1]: my value = 5

So, what is happening in the background here?  Why do I need to use malloc in order for my_print to be able to print my strings?

Thanks you


问:
Python: Removing a specific item that has a duplicate only knowing its index in a list
What I want this program to do is to delete all the 1's that are in the list that follow by index all the 2's.

This is the code:

```<code>a = [3, 1, 2, 1]
a.remove(a[3])
print(a)
</code>```

I really put this program into the basics but the point is that I have only got the index of the 1 that follows the 2, tho when I do this the result is:

```<code>[3, 2, 1]
</code>```

This means that it doesn't delete the 1 I want but just the first 1 it finds. Tho this is really a problem in a real program situation where the first 1 is an important value.

How can I fix it? Thanks

答:
The del keyword might be your best bet here, for example:

```<code>a = [3, 1, 2, 1]
index = 1
while index < len(a):
    if a[index - 1] == 2 and a[index] == 1:
        del a[index]
    else:
        index += 1
print(a)
</code>```

Body:
What I want this program to do is to delete all the 1's that are in the list that follow by index all the 2's.

This is the code:

a = [3, 1, 2, 1]
a.remove(a[3])
print(a)

I really put this program into the basics but the point is that I have only got the index of the 1 that follows the 2, tho when I do this the result is:

[3, 2, 1]

This means that it doesn't delete the 1 I want but just the first 1 it finds. Tho this is really a problem in a real program situation where the first 1 is an important value.

How can I fix it? Thanks

Body:
The del keyword might be your best bet here, for example:

a = [3, 1, 2, 1]
index = 1
while index < len(a):
    if a[index - 1] == 2 and a[index] == 1:
        del a[index]
    else:
        index += 1
print(a)


问:
Delay While Retrieving Data From Firebase Database
It's a chat app. I am retrieving messages to show on the chat room recyclerview. For that I'm using FirebaseRecyclerAdapter. I'm retrieving latest 500 messages. And that chat room has over 20k messages.. When I load that activity it is taking 6 seconds to load all 500 messages.

I tracked the time.

The delay was between setAdapter and RecyclerAdapter class.

My Message Structure In Firebase Database

```<code>{
  "-KlQc42ici0_PRCBX7-V" : {
    "message" : "message 1",
    "timestamp" : 1496185853436,
    "type" : "action",
    "username" : "berkleef2",
  },
  "-KlQmhcwK96j30FNoSs-" : {
    "message" : "message 2",
    "timestamp" : 1496188640000,
    "type" : "action",
    "username" : "atrickrodney16yahoocomat",
    "zread" : true
  },
  "-KlQmjSoucJD7uaHriOh" : {
    "message" : "message 3",
    "timestamp" : 1496188647083,
    "type" : "text",
    "username" : "atrickrodney16yahoocomat",
    "zread" : true
  }
}
</code>```

The Delay Started after setAdapter

```<code> mNewAdapter = new NewChatRecyclerAdapter(
                    ChatMessageItem.class,
                    R.layout.message_item,
                    RecyclerView.ViewHolder.class, ref.limitToLast(500), Fusername, booIsPrivateChat, chatd, strOpponent);
            messageList.setAdapter(mNewAdapter);
</code>```

I think there is no problem with the adapter class. So if the problem is with loading 500 messages. Then what should I do in this case to load chat messages...

答: You can use keepsynced function given by firebase database on your database reference.

Body:
It's a chat app. I am retrieving messages to show on the chat room recyclerview. For that I'm using FirebaseRecyclerAdapter. I'm retrieving latest 500 messages. And that chat room has over 20k messages.. When I load that activity it is taking 6 seconds to load all 500 messages.

I tracked the time.

The delay was between setAdapter and RecyclerAdapter class.

My Message Structure In Firebase Database

{
  "-KlQc42ici0_PRCBX7-V" : {
    "message" : "message 1",
    "timestamp" : 1496185853436,
    "type" : "action",
    "username" : "berkleef2",
  },
  "-KlQmhcwK96j30FNoSs-" : {
    "message" : "message 2",
    "timestamp" : 1496188640000,
    "type" : "action",
    "username" : "atrickrodney16yahoocomat",
    "zread" : true
  },
  "-KlQmjSoucJD7uaHriOh" : {
    "message" : "message 3",
    "timestamp" : 1496188647083,
    "type" : "text",
    "username" : "atrickrodney16yahoocomat",
    "zread" : true
  }
}

The Delay Started after setAdapter

 mNewAdapter = new NewChatRecyclerAdapter(
                    ChatMessageItem.class,
                    R.layout.message_item,
                    RecyclerView.ViewHolder.class, ref.limitToLast(500), Fusername, booIsPrivateChat, chatd, strOpponent);
            messageList.setAdapter(mNewAdapter);

I think there is no problem with the adapter class. So if the problem is with loading 500 messages. Then what should I do in this case to load chat messages...


答:
I don't know about the more pythonic way to do this, but you can keep a counter to check for the second appearance of a value you want to delete from a list.</p>

```<code>a = [3, 1, 2, 1]
counter = 0

for i, v in enumerate(a):
    if v==1:
        if counter == 1:
            del a[i]
        else:
            counter += 1

print a

#output: [3, 1, 2]
</code>```

Title: Python: Removing a specific item that has a duplicate only knowing its index in a list

Body:
I don't know about the more pythonic way to do this, but you can keep a counter to check for the second appearance of a value you want to delete from a list.

a = [3, 1, 2, 1]
counter = 0

for i, v in enumerate(a):
    if v==1:
        if counter == 1:
            del a[i]
        else:
            counter += 1

print a

#output: [3, 1, 2]


问:
Sending JSON through JQuery to Java
I have a URL that accepts JSON through a post method. It should return a cookie and status.

When I try the following, (the username and password should be the JSON I'm trying to send) , I get no response, any ideas?

```<code><script>
$.post("https://login-url",{"username":"user","password":"1234567890"},
function(data){
     alert("Data Loaded: " + data);
   }, "JSON" );
</script>
</code>```

UPDATE:

After following DavidDorward's comment my code looks like this:

```<code><script>
$.ajax({
    url: 'https://loginurl',
    type: 'POST',
    data: '{"username":"user","password":"1234567890"}',
    contentType: 'application/json',
    dataType: 'text',
    success: function(msg){
     alert("Data Loaded win: " + msg);}
</code>```

});

```<code></script>
</code>```

To describe my error a little better, a status should be returned, and a cookie. When I load this page firefox, and watch using firebug, there is no response, and no cookie information loaded in the header. Although it does seem to hit the URL, this makes me think its still a problem with the data. Although if the username and password are incorrect it should return an error, which is doesn't. It just consistently returns "null".

And to answer mattb's question, the login URL is only expecting "username" and "password" in JSON format and string datatype

答:
It sounds to me like you have some sort of AJAX cross domain problem. For example, if the page you are running uses http and the url you are trying to access is using https, you will run into this problem.

The result is often what you describe: no response

http://en.wikipedia.org/wiki/Same_origin_policy

Regards,
Thomas Kahn

Title: Sending JSON through JQuery to Java

Body:
I have a URL that accepts JSON through a post method. It should return a cookie and status.

When I try the following, (the username and password should be the JSON I'm trying to send) , I get no response, any ideas?

UPDATE:

After following DavidDorward's comment my code looks like this:

To describe my error a little better, a status should be returned, and a cookie. When I load this page firefox, and watch using firebug, there is no response, and no cookie information loaded in the header. Although it does seem to hit the URL, this makes me think its still a problem with the data. Although if the username and password are incorrect it should return an error, which is doesn't. It just consistently returns "null".

And to answer mattb's question, the login URL is only expecting "username" and "password" in JSON format and string datatype


问:
How to enable scripting in Tomcat 8 for RDF4J Workbench 2.2.4?
In order to create an RDFstore I have installed RDF4J server and RDF4J-Workbench 2.2.4 in Tomcat 8 (in Tomcat 8 I have deployed the relatives .war files of eclipse-rdf4j-2.2.4-sdk) in WIN10.

I have already configured Tomcat 8 by enabling the CGI and SSi servlets and the relatives mappings in CATALINA_HOME/conf/web.xml but workbench indicates the same message:

Scripting is not enabled. The Open RDF Sesame Workbench application requires scripting to be enabled in order to work properly.

At the same time, in the CATALINA_HOME/logs/catalina.2017 I receive the following:

...WARNING [http-nio-8080-exec-1] org.eclipse.rdf4j.workbench.proxy.ServerValidator.checkServerPrefixes server URL null does not have a prefix file: http: https:....

Please for any idea about script enabling in Tomcat and the warning above.

答:
The error indicating scripting must be enabled is referring to your browser settings. Do you know how to enable scripting in your browser?

The checkServerPrefix error is referring to a null server setting, which is really just complaining about not having a server setup (yet).


问:
Developing data entry application using angular material and javascript
I wanted to build application using angular material design, angularjs (in HTML) and javascript which takes an input (name, place, phone-number & email) once submitted it has to be stored in table below it.

Link to work in codepen
https://codepen.io/anon/pen/QOoEyW

I have tried various ways to materialize the code. Also the table should have solution of deleting the whole entry and editing the entered entry. I have tried a lot with code provided here. I was able to enter the data but unable to clear the data after submission

angular
  .module('MyApp', ['ngMaterial'])
  .controller('DemoCtrl', function($scope) {
    $scope.dataArray = [];
    $scope.add = function(data) {
      $scope.dataArray.push(data);
      $scope.data = null;
    }
    $scope.delete = function(index) {
      $scope.dataArray.splice(index, 1);
    }
  })
  .config(function($mdThemingProvider) {
    $mdThemingProvider.theme('docs-dark', 'default')
      .primaryPalette('yellow')
      .dark();
  });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div ng-controller="DemoCtrl" layout="column" ng-app="MyApp">
  <md-content md-theme="docs-dark" layout-gt-sm="row" layout-padding="">
    <md-input-container>
      <label>Name</label>
      <input ng-model="user.name" required="">
    </md-input-container>
    <md-input-container>
      <label>Place</label>
      <input ng-model="user.place" type="place" required="">
    </md-input-container>
    <md-input-container>
      <label>Email</label>
      <input ng-model="user.email" type="email" required="">
    </md-input-container>
    <md-input-container>
      <label>Phone</label>
      <input name="phoneNumber" ng-model="user.number" required="" ng-pattern="/^[0-9]{10}$/" md-maxlength="10">
    </md-input-container>
  </md-content>
  <section layout="column" layout-sm="column" layout-align="center center" layout-wrap>
    <md-button ng-click="add(data)" class="md-raised md-primary">Click to Add</md-button>
  </section>
  <table>
    <th width="20%">Name</th>
    <th width="20%">Place</th>
    <th width="30%">E-mail</th>
    <th width="20%">Number</th>
    <th width="10%">Remove</th>
    <tr data-ng-repeat="entry in dataArray  track by $index">
      <td data-ng-bind="user.name"></td>
      <td data-ng-bind="user.place"></td>
      <td data-ng-bind="user.email"></td>
      <td data-ng-bind="user.number"></td>
      <td data-ng-click="delete(dataArray.indexOf(entry))">click</td>
    </tr>
    <table></code>```

So please provide me with proper code..Else correct the provided code

答:
You have several problems with your code.

First:

```<code><md-button ng-click="add(data)" class="md-raised md-primary">Click to Add</md-button>
</code>```

Your function call is add(data) when it should be add(user)

Second:

```<code><tr data-ng-repeat="entry in dataArray  track by $index">
</code>```

You have data-ng-repeat="entry in dataArray, yet you use user to bind to the table. It should be entry.name, entry.email, etc.

Then, you can just add $scope.user = {} or $scope.user = null to your $scope.add function to clear the form fields.

Here's the fixed CodePen: https://codepen.io/anon/pen/gXExoM

Body:
I wanted to build application using angular material design, angularjs (in HTML) and javascript which takes an input (name, place, phone-number & email) once submitted it has to be stored in table below it.

Link to work in codepen
https://codepen.io/anon/pen/QOoEyW

I have tried various ways to materialize the code. Also the table should have solution of deleting the whole entry and editing the entered entry. I have tried a lot with code provided here. I was able to enter the data but unable to clear the data after submission

angular
  .module('MyApp', ['ngMaterial'])
  .controller('DemoCtrl', function($scope) {
    $scope.dataArray = [];
    $scope.add = function(data) {
      $scope.dataArray.push(data);
      $scope.data = null;
    }
    $scope.delete = function(index) {
      $scope.dataArray.splice(index, 1);
    }
  })
  .config(function($mdThemingProvider) {
    $mdThemingProvider.theme('docs-dark', 'default')
      .primaryPalette('yellow')
      .dark();
  });

  <md-content md-theme="docs-dark" layout-gt-sm="row" layout-padding="">
    <md-input-container>
      Name
      <input ng-model="user.name" required="">
    </md-input-container>
    <md-input-container>
      Place
      <input ng-model="user.place" type="place" required="">
    </md-input-container>
    <md-input-container>
      Email
      <input ng-model="user.email" type="email" required="">
    </md-input-container>
    <md-input-container>
      Phone
      <input name="phoneNumber" ng-model="user.number" required="" ng-pattern="/^[0-9]{10}$/" md-maxlength="10">
    </md-input-container>
  </md-content>

    <md-button ng-click="add(data)" class="md-raised md-primary">Click to Add</md-button>

    Name
    Place
    E-mail
    Number
    Remove

      click

So please provide me with proper code..Else correct the provided code

Body:
You have several problems with your code.

First:

<md-button ng-click="add(data)" class="md-raised md-primary">Click to Add</md-button>

Your function call is add(data) when it should be add(user)

Second:

<tr data-ng-repeat="entry in dataArray  track by $index">

You have data-ng-repeat="entry in dataArray, yet you use user to bind to the table. It should be entry.name, entry.email, etc.

Then, you can just add $scope.user = {} or $scope.user = null to your $scope.add function to clear the form fields.

Here's the fixed CodePen: https://codepen.io/anon/pen/gXExoM


问:
Conditionally choose a value on the left hand side of an assignment statement?
Is it possible to conditionally choose a value on the left hand side of an assignment statement (in C#)?

If I was assigning one of two values to a single variable, I could do this:

```<code>var1 = (mode == "A" ?
          someList.Any(itm => itm.prop == value) :
          someList.Any(itm => itm.prop == value2)  );

or

var1 = someList.Any(itm => itm.prop == (mode == "A" ? value : value2));
</code>```

But suppose I want to populate one of two variables with a value:

```<code>if (mode == "A")
    var1 = someList.Any(itm => itm.prop == value);

if (mode == "B")
    var2 = someList.Any(itm => itm.prop == value);
</code>```

Is there any way to do this in one line? (non working) example:

```<code>(mode == "A" ? var1 : var2) = someList.Any(itm => itm.prop == value);
</code>```

[I know I can introduce a variable and assign it to var1 or var2 before getting from somelist

```<code>var temp = (mode == "A" ? var1 : var2);
temp = someList.Any(itm => itm.prop == value);
</code>```

]

UPDATE
@HimBromBeere - I know that there are restrictions on the target of an assignment, and I don't need to do this, I just wondered if it was possible, in the same way that usage of the conditional operator is possible.

The code snippets were meant to illustrate and further explain the question.

...But I succeeded in getting two wonderful, useful nuggets of information from @EricLippert and @Servy: The ConditionalAssignment / SelectVariable function and the C# ref function.

I'll probably never use them (Eric - I'll stick to IF), but it helps me to grow.

Thanks everyone for all the useful feedback.

答:
```<code>        var var1 = "";
        var var2 = "";
        var mode = "A";
        var pointlessVar = "";
        pointlessVar =  mode == "A"  ? var1 = "blah" : var2 = "de blah";
</code>```

Body:
Is it possible to conditionally choose a value on the left hand side of an assignment statement (in C#)?

If I was assigning one of two values to a single variable, I could do this:

var1 = (mode == "A" ?
          someList.Any(itm => itm.prop == value) :
          someList.Any(itm => itm.prop == value2)  );

or

var1 = someList.Any(itm => itm.prop == (mode == "A" ? value : value2));

But suppose I want to populate one of two variables with a value:

if (mode == "A")
    var1 = someList.Any(itm => itm.prop == value);

if (mode == "B")
    var2 = someList.Any(itm => itm.prop == value);

Is there any way to do this in one line? (non working) example:

(mode == "A" ? var1 : var2) = someList.Any(itm => itm.prop == value);

[I know I can introduce a variable and assign it to var1 or var2 before getting from somelist

var temp = (mode == "A" ? var1 : var2);
temp = someList.Any(itm => itm.prop == value);

]

UPDATE
@HimBromBeere - I know that there are restrictions on the target of an assignment, and I don't need to do this, I just wondered if it was possible, in the same way that usage of the conditional operator is possible.

The code snippets were meant to illustrate and further explain the question.

...But I succeeded in getting two wonderful, useful nuggets of information from @EricLippert and @Servy: The ConditionalAssignment / SelectVariable function and the C# ref function.

I'll probably never use them (Eric - I'll stick to IF), but it helps me to grow.

Thanks everyone for all the useful feedback.


问:
Reload content in modal (twitter bootstrap)
I'm using twitter bootstrap's modal popup.

```<code><div id="myModal" class="modal hide fade in">
    <div class="modal-header">
        <a class="close" data-dismiss="modal">×</a>
        <h3>Header</h3>
    </div>
    <div class="modal-body"></div>
    <div class="modal-footer">
        <input type="submit" class="btn btn-success" value="Save"/>
    </div>
</div>
</code>```

I can load content using ajax with this a-element:

```<code><a data-toggle="modal" data-target="#myModal" href="edit.aspx">Open modal</a>
</code>```

Now I have to open the same modal but using a different url. I'm using this modal to edit an entity from my database. So when I click edit on an entity I need to load the modal with an ID.

```<code><a data-toggle="modal" data-target="#myModal" href="edit.aspx?id=1">Open modal</a>
<a data-toggle="modal" data-target="#myModal" href="edit.aspx?id=2">Open modal</a>
<a data-toggle="modal" data-target="#myModal" href="edit.aspx?id=3">Open modal</a>
</code>```

If I click on link number 1, it works fine. But if I then click on link number 2 the modal content is already loaded and therefor it will show the content from link number 1.

How can I refresh or reset the ajax loaded content in a twitter bootstrap modal popup?

答:
You can try this:</p>

```<code>$('#modal').on('hidden.bs.modal', function() {
    $(this).removeData('bs.modal');
});
</code>```

Body:
I'm using twitter bootstrap's modal popup.

        ×

Header

        <input type="submit" class="btn btn-success" value="Save"/>

I can load content using ajax with this a-element:

Open modal

Now I have to open the same modal but using a different url. I'm using this modal to edit an entity from my database. So when I click edit on an entity I need to load the modal with an ID.

Open modal
Open modal
Open modal

If I click on link number 1, it works fine. But if I then click on link number 2 the modal content is already loaded and therefor it will show the content from link number 1.

How can I refresh or reset the ajax loaded content in a twitter bootstrap modal popup?

Body:
You can try this:

$('#modal').on('hidden.bs.modal', function() {
    $(this).removeData('bs.modal');
});


问:
SAS, drop rows where values are numeric
I have rows from a Excel-file where some columns contains numeric values. I want to drop all rows that have columns with numeric values. One row I want to drop is for example:

```<code>User ID City State Country Age
4969          30   4970    Missing value
</code>```

Is there any easy function for this?

答:
Deleting a row with a condition is fairly straightforward.  You can use ANYALPHA to identify columns with non-numeric fields.</p>

```<code>data want;
  set have;
  if not (anyalpha(state)) then delete;
run;
</code>```

Title: SAS, drop rows where values are numeric

Body:
I have rows from a Excel-file where some columns contains numeric values. I want to drop all rows that have columns with numeric values. One row I want to drop is for example:

User ID City State Country Age
4969          30   4970    Missing value

Is there any easy function for this?

Body:
Deleting a row with a condition is fairly straightforward.  You can use ANYALPHA to identify columns with non-numeric fields.

data want;
  set have;
  if not (anyalpha(state)) then delete;
run;


问:
How to create static cells with dynamic cell heights with Swift
I have looked at several tutorials that show how to set dynamic cell heights, but all of them only show it if you are using dynamic cells by setting the appropriate constraints and using UITableViewAutomaticDimension. However, I would like to do this for static cells.

I have a table view controller in my app that contains several cells that display a category with a disclosure indicator in which there is a title and then a description and the size of the description text varies. Thus, I would like the height of the cell to be dynamic per the size of the description text.

The reason why I am using static cells and not dynamic cells is because above the category cells I have a few cells with some designs that I could only get by using static cells and storyboarding.

I am using iOS9, Xcode 7.3 and Swift 2.2

UPDATE

Table View Controller Code

```<code>import UIKit

class CategoriesTableViewController: UITableViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.rowHeight = UITableViewAutomaticDimension
        tableView.estimatedRowHeight = 140
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // MARK: - Table view data source

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return 2
    }

}
</code>```

UPDATE 2

Per accepted answer below I added the two methods below to my table view controller and removed the 2 lines I had in viewDidLoad(). This did it for me! Keep in mind that I had to make sure all the labels in each cell used a top, bottom, leading and trailing constraint. Also, the number of lines for each label must be set to 0.

```<code>override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    return UITableViewAutomaticDimension
}

override func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    return UITableViewAutomaticDimension
}
</code>```

答:
@Forge, add please to your topic

Swift 4 variant:

```<code>override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return UITableViewAutomaticDimension
}

override func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
    return UITableViewAutomaticDimension
}
</code>```

Body:
I have looked at several tutorials that show how to set dynamic cell heights, but all of them only show it if you are using dynamic cells by setting the appropriate constraints and using UITableViewAutomaticDimension. However, I would like to do this for static cells.

I have a table view controller in my app that contains several cells that display a category with a disclosure indicator in which there is a title and then a description and the size of the description text varies. Thus, I would like the height of the cell to be dynamic per the size of the description text.

The reason why I am using static cells and not dynamic cells is because above the category cells I have a few cells with some designs that I could only get by using static cells and storyboarding.

I am using iOS9, Xcode 7.3 and Swift 2.2

UPDATE

Table View Controller Code

import UIKit

class CategoriesTableViewController: UITableViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.rowHeight = UITableViewAutomaticDimension
        tableView.estimatedRowHeight = 140
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // MARK: - Table view data source

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return 2
    }

}

UPDATE 2

Per accepted answer below I added the two methods below to my table view controller and removed the 2 lines I had in viewDidLoad(). This did it for me! Keep in mind that I had to make sure all the labels in each cell used a top, bottom, leading and trailing constraint. Also, the number of lines for each label must be set to 0.

override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    return UITableViewAutomaticDimension
}

override func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    return UITableViewAutomaticDimension
}

Body:
@Forge, add please to your topic

Swift 4 variant:

override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return UITableViewAutomaticDimension
}

override func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
    return UITableViewAutomaticDimension
}


问:
HttpClient: Can't get data from external URL
I have a very basic (GET-) request fetching some kind of data (case-list.service.ts):

```<code>fetchCase(caseId: string) {
  return this.httpClient.get('http://localhost:54355/api/case/' + caseId);
}
</code>```

I need that kind of URL because my backend is on another port.
However, I'm getting an error, and the request is not being executed:

ERROR Error: resource is required
          at viewWrappedDebugError (core.es5.js:8422)
          at callWithDebugContext (core.es5.js:13477)
          at Object.debugCheckAndUpdateView [as checkAndUpdateView] (core.es5.js:13007)
          at ViewRef_.webpackJsonp.../../../core/@angular/core.es5.js.ViewRef_.detectChanges
  (core.es5.js:10174)
          at core.es5.js:4812
          at Array.forEach ()
          at ApplicationRef_.webpackJsonp.../../../core/@angular/core.es5.js.ApplicationRef_.tick (core.es5.js:4812)
          at core.es5.js:4684
          at ZoneDelegate.webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.invoke
  (zone.js:392)
          at Object.onInvoke (core.es5.js:3890)

But, when I replace that URL with a local one (e.g. '/api/case/' + caseId), it works as expected.

The localhost-URL is not the problem. I tried it with entering http://www.google.de/something, and it threw the same error as with the localhost address.

Any ideas why this is not working?
Any help is appreciated :)

@Update:
I subscribe to that observable in my component controller:
case-list.component.ts:

```<code>    this.caseListService.fetchCase(this.caseId).subscribe( (res) => {

      console.log(res);
      // comment in when backend is available
      // this.case = res;
    });
</code>```

答:
Ok, in my case I was a wrongly configured HTTP_INTERCEPTOR. The external URL was not added there.

Thanks all for your help :)

Body:
I have a very basic (GET-) request fetching some kind of data (case-list.service.ts):

fetchCase(caseId: string) {
  return this.httpClient.get('http://localhost:54355/api/case/' + caseId);
}

I need that kind of URL because my backend is on another port.
However, I'm getting an error, and the request is not being executed:

ERROR Error: resource is required
          at viewWrappedDebugError (core.es5.js:8422)
          at callWithDebugContext (core.es5.js:13477)
          at Object.debugCheckAndUpdateView [as checkAndUpdateView] (core.es5.js:13007)
          at ViewRef_.webpackJsonp.../../../core/@angular/core.es5.js.ViewRef_.detectChanges
  (core.es5.js:10174)
          at core.es5.js:4812
          at Array.forEach ()
          at ApplicationRef_.webpackJsonp.../../../core/@angular/core.es5.js.ApplicationRef_.tick (core.es5.js:4812)
          at core.es5.js:4684
          at ZoneDelegate.webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.invoke
  (zone.js:392)
          at Object.onInvoke (core.es5.js:3890)

But, when I replace that URL with a local one (e.g. '/api/case/' + caseId), it works as expected.

The localhost-URL is not the problem. I tried it with entering http://www.google.de/something, and it threw the same error as with the localhost address.

Any ideas why this is not working?
Any help is appreciated :)

@Update:
I subscribe to that observable in my component controller:
case-list.component.ts:

    this.caseListService.fetchCase(this.caseId).subscribe( (res) => {

      console.log(res);
      // comment in when backend is available
      // this.case = res;
    });


问:
Java, Reading two different types of variables from a file and using them as objects later
I working on a project that is based on reading a text from a file and putting it as objects in my code.

My file has the following elements:
(ignore the bullet points)

4

Christmas Party

20

Valentine

12

Easter

5

Halloween

8

The first line declares how many "parties" I have in my text file (its 4 btw)
Every party has two lines - the first line is the name and the second one is the number of places available.

So for example, Christmas Party has 20 places available

Here's my code for saving the information from the file as objects.

```<code>public class Parties
{
   static Scanner input = new Scanner(System.in);

  public static void main(String[] args) throws FileNotFoundException
  {

     Scanner inFile = new Scanner(new FileReader ("C:\\desktop\\file.txt"));

     int first = inFile.nextInt();
     inFile.nextLine();

    for(int i=0; i < first ; i++)
    {
        String str = inFile.nextLine();
        String[] e = str.split("\\n");

        String name = e[0];
        int tickets= Integer.parseInt(e[1]); //this is where it throw an error ArrayIndexOutOfBoundsException, i read about it and I still don't understand

        Party newParty = new Party(name, tickets);
        System.out.println(name+ " " + tickets);
    }
</code>```

This is my SingleParty Class:

```<code>public class SingleParty
{
    private String name;
    private int tickets;

    public Party(String newName, int newTickets)
    {
        newName = name;
        newTickets = tickets;

    }
</code>```

Can someone explain to me how could I approach this error?

Thank you

答:
nextLine() returns a single string.

Consider the first iteration, for example, "Christmas Party".

If you split this string by \n all you're gonna get is "Christmas Party" in an array of length 1. Split by "blank space" and it should work.

Body:
I working on a project that is based on reading a text from a file and putting it as objects in my code.

My file has the following elements:
(ignore the bullet points)

4

Christmas Party

20

Valentine

12

Easter

5

Halloween

8

The first line declares how many "parties" I have in my text file (its 4 btw)
Every party has two lines - the first line is the name and the second one is the number of places available.

So for example, Christmas Party has 20 places available

Here's my code for saving the information from the file as objects.

public class Parties
{
   static Scanner input = new Scanner(System.in);

  public static void main(String[] args) throws FileNotFoundException
  {

     Scanner inFile = new Scanner(new FileReader ("C:\\desktop\\file.txt"));

     int first = inFile.nextInt();
     inFile.nextLine();

    for(int i=0; i < first ; i++)
    {
        String str = inFile.nextLine();
        String[] e = str.split("\\n");

        String name = e[0];
        int tickets= Integer.parseInt(e[1]); //this is where it throw an error ArrayIndexOutOfBoundsException, i read about it and I still don't understand

        Party newParty = new Party(name, tickets);
        System.out.println(name+ " " + tickets);
    }

This is my SingleParty Class:

public class SingleParty
{
    private String name;
    private int tickets;

    public Party(String newName, int newTickets)
    {
        newName = name;
        newTickets = tickets;

    }

Can someone explain to me how could I approach this error?

Thank you