问:
Memory allocation for union in C
I was recently studying union and end up with a confusion even after reading a lot about it.

```<code>#include<stdio.h>
union test
{
    int x;
    char arr[4];
    int y;
};

int main()
{
    union test t;
    t.x = 0;
    t.arr[1] = 'G';
    printf("%s\n", t.arr);
    printf("%d\n",t.x);
    return 0;
}
</code>```

What I understood is :

Since x and arr[4] share the same memory, when we set x = 0, all characters of arr are set as 0. 0 is ASCII value of '\0'. When we do "t.arr[1] = 'G'", arr[] becomes "\0G\0\0". When we print a string using "%s", the printf function starts from the first character and keeps printing till it finds a \0. Since the first character itself is \0, nothing is printed.

What I don't get is second printf statement

Now since arr[] is "\0G\0\0" , the same location is shared with x and y.
So what I think x to be is the following

00000000 01000111 00000000 00000000 ("\0G\0\0")

so t.x should print 4653056.
But what it's printing is 18176.

Where am I going wrong?

Is this technically undefined or is it due to some silly mistake or am I missing some concept??

Title: Memory allocation for union in C

Body:
I was recently studying union and end up with a confusion even after reading a lot about it.

#include<stdio.h>
union test
{
    int x;
    char arr[4];
    int y;
};

int main()
{
    union test t;
    t.x = 0;
    t.arr[1] = 'G';
    printf("%s\n", t.arr);
    printf("%d\n",t.x);
    return 0;
}

What I understood is :

Since x and arr[4] share the same memory, when we set x = 0, all characters of arr are set as 0. 0 is ASCII value of '\0'. When we do "t.arr[1] = 'G'", arr[] becomes "\0G\0\0". When we print a string using "%s", the printf function starts from the first character and keeps printing till it finds a \0. Since the first character itself is \0, nothing is printed.

What I don't get is second printf statement

Now since arr[] is "\0G\0\0" , the same location is shared with x and y.
So what I think x to be is the following

00000000 01000111 00000000 00000000 ("\0G\0\0")

so t.x should print 4653056.
But what it's printing is 18176.

Where am I going wrong?

Is this technically undefined or is it due to some silly mistake or am I missing some concept??

Body:
All members of Union will share the same common memory. assume starting address of union is 0x100.
when you wrote  t.x = 0; whole 4 bytes got initialize with zero as

-------------------------------------------------
| 0000 0000 | 0000 0000 | 0000 0000 | 0000 0000  |
-------------------------------------------------
0x104     0x103       0x102        0x101        0x100
                                                 x,arr,y

when you are writing t.arr[1] = 'G'; arr[1] will overwritten with 'G' ascii value, it looks like

-------------------------------------------------
| 0000 0000 | 0000 0000 | 0100 0111 | 0000 0000  |
-------------------------------------------------
0x104     0x103       0x102        0x101        0x100

now calculates this value which is 18176.


来源: stackexchange

问:
Angular 5 WebStorm Run Configuration
I'm surprised to see Angular does not yet have an entry in Jet Brain's IDE, WebStorm, which run config do you guys use?

I want to execute: ng serve

but Maybe there's a better option?

one like vue's npm run dev which opens up a page in your default browser at the served address?

this page didn't hit run configs, https://www.jetbrains.com/help/webstorm/angular.html

UPDATE :

for clarification I'm talking about making a one click run button like you can for react and vue apps :

答:
Please see https://blog.jetbrains.com/webstorm/2017/01/debugging-angular-apps/ for instructions on debugging Angular apps in WebStorm.

right-click your package.json, choose Show NPM Scripts

in NPM tool window, click the start script to start the app

create a new JavaScript debug configuration (Run –> Edit configurations… –> Add –> JavaScript Debug), etter http://localhost:4200/ into the URL field, press Debug

ContentLicense: CC BY-SA 3.0

Title: Angular 5 WebStorm Run Configuration


问:
Ionic 2 - Google Maps Native: marker click event not firing
I am using Ionic 2 and the google maps cordova plugin.

"cordova-plugin-googlemaps": "^2.0.11"

I cannot get this listener to fire.

The marker is added to the map but the click event does not fire the alert.

Thanks for the help!

```<code>    let latlng = new LatLng(spot.lat, spot.long);
    let markerOptions: MarkerOptions = {
        'position': latlng,
        'animation': 'drop'
      };

      this.map.addMarker(markerOptions).then((marker: Marker) => {
        marker.addEventListener(GoogleMapsEvent.MARKER_CLICK).subscribe(e => {
          alert('foo');
        });
      });
</code>```

Additional Information

@ionic-native/core: 'version': 3.7.0

@ionic-native/google-maps: 'version': '4.3.0'

import {
 GoogleMaps,
 GoogleMap,
 GoogleMapsEvent,
 GoogleMapOptions,
 CameraPosition,
 MarkerOptions,
 LatLng,
 Marker
} from '@ionic-native/google-maps';

I am looping through multiple lat long coordinates and adding them to the map. The event never gets fired for any of them.

When I try to attach the even to just one of the markers it does not work either.

Lastly if I put another alert it does not fire. Is it possible the add marker promise is not resolving?

```<code>this.map.addMarker(markerOptions).then((marker: Marker) => {
   alert('in here');
 marker.addEventListener(GoogleMapsEvent.MARKER_CLICK).subscribe(e => {
   alert('foo');
 });
});
</code>```

答:
You need to use @ionic-native/core@4.4.0 and @ionic-native/google-maps@4.4.0.
At least @ionic-native/core@3.7.0 is too old.

```<code>$> npm uninstall @ionic-native/core @ionic-native/google-maps
$> cordova plugin rm cordova-plugin-googlemaps

$> npm install @ionic-native/core@latest @ionic-native/googlemaps@latest
$> cordova plugin add cordova-plugin-googlemaps --variable API_KEY_FOR_ANDROID="..." --variable API_KEY_FOR_IOS="..." --no-fetch
</code>```

From the @ionic-native/google-maps@4.4.0, the way of creating a map is changed.

```<code>export class HomePage {

  map: GoogleMap;

  constructor() {  // <-- no longer need to define in constructor
  }

  ionViewDidLoad() {
    this.loadMap();
  }

  loadMap() {
    this.map = GoogleMaps.create('map_canvas');  // <-- changed
    this.map.one(GoogleMapsEvent.MAP_READY).then(() => {
      ...
    });
  }
}
</code>```

Body:
I am using Ionic 2 and the google maps cordova plugin.

"cordova-plugin-googlemaps": "^2.0.11"

I cannot get this listener to fire.

The marker is added to the map but the click event does not fire the alert.

Thanks for the help!

    let latlng = new LatLng(spot.lat, spot.long);
    let markerOptions: MarkerOptions = {
        'position': latlng,
        'animation': 'drop'
      };

      this.map.addMarker(markerOptions).then((marker: Marker) => {
        marker.addEventListener(GoogleMapsEvent.MARKER_CLICK).subscribe(e => {
          alert('foo');
        });
      });

Additional Information

@ionic-native/core: 'version': 3.7.0

@ionic-native/google-maps: 'version': '4.3.0'

import {
 GoogleMaps,
 GoogleMap,
 GoogleMapsEvent,
 GoogleMapOptions,
 CameraPosition,
 MarkerOptions,
 LatLng,
 Marker
} from '@ionic-native/google-maps';

I am looping through multiple lat long coordinates and adding them to the map. The event never gets fired for any of them.

When I try to attach the even to just one of the markers it does not work either.

Lastly if I put another alert it does not fire. Is it possible the add marker promise is not resolving?

this.map.addMarker(markerOptions).then((marker: Marker) => {
   alert('in here');
 marker.addEventListener(GoogleMapsEvent.MARKER_CLICK).subscribe(e => {
   alert('foo');
 });
});

Body:
You need to use @ionic-native/core@4.4.0 and @ionic-native/google-maps@4.4.0.
At least @ionic-native/core@3.7.0 is too old.

$> npm uninstall @ionic-native/core @ionic-native/google-maps
$> cordova plugin rm cordova-plugin-googlemaps

$> npm install @ionic-native/core@latest @ionic-native/googlemaps@latest
$> cordova plugin add cordova-plugin-googlemaps --variable API_KEY_FOR_ANDROID="..." --variable API_KEY_FOR_IOS="..." --no-fetch

From the @ionic-native/google-maps@4.4.0, the way of creating a map is changed.

export class HomePage {

  map: GoogleMap;

  constructor() {  // <-- no longer need to define in constructor
  }

  ionViewDidLoad() {
    this.loadMap();
  }

  loadMap() {
    this.map = GoogleMaps.create('map_canvas');  // <-- changed
    this.map.one(GoogleMapsEvent.MAP_READY).then(() => {
      ...
    });
  }
}


问:
Passing variables to map function
I'm trying to send a few longitude and latitude variables to a function that will then generate a Google Map.

Starting with a datatable that retrieves various information stored in a database, I'm using data-attributes to store the lng and lat for each record.  When a record is selected, a modal opens and the map is displayed.

I was able to get the map to display with default lng and lat points.  But now I need to create a new map every time a record is selected.

Starting with the onclick event that triggers the modal to open (shortened as much as possible):

```<code>$('#example1').on('click', 'tr > td > a.actionMatch', function(e)
{
  e.preventDefault();

  var actimpbill = $(this).attr('data-actimpbill'); // random record info
  var actramplat = parseFloat($(this).attr('data-actramplat')); // first lat
  var actramplng = parseFloat($(this).attr('data-actramplng')); // first lng
  var actdellat = parseFloat($(this).attr('data-actdellat')); // second lat
  var actdellng = parseFloat($(this).attr('data-actdellng')); // second lng

  // my map was opening in a grey box. this next piece of code fixed that
  $("#actionMatchbackModal").on("shown.bs.modal", function () {
    google.maps.event.trigger(map, "resize");
  });

  initMap(actramplat, actramplng, actdellat, actdellng); // my attempt to call a function and the variables to it

  $('#actionMatchbackModal').modal('show'); // show the modal
});
</code>```

Here is the function that sets the map. This is located outside of the initial onclick event that opens the modal (I'm not sure if that's a problem).  This is where I'm trying to pass the variables that I created inside the onclick event:

```<code>function initMap(actramplat, actramplng, actdellat, actdellng)
{
  // map options
  var options = {
    zoom: 8,
    center: {actramplat, actramplng}
  }

  // new map
  var map = new google.maps.Map(document.getElementById('map'), options);

  // add marker
  var marker = new google.maps.Marker({
    position:{actdellat, actdellng},
    map: map
  });
}
</code>```

I am probably butchering the function call.  The function once housed the default lat and lng numbers and I was able to properly generate a map.

Edit

I just checked the console, and I am getting these errors:

```<code>InvalidValueError: setCenter: not a LatLng or LatLngLiteral: in property lat: not a number
InvalidValueError: setPosition: not a LatLng or LatLngLiteral: in property lat: not a number
</code>```

Edit

I just added parseFloat to the variables to ensure they are not strings, but still no success.

Edit

Here is what the data-attributes look like:

```<code><a href="#" class="actionMatch" id="actionMatch"
data-toggle="modal" data-actimpbill="xxxxxxxx"
data-actramplat="39.11" data-actramplng="-94.63"
data-actdellat="39.03" data-actdellng="-96.83"
data-actreclat="39.84" data-actreclng="-96.65"
rel="tooltip" data-placement="right" title="Action Matchback"></a>
</code>```

You can see the actramplat, actramplng, actdellat, actdellng in the A tag above.

答:
Looking at their API, they expect lat/long values to be provided as an object literal that looks like this: var myLatLng = {lat: -25.363, lng: 131.044};

So you need to call it like this:

```<code>// map options
  var options = {
    zoom: 8,
    center: {lat: dellat, lng: dellng}
  }

  // new map
  var map = new google.maps.Map(document.getElementById('map'), options);

  // add marker
  var marker = new google.maps.Marker({
    position:{lat: reclat, lng: reclng},
    map: map
  });
</code>```

ContentLicense: CC BY-SA 4.0

Title: Passing variables to map function

Body:
I'm trying to send a few longitude and latitude variables to a function that will then generate a Google Map.

Starting with a datatable that retrieves various information stored in a database, I'm using data-attributes to store the lng and lat for each record.  When a record is selected, a modal opens and the map is displayed.

I was able to get the map to display with default lng and lat points.  But now I need to create a new map every time a record is selected.

Starting with the onclick event that triggers the modal to open (shortened as much as possible):

$('#example1').on('click', 'tr > td > a.actionMatch', function(e)
{
  e.preventDefault();

  var actimpbill = $(this).attr('data-actimpbill'); // random record info
  var actramplat = parseFloat($(this).attr('data-actramplat')); // first lat
  var actramplng = parseFloat($(this).attr('data-actramplng')); // first lng
  var actdellat = parseFloat($(this).attr('data-actdellat')); // second lat
  var actdellng = parseFloat($(this).attr('data-actdellng')); // second lng

  // my map was opening in a grey box. this next piece of code fixed that
  $("#actionMatchbackModal").on("shown.bs.modal", function () {
    google.maps.event.trigger(map, "resize");
  });

  initMap(actramplat, actramplng, actdellat, actdellng); // my attempt to call a function and the variables to it

  $('#actionMatchbackModal').modal('show'); // show the modal
});

Here is the function that sets the map. This is located outside of the initial onclick event that opens the modal (I'm not sure if that's a problem).  This is where I'm trying to pass the variables that I created inside the onclick event:

function initMap(actramplat, actramplng, actdellat, actdellng)
{
  // map options
  var options = {
    zoom: 8,
    center: {actramplat, actramplng}
  }

  // new map
  var map = new google.maps.Map(document.getElementById('map'), options);

  // add marker
  var marker = new google.maps.Marker({
    position:{actdellat, actdellng},
    map: map
  });
}

I am probably butchering the function call.  The function once housed the default lat and lng numbers and I was able to properly generate a map.

Edit

I just checked the console, and I am getting these errors:

InvalidValueError: setCenter: not a LatLng or LatLngLiteral: in property lat: not a number
InvalidValueError: setPosition: not a LatLng or LatLngLiteral: in property lat: not a number

Edit

I just added parseFloat to the variables to ensure they are not strings, but still no success.

Edit

Here is what the data-attributes look like:

You can see the actramplat, actramplng, actdellat, actdellng in the A tag above.

Body:
Looking at their API, they expect lat/long values to be provided as an object literal that looks like this: var myLatLng = {lat: -25.363, lng: 131.044};

So you need to call it like this:

// map options
  var options = {
    zoom: 8,
    center: {lat: dellat, lng: dellng}
  }

  // new map
  var map = new google.maps.Map(document.getElementById('map'), options);

  // add marker
  var marker = new google.maps.Marker({
    position:{lat: reclat, lng: reclng},
    map: map
  });


问:
Django Rest Framework Testing response headers
I am trying to create automated tests and what I want is to check in my TestCase if there is a location header which it should be based on my code in views.py(Already tested it in Advanced REST Client). However, I can not to parse it in my tests.py

Here is my code:

```<code>from rest_framework import status
from rest_framework.test import APITestCase
url_1 = reverse('artists-list')

class ArtistTest(APITestCase):
    # Check the response if there is no data
    def test_get(self):
        # Checks the artists
        # self.client attribute will be an APIClient instance
        # Basically it will act as a client
        response = self.client.get(url_1)
        self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)
        self.assertEqual(response.content, '') # There should be no data
        # self.assertEqual(len(data), 0)
        # print ("%s.%s DONE - 1" % (self.__class__.__name__, inspect.stack()[0][3]))

    def test_post(self):
        _data = {"name": "50 Cent", "birth_date":"2005-02-13"}
        response = self.client.post(url_1, _data)
        print "----"
        print response.headers
        data = json.loads(response.content)["data"]
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)
        self.assertEqual(data, _data)
        self.assertEqual(Artist.objects.count(), 1)
        self.assertEqual(Artist.objects.get().name, '50 Cent')
</code>```

P.S.

Please be aware that:

```<code>print response.headers # this throws an error
print response # shows the header but I want it to be parsed
</code>```

答:
There are several options:</p>

```<code>>>> response.has_header('Location')
True

>>> response.get('Location')  # None if key not in headers
My location

>>> response['Location']  # KeyError if key doesn't exist
My location

>>> response._headers  # headers as dict
{'allow': ('Allow', 'GET, POST, HEAD, OPTIONS'), 'Location': ...}

>>> response.serialize_headers()  # headers as bytestring (in Python 3)
b'Allow: GET, POST, HEAD, OPTIONS\r\nLocation: ...'
</code>```

Body:
I am trying to create automated tests and what I want is to check in my TestCase if there is a location header which it should be based on my code in views.py(Already tested it in Advanced REST Client). However, I can not to parse it in my tests.py

Here is my code:

from rest_framework import status
from rest_framework.test import APITestCase
url_1 = reverse('artists-list')

class ArtistTest(APITestCase):
    # Check the response if there is no data
    def test_get(self):
        # Checks the artists
        # self.client attribute will be an APIClient instance
        # Basically it will act as a client
        response = self.client.get(url_1)
        self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)
        self.assertEqual(response.content, '') # There should be no data
        # self.assertEqual(len(data), 0)
        # print ("%s.%s DONE - 1" % (self.__class__.__name__, inspect.stack()[0][3]))

    def test_post(self):
        _data = {"name": "50 Cent", "birth_date":"2005-02-13"}
        response = self.client.post(url_1, _data)
        print "----"
        print response.headers
        data = json.loads(response.content)["data"]
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)
        self.assertEqual(data, _data)
        self.assertEqual(Artist.objects.count(), 1)
        self.assertEqual(Artist.objects.get().name, '50 Cent')

P.S.

Please be aware that:

print response.headers # this throws an error
print response # shows the header but I want it to be parsed

Body:
There are several options:

>>> response.has_header('Location')
True

>>> response.get('Location')  # None if key not in headers
My location

>>> response['Location']  # KeyError if key doesn't exist
My location

>>> response._headers  # headers as dict
{'allow': ('Allow', 'GET, POST, HEAD, OPTIONS'), 'Location': ...}

>>> response.serialize_headers()  # headers as bytestring (in Python 3)
b'Allow: GET, POST, HEAD, OPTIONS\r\nLocation: ...'


问:
How many levels of inheritance
Are there any best practices regarding the maximum depth of the inheritance hierarchy for a framework and guidelines when to use multiple levels of inheritance or join them in a single class?

Some references to established practices/examples that worked well in the Java world would be nice in the answers as this is from the perspective of the community and frameworks surrounding Java.

答:
You may be looking for a nice rule like "not more then 5 levels of inheritance" but I really doubt that there is such a rule. Objects usually model real world entities and the community of all those entities never agreed on a rule (as far as I know)...

One "best practice" is definitly: favor composition over inheritance. Following this guideline: define one interface and implementations with no further superclasses. All common fields and methods come with behaviour and strategies

On the other hand, we sometime model real world entities or structurs that already come with a deep hierarchy of entities. Classification of animals is one example or algebraic structures. A framework to model such existing structures would require a deep class hierarchy because it should follow the real world just to be understandable.

ContentLicense: CC BY-SA 2.5

Title: How many levels of inheritance


问:
How can I pop this letter if it exists based on this algorithm?
I'm trying to pop any letters given by the user, for example if they give you a keyword "ROSES" then these letters should be popped out of the list.

Note: I have a lot more explanation after the SOURCE CODE

SOURCE CODE

```<code>  alphabet = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]
        encrypted_message = []
        key_word = str(input("Please enter a word:"))
        key_word = list(key_word)
        #print(key_word)

        check_for_dup = 0

        for letter in key_word:
            for character in alphabet:
                if letter in character:
                    check_for_dup +=1
                    alphabet.pop(check_for_dup)

        print(alphabet)
        print(encrypted_message)
</code>```

SAMPLE INPUT

Let's say keyword is "Roses"

this what it gives me a list of the following ['A', 'C', 'E', 'G', 'I', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']

But that's wrong It should of just removed the characters that existed in the keyword given by the user, like the word "Roses" each letter should of been removed and not in the list being popped. as you can see in the list the letters "B","D","F","H",etc were gone. What I'm trying to do is pop the index of the alphabet letters that the keyword exists.

this is what should of happened.

["A","B","C","D","F","G","H","I","J","K","L","M","N","P","Q","T","U","V","W","X","Y","Z"]

The letters of the keyword "ROSES" were deleted of the list

答:
```<code>' '.join(alphabet).translate({ord(c): "" for c in keyword}).split()
</code>```

Body:
I'm trying to pop any letters given by the user, for example if they give you a keyword "ROSES" then these letters should be popped out of the list.

Note: I have a lot more explanation after the SOURCE CODE

SOURCE CODE

  alphabet = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]
        encrypted_message = []
        key_word = str(input("Please enter a word:"))
        key_word = list(key_word)
        #print(key_word)

        check_for_dup = 0

        for letter in key_word:
            for character in alphabet:
                if letter in character:
                    check_for_dup +=1
                    alphabet.pop(check_for_dup)

        print(alphabet)
        print(encrypted_message)

SAMPLE INPUT

Let's say keyword is "Roses"

this what it gives me a list of the following ['A', 'C', 'E', 'G', 'I', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']

But that's wrong It should of just removed the characters that existed in the keyword given by the user, like the word "Roses" each letter should of been removed and not in the list being popped. as you can see in the list the letters "B","D","F","H",etc were gone. What I'm trying to do is pop the index of the alphabet letters that the keyword exists.

this is what should of happened.

["A","B","C","D","F","G","H","I","J","K","L","M","N","P","Q","T","U","V","W","X","Y","Z"]

The letters of the keyword "ROSES" were deleted of the list


问:
Initializing *ngFor with a new Array()
Angular v5

My search component retrieves data from a service returning a search result promise. On page load my "searchResults" array is empty (= new Array()) until the search is called in page and the promise is returned.

*ngFor is throwing an error because the above mentioned "searchResults" is empty on page load. How do I circumvent this until the search results are populated?

Service:

```<code>getSearchResults(searchTerm: string, resourceType: string, pageSize: number = 9999, pageNumber: number = 1): Promise<object> {
const search = {
  Term: searchTerm,
  ResourceType: resourceType,
  PageSize: pageSize,
  PageNum: pageNumber,
  ModuleId: moduleId
};
const searchHeader = {headers: this.getHttpHeaders()};
const promise = new Promise((resolve, reject): void => {
  this.http.post(this.apiRoot, search, searchHeader).toPromise()
    .then(response => {
      resolve(JSON.parse(response['_body']));
    })
    .catch(error => {
      reject(error);
    });
});
return promise;
}
</code>```

Component:

```<code>submitSearch(): void {
this.siteSearchService.getSearchResults(this.searchString, this.selectedResourceType)
  .then(response => {
    let dto: DTO.SearchResults = <DTO.SearchResults>response;
    this.totalHits = dto.TotalHits;
    this.searchResults = dto.Results;
  }).catch(error => {
    console.log(error);
  });
}
</code>```

Template:

```<code><div class="row" *ngIf="searchResults" style="margin:25px;">
    <div class="col-xs-12 result-row" *ngFor="let result in searchResults">
      <div class="row">
        <div class="col-xs-12 col-sm-10">
          <a href [href]="result.Url" target="_blank" class="search-result-link">
            <h3>{{result.Title}}</h3>
          </a>
          <p>{{result.Description}}</p>
        </div>
        <div class="col-xs-12 col-sm-2">
          ToDo: Button
        </div>
      </div>
    </div>
  </div>
</code>```

答:
My fix would be to use the async pipe. This will let Angular know to wait for the results to arrive before trying to loop with ngFor. I would turn searchResults into an observable that emits results at the end of each search.

In the view, emit an event each time the button is clicked:

```<code><input #searchInput />
<button (click)="searchSubject.next(searchInput.value)">Search</button>
</code>```

In the component class:

```<code>// Will emit each new search term when user clicks search button
searchSubject = new Subject<string>();

// Will trigger the search each time the searchSubject emits:
searchResults = searchSubject
                 .switchMap(term => this.siteSearchService.getSearchResults(term));
                 .map(response => response.Results)
                 .catch(err => console.error(err));
</code>```

Finally modify the template to use the pipe:

```<code><div *ngFor="let result of searchResults | async">
</code>```

The async pipe will subscribe to searchResults and start listening to the click event. Once your component is destroyed, Angular will unsubscribe for you.

Title: Initializing *ngFor with a new Array()

Body:
Angular v5

My search component retrieves data from a service returning a search result promise. On page load my "searchResults" array is empty (= new Array()) until the search is called in page and the promise is returned.

*ngFor is throwing an error because the above mentioned "searchResults" is empty on page load. How do I circumvent this until the search results are populated?

Service:

getSearchResults(searchTerm: string, resourceType: string, pageSize: number = 9999, pageNumber: number = 1): Promise<object> {
const search = {
  Term: searchTerm,
  ResourceType: resourceType,
  PageSize: pageSize,
  PageNum: pageNumber,
  ModuleId: moduleId
};
const searchHeader = {headers: this.getHttpHeaders()};
const promise = new Promise((resolve, reject): void => {
  this.http.post(this.apiRoot, search, searchHeader).toPromise()
    .then(response => {
      resolve(JSON.parse(response['_body']));
    })
    .catch(error => {
      reject(error);
    });
});
return promise;
}

Component:

submitSearch(): void {
this.siteSearchService.getSearchResults(this.searchString, this.selectedResourceType)
  .then(response => {
    let dto: DTO.SearchResults = <DTO.SearchResults>response;
    this.totalHits = dto.TotalHits;
    this.searchResults = dto.Results;
  }).catch(error => {
    console.log(error);
  });
}

Template:

{{result.Title}}

{{result.Description}}

          ToDo: Button

Body:
My fix would be to use the async pipe. This will let Angular know to wait for the results to arrive before trying to loop with ngFor. I would turn searchResults into an observable that emits results at the end of each search.

In the view, emit an event each time the button is clicked:

<input #searchInput />
<button (click)="searchSubject.next(searchInput.value)">Search</button>

In the component class:

// Will emit each new search term when user clicks search button
searchSubject = new Subject<string>();

// Will trigger the search each time the searchSubject emits:
searchResults = searchSubject
                 .switchMap(term => this.siteSearchService.getSearchResults(term));
                 .map(response => response.Results)
                 .catch(err => console.error(err));

Finally modify the template to use the pipe:

<div *ngFor="let result of searchResults | async">

The async pipe will subscribe to searchResults and start listening to the click event. Once your component is destroyed, Angular will unsubscribe for you.


问:
Error after upgrade Google Play Services to 11.0.0 version
I have a strange issue. After uploading Google Play Services library from version 10.2.6 to version 11.0.0, when i try to compile I get this error:

Error:Execution failed for task ':app:processDebugGoogleServices'.
   Please fix the version conflict either by updating the version of the google-services plugin (information about the latest version is available at https://bintray.com/android/android-tools/com.google.gms.google-services/) or updating the version of com.google.android.gms to 11.0.0.

I visited the link mentioned in the error and the last version of the google-services plugin seems to be 3.1.0, ie the version i am using, and i have already upgraded all the play services libraries to 11.0.0 version. What can I do to compile my code with 11.0.0 version of GMS?

Here's my build.gradle file (module scope):

```<code>apply plugin: 'com.android.application'
apply plugin: 'realm-android'

android {

    compileSdkVersion 25
    buildToolsVersion "25.0.2"
    defaultConfig {
        applicationId "com.example.app"
        minSdkVersion 15
        targetSdkVersion 25
        versionCode 23
        versionName "0.7.3.2"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        manifestPlaceholders = [onesignal_app_id               : "12345678-1234-1234-1234-123456789",
                            // Project number pulled from dashboard, local value is ignored.
                            onesignal_google_project_number: "REMOTE"]
        multiDexEnabled true
    }
    buildTypes {

        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

    productFlavors {
        prontopro {
            applicationId "com.example.app"
            buildConfigField "boolean", "TEST_ENVIRONMENT", "false"
        }

        prontoproTest {
            applicationId "com.example.app"
            buildConfigField "boolean", "TEST_ENVIRONMENT", "true"
        }
    }

    dataBinding {
        enabled = true
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    compile 'com.android.support:multidex:1.0.1'
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support:design:25.3.1'
    compile 'com.google.android.gms:play-services-places:11.0.0'
    compile 'com.google.android.gms:play-services-location:11.0.0'
    compile 'org.parceler:parceler-api:1.1.6'
    annotationProcessor 'org.parceler:parceler:1.1.6'
    annotationProcessor 'com.android.databinding:compiler:2.2.2'
    compile 'com.viewpagerindicator:library:2.4.1'
    compile 'com.squareup.retrofit2:retrofit:2.1.0'
    compile 'com.squareup.retrofit2:converter-gson:2.1.0'
    compile 'com.squareup.okhttp3:logging-interceptor:3.4.2'
    compile 'com.google.code.gson:gson:2.7'
    compile 'com.github.bumptech.glide:glide:3.7.0'
    compile 'com.github.chrisbanes:PhotoView:1.2.6'
    compile 'de.hdodenhof:circleimageview:2.1.0'
    compile 'com.facebook.android:facebook-android-sdk:[4,5)'
    compile 'io.realm:android-adapters:2.0.0'
    compile 'com.google.firebase:firebase-crash:10.2.6'
    //reactive libraries
    compile 'io.reactivex:rxandroid:1.2.1'
    compile 'io.reactivex:rxjava:1.2.3'
    compile 'com.jakewharton.rxbinding:rxbinding:1.0.0'
    compile 'com.jakewharton.rxbinding:rxbinding-support-v4:1.0.0'
    compile 'com.jakewharton.rxbinding:rxbinding-appcompat-v7:1.0.0'
    compile 'com.jakewharton.rxbinding:rxbinding-design:1.0.0'
    compile 'com.jakewharton.rxbinding:rxbinding-recyclerview-v7:1.0.0'
    compile 'com.tbruyelle.rxpermissions:rxpermissions:0.8.2@aar'
    compile 'com.squareup.retrofit2:adapter-rxjava:2.1.0'
    compile 'com.github.pwittchen:reactivenetwork:0.8.0'
    compile 'com.hwangjr.rxbus:rxbus:1.0.5'
    compile 'com.f2prateek.rx.preferences:rx-preferences:1.0.2'
    //testing
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    testCompile 'junit:junit:4.12'
    testCompile 'org.mockito:mockito-core:2.6.3'
    //onesignal
    compile 'com.onesignal:OneSignal:3.4.4@aar'
    compile "com.mixpanel.android:mixpanel-android:5.1.0"
    compile 'com.google.android.gms:play-services-gcm:11.0.0'
}
apply plugin: 'com.google.gms.google-services'
</code>```

And finally here's my build.gradle file (app scope):

```<code>// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.2'
        classpath 'io.realm:realm-gradle-plugin:3.1.4'
        classpath 'com.google.gms:google-services:3.1.0'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        maven { url "http://dl.bintray.com/populov/maven" }
        maven { url "https://jitpack.io" }
        mavenCentral()
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

答:
Try targeting directly the required servies like if you want to get SmsRetriver compile

```<code>compile 'com.google.android.gms:play-services-auth-api-phone:11.0.1'
</code>```

Rather Than

```<code>compile 'com.google.android.gms:play-services:11.0.1'
</code>```

Body:
I have a strange issue. After uploading Google Play Services library from version 10.2.6 to version 11.0.0, when i try to compile I get this error:

Error:Execution failed for task ':app:processDebugGoogleServices'.
   Please fix the version conflict either by updating the version of the google-services plugin (information about the latest version is available at https://bintray.com/android/android-tools/com.google.gms.google-services/) or updating the version of com.google.android.gms to 11.0.0.

I visited the link mentioned in the error and the last version of the google-services plugin seems to be 3.1.0, ie the version i am using, and i have already upgraded all the play services libraries to 11.0.0 version. What can I do to compile my code with 11.0.0 version of GMS?

Here's my build.gradle file (module scope):

apply plugin: 'com.android.application'
apply plugin: 'realm-android'

android {

    compileSdkVersion 25
    buildToolsVersion "25.0.2"
    defaultConfig {
        applicationId "com.example.app"
        minSdkVersion 15
        targetSdkVersion 25
        versionCode 23
        versionName "0.7.3.2"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        manifestPlaceholders = [onesignal_app_id               : "12345678-1234-1234-1234-123456789",
                            // Project number pulled from dashboard, local value is ignored.
                            onesignal_google_project_number: "REMOTE"]
        multiDexEnabled true
    }
    buildTypes {

        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

    productFlavors {
        prontopro {
            applicationId "com.example.app"
            buildConfigField "boolean", "TEST_ENVIRONMENT", "false"
        }

        prontoproTest {
            applicationId "com.example.app"
            buildConfigField "boolean", "TEST_ENVIRONMENT", "true"
        }
    }

    dataBinding {
        enabled = true
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    compile 'com.android.support:multidex:1.0.1'
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support:design:25.3.1'
    compile 'com.google.android.gms:play-services-places:11.0.0'
    compile 'com.google.android.gms:play-services-location:11.0.0'
    compile 'org.parceler:parceler-api:1.1.6'
    annotationProcessor 'org.parceler:parceler:1.1.6'
    annotationProcessor 'com.android.databinding:compiler:2.2.2'
    compile 'com.viewpagerindicator:library:2.4.1'
    compile 'com.squareup.retrofit2:retrofit:2.1.0'
    compile 'com.squareup.retrofit2:converter-gson:2.1.0'
    compile 'com.squareup.okhttp3:logging-interceptor:3.4.2'
    compile 'com.google.code.gson:gson:2.7'
    compile 'com.github.bumptech.glide:glide:3.7.0'
    compile 'com.github.chrisbanes:PhotoView:1.2.6'
    compile 'de.hdodenhof:circleimageview:2.1.0'
    compile 'com.facebook.android:facebook-android-sdk:[4,5)'
    compile 'io.realm:android-adapters:2.0.0'
    compile 'com.google.firebase:firebase-crash:10.2.6'
    //reactive libraries
    compile 'io.reactivex:rxandroid:1.2.1'
    compile 'io.reactivex:rxjava:1.2.3'
    compile 'com.jakewharton.rxbinding:rxbinding:1.0.0'
    compile 'com.jakewharton.rxbinding:rxbinding-support-v4:1.0.0'
    compile 'com.jakewharton.rxbinding:rxbinding-appcompat-v7:1.0.0'
    compile 'com.jakewharton.rxbinding:rxbinding-design:1.0.0'
    compile 'com.jakewharton.rxbinding:rxbinding-recyclerview-v7:1.0.0'
    compile 'com.tbruyelle.rxpermissions:rxpermissions:0.8.2@aar'
    compile 'com.squareup.retrofit2:adapter-rxjava:2.1.0'
    compile 'com.github.pwittchen:reactivenetwork:0.8.0'
    compile 'com.hwangjr.rxbus:rxbus:1.0.5'
    compile 'com.f2prateek.rx.preferences:rx-preferences:1.0.2'
    //testing
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    testCompile 'junit:junit:4.12'
    testCompile 'org.mockito:mockito-core:2.6.3'
    //onesignal
    compile 'com.onesignal:OneSignal:3.4.4@aar'
    compile "com.mixpanel.android:mixpanel-android:5.1.0"
    compile 'com.google.android.gms:play-services-gcm:11.0.0'
}
apply plugin: 'com.google.gms.google-services'

And finally here's my build.gradle file (app scope):

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.2'
        classpath 'io.realm:realm-gradle-plugin:3.1.4'
        classpath 'com.google.gms:google-services:3.1.0'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        maven { url "http://dl.bintray.com/populov/maven" }
        maven { url "https://jitpack.io" }
        mavenCentral()
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

Body:
Try targeting directly the required servies like if you want to get SmsRetriver compile

compile 'com.google.android.gms:play-services-auth-api-phone:11.0.1'

Rather Than

compile 'com.google.android.gms:play-services:11.0.1'


问:
Using AudioKit's AKHighPassFilter to filter frequencies
I'm attempting to filter out frequencies below a specified threshold with AudioKit. I'm using AKHighPassFilter to accomplish this.

```<code>func playSound(duration: Int, frequencyRange: Range<Double>) {

    generator = AKOperationGenerator() { parameters in

        let volume = AKOperation.sineWave(frequency: parameters[0]).scale(minimum: 0, maximum: 0.1)
        let jitter = AKOperation.jitter(amplitude: parameters[1], minimumFrequency: lowerFrequency, maximumFrequency: upperFrequency)

        return AKOperation.sineWave(frequency: jitter, amplitude: volume)
    }

    generator!.parameters = [baseFrequency, amplitude]

    // Exception thrown at this line after method called 1 time
    var highPassFilter = AKHighPassFilter(generator)
    highPassFilter.cutoffFrequency = frequencyRange.lowerBound
    highPassFilter.resonance = 0

    AudioKit.output = highPassFilter
    AudioKit.start()

    generator?.play()
}
</code>```

The first time I call playSound(duration:, frequencyRange:), it works fine. Once I stop AudioKit and attempt to play a sound a second time, an exception is thrown at this line:

```<code>var highPassFilter = AKHighPassFilter(generator)
</code>```

Here is the console output from the crash:

```<code>2017-05-01 14:32:01.169 MyApp[18123:3459824] *** Terminating app due to uncaught exception 'com.apple.coreaudio.avfaudio', reason: 'required condition is false: [_nodes containsObject: node]'
*** First throw call stack:
(
    0   CoreFoundation                      0x0000000109ea7b0b __exceptionPreprocess + 171
    1   libobjc.A.dylib                     0x000000010990c141 objc_exception_throw + 48
    2   CoreFoundation                      0x0000000109eabcf2 +[NSException raise:format:arguments:] + 98
    3   AVFAudio                            0x000000010cdc3a9e _Z19AVAE_RaiseExceptionP8NSStringz + 158
    4   AVFAudio                            0x000000010cdc9cbb _ZN17AVAudioEngineImpl10DetachNodeEP11AVAudioNodeb + 421
    5   AVFAudio                            0x000000010cdc9ad0 -[AVAudioEngine detachNode:] + 67
    6   AudioKit                            0x0000000108d3bee4 _TToFC8AudioKit6AKNodeD + 84
    7   libobjc.A.dylib                     0x0000000109920b8e _ZN11objc_object17sidetable_releaseEb + 202
    8   AudioKit                            0x0000000108d39a99 _TToFC8AudioKit16AKHighPassFilterE + 25
    9   libobjc.A.dylib                     0x000000010990a9bc _ZL27object_cxxDestructFromClassP11objc_objectP10objc_class + 127
    10  libobjc.A.dylib                     0x0000000109916d34 objc_destructInstance + 129
    11  libobjc.A.dylib                     0x0000000109916d66 object_dispose + 22
    12  AudioKit                            0x0000000108d3bf1b _TToFC8AudioKit6AKNodeD + 139
    13  libobjc.A.dylib                     0x0000000109920b8e _ZN11objc_object17sidetable_releaseEb + 202
    14  MyApp                             0x00000001087301ec _TFC7MyApp11SoundPlayerClass9playSoundfT8durationSi14frequencyRangeGVs5RangeSd__T_ + 988
    15  MyApp                             0x000000010873a1a4 _TFC7MyApp18MainViewController13playFrequencyfCS_12FrostyButtonT_ + 2276
    16  MyApp                             0x000000010873a4fa _TToFC7MyApp18MainViewController13playFrequencyfCS_12FrostyButtonT_ + 58
    17  UIKit                               0x000000010ab63d22 -[UIApplication sendAction:to:from:forEvent:] + 83
    18  UIKit                               0x000000010ace825c -[UIControl sendAction:to:forEvent:] + 67
    19  UIKit                               0x000000010ace8577 -[UIControl _sendActionsForEvents:withEvent:] + 450
    20  UIKit                               0x000000010ace74b2 -[UIControl touchesEnded:withEvent:] + 618
    21  UIKit                               0x000000010abd149a -[UIWindow _sendTouchesForEvent:] + 2707
    22  UIKit                               0x000000010abd2bb0 -[UIWindow sendEvent:] + 4114
    23  UIKit                               0x000000010ab7f7b0 -[UIApplication sendEvent:] + 352
    24  UIKit                               0x000000011e3c075c -[UIApplicationAccessibility sendEvent:] + 85
    25  UIKit                               0x000000010b362adc __dispatchPreprocessedEventFromEventQueue + 2926
    26  UIKit                               0x000000010b35aa3a __handleEventQueue + 1122
    27  UIKit                               0x000000010b35bd08 __handleEventQueue + 5936
    28  CoreFoundation                      0x0000000109e4dc01 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17
    29  CoreFoundation                      0x0000000109e330cf __CFRunLoopDoSources0 + 527
    30  CoreFoundation                      0x0000000109e325ff __CFRunLoopRun + 911
    31  CoreFoundation                      0x0000000109e32016 CFRunLoopRunSpecific + 406
    32  GraphicsServices                    0x000000010ecd4a24 GSEventRunModal + 62
    33  UIKit                               0x000000010ab620d4 UIApplicationMain + 159
    34  MyApp                             0x000000010872cb77 main + 55
    35  libdyld.dylib                       0x000000010fbaf65d start + 1
    36  ???                                 0x0000000000000001 0x0 + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
</code>```

Prior to adding AKHighPassFilter, the method worked fine. I welcome suggestions re: how to resolve this crash. Thank you for reading.

答: I think the main problem here is that you are recreating all your objects on every playSound call as well as setting the AudioKit.output in your play method everytime it's called. What you want to do is to create your object chain in an initialization routine, then just change parameters as needed after that. All the connections only need to be established once. One technique is to use AKMixer as your input or output and add and remove nodes from it. For example a high pass filter could be filters the output of an AKMixer. This mixer could have any number of nodes attached to it. AVAudioEngine can be somewhat touchy about nodes removed or added when it's running.</p>

Body:
I'm attempting to filter out frequencies below a specified threshold with AudioKit. I'm using AKHighPassFilter to accomplish this.

func playSound(duration: Int, frequencyRange: Range<Double>) {

    generator = AKOperationGenerator() { parameters in

        let volume = AKOperation.sineWave(frequency: parameters[0]).scale(minimum: 0, maximum: 0.1)
        let jitter = AKOperation.jitter(amplitude: parameters[1], minimumFrequency: lowerFrequency, maximumFrequency: upperFrequency)

        return AKOperation.sineWave(frequency: jitter, amplitude: volume)
    }

    generator!.parameters = [baseFrequency, amplitude]

    // Exception thrown at this line after method called 1 time
    var highPassFilter = AKHighPassFilter(generator)
    highPassFilter.cutoffFrequency = frequencyRange.lowerBound
    highPassFilter.resonance = 0

    AudioKit.output = highPassFilter
    AudioKit.start()

    generator?.play()
}

The first time I call playSound(duration:, frequencyRange:), it works fine. Once I stop AudioKit and attempt to play a sound a second time, an exception is thrown at this line:

var highPassFilter = AKHighPassFilter(generator)

Here is the console output from the crash:

2017-05-01 14:32:01.169 MyApp[18123:3459824] *** Terminating app due to uncaught exception 'com.apple.coreaudio.avfaudio', reason: 'required condition is false: [_nodes containsObject: node]'
*** First throw call stack:
(
    0   CoreFoundation                      0x0000000109ea7b0b __exceptionPreprocess + 171
    1   libobjc.A.dylib                     0x000000010990c141 objc_exception_throw + 48
    2   CoreFoundation                      0x0000000109eabcf2 +[NSException raise:format:arguments:] + 98
    3   AVFAudio                            0x000000010cdc3a9e _Z19AVAE_RaiseExceptionP8NSStringz + 158
    4   AVFAudio                            0x000000010cdc9cbb _ZN17AVAudioEngineImpl10DetachNodeEP11AVAudioNodeb + 421
    5   AVFAudio                            0x000000010cdc9ad0 -[AVAudioEngine detachNode:] + 67
    6   AudioKit                            0x0000000108d3bee4 _TToFC8AudioKit6AKNodeD + 84
    7   libobjc.A.dylib                     0x0000000109920b8e _ZN11objc_object17sidetable_releaseEb + 202
    8   AudioKit                            0x0000000108d39a99 _TToFC8AudioKit16AKHighPassFilterE + 25
    9   libobjc.A.dylib                     0x000000010990a9bc _ZL27object_cxxDestructFromClassP11objc_objectP10objc_class + 127
    10  libobjc.A.dylib                     0x0000000109916d34 objc_destructInstance + 129
    11  libobjc.A.dylib                     0x0000000109916d66 object_dispose + 22
    12  AudioKit                            0x0000000108d3bf1b _TToFC8AudioKit6AKNodeD + 139
    13  libobjc.A.dylib                     0x0000000109920b8e _ZN11objc_object17sidetable_releaseEb + 202
    14  MyApp                             0x00000001087301ec _TFC7MyApp11SoundPlayerClass9playSoundfT8durationSi14frequencyRangeGVs5RangeSd__T_ + 988
    15  MyApp                             0x000000010873a1a4 _TFC7MyApp18MainViewController13playFrequencyfCS_12FrostyButtonT_ + 2276
    16  MyApp                             0x000000010873a4fa _TToFC7MyApp18MainViewController13playFrequencyfCS_12FrostyButtonT_ + 58
    17  UIKit                               0x000000010ab63d22 -[UIApplication sendAction:to:from:forEvent:] + 83
    18  UIKit                               0x000000010ace825c -[UIControl sendAction:to:forEvent:] + 67
    19  UIKit                               0x000000010ace8577 -[UIControl _sendActionsForEvents:withEvent:] + 450
    20  UIKit                               0x000000010ace74b2 -[UIControl touchesEnded:withEvent:] + 618
    21  UIKit                               0x000000010abd149a -[UIWindow _sendTouchesForEvent:] + 2707
    22  UIKit                               0x000000010abd2bb0 -[UIWindow sendEvent:] + 4114
    23  UIKit                               0x000000010ab7f7b0 -[UIApplication sendEvent:] + 352
    24  UIKit                               0x000000011e3c075c -[UIApplicationAccessibility sendEvent:] + 85
    25  UIKit                               0x000000010b362adc __dispatchPreprocessedEventFromEventQueue + 2926
    26  UIKit                               0x000000010b35aa3a __handleEventQueue + 1122
    27  UIKit                               0x000000010b35bd08 __handleEventQueue + 5936
    28  CoreFoundation                      0x0000000109e4dc01 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17
    29  CoreFoundation                      0x0000000109e330cf __CFRunLoopDoSources0 + 527
    30  CoreFoundation                      0x0000000109e325ff __CFRunLoopRun + 911
    31  CoreFoundation                      0x0000000109e32016 CFRunLoopRunSpecific + 406
    32  GraphicsServices                    0x000000010ecd4a24 GSEventRunModal + 62
    33  UIKit                               0x000000010ab620d4 UIApplicationMain + 159
    34  MyApp                             0x000000010872cb77 main + 55
    35  libdyld.dylib                       0x000000010fbaf65d start + 1
    36  ???                                 0x0000000000000001 0x0 + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException

Prior to adding AKHighPassFilter, the method worked fine. I welcome suggestions re: how to resolve this crash. Thank you for reading.


问:
different login pages in root web.config file for authentication
how can i specify two different login pages in root web.config file since i need to have authentication for two folders.for securing My Account module i did like this in the root folder

i need to have it for another folder called EBox also.

答:
I guess your problem is similar to the following one (which has an approved solution):

How to override/change FormsAuthentication LoginUrl in certain cases

Hope this will help you.


问:
Java : Dirty Check for ArrayList?
How can I perform a dirty check on an ArrayList in Java?

I have an object

```<code>Animal
{
    String animalName;
    String animalType;
    String animalPlace
}
</code>```

I have two lists:

```<code>List<Animal> animalList1 = new ArrayList<Animal>();
List<Animal> animalList2 = new ArrayList<Animal>();
</code>```

In the first list,
I have the values:

```<code>[0][lion,Carnivorous,Africa]
[1][tiger,Carnivorous,Zambia]
[2][Goat,Herbivorous,Zimbabwe]
</code>```

In the second list,
I have the values:

```<code>[0][lion,Carnivorous,Africa]
[1][tiger,Carnivorous,Zambia]
[2][Goat,Herbivorous,Norway]
</code>```

In the second list,
the animalPlace for the element at index 2 has changed from Zimbabwe to Norway.
How do I compare the two list values and the values which have changed put that object in a separate list?

```<code>List<Animal> animalList3 = new ArrayList<Animal>();

[0] [Goat,Herbivorous,Norway]
</code>```

I know the traditional way of doing it by comparing the list using a for loop:

```<code>for (int i = 0; i < list1.size(); i++)
{
  for (int j = i+1; j < list2.size(); j++)
  {
    // compare list1 and list2 values
  }
}
</code>```

Is there any faster and/or better way?

答:
The List#removeAll() method is your friend.

Implement equals() and hashCode() for Animal, and then:

```<code>List<Animal> animalList3 = new ArrayList<Animal>(animalList2);
animalList3.removeAll(animalList1);
</code>```

Title: Java : Dirty Check for ArrayList?

Body:
How can I perform a dirty check on an ArrayList in Java?

I have an object

Animal
{
    String animalName;
    String animalType;
    String animalPlace
}

I have two lists:

List<Animal> animalList1 = new ArrayList<Animal>();
List<Animal> animalList2 = new ArrayList<Animal>();

In the first list,
I have the values:

[0][lion,Carnivorous,Africa]
[1][tiger,Carnivorous,Zambia]
[2][Goat,Herbivorous,Zimbabwe]

In the second list,
I have the values:

[0][lion,Carnivorous,Africa]
[1][tiger,Carnivorous,Zambia]
[2][Goat,Herbivorous,Norway]

In the second list,
the animalPlace for the element at index 2 has changed from Zimbabwe to Norway.
How do I compare the two list values and the values which have changed put that object in a separate list?

List<Animal> animalList3 = new ArrayList<Animal>();

[0] [Goat,Herbivorous,Norway]

I know the traditional way of doing it by comparing the list using a for loop:

for (int i = 0; i < list1.size(); i++)
{
  for (int j = i+1; j < list2.size(); j++)
  {
    // compare list1 and list2 values
  }
}

Is there any faster and/or better way?

Body:
The List#removeAll() method is your friend.

Implement equals() and hashCode() for Animal, and then:

List<Animal> animalList3 = new ArrayList<Animal>(animalList2);
animalList3.removeAll(animalList1);


问:
Prevent pwgen -y generating backticks or quotes? (or otherwise sanitize output)
I'm using pwgen in a bash script. For security, we have to use the -y flag to include at least one special character. However, this frequently returns passwords with one or more of ` or " which break the surrounding script.

Can I prevent these characters being generated? If not, what's the cleanest way to remove, replace or otherwise sanitize pwgen's output to exclude these characters?

My current pwgen is;

```<code>intPW=$(pwgen -c -n -y -B -1 15)
</code>```

which means intPW's value could be something like;

```<code>iqui`c:ee4so4Ch
hph7eew"ohr9Ee
</code>```

I need to guarantee that every password has a symbol in it, just not one of the problematic symbols.

Anything I can think of in terms of replacement, from an if loop to a sed, breaks because I'm trying to target a backtick.

答:
Assuming you don't also need to protect single quote characters, the following should be OK:

```<code>intPW=$(pwgen -c -n -y -B -1 15 | tr '`"' '$@')
</code>```

That will translate ` to $ and " to @. Feel free to pick any other characters you fancy!

Body:
I'm using pwgen in a bash script. For security, we have to use the -y flag to include at least one special character. However, this frequently returns passwords with one or more of ` or " which break the surrounding script.

Can I prevent these characters being generated? If not, what's the cleanest way to remove, replace or otherwise sanitize pwgen's output to exclude these characters?

My current pwgen is;

intPW=$(pwgen -c -n -y -B -1 15)

which means intPW's value could be something like;

iqui`c:ee4so4Ch
hph7eew"ohr9Ee

I need to guarantee that every password has a symbol in it, just not one of the problematic symbols.

Anything I can think of in terms of replacement, from an if loop to a sed, breaks because I'm trying to target a backtick.

Body:
Assuming you don't also need to protect single quote characters, the following should be OK:

intPW=$(pwgen -c -n -y -B -1 15 | tr '`"' '$@')

That will translate ` to $ and " to @. Feel free to pick any other characters you fancy!


问:
PHP type hinting in Laravel
I was wondering if there is any difference in using type hint in method parameters, such as:

```<code>function xyz (UserRepository $repo)
</code>```

and doing the same stuff with annotations:

```<code>function xyz ($repo)
    /* @var UserRepository $repo */
</code>```

答: In addition to what Gordon said, Laravel uses type-hints for automatic injection: https://laravel.com/docs/5.5/container#automatic-injection</p>

Title: PHP type hinting in Laravel

Body:
I was wondering if there is any difference in using type hint in method parameters, such as:

function xyz (UserRepository $repo)

and doing the same stuff with annotations:

function xyz ($repo)
    /* @var UserRepository $repo */


问:
Large PCIe DMA Linux x86-64
I am working with a high speed serial card for high rate data transfers from an external source to a Linux box with a PCIe card. The PCIe card came with some 3rd party drivers that use dma_alloc_coherent to allocate the dma buffers to receive the data. Due to Linux limitations however, this approach limits data transfers to 4MB. I have been reading and trying multiple methods for allocating a large DMA buffer and haven't been able to get one to work.

This system has 32GB of memory and is running Red Hat with a kernel version of 3.10 and I would like to make 4GB of that available for a contiguous DMA. I know the preferred method is scatter/gather, but this is not possible in my situation as there is a hardware chip that translated the serial protocol into a DMA beyond my control, where the only thing that I can control is adding an offset to the incoming addresses (ie, address zero as seen from the external system can be mapped to address 0x700000000 on the local bus).

Since this is a one-off lab machine I think the fastest/easiest approach would be to use mem=28GB boot configuration parameter. I have this working fine, but the next step to access that memory from virtual space is where I am having problems. Here is my code condensed to the relevant components:

In the kernel module:

```<code>size_t len = 0x100000000ULL; // 4GB
size_t phys = 0x700000000ULL; // 28GB
size_t virt = ioremap_nocache( phys, len ); // address not usable via direct reference
size_t bus = (size_t)virt_to_bus( (void*)virt ); // this should be the same as phys for x86-64, shouldn't it?

// OLD WAY
/*size_t len = 0x400000; // 4MB
size_t bus;
size_t virt = dma_alloc_coherent( devHandle, len, &bus, GFP_ATOMIC );
size_t phys = (size_t)virt_to_phys( (void*)virt );*/
</code>```

In the application:

```<code>// Attempt to make a usable virtual pointer
u32 pSize = sysconf(_SC_PAGESIZE);
void* mapAddr = mmap(0, len+(phys%pSize), PROT_READ|PROT_WRITE, MAP_SHARED, devHandle, phys-(phys%pSize));
virt = (size_t)mapAddr + (phys%pSize);

// do DMA to 0x700000000 bus address

printf("Value %x\n", *((u32*)virt)); // this is returning zero
</code>```

Another interesting thing is that before doing all of this, the physical address returned from dma_alloc_coherent is greater than the amount of RAM on the system(0x83d000000). I thought that in x86 the RAM will always be the lowest addresses and therefore I would expect an address less than 32GB.

Any help would be appreciated.

答:
Instead of limiting the amount of system memory via mem, try using CMA: https://lwn.net/Articles/486301/

Using the CMA kernel command line argument allows you to reserve a certain amount of memory for DMA operations that is guaranteed to be contiguous. The kernel will allow non-DMA processes to access that memory, but as soon as a DMA operation needs that memory, non-DMA processes will be evicted. So, I would advise not changing your mem parameter, but adding cma=4G to your cmdline. dma_alloc_coherent should automatically pull from that reserved space, but you can enable CMA debugging in your kernel config to make sure.

Title: Large PCIe DMA Linux x86-64

Body:
I am working with a high speed serial card for high rate data transfers from an external source to a Linux box with a PCIe card. The PCIe card came with some 3rd party drivers that use dma_alloc_coherent to allocate the dma buffers to receive the data. Due to Linux limitations however, this approach limits data transfers to 4MB. I have been reading and trying multiple methods for allocating a large DMA buffer and haven't been able to get one to work.

This system has 32GB of memory and is running Red Hat with a kernel version of 3.10 and I would like to make 4GB of that available for a contiguous DMA. I know the preferred method is scatter/gather, but this is not possible in my situation as there is a hardware chip that translated the serial protocol into a DMA beyond my control, where the only thing that I can control is adding an offset to the incoming addresses (ie, address zero as seen from the external system can be mapped to address 0x700000000 on the local bus).

Since this is a one-off lab machine I think the fastest/easiest approach would be to use mem=28GB boot configuration parameter. I have this working fine, but the next step to access that memory from virtual space is where I am having problems. Here is my code condensed to the relevant components:

In the kernel module:

size_t len = 0x100000000ULL; // 4GB
size_t phys = 0x700000000ULL; // 28GB
size_t virt = ioremap_nocache( phys, len ); // address not usable via direct reference
size_t bus = (size_t)virt_to_bus( (void*)virt ); // this should be the same as phys for x86-64, shouldn't it?

// OLD WAY
/*size_t len = 0x400000; // 4MB
size_t bus;
size_t virt = dma_alloc_coherent( devHandle, len, &bus, GFP_ATOMIC );
size_t phys = (size_t)virt_to_phys( (void*)virt );*/

In the application:

// Attempt to make a usable virtual pointer
u32 pSize = sysconf(_SC_PAGESIZE);
void* mapAddr = mmap(0, len+(phys%pSize), PROT_READ|PROT_WRITE, MAP_SHARED, devHandle, phys-(phys%pSize));
virt = (size_t)mapAddr + (phys%pSize);

// do DMA to 0x700000000 bus address

printf("Value %x\n", *((u32*)virt)); // this is returning zero

Another interesting thing is that before doing all of this, the physical address returned from dma_alloc_coherent is greater than the amount of RAM on the system(0x83d000000). I thought that in x86 the RAM will always be the lowest addresses and therefore I would expect an address less than 32GB.

Any help would be appreciated.


问:
Open liberty features
I am currently evaluating Kumuluzee vs Wildfly Swarm vs OpenLiberty. I have some questions:

Does OpenLiberty have Gradle samples/plugin in addition to the maven one.

Is it possible/documented how to extend OL itself with libraries, rather than putting them in web-inf/lib. (Skinny wars ). If possible, are such jars excluded from redeployment scans (faster dev cycles)?

In many cases one wants to deploy several wars in single jvm (anti-microservice). Can several  web applications can you enumerate in the server.xml file?

答:
The MicroProfile Showcase Application has been updated so that you can build with Maven or Gradle.
https://github.com/OpenLiberty/sample-mpconf

Quite a few of the samples in https://github.com/WASdev/ were updated in October to show using Gradle. They do not use the Open Liberty runtime maven coordinates but many of them could.

Title: Open liberty features


问:
The pd.Series.prod() function
This should be probably elementary but still I can not figure it out.

I am reading the documentation on pd.Series and doing simple exercises.

My code is the following:

```<code>import pandas as pd
import numpy as np
pd.Series([2, 4, 6]).prod()
Out[7]: 48

a = pd.Series(np.arange(1, 100, 3))

a
Out[9]:
0      1
1      4
2      7
3     10
4     13
5     16
6     19
7     22
8     25
9     28
10    31
11    34
12    37
13    40
14    43
15    46
16    49
17    52
18    55
19    58
20    61
21    64
22    67
23    70
24    73
25    76
26    79
27    82
28    85
29    88
30    91
31    94
32    97
dtype: int32

a.prod()
Out[10]: 0

a = pd.Series(np.arange(1, 100, 2))

a.prod()
Out[15]: -373459037

type(a)
Out[18]: pandas.core.series.Series
</code>```

My question is why this erratic -to my eyes-- behavior?  Why a.prod() the first time evaluates to 0 and then evaluates to a negative integer?

Your advice will be appreciated.

答:
We can directly use numpy's np.prod with specified dtype to overcome int overflow :

```<code>np.prod(a.values,dtype=np.int64)
Out[938]: 5196472710489536419
</code>```

Title: The pd.Series.prod() function

Body:
This should be probably elementary but still I can not figure it out.

I am reading the documentation on pd.Series and doing simple exercises.

My code is the following:

import pandas as pd
import numpy as np
pd.Series([2, 4, 6]).prod()
Out[7]: 48

a = pd.Series(np.arange(1, 100, 3))

a
Out[9]:
0      1
1      4
2      7
3     10
4     13
5     16
6     19
7     22
8     25
9     28
10    31
11    34
12    37
13    40
14    43
15    46
16    49
17    52
18    55
19    58
20    61
21    64
22    67
23    70
24    73
25    76
26    79
27    82
28    85
29    88
30    91
31    94
32    97
dtype: int32

a.prod()
Out[10]: 0

a = pd.Series(np.arange(1, 100, 2))

a.prod()
Out[15]: -373459037

type(a)
Out[18]: pandas.core.series.Series

My question is why this erratic -to my eyes-- behavior?  Why a.prod() the first time evaluates to 0 and then evaluates to a negative integer?

Your advice will be appreciated.

Body:
We can directly use numpy's np.prod with specified dtype to overcome int overflow :

np.prod(a.values,dtype=np.int64)
Out[938]: 5196472710489536419


问:
Can Webpack tree-shaking remove unused babel-polyfills?
I try to make webpack tree-shaking remove unused babel-polyfill.

index.js file contains:

```<code>import 'babel-polyfill'
const add4 = n => n + 4
const add5 = n => n + 5
add4(6)

console.log('boom', add4(4))
</code>```

In this file no code require any es2015+ polyfill, so I expected tree-shaking to remove the unused babel-polyfills in the bundled output. It's not the case, and the bundle still contains them (minified).

Here is a git repo with this code.

The webpack config:

```<code>const MinifyPlugin = require('babel-minify-webpack-plugin')

module.exports = {
  entry: './index.js',
  output: {
    filename: 'bundle-webpack.js'
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader'
        }
      }
    ]
  },
  plugins: [
    new MinifyPlugin({ mangle: { topLevel: true } }, { comments: false })
  ]
}
</code>```

and .babelrc:

```<code>{
  "presets": [
    [
      "env",
      {
        "targets": {
          "browsers": ["chrome >= 50", "iOS >= 10", "ie >= 8"]
        },
        "useBuiltIns": true,
        "modules": false,
        "loose": true
      }
    ]
  ]
}
</code>```

I tried to replace babel-minify-webpack-plugin with uglifyjs-webpack-plugin, but it gave the same result.

How is it possible to make tree-shaking work, and the output not contain any babel-polyfills which are not used in the original code?

答:
Now I realize that babel-polyfill modifies the global scope where tree-shaking might have no effects...

This was a stupid question : )

Body:
I try to make webpack tree-shaking remove unused babel-polyfill.

index.js file contains:

import 'babel-polyfill'
const add4 = n => n + 4
const add5 = n => n + 5
add4(6)

console.log('boom', add4(4))

In this file no code require any es2015+ polyfill, so I expected tree-shaking to remove the unused babel-polyfills in the bundled output. It's not the case, and the bundle still contains them (minified).

Here is a git repo with this code.

The webpack config:

const MinifyPlugin = require('babel-minify-webpack-plugin')

module.exports = {
  entry: './index.js',
  output: {
    filename: 'bundle-webpack.js'
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader'
        }
      }
    ]
  },
  plugins: [
    new MinifyPlugin({ mangle: { topLevel: true } }, { comments: false })
  ]
}

and .babelrc:

{
  "presets": [
    [
      "env",
      {
        "targets": {
          "browsers": ["chrome >= 50", "iOS >= 10", "ie >= 8"]
        },
        "useBuiltIns": true,
        "modules": false,
        "loose": true
      }
    ]
  ]
}

I tried to replace babel-minify-webpack-plugin with uglifyjs-webpack-plugin, but it gave the same result.

How is it possible to make tree-shaking work, and the output not contain any babel-polyfills which are not used in the original code?


问:
Accessibility: Can a label have children besides the input?
Accessibility question: Can a ... have children besides an <input ... />? We're using Material UI on a project and their <Switch /> component is built like:

```<code><label>
  <div>
    <span>
      <span>
        <input />
      </span>
    </span>
  </div>
</label>
</code>```

which is triggering an accessibility error in HTML_Codesniffer.

Not sure if it's just not used to this structure and expects the label to be the direct parent of input or if it's an actual error.

答: inline elements aren't actually designed for containing elements maybe you should use "div" instead of "span"</p>

Body:
Accessibility question: Can a ... have children besides an <input ... />? We're using Material UI on a project and their <Switch /> component is built like:

        <input />

which is triggering an accessibility error in HTML_Codesniffer.

Not sure if it's just not used to this structure and expects the label to be the direct parent of input or if it's an actual error.


问:
In Hibernate 5, what's the CriteriaQuery equivalent of Criteria's restriction and projection?
Before Hibernate 5 deprecated the Criteria class, you could add restrictions to a Criteria to act as a constraint, and projections to act as select statements, like so

```<code>Criteria criteria = session.createCriteria(T.class)
    .add(Restrictions.or(Restrictions.eq(property, constraintValue)
    .set(Projection(Projections.projectionList()
    .add(Projections.property(selectValue)));
</code>```

But, since you now need to use CriteriaQuery like so,

```<code> CriteriaBuilder criteriaBuilder = session.getCriteriaBuilder();
 CriteriaQuery<T> criteriaQuery = criteriaBuilder.createQuery(T.class);
 Root<T> root = criteriaQuery.from(T.class);
 criteriaQuery.select(root);

 Query<T> query = session.createQuery(criteriaQuery);
</code>```

However I have been unable to figure out how to add certain things which are required in SQL statements, mainly because searching for documentation tends to wind up on documentation about Criteria, due to the naming similarity.

So, how can I recreate a simple query, like the one below, using CriteriaQuery?

```<code>SELECT selectValue
FROM tables.T
WHERE property = constraintValue
</code>```

答:
Source.

Has multiple examples, but turns out that the simple select statement we were trying to recreate can be done like so:

```<code>CriteriaBuilder criteriaBuilder = session.getCriteriaBuilder();
CriteriaQuery<SELECTVALUETYPE> criteriaQuery = criteriaBuilder.createQuery(SELECTVALUETYPE.class);
Root<PARENTCLASS> root = criteriaQuery.from(PARENTCLASS.class);
criteriaQuery.select(root);
criteriaQuery.where(criteriaBuilder.equal(root.get(property), constraintValue));

Query<SELECTVALUETYPE> query = session.createQuery(criteriaQuery);
</code>```

Note that this is a generic answer, and won't actually run. The reason being, SELECTVALUETYPE needs to be replaced with the data type of selectValue.

For example, CriteriaQuery might become:

String selectValue -> CriteriaQuery

T selectValue -> CriteriaQuery

Therefore, a working example for the statement

```<code>Select name
From Users
Where ID = 1
</code>```

Could be expressed with the following block

```<code>int ID = 1;
CriteriaBuilder criteriaBuilder = session.getCriteriaBuilder();
CriteriaQuery<String> criteriaQuery = criteriaBuilder.createQuery(String.class);
Root<User> root = criteriaQuery.from(User.class);
criteriaQuery.select(root.get("name");
criteriaQuery.where(criteriaBuilder.equal(root.get("ID"), ID));

Query<String> query = session.createQuery(criteriaQuery);

List<String>results = query.getResultList();
for(String name : results){
    System.out.println("Name: " + name);
}
</code>```

Body:
Before Hibernate 5 deprecated the Criteria class, you could add restrictions to a Criteria to act as a constraint, and projections to act as select statements, like so

Criteria criteria = session.createCriteria(T.class)
    .add(Restrictions.or(Restrictions.eq(property, constraintValue)
    .set(Projection(Projections.projectionList()
    .add(Projections.property(selectValue)));

But, since you now need to use CriteriaQuery like so,

 CriteriaBuilder criteriaBuilder = session.getCriteriaBuilder();
 CriteriaQuery<T> criteriaQuery = criteriaBuilder.createQuery(T.class);
 Root<T> root = criteriaQuery.from(T.class);
 criteriaQuery.select(root);

 Query<T> query = session.createQuery(criteriaQuery);

However I have been unable to figure out how to add certain things which are required in SQL statements, mainly because searching for documentation tends to wind up on documentation about Criteria, due to the naming similarity.

So, how can I recreate a simple query, like the one below, using CriteriaQuery?

SELECT selectValue
FROM tables.T
WHERE property = constraintValue

Body:
Source.

Has multiple examples, but turns out that the simple select statement we were trying to recreate can be done like so:

CriteriaBuilder criteriaBuilder = session.getCriteriaBuilder();
CriteriaQuery<SELECTVALUETYPE> criteriaQuery = criteriaBuilder.createQuery(SELECTVALUETYPE.class);
Root<PARENTCLASS> root = criteriaQuery.from(PARENTCLASS.class);
criteriaQuery.select(root);
criteriaQuery.where(criteriaBuilder.equal(root.get(property), constraintValue));

Query<SELECTVALUETYPE> query = session.createQuery(criteriaQuery);

Note that this is a generic answer, and won't actually run. The reason being, SELECTVALUETYPE needs to be replaced with the data type of selectValue.

For example, CriteriaQuery might become:

String selectValue -> CriteriaQuery

T selectValue -> CriteriaQuery

Therefore, a working example for the statement

Select name
From Users
Where ID = 1

Could be expressed with the following block

int ID = 1;
CriteriaBuilder criteriaBuilder = session.getCriteriaBuilder();
CriteriaQuery<String> criteriaQuery = criteriaBuilder.createQuery(String.class);
Root<User> root = criteriaQuery.from(User.class);
criteriaQuery.select(root.get("name");
criteriaQuery.where(criteriaBuilder.equal(root.get("ID"), ID));

Query<String> query = session.createQuery(criteriaQuery);

List<String>results = query.getResultList();
for(String name : results){
    System.out.println("Name: " + name);
}


问:
Running a program in Debug mode is incredible slow
Since recently it's much slower running a program in Debug mode in Eclipse Galileo.

I'm not aware of any changes.

Do you know what could be the cause? Running it normally is not a problem.

答: Disable 'Show method result after a step operation'.


问:
How to test PHP socket TCP/IP Server using Terminal/PHP?
I have a server up online, and I made a simple TCP/IP Server using PHP to handle a certain port. The code I use is found below:

```<code><?php
error_reporting(E_ALL);

/* Allow the script to wait for connections. */
set_time_limit(0);

/* Activate the implicit exit dump, so we'll see what we're getting
* while messages come. */
ob_implicit_flush();

$address = '123.456.789.123';
$port = 1234;

if (($sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) === false) {
    echo "socket_create() failed: reason: " . socket_strerror(socket_last_error()) . "\n";
}

if (socket_bind($sock, $address, $port) === false) {
    echo "socket_bind() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n";
}

if (socket_listen($sock, 5) === false) {
    echo "socket_listen() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n";
}

//clients array
$clients = array();

do {
    $read = array();
    $read[] = $sock;

    $read = array_merge($read,$clients);

    $write = NULL;
    $except = NULL;
    $tv_sec = 5;

    // Set up a blocking call to socket_select
    if(socket_select($read, $write, $except, $tv_sec) < 1)
    {
        //    SocketServer::debug("Problem blocking socket_select?");
        echo "socket continuing";
        continue;
    }

    // Handle new Connections
    if (in_array($sock, $read)) {

        if (($msgsock = socket_accept($sock)) === false) {
            echo "socket_accept() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n";
            break;
        }
        $clients[] = $msgsock;
        $key = array_keys($clients, $msgsock);

        $msg = "\Welcome to the PHP Test Server. \n" .
        "You are the customer number: {$key[0]}\n" .
        "To exit, type 'quit'. To close the server type 'shutdown'.\n";
        socket_write($msgsock, $msg, strlen($msg));

    }

    // Handle Input
    foreach ($clients as $key => $client) { // for each client
        if (in_array($client, $read)) {
            if (false === ($buf = socket_read($client, 2048, PHP_NORMAL_READ))) {
                echo "socket_read() failed: reason: " . socket_strerror(socket_last_error($client)) . "\n";
                break 2;
            }
            if (!$buf = trim($buf)) {
                continue;
            }
            if ($buf == 'quit') {
                unset($clients[$key]);
                socket_close($client);
                break;
            }
            if ($buf == 'shutdown') {
                socket_close($client);
                break 2;
            }
            $talkback = "Client {$key}: You said '$buf'.\n";
            socket_write($client, $talkback, strlen($talkback));
            echo "$buf\n";
        }

    }
} while (true);

socket_close($sock);
?>
</code>```

The script just basically runs and allows for more than one connection to run. After uploading the code to the server, I connected to the server, got to the directory where the file is, and then ran php filename.php. It does not show any warning or errors.

However, I need to further configure this TCP/IP Server and do things based on the input it receives. Right now, when I run php filename.php, it doesn't show anything (I'm guessing because all the outputs are written to the socket, and not echoed).

How do I test this TCP/IP Server that I made? telnet is out of the question since it's not secure. Right now I'm looking for nothing too complicated, so the Terminal or another simple PHP File would be a good choice.

答:
I would try to use react/socket for your testing purposes. It allows to create clients and servers pretty fast. Try this client code just to get started:

```<code><?php

require_once __DIR__ . "/vendor/autoload.php";

$loop = React\EventLoop\Factory::create();
$connector = new React\Socket\Connector($loop);

$connector->connect('127.0.0.1:1234')->then(function (React\Socket\ConnectionInterface $conn) use ($loop) {

    $conn->on('data', function ($data) use ($conn) {

        echo $data;

        $conn->close();
    });
});

$loop->run();
</code>```

The documentation is here.

Body:
I have a server up online, and I made a simple TCP/IP Server using PHP to handle a certain port. The code I use is found below:

<?php
error_reporting(E_ALL);

/* Allow the script to wait for connections. */
set_time_limit(0);

/* Activate the implicit exit dump, so we'll see what we're getting
* while messages come. */
ob_implicit_flush();

$address = '123.456.789.123';
$port = 1234;

if (($sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) === false) {
    echo "socket_create() failed: reason: " . socket_strerror(socket_last_error()) . "\n";
}

if (socket_bind($sock, $address, $port) === false) {
    echo "socket_bind() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n";
}

if (socket_listen($sock, 5) === false) {
    echo "socket_listen() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n";
}

//clients array
$clients = array();

do {
    $read = array();
    $read[] = $sock;

    $read = array_merge($read,$clients);

    $write = NULL;
    $except = NULL;
    $tv_sec = 5;

    // Set up a blocking call to socket_select
    if(socket_select($read, $write, $except, $tv_sec) < 1)
    {
        //    SocketServer::debug("Problem blocking socket_select?");
        echo "socket continuing";
        continue;
    }

    // Handle new Connections
    if (in_array($sock, $read)) {

        if (($msgsock = socket_accept($sock)) === false) {
            echo "socket_accept() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n";
            break;
        }
        $clients[] = $msgsock;
        $key = array_keys($clients, $msgsock);

        $msg = "\Welcome to the PHP Test Server. \n" .
        "You are the customer number: {$key[0]}\n" .
        "To exit, type 'quit'. To close the server type 'shutdown'.\n";
        socket_write($msgsock, $msg, strlen($msg));

    }

    // Handle Input
    foreach ($clients as $key => $client) { // for each client
        if (in_array($client, $read)) {
            if (false === ($buf = socket_read($client, 2048, PHP_NORMAL_READ))) {
                echo "socket_read() failed: reason: " . socket_strerror(socket_last_error($client)) . "\n";
                break 2;
            }
            if (!$buf = trim($buf)) {
                continue;
            }
            if ($buf == 'quit') {
                unset($clients[$key]);
                socket_close($client);
                break;
            }
            if ($buf == 'shutdown') {
                socket_close($client);
                break 2;
            }
            $talkback = "Client {$key}: You said '$buf'.\n";
            socket_write($client, $talkback, strlen($talkback));
            echo "$buf\n";
        }

    }
} while (true);

socket_close($sock);
?>

The script just basically runs and allows for more than one connection to run. After uploading the code to the server, I connected to the server, got to the directory where the file is, and then ran php filename.php. It does not show any warning or errors.

However, I need to further configure this TCP/IP Server and do things based on the input it receives. Right now, when I run php filename.php, it doesn't show anything (I'm guessing because all the outputs are written to the socket, and not echoed).

How do I test this TCP/IP Server that I made? telnet is out of the question since it's not secure. Right now I'm looking for nothing too complicated, so the Terminal or another simple PHP File would be a good choice.

Body:
I would try to use react/socket for your testing purposes. It allows to create clients and servers pretty fast. Try this client code just to get started:

<?php

require_once __DIR__ . "/vendor/autoload.php";

$loop = React\EventLoop\Factory::create();
$connector = new React\Socket\Connector($loop);

$connector->connect('127.0.0.1:1234')->then(function (React\Socket\ConnectionInterface $conn) use ($loop) {

    $conn->on('data', function ($data) use ($conn) {

        echo $data;

        $conn->close();
    });
});

$loop->run();

The documentation is here.


问:
How to Read / Improve C.R.A.P Index Calculated by PHP
I just started working with PHPUnit and its colorful code coverage reports. I understand all the numbers and percentages save one: The C.R.A.P index. Can anyone offer me a solid explanation of what it means, how to analyze it and how to lower it?</p>

答:
@Toader Mihai offered a solid explanation. (+1 from me)

How to lower it:

Write less complex code OR write better tested code. (See the graph below)

Better tested Code ?

In this context this just means: A higher code coverage and usually results in writing more tests.

Less complex code ?

For example: Refactor your methods into smaller ones:

```<code>// Complex
function doSomething() {
    if($a) {
        if($b) {
        }
        if($c) {
        }
    } else {
        if($b) {
        }
        if($c) {
        }
    }
}

// 3 less complex functions
function doSomething() {
    if($a) {
        doA();
    } else {
        doNotA();
    }
}

function doA() {
    if($b) {
    }
    if($c) {
    }
}

function doNotA() {
    if($b) {
    }
    if($c) {
    }
}
</code>```

(just a trivial example, you'll find more resources for that i'm sure)

Additional resources:

First off let me provide some additional resources:

Creators blog post about the crap index

just in case: Cyclomatic complexity explained. Tools like PHP_CodeSniffer and PHPMD will tell you that number in case you want to know.

And while it is for you to decide what number is "ok" one often suggested number (that is a litte high imho) is a crap index of 30 resulting in a Graph like this:

(You can get the .ods file here: https://www.dropbox.com/s/3bihb9thlp2fyg8/crap.ods?dl=1 )

Body:
@Toader Mihai offered a solid explanation. (+1 from me)

How to lower it:

Write less complex code OR write better tested code. (See the graph below)

Better tested Code ?

In this context this just means: A higher code coverage and usually results in writing more tests.

Less complex code ?

For example: Refactor your methods into smaller ones:

// Complex
function doSomething() {
    if($a) {
        if($b) {
        }
        if($c) {
        }
    } else {
        if($b) {
        }
        if($c) {
        }
    }
}

// 3 less complex functions
function doSomething() {
    if($a) {
        doA();
    } else {
        doNotA();
    }
}

function doA() {
    if($b) {
    }
    if($c) {
    }
}

function doNotA() {
    if($b) {
    }
    if($c) {
    }
}

(just a trivial example, you'll find more resources for that i'm sure)

Additional resources:

First off let me provide some additional resources:

Creators blog post about the crap index

just in case: Cyclomatic complexity explained. Tools like PHP_CodeSniffer and PHPMD will tell you that number in case you want to know.

And while it is for you to decide what number is "ok" one often suggested number (that is a litte high imho) is a crap index of 30 resulting in a Graph like this:

(You can get the .ods file here: https://www.dropbox.com/s/3bihb9thlp2fyg8/crap.ods?dl=1 )


问:
Finding coherent groups of identical items in pandas dataframe across one dimension
Suppose I have following pandas dataframe containing US GDP data. Column Change holds absolute change values from quarter to quarter and column Trend is just a gimmick to make trend changes more visible.

```<code>             GDP  Change Trend
Quarter

2007q4   14991.8    53.3    up
2008q1   14889.5  -102.3  down
2008q2   14963.4    73.9    up
2008q3   14891.6   -71.8  down
2008q4   14577.0  -314.6  down
2009q1   14375.0  -202.0  down
2009q2   14355.6   -19.4  down
2009q3   14402.5    46.9    up
2009q4   14541.9   139.4    up
2010q1   14604.8    62.9    up
</code>```

What I want to achieve is to find the quarter in which a recession began. A recession is defined by 2 consecutive quarterly decreases in GDP. I am sure that this task can be solved by iterating over rows but I am wondering if there is a more pandorable, vectorised way. I have tried a couple of things using df.rolling() but I cannot seem to find a way. Help is much appreciated!

Edit: In the example above the start of a recession would be 2008q3. Sorry for that ambiguity!

答:
Try

```<code>((df['Change'].shift() < 0) &(df['Change'].shift(2) < 0)).idxmax()
</code>```

You get

```<code>'2009q1'
</code>```

For the Edit, just a little tweak to the condition

```<code>((df['Change'] < 0) &(df['Change'].shift(-1) < 0)).idxmax()
</code>```

And you get

```<code>'2008q3'
</code>```

Body:
Suppose I have following pandas dataframe containing US GDP data. Column Change holds absolute change values from quarter to quarter and column Trend is just a gimmick to make trend changes more visible.

             GDP  Change Trend
Quarter

2007q4   14991.8    53.3    up
2008q1   14889.5  -102.3  down
2008q2   14963.4    73.9    up
2008q3   14891.6   -71.8  down
2008q4   14577.0  -314.6  down
2009q1   14375.0  -202.0  down
2009q2   14355.6   -19.4  down
2009q3   14402.5    46.9    up
2009q4   14541.9   139.4    up
2010q1   14604.8    62.9    up

What I want to achieve is to find the quarter in which a recession began. A recession is defined by 2 consecutive quarterly decreases in GDP. I am sure that this task can be solved by iterating over rows but I am wondering if there is a more pandorable, vectorised way. I have tried a couple of things using df.rolling() but I cannot seem to find a way. Help is much appreciated!

Edit: In the example above the start of a recession would be 2008q3. Sorry for that ambiguity!

Body:
Try

((df['Change'].shift() < 0) &(df['Change'].shift(2) < 0)).idxmax()

You get

'2009q1'

For the Edit, just a little tweak to the condition

((df['Change'] < 0) &(df['Change'].shift(-1) < 0)).idxmax()

And you get

'2008q3'


问:
How to extract elements from list of lists
I am a newbie to R. I have a  list  t1 in R which looks like

```<code>[[1]]
[[1]][[1]]
[1] "a"       "control"

[[2]]
[[2]][[1]]
[1] "a"        "disease1"

[[3]]
[[3]][[1]]
[1] "a"        "disease2"

[[4]]
[[4]][[1]]
[1] "b"       "control"

[[5]]
[[5]][[1]]
[1] "b"        "disease1"

[[6]]
[[6]][[1]]
[1] "b"        "disease2"
</code>```

I need to get a unique list of first elements into a vector i.e ["a", "b"] from this vector t1. How can I do this?

答:
Use package rlist, i.e.

```<code>library(rlist)
yourlist %>>% list.map(.[1])
</code>```

Body:
I am a newbie to R. I have a  list  t1 in R which looks like

[[1]]
[[1]][[1]]
[1] "a"       "control"

[[2]]
[[2]][[1]]
[1] "a"        "disease1"

[[3]]
[[3]][[1]]
[1] "a"        "disease2"

[[4]]
[[4]][[1]]
[1] "b"       "control"

[[5]]
[[5]][[1]]
[1] "b"        "disease1"

[[6]]
[[6]][[1]]
[1] "b"        "disease2"

I need to get a unique list of first elements into a vector i.e ["a", "b"] from this vector t1. How can I do this?

Body:
Use package rlist, i.e.

library(rlist)
yourlist %>>% list.map(.[1])


问:
Does the Java compiler optimize type conversions when mixing numeric types?
Could there be any difference in speed (however small) between Case 1 and Case 2 below?

```<code>double total = 12.34
double percentage = 56.78;
double amount;

// Case 1:
amount = (100 - percentage) * total;

// Case 2
amount = (100.0 - percentage) * total;
</code>```

Or does Java automatically convert the integer literal (100) to a double (100.0) at compile time?

答:
Decompiled version shows that output will be same for both cases.

But as a best practice Case 2 will be more readable and understandable.

```<code>double d1 = 12.34D;
double d2 = 56.78D;

double d3 = (100.0D - d2) * d1;

d3 = (100.0D - d2) * d1;
</code>```

Body:
Could there be any difference in speed (however small) between Case 1 and Case 2 below?

double total = 12.34
double percentage = 56.78;
double amount;

// Case 1:
amount = (100 - percentage) * total;

// Case 2
amount = (100.0 - percentage) * total;

Or does Java automatically convert the integer literal (100) to a double (100.0) at compile time?

Body:
Decompiled version shows that output will be same for both cases.

But as a best practice Case 2 will be more readable and understandable.

double d1 = 12.34D;
double d2 = 56.78D;

double d3 = (100.0D - d2) * d1;

d3 = (100.0D - d2) * d1;


答:
Use shift :

```<code>df['Trend2']=df['Trend'].shift(-1)
df['recession']= np.logical_and(df.Trend=='down',df.Trend2=='down')

2007q4    False
2008q1    False
2008q2    False
2008q3     True
2008q4     True
2009q1     True
2009q2    False
2009q3    False
2009q4    False
2010q1    False
</code>```

Title: Finding coherent groups of identical items in pandas dataframe across one dimension

Body:
Use shift :

df['Trend2']=df['Trend'].shift(-1)
df['recession']= np.logical_and(df.Trend=='down',df.Trend2=='down')

2007q4    False
2008q1    False
2008q2    False
2008q3     True
2008q4     True
2009q1     True
2009q2    False
2009q3    False
2009q4    False
2010q1    False


答:
You can do it this way : iterate over second list and keep only the ones that are also in first list BUT which are not equals : they have been modified (type or place, name is same)

```<code>List<Animal> res = animalList2.stream()
            .filter(a -> animalList1.stream()
                        .anyMatch(b -> !b.equals(a) && b.animalName.equals(a.animalName)))
            .collect(Collectors.toList());
</code>```

With :

```<code>List<Animal> animalList1 = new ArrayList<Animal>();
animalList1.add(new Animal("lion", "Carnivorous", "Africa"));
animalList1.add(new Animal("tiger", "Carnivorous", "Zambia"));
animalList1.add(new Animal("Goat", "Herbivorous", "Zimbabwe"));
animalList1.add(new Animal("Donkey", "Herbivorous", "Zimbabwe"));

List<Animal> animalList2 = new ArrayList<Animal>();
animalList2.add(new Animal("lion", "Carnivorous", "Africa"));  //not new but no modif   X
animalList2.add(new Animal("tiger", "Carnivorous", "Zambia")); //not new but no modif   X
animalList2.add(new Animal("Goat", "Herbivorous", "Norway"));  //not new and modif      V
animalList2.add(new Animal("Horse", "Herbivorous", "Norway")); //new                    X
</code>```

You'll get only [Goat,Herbivorous,Norway] at the end, the only one which is an update from first list to second

And you need an equals() like this :

```<code>@Override
public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;
    Animal animal = (Animal) o;
    return animalName.equals(animal.animalName) && animalType.equals(animal.animalType) && animalPlace.equals(animal.animalPlace);
}
</code>```

Title: Java : Dirty Check for ArrayList?

Body:
How can I perform a dirty check on an ArrayList in Java?

I have an object

Animal
{
    String animalName;
    String animalType;
    String animalPlace
}

I have two lists:

List<Animal> animalList1 = new ArrayList<Animal>();
List<Animal> animalList2 = new ArrayList<Animal>();

In the first list,
I have the values:

[0][lion,Carnivorous,Africa]
[1][tiger,Carnivorous,Zambia]
[2][Goat,Herbivorous,Zimbabwe]

In the second list,
I have the values:

[0][lion,Carnivorous,Africa]
[1][tiger,Carnivorous,Zambia]
[2][Goat,Herbivorous,Norway]

In the second list,
the animalPlace for the element at index 2 has changed from Zimbabwe to Norway.
How do I compare the two list values and the values which have changed put that object in a separate list?

List<Animal> animalList3 = new ArrayList<Animal>();

[0] [Goat,Herbivorous,Norway]

I know the traditional way of doing it by comparing the list using a for loop:

for (int i = 0; i < list1.size(); i++)
{
  for (int j = i+1; j < list2.size(); j++)
  {
    // compare list1 and list2 values
  }
}

Is there any faster and/or better way?

Body:
You can do it this way : iterate over second list and keep only the ones that are also in first list BUT which are not equals : they have been modified (type or place, name is same)

List<Animal> res = animalList2.stream()
            .filter(a -> animalList1.stream()
                        .anyMatch(b -> !b.equals(a) && b.animalName.equals(a.animalName)))
            .collect(Collectors.toList());

With :

List<Animal> animalList1 = new ArrayList<Animal>();
animalList1.add(new Animal("lion", "Carnivorous", "Africa"));
animalList1.add(new Animal("tiger", "Carnivorous", "Zambia"));
animalList1.add(new Animal("Goat", "Herbivorous", "Zimbabwe"));
animalList1.add(new Animal("Donkey", "Herbivorous", "Zimbabwe"));

List<Animal> animalList2 = new ArrayList<Animal>();
animalList2.add(new Animal("lion", "Carnivorous", "Africa"));  //not new but no modif   X
animalList2.add(new Animal("tiger", "Carnivorous", "Zambia")); //not new but no modif   X
animalList2.add(new Animal("Goat", "Herbivorous", "Norway"));  //not new and modif      V
animalList2.add(new Animal("Horse", "Herbivorous", "Norway")); //new                    X

You'll get only [Goat,Herbivorous,Norway] at the end, the only one which is an update from first list to second

And you need an equals() like this :

@Override
public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;
    Animal animal = (Animal) o;
    return animalName.equals(animal.animalName) && animalType.equals(animal.animalType) && animalPlace.equals(animal.animalPlace);
}